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
+72 -13
View File
@@ -2,6 +2,8 @@ package pipeline
import (
"context"
"database/sql"
"errors"
"time"
)
@@ -23,6 +25,11 @@ type OperatorSession struct {
Tag string
CreatedAt int64
UpdatedAt int64
// ClosedAt is the epoch-millisecond time the operator finished with the
// session, or 0 while it is open. It records the closed state on the server
// so every client sees the same thing; the session and its history are never
// deleted, and reopening clears it back to 0.
ClosedAt int64
}
// initOperatorSessions creates the operator-session registry. It is a table of
@@ -30,44 +37,96 @@ type OperatorSession struct {
// ownership (run_session_owners, SessionOwner) is untouched and the two
// vocabularies cannot be confused. session_id is the primary key, so lookups and
// the upsert use the index; operator_sessions_recent serves the recency order.
// closed_at is added here for a fresh database and by migrateOperatorSessions for
// one created before the closed state existed.
func (s *Store) initOperatorSessions() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions (
session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '',
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL);
tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL,
closed_at INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
return err
if err != nil {
return err
}
return s.migrateOperatorSessions()
}
// migrateOperatorSessions adds the closed_at column to a database created before
// the closed state existed. Adding a column with a default leaves every existing
// row valid and open (0), so an upgrade is idempotent across repeated Open calls
// and no session is silently reported as closed.
func (s *Store) migrateOperatorSessions() error {
return s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0")
}
// RecordOperatorSession upserts one operator chat session in a single statement:
// a new id is inserted with its created_at and last_used_at set to now, and a
// repeated id updates directory/title/tag and moves last_used_at to now while
// preserving the original created_at. CreatedAt is therefore stable across
// re-records.
// re-records. Recording also clears any closed state: re-creating or adopting a
// session is use, so it is open again.
func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error {
now := time.Now().UnixMilli()
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at)
VALUES(?,?,?,?,?,?)
ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at`,
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at)
VALUES(?,?,?,?,?,?,0)
ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0`,
sessionID, directory, title, tag, now, now)
return err
}
// TouchOperatorSession records that an operator session was just used, in one
// UPDATE. A session id that is not an operator session updates no row and is not
// an error: the statement is itself the presence check, so no second read is
// UPDATE. It also clears the closed state, so simply prompting a closed session
// reopens it. A session id that is not an operator session updates no row and is
// not an error: the statement is itself the presence check, so no second read is
// needed.
func (s *Store) TouchOperatorSession(ctx context.Context, sessionID string) error {
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET last_used_at=? WHERE session_id=?", time.Now().UnixMilli(), sessionID)
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET last_used_at=?, closed_at=0 WHERE session_id=?", time.Now().UnixMilli(), sessionID)
return err
}
// CloseOperatorSession records that the operator finished with an operator
// session, in one UPDATE that sets closed_at to now. Nothing is deleted: the row,
// its history and the OpenCode session itself are untouched. A session id that is
// not an operator session (for example a pipeline-owned run session) updates no
// row and is not an error, so run sessions are never affected.
func (s *Store) CloseOperatorSession(ctx context.Context, sessionID string) error {
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET closed_at=? WHERE session_id=?", time.Now().UnixMilli(), sessionID)
return err
}
// ReopenOperatorSession clears the closed state of an operator session, in one
// UPDATE that sets closed_at back to 0. A session id that is not an operator
// session updates no row and is not an error.
func (s *Store) ReopenOperatorSession(ctx context.Context, sessionID string) error {
_, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET closed_at=0 WHERE session_id=?", sessionID)
return err
}
// OperatorSession returns one operator session by id. found is false when the id
// is not a recorded operator session (so a pipeline-owned run session is never
// returned). It is one indexed lookup and never mutates the row.
func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) {
var session OperatorSession
row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return OperatorSession{}, false, nil
}
return OperatorSession{}, false, err
}
return session, true, nil
}
// OperatorSessions reports the operator's chat sessions, most-recently-used
// first (ties broken by session id for a deterministic order), capped at
// operatorSessionListLimit. Rows with no tag are omitted: a session with no
// recorded tag is not an operator session and must never be listed. It is one
// bounded statement; recency is never mutated here.
// recorded tag is not an operator session and must never be listed. Closed
// sessions are included: the app groups or filters them as history, so the
// operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) {
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at
rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at
FROM operator_sessions WHERE tag <> '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
@@ -76,7 +135,7 @@ FROM operator_sessions WHERE tag <> '' ORDER BY last_used_at DESC, session_id LI
sessions := []OperatorSession{}
for rows.Next() {
var session OperatorSession
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt); err != nil {
if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt); err != nil {
return nil, err
}
sessions = append(sessions, session)
@@ -0,0 +1,124 @@
package pipeline
import (
"context"
"path/filepath"
"testing"
)
// TestOperatorSessionsCloseReopenAndTouch proves the closed-state contract: a
// close records closed_at and the session is still listed as history, an explicit
// reopen clears it, a prompt (touch) clears it, re-recording clears it, and the
// session, its history and its created_at are never deleted or rewritten.
func TestOperatorSessionsCloseReopenAndTouch(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "close.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil {
t.Fatal(err)
}
before, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil {
t.Fatal(err)
}
closed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(closed) != 1 || closed[0].ClosedAt <= 0 {
t.Fatalf("close did not record closed_at: %+v", closed)
}
if closed[0].ID != before[0].ID || closed[0].Directory != before[0].Directory ||
closed[0].Title != before[0].Title || closed[0].Tag != before[0].Tag || closed[0].CreatedAt != before[0].CreatedAt {
t.Fatalf("close changed the session beyond closed_at:\nbefore %+v\nafter %+v", before[0], closed[0])
}
one, found, err := store.OperatorSession(ctx, "ses_a")
if err != nil || !found || one.ClosedAt <= 0 {
t.Fatalf("OperatorSession = %+v found=%v err=%v", one, found, err)
}
if _, found, err := store.OperatorSession(ctx, "ses_run"); err != nil || found {
t.Fatalf("a non-operator session was reported found=%v err=%v", found, err)
}
if err := store.ReopenOperatorSession(ctx, "ses_a"); err != nil {
t.Fatal(err)
}
if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt != 0 {
t.Fatalf("explicit reopen did not clear closed_at: %+v %v", rows, err)
}
// Prompting (touch) reopens too.
if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil {
t.Fatal(err)
}
if err := store.TouchOperatorSession(ctx, "ses_a"); err != nil {
t.Fatal(err)
}
if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt != 0 {
t.Fatalf("touch did not clear closed_at: %+v %v", rows, err)
}
// Re-recording (create/adopt) reopens too.
if err := store.CloseOperatorSession(ctx, "ses_a"); err != nil {
t.Fatal(err)
}
if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil {
t.Fatal(err)
}
if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt != 0 {
t.Fatalf("re-record did not clear closed_at: %+v %v", rows, err)
}
// Closing a session id that is not an operator session writes nothing.
if err := store.CloseOperatorSession(ctx, "ses_run"); err != nil {
t.Fatalf("closing a non-operator session errored: %v", err)
}
}
// TestOperatorSessionsMigrationAddsClosedAt proves an existing database created
// before the closed state opens cleanly: the column is added with a default, so
// every existing session stays open and Close/Reopen work afterwards.
func TestOperatorSessionsMigrationAddsClosedAt(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "migrate.db")
store, err := Open(path)
if err != nil {
t.Fatal(err)
}
if err := store.RecordOperatorSession(ctx, "ses_old", "/work/old", "Old", "operator"); err != nil {
t.Fatal(err)
}
// Simulate the pre-closed schema by dropping the column, then reopen.
if _, err := store.db.ExecContext(ctx, "ALTER TABLE operator_sessions DROP COLUMN closed_at"); err != nil {
t.Fatalf("drop closed_at: %v", err)
}
if err := store.Close(); err != nil {
t.Fatal(err)
}
store, err = Open(path)
if err != nil {
t.Fatalf("Open after drop: %v", err)
}
defer store.Close()
rows, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(rows) != 1 || rows[0].ID != "ses_old" || rows[0].ClosedAt != 0 {
t.Fatalf("migrated rows = %+v, want the old session open", rows)
}
if err := store.CloseOperatorSession(ctx, "ses_old"); err != nil {
t.Fatal(err)
}
if rows, err := store.OperatorSessions(ctx); err != nil || len(rows) != 1 || rows[0].ClosedAt <= 0 {
t.Fatalf("close after migration failed: %+v %v", rows, err)
}
}