chat: close and reopen an operator session on the server, keeping its history

Add a server-side close for operator chats, so finishing with a chat takes it out
of the active list for every client without deleting anything. The brokered
protocol gains chat_close and chat_reopen; chat_close stops a running turn by
reusing the existing broker interrupt (its result carries an interrupted flag, so
a stream is never left running into nothing) and then sets closed_at on the
session's operator_sessions row. The session, its transcript and its history
survive, and because the closed state lives in the registry chat_sessions reports
it to every client, not just the one that asked. An id that is not a recorded
operator session, including a pipeline-owned run session, is refused before
anything is written. chat_reopen clears the state again, and simply prompting a
closed session also clears it (the store clears closed_at on touch).

The registry gains closed_at for a fresh database and an idempotent migration for
one created before it existed. The app renders closed sessions under a labelled
Closed section with a Closed chip, offers a Close action with a confirmation that
says it stops a running turn, marks the chat closed on every device and deletes
nothing, and a Reopen action on each closed row. The device-local hide is renamed
Hide on this device, with a snackbar saying the chat stays on the server, so it is
never confused with the real close. No new dependency, the installer and Docker
files are untouched, and no run is started from the app.

Checked before committing: the packaged templates carry no chat surface and need
no update, and internal/author/install.go's managed inventory needs none either
(this adds no reference file). The packaged authoring skill reference
internal/author/skill/references/operations.md and the shared docs/cli.md and
android/README.md are stale because of this change, but an item no longer edits a
shared document: what is stale and what should change there is recorded in
docs/notes/chat-close.md for the docs-fold writer, which is committed here with
the change.

Checks: gofmt clean, go build ./... and go vet ./... clean, and
go test ./internal/protocol/... ./internal/pipeline/... ./internal/server/...
./internal/author/... pass. The app side is verified with :app:assembleDebug and
:app:testDebugUnitTest (--offline --no-daemon, BUILD SUCCESSFUL); the on-device
close, second-client and reopen check is deferred to visual review.

