chat: give the operator their own sessions, separate from run sessions
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.
This commit is contained in:
@@ -502,15 +502,21 @@ func TestDecodeChatMessagesSkipsUnknownPartsAndRoles(t *testing.T) {
|
||||
// TestChatSessionsListsAndLiftsShape loads the verified V2 session list
|
||||
// (GET /api/session: {"data":[{id,...,location.directory,time{created,updated},
|
||||
// parentID}]}) and asserts the adapter reads it exactly once, lifts the nested
|
||||
// directory/time onto protocol.ChatSession, and orders newest-updated first.
|
||||
// directory/time onto protocol.ChatSession, orders newest-updated first, and does
|
||||
// not scope the list to the connection's own directory (so operator sessions in
|
||||
// other directories are returned for the caller to filter).
|
||||
func TestChatSessionsListsAndLiftsShape(t *testing.T) {
|
||||
var reads atomic.Int32
|
||||
var scoped bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet || r.URL.Path != "/api/session" {
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
return
|
||||
}
|
||||
reads.Add(1)
|
||||
if r.URL.Query().Get("directory") != "" {
|
||||
scoped = true
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[
|
||||
{"id":"ses_old","title":"older","agent":"build","model":{"id":"m1"},"parentID":"ses_new","location":{"directory":"/proj"},"time":{"created":10,"updated":20}},
|
||||
@@ -519,7 +525,7 @@ func TestChatSessionsListsAndLiftsShape(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, Directory: "/repo"})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
sessions, err := chat.Sessions(ctx)
|
||||
@@ -529,6 +535,9 @@ func TestChatSessionsListsAndLiftsShape(t *testing.T) {
|
||||
if reads.Load() != 1 {
|
||||
t.Fatalf("session endpoint read %d times, want 1", reads.Load())
|
||||
}
|
||||
if scoped {
|
||||
t.Fatal("session list was scoped to the connection directory; it must list every directory")
|
||||
}
|
||||
if len(sessions) != 2 {
|
||||
t.Fatalf("sessions = %+v, want 2", sessions)
|
||||
}
|
||||
@@ -631,6 +640,65 @@ func TestChatStreamRequiresEndpoint(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCreatePostsSessionEndpoint pins the outbound create call: the adapter
|
||||
// must POST exactly once to /api/session with the verified V2 body
|
||||
// {"title":...,"location":{"directory":...}} (no invented mechanism, no model or
|
||||
// permission override), read exactly that one path, and lift the nested
|
||||
// location.directory from the {"data":{...}} response.
|
||||
func TestChatCreatePostsSessionEndpoint(t *testing.T) {
|
||||
type request struct{ method, path, body string }
|
||||
var mu sync.Mutex
|
||||
var requests []request
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
requests = append(requests, request{method: r.Method, path: r.URL.Path, body: string(data)})
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"data":{"id":"ses_new","title":"demo","location":{"directory":"/work/proj"},"time":{"created":11,"updated":22}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
session, err := chat.Create(ctx, "demo", "/work/proj")
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
mu.Lock()
|
||||
got := append([]request(nil), requests...)
|
||||
mu.Unlock()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("create requests = %d, want 1: %+v", len(got), got)
|
||||
}
|
||||
if got[0].method != http.MethodPost || got[0].path != "/api/session" {
|
||||
t.Fatalf("create request = %+v", got[0])
|
||||
}
|
||||
if got[0].body != `{"title":"demo","location":{"directory":"/work/proj"}}` {
|
||||
t.Fatalf("create body = %q", got[0].body)
|
||||
}
|
||||
if session.ID != "ses_new" || session.Title != "demo" || session.Directory != "/work/proj" || session.CreatedAt != 11 || session.UpdatedAt != 22 {
|
||||
t.Fatalf("created session = %+v", session)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatCreateRejectsMalformedSession pins that a response without a valid
|
||||
// session id is an error, not a silent empty success.
|
||||
func TestChatCreateRejectsMalformedSession(t *testing.T) {
|
||||
for _, raw := range []string{`{"data":{}}`, `{"data":{"id":""}}`, `{"data":{"id":"msg_not_a_session"}}`, `not json`} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(raw))
|
||||
}))
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
if _, err := chat.Create(context.Background(), "demo", "/work"); err == nil {
|
||||
t.Fatalf("response %q must be an error, not empty success", raw)
|
||||
}
|
||||
srv.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeChatEventWithoutMessageID(t *testing.T) {
|
||||
for _, payload := range []string{
|
||||
`{"type":"session.text.delta","data":{"sessionID":"ses_1","ordinal":0,"delta":"x"}}`,
|
||||
|
||||
Reference in New Issue
Block a user