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 // Backend names the chat harness that owns the session: opencode, codex or // claude. Rows created before backends existed default to opencode. Backend 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 // StarredAt is the epoch-millisecond time the operator starred this session, // or 0 while unstarred. It lives on the server so the starred group is shared // by every browser and device. StarredAt 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, starred_at INTEGER NOT NULL DEFAULT 0, backend TEXT NOT NULL DEFAULT 'opencode', 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 { for _, column := range []string{"chat_model", "chat_model_provider"} { if err := s.addColumnIfMissing("operator_sessions", column, "TEXT NOT NULL DEFAULT ''"); err != nil { return err } } if err := s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0"); err != nil { return err } // starred_at records the shared star. Existing sessions default to 0 // (unstarred); the column is independent of closed_at. if err := s.addColumnIfMissing("operator_sessions", "starred_at", "INTEGER NOT NULL DEFAULT 0"); err != nil { return err } // backend records which harness owns the session so a restart can route a // chat without guessing from its id. Existing rows are OpenCode. if err := s.addColumnIfMissing("operator_sessions", "backend", "TEXT NOT NULL DEFAULT 'opencode'"); 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") } // SetChatModelSelection saves a Pipelines next-turn override, not a remote // harness acknowledgement. Only registered Codex/Claude operator chats qualify. func (s *Store) SetChatModelSelection(ctx context.Context, id, provider, model string) error { if provider == "" || model == "" { return errors.New("a model and provider are required") } result, err := s.db.ExecContext(ctx, `UPDATE operator_sessions SET chat_model=?,chat_model_provider=? WHERE session_id=? AND backend IN ('codex','claude') AND tag<>''`, model, provider, id) if err != nil { return err } count, err := result.RowsAffected() if err != nil { return err } if count != 1 { return errors.New("model selection requires a registered Codex or Claude operator chat") } return nil } // ChatModelSelection reads a durable next-turn choice without touching recency. func (s *Store) ChatModelSelection(ctx context.Context, id string) (provider, model string, err error) { err = s.db.QueryRowContext(ctx, `SELECT chat_model_provider,chat_model FROM operator_sessions WHERE session_id=? AND backend IN ('codex','claude') AND tag<>''`, id).Scan(&provider, &model) if errors.Is(err, sql.ErrNoRows) { return "", "", nil } return } // 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 } // SetOperatorSessionTitle records the operator's shared chat title in one // UPDATE. It deliberately does not touch last_used_at: renaming is not use and // must not reorder the list. A session id that is not an operator session // updates no row and is not an error. func (s *Store) SetOperatorSessionTitle(ctx context.Context, sessionID, title string) error { _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET title=? WHERE session_id=?", title, sessionID) return err } // SetOperatorSessionBackend records which harness owns a session. It is called // once after a create; the backend never changes for an existing session. func (s *Store) SetOperatorSessionBackend(ctx context.Context, sessionID, backend string) error { _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET backend=? WHERE session_id=?", backend, sessionID) return err } // SetOperatorSessionStar records the shared star state in one UPDATE. A session // id that is not an operator session updates no row and is not an error, so a // pipeline-owned run session is never affected. func (s *Store) SetOperatorSessionStar(ctx context.Context, sessionID string, starred bool) error { at := int64(0) if starred { at = time.Now().UnixMilli() } _, err := s.db.ExecContext(ctx, "UPDATE operator_sessions SET starred_at=? WHERE session_id=?", at, 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,backend,created_at,last_used_at,closed_at,starred_at FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); 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,backend,created_at,last_used_at,closed_at,starred_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.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt); 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() }