Files
pipelines/internal/pipeline/operator_sessions.go
T
alan 2fe63012f9 chat: a verification chat can never appear in the operator's list
The operator's chat list showed ~99 stray "New chat" entries. The listing
was already fail-closed (registry-only); the fault was what got recorded: an
automated UI check drives the real page, so its throwaway chat was recorded as
an operator chat exactly like a manually created one and stayed in the list for
ever (each run added one).

Server: chat_create takes an optional ephemeral flag. The session is created,
bootstrapped, usable, closable and reopenable exactly like any other, but its
registry row is hidden, so chat_sessions never lists it. operator_sessions gains
an ephemeral column (idempotent migration, existing rows default to listed) and
the list query filters it; the single-row lookup does not, so close/reopen keep
working. RecordVerificationSession is the hidden recorder.

Web: the page marks a create ephemeral only when automation asks for it
(__pipelinesEphemeralChat, set by the UI smoke for its throwaway chat), so the
smoke's own runs stop polluting while a manual create is unchanged.

Tests: a hidden row is never listed yet is still looked up and closable; a
normal re-record of the same id lists it again; a pre-ephemeral database
migrates with every existing chat still listed. Live data pruned separately
(107 -> 8 registry rows, backed up).
2026-10-19 13:15:08 +01:00

272 lines
13 KiB
Go

