From 9231236f838b12b77ba3202454123faf20616312 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 11:58:55 +0100 Subject: [PATCH 1/4] web: local command notices in chat, individually dismissible (C12) --- web/PARITY.md | 2 +- web/src/app.js | 42 ++++-- web/src/chat.js | 60 +++++++- web/test/chat.test.mjs | 105 ++++++++++++++ web/test/ui-smoke.mjs | 320 +++++++++++++++++++++++++++++++++++++++-- 5 files changed, 508 insertions(+), 21 deletions(-) diff --git a/web/PARITY.md b/web/PARITY.md index 67d64de9..173385b7 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -99,7 +99,7 @@ the pipeline list already carries — rather than a pluralised verb. | 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 `, `/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` is the local rename pending C13, `/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` | | C11 | Background tasks bar: running shells only, capped + scrollable, bounded output page | `chat_shells`, `chat_shell_output` | todo | -| 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 | todo | | 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 | diff --git a/web/src/app.js b/web/src/app.js index 29d088f6..96682034 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -229,6 +229,7 @@ import { import { BACKGROUND_TASKS_TITLE, CHAT_ATTACH_LABEL, + CHAT_COMMAND_DISMISS_LABEL, CHAT_COMMAND_GLYPH, CHAT_COMPOSER_PLACEHOLDER, CHAT_EMPTY, @@ -272,6 +273,7 @@ import { SHELL_ROW_LABEL, applyChatEvent, applyChatPermission, + appendChatNotice, approvalCard, attachmentDisplayName, attachmentError, @@ -285,6 +287,7 @@ import { chatFollowsAt, chatHeaderMeta, chatNoMatchMessage, + chatNoticeLabel, chatOpensAtNewest, chatShowJumpToLatest, chatStreamState, @@ -294,9 +297,11 @@ import { composerSendEnabled, composerSubmit, directoryLabel, + dismissChatNotice as dismissChatNoticeModel, filterSessions, groupSessionsByDirectory, historyResync, + makeChatNotice, mergeHistoryPage, mergeShellFrame, newChatThread, @@ -318,6 +323,7 @@ import { shellCommandSummary, shellOutputState, shellsLoaded, + takeChatNoticeOffer as takeChatNoticeOfferModel, formatToolDuration, threadElapsedMillis, threadPhase, @@ -4408,15 +4414,15 @@ function addChatNotice(sessionId, text, { failed = false, offer = null } = {}) { const thread = state.chatThreads.get(sessionId); if (!thread) return; chatNoticeSeq += 1; - const notice = { id: `notice-${chatNoticeSeq}`, text, failed, offer }; - setThread(sessionId, { notices: [...(thread.notices ?? []), notice] }); + const notice = makeChatNotice(`notice-${chatNoticeSeq}`, text, { failed, offer }); + 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) { const thread = state.chatThreads.get(sessionId); if (!thread) return; - setThread(sessionId, { notices: (thread.notices ?? []).filter((n) => n.id !== noticeId) }); + setThread(sessionId, { notices: dismissChatNoticeModel(thread.notices, noticeId) }); renderContent(); } @@ -4426,10 +4432,11 @@ function dismissChatNotice(sessionId, noticeId) { */ function takeChatNoticeOffer(sessionId, noticeId) { const thread = state.chatThreads.get(sessionId); - const notice = (thread?.notices ?? []).find((n) => n.id === noticeId); - if (!notice || notice.offer == null) return null; - setThread(sessionId, { notices: (thread.notices ?? []).filter((n) => n.id !== noticeId) }); - return notice.offer; + if (!thread) return null; + const taken = takeChatNoticeOfferModel(thread.notices, noticeId); + if (taken.offer == null) return null; + setThread(sessionId, { notices: taken.notices }); + return taken.offer; } /** @@ -5770,6 +5777,7 @@ function renderChatCommandNotice(sessionId, notice) { const row = h("div", { class: `chat-command-notice${failed ? " chat-command-notice-failed" : ""}`, role: "note", + "data-notice-id": notice?.id ?? "", }); const head = h("div", { class: "chat-command-notice-head" }); head.append( @@ -5782,7 +5790,7 @@ function renderChatCommandNotice(sessionId, notice) { }), ); 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(h("div", { class: "chat-command-notice-text", text: notice?.text ?? "" })); @@ -5805,6 +5813,22 @@ function renderChatCommandNotice(sessionId, notice) { }), ); 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; } diff --git a/web/src/chat.js b/web/src/chat.js index 37b626ea..c42453a9 100644 --- a/web/src/chat.js +++ b/web/src/chat.js @@ -20,7 +20,11 @@ // chatShowJumpToLatest, chatOpensAtNewest, // chatFirstScroll // 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, // the submit routing (command vs prompt) // ui/chat/ChatCommands.kt CHAT_COMMANDS, parseChatInput, chatCommandSuggestions, @@ -1362,6 +1366,60 @@ export const CHAT_QUEUED_NOTICE = "Queued — it will send when the current turn */ 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]. */ export const COMPOSER_SEND = "send"; export const COMPOSER_STOP = "stop"; diff --git a/web/test/chat.test.mjs b/web/test/chat.test.mjs index fc252ab3..b87ee274 100644 --- a/web/test/chat.test.mjs +++ b/web/test/chat.test.mjs @@ -8,7 +8,10 @@ import { BACKGROUND_TASKS_TITLE, BACKGROUND_TASK_VISIBLE_ROWS, CHAT_COMMANDS, + CHAT_COMMAND_DISMISS_LABEL, + CHAT_COMMAND_FAILED_LABEL, CHAT_COMMAND_GLYPH, + CHAT_COMMAND_LABEL, CHAT_FOLLOW_THRESHOLD_PX, CHAT_QUEUED_NOTICE, COMPOSER_SEND, @@ -48,6 +51,7 @@ import { TURN_PHASE_TOOL, TURN_PHASE_WAITING, TURN_THINKING_WINDOW_MILLIS, + appendChatNotice, applyChatEvent, applyChatPermission, approvalCard, @@ -66,6 +70,7 @@ import { chatFollowsAt, chatHeaderMeta, chatNoMatchMessage, + chatNoticeLabel, chatOpensAtNewest, chatShowJumpToLatest, chatStreamState, @@ -77,11 +82,13 @@ import { decisionLabel, deltaPartId, directoryLabel, + dismissChatNotice, filterSessions, formatToolDuration, groupSessionsByDirectory, historyResync, lineDiff, + makeChatNotice, mergeHistoryPage, mergeShellFrame, mergeToolPart, @@ -109,6 +116,7 @@ import { shellCommandSummary, shellOutputState, shellsLoaded, + takeChatNoticeOffer, threadElapsedMillis, threadPhase, threadRunningTools, @@ -833,6 +841,103 @@ test("a command notice carries one terminal glyph for both states", () => { 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) // --------------------------------------------------------------------------- diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index f63d79c8..68eee472 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -102,6 +102,19 @@ const showComposer = () => 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 // 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 — @@ -422,6 +435,14 @@ try { } if (frame) { (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") { const requestId = frame.chat_reply && frame.chat_reply.request_id; if (window.__suppressChatReplyIds.includes(requestId)) { @@ -3075,27 +3096,116 @@ try { throw new Error(`prefix filter: ${JSON.stringify(narrowedCommands)}`); } - // (c) An unknown command: its notice with the exact wording and the offer, then - // Cancel. The composer is driven without submitting, so no prompt is sent. - await page.fill("#chatInput", "/nope"); - await page.evaluate( - `document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, + // (c) C12: local command notices on this (read-only) conversation. A `/help` + // success line and an unknown command's failed line render full width after the + // turns, never as message bubbles; both are local, so the recorded send + // assertions below must show no chat_prompt for either. The failed one keeps + // 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 }); const notice = await page.evaluate(`(() => { const node = document.querySelector(".chat-command-notice-failed"); node.scrollIntoView({ block: "center" }); 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), + failed: node.classList.contains("chat-command-notice-failed"), draft: document.querySelector("#chatInput")?.value ?? null, send: !!document.querySelector("#chatSend"), stop: !!document.querySelector("#chatStop"), }; })()`); if (notice.label !== "Command failed") throw new Error(`notice label: ${notice.label}`); + if (notice.glyph !== ">_") throw new Error(`failed notice glyph: ${notice.glyph}`); if ( notice.text !== "“/nope” is not a command, so nothing was sent to the agent. Send it as a message, or cancel." @@ -3105,14 +3215,79 @@ try { if (notice.buttons.join("|") !== "Send as message|Cancel") { 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)}`); + 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( + ` 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 page.clickText(".chat-command-notice-failed button", "Cancel"); - await eventually(() => page.evaluate(`!document.querySelector(".chat-command-notice-failed")`), { - timeout: 5000, - what: "the unknown-command notice to be dismissed", - }); + await showChatNotice(); + await shot("73-chat-command-failed-offer.png"); + + // 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 // limit with its error. Driving the real file input (a DataTransfer) exercises @@ -3222,6 +3397,131 @@ try { 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. await page.fill("#chatInput", "Reply with exactly one word: hi"); await page.evaluate( From 94c802a14730d2758645b033d07c9d05f8e752ac Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 12:57:52 +0100 Subject: [PATCH 2/4] web/PARITY: restore C11's done row lost in a later merge --- web/PARITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/PARITY.md b/web/PARITY.md index 173385b7..aafa0796 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -98,7 +98,7 @@ 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 | | 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` is the local rename pending C13, `/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` | -| 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` | 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 | todo | | 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 | From 2fe63012f9ae1acb46384dc0d11dfe63658432e0 Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 13:15:08 +0100 Subject: [PATCH 3/4] chat: a verification chat can never appear in the operator's list The operator's chat list showed ~99 stray "New chat" entries. The listing was already fail-closed (registry-only); the fault was what got recorded: an automated UI check drives the real page, so its throwaway chat was recorded as an operator chat exactly like a manually created one and stayed in the list for ever (each run added one). Server: chat_create takes an optional ephemeral flag. The session is created, bootstrapped, usable, closable and reopenable exactly like any other, but its registry row is hidden, so chat_sessions never lists it. operator_sessions gains an ephemeral column (idempotent migration, existing rows default to listed) and the list query filters it; the single-row lookup does not, so close/reopen keep working. RecordVerificationSession is the hidden recorder. Web: the page marks a create ephemeral only when automation asks for it (__pipelinesEphemeralChat, set by the UI smoke for its throwaway chat), so the smoke's own runs stop polluting while a manual create is unchanged. Tests: a hidden row is never listed yet is still looked up and closable; a normal re-record of the same id lists it again; a pre-ephemeral database migrates with every existing chat still listed. Live data pruned separately (107 -> 8 registry rows, backed up). --- docs/cli.md | 6 ++ internal/pipeline/operator_sessions.go | 47 ++++++++--- internal/pipeline/operator_sessions_test.go | 88 +++++++++++++++++++++ internal/protocol/chat.go | 8 ++ internal/server/chat.go | 3 + internal/server/chat_sessions.go | 23 +++++- internal/server/chat_test.go | 54 +++++++++++++ web/src/app.js | 7 +- web/src/repository.js | 9 ++- web/test/ui-smoke.mjs | 6 +- 10 files changed, 233 insertions(+), 18 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index b1e9c2ac..3b2c2563 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -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 rejected before any OpenCode call. The created session is recorded with the 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 previous operator sessions most-recently-used first, deduplicated and bounded (currently 8). It is a dedicated request so the create dialog can load the diff --git a/internal/pipeline/operator_sessions.go b/internal/pipeline/operator_sessions.go index 4d1f8a9a..fedb4736 100644 --- a/internal/pipeline/operator_sessions.go +++ b/internal/pipeline/operator_sessions.go @@ -58,7 +58,7 @@ func (s *Store) initOperatorSessions() error { _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS operator_sessions ( session_id TEXT PRIMARY KEY, directory TEXT NOT NULL, title TEXT NOT NULL DEFAULT '', tag TEXT NOT NULL DEFAULT '', created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL, -closed_at INTEGER NOT NULL DEFAULT 0); +closed_at INTEGER NOT NULL DEFAULT 0, ephemeral INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS operator_sessions_recent ON operator_sessions(last_used_at DESC);`) if err != nil { return err @@ -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 // and no session is silently reported as closed. func (s *Store) migrateOperatorSessions() error { - return s.addColumnIfMissing("operator_sessions", "closed_at", "INTEGER NOT NULL DEFAULT 0") + 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: @@ -139,13 +145,32 @@ func (s *Store) migrateOperatorSessions() error { // repeated id updates directory/title/tag and moves last_used_at to now while // preserving the original created_at. CreatedAt is therefore stable across // re-records. Recording also clears any closed state: re-creating or adopting a -// session is use, so it is open again. +// session is use, so it is open again. The row is a normal listed operator chat +// (ephemeral = 0). func (s *Store) RecordOperatorSession(ctx context.Context, sessionID, directory, title, tag string) error { + return s.recordSession(ctx, sessionID, directory, title, tag, false) +} + +// RecordVerificationSession upserts one chat created for automated verification +// (chat_create with ephemeral set). It is a real registry row — so the session +// can still be closed, reopened and looked up by id — but OperatorSessions, and +// therefore chat_sessions, never lists it. It exists so a check that drives the +// real UI cannot leave a permanent "New chat" in the operator's list, and a +// re-record always keeps it hidden. +func (s *Store) RecordVerificationSession(ctx context.Context, sessionID, directory, title, tag string) error { + return s.recordSession(ctx, sessionID, directory, title, tag, true) +} + +func (s *Store) recordSession(ctx context.Context, sessionID, directory, title, tag string, ephemeral bool) error { now := time.Now().UnixMilli() - _, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at) -VALUES(?,?,?,?,?,?,0) -ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0`, - sessionID, directory, title, tag, now, now) + hidden := 0 + if ephemeral { + hidden = 1 + } + _, err := s.db.ExecContext(ctx, `INSERT INTO operator_sessions(session_id,directory,title,tag,created_at,last_used_at,closed_at,ephemeral) +VALUES(?,?,?,?,?,?,0,?) +ON CONFLICT(session_id) DO UPDATE SET directory=excluded.directory,title=excluded.title,tag=excluded.tag,last_used_at=excluded.last_used_at,closed_at=0,ephemeral=excluded.ephemeral`, + sessionID, directory, title, tag, now, now, hidden) return err } @@ -196,13 +221,15 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) // OperatorSessions reports the operator's chat sessions, most-recently-used // first (ties broken by session id for a deterministic order), capped at // operatorSessionListLimit. Rows with no tag are omitted: a session with no -// recorded tag is not an operator session and must never be listed. Closed -// sessions are included: the app groups or filters them as history, so the +// recorded tag is not an operator session and must never be listed. Ephemeral +// rows are omitted too: a chat created for automated verification is usable and +// closable but never listed here, so it cannot clutter the operator's list. +// Closed sessions are included: the app groups or filters them as history, so the // operator can still see and reopen what they finished. It is one bounded // statement; recency is never mutated here. func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) { rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,created_at,last_used_at,closed_at -FROM operator_sessions WHERE tag <> '' 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 { return nil, err } diff --git a/internal/pipeline/operator_sessions_test.go b/internal/pipeline/operator_sessions_test.go index e326350f..06140a79 100644 --- a/internal/pipeline/operator_sessions_test.go +++ b/internal/pipeline/operator_sessions_test.go @@ -232,3 +232,91 @@ func TestOperatorSessionsSurviveRestart(t *testing.T) { 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) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index c9f9f4ed..cd6b87da 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -187,6 +187,14 @@ type ChatCreateRequest struct { Title string `json:"title,omitempty"` Directory string `json:"directory,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 diff --git a/internal/server/chat.go b/internal/server/chat.go index c0da3f30..8ae8bd3f 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -68,6 +68,9 @@ type operatorRegistry interface { SetChatCreateSession(ctx context.Context, requestID, sessionID string) error AdvanceChatCreate(ctx context.Context, requestID, from, to 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 OperatorSessions(ctx context.Context) ([]pipeline.OperatorSession, error) OperatorDirectories(ctx context.Context, limit int) ([]string, error) diff --git a/internal/server/chat_sessions.go b/internal/server/chat_sessions.go index a2213e94..5b22851f 100644 --- a/internal/server/chat_sessions.go +++ b/internal/server/chat_sessions.go @@ -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 // 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 -// 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) { if broker == nil { _ = 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 := "" directory := "" operationID := "" + ephemeral := false if request.ChatCreate != nil { title = strings.TrimSpace(request.ChatCreate.Title) directory = strings.TrimSpace(request.ChatCreate.Directory) operationID = strings.TrimSpace(request.ChatCreate.OperationID) + ephemeral = request.ChatCreate.Ephemeral } // Legacy clients did not carry a durable create identity. Give each received // 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) 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()}) return } @@ -198,8 +209,12 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat session.Tag = protocol.ChatSessionTagOperator 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 - // into chat_sessions without a re-list. - response.ChatSessions = []protocol.ChatSession{session} + // into chat_sessions without a re-list. An ephemeral create has no listed row + // 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) } diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index 312bc221..c4c567c7 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -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) { broker := &fakeChat{created: protocol.ChatSession{ID: "ses_new"}, activateErr: errors.New("skill not found")} store := newOperatorStore(t) diff --git a/web/src/app.js b/web/src/app.js index 96682034..ee4f0661 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -4582,7 +4582,12 @@ function applyChatCommandEffect(sessionId, session, effect) { async function startChatSession(directory) { const from = state.chatActiveId; 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 // before the conversation opens, then refresh from the server. state.chatSessions = [created, ...state.chatSessions.filter((s) => s.id !== created.id)]; diff --git a/web/src/repository.js b/web/src/repository.js index 62f112db..1126f410 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -389,11 +389,16 @@ export class PipelinesRepository { * 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 * 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({ 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]; if (!session) { diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 68eee472..474e4f06 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -3371,7 +3371,11 @@ try { await page.fill("#chatInput", ""); // (e) `/new` creates a fresh throwaway session (C2's chat_create, sent directly - // until C2 lands) and opens it. The operator's session is left untouched. + // until C2 lands) and opens it. The operator's session is left untouched. The + // throwaway is created EPHEMERAL: this check drives the real page, so without it + // every run would leave a permanent "New chat" in the operator's chat list (the + // server writes no operator-registry row for an ephemeral create). + await page.evaluate(`window.__pipelinesEphemeralChat = true`); await page.fill("#chatInput", "/new"); await page.evaluate( `document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, From b88904c360f46f18964911911293cd718bf46db6 Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 13:32:54 +0100 Subject: [PATCH 4/4] web: let concurrent ui-smoke runs pick their own port Every run defaulted to 8091, so two parallel pipeline items running the UI check collided with EADDRINUSE. An explicit --port/WEB_UI_PORT still wins; otherwise the OS assigns a free port. Verified with two simultaneous --scratch runs (60540/60541), both PASS. --- web/test/ui-smoke.mjs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 474e4f06..8d2b49e1 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -2,7 +2,9 @@ // Chrome, connect to a running Pipelines server through the page's own proxy, // 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 // 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; } -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 out = resolve( flag(process.argv, "--out", process.env.WEB_UI_OUT ?? join(tmpdir(), "pipelines-web-ui")),