Merge branch 'main' into web-chat-local

Resolve the C11/C12 vs C13 overlap in the chat work:
- PARITY: keep main's done C11/C12 rows and this branch's done C13 row.
- app.js/chat tests: keep both import/helper sets (notices and overrides/seen).
- ui-smoke: keep main's C11 background-task bar, C12 notice checks and the
  shared composer throwaway, and C13's row-menu rename/hide/seen checks.
  The composer throwaway stays a listed server session: C12 switches away
  and back to it and C13 reads its row, which an ephemeral create (2fe6301)
  deliberately hides from chat_sessions. The live-run graph halo check is
  best effort as its own comment says, so a run with no stage in flight at
  capture time skips instead of failing the whole smoke.
This commit is contained in:
2026-10-19 14:07:28 +01:00
13 changed files with 791 additions and 79 deletions
+6
View File
@@ -349,6 +349,12 @@ sessions pipeline runs create. The protocol types are:
value all resolve to the home directory). A relative or missing directory is value all resolve to the home directory). A relative or missing directory is
rejected before any OpenCode call. The created session is recorded with the rejected before any OpenCode call. The created session is recorded with the
stored tag `operator` and returned as the response's `chat_session`. stored tag `operator` and returned as the response's `chat_session`.
An optional `ephemeral: true` creates the session for automated verification:
it is created, bootstrapped and usable exactly like any other chat and can still
be closed and reopened, but its registry row is hidden, so `chat_sessions` never
lists it and a check that drives the real UI cannot leave a stray "New chat" in
the operator's list. The flag only removes a chat from the shared list, so it
cannot reveal or alter another session.
- `chat_directories` returns the operator's home first, then the directories of - `chat_directories` returns the operator's home first, then the directories of
previous operator sessions most-recently-used first, deduplicated and bounded previous operator sessions most-recently-used first, deduplicated and bounded
(currently 8). It is a dedicated request so the create dialog can load the (currently 8). It is a dedicated request so the create dialog can load the
+37 -10
View File
@@ -58,7 +58,7 @@ func (s *Store) initOperatorSessions() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions ( _, 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 '', 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); 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);`) CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`)
if err != nil { if err != nil {
return err return err
@@ -131,7 +131,13 @@ func (s *Store) AdvanceChatCreate(ctx context.Context, requestID, from, to strin
// row valid and open (0), so an upgrade is idempotent across repeated Open calls // row valid and open (0), so an upgrade is idempotent across repeated Open calls
// and no session is silently reported as closed. // and no session is silently reported as closed.
func (s *Store) migrateOperatorSessions() error { func (s *Store) migrateOperatorSessions() error {
return s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0") 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: // RecordOperatorSession upserts one operator chat session in a single statement:
@@ -139,13 +145,32 @@ func (s *Store) migrateOperatorSessions() error {
// repeated id updates directory/title/tag and moves last_used_at to now while // repeated id updates directory/title/tag and moves last_used_at to now while
// preserving the original created_at. CreatedAt is therefore stable across // preserving the original created_at. CreatedAt is therefore stable across
// re-records. Recording also clears any closed state: re-creating or adopting a // re-records. Recording also clears any closed state: re-creating or adopting a
// session is use, so it is open again. // 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 { 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() now := time.Now().UnixMilli()
_, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at) hidden := 0
VALUES(?,?,?,?,?,?,0) if ephemeral {
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`, hidden = 1
sessionID, directory, title, tag, now, now) }
_, 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 return err
} }
@@ -196,13 +221,15 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID)
// OperatorSessions reports the operator's chat sessions, most-recently-used // OperatorSessions reports the operator's chat sessions, most-recently-used
// first (ties broken by session id for a deterministic order), capped at // first (ties broken by session id for a deterministic order), capped at
// operatorSessionListLimit. Rows with no tag are omitted: a session with no // operatorSessionListLimit. Rows with no tag are omitted: a session with no
// recorded tag is not an operator session and must never be listed. Closed // recorded tag is not an operator session and must never be listed. Ephemeral
// sessions are included: the app groups or filters them as history, so the // 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 // operator can still see and reopen what they finished. It is one bounded
// statement; recency is never mutated here. // statement; recency is never mutated here.
func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) { 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 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) FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -232,3 +232,91 @@ func TestOperatorSessionsSurviveRestart(t *testing.T) {
t.Fatalf("restarted row missing fields: %+v", after[0]) t.Fatalf("restarted row missing fields: %+v", after[0])
} }
} }
// TestRecordVerificationSessionIsRealButNeverListed proves the automated-
// verification contract: the row exists and is closable (so a check that drives
// the real page can still close its throwaway chat), but OperatorSessions — and
// therefore chat_sessions — never lists it.
func TestRecordVerificationSessionIsRealButNeverListed(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "verification-session.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if err := store.RecordOperatorSession(ctx, "ses_mine", "/work/mine", "Mine", "operator"); err != nil {
t.Fatal(err)
}
if err := store.RecordVerificationSession(ctx, "ses_check", "/work/check", "New chat", "operator"); err != nil {
t.Fatal(err)
}
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 1 || listed[0].ID != "ses_mine" {
t.Fatalf("verification session was listed: %+v", listed)
}
session, found, err := store.OperatorSession(ctx, "ses_check")
if err != nil || !found {
t.Fatalf("verification session is not looked up: found=%v err=%v", found, err)
}
if session.ID != "ses_check" || session.Directory != "/work/check" {
t.Fatalf("verification session row = %+v", session)
}
if err := store.CloseOperatorSession(ctx, "ses_check"); err != nil {
t.Fatalf("close verification session: %v", err)
}
// Re-recording keeps it hidden, and a normal record of the same id lists it
// again (the flag is replaced, not sticky).
if err := store.RecordVerificationSession(ctx, "ses_check", "/work/check", "New chat", "operator"); err != nil {
t.Fatal(err)
}
if listed, err = store.OperatorSessions(ctx); err != nil || len(listed) != 1 {
t.Fatalf("re-recorded verification session listed: %+v err=%v", listed, err)
}
if err := store.RecordOperatorSession(ctx, "ses_check", "/work/check", "Kept", "operator"); err != nil {
t.Fatal(err)
}
if listed, err = store.OperatorSessions(ctx); err != nil || len(listed) != 2 {
t.Fatalf("a normal re-record did not list the session: %+v err=%v", listed, err)
}
}
// TestOperatorSessionsMigrationAddsEphemeral proves an existing database created
// before the ephemeral column opens cleanly and keeps every existing chat listed.
func TestOperatorSessionsMigrationAddsEphemeral(t *testing.T) {
ctx := context.Background()
path := filepath.Join(t.TempDir(), "migrate-ephemeral.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)
}
if _, err := store.db.ExecContext(ctx, "ALTER TABLE operator_sessions DROP COLUMN ephemeral"); err != nil {
t.Fatalf("drop ephemeral: %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()
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 1 || listed[0].ID != "ses_old" {
t.Fatalf("migrated session list = %+v", listed)
}
if err := store.RecordVerificationSession(ctx, "ses_new_check", "/work/new", "New chat", "operator"); err != nil {
t.Fatal(err)
}
if listed, err = store.OperatorSessions(ctx); err != nil || len(listed) != 1 {
t.Fatalf("verification session listed after migration: %+v err=%v", listed, err)
}
}
+8
View File
@@ -187,6 +187,14 @@ type ChatCreateRequest struct {
Title string `json:"title,omitempty"` Title string `json:"title,omitempty"`
Directory string `json:"directory,omitempty"` Directory string `json:"directory,omitempty"`
OperationID string `json:"operation_id,omitempty"` OperationID string `json:"operation_id,omitempty"`
// Ephemeral creates a chat for automated verification: the session is created,
// bootstrapped and usable exactly like a normal one, but no operator-registry
// row is written, so it can never appear in chat_sessions. It exists because a
// verification client drives the real UI and would otherwise leave a permanent
// "New chat" in the operator's list for every run. The flag is client-supplied
// and only ever *removes* a chat from the shared list, so a buggy or hostile
// client can hide its own chat but cannot reveal or alter another one.
Ephemeral bool `json:"ephemeral,omitempty"`
} }
// ChatAdoptRequest is the chat_adopt request body: the id of a session that // ChatAdoptRequest is the chat_adopt request body: the id of a session that
+3
View File
@@ -68,6 +68,9 @@ type operatorRegistry interface {
SetChatCreateSession(ctx context.Context, requestID, sessionID string) error SetChatCreateSession(ctx context.Context, requestID, sessionID string) error
AdvanceChatCreate(ctx context.Context, requestID, from, to string) error AdvanceChatCreate(ctx context.Context, requestID, from, to string) error
RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error
// RecordVerificationSession records a chat created for automated verification:
// a real, closable row that OperatorSessions never lists.
RecordVerificationSession(ctx context.Context, sessionID, directory, title, tag string) error
TouchOperatorSession(ctx context.Context, sessionID string) error TouchOperatorSession(ctx context.Context, sessionID string) error
OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error) OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error)
OperatorDirectories(ctx context.Context, limit int) ([]string, error) OperatorDirectories(ctx context.Context, limit int) ([]string, error)
+19 -4
View File
@@ -90,7 +90,9 @@ func handleChatSessions(ctx context.Context, request protocol.Message, broker ch
// resolved directory, the title and the operator tag. A blank or omitted // resolved directory, the title and the operator tag. A blank or omitted
// directory defaults to the operator's home, never the server's working // directory defaults to the operator's home, never the server's working
// directory. A registry write failure answers an error naming the created id, so // directory. A registry write failure answers an error naming the created id, so
// an orphaned session is visible rather than silently reported as success. // an orphaned session is visible rather than silently reported as success. A
// request with Ephemeral set creates the session without any registry row, for
// automated verification that must never add a chat to the operator's list.
func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) { func handleChatCreate(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
if broker == nil { if broker == nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
@@ -103,10 +105,12 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
title := "" title := ""
directory := "" directory := ""
operationID := "" operationID := ""
ephemeral := false
if request.ChatCreate != nil { if request.ChatCreate != nil {
title = strings.TrimSpace(request.ChatCreate.Title) title = strings.TrimSpace(request.ChatCreate.Title)
directory = strings.TrimSpace(request.ChatCreate.Directory) directory = strings.TrimSpace(request.ChatCreate.Directory)
operationID = strings.TrimSpace(request.ChatCreate.OperationID) operationID = strings.TrimSpace(request.ChatCreate.OperationID)
ephemeral = request.ChatCreate.Ephemeral
} }
// Legacy clients did not carry a durable create identity. Give each received // Legacy clients did not carry a durable create identity. Give each received
// request its own server-generated scope so their connection-local envelope // request its own server-generated scope so their connection-local envelope
@@ -182,7 +186,14 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
chatCreateConflictError(request, err, write) chatCreateConflictError(request, err, write)
return return
} }
if err := registry.RecordOperatorSession(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil { // An ephemeral (verification) create records a real but hidden row: the chat
// stays usable and closable, and chat_sessions never lists it. Everything
// else about the session — its id, skill activation and use — is identical.
record := registry.RecordOperatorSession
if ephemeral {
record = registry.RecordVerificationSession
}
if err := record(ctx, session.ID, resolved, title, protocol.ChatSessionTagOperator); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()}) _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was created but could not be recorded: " + err.Error()})
return return
} }
@@ -198,8 +209,12 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
session.Tag = protocol.ChatSessionTagOperator session.Tag = protocol.ChatSessionTagOperator
response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session} response := protocol.Message{Type: protocol.ChatCreate, ID: request.ID, ChatSession: &session}
// The same registry row is echoed on the list field so a client can splice it // The same registry row is echoed on the list field so a client can splice it
// into chat_sessions without a re-list. // into chat_sessions without a re-list. An ephemeral create has no listed row
response.ChatSessions = []protocol.ChatSession{session} // to splice, so that field stays empty and the client that asked for it opens
// the session from the echoed ChatSession instead.
if !ephemeral {
response.ChatSessions = []protocol.ChatSession{session}
}
_ = write(response) _ = write(response)
} }
+54
View File
@@ -1451,6 +1451,60 @@ func TestChatCreateRecordsOperatorSession(t *testing.T) {
} }
} }
func TestChatCreateEphemeralSessionIsNeverListed(t *testing.T) {
store := newOperatorStore(t)
broker := scriptedChat()
broker.created = protocol.ChatSession{ID: "ses_verify", Title: "New chat"}
dir := t.TempDir()
ctx, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatCreate, ID: "c1", ChatCreate: &protocol.ChatCreateRequest{Title: "New chat", Directory: dir, Ephemeral: true}}); err != nil {
t.Fatal(err)
}
var response protocol.Message
if err := wsjson.Read(ctx, conn, &response); err != nil {
t.Fatal(err)
}
// The session is real and usable: it is created, bootstrapped and echoed.
if response.Type != protocol.ChatCreate || response.ChatSession == nil || response.ChatSession.ID != "ses_verify" {
t.Fatalf("ephemeral chat_create response = %+v", response)
}
if calls, _, _ := broker.createQuery(); calls != 1 {
t.Fatalf("broker.Create calls = %d, want 1", calls)
}
broker.mu.Lock()
activateCalls := broker.activateCalls
broker.mu.Unlock()
if activateCalls != 1 {
t.Fatalf("manager bootstrap calls = %d, want 1", activateCalls)
}
// No LISTED row was written, so no list row is echoed and chat_sessions cannot
// list the verification chat...
if len(response.ChatSessions) != 0 {
t.Fatalf("ephemeral chat echoed a registry row: %+v", response.ChatSessions)
}
recorded, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(recorded) != 0 {
t.Fatalf("ephemeral chat recorded %d listed operator session(s): %+v", len(recorded), recorded)
}
// ...but the row is real, so the session stays closable like any other chat.
if _, found, err := store.OperatorSession(ctx, "ses_verify"); err != nil || !found {
t.Fatalf("ephemeral chat is not closable: found=%v err=%v", found, err)
}
if err := store.CloseOperatorSession(ctx, "ses_verify"); err != nil {
t.Fatalf("close ephemeral chat: %v", err)
}
listed, err := store.OperatorSessions(ctx)
if err != nil {
t.Fatal(err)
}
if len(listed) != 0 {
t.Fatalf("closing an ephemeral chat listed it: %+v", listed)
}
}
func TestChatCreateReportsManagerBootstrapFailure(t *testing.T) { func TestChatCreateReportsManagerBootstrapFailure(t *testing.T) {
broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")} broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")}
store := newOperatorStore(t) store := newOperatorStore(t)
+2 -2
View File
@@ -98,8 +98,8 @@ the pipeline list already carries — rather than a pluralised verb.
| C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | done — the composer at the foot of an open conversation: a growing 1–6-row `<textarea>` (placeholder `Message the agent… or / for commands`) where Enter submits and Shift+Enter inserts a newline (the submit routing is the pure `composerSubmit`), an `Attach file` control opening a multi-file picker, a removable chip per attachment (an image thumbnail else a file glyph, the display name, then the error text or `humanBytes(size)`, and a remove control named `Remove {name}`), and one primary control: Stop (`aria-label`/title `Stop`, error tint) while a turn runs, else Send (`aria-label` `Send`, disabled unless a non-blank draft with no failed attachment — or a slash draft). The 25 MiB guard reads `"{display}" is too large (25.0 MiB limit).` and an unreadable file `"{display}" could not be read.`; the web file picker cannot produce an unreadable file, so only the limit branch is captured and both are unit-tested (`test/chat.test.mjs`). Send trims the draft, clears the draft and the attachments at once, calls `chatPrompt` with `{session_id,text,operation_id,native_message_id}` (+ `files` only when present) and reads the reply's `chat_queued` into the notice `Queued — it will send when the current turn finishes.`; a rejected prompt restores the draft and the attachments (each flagged with the server's own message) and shows the shared `Action failed` dialog. The queued flag clears on any incoming frame (the client fans unsolicited envelopes out as a `frame` event; the composer folds it). The draft is kept per chat in memory **and** mirrored into `localStorage` (`pipelines.web.chatDraft.v1`) — the web analogue of per-device persistence — while attachments stay memory-only. Captured 2026-10-19 against a **freshly created** session (never the operator's own): `captures/56-chat-composer-draft.png`, `captures/60-chat-attachment-chips.png`, `captures/61-chat-attachment-removed.png`, `captures/63-chat-composer-stop.png` (a real prompt to the throwaway session turned Send into Stop), `captures/63b-chat-stop-interrupt.png` (the Stop control was **clicked**: it sent `chat_interrupt` and the page showed `Stopping the running turn…`, with no `Action failed` — the control is wired to `chat_interrupt`, never to the inert submit path) and `captures/64-chat-throwaway-closed.png` (after `/close`, the closed row plus the conversation pane left for the list). The throwaway session was created with `chat_create`, really prompted, really interrupted and closed with `chat_close`; the operator's session `ses_eae413f50ffeLQDExlg8cYnscN` was never prompted | | C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | done — the composer at the foot of an open conversation: a growing 1–6-row `<textarea>` (placeholder `Message the agent… or / for commands`) where Enter submits and Shift+Enter inserts a newline (the submit routing is the pure `composerSubmit`), an `Attach file` control opening a multi-file picker, a removable chip per attachment (an image thumbnail else a file glyph, the display name, then the error text or `humanBytes(size)`, and a remove control named `Remove {name}`), and one primary control: Stop (`aria-label`/title `Stop`, error tint) while a turn runs, else Send (`aria-label` `Send`, disabled unless a non-blank draft with no failed attachment — or a slash draft). The 25 MiB guard reads `"{display}" is too large (25.0 MiB limit).` and an unreadable file `"{display}" could not be read.`; the web file picker cannot produce an unreadable file, so only the limit branch is captured and both are unit-tested (`test/chat.test.mjs`). Send trims the draft, clears the draft and the attachments at once, calls `chatPrompt` with `{session_id,text,operation_id,native_message_id}` (+ `files` only when present) and reads the reply's `chat_queued` into the notice `Queued — it will send when the current turn finishes.`; a rejected prompt restores the draft and the attachments (each flagged with the server's own message) and shows the shared `Action failed` dialog. The queued flag clears on any incoming frame (the client fans unsolicited envelopes out as a `frame` event; the composer folds it). The draft is kept per chat in memory **and** mirrored into `localStorage` (`pipelines.web.chatDraft.v1`) — the web analogue of per-device persistence — while attachments stay memory-only. Captured 2026-10-19 against a **freshly created** session (never the operator's own): `captures/56-chat-composer-draft.png`, `captures/60-chat-attachment-chips.png`, `captures/61-chat-attachment-removed.png`, `captures/63-chat-composer-stop.png` (a real prompt to the throwaway session turned Send into Stop), `captures/63b-chat-stop-interrupt.png` (the Stop control was **clicked**: it sent `chat_interrupt` and the page showed `Stopping the running turn…`, with no `Action failed` — the control is wired to `chat_interrupt`, never to the inert submit path) and `captures/64-chat-throwaway-closed.png` (after `/close`, the closed row plus the conversation pane left for the list). The throwaway session was created with `chat_create`, really prompted, really interrupted and closed with `chat_close`; the operator's session `ses_eae413f50ffeLQDExlg8cYnscN` was never prompted |
| C9 | Slash commands | client-side | done — the palette appears above the composer only while the trimmed draft starts with `/` and has no whitespace, filtered case-insensitively by name prefix, each row showing `/name` and the summary and the highlighted row marked `aria-selected`; Up/Down move the highlight and Enter runs it, a tap runs a row directly, and running a command always consumes the draft and never reaches the prompt path. The five commands and their summaries are `CHAT_COMMANDS` (`/new`, `/close`, `/rename <title>`, `/stop`, `/help`), unit-tested verbatim, with `chatCommandHelp()` the `usage — summary` lines. Effects: `/new` sends `chat_create` directly (C2's item) and opens the created session, `/close` reuses the C3 `Close chat?` confirm, `/rename` writes through C13's durable device-local store (the same one the row's `Rename…` dialog uses), `/stop` interrupts (`chat_interrupt`) and `/help` shows the command list. Error wording is the Android source verbatim: the unknown command reads `“{token}” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.` with the draft offered back and `Send as message` / `Cancel`; an extra argument on an argument-less command reads `{usage} does not take an argument.`; `/rename` with no title reads `Usage: /rename <title> — renames this session on this device.`; `/stop` with nothing running reads `No turn is running in this chat.`. A notice renders as a full-width line after the turns (not a bubble) with the label `Command` / `Command failed` and a terminal glyph, error-coloured when failed. Captured 2026-10-19: `captures/57-chat-command-palette.png`, `captures/58-chat-command-palette-selected.png` (ArrowDown moved the highlight), `captures/59-chat-command-unknown.png` (the failed notice and its offer, dismissed with Cancel), `captures/62-chat-new-session.png` (`/new`'s created session and its `Command` notice) | | C9 | Slash commands | client-side | done — the palette appears above the composer only while the trimmed draft starts with `/` and has no whitespace, filtered case-insensitively by name prefix, each row showing `/name` and the summary and the highlighted row marked `aria-selected`; Up/Down move the highlight and Enter runs it, a tap runs a row directly, and running a command always consumes the draft and never reaches the prompt path. The five commands and their summaries are `CHAT_COMMANDS` (`/new`, `/close`, `/rename <title>`, `/stop`, `/help`), unit-tested verbatim, with `chatCommandHelp()` the `usage — summary` lines. Effects: `/new` sends `chat_create` directly (C2's item) and opens the created session, `/close` reuses the C3 `Close chat?` confirm, `/rename` writes through C13's durable device-local store (the same one the row's `Rename…` dialog uses), `/stop` interrupts (`chat_interrupt`) and `/help` shows the command list. Error wording is the Android source verbatim: the unknown command reads `“{token}” is not a command, so nothing was sent to the agent. Send it as a message, or cancel.` with the draft offered back and `Send as message` / `Cancel`; an extra argument on an argument-less command reads `{usage} does not take an argument.`; `/rename` with no title reads `Usage: /rename <title> — renames this session on this device.`; `/stop` with nothing running reads `No turn is running in this chat.`. A notice renders as a full-width line after the turns (not a bubble) with the label `Command` / `Command failed` and a terminal glyph, error-coloured when failed. Captured 2026-10-19: `captures/57-chat-command-palette.png`, `captures/58-chat-command-palette-selected.png` (ArrowDown moved the highlight), `captures/59-chat-command-unknown.png` (the failed notice and its offer, dismissed with Cancel), `captures/62-chat-new-session.png` (`/new`'s created session and its `Command` notice) |
| C10 | Permission/approval cards (allow once/always/reject) | `chat_permission`, `chat_reply` | done — captured 2026-10-19: `captures/65-chat-approval-pending.png` (the pending card as the transcript's last item: the amber outlined shield + `Approve bash`, `Waiting for your response`, the request's six monospace resource lines, the amber `RISK REVIEW` panel, the `Allow once` / `Always allow` / `Reject` controls, and the top bar's `Waiting for your approval` control, with `#chatRunning` stood down), `captures/66-chat-approval-answered.png` (`Allowed once` / `Waiting for the agent to continue…`, controls and top-bar control gone), `captures/67-chat-approval-resolved.png` (a server resolution: `Always allowed` with its note `Another client already allowed this.`, no controls, no risk panel) and `captures/68-chat-approval-rejected.png` (a blank-action request answered `Reject`: `Rejected` / `Waiting for the agent to continue…`, the risk panel kept with the fallback sentence, no controls). The pure model is `src/chat.js` (`approvalCard`/`applyChatPermission`/`permissionRiskText`/`decisionLabel`): while pending `Approve {action}` (blank action → `Approve tool call`), after answering the decision label (`Allowed once` / `Always allowed` / `Rejected`, an unknown decision → `Resolved`) and `Waiting for the agent to continue…`, and once the server reports `resolved`/a decision that label (else `Already resolved`) with its `message` as the status (else `Another client already answered this request.`); the amber `RISK REVIEW` box shows only while pending or after a reject. Resources drop blanks and cap at six visible lines: `approvalResourceText` caps the joined text at six lines with an ellipsis on the last kept line, and the rendered text is a padding-free `-webkit-line-clamp: 6` block inside a padded frame, so a long resource that wraps is elided at the content edge and no seventh line paints into the frame's padding — matching Android's `maxLines = 6, Ellipsis` (the smoke asserts six clipped lines, a hidden overflow and the block ending at the frame's content edge, with seven lines unclamped). `Allow once` is rendered as the browser's filled primary control, matching the app's filled `Button` versus its two `TextButton`s; the head and risk-panel shields are inline SVG stroked with `currentColor` so the warn hue actually tints them (a colour emoji cannot be tinted). A server resolution always outranks a local answer, a new request replaces the settled card and clears the answer, and the same request keeps it. `PipelinesRepository.chatReply` sends exactly `{type:'chat_reply',chat_reply:{session_id,request_id,decision,client}}` (`message` only when non-blank) and refuses blank ids or a decision outside once/always/reject; answering settles the card optimistically, and a refused send reopens the same request and reports the server's reason on the thread's error line (ignored if a different request has replaced the card), so an unaccepted decision is never shown as accepted. The card is fed by `chat_permission` frames through `client.js`'s unsolicited-frame path, folded only for sessions this client has open. **Replayed, not real**: no live pending approval was available, so the captures were driven by synthetic `chat_permission` frames replayed through the page's own socket handler against the live session; the page's real `chat_reply` path was exercised but the smoke's shim suppressed every reply for the synthetic request ids (suppressed 3, one of them answered with a server error to prove the reopen path, forwarded 0), so **no approval decision was sent to the operator's server**. Unit-tested in `test/chat.test.mjs` and the reply shape in `test/repository.test.mjs`; the DOM assertions and log lines are produced by `test/ui-smoke.mjs` | | C10 | Permission/approval cards (allow once/always/reject) | `chat_permission`, `chat_reply` | done — captured 2026-10-19: `captures/65-chat-approval-pending.png` (the pending card as the transcript's last item: the amber outlined shield + `Approve bash`, `Waiting for your response`, the request's six monospace resource lines, the amber `RISK REVIEW` panel, the `Allow once` / `Always allow` / `Reject` controls, and the top bar's `Waiting for your approval` control, with `#chatRunning` stood down), `captures/66-chat-approval-answered.png` (`Allowed once` / `Waiting for the agent to continue…`, controls and top-bar control gone), `captures/67-chat-approval-resolved.png` (a server resolution: `Always allowed` with its note `Another client already allowed this.`, no controls, no risk panel) and `captures/68-chat-approval-rejected.png` (a blank-action request answered `Reject`: `Rejected` / `Waiting for the agent to continue…`, the risk panel kept with the fallback sentence, no controls). The pure model is `src/chat.js` (`approvalCard`/`applyChatPermission`/`permissionRiskText`/`decisionLabel`): while pending `Approve {action}` (blank action → `Approve tool call`), after answering the decision label (`Allowed once` / `Always allowed` / `Rejected`, an unknown decision → `Resolved`) and `Waiting for the agent to continue…`, and once the server reports `resolved`/a decision that label (else `Already resolved`) with its `message` as the status (else `Another client already answered this request.`); the amber `RISK REVIEW` box shows only while pending or after a reject. Resources drop blanks and cap at six visible lines: `approvalResourceText` caps the joined text at six lines with an ellipsis on the last kept line, and the rendered text is a padding-free `-webkit-line-clamp: 6` block inside a padded frame, so a long resource that wraps is elided at the content edge and no seventh line paints into the frame's padding — matching Android's `maxLines = 6, Ellipsis` (the smoke asserts six clipped lines, a hidden overflow and the block ending at the frame's content edge, with seven lines unclamped). `Allow once` is rendered as the browser's filled primary control, matching the app's filled `Button` versus its two `TextButton`s; the head and risk-panel shields are inline SVG stroked with `currentColor` so the warn hue actually tints them (a colour emoji cannot be tinted). A server resolution always outranks a local answer, a new request replaces the settled card and clears the answer, and the same request keeps it. `PipelinesRepository.chatReply` sends exactly `{type:'chat_reply',chat_reply:{session_id,request_id,decision,client}}` (`message` only when non-blank) and refuses blank ids or a decision outside once/always/reject; answering settles the card optimistically, and a refused send reopens the same request and reports the server's reason on the thread's error line (ignored if a different request has replaced the card), so an unaccepted decision is never shown as accepted. The card is fed by `chat_permission` frames through `client.js`'s unsolicited-frame path, folded only for sessions this client has open. **Replayed, not real**: no live pending approval was available, so the captures were driven by synthetic `chat_permission` frames replayed through the page's own socket handler against the live session; the page's real `chat_reply` path was exercised but the smoke's shim suppressed every reply for the synthetic request ids (suppressed 3, one of them answered with a server error to prove the reopen path, forwarded 0), so **no approval decision was sent to the operator's server**. Unit-tested in `test/chat.test.mjs` and the reply shape in `test/repository.test.mjs`; the DOM assertions and log lines are produced by `test/ui-smoke.mjs` |
| C11 | Background tasks bar: running shells only, capped + scrollable, bounded output page | `chat_shells`, `chat_shell_output` | todo | | C11 | Background tasks bar: running shells only, capped + scrollable, bounded output page | `chat_shells`, `chat_shell_output` | done — captured 2026-10-19 into a live session: `captures/65-chat-background-tasks.png` (the bar with five running tasks — heading `Background tasks`, count `5 running`, three visible rows and a scrolling list), `captures/66-chat-background-task-detail.png` (a selected task's detail: `Command` + the command, `Task identity` + the id in monospace, `Status: running`, then `Output` + the monospace text and `Refresh`), `captures/67-chat-background-task-empty.png` (`No output yet.`), `captures/68-chat-background-task-unavailable.png` (`Output unavailable for this task.`), `captures/69-chat-background-task-truncated.png` (`Output is bounded to 64 KiB.` plus `Refresh`), `captures/70-chat-background-task-loading.png` (the spinner while the page loads) and `captures/71-chat-background-tasks-exited.png` (the bar gone after the last exit). The bar is shown only while at least one shell is running and disappears with the last exit; only running shells are listed (an exited shell is never a task). Its visible rows are capped at 3 (`BACKGROUND_TASK_VISIBLE_ROWS`) and the list scrolls beyond that instead of growing; each row is a play glyph + `Running` + `shellCommandSummary(command)` (trimmed, whitespace-collapsed, elided past 72; blank → `background process`) + `Details` only while selected, and tapping a row toggles its detail pane. Refresh always rereads the page from cursor 0 with `limit` 65536 (`SHELL_OUTPUT_LIMIT`, the server's 64 KiB bound) and never appends, so the client's output cannot grow unbounded — the smoke's own Refresh click issues exactly such a second read and the smoke asserts its `{cursor:0,limit:65536}` bounds. `chat_shells` is fetched when the conversation opens (`chat_query` body `{session_id}`) and again on every stream reconnect, and `chat_shell_output` sends `chat_shell_output_query` (`{session_id,shell_id,cursor,limit}`); both the request shapes and the pure model (`runningBackgroundShells`, `shellCommandSummary`, `mergeShellFrame`, `shellsLoaded`, `shellOutputState`, every wording constant) are unit-tested (`test/chat.test.mjs`, `test/repository.test.mjs`). A `shell` frame folds its shell into the retained set, merges a blank command from the previous frame, and never marks the thread running — a background process outlives the turn (a step ending does not clear it; only the reconnect drops and re-learns it). Every server string is set with `textContent`; shell output is never parsed as markup. **Replayed vs real, stated plainly**: only the `shell` frames (injected synthetic `chat_event` frames) and the `chat_shell_output` pages (answered by a socket reply hook) are synthetic, because the live server had no running shell to read safely; the `chat_shells` list, the `chat_subscribe` ack and every `chat_history` reply came from the real server, and the smoke asserts the real `chat_shells` fetch on open and after a reconnect. The one drop that hit a bounded read mid-section was recovered by the smoke's own bounded retry through the page's controls |
| C12 | Human-decision notices inside chat + dismiss | `chat_event` | todo | | C12 | Human-decision notices inside chat + dismiss | `chat_event` | done — the local command-notice surface is captured and dismissible per notice. Captured 2026-10-19: `captures/72-chat-command-notice.png` (a full-width `Command` line after the turns, never a message bubble: the shared terminal glyph `>_`, the `/help` command list and its own `Dismiss`), `captures/73-chat-command-failed-offer.png` (an unknown command: `Command failed` in the error tint, the exact Android sentence and the `Send as message` / `Cancel` pair) and `captures/74-chat-command-dismissed.png` (the `/help` notice dismissed; the failed offer line and its controls remain — exactly one notice removed). A notice is a local `ChatCommandNotice`, never a `ChatMessage`: it lives in that conversation's `state.chatThreads` entry, survives switching away and back while the page is open, and never enters the prompt path — the smoke's recorded sends show **no** `chat_prompt` for `/help` or an unknown command. `Send as message` takes the offered draft through the ordinary `postChatPrompt` path, removing the notice **before** sending, so a stale second tap sends nothing (the smoke verifies both on a throwaway session). The pure model lives in `src/chat.js` (`makeChatNotice`, `appendChatNotice`, `dismissChatNotice`, `takeChatNoticeOffer`, `chatNoticeLabel`) and is unit-tested (`test/chat.test.mjs`): append, dismiss one, take the offer, a stale/offerless offer returning null and leaving the list untouched, per-conversation scoping, and the failed label/tint flag. **Wire finding, not an invented source**: `chat_event` kinds are exactly `user`, `text`, `reasoning`, `tool`, `shell`, `step` and `usage` (`internal/protocol/chat.go` `ChatEvent*`), and `chat_permission` is the only approval frame — there is **no** in-chat run-decision notice on the wire. Run-level human decisions live on R11's run-detail decision sheet (`decide_run`) and C10's approval cards (`chat_permission` / `chat_reply`), exactly as the app does it. **Stated browser divergence**: Android's `ChatCommandNoticeItem` shows actions only when `offer != null`, so it cannot dismiss a `/help` or `/new` line; the browser adds a `Dismiss` control (accessible name `Dismiss command notice`) on offerless notices to meet "each is individually dismissible", keeping the app's `Send as message` / `Cancel` pair verbatim on offer notices. |
| C13 | Local rename/hide, seen state, persistence to `localStorage` | client-side | done — the row's `.chat-menu-button` (`Chat actions`) opens, in Android's order, `Rename…`, `Close chat…` (open rows) or `Reopen` (closed rows) and `Hide on this device`; the list is unclipped only while the menu is open (`.chat-list.menu-open`, mirroring `.list.runs`) so the panel is never cut off at the list's bottom edge, and the smoke hit-tests the last row's `Hide on this device` at its own centre. **Rename (device-local)**: the dialog is titled `Rename chat`, has a field labelled `Name` pre-filled with the current effective title, the helper `The server has no rename for a chat, so this name is kept on this device.`, and `Save` (disabled while the trimmed value is blank) / `Cancel`; backdrop and Escape close it, typing toggles Save in place without re-rendering the transcript, and saving sends nothing. A local title is trimmed and wins over the server's on every later list refresh. **Hide (device-local, distinct from the server close)**: the row disappears here, the open conversation closes (its thread dropped, `chatActiveId` cleared, its subscription forgotten) and one snackbar reads `Hidden on this device; the chat stays on the server.` with `Undo`; a newer hide replaces the in-flight report rather than queueing, and `Undo` restores the row and clears the hidden list — nothing on the server is touched. **Seen markers**: the row's dot+word badge is `Streaming` / `New` / `Open`, precedence exactly Streaming > New > Open, with `Open` only while that conversation is open (never colour alone; word is always rendered). A session is new only when it is not the active one and either it is in the explicit unseen set (a pushed `chat_event` for a backgrounded chat) or it has never been opened here and its `updated_at` is strictly greater than the stored watermark; the first sight of a session is seeded as a baseline only when its watermark is 0 and `updated_at > 0`, so pre-existing chats are never all "new", and opening a conversation advances the watermark (monotonically — a stale read cannot rewind) and clears its mark. **Persistence** is the web analogue of the app's SharedPreferences, one JSON value per key, both decoding blank/corrupt/wrong-typed input to their empty model: `pipelines.web.chatOverrides.v1` = `{"titles":{"<id>":"<title>"},"hidden":["<id>"]}` and `pipelines.web.chatSeen.v1` = `{"seenAt":{"<id>":<updated_at ms>},"unseen":["<id>"]}` (Android field names `titles`/`hidden` and `seenAt`/`unseen`). The pure model lives in `src/chat.js` (`renameChatOverride`/`hideChatOverride`/`restoreChatOverride`/`applyChatOverrides`, `chatSeenWatermark`/`seedChatSeen`/`readChatSeen`/`markChatUnseen`/`isChatSessionUnseen`, the tolerant `decode`/`encode`) and is unit-tested in `test/chat.test.mjs`. C9's `/rename <title>` now writes through the same durable store. Captured 2026-10-19, all live (no synthesised frames): `captures/72-chat-rename-dialog.png` (the dialog, blank field, Save disabled), `captures/73-chat-renamed-row.png` (a closed row showing its local title `Local capture chat` after a server list refresh), `captures/74-chat-hide-snackbar.png` (the hidden open conversation closed, one snackbar with `Undo`) and `captures/75-chat-new-marker.png` (the non-active prompt-and-stopped throwaway, reloaded and reconnected, carrying the coloured dot + `New`). The New marker is **not** synthesised: the smoke `/new`s a throwaway, sends a real prompt, clicks `Stop`, reloads the page and reconnects, then asserts the row's `.chat-activity-new` word `New` while the persisted watermark predates the turn | | C13 | Local rename/hide, seen state, persistence to `localStorage` | client-side | done — the row's `.chat-menu-button` (`Chat actions`) opens, in Android's order, `Rename…`, `Close chat…` (open rows) or `Reopen` (closed rows) and `Hide on this device`; the list is unclipped only while the menu is open (`.chat-list.menu-open`, mirroring `.list.runs`) so the panel is never cut off at the list's bottom edge, and the smoke hit-tests the last row's `Hide on this device` at its own centre. **Rename (device-local)**: the dialog is titled `Rename chat`, has a field labelled `Name` pre-filled with the current effective title, the helper `The server has no rename for a chat, so this name is kept on this device.`, and `Save` (disabled while the trimmed value is blank) / `Cancel`; backdrop and Escape close it, typing toggles Save in place without re-rendering the transcript, and saving sends nothing. A local title is trimmed and wins over the server's on every later list refresh. **Hide (device-local, distinct from the server close)**: the row disappears here, the open conversation closes (its thread dropped, `chatActiveId` cleared, its subscription forgotten) and one snackbar reads `Hidden on this device; the chat stays on the server.` with `Undo`; a newer hide replaces the in-flight report rather than queueing, and `Undo` restores the row and clears the hidden list — nothing on the server is touched. **Seen markers**: the row's dot+word badge is `Streaming` / `New` / `Open`, precedence exactly Streaming > New > Open, with `Open` only while that conversation is open (never colour alone; word is always rendered). A session is new only when it is not the active one and either it is in the explicit unseen set (a pushed `chat_event` for a backgrounded chat) or it has never been opened here and its `updated_at` is strictly greater than the stored watermark; the first sight of a session is seeded as a baseline only when its watermark is 0 and `updated_at > 0`, so pre-existing chats are never all "new", and opening a conversation advances the watermark (monotonically — a stale read cannot rewind) and clears its mark. **Persistence** is the web analogue of the app's SharedPreferences, one JSON value per key, both decoding blank/corrupt/wrong-typed input to their empty model: `pipelines.web.chatOverrides.v1` = `{"titles":{"<id>":"<title>"},"hidden":["<id>"]}` and `pipelines.web.chatSeen.v1` = `{"seenAt":{"<id>":<updated_at ms>},"unseen":["<id>"]}` (Android field names `titles`/`hidden` and `seenAt`/`unseen`). The pure model lives in `src/chat.js` (`renameChatOverride`/`hideChatOverride`/`restoreChatOverride`/`applyChatOverrides`, `chatSeenWatermark`/`seedChatSeen`/`readChatSeen`/`markChatUnseen`/`isChatSessionUnseen`, the tolerant `decode`/`encode`) and is unit-tested in `test/chat.test.mjs`. C9's `/rename <title>` now writes through the same durable store. Captured 2026-10-19, all live (no synthesised frames): `captures/72-chat-rename-dialog.png` (the dialog, blank field, Save disabled), `captures/73-chat-renamed-row.png` (a closed row showing its local title `Local capture chat` after a server list refresh), `captures/74-chat-hide-snackbar.png` (the hidden open conversation closed, one snackbar with `Undo`) and `captures/75-chat-new-marker.png` (the non-active prompt-and-stopped throwaway, reloaded and reconnected, carrying the coloured dot + `New`). The New marker is **not** synthesised: the smoke `/new`s a throwaway, sends a real prompt, clicks `Stop`, reloads the page and reconnects, then asserts the row's `.chat-activity-new` word `New` while the persisted watermark predates the turn |
| C14 | Scroll behaviour: follow newest, "jump to newest", restored position | client-side | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the conversation opens at its newest content instantly — the only live session has no saved position, so it lands at the end rather than at the top of a turn taller than the viewport) and `captures/46-chat-transcript-top.png` (after a **real wheel gesture** on the transcript — the app's own listener, not a programmatic scroll, which by the implementation's own rule cannot change intent — `Jump to latest` is offered; the smoke asserts the control and performs the gesture, `ui-smoke` log line "after a real wheel gesture (scrollTop 0) 'Jump to latest' is offered at the top"). A thread with a saved position is restored to it (a saved top, index 0, is a real position and is never treated as "new"); while within the 32 px bottom threshold the view follows, and only the operator's own wheel/drag changes that intent (a programmatic placement or follow cannot); `Jump to latest` is offered only when not following and something is below the fold; the position is saved per session in `localStorage` (`pipelines.web.chatScroll.v1`). A re-render (opening/dismissing a dialog, a refresh, or the loading frame of a paging fetch) captures the live position first and puts the operator back exactly where they were — the smoke asserts the transcript stays put across the `Close chat?` dialog (`ui-smoke` log line "the transcript stayed put across the dialog (top 7141 -> 7141)"); the paging anchor is held until the frame that actually carries the older page, so a real prepend stays on the previously visible message. No auto-load on scroll. The pure decisions are unit-tested (`chatBottomDistancePx`, `chatFollowsAt`, `chatShowJumpToLatest`, `chatOpensAtNewest`, `chatFirstScroll`) in `test/chat.test.mjs`, and the live measurement uses `chatBottomDistancePx` itself | | C14 | Scroll behaviour: follow newest, "jump to newest", restored position | client-side | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the conversation opens at its newest content instantly — the only live session has no saved position, so it lands at the end rather than at the top of a turn taller than the viewport) and `captures/46-chat-transcript-top.png` (after a **real wheel gesture** on the transcript — the app's own listener, not a programmatic scroll, which by the implementation's own rule cannot change intent — `Jump to latest` is offered; the smoke asserts the control and performs the gesture, `ui-smoke` log line "after a real wheel gesture (scrollTop 0) 'Jump to latest' is offered at the top"). A thread with a saved position is restored to it (a saved top, index 0, is a real position and is never treated as "new"); while within the 32 px bottom threshold the view follows, and only the operator's own wheel/drag changes that intent (a programmatic placement or follow cannot); `Jump to latest` is offered only when not following and something is below the fold; the position is saved per session in `localStorage` (`pipelines.web.chatScroll.v1`). A re-render (opening/dismissing a dialog, a refresh, or the loading frame of a paging fetch) captures the live position first and puts the operator back exactly where they were — the smoke asserts the transcript stays put across the `Close chat?` dialog (`ui-smoke` log line "the transcript stayed put across the dialog (top 7141 -> 7141)"); the paging anchor is held until the frame that actually carries the older page, so a real prepend stays on the previously visible message. No auto-load on scroll. The pure decisions are unit-tested (`chatBottomDistancePx`, `chatFollowsAt`, `chatShowJumpToLatest`, `chatOpensAtNewest`, `chatFirstScroll`) in `test/chat.test.mjs`, and the live measurement uses `chatBottomDistancePx` itself |
+39 -10
View File
@@ -230,6 +230,7 @@ import {
BACKGROUND_TASKS_TITLE, BACKGROUND_TASKS_TITLE,
CHAT_ACTIONS_LABEL, CHAT_ACTIONS_LABEL,
CHAT_ATTACH_LABEL, CHAT_ATTACH_LABEL,
CHAT_COMMAND_DISMISS_LABEL,
CHAT_COMMAND_GLYPH, CHAT_COMMAND_GLYPH,
CHAT_COMPOSER_PLACEHOLDER, CHAT_COMPOSER_PLACEHOLDER,
CHAT_EMPTY, CHAT_EMPTY,
@@ -283,6 +284,7 @@ import {
applyChatEvent, applyChatEvent,
applyChatOverrides, applyChatOverrides,
applyChatPermission, applyChatPermission,
appendChatNotice,
approvalCard, approvalCard,
attachmentDisplayName, attachmentDisplayName,
attachmentError, attachmentError,
@@ -296,6 +298,7 @@ import {
chatFollowsAt, chatFollowsAt,
chatHeaderMeta, chatHeaderMeta,
chatNoMatchMessage, chatNoMatchMessage,
chatNoticeLabel,
chatOpensAtNewest, chatOpensAtNewest,
chatShowJumpToLatest, chatShowJumpToLatest,
chatStreamState, chatStreamState,
@@ -307,6 +310,7 @@ import {
decodeChatOverrides, decodeChatOverrides,
decodeChatSeen, decodeChatSeen,
directoryLabel, directoryLabel,
dismissChatNotice as dismissChatNoticeModel,
emptyChatOverrides, emptyChatOverrides,
emptyChatSeen, emptyChatSeen,
encodeChatOverrides, encodeChatOverrides,
@@ -316,6 +320,7 @@ import {
hideChatOverride, hideChatOverride,
historyResync, historyResync,
isChatSessionUnseen, isChatSessionUnseen,
makeChatNotice,
markChatUnseen, markChatUnseen,
mergeHistoryPage, mergeHistoryPage,
mergeShellFrame, mergeShellFrame,
@@ -342,6 +347,7 @@ import {
shellCommandSummary, shellCommandSummary,
shellOutputState, shellOutputState,
shellsLoaded, shellsLoaded,
takeChatNoticeOffer as takeChatNoticeOfferModel,
formatToolDuration, formatToolDuration,
threadElapsedMillis, threadElapsedMillis,
threadPhase, threadPhase,
@@ -4654,15 +4660,15 @@ function addChatNotice(sessionId, text, { failed = false, offer = null } = {}) {
const thread = state.chatThreads.get(sessionId); const thread = state.chatThreads.get(sessionId);
if (!thread) return; if (!thread) return;
chatNoticeSeq += 1; chatNoticeSeq += 1;
const notice = { id: `notice-${chatNoticeSeq}`, text, failed, offer }; const notice = makeChatNotice(`notice-${chatNoticeSeq}`, text, { failed, offer });
setThread(sessionId, { notices: [...(thread.notices ?? []), notice] }); setThread(sessionId, { notices: appendChatNotice(thread.notices, notice) });
} }
/** Remove one local command line (the operator cancelled its offer). */ /** Remove one local command line (the operator cancelled or dismissed it). */
function dismissChatNotice(sessionId, noticeId) { function dismissChatNotice(sessionId, noticeId) {
const thread = state.chatThreads.get(sessionId); const thread = state.chatThreads.get(sessionId);
if (!thread) return; if (!thread) return;
setThread(sessionId, { notices: (thread.notices ?? []).filter((n) => n.id !== noticeId) }); setThread(sessionId, { notices: dismissChatNoticeModel(thread.notices, noticeId) });
renderContent(); renderContent();
} }
@@ -4672,10 +4678,11 @@ function dismissChatNotice(sessionId, noticeId) {
*/ */
function takeChatNoticeOffer(sessionId, noticeId) { function takeChatNoticeOffer(sessionId, noticeId) {
const thread = state.chatThreads.get(sessionId); const thread = state.chatThreads.get(sessionId);
const notice = (thread?.notices ?? []).find((n) => n.id === noticeId); if (!thread) return null;
if (!notice || notice.offer == null) return null; const taken = takeChatNoticeOfferModel(thread.notices, noticeId);
setThread(sessionId, { notices: (thread.notices ?? []).filter((n) => n.id !== noticeId) }); if (taken.offer == null) return null;
return notice.offer; setThread(sessionId, { notices: taken.notices });
return taken.offer;
} }
/** /**
@@ -4822,7 +4829,12 @@ function applyChatCommandEffect(sessionId, session, effect) {
async function startChatSession(directory) { async function startChatSession(directory) {
const from = state.chatActiveId; const from = state.chatActiveId;
try { try {
const created = await repo.chatCreate("New chat", directory); // An automated check (the UI smoke) can mark its throwaway chat ephemeral, so
// creating one for verification never adds a stray "New chat" to the
// operator's list. Set only by test tooling; a normal page leaves it unset.
const created = await repo.chatCreate("New chat", directory, undefined, {
ephemeral: globalThis.__pipelinesEphemeralChat === true,
});
// The list is the server's; insert the created session so the row is present // The list is the server's; insert the created session so the row is present
// before the conversation opens, then refresh from the server. // before the conversation opens, then refresh from the server.
state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)]; state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)];
@@ -6151,6 +6163,7 @@ function renderChatCommandNotice(sessionId, notice) {
const row = h("div", { const row = h("div", {
class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`, class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`,
role: "note", role: "note",
"data-notice-id": notice?.id ?? "",
}); });
const head = h("div", { class: "chat-command-notice-head" }); const head = h("div", { class: "chat-command-notice-head" });
head.append( head.append(
@@ -6163,7 +6176,7 @@ function renderChatCommandNotice(sessionId, notice) {
}), }),
); );
head.append( head.append(
h("span", { class: "chat-command-notice-label", text: failed ? "Command failed" : "Command" }), h("span", { class: "chat-command-notice-label", text: chatNoticeLabel(failed) }),
); );
row.append(head); row.append(head);
row.append(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" })); row.append(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" }));
@@ -6186,6 +6199,22 @@ function renderChatCommandNotice(sessionId, notice) {
}), }),
); );
row.append(actions); row.append(actions);
} else {
// Android only offers the Send/Cancel pair on an offer-bearing notice, so a
// `/help` or `/new` line cannot be dismissed there. The browser item requires
// each notice to be individually dismissible; the wording and the offer pair
// still match the app verbatim, and this extra control is stated in PARITY.
const actions = h("div", { class: "chat-command-notice-actions" });
actions.append(
h("button", {
class: "ghost chat-command-dismiss",
type: "button",
text: "Dismiss",
"aria-label": CHAT_COMMAND_DISMISS_LABEL,
onclick: () => dismissChatNotice(sessionId, notice.id),
}),
);
row.append(actions);
} }
return row; return row;
} }
+59 -1
View File
@@ -20,7 +20,11 @@
// chatShowJumpToLatest, chatOpensAtNewest, // chatShowJumpToLatest, chatOpensAtNewest,
// chatFirstScroll // chatFirstScroll
// ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an // ui/chat/ChatStore.kt the history page merge (dedupe by id, prepend an
// older page, replace nextCursor/hasMore) // older page, replace nextCursor/hasMore) and the
// local command notices (append, dismiss one,
// take an offer; ChatCommandNotice)
// ui/chat/ChatCommandUi.kt the Command / Command failed labels and the
// terminal glyph of one local notice line
// ui/chat/ChatComposer.kt composerAction, composerCanSend/composerSendEnabled, // ui/chat/ChatComposer.kt composerAction, composerCanSend/composerSendEnabled,
// the submit routing (command vs prompt) // the submit routing (command vs prompt)
// ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions, // ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions,
@@ -1624,6 +1628,60 @@ export const CHAT_QUEUED_NOTICE = "Queued — it will send when the current turn
*/ */
export const CHAT_COMMAND_GLYPH = ">_"; export const CHAT_COMMAND_GLYPH = ">_";
/** The two labels a local command line can carry (ChatCommandUi.kt). */
export const CHAT_COMMAND_LABEL = "Command";
export const CHAT_COMMAND_FAILED_LABEL = "Command failed";
/** The accessible name of an offerless notice's dismiss control. */
export const CHAT_COMMAND_DISMISS_LABEL = "Dismiss command notice";
/**
* The label for one command notice: `Command failed` when the command could not
* be honoured, else `Command` (ChatCommandUi.kt's own choice). The same flag
* selects the error tint on the caller's row.
*/
export function chatNoticeLabel(failed) {
return failed === true ? CHAT_COMMAND_FAILED_LABEL : CHAT_COMMAND_LABEL;
}
/**
* One local command line, the app's `ChatCommandNotice` shape: it lives beside a
* conversation, never inside its messages, so it is never sent to the agent.
* [offer] is set only for an unrecognised command, whose draft the operator can
* still choose to send as a message.
*/
export function makeChatNotice(id, text, { failed = false, offer = null } = {}) {
return {
id: str(id),
text: str(text),
failed: failed === true,
offer: offer == null ? null : str(offer),
};
}
/** Append one notice to a conversation's list, preserving order. */
export function appendChatNotice(notices, notice) {
return [...(notices ?? []), notice];
}
/** Drop one notice by id, leaving every other notice and its order untouched. */
export function dismissChatNotice(notices, noticeId) {
return (notices ?? []).filter((notice) => notice?.id !== noticeId);
}
/**
* Take the draft an unrecognised-command notice offers, removing the notice
* first (mirrors `ChatStore.takeNoticeOffer`). Returns `{notices, offer}`:
* `offer` is null — and the list is returned untouched — when the notice is
* missing, already taken or carries no offer, so a stale tap sends nothing.
*/
export function takeChatNoticeOffer(notices, noticeId) {
const list = notices ?? [];
const notice = list.find((entry) => entry?.id === noticeId);
if (!notice || notice.offer == null) return { notices: list, offer: null };
return { notices: dismissChatNotice(list, noticeId), offer: notice.offer };
}
/** The two values of [composerAction]. */ /** The two values of [composerAction]. */
export const COMPOSER_SEND = "send"; export const COMPOSER_SEND = "send";
export const COMPOSER_STOP = "stop"; export const COMPOSER_STOP = "stop";
+7 -2
View File
@@ -389,11 +389,16 @@ export class PipelinesRepository {
* never created in whatever directory the server happens to be running in. The * never created in whatever directory the server happens to be running in. The
* reply's `chat_session` is returned, or a `ProtocolError` when the server did * reply's `chat_session` is returned, or a `ProtocolError` when the server did
* not return one. * not return one.
*
* `ephemeral` creates a verification chat: the server makes and bootstraps the
* session but records no operator-registry row, so the chat never appears in
* `chat_sessions` for the operator. Automated checks that drive this real page
* set it, so a run can never leave a stray "New chat" in the operator's list.
*/ */
async chatCreate(title, directory, operationId = newChatOperationId()) { async chatCreate(title, directory, operationId = newChatOperationId(), { ephemeral = false } = {}) {
const response = await this.#client.call({ const response = await this.#client.call({
type: Protocol.CHAT_CREATE, type: Protocol.CHAT_CREATE,
[ChatKeys.CREATE]: { title, directory, operation_id: operationId }, [ChatKeys.CREATE]: { title, directory, operation_id: operationId, ...(ephemeral ? { ephemeral: true } : {}) },
}); });
const session = response[ChatKeys.SESSION]; const session = response[ChatKeys.SESSION];
if (!session) { if (!session) {
+105
View File
@@ -9,7 +9,10 @@ import {
BACKGROUND_TASK_VISIBLE_ROWS, BACKGROUND_TASK_VISIBLE_ROWS,
CHAT_ACTIONS_LABEL, CHAT_ACTIONS_LABEL,
CHAT_COMMANDS, CHAT_COMMANDS,
CHAT_COMMAND_DISMISS_LABEL,
CHAT_COMMAND_FAILED_LABEL,
CHAT_COMMAND_GLYPH, CHAT_COMMAND_GLYPH,
CHAT_COMMAND_LABEL,
CHAT_FOLLOW_THRESHOLD_PX, CHAT_FOLLOW_THRESHOLD_PX,
CHAT_HIDE_ACTION, CHAT_HIDE_ACTION,
CHAT_QUEUED_NOTICE, CHAT_QUEUED_NOTICE,
@@ -58,6 +61,7 @@ import {
TURN_PHASE_TOOL, TURN_PHASE_TOOL,
TURN_PHASE_WAITING, TURN_PHASE_WAITING,
TURN_THINKING_WINDOW_MILLIS, TURN_THINKING_WINDOW_MILLIS,
appendChatNotice,
applyChatEvent, applyChatEvent,
applyChatOverrides, applyChatOverrides,
applyChatPermission, applyChatPermission,
@@ -77,6 +81,7 @@ import {
chatFollowsAt, chatFollowsAt,
chatHeaderMeta, chatHeaderMeta,
chatNoMatchMessage, chatNoMatchMessage,
chatNoticeLabel,
chatOpensAtNewest, chatOpensAtNewest,
chatSeenWatermark, chatSeenWatermark,
chatShowJumpToLatest, chatShowJumpToLatest,
@@ -91,6 +96,7 @@ import {
decodeChatSeen, decodeChatSeen,
deltaPartId, deltaPartId,
directoryLabel, directoryLabel,
dismissChatNotice,
emptyChatOverrides, emptyChatOverrides,
emptyChatSeen, emptyChatSeen,
encodeChatOverrides, encodeChatOverrides,
@@ -102,6 +108,7 @@ import {
historyResync, historyResync,
isChatSessionUnseen, isChatSessionUnseen,
lineDiff, lineDiff,
makeChatNotice,
markChatUnseen, markChatUnseen,
mergeHistoryPage, mergeHistoryPage,
mergeShellFrame, mergeShellFrame,
@@ -134,6 +141,7 @@ import {
shellCommandSummary, shellCommandSummary,
shellOutputState, shellOutputState,
shellsLoaded, shellsLoaded,
takeChatNoticeOffer,
threadElapsedMillis, threadElapsedMillis,
threadPhase, threadPhase,
threadRunningTools, threadRunningTools,
@@ -858,6 +866,103 @@ test("a command notice carries one terminal glyph for both states", () => {
assert.equal(CHAT_COMMAND_GLYPH, ">_"); assert.equal(CHAT_COMMAND_GLYPH, ">_");
}); });
// ---------------------------------------------------------------------------
// Local command notices (C12) — ChatStore.kt notice/dismissNotice/takeNoticeOffer
// and ChatCommandUi.kt's labels
// ---------------------------------------------------------------------------
test("chatNoticeLabel names a command and its failure", () => {
assert.equal(CHAT_COMMAND_LABEL, "Command");
assert.equal(CHAT_COMMAND_FAILED_LABEL, "Command failed");
assert.equal(chatNoticeLabel(false), "Command");
assert.equal(chatNoticeLabel(true), "Command failed");
// Anything that is not the literal failed flag keeps the ordinary label.
assert.equal(chatNoticeLabel(undefined), "Command");
assert.equal(chatNoticeLabel("failed"), "Command");
});
test("the offerless notice's dismiss control has an accessible name", () => {
assert.equal(CHAT_COMMAND_DISMISS_LABEL, "Dismiss command notice");
});
test("makeChatNotice keeps the id, text, failure flag and offer", () => {
assert.deepEqual(makeChatNotice("notice-1", "No turn is running in this chat."), {
id: "notice-1",
text: "No turn is running in this chat.",
failed: false,
offer: null,
});
assert.deepEqual(
makeChatNotice("notice-2", "Started a new session.", { failed: true, offer: "/nope" }),
{ id: "notice-2", text: "Started a new session.", failed: true, offer: "/nope" },
);
});
test("appendChatNotice appends one notice and preserves order", () => {
const first = makeChatNotice("notice-1", "Command one");
const second = makeChatNotice("notice-2", "Command two", { failed: true });
const afterFirst = appendChatNotice([], first);
const afterSecond = appendChatNotice(afterFirst, second);
assert.deepEqual(afterSecond, [first, second]);
// The previous list is never mutated.
assert.deepEqual(afterFirst, [first]);
assert.deepEqual(appendChatNotice(undefined, first), [first]);
});
test("dismissChatNotice removes exactly the named notice", () => {
const first = makeChatNotice("notice-1", "Command one");
const second = makeChatNotice("notice-2", "Command two", { failed: true });
const third = makeChatNotice("notice-3", "Command three");
assert.deepEqual(dismissChatNotice([first, second, third], "notice-2"), [first, third]);
// An unknown id leaves the list as it was.
assert.deepEqual(dismissChatNotice([first, third], "notice-9"), [first, third]);
assert.deepEqual(dismissChatNotice(undefined, "notice-1"), []);
});
test("takeChatNoticeOffer removes the notice and returns its draft", () => {
const offerless = makeChatNotice("notice-1", "Command one");
const offered = makeChatNotice("notice-2", "Not a command.", { failed: true, offer: "/nope" });
const taken = takeChatNoticeOffer([offerless, offered], "notice-2");
assert.equal(taken.offer, "/nope");
assert.deepEqual(taken.notices, [offerless]);
});
test("takeChatNoticeOffer returns null and leaves the list for a stale or offerless notice", () => {
const offerless = makeChatNotice("notice-1", "Command one");
const offered = makeChatNotice("notice-2", "Not a command.", { failed: true, offer: "/nope" });
for (const id of ["notice-1", "notice-9"]) {
const taken = takeChatNoticeOffer([offerless, offered], id);
assert.equal(taken.offer, null);
assert.deepEqual(taken.notices, [offerless, offered]);
}
// A second take of an already-taken id is stale and sends nothing.
const firstTake = takeChatNoticeOffer([offered], "notice-2");
const secondTake = takeChatNoticeOffer(firstTake.notices, "notice-2");
assert.equal(secondTake.offer, null);
assert.deepEqual(secondTake.notices, []);
});
test("notice lists are scoped per conversation and never share state", () => {
// Two conversations' notice lists are independent arrays: appending or
// dismissing in one cannot touch the other (the app keeps one per thread).
const operator = [];
const throwaway = [];
const operatorNotice = makeChatNotice("notice-1", "Operator command");
const throwawayNotice = makeChatNotice("notice-2", "Throwaway command", { failed: true });
const operatorAfter = appendChatNotice(operator, operatorNotice);
const throwawayAfter = appendChatNotice(throwaway, throwawayNotice);
assert.deepEqual(operatorAfter, [operatorNotice]);
assert.deepEqual(throwawayAfter, [throwawayNotice]);
assert.deepEqual(dismissChatNotice(operatorAfter, "notice-1"), []);
assert.deepEqual(throwawayAfter, [throwawayNotice]);
const taken = takeChatNoticeOffer(
appendChatNotice(throwawayAfter, makeChatNotice("notice-3", "Offer", { offer: "/help" })),
"notice-3",
);
assert.equal(taken.offer, "/help");
assert.deepEqual(operatorAfter, [operatorNotice]);
});
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Slash commands (C9) // Slash commands (C9)
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
+364 -50
View File
@@ -2,7 +2,9 @@
// Chrome, connect to a running Pipelines server through the page's own proxy, // Chrome, connect to a running Pipelines server through the page's own proxy,
// and capture what actually rendered. // and capture what actually rendered.
// //
// node test/ui-smoke.mjs [--port 8091] [--pipelines 127.0.0.1:8080] [--out DIR] [--scratch] // node test/ui-smoke.mjs [--port PORT] [--pipelines 127.0.0.1:8080] [--out DIR] [--scratch]
//
// Without --port the OS picks a free port, so concurrent checks do not collide.
// //
// This is the UI evidence a review stage produces: real screenshots of the // This is the UI evidence a review stage produces: real screenshots of the
// rendered client, not a claim. It needs a running Pipelines server (the live one // rendered client, not a claim. It needs a running Pipelines server (the live one
@@ -51,7 +53,12 @@ function flag(argv, name, fallback) {
return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback; return i !== -1 && argv[i + 1] ? argv[i + 1] : fallback;
} }
const port = Number(flag(process.argv, "--port", process.env.WEB_UI_PORT ?? 8091)); // No fixed default port: an explicit --port/WEB_UI_PORT still wins, but otherwise
// each run asks the OS for a free one. Concurrent checks (parallel pipeline items)
// therefore never collide on 8091 — the earlier fixed default made a second
// simultaneous UI stage fail with EADDRINUSE.
const explicitPort = flag(process.argv, "--port", process.env.WEB_UI_PORT);
const port = explicitPort ? Number(explicitPort) : await freePort();
const pipelines = flag(process.argv, "--pipelines", process.env.PIPELINES_TARGET ?? "127.0.0.1:8080"); const pipelines = flag(process.argv, "--pipelines", process.env.PIPELINES_TARGET ?? "127.0.0.1:8080");
const out = resolve( const out = resolve(
flag(process.argv, "--out", process.env.WEB_UI_OUT ?? join(tmpdir(), "pipelines-web-ui")), flag(process.argv, "--out", process.env.WEB_UI_OUT ?? join(tmpdir(), "pipelines-web-ui")),
@@ -102,6 +109,19 @@ const showComposer = () =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve(true))); requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
})`); })`);
// Show the foot of an open conversation without scrolling the whole document.
// The session list can be taller than the chat pane (the smoke leaves closed
// throwaway rows behind), so scrolling to the document bottom would push the
// conversation above the viewport and capture an empty pane. The transcript is
// the only scroller that needs to move for a command-notice capture.
const showChatNotice = () =>
page.evaluate(`new Promise((resolve) => {
window.scrollTo(0, 0);
const transcript = document.querySelector("#chatTranscript");
if (transcript) transcript.scrollTop = transcript.scrollHeight;
requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
})`);
// The shared live server can drop a long-lived socket while the earlier screens // The shared live server can drop a long-lived socket while the earlier screens
// are captured (observed as a spurious 1006 mid-run). A capture step must not // are captured (observed as a spurious 1006 mid-run). A capture step must not
// depend on an unasserted connection, so this nudges the page's own recovery — // depend on an unasserted connection, so this nudges the page's own recovery —
@@ -432,6 +452,14 @@ try {
} }
if (frame) { if (frame) {
(window.__pipelinesSentTypes = window.__pipelinesSentTypes || []).push(frame.type); (window.__pipelinesSentTypes = window.__pipelinesSentTypes || []).push(frame.type);
// C12: the prompt bodies this page actually sent, so the smoke can prove
// the help command and an unknown command generate none, and that the
// offer path sends exactly the draft it offered.
if (frame.type === "chat_prompt") {
(window.__chatPromptTexts = window.__chatPromptTexts || []).push(
frame.chat_prompt?.text ?? "",
);
}
if (frame.type === "chat_reply") { if (frame.type === "chat_reply") {
const requestId = frame.chat_reply && frame.chat_reply.request_id; const requestId = frame.chat_reply && frame.chat_reply.request_id;
if (window.__suppressChatReplyIds.includes(requestId)) { if (window.__suppressChatReplyIds.includes(requestId)) {
@@ -1461,6 +1489,9 @@ try {
await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 }); await page.waitForSelector(".detail .detail-tabs", { timeout: 25000 });
await page.clickText(".detail .detail-tabs .detail-tab", "Graph"); await page.clickText(".detail .detail-tabs .detail-tab", "Graph");
await page.waitForSelector(".run-detail .graph-node", { timeout: 15000 }); await page.waitForSelector(".run-detail .graph-node", { timeout: 15000 });
// The run can stop (or be reported `running` with no stage in flight) between
// the list read and this graph, so treat the halo as the best effort its
// comment promises rather than failing the whole run on a race.
const live = await eventually( const live = await eventually(
async () => async () =>
page.evaluate(`(() => { page.evaluate(`(() => {
@@ -1473,11 +1504,15 @@ try {
}; };
})()`), })()`),
{ timeout: 15000, what: "the live run's active stage" }, { timeout: 15000, what: "the live run's active stage" },
); ).catch(() => null);
if (!live.badge) throw new Error(`the active stage showed no elapsed badge: ${JSON.stringify(live)}`); if (!live) {
console.log(` live run ${liveRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`); console.log(` -- run ${liveRunId} shows no stage in flight; skipped the live graph halo capture`);
await page.rect(".run-detail .graph-viewport"); } else {
shots.push(await page.screenshot(`${out}/31-run-live-graph.png`)); if (!live.badge) throw new Error(`the active stage showed no elapsed badge: ${JSON.stringify(live)}`);
console.log(` live run ${liveRunId}: active stage ${live.activeKey} (pulsing=${live.pulsing}), badge ${live.badge}`);
await page.rect(".run-detail .graph-viewport");
shots.push(await page.screenshot(`${out}/31-run-live-graph.png`));
}
} }
// The Output empty state, on the running run that has not produced output yet. // The Output empty state, on the running run that has not produced output yet.
@@ -3022,36 +3057,7 @@ try {
await ensureConnected(); await ensureConnected();
await page.waitForSelector("#chatInput", { timeout: 15000 }); await page.waitForSelector("#chatInput", { timeout: 15000 });
// (a) `/new` creates a fresh throwaway session (C2's chat_create, sent directly // (a) A draft: the placeholder, Send present and enabled, Stop absent.
// until C2 lands) and opens it. Every composer state below is exercised on this
// idle session rather than the operator's own, whose live turn may be running
// (the list's activity word is honest about it but must not fail this stage).
await page.fill("#chatInput", "/new");
await page.evaluate(
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
);
const throwawayId = await eventually(
async () => {
const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`);
return id && id !== openedId ? id : false;
},
{ timeout: 25000, what: "the new throwaway session to open" },
);
await page.waitForSelector("#chatInput", { timeout: 10000 });
const throwawayTitle = await page.evaluate(`document.querySelector(".chat-bar-title")?.textContent ?? ""`);
if (throwawayTitle !== "New chat") throw new Error(`new session title: ${throwawayTitle}`);
throwawaySessionId = throwawayId;
const startedNotice = await page.evaluate(
`document.querySelector(".chat-command-notice .chat-command-notice-text")?.textContent ?? ""`,
);
if (!startedNotice.startsWith("Started a new session “")) {
throw new Error(`/new notice: ${startedNotice}`);
}
console.log(` /new opened throwaway session ${throwawayId} ("${throwawayTitle}") — ${startedNotice}`);
await showComposer();
await shot("62-chat-new-session.png");
// (b) A draft: the placeholder, Send present and enabled, Stop absent.
await page.fill("#chatInput", "A draft from the smoke"); await page.fill("#chatInput", "A draft from the smoke");
const draftState = await page.evaluate(`(() => ({ const draftState = await page.evaluate(`(() => ({
placeholder: document.querySelector("#chatInput")?.getAttribute("placeholder") ?? "", placeholder: document.querySelector("#chatInput")?.getAttribute("placeholder") ?? "",
@@ -3128,27 +3134,116 @@ try {
throw new Error(`prefix filter: ${JSON.stringify(narrowedCommands)}`); throw new Error(`prefix filter: ${JSON.stringify(narrowedCommands)}`);
} }
// (c) An unknown command: its notice with the exact wording and the offer, then // (c) C12: local command notices on this (read-only) conversation. A `/help`
// Cancel. The composer is driven without submitting, so no prompt is sent. // success line and an unknown command's failed line render full width after the
await page.fill("#chatInput", "/nope"); // turns, never as message bubbles; both are local, so the recorded send
await page.evaluate( // assertions below must show no chat_prompt for either. The failed one keeps
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, // Android's `Send as message` / `Cancel` pair; an offerless line is dismissible
// by its own `Dismiss` control (the browser completion recorded in PARITY).
await page.evaluate(`(() => {
window.__pipelinesSentTypes = [];
window.__chatPromptTexts = [];
return true;
})()`);
const runSlashDraft = async (text) => {
await page.fill("#chatInput", text);
await page.evaluate(
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
);
};
await runSlashDraft("/help");
const helpNotice = await eventually(
() =>
page.evaluate(`(() => {
const node = [...document.querySelectorAll("#chatTranscript .chat-command-notice:not(.chat-command-notice-failed)")]
.find((n) => (n.querySelector(".chat-command-notice-text")?.textContent ?? "").includes("/help — List every command"));
if (!node) return null;
node.scrollIntoView({ block: "center" });
const transcript = document.querySelector("#chatTranscript");
const children = [...transcript.children];
const index = children.indexOf(node);
const lastTurn = children.reduce(
(last, child, i) => (child.matches(".chat-turn-user, .chat-turn-agent") ? i : last),
-1,
);
return {
id: node.dataset.noticeId ?? "",
label: node.querySelector(".chat-command-notice-label")?.textContent ?? "",
glyph: node.querySelector(".chat-command-notice-glyph")?.textContent ?? "",
text: node.querySelector(".chat-command-notice-text")?.textContent ?? "",
buttons: [...node.querySelectorAll(".chat-command-notice-actions button")].map((b) => b.textContent),
dismissLabel: node.querySelector(".chat-command-dismiss")?.getAttribute("aria-label") ?? "",
bubble:
node.classList.contains("chat-turn-user") ||
node.classList.contains("chat-turn-agent") ||
!!node.closest(".chat-bubble"),
width: Math.round(node.getBoundingClientRect().width),
contentWidth: Math.round(transcript.clientWidth - 24),
afterTurns: index > lastTurn,
turns: children.filter((child) => child.matches(".chat-turn-user, .chat-turn-agent")).length,
};
})()`),
{ timeout: 10000, what: "the /help command notice" },
); );
if (helpNotice.label !== "Command") throw new Error(`/help notice label: ${helpNotice.label}`);
if (helpNotice.glyph !== ">_") throw new Error(`/help notice glyph: ${helpNotice.glyph}`);
if (!helpNotice.text.startsWith("/new — Start a fresh session in this directory")) {
throw new Error(`/help notice text: ${helpNotice.text}`);
}
if (!helpNotice.text.includes("/help — List every command")) {
throw new Error(`/help notice is missing its last command line: ${helpNotice.text}`);
}
if (helpNotice.buttons.join("|") !== "Dismiss") {
throw new Error(`offerless notice controls: ${JSON.stringify(helpNotice.buttons)}`);
}
if (helpNotice.dismissLabel !== "Dismiss command notice") {
throw new Error(`dismiss accessible name: ${helpNotice.dismissLabel}`);
}
if (helpNotice.bubble || !helpNotice.afterTurns || helpNotice.turns < 1) {
throw new Error(
`the /help line is not a full-width transcript line after the turns: ${JSON.stringify(helpNotice)}`,
);
}
if (helpNotice.width < helpNotice.contentWidth - 3) {
throw new Error(
`the /help line is not full width: ${helpNotice.width}px of ${helpNotice.contentWidth}px`,
);
}
const promptless = await page.evaluate(
`({ types: window.__pipelinesSentTypes || [], texts: window.__chatPromptTexts || [] })`,
);
if (promptless.types.includes("chat_prompt") || promptless.texts.length !== 0) {
throw new Error(`/help reached the prompt path: ${JSON.stringify(promptless)}`);
}
console.log(
` /help: "${helpNotice.label}" line (${helpNotice.width}px of ${helpNotice.contentWidth}px, ` +
`${helpNotice.turns} turn(s) above it), no bubble; only a Dismiss control; no chat_prompt sent`,
);
await showChatNotice();
await shot("72-chat-command-notice.png");
// The unknown command's failed line: the app's wording, the shared terminal
// glyph and the error tint, with the offer's exact control pair.
await runSlashDraft("/nope");
await page.waitForSelector(".chat-command-notice-failed", { timeout: 10000 }); await page.waitForSelector(".chat-command-notice-failed", { timeout: 10000 });
const notice = await page.evaluate(`(() => { const notice = await page.evaluate(`(() => {
const node = document.querySelector(".chat-command-notice-failed"); const node = document.querySelector(".chat-command-notice-failed");
node.scrollIntoView({ block: "center" }); node.scrollIntoView({ block: "center" });
return { return {
id: node.dataset.noticeId ?? "",
label: node.querySelector(".chat-command-notice-label")?.textContent ?? "", label: node.querySelector(".chat-command-notice-label")?.textContent ?? "",
glyph: node.querySelector(".chat-command-notice-glyph")?.textContent ?? "", glyph: node.querySelector(".chat-command-notice-glyph")?.textContent ?? "",
text: node.querySelector(".chat-command-notice-text")?.textContent ?? "", text: node.querySelector(".chat-command-notice-text")?.textContent ?? "",
buttons: [...node.querySelectorAll(".chat-command-notice-actions button")].map((b) => b.textContent), buttons: [...node.querySelectorAll(".chat-command-notice-actions button")].map((b) => b.textContent),
failed: node.classList.contains("chat-command-notice-failed"),
draft: document.querySelector("#chatInput")?.value ?? null, draft: document.querySelector("#chatInput")?.value ?? null,
send: !!document.querySelector("#chatSend"), send: !!document.querySelector("#chatSend"),
stop: !!document.querySelector("#chatStop"), stop: !!document.querySelector("#chatStop"),
}; };
})()`); })()`);
if (notice.label !== "Command failed") throw new Error(`notice label: ${notice.label}`); if (notice.label !== "Command failed") throw new Error(`notice label: ${notice.label}`);
if (notice.glyph !== ">_") throw new Error(`failed notice glyph: ${notice.glyph}`);
if ( if (
notice.text !== notice.text !==
"“/nope” is not a command, so nothing was sent to the agent. Send it as a message, or cancel." "“/nope” is not a command, so nothing was sent to the agent. Send it as a message, or cancel."
@@ -3158,14 +3253,79 @@ try {
if (notice.buttons.join("|") !== "Send as message|Cancel") { if (notice.buttons.join("|") !== "Send as message|Cancel") {
throw new Error(`unknown-command offer buttons: ${JSON.stringify(notice.buttons)}`); throw new Error(`unknown-command offer buttons: ${JSON.stringify(notice.buttons)}`);
} }
if (!notice.failed) throw new Error("the failed notice does not carry the error styling class");
if (notice.draft !== "") throw new Error(`the command did not consume the draft: ${JSON.stringify(notice.draft)}`); if (notice.draft !== "") throw new Error(`the command did not consume the draft: ${JSON.stringify(notice.draft)}`);
const tint = await page.evaluate(`(() => {
const failedNode = document.querySelector('.chat-command-notice-failed[data-notice-id="${notice.id}"]');
const okNode = document.querySelector('.chat-command-notice[data-notice-id="${helpNotice.id}"]');
return {
failedBorder: failedNode ? getComputedStyle(failedNode).borderColor : "",
okBorder: okNode ? getComputedStyle(okNode).borderColor : "",
};
})()`);
if (!tint.failedBorder || tint.failedBorder === tint.okBorder) {
throw new Error(`the failed notice is not tinted differently from a command line: ${JSON.stringify(tint)}`);
}
const stillPromptless = await page.evaluate(`window.__chatPromptTexts || []`);
if (stillPromptless.length !== 0) {
throw new Error(`an unknown command reached the prompt path: ${JSON.stringify(stillPromptless)}`);
}
console.log(` unknown command: "${notice.text}" (offer: ${notice.buttons.join(" / ")})`); console.log(` unknown command: "${notice.text}" (offer: ${notice.buttons.join(" / ")})`);
console.log(
` both command lines stayed local: no chat_prompt was sent (recorded types: ${JSON.stringify(
(await page.evaluate(`window.__pipelinesSentTypes || []`)).filter((type) => type.startsWith("chat_")),
)})`,
);
await showChatNotice();
await shot("59-chat-command-unknown.png"); await shot("59-chat-command-unknown.png");
await page.clickText(".chat-command-notice-failed button", "Cancel"); await showChatNotice();
await eventually(() => page.evaluate(`!document.querySelector(".chat-command-notice-failed")`), { await shot("73-chat-command-failed-offer.png");
timeout: 5000,
what: "the unknown-command notice to be dismissed", // Dismissal removes exactly the named notice: the offerless `/help` line goes,
}); // the failed offer notice stays with its draft and controls.
const dismissed = await page.evaluate(`(() => {
const help = document.querySelector('.chat-command-notice[data-notice-id="${helpNotice.id}"]');
const idsBefore = [...document.querySelectorAll("#chatTranscript .chat-command-notice")].map(
(node) => node.dataset.noticeId,
);
help?.querySelector(".chat-command-dismiss")?.click();
return { idsBefore, clicked: !!help };
})()`);
if (!dismissed.clicked || !dismissed.idsBefore.includes(helpNotice.id)) {
throw new Error(`the /help notice was not dismissed: ${JSON.stringify(dismissed)}`);
}
await eventually(
() =>
page.evaluate(
`!document.querySelector('.chat-command-notice[data-notice-id="${helpNotice.id}"]')`,
),
{ timeout: 5000, what: "the dismissed /help notice to be gone" },
);
const noticeRemoval = await page.evaluate(`(() => ({
ids: [...document.querySelectorAll("#chatTranscript .chat-command-notice")].map((node) => node.dataset.noticeId),
failed: document.querySelector('.chat-command-notice-failed[data-notice-id="${notice.id}"] .chat-command-notice-text')?.textContent ?? "",
buttons: [...document.querySelectorAll('.chat-command-notice-failed[data-notice-id="${notice.id}"] .chat-command-notice-actions button')].map((b) => b.textContent),
}))()`);
if (
noticeRemoval.ids.includes(helpNotice.id) ||
!noticeRemoval.ids.includes(notice.id) ||
noticeRemoval.ids.length !== dismissed.idsBefore.length - 1 ||
noticeRemoval.failed !== notice.text ||
noticeRemoval.buttons.join("|") !== "Send as message|Cancel"
) {
throw new Error(`dismissing one notice changed the wrong ones: ${JSON.stringify({ dismissed, noticeRemoval })}`);
}
console.log(
` dismissed only ${helpNotice.id} (${dismissed.idsBefore.length} -> ${noticeRemoval.ids.length} notices; ` +
`${notice.id} and its offer remain)`,
);
await showChatNotice();
await shot("74-chat-command-dismissed.png");
await page.clickText(`.chat-command-notice-failed[data-notice-id="${notice.id}"] button`, "Cancel");
await eventually(
() => page.evaluate(`!document.querySelector('.chat-command-notice[data-notice-id="${notice.id}"]')`),
{ timeout: 5000, what: "the unknown-command notice to be dismissed" },
);
// (d) Attachment chips: a small file with its size, and a file over the 25 MiB // (d) Attachment chips: a small file with its size, and a file over the 25 MiB
// limit with its error. Driving the real file input (a DataTransfer) exercises // limit with its error. Driving the real file input (a DataTransfer) exercises
@@ -3248,9 +3408,163 @@ try {
}); });
await page.fill("#chatInput", ""); await page.fill("#chatInput", "");
// (f) The throwaway created at the start is still open and idle (the palette, // (e) `/new` creates a fresh throwaway session (C2's chat_create, sent directly
// notice and attachment probes above never submitted anything). Prompt it for // until C2 lands) and opens it. The operator's session is left untouched. The
// the real running-turn state; the operator's session is left untouched. // throwaway must stay a listed server session: C12's notice check switches away
// to another row and back to it, and C13 reads its row for the device-local
// rename; an ephemeral create (2fe6301's `__pipelinesEphemeralChat`) is hidden
// from `chat_sessions`, so it is deliberately NOT used here. The session is
// closed again in cleanup, like the New-marker throwaway C13 creates itself.
await page.fill("#chatInput", "/new");
await page.evaluate(
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
);
const throwawayId = await eventually(
async () => {
const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`);
return id && id !== openedId ? id : false;
},
{ timeout: 25000, what: "the new throwaway session to open" },
);
await page.waitForSelector("#chatInput", { timeout: 10000 });
const throwawayTitle = await page.evaluate(`document.querySelector(".chat-bar-title")?.textContent ?? ""`);
if (throwawayTitle !== "New chat") throw new Error(`new session title: ${throwawayTitle}`);
throwawaySessionId = throwawayId;
const startedNotice = await page.evaluate(
`document.querySelector(".chat-command-notice .chat-command-notice-text")?.textContent ?? ""`,
);
if (!startedNotice.startsWith("Started a new session “")) {
throw new Error(`/new notice: ${startedNotice}`);
}
console.log(` /new opened throwaway session ${throwawayId} ("${throwawayTitle}") — ${startedNotice}`);
await showComposer();
await shot("62-chat-new-session.png");
// C12: notices belong to one conversation and survive switching away and back.
// The offer notice is added on this throwaway session (never the operator's),
// then the pane switches to the operator session and back. Finally the offer is
// taken: the notice is gone before the prompt is sent, a stale second tap sends
// nothing, and the draft goes through the ordinary chat_prompt path. The shim
// answers that one prompt locally so this step does not add a live turn; the
// real prompt below still exercises the live turn and Stop.
await page.evaluate(`(() => {
window.__pipelinesSentTypes = [];
window.__chatPromptTexts = [];
return true;
})()`);
await page.fill("#chatInput", "/nope");
await page.evaluate(
`document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`,
);
const offerNotice = await eventually(
() =>
page.evaluate(`(() => {
const node = document.querySelector('#chatTranscript[data-session="${throwawayId}"] .chat-command-notice-failed');
if (!node) return null;
return {
id: node.dataset.noticeId ?? "",
text: node.querySelector(".chat-command-notice-text")?.textContent ?? "",
buttons: [...node.querySelectorAll(".chat-command-notice-actions button")].map((b) => b.textContent),
};
})()`),
{ timeout: 10000, what: "the throwaway command notice" },
);
if (offerNotice.buttons.join("|") !== "Send as message|Cancel") {
throw new Error(`throwaway notice controls: ${JSON.stringify(offerNotice.buttons)}`);
}
const throwawayPromptless = await page.evaluate(`window.__chatPromptTexts || []`);
if (throwawayPromptless.length !== 0) {
throw new Error(`the unknown command on the throwaway reached the prompt path: ${JSON.stringify(throwawayPromptless)}`);
}
await page.evaluate(`document.querySelector('#chatRows .chat-row[data-session="${openedId}"]')?.click()`);
await page.waitForSelector(`#chatTranscript[data-session="${openedId}"]`, { timeout: 25000 });
const leaked = await page.evaluate(
`!!document.querySelector('.chat-command-notice[data-notice-id="${offerNotice.id}"]')`,
);
if (leaked) throw new Error("the throwaway's notice leaked into the operator's conversation");
await page.evaluate(`document.querySelector('#chatRows .chat-row[data-session="${throwawayId}"]')?.click()`);
await page.waitForSelector(`#chatTranscript[data-session="${throwawayId}"]`, { timeout: 25000 });
const survived = await eventually(
() =>
page.evaluate(`(() => {
const node = document.querySelector('#chatTranscript[data-session="${throwawayId}"] .chat-command-notice[data-notice-id="${offerNotice.id}"]');
if (!node) return null;
return {
text: node.querySelector(".chat-command-notice-text")?.textContent ?? "",
buttons: [...node.querySelectorAll(".chat-command-notice-actions button")].map((b) => b.textContent),
};
})()`),
{ timeout: 15000, what: "the throwaway notice after switching away and back" },
);
if (survived.text !== offerNotice.text || survived.buttons.join("|") !== "Send as message|Cancel") {
throw new Error(`the notice did not survive the switch: ${JSON.stringify({ offerNotice, survived })}`);
}
console.log(
` the notice survived a switch away and back on ${throwawayId} (absent from the operator's conversation)`,
);
const offerClicked = await page.evaluate(`(() => {
const node = document.querySelector('#chatTranscript[data-session="${throwawayId}"] .chat-command-notice[data-notice-id="${offerNotice.id}"]');
const button = node?.querySelector(".chat-command-send-as-message") ?? null;
window.__staleOfferButton = button;
window.__promptCountBeforeOffer = (window.__pipelinesSentTypes || []).length;
window.__pipelinesIntercept = (frame) =>
frame.type === "chat_prompt" ? { id: frame.id, type: "chat_prompt", chat_queued: false } : null;
button?.click();
return !!button;
})()`);
if (!offerClicked) throw new Error("the throwaway notice has no Send as message control");
await eventually(
() =>
page.evaluate(
`!document.querySelector('#chatTranscript[data-session="${throwawayId}"] .chat-command-notice[data-notice-id="${offerNotice.id}"]')`,
),
{ timeout: 10000, what: "the taken offer notice to be removed" },
);
const offeredSend = await page.evaluate(`(() => {
const types = (window.__pipelinesSentTypes || []).slice(window.__promptCountBeforeOffer);
return { chatPrompts: types.filter((type) => type === "chat_prompt").length, texts: window.__chatPromptTexts || [] };
})()`);
if (offeredSend.chatPrompts !== 1 || offeredSend.texts.length !== 1 || offeredSend.texts[0] !== "/nope") {
throw new Error(`the offer did not take the ordinary prompt path: ${JSON.stringify(offeredSend)}`);
}
const staleTap = await page.evaluate(`(() => {
const before = (window.__pipelinesSentTypes || []).length;
window.__staleOfferButton?.click();
return {
before,
after: (window.__pipelinesSentTypes || []).length,
texts: (window.__chatPromptTexts || []).length,
};
})()`);
if (staleTap.after !== staleTap.before || staleTap.texts !== 1) {
throw new Error(`a stale Send as message tap sent something: ${JSON.stringify(staleTap)}`);
}
console.log(
" Send as message removed the notice first, then sent /nope once through chat_prompt; " +
"a stale second tap sent nothing",
);
// Settle the (locally answered) prompt so the real turn below starts from Send,
// and drop the one-shot prompt interceptor.
const settledOffer = await page.evaluate(`(() => {
const ws = window.__pipelinesSocket;
if (!ws || typeof ws.onmessage !== "function") return false;
ws.onmessage({
data: JSON.stringify({
type: "chat_event",
chat_event: { session_id: "${throwawayId}", kind: "step", step: { status: "ended" } },
}),
});
return true;
})()`);
if (!settledOffer) throw new Error("the socket shim did not expose the live socket to settle the offered prompt");
await eventually(() => page.evaluate(`!document.querySelector("#chatStop")`), {
timeout: 10000,
what: "the offered prompt's running state to settle",
});
await page.evaluate(`(() => { window.__pipelinesIntercept = null; return true; })()`);
// A real prompt to the throwaway session turns the Send control into Stop. // A real prompt to the throwaway session turns the Send control into Stop.
await page.fill("#chatInput", "Reply with exactly one word: hi"); await page.fill("#chatInput", "Reply with exactly one word: hi");
await page.evaluate( await page.evaluate(