package pipeline
import (
"context"
"database/sql"
"errors"
"time"
)
// operatorSessionListLimit bounds one OperatorSessions read so a long-lived
// database with unbounded operator-session history cannot make one chat_sessions
// request scan it all. Rows are read most-recently-used first, so the bound only
// ever drops the oldest sessions, never one the operator just used. It mirrors
// the bounded newest-first convention of sessionOwnerScanLimit.
const operatorSessionListLimit = 128
// OperatorSession is one recorded operator chat session: a chat the person
// created through chat_create, tagged with its kind and carrying the directory
// it lives in. CreatedAt is when the row was first recorded; UpdatedAt is the
// last-used epoch-millisecond timestamp that drives most-recently-used ordering.
type OperatorSession struct {
ID string
Directory string
Title string
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
}
// ChatCreateBootstrap is the durable progress record for one chat_create
// operation. It lets a retried operation resume after endpoint activation or a
// registry write failed, without creating or activating another session.
type ChatCreateBootstrap struct {
RequestID string
SessionID string
Title string
Directory string
State string
}
// ErrChatCreateConflict reports that another request owns the durable bootstrap
// transition, or that its expected phase no longer matches.
var ErrChatCreateConflict = errors.New("chat_create bootstrap ownership/state conflict")
// initOperatorSessions creates the operator-session registry. It is a table of
// its own rather than a kind column on run_steps so a pipeline run's session
// 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,
closed_at INTEGER NOT NULL DEFAULT 0, ephemeral INTEGER NOT NULL DEFAULT 0);
CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
if err != nil {
return err
}
_, err = s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_create_bootstraps (
request_id TEXT PRIMARY KEY, session_id TEXT NOT NULL DEFAULT '', title TEXT NOT NULL,
directory TEXT NOT NULL, state TEXT NOT NULL, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);`)
if err != nil {
return err
}
return s.migrateOperatorSessions()
}
// BeginChatCreate reserves an operation id or returns its prior progress. The
// operation id is the client retry key and is never reused for different input.
// It remains stored in request_id for compatibility with existing bootstrap rows.
func (s *Store) BeginChatCreate(ctx context.Context, operationID, title, directory string) (ChatCreateBootstrap, error) {
now := time.Now().UnixMilli()
_, err := s.db.ExecContext(ctx, `INSERT INTO chat_create_bootstraps(request_id,title,directory,state,created_at,updated_at)
VALUES(?,?,?,?,?,?) ON CONFLICT(request_id) DO NOTHING`, operationID, title, directory, "created", now, now)
if err != nil {
return ChatCreateBootstrap{}, err
}
var b ChatCreateBootstrap
err = s.db.QueryRowContext(ctx, `SELECT request_id,session_id,title,directory,state FROM chat_create_bootstraps WHERE request_id=?`, operationID).
Scan(&b.RequestID, &b.SessionID, &b.Title, &b.Directory, &b.State)
if err != nil {
return ChatCreateBootstrap{}, err
}
if b.Title != title || b.Directory != directory {
return ChatCreateBootstrap{}, errors.New("chat_create operation id was reused with different input")
}
return b, nil
}
func (s *Store) SetChatCreateSession(ctx context.Context, requestID, sessionID string) error {
result, err := s.db.ExecContext(ctx, `UPDATE chat_create_bootstraps SET session_id=?,updated_at=? WHERE request_id=? AND state='creating' AND session_id=''`, sessionID, time.Now().UnixMilli(), requestID)
if err != nil {
return err
}
changed, err := result.RowsAffected()
if err != nil {
return err
}
if changed != 1 {
return ErrChatCreateConflict
}
return nil
}
// AdvanceChatCreate moves a bootstrap exactly one expected phase. Callers must
// reserve external work through this conditional update before performing it.
func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, from, to string) error {
result, err := s.db.ExecContext(ctx, `UPDATE chat_create_bootstraps SET state=?,updated_at=? WHERE request_id=? AND state=?`, to, time.Now().UnixMilli(), requestID, from)
if err != nil {
return err
}
changed, err := result.RowsAffected()
if err != nil {
return err
}
if changed != 1 {
return ErrChatCreateConflict
}
return nil
}
// 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 {
if err := s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0"); err != nil {
return err
}
// ephemeral marks a chat created for automated verification. It is hidden from
// OperatorSessions but still a real row, so the session stays usable and
// closable. Existing rows default to 0 (a normal, listed chat).
return s.addColumnIfMissing("operator_sessions", "ephemeral", "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. Recording also clears any closed state: re-creating or adopting a
// session is use, so it is open again. The row is a normal listed operator chat
// (ephemeral = 0).
func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error {
return s.recordSession(ctx, sessionID, directory, title, tag, false)
}
// RecordVerificationSession upserts one chat created for automated verification
// (chat_create with ephemeral set). It is a real registry row — so the session
// can still be closed, reopened and looked up by id — but OperatorSessions, and
// therefore chat_sessions, never lists it. It exists so a check that drives the
// real UI cannot leave a permanent "New chat" in the operator's list, and a
// re-record always keeps it hidden.
func (s *Store) RecordVerificationSession(ctx context.Context, sessionID, directory, title, tag string) error {
return s.recordSession(ctx, sessionID, directory, title, tag, true)
}
func (s *Store) recordSession(ctx context.Context, sessionID, directory, title, tag string, ephemeral bool) error {
now := time.Now().UnixMilli()
hidden := 0
if ephemeral {
hidden = 1
}
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at,ephemeral)
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,ephemeral=excluded.ephemeral`,
sessionID, directory, title, tag, now, now, hidden)
return err
}
// TouchOperatorSession records that an operator session was just used, in one
// 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=?, 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. Ephemeral
// rows are omitted too: a chat created for automated verification is usable and
// closable but never listed here, so it cannot clutter the operator's list.
// 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,closed_at
FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil {
return nil, err
}
defer rows.Close()
sessions := []OperatorSession{}
for rows.Next() {
var session OperatorSession
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)
}
return sessions, rows.Err()
}
// OperatorDirectories reports the distinct directories of the operator's
// sessions, most-recently-used first, deduplicated in SQL and capped at limit.
// It is one bounded statement, newest use per directory wins the ordering, and
// it never mutates recency. A non-positive limit returns no directories.
func (s *Store) OperatorDirectories(ctx context.Context, limit int) ([]string, error) {
if limit <= 0 {
return nil, nil
}
rows, err := s.db.QueryContext(ctx, `SELECT directory FROM operator_sessions WHERE tag <> ''
GROUP BY directory ORDER BY MAX(last_used_at) DESC, directory LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
directories := []string{}
for rows.Next() {
var directory string
if err := rows.Scan(&directory); err != nil {
return nil, err
}
directories = append(directories, directory)
}
return directories, rows.Err()
}