18398dfa5b
chat_sessions used to list exactly the OpenCode sessions the pipelines own,
filtered through pipeline.SessionOwner (run_steps/run_session_owners), so an
operator-created chat was an accident of the run-ownership table and the
operator's working sessions were mixed with the internals of running pipelines.
Add a first-class operator session:
- internal/pipeline/operator_sessions.go: a dedicated operator_sessions table
(session_id PK, directory, title, tag, created_at, last_used_at) with
RecordOperatorSession (upsert preserving created_at), a one-statement
TouchOperatorSession (no-op for a non-operator id), OperatorSessions bounded to
128 rows most-recently-used first, and OperatorDirectories (bounded MRU,
deduped). run_steps/run_session_owners and SessionOwner/OwnedSessions are
untouched.
- internal/server/chat.go: chat_sessions returns operator sessions only - it
reads the registry once, intersects it with one broker session-list call, fills
directory/tag/created/updated from the registry, sets busy for a session held
by another connection, keeps MRU order, and stays fail-closed (empty list, never
the endpoint's whole list). A pipeline stage session and an untagged row can
never be listed. chat_create resolves the directory (empty/'~'/'~/...' ->
operator home; relative or missing rejected before any OpenCode call), calls
broker.Create(title, resolved) and records the row with the operator tag.
chat_directories returns home first then bounded (8) deduped recents. A
successful prompt touches the operator session without affecting pipeline
prompts.
- internal/opencode, internal/protocol, internal/server/websocket.go and
message.go: unscoped session list, Create posts {"title":...,
"location":{"directory":...}} to POST /api/session, additive protocol fields
(omitempty) and the ChatDirectories request/response, plus the OperatorRegistry
option defaulting to the first store. One OpenCode transport per server is
unchanged.
Docs and references: docs/cli.md gains a "Chat sessions" section documenting the
operator-only fail-closed list, directory defaulting/rejection, chat_directories
(home first, deduped, bounded 8) and why a dedicated request was chosen.
internal/author/skill/references/operations.md's stale "Brokered OpenCode chat"
text (chat_create unbrokered, run_steps filtering, "listed the owned scratch
session" evidence) is rewritten to the operator-session registry, the fail-closed
filter, directory defaulting and the corrected live-test wording. No new
reference file, so internal/author/install.go's inventory is unchanged.
Checked for staleness elsewhere: README.md, the docs/ topic pages and the
packaged server/TUI templates carry no chat-session ownership claims, so none
needed updating.
Verified: gofmt -l clean; go vet and go build ./... clean; go test -count=1
./internal/pipeline/... ./internal/protocol/... ./internal/opencode/...
./internal/server/... and the full go test -count=1 ./... pass.
219 lines
8.9 KiB
Go
219 lines
8.9 KiB
Go
package protocol
|
|
|
|
import (
|
|
"encoding/json"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
// chatSamples covers every new chat type with a populated value, plus a text and
|
|
// a tool chat_event, so a round-trip loss in any field fails the test.
|
|
func chatSamples() []struct {
|
|
name string
|
|
value any
|
|
} {
|
|
return []struct {
|
|
name string
|
|
value any
|
|
}{
|
|
{"session", ChatSession{
|
|
ID: "ses_1", Title: "demo", Agent: "build", Model: "deepseek-v4.1-flash",
|
|
Directory: "/work", ParentID: "ses_0", Tag: ChatSessionTagOperator, CreatedAt: 1792112366711, UpdatedAt: 1792112367999,
|
|
}},
|
|
{"session_busy", ChatSession{ID: "ses_2", Title: "held", Busy: true}},
|
|
{"create", ChatCreateRequest{Title: "demo", Directory: "/work"}},
|
|
{"query", ChatQuery{SessionID: "ses_1", Limit: 50}},
|
|
{"prompt", ChatPromptRequest{SessionID: "ses_1", Text: "hello", Model: "m", Agent: "build", Files: []string{"file:///tmp/a.png"}}},
|
|
{"message", ChatMessage{
|
|
ID: "msg_1", SessionID: "ses_1", Role: ChatRoleAssistant, Model: "m", Agent: "build", CreatedAt: 1792112366711,
|
|
Parts: []ChatPart{
|
|
{Type: ChatPartText, ID: "p1", Text: "done"},
|
|
{Type: ChatPartReasoning, ID: "p2", Text: "thinking"},
|
|
{Type: ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
|
|
State: &ChatToolState{
|
|
Status: ChatToolCompleted,
|
|
Input: json.RawMessage(`{"command":"ls"}`),
|
|
Content: []ChatToolContent{{Type: "text", Text: "app-debug.apk"}, {Type: "file", URI: "file:///tmp/x.png", Mime: "image/png", Name: "x.png"}},
|
|
Metadata: map[string]any{"exit": "0"},
|
|
},
|
|
Time: &ChatTime{Created: 1, Ran: 2, Completed: 3},
|
|
},
|
|
{Type: ChatPartTool, ID: "call_2", Name: "edit",
|
|
State: &ChatToolState{Status: ChatToolError, Input: json.RawMessage(`{}`), Error: &ChatError{Type: "tool", Message: "boom"}},
|
|
},
|
|
},
|
|
}},
|
|
{"event_text", ChatEventFrame{
|
|
SessionID: "ses_1", MessageID: "msg_1", Kind: ChatEventText, Delta: "hel",
|
|
Part: &ChatPart{Type: ChatPartText, ID: "p1"},
|
|
}},
|
|
{"event_tool", ChatEventFrame{
|
|
SessionID: "ses_1", MessageID: "msg_1", Kind: ChatEventTool,
|
|
Part: &ChatPart{Type: ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
|
|
State: &ChatToolState{Status: ChatToolRunning, Input: json.RawMessage(`{"command":"ls"}`)},
|
|
},
|
|
}},
|
|
{"event_step", ChatEventFrame{SessionID: "ses_1", Kind: ChatEventStep, Step: &ChatStep{Status: ChatStepEnded, Index: 2}}},
|
|
{"event_usage", ChatEventFrame{SessionID: "ses_1", Kind: ChatEventUsage, Usage: &ChatUsage{InputTokens: 12, OutputTokens: 34, Cost: 0.001}}},
|
|
{"permission", ChatPermissionFrame{
|
|
SessionID: "ses_1", RequestID: "per_1", Action: "bash",
|
|
Resources: []string{"rm -rf /tmp"}, Save: []string{"bash:rm -rf /tmp"},
|
|
Metadata: map[string]any{"command": "rm -rf /tmp"},
|
|
Source: &ChatPermissionSource{Type: "tool", MessageID: "msg_1", ID: "call_1"},
|
|
Message: "wants to run a command",
|
|
}},
|
|
{"reply", ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionOnce, Message: "ok"}},
|
|
}
|
|
}
|
|
|
|
func TestChatTypesGoldenRoundTrip(t *testing.T) {
|
|
for _, sample := range chatSamples() {
|
|
encoded, err := json.Marshal(sample.value)
|
|
if err != nil {
|
|
t.Fatalf("%s: marshal: %v", sample.name, err)
|
|
}
|
|
target := reflect.New(reflect.TypeOf(sample.value))
|
|
if err := json.Unmarshal(encoded, target.Interface()); err != nil {
|
|
t.Fatalf("%s: unmarshal: %v", sample.name, err)
|
|
}
|
|
decoded := target.Elem().Interface()
|
|
if !reflect.DeepEqual(decoded, sample.value) {
|
|
t.Fatalf("%s: fields lost\n got %+v\nwant %+v", sample.name, decoded, sample.value)
|
|
}
|
|
again, err := json.Marshal(decoded)
|
|
if err != nil {
|
|
t.Fatalf("%s: re-marshal: %v", sample.name, err)
|
|
}
|
|
if string(again) != string(encoded) {
|
|
t.Fatalf("%s: wire shape not stable\n got %s\nwant %s", sample.name, again, encoded)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestChatEventGoldenJSON pins the exact wire shape of a pushed frame so a JSON
|
|
// tag change cannot silently alter what the phone parses.
|
|
func TestChatEventGoldenJSON(t *testing.T) {
|
|
event := ChatEventFrame{
|
|
SessionID: "ses_1", MessageID: "msg_1", Kind: ChatEventTool,
|
|
Part: &ChatPart{Type: ChatPartTool, ID: "call_1", Name: "shell", Executed: true,
|
|
State: &ChatToolState{
|
|
Status: ChatToolStreaming,
|
|
Input: json.RawMessage(`"{\"command\":\"ls\""`),
|
|
Content: nil,
|
|
},
|
|
Time: &ChatTime{Created: 10, Ran: 11, Completed: 12},
|
|
},
|
|
}
|
|
encoded, err := json.Marshal(event)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := `{"session_id":"ses_1","message_id":"msg_1","kind":"tool","part":{"type":"tool","id":"call_1","name":"shell","executed":true,"state":{"status":"streaming","input":"{\"command\":\"ls\""},"time":{"created":10,"ran":11,"completed":12}}}`
|
|
if string(encoded) != want {
|
|
t.Fatalf("golden mismatch\n got %s\nwant %s", encoded, want)
|
|
}
|
|
var decoded ChatEventFrame
|
|
if err := json.Unmarshal([]byte(want), &decoded); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !reflect.DeepEqual(decoded, event) {
|
|
t.Fatalf("golden did not decode back: %+v", decoded)
|
|
}
|
|
}
|
|
|
|
// TestChatPermissionGoldenJSON pins the exact wire shape of the pushed
|
|
// chat_permission frame so a JSON tag change cannot silently alter what the
|
|
// phone parses.
|
|
func TestChatPermissionGoldenJSON(t *testing.T) {
|
|
frame := ChatPermissionFrame{
|
|
SessionID: "ses_1", RequestID: "per_1", Action: "bash",
|
|
Resources: []string{"rm -rf /tmp"},
|
|
Source: &ChatPermissionSource{Type: "tool", MessageID: "msg_1", ID: "call_1"},
|
|
}
|
|
encoded, err := json.Marshal(frame)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
want := `{"session_id":"ses_1","request_id":"per_1","action":"bash","resources":["rm -rf /tmp"],"source":{"type":"tool","message_id":"msg_1","id":"call_1"}}`
|
|
if string(encoded) != want {
|
|
t.Fatalf("golden mismatch\n got %s\nwant %s", encoded, want)
|
|
}
|
|
var decoded ChatPermissionFrame
|
|
if err := json.Unmarshal([]byte(want), &decoded); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !reflect.DeepEqual(decoded, frame) {
|
|
t.Fatalf("golden did not decode back: %+v", decoded)
|
|
}
|
|
}
|
|
|
|
func TestChatEnvelopeRoundTrip(t *testing.T) {
|
|
session := ChatSession{ID: "ses_1", Title: "demo"}
|
|
message := Message{
|
|
Type: ChatSessions, ID: "r1",
|
|
ChatSessions: []ChatSession{session},
|
|
ChatSession: &session,
|
|
ChatCreate: &ChatCreateRequest{Title: "new"},
|
|
ChatQuery: &ChatQuery{SessionID: "ses_1", Limit: 10},
|
|
ChatPrompt: &ChatPromptRequest{SessionID: "ses_1", Text: "hi"},
|
|
ChatMessages: []ChatMessage{{ID: "msg_1", SessionID: "ses_1", Role: ChatRoleUser, Parts: []ChatPart{{Type: ChatPartText, Text: "hi"}}}},
|
|
ChatEvent: &ChatEventFrame{SessionID: "ses_1", Kind: ChatEventText, Delta: "hi"},
|
|
ChatPermission: &ChatPermissionFrame{
|
|
SessionID: "ses_1", RequestID: "per_1", Action: "bash", Resources: []string{"rm -rf /"},
|
|
},
|
|
ChatReply: &ChatReplyRequest{SessionID: "ses_1", RequestID: "req_1", Decision: ChatDecisionReject},
|
|
ChatDirectories: []string{"/home/operator", "/work/project"},
|
|
}
|
|
encoded, err := json.Marshal(message)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var decoded Message
|
|
if err := json.Unmarshal(encoded, &decoded); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if decoded.Type != ChatSessions || decoded.ID != "r1" {
|
|
t.Fatalf("envelope lost: %+v", decoded)
|
|
}
|
|
if !reflect.DeepEqual(decoded.ChatSessions, message.ChatSessions) ||
|
|
!reflect.DeepEqual(decoded.ChatSession, message.ChatSession) ||
|
|
!reflect.DeepEqual(decoded.ChatCreate, message.ChatCreate) ||
|
|
!reflect.DeepEqual(decoded.ChatQuery, message.ChatQuery) ||
|
|
!reflect.DeepEqual(decoded.ChatPrompt, message.ChatPrompt) ||
|
|
!reflect.DeepEqual(decoded.ChatMessages, message.ChatMessages) ||
|
|
!reflect.DeepEqual(decoded.ChatEvent, message.ChatEvent) ||
|
|
!reflect.DeepEqual(decoded.ChatPermission, message.ChatPermission) ||
|
|
!reflect.DeepEqual(decoded.ChatReply, message.ChatReply) ||
|
|
!reflect.DeepEqual(decoded.ChatDirectories, message.ChatDirectories) {
|
|
t.Fatalf("chat payloads lost: %+v", decoded)
|
|
}
|
|
}
|
|
|
|
func TestChatFieldsOmittedWhenUnused(t *testing.T) {
|
|
minimal, err := json.Marshal(Message{Type: List, ID: "r1"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, absent := range []string{"chat_sessions", "chat_session", "chat_create", "chat_query", "chat_prompt", "chat_messages", "chat_event", "chat_permission", "chat_reply", "chat_directories"} {
|
|
if strings.Contains(string(minimal), absent) {
|
|
t.Fatalf("absent %q must be omitted: %s", absent, minimal)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestChatOperatorTagVocabulary pins that the stored tag and the display label
|
|
// are one mapping (a wire tag plus a derived label), not a second vocabulary.
|
|
func TestChatOperatorTagVocabulary(t *testing.T) {
|
|
if ChatSessionTagOperator != "operator" || ChatSessionTagOperatorDisplay != "Operator" {
|
|
t.Fatalf("operator tag vocabulary = %q/%q, want operator/Operator", ChatSessionTagOperator, ChatSessionTagOperatorDisplay)
|
|
}
|
|
encoded, err := json.Marshal(ChatSession{ID: "ses_1", Tag: ChatSessionTagOperator})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(string(encoded), `"tag":"operator"`) {
|
|
t.Fatalf("operator tag not on the wire: %s", encoded)
|
|
}
|
|
}
|