Not deployed; deploying is the operator's step.
This commit is contained in:
2026-10-18 00:10:47 +01:00
parent 73284ff68c
commit 971e555ceb
21 changed files with 1293 additions and 44 deletions
+15
View File
@@ -44,6 +44,15 @@ type operatorRegistry interface {
TouchOperatorSession(ctx context.Context, sessionID string) error
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
OperatorDirectories(ctx context.Context, limit int) ([]string, error)
// OperatorSession returns one recorded operator session by id (found false
// when the id is not an operator session), so chat_close/chat_reopen can echo
// the updated row and refuse a session that is not theirs.
OperatorSession(ctx context.Context, sessionID string) (pipeline.OperatorSession, bool, error)
// CloseOperatorSession records the closed state; ReopenOperatorSession clears
// it. Neither deletes anything, and neither touches a pipeline-owned run
// session (which has no operator_sessions row).
CloseOperatorSession(ctx context.Context, sessionID string) error
ReopenOperatorSession(ctx context.Context, sessionID string) error
}
// chatClientToken returns an unguessable per-connection identity. It attributes
@@ -89,6 +98,12 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
case protocol.ChatDirectories:
handleChatDirectories(ctx, request, registry, write)
return true
case protocol.ChatClose:
handleChatClose(ctx, request, broker, hub, registry, write)
return true
case protocol.ChatReopen:
handleChatReopen(ctx, request, registry, write)
return true
}
return false
}
+11
View File
@@ -48,6 +48,17 @@ func (h *chatHub) busyForOther(sessionID, clientID string) bool {
return ok && holder != clientID
}
// active reports whether any client currently holds sessionID, so a turn may be
// running. chat_close uses it to decide whether to interrupt; the claim is
// released when the turn's stream drains, so it is never left set for a settled
// session.
func (h *chatHub) active(sessionID string) bool {
h.mu.Lock()
defer h.mu.Unlock()
_, ok := h.claims[sessionID]
return ok
}
// evictClaimsLocked drops the oldest claim when the cap is reached, keeping the
// claim map bounded like the retained turns. Callers must hold h.mu.
func (h *chatHub) evictClaimsLocked() {
+143
View File
@@ -0,0 +1,143 @@
package server
import (
"context"
"strings"
"git.a-wan.net/alan/pipelines/internal/opencode"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// handleChatClose finishes an operator chat session and records it as closed on
// the server. It stops a turn that is running by reusing the existing interrupt
// (so a stream is never left running into nothing, and the result records that a
// turn was stopped), then sets the closed state in the operator-session
// registry. Nothing is deleted: the session, its transcript and its history
// survive, and every client sees the closed state because it lives in the
// registry, not on one device. A session id that is not a recorded operator
// session is refused before anything is written, so a pipeline-owned run session
// is never touched.
func handleChatClose(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
return
}
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
sessionID := query.SessionID
if _, found, err := registry.OperatorSession(ctx, sessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
} else if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is not an operator chat session"})
return
}
// Stop a running turn first. A failed interrupt is surfaced and the close is
// not recorded, so the operator is never told a live turn was stopped when it
// was not.
interrupted := hub.active(sessionID)
if interrupted {
if err := broker.Interrupt(ctx, sessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " could not be stopped: " + err.Error()})
return
}
}
if err := registry.CloseOperatorSession(ctx, sessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
session, found, err := registry.OperatorSession(ctx, sessionID)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " was closed but is no longer an operator session"})
return
}
wire := chatSessionFromOperator(session)
response := protocol.Message{
Type: protocol.ChatClose,
ID: request.ID,
ChatSession: &wire,
ChatClose: &protocol.ChatCloseResult{SessionID: sessionID, ClosedAt: session.ClosedAt, Interrupted: interrupted},
}
// Echo the registry row on the list field so a client can splice it into
// chat_sessions without a re-list.
response.ChatSessions = []protocol.ChatSession{wire}
_ = write(response)
}
// handleChatReopen clears the closed state of an operator chat session so it
// returns to the active list. Nothing is created or deleted; it is the inverse of
// chat_close. Prompting a closed session also reopens it (the store clears the
// closed state on touch), so both an explicit reopen and simply sending another
// message work. A session id that is not a recorded operator session is refused.
func handleChatReopen(ctx context.Context, request protocol.Message, registry operatorRegistry, write func(protocol.Message) error) {
if registry == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
return
}
query := request.ChatQuery
if query == nil || !opencode.ValidSessionID(query.SessionID) {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
return
}
sessionID := query.SessionID
if _, found, err := registry.OperatorSession(ctx, sessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
} else if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is not an operator chat session"})
return
}
if err := registry.ReopenOperatorSession(ctx, sessionID); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
session, found, err := registry.OperatorSession(ctx, sessionID)
if err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
if !found {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + sessionID + " is no longer an operator session"})
return
}
wire := chatSessionFromOperator(session)
response := protocol.Message{
Type: protocol.ChatReopen,
ID: request.ID,
ChatSession: &wire,
}
response.ChatSessions = []protocol.ChatSession{wire}
_ = write(response)
}
// chatSessionFromOperator projects one registry row to the wire ChatSession the
// app lists, so close/reopen and chat_sessions agree on the closed fields. The
// id is always set; title/directory/tag are copied verbatim, and the closed
// state comes from closed_at.
func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSession {
out := protocol.ChatSession{
ID: session.ID,
Title: strings.TrimSpace(session.Title),
Directory: session.Directory,
Tag: session.Tag,
CreatedAt: session.CreatedAt,
UpdatedAt: session.UpdatedAt,
}
if session.ClosedAt > 0 {
out.Closed = true
out.ClosedAt = session.ClosedAt
}
return out
}
+313
View File
@@ -0,0 +1,313 @@
package server
import (
"strings"
"testing"
"github.com/coder/websocket/wsjson"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// TestChatCloseRecordsClosedState is the close-records-state evidence: a
// chat_close on a recorded operator session answers with the closed session, sets
// closed_at in the registry and leaves the session listed (as closed) by
// chat_sessions, so every client sees the same state.
func TestChatCloseRecordsClosedState(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.sessions = []protocol.ChatSession{{ID: "ses_1", Title: "A", Directory: "/work/a"}}
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatClose || response.ID != "cl1" {
t.Fatalf("chat_close response = %+v", response)
}
if response.ChatSession == nil || !response.ChatSession.Closed || response.ChatSession.ClosedAt <= 0 {
t.Fatalf("closed session not reported: %+v", response.ChatSession)
}
if response.ChatClose == nil || response.ChatClose.SessionID != "ses_1" || response.ChatClose.ClosedAt <= 0 {
t.Fatalf("chat_close result = %+v", response.ChatClose)
}
if response.ChatClose.Interrupted {
t.Fatalf("idle session reported an interrupted turn: %+v", response.ChatClose)
}
if _, interrupts, _ := broker.counts(); interrupts != 0 {
t.Fatalf("idle close interrupted a turn: %d", interrupts)
}
rows, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ClosedAt <= 0 {
t.Fatalf("registry did not record the closed state: %+v", rows)
}
// The list still carries the session, marked closed, so it is reachable as
// history rather than disappearing.
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "l1"}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatSessions || len(response.ChatSessions) != 1 {
t.Fatalf("chat_sessions = %+v", response)
}
if !response.ChatSessions[0].Closed || response.ChatSessions[0].ClosedAt <= 0 {
t.Fatalf("closed session not listed as closed: %+v", response.ChatSessions[0])
}
}
// TestChatCloseStopsRunningTurn is the close-stops-a-running-turn evidence: a
// prompt holds the session (its stream is live), and chat_close from another
// connection interrupts it through the existing broker interrupt and reports that
// a turn was stopped.
func TestChatCloseStopsRunningTurn(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.block = true
broker.started = make(chan struct{})
broker.done = make(chan struct{})
ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 2)
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
// Start a long-running turn on the first connection.
if err := wsjson.Write(ctx, conns[0], protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "long running"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conns[0], &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt {
t.Fatalf("prompt ack = %+v", ack)
}
<-broker.started
// Close from the second connection; it must interrupt the running turn.
if err := wsjson.Write(ctx, conns[1], protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conns[1], &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatClose || response.ID != "cl1" {
t.Fatalf("chat_close response = %+v", response)
}
if response.ChatClose == nil || !response.ChatClose.Interrupted {
t.Fatalf("close did not record a stopped turn: %+v", response.ChatClose)
}
if _, interrupts, _ := broker.counts(); interrupts != 1 {
t.Fatalf("interrupts = %d, want 1", interrupts)
}
rows, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ClosedAt <= 0 {
t.Fatalf("registry did not record the closed state: %+v", rows)
}
}
// TestChatCloseKeepsSessionAndMessages pins that closing deletes nothing: the
// registry row survives (only its closed_at changes) and the session's history is
// still readable afterwards.
func TestChatCloseKeepsSessionAndMessages(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.messages = []protocol.ChatMessage{{ID: "m1", SessionID: "ses_1", Role: protocol.ChatRoleUser}}
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
before, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatClose {
t.Fatalf("close failed: %+v", response)
}
after, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(after) != 1 || after[0].ID != before[0].ID || after[0].Directory != before[0].Directory ||
after[0].Title != before[0].Title || after[0].Tag != before[0].Tag || after[0].CreatedAt != before[0].CreatedAt {
t.Fatalf("close changed the session beyond closed_at:\nbefore %+v\nafter %+v", before[0], after[0])
}
// The transcript is still readable.
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatMessages, ID: "ms1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatMessages || len(response.ChatMessages) != 1 || response.ChatMessages[0].ID != "m1" {
t.Fatalf("history lost after close: %+v", response)
}
if calls, _, _ := broker.messageQuery(); calls != 1 {
t.Fatalf("message reads = %d, want 1", calls)
}
}
// TestChatReopenClearsClosedState pins that chat_reopen is the inverse of
// chat_close: the closed state is cleared and the session is listed as active
// again.
func TestChatReopenClearsClosedState(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := store.CloseOperatorSession(ctx, "ses_1"); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatReopen, ID: "op1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.ChatReopen || response.ID != "op1" || response.ChatSession == nil {
t.Fatalf("chat_reopen response = %+v", response)
}
if response.ChatSession.Closed || response.ChatSession.ClosedAt != 0 {
t.Fatalf("reopened session still closed: %+v", response.ChatSession)
}
rows, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ClosedAt != 0 {
t.Fatalf("registry still closed after reopen: %+v", rows)
}
}
// TestChatPromptReopensClosedSession pins the second reopen path: simply
// prompting a closed session clears its closed state, so the operator never has
// to make an explicit reopen request.
func TestChatPromptReopensClosedSession(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := store.RecordOperatorSession(ctx, "ses_1", "/work/a", "A", protocol.ChatSessionTagOperator); err != nil {
t.Fatal(err)
}
if err := store.CloseOperatorSession(ctx, "ses_1"); err != nil {
t.Fatal(err)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "r1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "resume"}}); err != nil {
t.Fatal(err)
}
var ack protocol.Message
if err := wsjson.Read(ctx, conn, &ack); err != nil {
t.Fatal(err)
}
if ack.Type != protocol.ChatPrompt {
t.Fatalf("prompt ack = %+v", ack)
}
_ = readChatTurn(t, ctx, conn)
rows, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ClosedAt != 0 {
t.Fatalf("prompting did not clear the closed state: %+v", rows)
}
}
// TestChatCloseRefusesNonOperatorSession pins that a pipeline-owned run session
// (which has no operator_sessions row) is refused and nothing is written, so the
// close never touches the sessions the pipelines own.
func TestChatCloseRefusesNonOperatorSession(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "cl1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_run"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not an operator") {
t.Fatalf("non-operator session not refused: %+v", response)
}
if _, interrupts, _ := broker.counts(); interrupts != 0 {
t.Fatalf("refused close still interrupted: %d", interrupts)
}
rows, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(rows) != 0 {
t.Fatalf("refused close wrote a registry row: %+v", rows)
}
}
// TestChatCloseRejectsInvalidInput pins that a missing/invalid session id and an
// unconfigured broker/registry are answered with an error before any write.
func TestChatCloseRejectsInvalidInput(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
for _, query := range []*protocol.ChatQuery{nil, {}, {SessionID: "not-a-session"}} {
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatClose, ID: "bad", ChatQuery: query}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || response.ID != "bad" {
t.Fatalf("query %+v not rejected: %+v", query, response)
}
}
// No registry configured: refuse rather than close nothing.
noRegCtx, cancelNoReg, noRegConn := dialChatOptions(t, Options{Chat: broker})
defer cancelNoReg()
if err := wsjson.Write(noRegCtx, noRegConn, protocol.Message{Type: protocol.ChatClose, ID: "nr", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(noRegCtx, noRegConn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "registry") {
t.Fatalf("close without registry = %+v", response)
}
// No broker configured: the existing "not configured" error.
noBrokerCtx, cancelNoBroker, noBrokerConn := dialChatOptions(t, Options{OperatorRegistry: store})
defer cancelNoBroker()
if err := wsjson.Write(noBrokerCtx, noBrokerConn, protocol.Message{Type: protocol.ChatClose, ID: "nb", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
if err := wsjson.Read(noBrokerCtx, noBrokerConn, &response); err != nil {
t.Fatal(err)
}
if response.Type != protocol.Error || !strings.Contains(response.Error, "not configured") {
t.Fatalf("close without broker = %+v", response)
}
}
+5
View File
@@ -74,6 +74,11 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
session.Tag = operator.Tag
session.CreatedAt = operator.CreatedAt
session.UpdatedAt = operator.UpdatedAt
// The closed state comes from the registry, so every client sees the same
// thing; a closed session stays in the list (the app groups it as history)
// rather than disappearing.
session.Closed = operator.ClosedAt > 0
session.ClosedAt = operator.ClosedAt
session.Busy = hub.busyForOther(operator.ID, clientID)
response.ChatSessions = append(response.ChatSessions, session)
}