From 9231236f838b12b77ba3202454123faf20616312 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 19 Oct 2026 11:58:55 +0100 Subject: [PATCH 1/8] 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/8] 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/8] 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/8] 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")), From 3d7ad54e689eb764232f7a13a54c390a5522c411 Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 13:50:13 +0100 Subject: [PATCH 5/8] web: local rename/hide, seen markers and per-device persistence (C13) --- web/PARITY.md | 13 +- web/src/app.js | 493 +++++++++++++++++++++++++++++++++++++---- web/src/chat.js | 262 ++++++++++++++++++++++ web/styles.css | 66 +++++- web/test/chat.test.mjs | 191 ++++++++++++++++ web/test/ui-smoke.mjs | 403 +++++++++++++++++++++++++++++---- 6 files changed, 1336 insertions(+), 92 deletions(-) diff --git a/web/PARITY.md b/web/PARITY.md index 67d64de9..cb4ead14 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -96,11 +96,11 @@ the pipeline list already carries — rather than a pluralised verb. | C6 | Reasoning block + tool calls with name/input for the whole lifecycle | `chat_event` | done — the assistant turn draws, in order, its one collapsible reasoning block and its one tool-call chip (then the answer). Reasoning labels match the app: `Thinking…` / `Reasoning` for a single step and `Thinking · {N} steps` / `Reasoning · {N} steps` for several, with ` · {duration}` appended when the parts' timing gives a settled span (earliest start → latest completed), through chevrons named `Show reasoning` / `Hide reasoning`. The chip reads `1 tool called` / `{N} tools called`, announces `… expand for details`, wears the shared spinner while a call is in flight and an error tint once one failed, and opens a fixed overlay panel under the chip (flipped above / clamped into the viewport when there is no room) with the same count, a `Close tool calls` control and an internally scrolling, independently-expandable row per call: the name (else `tool`), the first of `description`/`command`/`filePath`/`file_path`/`path`/`pattern`/`query`/`url` collapsed and elided to 72 characters, the `+N -M` edit stat when present, the `formatToolDuration` value (`340ms`/`1.2s`/`2m 3s`), and `Expand {name}`/`Collapse {name}`; a failed row is marked `Failed tool call`. An expanded row shows INPUT (pretty-printed JSON, or the raw partial string), the LCS edit diff (at most 200 rendered lines with the remaining `… {N} more changed line(s) not shown`), then ERROR (the server's `error.message`, else the output) or OUTPUT (`(no output)` when settled and empty, nothing while in flight). Lifecycle words `streaming`/`running` are in flight and `completed`/`error` settled; a settled call never spins or wears the ` · long` mark. Because the panel is a fixed overlay, opening or closing it never re-flows the transcript nor moves its scroll (C14). Captured 2026-10-19 against `ses_eae413f50ffeLQDExlg8cYnscN` (one folded turn, 80 reasoning steps, 122 tool calls): `captures/51-chat-reasoning-collapsed.png`, `captures/52-chat-reasoning-expanded.png`, `captures/53-chat-tool-chip.png`, `captures/54-chat-tool-panel.png` (an opened `read` row showing INPUT + OUTPUT) and `captures/55-chat-edit-diff-sample.png`. The live history carries no failed or edit-family call, so that capture renders a labelled page-rendered sample — a `shell` row marked `Failed tool call` with INPUT + ERROR and an `edit` row with a `+2 -1` diff — through the page's own row builder; the transcript stayed put across open/close (top 43065 → 43065). **Live arrival over `chat_event` is C5**: the renderer is built from the same part shapes (`ChatPart{type,name,state{status,input,content,error},time}`) and takes a `streaming` flag plus a live elapsed source so C5 can drive in-flight calls; the chip's in-flight spinner, the ` · long` 60s mark, the panel flip-above and an edit-family call are not reachable against the live server, so they are unit-tested (`test/chat.test.mjs`) rather than claimed as captured | | C7 | Markdown rendering + code blocks | — | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (opened at the newest content: bold, bullet lists, a `|` table with its `---` delimiter row and inline code spans from the live assistant answer), `captures/47b-chat-markdown-code.png` (a rendered fenced code block — label `js`, the pre body `const answer = 42;` — drawn in the live browser by the page's own `renderMarkdown`, the same function that renders the answer) and `captures/47-chat-reasoning-code.png`. The subset is exactly `Markdown.kt`: paragraphs, `#`–`######` headings, fenced code (```/~~~, the language label else `code`), block quotes, bullet/ordered lists, `|` tables with a `---` delimiter row, thematic rules, inline code, bold, italic (underscore only at word boundaries, so `snake_case` stays plain), `[label](url)` links and bare http(s) autolinks; HTML entities are decoded first in one pass, and HTML, reference links, strikethrough and nested lists render as plain text and are never dropped. **Code-block caveat, stated plainly**: the live assistant answer carries **no** fenced block — its four fences live in the reasoning transcript, which the app draws as plain text, not as markdown (`captures/47-chat-reasoning-code.png` shows one such fence as muted plain text; that is C6 material, not the markdown path). So the rendered `<pre>` code block is captured from a labelled sample through the page's real renderer (`47b`), and the same path plus its `code`-else-language label is unit-tested in `test/markdown.test.mjs`. Only `http(s)` link targets become clickable — the transcript is untrusted model output, so a `javascript:`/`data:` target renders as its label, never as a live link | | 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) | +| 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` | | 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 | -| C13 | Local rename/hide, seen state, persistence to `localStorage` | client-side | todo | +| 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 | Three decisions in Chat, recorded here as the browser client's own choices where @@ -122,9 +122,12 @@ today, so the browser collects, validates and blocks on a failed attachment and then sends it best-effort as the file's own reference string, but the file is not yet forwarded to OpenCode. **`/new` sends `chat_create` directly** because C2's create dialog is a separate item; it creates a session titled `New chat` in the -current directory and opens it. **`/rename` is a local, per-device rename** until -C13 lands (the browser item mirrors C13's dependency rather than inventing a -server rename). And the **draft is held per chat in memory and mirrored into +current directory and opens it. **`/rename` writes through C13's durable, +per-device store** (the browser item mirrors C13's dependency rather than +inventing a server rename), so a `/rename`d chat keeps its local title across a +refresh and shows the same `Renamed this session to “{title}” on this device +only; the server's title is unchanged.` notice. And the **draft is held per chat +in memory and mirrored into `localStorage`** (`pipelines.web.chatDraft.v1`), the web analogue of per-device persistence, while attachments are memory-only because a `File` handle cannot be serialised. The composer's Stop control appears the moment a prompt is accepted diff --git a/web/src/app.js b/web/src/app.js index 29d088f6..4ae49a85 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -228,19 +228,29 @@ import { } from "./actions.js"; import { BACKGROUND_TASKS_TITLE, + CHAT_ACTIONS_LABEL, CHAT_ATTACH_LABEL, CHAT_COMMAND_GLYPH, CHAT_COMPOSER_PLACEHOLDER, CHAT_EMPTY, CHAT_FOLLOW_THRESHOLD_PX, + CHAT_HIDE_ACTION, CHAT_LOADING, CHAT_NEW_ACTION, CHAT_NO_MATCH_ACTION, CHAT_QUEUED_NOTICE, + CHAT_REMOVED_MESSAGE, + CHAT_RENAME_ACTION, + CHAT_RENAME_DISMISS, + CHAT_RENAME_FIELD_LABEL, + CHAT_RENAME_HELPER, + CHAT_RENAME_SAVE, + CHAT_RENAME_TITLE, CHAT_SEARCH_LABEL, CHAT_SEND_LABEL, CHAT_STOP_LABEL, CHAT_TAB_TITLE, + CHAT_UNDO_ACTION, CLOSED_CHIP_LABEL, CLOSED_SECTION_LABEL, CLOSE_CHAT_ACTION, @@ -271,6 +281,7 @@ import { SHELL_OUTPUT_UNAVAILABLE, SHELL_ROW_LABEL, applyChatEvent, + applyChatOverrides, applyChatPermission, approvalCard, attachmentDisplayName, @@ -293,20 +304,33 @@ import { composerCanSend, composerSendEnabled, composerSubmit, + decodeChatOverrides, + decodeChatSeen, directoryLabel, + emptyChatOverrides, + emptyChatSeen, + encodeChatOverrides, + encodeChatSeen, filterSessions, groupSessionsByDirectory, + hideChatOverride, historyResync, + isChatSessionUnseen, + markChatUnseen, mergeHistoryPage, mergeShellFrame, newChatThread, parseChatInput, queuedAfterFrame, + readChatSeen, reasoningLabel, + renameChatOverride, + restoreChatOverride, resumedThread, runningAfterFrame, runningBackgroundShells, runningToolElapsedMillis, + seedChatSeen, sessionActivity, sessionActivityBadge, sessionChipLabel, @@ -357,6 +381,22 @@ const CHAT_SCROLL_STORAGE_KEY = "pipelines.web.chatScroll.v1"; */ const CHAT_DRAFT_STORAGE_KEY = "pipelines.web.chatDraft.v1"; +/** + * The operator's own chat changes (C13): local renames and hidden session ids, + * the web analogue of Android's `chat_overrides` preference. One JSON value: + * `{titles:{"<id>":"<title>"},hidden:["<id>"]}`. A local title wins over the + * server's on every later list refresh; a hidden id only disappears here. + */ +const CHAT_OVERRIDES_STORAGE_KEY = "pipelines.web.chatOverrides.v1"; + +/** + * What the operator has already seen of the session list (C13), the web analogue + * of Android's `chat_seen` preference. One JSON value: + * `{seenAt:{"<id>":<updated_at ms>},unseen:["<id>"]}`. The watermark is advanced + * only by opening a chat (or first-sight seeding), never by a stale list. + */ +const CHAT_SEEN_STORAGE_KEY = "pipelines.web.chatSeen.v1"; + /** Shown where tiles exist but the configured server URL cannot resolve them. */ const ARTIFACT_SERVER_HINT = "Set the server URL in Settings to open or copy artifact links."; @@ -526,6 +566,18 @@ const state = { // report for a refused close/reopen. chatClose: null, chatBusy: false, + // C13: this device's local titles/hidden ids and the seen watermarks, both + // persisted as one JSON value each. `chatMenu` is the row whose Chat actions + // menu is open, `chatRename` the session whose Rename chat dialog is open, and + // `chatSnackbar` the one in-flight hide report (`{id, sessionId}`) with the + // timer that auto-dismisses it. A new hide replaces the previous report. + chatOverrides: readChatOverridesStore(), + chatSeen: readChatSeenStore(), + chatMenu: null, + chatRename: null, + chatSnackbar: null, + chatSnackbarSeq: 0, + chatSnackbarTimer: null, // C5: the session ids this connection currently has subscribed to their shared // live stream. The server detaches a subscription when the connection closes // (there is no chat_unsubscribe), so this is cleared on every socket drop and @@ -3912,6 +3964,47 @@ function readChatDraft(sessionId) { return typeof value === "string" ? value : ""; } +/** The persisted local chat overrides; unreadable storage means no overrides. */ +function readChatOverridesStore() { + try { + return decodeChatOverrides(localStorage.getItem(CHAT_OVERRIDES_STORAGE_KEY)); + } catch { + return emptyChatOverrides(); + } +} + +/** Persist the current local overrides; storage failure leaves memory authoritative. */ +function saveChatOverrides() { + try { + localStorage.setItem(CHAT_OVERRIDES_STORAGE_KEY, encodeChatOverrides(state.chatOverrides)); + } catch { + // storage may be full or disabled; the in-memory overrides still hold + } +} + +/** The persisted seen state; unreadable storage means nothing seen. */ +function readChatSeenStore() { + try { + return decodeChatSeen(localStorage.getItem(CHAT_SEEN_STORAGE_KEY)); + } catch { + return emptyChatSeen(); + } +} + +/** + * Persist the seen state only when it actually changed. Every frame and refresh + * would otherwise rewrite localStorage for no reason. + */ +function saveChatSeen(next) { + if (next === state.chatSeen) return; + state.chatSeen = next; + try { + localStorage.setItem(CHAT_SEEN_STORAGE_KEY, encodeChatSeen(state.chatSeen)); + } catch { + // storage may be full or disabled; the in-memory state still holds + } +} + /** * The pixels the transcript still sits above its end (0 when at the bottom), via * the same pure decision the unit tests cover. `chatBottomDistancePx` measures @@ -3979,6 +4072,10 @@ async function loadChatSessions(force = false) { try { state.chatSessions = await repo.chatSessions(); state.chatLoaded = true; + // Fold this device's seen state in: the active chat has been read, and every + // session seen for the first time gets a baseline so pre-existing chats are + // not all reported as new. + saveChatSeen(seedChatSeen(state.chatSeen, state.chatSessions, state.chatActiveId)); } catch (error) { state.chatError = describeError(error); } @@ -3993,11 +4090,16 @@ async function openChatSession(id) { const leaving = document.getElementById("chatTranscript"); if (leaving && state.chatActiveId) saveChatScroll(state.chatActiveId, currentChatPosition(leaving)); state.chatActiveId = id; + state.chatMenu = null; state.chatPlaced = null; state.chatFollowing = true; state.chatReasoning = new Set(); state.chatToolPanels = new Set(); state.chatToolRows = new Set(); + // Opening reads the conversation: advance the watermark to its current recency + // and clear the explicit unseen mark (a row that is absent has no recency). + const session = state.chatSessions.find((candidate) => candidate.id === id) ?? null; + saveChatSeen(readChatSeen(state.chatSeen, id, session?.updated_at ?? 0)); const existing = state.chatThreads.get(id); state.chatThreads.set(id, { ...newChatThread(id), @@ -4077,11 +4179,23 @@ function settleChatThreads() { function onChatEvent(frame) { const sessionId = String(frame?.session_id ?? "").trim(); if (!sessionId || !state.chatThreads.has(sessionId)) return; + markBackgroundChatUnseen(sessionId); const thread = state.chatThreads.get(sessionId); state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now())); renderContent(); } +/** + * A frame for a conversation that is not on screen marks it explicitly unseen, + * so its live activity is visible in the list even though a pushed stream carries + * no wall-clock recency to compare. The active chat is read as it arrives and is + * never marked. + */ +function markBackgroundChatUnseen(sessionId) { + if (!sessionId || sessionId === state.chatActiveId) return; + saveChatSeen(markChatUnseen(state.chatSeen, sessionId)); +} + /** * Fold one pushed `chat_permission` frame into its conversation (C10). Only a * conversation this client has open is folded — the server only pushes a @@ -4293,6 +4407,7 @@ async function loadOlderChatHistory(id) { /** Open the Close chat? confirm for [session] (the mutation only on confirm). */ function openChatClose(session) { + state.chatMenu = null; state.chatClose = session; renderContent(); } @@ -4340,6 +4455,7 @@ async function acceptChatClose(session) { async function reopenChatSession(id) { if (state.chatBusy) return; state.chatBusy = true; + state.chatMenu = null; renderContent(); try { const { session: updated } = await repo.reopenChat(id); @@ -4358,6 +4474,136 @@ function applyChatSessionUpdate(id, updated, closed) { ); } +// --------------------------------------------------------------------------- +// This device's chat changes (C13): local rename, hide + undo, row menu +// --------------------------------------------------------------------------- + +/** The server row with this device's local title applied (for the open pane). */ +function effectiveChatSession(session) { + if (!session) return null; + return applyChatOverrides([session], state.chatOverrides)[0] ?? session; +} + +/** Open one row's Chat actions menu, closing any other. */ +function openChatMenu(sessionId) { + state.chatMenu = state.chatMenu === sessionId ? null : sessionId; + renderContent(); + // The re-render replaced the focused button; move focus into the panel so a + // keyboard operator can walk the items without hunting for the next Tab stop. + if (state.chatMenu) { + const first = document.querySelector(`#chatRows .chat-row[data-session="${CSS.escape(sessionId)}"] .chat-menu-item`); + first?.focus(); + } +} + +/** Open the Rename chat dialog for [session] (its current effective title). */ +function openChatRename(session) { + state.chatMenu = null; + state.chatRename = session; + renderContent(); + // Same re-render note as the menu: put the cursor in the Name field. + document.getElementById("chatRenameInput")?.focus(); +} + +function dismissChatRename() { + state.chatRename = null; + renderContent(); +} + +/** + * Record a local rename, persist it and reflect it at once: the row shows the + * local title on the next render (and every later refresh), and an open + * conversation's own title follows. Nothing is sent to the server — the + * brokered protocol has no chat rename. + */ +function applyLocalChatRename(sessionId, title) { + const next = renameChatOverride(state.chatOverrides, sessionId, title); + if (next === state.chatOverrides) return false; + state.chatOverrides = next; + saveChatOverrides(); + const local = next.titles[String(sessionId)]; + if (local != null) setThread(sessionId, { title: local }); + return true; +} + +/** + * The dialog's Save: trim, record the override, close the dialog and re-render. + * A blank title is ignored (Save is already disabled while trimmed-blank). + */ +function acceptChatRename(session, title) { + const trimmed = String(title ?? "").trim(); + if (trimmed === "") return; + applyLocalChatRename(session.id, trimmed); + state.chatRename = null; + renderContent(); +} + +/** + * Hide a session on this device only. The server is not asked to delete + * anything: the row disappears from this list, its conversation closes, and the + * one snackbar says exactly that with an Undo. A new hide replaces the previous + * report (one snackbar slot), never queues behind it. + */ +function hideChatLocally(sessionId) { + const id = String(sessionId ?? ""); + if (!id) return; + const next = hideChatOverride(state.chatOverrides, id); + if (next === state.chatOverrides) return; + state.chatOverrides = next; + saveChatOverrides(); + state.chatMenu = null; + state.chatRename = null; + // Hiding closes the conversation, exactly as Android's remove does: the thread + // is dropped, the active id cleared and the subscription forgotten. + state.chatThreads.delete(id); + if (state.chatActiveId === id) { + state.chatActiveId = null; + state.chatPlaced = null; + } + if (state.chatSubscriptions.has(id)) { + state.chatSubscriptions = new Set(state.chatSubscriptions); + state.chatSubscriptions.delete(id); + } + installChatSnackbar(id); + renderContent(); +} + +/** Replace the one in-flight hide report and (re)start its auto-dismiss timer. */ +function installChatSnackbar(sessionId) { + if (state.chatSnackbarTimer != null) clearTimeout(state.chatSnackbarTimer); + state.chatSnackbarSeq += 1; + const id = state.chatSnackbarSeq; + state.chatSnackbar = { id, sessionId }; + state.chatSnackbarTimer = setTimeout(() => { + state.chatSnackbarTimer = null; + if (state.chatSnackbar?.id !== id) return; + state.chatSnackbar = null; + renderContent(); + }, 6000); +} + +/** Undo the last hide: restore its row and clear the report (nothing server-side). */ +function undoHideChat() { + const sessionId = state.chatSnackbar?.sessionId; + if (!sessionId) return; + const next = restoreChatOverride(state.chatOverrides, sessionId); + if (next !== state.chatOverrides) { + state.chatOverrides = next; + saveChatOverrides(); + } + clearChatSnackbar(); + renderContent(); +} + +/** Drop the hide report and its timer (Undo, expiry, or leaving the list). */ +function clearChatSnackbar() { + if (state.chatSnackbarTimer != null) { + clearTimeout(state.chatSnackbarTimer); + state.chatSnackbarTimer = null; + } + state.chatSnackbar = null; +} + // --------------------------------------------------------------------------- // The composer and its slash commands (C8 · C9) // --------------------------------------------------------------------------- @@ -4543,8 +4789,9 @@ function runChatCommand(sessionId, session, text) { /** * Perform one command effect. `/new` creates a session in the current directory * and opens it (the create request is C2's; until C2 lands the browser sends - * `chat_create` directly); `/close` reuses the C3 confirm; `/rename` is the local - * rename pending C13; `/stop` interrupts; `/help` shows the command list. + * `chat_create` directly); `/close` reuses the C3 confirm; `/rename` writes to + * C13's durable device-local store; `/stop` interrupts; `/help` shows the + * command list. */ function applyChatCommandEffect(sessionId, session, effect) { switch (effect.kind) { @@ -4604,16 +4851,15 @@ async function startChatSession(directory) { } /** - * `/rename`: rename the session on this device only. C13 owns the durable local - * rename/hide store; until it lands this renames the held row and the open - * conversation in memory and says so. + * `/rename`: rename the session on this device only, through the same durable + * store the row's Rename chat dialog uses (C13). The local title wins over the + * server's on every later refresh; nothing is sent to the server. */ function renameChatSessionLocally(sessionId, title) { - state.chatSessions = state.chatSessions.map((session) => - session.id === sessionId ? { ...session, title } : session, - ); - setThread(sessionId, { title }); - addChatNotice(sessionId, `Renamed this session to “${title}” on this device only; the server's title is unchanged.`); + const trimmed = String(title ?? "").trim(); + if (trimmed === "") return; + applyLocalChatRename(sessionId, trimmed); + addChatNotice(sessionId, `Renamed this session to “${trimmed}” on this device only; the server's title is unchanged.`); } /** The composer's Stop control: interrupt the session's running turn. */ @@ -4747,7 +4993,9 @@ function removeChatAttachment(sessionId, attachmentId) { } function renderChatList() { - const list = h("div", { class: "list chat-list" }); + // The open menu must not be clipped by the list's rounded-corner overflow; the + // class is present only while a menu is open, so the normal list stays clipped. + const list = h("div", { class: `list chat-list${state.chatMenu ? " menu-open" : ""}` }); const toolbar = h("div", { class: "list-toolbar chat-toolbar" }); toolbar.append( h("input", { @@ -4787,7 +5035,8 @@ function fillChatRows(rows) { rows.append(empty); return; } - const filtered = filterSessions(state.chatSessions, state.chatQuery); + const visible = applyChatOverrides(state.chatSessions, state.chatOverrides); + const filtered = filterSessions(visible, state.chatQuery); if (filtered.length === 0 && state.chatQuery.trim() !== "") { const empty = chatEmpty(chatNoMatchMessage(state.chatQuery)); empty.append( @@ -4853,7 +5102,14 @@ function chatEmpty(message) { function renderChatRow(session) { const open = state.chatActiveId === session.id; const thread = state.chatThreads.get(session.id) ?? null; - const activity = sessionActivity(thread?.running === true, false); + const unseen = + !session.closed && + isChatSessionUnseen(session, { + activeId: state.chatActiveId, + seen: state.chatSeen, + opened: state.chatThreads.has(session.id), + }); + const activity = sessionActivity(thread?.running === true, unseen); const badge = sessionActivityBadge(activity, open); const row = h("div", { class: `row chat-row${open ? " selected" : ""}`, @@ -4862,8 +5118,8 @@ function renderChatRow(session) { "data-session": session.id, onclick: () => openChatSession(session.id), onkeydown: (event) => { - // Only the row itself opens on Enter/Space; a nested Close chat…/Reopen - // button handles its own keyboard activation (and must not double-fire). + // Only the row itself opens on Enter/Space; the Chat actions menu handles + // its own keyboard activation (and must not double-fire). if (event.target !== event.currentTarget) return; if (event.key === "Enter" || event.key === " ") { event.preventDefault(); @@ -4891,38 +5147,82 @@ function renderChatRow(session) { text: sessionMeta(session, sessionWorkLabel(session.busy === true, thread)), }), ); - const actions = h("div", { class: "chat-row-actions" }); - if (session.closed) { - actions.append( - h("button", { - class: "ghost chat-reopen", - type: "button", - text: REOPEN_ACTION, - disabled: state.chatBusy, - onclick: (event) => { - event.stopPropagation(); - reopenChatSession(session.id); - }, - }), - ); - } else { - actions.append( - h("button", { - class: "ghost chat-close", - type: "button", - text: CLOSE_CHAT_ACTION, - disabled: state.chatBusy, - onclick: (event) => { - event.stopPropagation(); - openChatClose(session); - }, - }), - ); - } - row.append(actions); + row.append(renderChatActionsMenu(session)); return row; } +/** + * One row's Chat actions menu, with Android's items in its order: Rename…, then + * Close chat… (open) or Reopen (closed), then Hide on this device. Closing is the + * shared, server-side finish; hiding only affects this device and says so. + */ +function renderChatActionsMenu(session) { + const wrap = h("div", { class: "chat-row-actions chat-menu-wrap" }); + const expanded = state.chatMenu === session.id; + wrap.append( + h("button", { + class: "ghost chat-menu-button", + type: "button", + text: "⋯", + "aria-label": CHAT_ACTIONS_LABEL, + "aria-haspopup": "menu", + "aria-expanded": expanded ? "true" : "false", + title: CHAT_ACTIONS_LABEL, + onclick: (event) => { + event.stopPropagation(); + openChatMenu(session.id); + }, + }), + ); + if (expanded) { + const menu = h("div", { class: "chat-menu-panel", role: "menu", "aria-label": CHAT_ACTIONS_LABEL }); + menu.addEventListener("click", (event) => event.stopPropagation()); + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-rename", + type: "button", + role: "menuitem", + text: CHAT_RENAME_ACTION, + onclick: () => openChatRename(session), + }), + ); + if (session.closed) { + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-reopen", + type: "button", + role: "menuitem", + text: REOPEN_ACTION, + disabled: state.chatBusy, + onclick: () => reopenChatSession(session.id), + }), + ); + } else { + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-close", + type: "button", + role: "menuitem", + text: CLOSE_CHAT_ACTION, + disabled: state.chatBusy, + onclick: () => openChatClose(session), + }), + ); + } + menu.append( + h("button", { + class: "ghost chat-menu-item chat-menu-hide", + type: "button", + role: "menuitem", + text: CHAT_HIDE_ACTION, + onclick: () => hideChatLocally(session.id), + }), + ); + wrap.append(menu); + } + return wrap; +} + /** The active conversation: identity, context, transcript and its controls. */ function renderChatConversation() { const pane = h("div", { class: "detail chat-detail" }); @@ -4932,8 +5232,9 @@ function renderChatConversation() { return pane; } const session = state.chatSessions.find((candidate) => candidate.id === state.chatActiveId) ?? null; + const effective = effectiveChatSession(session); const thread = state.chatThreads.get(state.chatActiveId) ?? null; - const title = session ? sessionTitle(session) : state.chatActiveId.slice(0, 18); + const title = effective ? sessionTitle(effective) : state.chatActiveId.slice(0, 18); // The pending approval card (C10), derived from the stored frame plus the local // answer. While it is actionable the top bar offers a jump control and the // running indicator stands down (a turn blocked on a decision is not generating). @@ -5045,9 +5346,89 @@ function renderChatConversation() { */ function appendChatDialogs(pane) { if (state.chatClose) pane.append(renderChatCloseDialog(state.chatClose)); + if (state.chatRename) pane.append(renderChatRenameDialog(state.chatRename)); + if (state.chatSnackbar) pane.append(renderChatSnackbar()); if (state.actionError) pane.append(renderActionFailedDialog()); } +/** + * The one hide report (C13): the exact Android message and an `Undo` action. It + * is a fixed overlay (so a re-render or the transcript's height never moves it) + * and it is replaced, never queued, by a newer hide. + */ +function renderChatSnackbar() { + const bar = h("div", { class: "chat-snackbar", role: "status" }); + bar.append(h("span", { class: "chat-snackbar-message", text: CHAT_REMOVED_MESSAGE })); + bar.append( + h("button", { + class: "ghost chat-snackbar-undo", + type: "button", + text: CHAT_UNDO_ACTION, + onclick: () => undoHideChat(), + }), + ); + return bar; +} + +/** + * The Rename chat dialog (C13): a locally-kept name, with the helper that says so + * plainly. Save is disabled while the trimmed value is blank; typing toggles that + * state directly, so the transcript's scroll is never disturbed by a re-render. + * Nothing is sent to the server — there is no chat rename on the wire. + */ +function renderChatRenameDialog(session) { + const effective = effectiveChatSession(session) ?? session; + const overlay = h("div", { + class: "confirm-dialog confirm-chat-rename", + role: "dialog", + "aria-modal": "true", + "aria-label": CHAT_RENAME_TITLE, + }); + overlay.addEventListener("click", (event) => { + if (event.target === overlay) dismissChatRename(); + }); + const panel = h("div", { class: "confirm-panel" }); + panel.append(h("h2", { class: "confirm-title", text: CHAT_RENAME_TITLE })); + const field = h("div", { class: "chat-rename-field" }); + field.append(h("label", { class: "chat-rename-label", for: "chatRenameInput", text: CHAT_RENAME_FIELD_LABEL })); + const input = h("input", { + id: "chatRenameInput", + class: "rename-input chat-rename-input", + type: "text", + value: sessionTitle(effective), + spellcheck: "false", + autocomplete: "off", + }); + field.append(input); + panel.append(field); + panel.append(h("p", { class: "chat-rename-helper", text: CHAT_RENAME_HELPER })); + const actions = h("div", { class: "confirm-actions" }); + actions.append( + h("button", { + class: "ghost confirm-dismiss chat-rename-cancel", + type: "button", + text: CHAT_RENAME_DISMISS, + onclick: dismissChatRename, + }), + ); + const save = h("button", { + class: "confirm-accept chat-rename-save", + type: "button", + text: CHAT_RENAME_SAVE, + disabled: input.value.trim() === "", + onclick: () => acceptChatRename(session, input.value), + }); + // Toggle Save in place on input: no renderContent, so the transcript's scroll + // position (C14) is untouched while the operator types. + input.addEventListener("input", () => { + save.disabled = input.value.trim() === ""; + }); + actions.append(save); + panel.append(actions); + overlay.append(panel); + return overlay; +} + /** * The background-tasks bar (C11): the running shells this conversation still * owns. It returns null (renders nothing) unless at least one shell is running, @@ -6955,6 +7336,11 @@ document.addEventListener("keydown", (event) => { dismissActionError(); return; } + if (state.chatRename) { + event.preventDefault(); + dismissChatRename(); + return; + } if (state.chatClose) { event.preventDefault(); dismissChatClose(); @@ -6975,12 +7361,29 @@ document.addEventListener("keydown", (event) => { closeStagePane(); return; } + if (state.chatMenu) { + event.preventDefault(); + state.chatMenu = null; + renderContent(); + return; + } if (state.searchOpen) { event.preventDefault(); closeSearch(); } }); +// A click anywhere outside an open Chat actions menu closes it, so a menu never +// lingers behind another row's selection. The wrap element (button + panel) +// keeps its own clicks from closing it. +document.addEventListener("click", (event) => { + if (!state.chatMenu) return; + const target = event.target; + if (target instanceof Element && target.closest(".chat-menu-wrap")) return; + state.chatMenu = null; + renderContent(); +}); + // Return-to-foreground recovery (T4): the page becomes visible again, or the // browser reports it is back online, and the client drives its socket back // without waiting out the backoff. DOM-only, and idempotent. diff --git a/web/src/chat.js b/web/src/chat.js index 37b626ea..19e751aa 100644 --- a/web/src/chat.js +++ b/web/src/chat.js @@ -29,6 +29,10 @@ // ui/chat/ChatFormat.kt attachmentError, attachmentFiles, // MAX_ATTACHMENT_BYTES, attachmentDisplayName // ui/chat/ChatAttachments.kt the attachment display name/error rules +// ui/chat/ChatOverrides.kt ChatSessionOverrides: local titles + hidden ids, +// applied over every server list refresh +// ui/chat/ChatSeen.kt ChatSeenState: the seen watermark and explicit +// unseen marks behind the row's "New" badge // // Nothing here touches the DOM or imports the app: every wording and decision is // unit-tested without a browser. The caller sets each server string with @@ -557,6 +561,264 @@ export function closeChatConfirmation(title) { ); } +// --------------------------------------------------------------------------- +// Local overrides and seen state (ChatOverrides.kt / ChatSeen.kt) +// --------------------------------------------------------------------------- + +/** The row menu and the rename dialog, verbatim from ChatListPane.kt. */ +export const CHAT_RENAME_ACTION = "Rename…"; +export const CHAT_HIDE_ACTION = "Hide on this device"; +export const CHAT_ACTIONS_LABEL = "Chat actions"; +export const CHAT_REMOVED_MESSAGE = "Hidden on this device; the chat stays on the server."; +export const CHAT_UNDO_ACTION = "Undo"; +export const CHAT_RENAME_TITLE = "Rename chat"; +export const CHAT_RENAME_FIELD_LABEL = "Name"; +export const CHAT_RENAME_HELPER = + "The server has no rename for a chat, so this name is kept on this device."; +export const CHAT_RENAME_SAVE = "Save"; +export const CHAT_RENAME_DISMISS = "Cancel"; + +/** The empty override model: no local titles, nothing hidden. */ +export function emptyChatOverrides() { + return { titles: {}, hidden: [] }; +} + +/** The empty seen model: no watermarks, no explicit unseen marks. */ +export function emptyChatSeen() { + return { seenAt: {}, unseen: [] }; +} + +/** A positive finite epoch-millisecond value, else 0 (never NaN). */ +function millis(value) { + const number = Number(value); + return Number.isFinite(number) && number > 0 ? number : 0; +} + +/** + * Decode a stored overrides value. Blank text, `null`, corrupt JSON, an array and + * wrong-typed fields all fall back to the empty model; nothing here throws, so a + * bad preference can never break the list. + */ +export function decodeChatOverrides(stored) { + const empty = emptyChatOverrides(); + if (stored == null || stored === "") return empty; + let parsed = stored; + if (typeof stored === "string") { + if (stored.trim() === "") return empty; + try { + parsed = JSON.parse(stored); + } catch { + return empty; + } + } + if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty; + + const titles = {}; + const rawTitles = parsed.titles; + if (rawTitles != null) { + if (typeof rawTitles !== "object" || Array.isArray(rawTitles)) return empty; + for (const [id, title] of Object.entries(rawTitles)) { + if (isBlank(id) || typeof title !== "string" || isBlank(title)) continue; + titles[id] = title.trim(); + } + } + + const hidden = []; + const rawHidden = parsed.hidden; + if (rawHidden != null) { + if (!Array.isArray(rawHidden)) return empty; + for (const id of rawHidden) { + if (typeof id !== "string" || isBlank(id) || hidden.includes(id)) continue; + hidden.push(id); + } + } + return { titles, hidden }; +} + +/** The one-line JSON an overrides value is stored as. */ +export function encodeChatOverrides(overrides) { + return JSON.stringify({ + titles: { ...(overrides?.titles ?? {}) }, + hidden: [...(overrides?.hidden ?? [])], + }); +} + +/** + * Decode a stored seen value with the same tolerance as the overrides: blank, + * corrupt or wrong-typed input is nothing seen, never an exception. Unseen ids + * are de-duplicated. + */ +export function decodeChatSeen(stored) { + const empty = emptyChatSeen(); + if (stored == null || stored === "") return empty; + let parsed = stored; + if (typeof stored === "string") { + if (stored.trim() === "") return empty; + try { + parsed = JSON.parse(stored); + } catch { + return empty; + } + } + if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) return empty; + + const seenAt = {}; + const rawSeenAt = parsed.seenAt; + if (rawSeenAt != null) { + if (typeof rawSeenAt !== "object" || Array.isArray(rawSeenAt)) return empty; + for (const [id, value] of Object.entries(rawSeenAt)) { + const at = millis(value); + if (isBlank(id) || at <= 0) continue; + seenAt[id] = at; + } + } + + const unseen = []; + const rawUnseen = parsed.unseen; + if (rawUnseen != null) { + if (!Array.isArray(rawUnseen)) return empty; + for (const id of rawUnseen) { + if (typeof id !== "string" || isBlank(id) || unseen.includes(id)) continue; + unseen.push(id); + } + } + return { seenAt, unseen }; +} + +/** The one-line JSON a seen value is stored as. */ +export function encodeChatSeen(seen) { + return JSON.stringify({ + seenAt: { ...(seen?.seenAt ?? {}) }, + unseen: [...(seen?.unseen ?? [])], + }); +} + +/** + * Record a local rename. A blank id or a title that is blank after trimming + * changes nothing; a recorded title is trimmed, and it wins over the server's + * own on every later refresh. + */ +export function renameChatOverride(overrides, id, title) { + const current = overrides ?? emptyChatOverrides(); + const trimmed = str(title).trim(); + const key = str(id); + if (isBlank(key) || trimmed === "") return current; + if (current.titles?.[key] === trimmed) return current; + return { ...current, titles: { ...(current.titles ?? {}), [key]: trimmed } }; +} + +/** + * Hide a session on this device. A blank id or an already-hidden id changes + * nothing, and an id is never appended twice. + */ +export function hideChatOverride(overrides, id) { + const current = overrides ?? emptyChatOverrides(); + const key = str(id); + const hidden = current.hidden ?? []; + if (isBlank(key) || hidden.includes(key)) return current; + return { ...current, hidden: [...hidden, key] }; +} + +/** Restore a hidden session, undoing [hideChatOverride]. */ +export function restoreChatOverride(overrides, id) { + const current = overrides ?? emptyChatOverrides(); + const key = str(id); + const hidden = current.hidden ?? []; + if (!hidden.includes(key)) return current; + return { ...current, hidden: hidden.filter((entry) => entry !== key) }; +} + +/** + * The server's sessions with this device's overrides applied: hidden ids are + * removed (the set is built once, so each row is O(1)) and a local title replaces + * the server's. A blank/absent server title still falls through to + * `sessionTitle` at render time. + */ +export function applyChatOverrides(sessions, overrides) { + const list = Array.isArray(sessions) ? sessions : []; + const titles = overrides?.titles ?? {}; + const hiddenIds = new Set(overrides?.hidden ?? []); + if (hiddenIds.size === 0 && Object.keys(titles).length === 0) return list; + return list + .filter((session) => !hiddenIds.has(str(session?.id))) + .map((session) => { + const local = titles[str(session?.id)]; + return typeof local === "string" && local.trim() !== "" + ? { ...session, title: local.trim() } + : session; + }); +} + +/** The newest recency the operator has seen for [id], or 0 when never seen. */ +export function chatSeenWatermark(seen, id) { + const value = seen?.seenAt?.[str(id)]; + return millis(value); +} + +/** + * Record the first sight of every listed session, so a pre-existing chat is not + * reported as new activity. The active session is read (it is on screen); every + * other session is seeded only when it has no watermark yet and its recency is a + * real timestamp. An explicit unseen mark is never cleared by seeding. + */ +export function seedChatSeen(seen, sessions, activeId) { + let next = seen ?? emptyChatSeen(); + for (const session of Array.isArray(sessions) ? sessions : []) { + const id = str(session?.id); + const updatedAt = millis(session?.updated_at); + if (isBlank(id) || updatedAt <= 0) continue; + if (id === str(activeId)) { + next = readChatSeen(next, id, updatedAt); + } else if (chatSeenWatermark(next, id) === 0) { + next = { ...next, seenAt: { ...(next.seenAt ?? {}), [id]: updatedAt } }; + } + } + return next; +} + +/** + * Read [id] up to [updatedAt]: the watermark advances only when the value is + * strictly newer (a stale read can never rewind it) and any explicit unseen mark + * is cleared. A blank id changes nothing. + */ +export function readChatSeen(seen, id, updatedAt) { + const current = seen ?? emptyChatSeen(); + const key = str(id); + if (isBlank(key)) return current; + const at = millis(updatedAt); + const advanced = at > chatSeenWatermark(current, key); + const unseen = current.unseen ?? []; + const marked = unseen.includes(key); + if (!advanced && !marked) return current; + return { + seenAt: advanced ? { ...(current.seenAt ?? {}), [key]: at } : { ...(current.seenAt ?? {}) }, + unseen: marked ? unseen.filter((entry) => entry !== key) : [...unseen], + }; +} + +/** Mark [id] as moved on while it was not on screen; blank ids and duplicates no-op. */ +export function markChatUnseen(seen, id) { + const current = seen ?? emptyChatSeen(); + const key = str(id); + const unseen = current.unseen ?? []; + if (isBlank(key) || unseen.includes(key)) return current; + return { ...current, seenAt: { ...(current.seenAt ?? {}) }, unseen: [...unseen, key] }; +} + +/** + * The exact `ChatState.isUnseen` rule: a session is new only when it is not the + * active one and either an explicit unseen mark exists or it has never been + * opened here and its `updated_at` is strictly newer than the stored watermark. + */ +export function isChatSessionUnseen(session, { activeId = null, seen = null, opened = false } = {}) { + const id = str(session?.id); + if (isBlank(id) || id === str(activeId)) return false; + if ((seen?.unseen ?? []).includes(id)) return true; + if (opened) return false; + return millis(session?.updated_at) > chatSeenWatermark(seen, id); +} + + // --------------------------------------------------------------------------- // Session narrowing and grouping (ChatListFilter.kt) // --------------------------------------------------------------------------- diff --git a/web/styles.css b/web/styles.css index 89b47ead..1e7959e7 100644 --- a/web/styles.css +++ b/web/styles.css @@ -1434,6 +1434,11 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- --------------------------------------------------------------------------- */ .chat-list { display: flex; flex-direction: column; } +/* A row's Chat actions menu hangs below the button. `.list` clips its children + for the rounded corners, which cut the panel off at the list's bottom edge and + made the final rows' Hide/Rename items unclickable. Unclip only while a menu is + open, mirroring `.list.runs`' filter-menu treatment. */ +.chat-list.menu-open { overflow: visible; } .chat-search { flex: 1 1 auto; min-width: 0; } .chat-group-header { @@ -1457,10 +1462,67 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- .chat-row .row-meta { grid-column: 1; } .chat-row-actions { grid-column: 2; grid-row: 1 / span 2; align-self: center; } .chat-row-actions button { padding: 3px 10px; font-size: 12px; } -.chat-close { border-color: var(--warn); color: var(--warn); } -.chat-reopen { border-color: var(--accent); color: var(--accent); } +.chat-menu-wrap { position: relative; } +.chat-menu-button { min-width: 30px; font-size: 15px; line-height: 1; } +.chat-menu-panel { + position: absolute; + top: calc(100% + 4px); + right: 0; + z-index: 25; + display: grid; + min-width: 190px; + padding: 4px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 10px; + box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5); +} +.chat-menu-item { + justify-content: flex-start; + padding: 7px 10px; + text-align: left; + font-size: 13px; + border: none; + white-space: nowrap; +} +.chat-menu-item:hover { background: var(--surface); } +.chat-menu-close { color: var(--warn); } +.chat-menu-reopen { color: var(--accent); } .chat-closed-chip { opacity: 0.8; } +/* The Rename chat dialog (C13): a name kept on this device only. */ +.chat-rename-field { display: grid; gap: 4px; } +.chat-rename-label { font-size: 12px; color: var(--muted); } +.chat-rename-helper { margin: 0; line-height: 1.5; font-size: 13px; color: var(--muted); } +.chat-rename-save:disabled { opacity: 0.5; } + +/* The one hide report (C13): fixed above the pane, replaced rather than queued. */ +.chat-snackbar { + position: fixed; + left: 50%; + bottom: 20px; + z-index: 35; + transform: translateX(-50%); + display: flex; + gap: 16px; + align-items: center; + max-width: min(560px, calc(100vw - 32px)); + padding: 12px 16px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 10px; + box-shadow: 0 16px 40px rgba(0, 0, 0, 0.55); + font-size: 13px; +} +.chat-snackbar-message { line-height: 1.4; } +.chat-snackbar-undo { + flex: none; + border-color: var(--accent); + color: var(--accent); + font-weight: 600; + font-size: 13px; +} + .chat-activity { display: inline-flex; align-items: center; gap: 5px; font-size: 11px; color: var(--muted); } .chat-activity-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; } .chat-activity-streaming { color: var(--accent); } diff --git a/web/test/chat.test.mjs b/web/test/chat.test.mjs index fc252ab3..8764c29e 100644 --- a/web/test/chat.test.mjs +++ b/web/test/chat.test.mjs @@ -7,10 +7,20 @@ import assert from "node:assert/strict"; import { BACKGROUND_TASKS_TITLE, BACKGROUND_TASK_VISIBLE_ROWS, + CHAT_ACTIONS_LABEL, CHAT_COMMANDS, CHAT_COMMAND_GLYPH, CHAT_FOLLOW_THRESHOLD_PX, + CHAT_HIDE_ACTION, CHAT_QUEUED_NOTICE, + CHAT_REMOVED_MESSAGE, + CHAT_RENAME_ACTION, + CHAT_RENAME_DISMISS, + CHAT_RENAME_FIELD_LABEL, + CHAT_RENAME_HELPER, + CHAT_RENAME_SAVE, + CHAT_RENAME_TITLE, + CHAT_UNDO_ACTION, COMPOSER_SEND, COMPOSER_STOP, ChatTurn, @@ -49,6 +59,7 @@ import { TURN_PHASE_WAITING, TURN_THINKING_WINDOW_MILLIS, applyChatEvent, + applyChatOverrides, applyChatPermission, approvalCard, approvalResources, @@ -67,6 +78,7 @@ import { chatHeaderMeta, chatNoMatchMessage, chatOpensAtNewest, + chatSeenWatermark, chatShowJumpToLatest, chatStreamState, closeChatConfirmation, @@ -75,13 +87,22 @@ import { composerSendEnabled, composerSubmit, decisionLabel, + decodeChatOverrides, + decodeChatSeen, deltaPartId, directoryLabel, + emptyChatOverrides, + emptyChatSeen, + encodeChatOverrides, + encodeChatSeen, filterSessions, formatToolDuration, groupSessionsByDirectory, + hideChatOverride, historyResync, + isChatSessionUnseen, lineDiff, + markChatUnseen, mergeHistoryPage, mergeShellFrame, mergeToolPart, @@ -91,12 +112,16 @@ import { permissionRiskText, prettyToolInput, queuedAfterFrame, + readChatSeen, reasoningLabel, + renameChatOverride, + restoreChatOverride, resumedThread, runningAfterFrame, runningBackgroundShells, runningToolElapsedMillis, runningToolStamps, + seedChatSeen, sessionActivity, sessionActivityBadge, sessionChipLabel, @@ -1507,3 +1532,169 @@ test("a step that ends does not clear a background shell that outlives the turn" assert.equal(resumed.selectedShellId, null); assert.equal(resumed.shellOutput, null); }); + +// --------------------------------------------------------------------------- +// C13: the local overrides and the seen state (ChatOverrides.kt / ChatSeen.kt) +// --------------------------------------------------------------------------- + +const sess = (id, title, updated_at) => ({ id, title, updated_at }); + +test("local overrides: a local title wins on every refresh, trimmed, blanks ignored", () => { + const sessions = [sess("a", "Server A", 100), sess("b", "Server B", 200)]; + + // No overrides: the server's own list is returned untouched. + assert.equal(applyChatOverrides(sessions, emptyChatOverrides()), sessions); + + let overrides = renameChatOverride(emptyChatOverrides(), "a", " My A "); + assert.deepEqual(overrides.titles, { a: "My A" }); + const applied = applyChatOverrides(sessions, overrides); + assert.equal(applied[0].title, "My A"); + assert.equal(applied[1].title, "Server B"); + // A later refresh (the server's own title still "Server A") keeps the local name. + assert.equal(applyChatOverrides(sessions, overrides)[0].title, "My A"); + + // A blank id or a blank/whitespace title changes nothing (identity preserved). + assert.equal(renameChatOverride(overrides, "a", " "), overrides); + assert.equal(renameChatOverride(overrides, " ", "Nope"), overrides); + // A rename for another id is recorded without touching the first. + const both = renameChatOverride(overrides, "b", "Bee"); + assert.deepEqual(both.titles, { a: "My A", b: "Bee" }); + assert.equal(applyChatOverrides(sessions, both)[1].title, "Bee"); + // Re-recording the same trimmed title is a no-op (same object). + assert.equal(renameChatOverride(both, "b", " Bee "), both); +}); + +test("hide + undo: one entry per id, blank ignored, restore returns the prior state", () => { + const overrides = emptyChatOverrides(); + const hidden = hideChatOverride(overrides, "s1"); + assert.deepEqual(hidden.hidden, ["s1"]); + // Already hidden: nothing changes, and no duplicate is appended. + assert.equal(hideChatOverride(hidden, "s1"), hidden); + assert.equal(hideChatOverride(hidden, " "), hidden); + + const sessions = [sess("s1", "One", 1), sess("s2", "Two", 2)]; + assert.deepEqual(applyChatOverrides(sessions, hidden).map((s) => s.id), ["s2"]); + + const restored = restoreChatOverride(hidden, "s1"); + assert.deepEqual(restored.hidden, []); + assert.deepEqual(applyChatOverrides(sessions, restored).map((s) => s.id), ["s1", "s2"]); + // Restoring something that was never hidden changes nothing. + assert.equal(restoreChatOverride(restored, "s9"), restored); + // Hide then undo returns the original model. + assert.deepEqual(restoreChatOverride(hideChatOverride(overrides, "s1"), "s1"), overrides); +}); + +test("overrides JSON round-trips, and unreadable/wrong-typed input decodes to empty", () => { + const overrides = renameChatOverride(hideChatOverride(emptyChatOverrides(), "gone"), "kept", "Name"); + assert.deepEqual(decodeChatOverrides(encodeChatOverrides(overrides)), overrides); + + for (const corrupt of [null, "", "not json", "{", "[]", '"x"', "42"]) { + assert.deepEqual(decodeChatOverrides(corrupt), emptyChatOverrides()); + } + // Wrong-typed fields fall back to the empty model rather than throwing. + assert.deepEqual(decodeChatOverrides('{"titles":[],"hidden":"x"}'), emptyChatOverrides()); + assert.deepEqual(decodeChatOverrides('{"titles":{"a":3},"hidden":[7,"ok","ok"]}').hidden, ["ok"]); + assert.deepEqual(decodeChatOverrides('{"titles":{"":"x","b":" B "}}'), { titles: { b: "B" }, hidden: [] }); +}); + +test("seen JSON round-trips, de-duplicates unseen, and tolerates corrupt input", () => { + let seen = markChatUnseen(emptyChatSeen(), "s1"); + seen = markChatUnseen(seen, "s1"); // duplicate + seen = readChatSeen(seen, "s2", 500); + const decoded = decodeChatSeen(encodeChatSeen(seen)); + assert.deepEqual(decoded.seenAt, { s2: 500 }); + assert.deepEqual(decoded.unseen, ["s1"]); + + for (const corrupt of [null, "", "not json", "{", "[]", "true"]) { + assert.deepEqual(decodeChatSeen(corrupt), emptyChatSeen()); + } + assert.deepEqual(decodeChatSeen('{"seenAt":[],"unseen":"x"}'), emptyChatSeen()); + const tolerated = decodeChatSeen('{"seenAt":{"a":10,"b":"x","":5},"unseen":["u","u",""]}'); + assert.deepEqual(tolerated.seenAt, { a: 10 }); + assert.deepEqual(tolerated.unseen, ["u"]); +}); + +test("first sight seeding: a baseline is set once and never clears an explicit unseen", () => { + const sessions = [sess("a", "A", 100), sess("b", "B", 0)]; + const seeded = seedChatSeen(emptyChatSeen(), sessions, null); + assert.deepEqual(seeded.seenAt, { a: 100 }); + // An absent or zero recency is never recorded. + assert.equal(seeded.seenAt.b, undefined); + // A later, higher recency is not re-seeded over the existing baseline. + const later = seedChatSeen(seeded, [sess("a", "A", 300)], null); + assert.deepEqual(later.seenAt, { a: 100 }); + + // Seeding never clears an unseen mark. + const marked = markChatUnseen(seeded, "a"); + const reseeded = seedChatSeen(marked, [sess("a", "A", 400)], null); + assert.deepEqual(reseeded.unseen, ["a"]); + + // The active session is read (watermark advances, the mark clears). + const active = seedChatSeen(markChatUnseen(emptyChatSeen(), "a"), [sess("a", "A", 900)], "a"); + assert.deepEqual(active.seenAt, { a: 900 }); + assert.deepEqual(active.unseen, []); +}); + +test("reading advances the watermark monotonically and always clears the mark", () => { + const first = readChatSeen(emptyChatSeen(), "s", 100); + assert.equal(chatSeenWatermark(first, "s"), 100); + // A stale read cannot rewind it... + assert.equal(readChatSeen(first, "s", 50), first); + // ...an equal read is not "newer" either... + assert.equal(readChatSeen(first, "s", 100), first); + // ...but a strictly newer one advances. + assert.equal(chatSeenWatermark(readChatSeen(first, "s", 101), "s"), 101); + + // A mark is cleared even when the recency does not advance. + const marked = markChatUnseen(first, "s"); + const read = readChatSeen(marked, "s", 100); + assert.deepEqual(read.unseen, []); + assert.equal(read.seenAt.s, 100); + // A blank id is a no-op. + assert.equal(readChatSeen(first, " ", 500), first); +}); + +test("the unseen rule: not active, explicit mark or never-opened-and-strictly-newer", () => { + let seen = readChatSeen(emptyChatSeen(), "opened", 100); + seen = readChatSeen(seen, "equal", 100); + // A watermark ahead of the session's own recency: not newer, so not new. + seen = readChatSeen(seen, "old", 120); + const opened = sess("opened", "Opened", 200); // moved on after it was read + const fresh = sess("fresh", "Fresh", 150); + const equal = sess("equal", "Equal", 100); + const old = sess("old", "Old", 50); + + // The active session is never new, even with an explicit mark. + assert.equal( + isChatSessionUnseen(opened, { activeId: "opened", seen: markChatUnseen(seen, "opened"), opened: true }), + false, + ); + // A never-opened session is new only while strictly newer than the watermark. + assert.equal(isChatSessionUnseen(fresh, { seen, opened: false }), true); + assert.equal(isChatSessionUnseen(equal, { seen, opened: false }), false); + assert.equal(isChatSessionUnseen(old, { seen, opened: false }), false); + // A session already opened here is judged by the explicit mark alone. + assert.equal(isChatSessionUnseen(opened, { seen, opened: true }), false); + assert.equal(isChatSessionUnseen(opened, { seen: markChatUnseen(seen, "opened"), opened: true }), true); +}); + +test("the C13 wording matches the Android sources verbatim", () => { + assert.equal(CHAT_RENAME_ACTION, "Rename…"); + assert.equal(CHAT_HIDE_ACTION, "Hide on this device"); + assert.equal(CHAT_ACTIONS_LABEL, "Chat actions"); + assert.equal(CHAT_REMOVED_MESSAGE, "Hidden on this device; the chat stays on the server."); + assert.equal(CHAT_UNDO_ACTION, "Undo"); + assert.equal(CHAT_RENAME_TITLE, "Rename chat"); + assert.equal(CHAT_RENAME_FIELD_LABEL, "Name"); + assert.equal( + CHAT_RENAME_HELPER, + "The server has no rename for a chat, so this name is kept on this device.", + ); + assert.equal(CHAT_RENAME_SAVE, "Save"); + assert.equal(CHAT_RENAME_DISMISS, "Cancel"); + // The badge precedence words, with Open only while the conversation is open. + assert.equal(sessionActivityBadge(sessionActivity(true, true), true), "Streaming"); + assert.equal(sessionActivityBadge(sessionActivity(false, true), true), "New"); + assert.equal(sessionActivityBadge(sessionActivity(false, false), true), "Open"); + assert.equal(sessionActivityBadge(sessionActivity(false, false), false), null); +}); diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index f63d79c8..d5b984ea 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -145,6 +145,16 @@ async function openRunDetail(runId) { } } +// Open one chat row's Chat actions menu (the row's management items live behind +// it since C13: Rename… / Close chat… or Reopen / Hide on this device). +async function openChatRowMenu(sessionId) { + await page.click(`#chatRows .chat-row[data-session="${sessionId}"] .chat-menu-button`); + await page.waitForSelector( + `#chatRows .chat-row[data-session="${sessionId}"] .chat-menu-panel`, + { timeout: 10000 }, + ); +} + // --- P5: create a pipeline from a template (scratch server only) ----------- // The scratch server has no real runs and no live chat, so this is the whole // point of a `--scratch` run. It opens a template, opens the create action, @@ -2370,7 +2380,8 @@ try { title: row.querySelector(".chat-row-title")?.textContent ?? "", chips: [...row.querySelectorAll(".chip")].map((chip) => chip.textContent), meta: row.querySelector(".chat-row-meta")?.textContent ?? "", - close: !!row.querySelector(".chat-close"), + menu: !!row.querySelector(".chat-menu-button"), + menuLabel: row.querySelector(".chat-menu-button")?.getAttribute("aria-label") ?? "", })), }))()`); if (chatList.label !== "Search chats") throw new Error(`chat search label: ${chatList.label}`); @@ -2380,7 +2391,9 @@ try { if (!chatList.rows[0].chips.includes("Operator")) { throw new Error(`chat kind chip: ${chatList.rows[0].chips.join(", ")}`); } - if (!chatList.rows[0].close) throw new Error("the open chat row offers no Close chat action"); + if (!chatList.rows[0].menu || chatList.rows[0].menuLabel !== "Chat actions") { + throw new Error(`the open chat row's Chat actions menu: ${JSON.stringify(chatList.rows[0])}`); + } console.log( ` chat list: ${chatList.rows.length} session(s); "${chatList.rows[0].title}" ` + `[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}`, @@ -2388,9 +2401,11 @@ try { await shot("44-chat-sessions.png"); // The row's own Close chat… action with NO conversation open: the list offers - // it on every open row, so the confirm must still appear. Shown and dismissed - // with Cancel; no chat_close is ever sent for the operator's live session. - await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-close`); + // it on every open row (behind the Chat actions menu), so the confirm must + // still appear. Shown and dismissed with Cancel; no chat_close is ever sent for + // the operator's live session. + await openChatRowMenu(chatList.rows[0].id); + await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-menu-close`); await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); const listClose = await page.evaluate( `document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`, @@ -2430,6 +2445,12 @@ try { const candidates = [ ...new Set([...(preferred ? [preferred.id] : []), ...openRows, ...chatList.rows.map((r) => r.id)]), ]; + // Record the frames the page sends from before the first genuine open. With + // more than one row the test switches away and re-opens, so the assertion below + // sees that fresh open; with a server that lists only one session the first + // click is itself the fresh open (clicking it again would early-return), and + // clearing here would throw that real request away. + await page.evaluate(`(() => { window.__pipelinesSentTypes = []; return true; })()`); let openedId = null; for (const candidate of candidates) { await page.click(`#chatRows .chat-row[data-session="${candidate}"]`); @@ -2450,15 +2471,17 @@ try { } // Leave the discovered session first: the loop above already opened it, and // openChatSession keeps a loaded thread, so clicking it again would early-return - // and send nothing. Opening a different row restores a genuine fresh open. + // and send nothing. Opening a different row restores a genuine fresh open. With + // only one listed session there is no other row, so the loop's own open above is + // the fresh-open proof. const otherRow = candidates.find((id) => id !== openedId); if (otherRow) { await page.click(`#chatRows .chat-row[data-session="${otherRow}"]`); await new Promise((resolve) => setTimeout(resolve, 600)); + await page.evaluate(`(() => { window.__pipelinesSentTypes = []; return true; })()`); + } else { + console.log(" -- the server lists one session, so the first open above is the fresh-open proof"); } - // Record the frames the page sends, so the C11 chat_shells fetch on open is - // asserted rather than assumed. - await page.evaluate(`(() => { window.__pipelinesSentTypes = []; return true; })()`); await page.click(`#chatRows .chat-row[data-session="${openedId}"]`); await page.waitForSelector("#chatTranscript", { timeout: 25000 }); await eventually( @@ -2932,7 +2955,8 @@ try { if (!beforeDialog || beforeDialog.top == null || beforeDialog.top === 0) { throw new Error(`the transcript was not mid-scroll before the dialog: ${JSON.stringify(beforeDialog)}`); } - await page.click(`#chatRows .chat-row[data-session="${openedId}"] .chat-close`); + await openChatRowMenu(openedId); + await page.click(`#chatRows .chat-row[data-session="${openedId}"] .chat-menu-close`); await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); const closeDialog = await page.evaluate(`(() => ({ title: document.querySelector(".confirm-chat-close .confirm-title")?.textContent ?? "", @@ -2998,7 +3022,36 @@ try { await ensureConnected(); await page.waitForSelector("#chatInput", { timeout: 15000 }); - // (a) A draft: the placeholder, Send present and enabled, Stop absent. + // (a) `/new` creates a fresh throwaway session (C2's chat_create, sent directly + // 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"); const draftState = await page.evaluate(`(() => ({ placeholder: document.querySelector("#chatInput")?.getAttribute("placeholder") ?? "", @@ -3195,33 +3248,9 @@ 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. - 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"); - + // (f) The throwaway created at the start is still open and idle (the palette, + // notice and attachment probes above never submitted anything). Prompt it for + // the real running-turn state; the operator's session is left untouched. // 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( @@ -3288,15 +3317,31 @@ try { ), { timeout: 15000, what: "the throwaway session to show as closed" }, ); + await openChatRowMenu(throwawayId); const closedRow = await page.evaluate(`(() => { const row = document.querySelector('.chat-row[data-session="${throwawayId}"]'); row?.scrollIntoView({ block: "center" }); return { closed: !!row?.querySelector(".chat-closed-chip"), - hasClose: !!row?.querySelector(".chat-close"), - hasReopen: !!row?.querySelector(".chat-reopen"), + items: [...row.querySelectorAll(".chat-menu-panel .chat-menu-item")].map((b) => b.textContent), + hasClose: !!row?.querySelector(".chat-menu-close"), + hasReopen: !!row?.querySelector(".chat-menu-reopen"), }; })()`); + if (!closedRow.closed || !closedRow.hasReopen || closedRow.hasClose) { + throw new Error(`the closed row's Chat actions menu: ${JSON.stringify(closedRow)}`); + } + if (closedRow.items.join("|") !== "Rename…|Reopen|Hide on this device") { + throw new Error(`the closed row's menu items and order: ${JSON.stringify(closedRow.items)}`); + } + // Close the menu again (a second press on its own button toggles it shut). + await page.evaluate( + `document.querySelector('.chat-row[data-session="${throwawayId}"] .chat-menu-button')?.click()`, + ); + await eventually( + () => page.evaluate(`!document.querySelector('.chat-row[data-session="${throwawayId}"] .chat-menu-panel')`), + { timeout: 5000, what: "the closed row's menu to close" }, + ); // Closing finishes the session: the conversation leaves the pane (back to the // list with the select hint) and no row stays selected, as Android's // finishSession does. @@ -4684,6 +4729,284 @@ try { ); console.log(" chat_shells re-fetched after the stream reconnect (real request)"); + // C13: this device's own chat changes — a local rename that wins over the + // server's title, the hide + Undo report, and the seen/New marker. Every + // action here is device-local (localStorage): nothing is sent to the server for + // a rename or a hide, and the closed throwaway session from C8 is the row used + // for the rename/hide captures so the operator's live session is never hidden + // in a way the run leaves behind (Hide is undone before the marker step). + step("C13: local rename/hide, the hide snackbar and the seen/New marker"); + await ensureConnected(); + await page.evaluate(`(() => { + const tab = [...document.querySelectorAll("nav.tabs button.tab")].find((b) => b.textContent.trim() === "Chat"); + if (tab) tab.click(); + return !!tab; + })()`); + await page.waitForSelector("#chatRows .chat-row", { timeout: 25000 }); + + // (a) Rename… opens the dialog: its exact title, the field label, the pre-fill + // and the helper, and Save disabled while the trimmed value is blank. + await openChatRowMenu(throwawayId); + await page.click(`#chatRows .chat-row[data-session="${throwawayId}"] .chat-menu-rename`); + await page.waitForSelector(".confirm-chat-rename", { timeout: 10000 }); + await page.waitForSelector("#chatRenameInput", { timeout: 5000 }); + const renameDialog = await page.evaluate(`(() => ({ + title: document.querySelector(".confirm-chat-rename .confirm-title")?.textContent ?? "", + label: document.querySelector(".confirm-chat-rename .chat-rename-label")?.textContent ?? "", + value: document.querySelector("#chatRenameInput")?.value ?? null, + helper: document.querySelector(".confirm-chat-rename .chat-rename-helper")?.textContent ?? "", + save: document.querySelector(".chat-rename-save")?.textContent ?? "", + cancel: document.querySelector(".chat-rename-cancel")?.textContent ?? "", + }))()`); + if (renameDialog.title !== "Rename chat") throw new Error(`rename title: ${renameDialog.title}`); + if (renameDialog.label !== "Name") throw new Error(`rename field label: ${renameDialog.label}`); + if (renameDialog.value !== "New chat") throw new Error(`rename pre-fill: ${JSON.stringify(renameDialog.value)}`); + if ( + renameDialog.helper !== + "The server has no rename for a chat, so this name is kept on this device." + ) { + throw new Error(`rename helper: ${renameDialog.helper}`); + } + if (renameDialog.save !== "Save" || renameDialog.cancel !== "Cancel") { + throw new Error(`rename buttons: ${JSON.stringify(renameDialog)}`); + } + // Typing toggles Save in place: blank (whitespace) disables it, a real value + // enables it, with no re-render of the transcript underneath. + await page.fill("#chatRenameInput", " "); + await eventually( + () => page.evaluate(`document.querySelector(".chat-rename-save")?.disabled === true`), + { timeout: 5000, what: "Save to disable while the name is blank" }, + ); + console.log(` rename dialog: "${renameDialog.title}" / "${renameDialog.label}" pre-filled "${renameDialog.value}"; Save disabled while blank`); + await shot("72-chat-rename-dialog.png"); + + // (b) Save a locally-titled name; the row shows it now and after a server list + // refresh, and the overrides JSON is in localStorage under its own key. + await page.fill("#chatRenameInput", "Local capture chat"); + await eventually( + () => page.evaluate(`document.querySelector(".chat-rename-save")?.disabled === false`), + { timeout: 5000, what: "Save to enable for a non-blank name" }, + ); + await page.click(".chat-rename-save"); + await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-rename")`), { + timeout: 5000, + what: "the rename dialog to close on Save", + }); + const renamedTitle = await eventually( + async () => { + const value = await page.evaluate( + `document.querySelector('.chat-row[data-session="${throwawayId}"] .chat-row-title')?.textContent ?? ""`, + ); + return value === "Local capture chat" ? value : false; + }, + { timeout: 8000, what: "the renamed row to show its local title" }, + ); + console.log(` row ${throwawayId} shows the local title "${renamedTitle}"`); + // Refresh the list from the server (the same header Refresh the page offers); + // the local title must still win over the server's own. + await page.clickText("nav.tabs button.ghost", "Refresh"); + await eventually( + () => + page.evaluate( + `document.querySelector('.chat-row[data-session="${throwawayId}"] .chat-row-title')?.textContent === "Local capture chat"`, + ), + { timeout: 15000, what: "the local title to survive a server list refresh" }, + ); + const storedOverrides = await page.evaluate(`localStorage.getItem("pipelines.web.chatOverrides.v1")`); + const overridesJson = JSON.parse(storedOverrides ?? "{}"); + if (overridesJson.titles?.[throwawayId] !== "Local capture chat") { + throw new Error(`the local title was not persisted: ${storedOverrides}`); + } + console.log(` after a server list refresh the row still reads "${renamedTitle}"; localStorage ${storedOverrides}`); + await shot("73-chat-renamed-row.png"); + + // The final row's menu must not be clipped by the list's rounded-corner + // overflow: assert the Hide item's own centre is the element a real click + // would hit (the review measured the panel cut off at the list's bottom edge + // on the last rows). The menu is closed again without acting on it. + const lastRowId = await page.evaluate( + `(() => { const rows = [...document.querySelectorAll("#chatRows .chat-row")]; return rows.at(-1)?.dataset.session ?? ""; })()`, + ); + if (!lastRowId) throw new Error("C13: no last row to test the menu against"); + await page.evaluate(`document.querySelector('.chat-row[data-session="${lastRowId}"]')?.scrollIntoView({ block: "center" })`); + await openChatRowMenu(lastRowId); + const lastMenuHit = await page.evaluate(`(() => { + const button = document.querySelector('.chat-row[data-session="${lastRowId}"] .chat-menu-hide'); + if (!button) return { found: false }; + const rect = button.getBoundingClientRect(); + const x = rect.left + rect.width / 2; + const y = rect.top + rect.height / 2; + const hit = document.elementFromPoint(x, y); + return { + found: true, + label: button.textContent, + hit: hit === button || button.contains(hit), + rect: { top: rect.top, bottom: rect.bottom }, + viewport: window.innerHeight, + listBottom: document.querySelector(".chat-list")?.getBoundingClientRect().bottom ?? null, + }; + })()`); + if (!lastMenuHit.found || !lastMenuHit.hit) { + throw new Error(`C13: the last row's menu item is not clickable: ${JSON.stringify(lastMenuHit)}`); + } + console.log( + ` last row ${lastRowId}: "${lastMenuHit.label}" is hit-testable at its centre (menu bottom ${Math.round(lastMenuHit.rect.bottom)}, viewport ${lastMenuHit.viewport})`, + ); + await page.click(`#chatRows .chat-row[data-session="${lastRowId}"] .chat-menu-button`); + await eventually( + () => page.evaluate(`!document.querySelector('.chat-row[data-session="${lastRowId}"] .chat-menu-panel')`), + { timeout: 5000, what: "the last row's menu to close again" }, + ); + + // (c) Hide the row the conversation is open on: it disappears, its conversation + // closes, and one snackbar carries the exact message and Undo. Undo puts the + // row back and leaves the server untouched. + const activeBeforeHide = await page.evaluate( + `document.querySelector(".chat-row.selected")?.dataset.session ?? ""`, + ); + if (!activeBeforeHide) throw new Error("C13: no conversation was open before the hide"); + await openChatRowMenu(activeBeforeHide); + await page.click(`#chatRows .chat-row[data-session="${activeBeforeHide}"] .chat-menu-hide`); + await page.waitForSelector(".chat-snackbar", { timeout: 10000 }); + const hiddenState = await page.evaluate(`(() => ({ + row: !!document.querySelector('.chat-row[data-session="${activeBeforeHide}"]'), + snackbars: document.querySelectorAll(".chat-snackbar").length, + message: document.querySelector(".chat-snackbar-message")?.textContent ?? "", + undo: document.querySelector(".chat-snackbar-undo")?.textContent ?? "", + hint: document.querySelector(".chat-detail .empty .muted")?.textContent ?? "", + composer: !!document.querySelector("#chatComposer"), + hidden: JSON.parse(localStorage.getItem("pipelines.web.chatOverrides.v1") ?? "{}").hidden ?? [], + }))()`); + if (hiddenState.row) throw new Error(`C13: the hidden row is still listed: ${JSON.stringify(hiddenState)}`); + if (hiddenState.snackbars !== 1) throw new Error(`C13: expected one snackbar, got ${hiddenState.snackbars}`); + if (hiddenState.message !== "Hidden on this device; the chat stays on the server.") { + throw new Error(`C13: snackbar message ${JSON.stringify(hiddenState.message)}`); + } + if (hiddenState.undo !== "Undo") throw new Error(`C13: snackbar action ${JSON.stringify(hiddenState.undo)}`); + if (hiddenState.composer || hiddenState.hint !== "Select a chat to open it.") { + throw new Error(`C13: hiding the open conversation did not close it: ${JSON.stringify(hiddenState)}`); + } + if (!hiddenState.hidden.includes(activeBeforeHide)) { + throw new Error(`C13: the hidden id was not persisted: ${JSON.stringify(hiddenState.hidden)}`); + } + console.log( + ` hid ${activeBeforeHide}: row gone, conversation closed, one snackbar "${hiddenState.message}" with "${hiddenState.undo}"`, + ); + await shot("74-chat-hide-snackbar.png"); + + // Undo restores the row (and only here: the conversation stays closed, exactly + // as Android's undoRemove does) and clears the hidden list. + await page.click(".chat-snackbar-undo"); + await eventually( + () => + page.evaluate( + `!!document.querySelector('.chat-row[data-session="${activeBeforeHide}"]') && !document.querySelector(".chat-snackbar")`, + ), + { timeout: 8000, what: "Undo to restore the hidden row and clear the snackbar" }, + ); + const afterUndo = await page.evaluate( + `JSON.parse(localStorage.getItem("pipelines.web.chatOverrides.v1") ?? "{}").hidden ?? []`, + ); + if (afterUndo.includes(activeBeforeHide)) { + throw new Error(`C13: Undo left the id hidden: ${JSON.stringify(afterUndo)}`); + } + console.log(` Undo restored ${activeBeforeHide}; hidden ids now ${JSON.stringify(afterUndo)}`); + + // (d) The "New" marker, honestly: the restart rule. A fresh throwaway is + // prompted and stopped, and the page is then reloaded — its threads are empty + // while the persisted watermark predates the turn, so the non-active row reads + // New after the reconnect. First reopen the operator conversation so `/new` + // has a directory. + await page.evaluate(`document.querySelector('.chat-row[data-session="${sessionId}"]')?.click()`); + await page.waitForSelector("#chatTranscript", { timeout: 20000 }); + await page.fill("#chatInput", "/new"); + await page.evaluate( + `document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, + ); + const newMarkerId = await eventually( + async () => { + const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`); + return id && id !== sessionId && id !== throwawayId ? id : false; + }, + { timeout: 25000, what: "the fresh throwaway session to open for the New-marker step" }, + ); + await page.waitForSelector("#chatInput", { timeout: 10000 }); + // The watermark for this session is seeded at its creation recency; a real + // prompt then advances the server's updated_at past it. + await page.fill("#chatInput", "Reply with exactly one word: hi"); + await page.evaluate( + `document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, + ); + await page.waitForSelector("#chatStop", { timeout: 20000 }); + await page.click("#chatStop"); + await eventually( + () => + page.evaluate( + `[...document.querySelectorAll(".chat-command-notice-text")].some((n) => n.textContent === "Stopping the running turn…")`, + ), + { timeout: 15000, what: "the New-marker throwaway turn to be interrupted" }, + ); + const watermarkBefore = await page.evaluate( + `JSON.parse(localStorage.getItem("pipelines.web.chatSeen.v1") ?? "{}").seenAt?.[${JSON.stringify(newMarkerId)}] ?? 0`, + ); + // A reload empties the page's threads and re-reads the server list: the row is + // no longer active, and its server recency has moved past the stored watermark. + await page.evaluate(`location.reload()`); + await page.waitForSelector("#url", { timeout: 15000 }); + // A reload starts idle: open the configured endpoint through the header's own + // control (the same connect-only path the Settings destination uses). + await page.evaluate(`(() => { + const control = document.querySelector("#reconnectBtn") || document.querySelector("#connectBtn"); + if (control) control.click(); + return !!control; + })()`); + await ensureConnected(30000); + await page.clickText("nav.tabs button.tab", "Chat"); + await page.waitForSelector("#chatRows .chat-row", { timeout: 25000 }); + const newMarker = await eventually( + async () => { + const value = await page.evaluate(`(() => { + const row = document.querySelector('.chat-row[data-session="${newMarkerId}"]'); + const word = row?.querySelector(".chat-activity-new .chat-activity-word")?.textContent ?? ""; + return { word, selected: !!row?.classList.contains("selected") }; + })()`); + return value.word === "New" ? value : false; + }, + { timeout: 15000, what: "the non-active row to carry the New marker after the reload" }, + ); + const watermarkAfter = await page.evaluate( + `JSON.parse(localStorage.getItem("pipelines.web.chatSeen.v1") ?? "{}").seenAt?.[${JSON.stringify(newMarkerId)}] ?? 0`, + ); + console.log( + ` after the reload, non-active ${newMarkerId} carries the New marker ` + + `(watermark before the turn ${watermarkBefore}, after the reload ${watermarkAfter})`, + ); + await shot("75-chat-new-marker.png"); + + // Cleanup: open the New-marker throwaway and /close it, so the run leaves no + // open session of its own (the rename override on the earlier throwaway is + // device-local and the browser profile is temporary). + await page.evaluate(`document.querySelector('.chat-row[data-session="${newMarkerId}"]')?.click()`); + await page.waitForSelector("#chatInput", { timeout: 20000 }); + await page.fill("#chatInput", "/close"); + await page.evaluate( + `document.querySelector("#chatInput").dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }))`, + ); + await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); + await page.click(".confirm-chat-close .confirm-accept"); + await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), { + timeout: 15000, + what: "the New-marker throwaway to close", + }); + await eventually( + () => + page.evaluate( + `!!document.querySelector('.chat-row[data-session="${newMarkerId}"] .chat-closed-chip')`, + ), + { timeout: 15000, what: "the New-marker throwaway to show as closed" }, + ); + console.log(` cleanup: /close closed the New-marker throwaway ${newMarkerId}`); + console.log("\nUI SMOKE PASS"); for (const shot of shots) console.log(` ${shot}`); } From 878b1e0bf3630b93e2174303d4487296e90c5df7 Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 14:11:31 +0100 Subject: [PATCH 6/8] web: notify failed and waiting runs from the browser Notification API (L5) --- web/PARITY.md | 2 +- web/src/app.js | 181 +++++++++++++++++++- web/src/notify.js | 315 +++++++++++++++++++++++++++++++++++ web/src/protocol.js | 8 + web/src/repository.js | 18 ++ web/styles.css | 13 ++ web/test/notify.test.mjs | 214 ++++++++++++++++++++++++ web/test/repository.test.mjs | 24 +++ web/test/ui-smoke.mjs | 235 +++++++++++++++++++++++++- 9 files changed, 1007 insertions(+), 3 deletions(-) create mode 100644 web/src/notify.js create mode 100644 web/test/notify.test.mjs diff --git a/web/PARITY.md b/web/PARITY.md index aafa0796..18afb253 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -146,7 +146,7 @@ delete command). | L2 | Wide layout: left rail + two panes | client-side | todo | | L3 | Narrow layout: bottom section strip + bottom navigation | client-side | todo | | L4 | Responsive switch by viewport width (no hardcoded device) | `WindowSize.kt` analogue | todo | -| L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived | todo | +| L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived from `subscribe` / `run_event` | **partial** — the browser notification path is implemented and captured in Settings, but **no real OS notification was observed**, so the row is not `done`. The exact reason: headless Chrome cannot reliably show or capture an OS notification; the smoke stubs and records the `Notification` constructor, while the transition decisions run through the page's real socket `onmessage`/`frame` path. Pure logic lives in `src/notify.js` and mirrors `notify/RunAlerts.kt` + `ui/Attention.kt`: only a run becoming `failed` (headline `A run failed`) or `waiting` (headline `A run needs your decision`) notifies; `queued`, `running`, `succeeded`, `canceled`, `interrupted` and unknown statuses never do. Body is the attention label (trimmed title else pipeline) then ` · {pipeline}`, with no separator when the pipeline is blank or equal; identity/tag is the attention key `{runId}:{kind}` so one run+kind notifies once, duplicate frames repeat nothing, a key is forgotten when the run leaves that qualifying state, and a genuinely new transition may notify again. First-seen `failed`/`waiting` from the initial `list_runs` or the `subscribe` snapshot raises nothing (the snapshot is bracketed as a seed); a disconnect drops the baseline but keeps the page session's dedupe set and reseeds before resubscribing, so a gap never notifies. A key present in the attention surface's `dismissed` set (`state.attentionDismissed`) is suppressed. Settings now shows the Android rationale verbatim (`Pipelines can notify you when a run is waiting for your decision or has failed. Without it, those runs still appear in the in-app Needs you surface.`) and honest copy for unsupported, insecure context, default, granted and denied; only `default` on a supported secure page offers the explicit `Enable notifications` control, which is the only call to `Notification.requestPermission()` (never on load). Only `{asked:true|false}` is stored under `pipelines.web.notify.v1`; malformed storage decodes to never-asked and the wording never claims consent. Clicking a notification focuses the page and opens Runs with the run selected through the **existing** navigation; **L6's `/runs/:id` URL route is still `todo`**, so no URL route is invented. `subscribeRuns`/`unsubscribeRuns` send exactly `{type:'subscribe',workspace:''}` and `{type:'unsubscribe'}` (no `run_ids`, no polling timer) and are sent only after the page is connected. Unit-tested in `test/notify.test.mjs` (qualification, wording/body, per-run dedupe, seed/snapshot suppression, dismissed keys, permission copy, asked storage) and `test/repository.test.mjs` (both request shapes + the not-connected guard). Captured 2026-10-19: `captures/L5-notifications-settings.png` (default state, control offered, 0 requests on load), `captures/L5-notifications-granted.png` (after the one explicit grant) and `captures/L5-notifications-denied.png` (honest denied copy, no control). The same checks live in `test/ui-smoke.mjs` behind `--notify` (a focused mode that runs exactly this evidence); that run finished `UI SMOKE PASS` and logged: queued→failed and running→waiting each raised exactly one recorded notification, duplicates/terminal/unknown statuses/first-seen/dismissed raised none, and the click opened the run. **Not observed:** the OS notification itself. The default full live suite could not reach this block cleanly on 2026-10-19 because unrelated live chat steps (C8/C9/C12) raced the shared operator session (another live worktree was streaming into it); the captured Settings states and transition assertions above are from the focused `--notify` run, not a full-suite pass | | L6 | Deep links to a run (`pipelines://run/…` analogue → URL route) | — | todo | | L7 | Accessibility: focus order, labels, keyboard operation | — | todo | diff --git a/web/src/app.js b/web/src/app.js index ee4f0661..a3aa1d14 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -174,6 +174,15 @@ import { decodeAttentionDismissals, encodeAttentionDismissals, } from "./attention.js"; +import { + NOTIFICATION_RATIONALE, + NOTIFY_STORAGE_KEY, + createAlertLedger, + decodeNotificationSettings, + encodeNotificationSettings, + notificationEnvironment, + notificationPermissionState, +} from "./notify.js"; import { DEFAULT_SEARCH_KIND, DEFAULT_SEARCH_SORT, @@ -469,6 +478,10 @@ const state = { attentionDismissed: new Set(), attentionSheetOpen: false, attentionSnapshot: null, + // Notifications (L5): whether the operator has already been asked, loaded once + // at boot from localStorage. The browser owns the permission itself; this flag + // only changes the honest wording in Settings and is never a claim of consent. + notifyAsked: false, // Omni-search (S1/S2): the field/panel state, kept beside the view it never // changes, plus the pure debounce/stale-token sequencer. Opening or closing the // search leaves state.view, the selection and the loaded data untouched. @@ -540,6 +553,11 @@ const state = { chatSubscriptions: new Set(), }; +// The run-notification ledger (L5). It is seeded from the authoritative run list +// and from the subscribe snapshot, then observes pushed `run_event` frames; it +// never feeds the runs list (that is R10's separate fold). +const runAlerts = createAlertLedger(); + let runPoll = null; // One shared live clock for the runs list: it ticks only while a shown run is @@ -1006,6 +1024,76 @@ function loadAttentionDismissed() { } } +/** + * Fold one pushed `run_event` frame into the notification ledger (L5). It does + * not touch the runs list (R10's fold is separate); it only decides whether this + * transition raises exactly one notification. A run already failed/waiting when + * seeded, a duplicate frame, a non-qualifying status and a key the operator + * dismissed all produce nothing. + */ +function onRunAlertFrame(frame) { + const alert = runAlerts.observe(frame, { dismissed: state.attentionDismissed }); + if (!alert || !notificationsAllowed()) return; + try { + const notification = new Notification(alert.title, { body: alert.body, tag: alert.key }); + notification.onclick = () => { + window.focus(); + state.view = "runs"; + render(); + selectRun(alert.runId); + }; + } catch { + // Some browsers can throw even with permission granted; the in-page Needs + // you surface remains the only honest channel and nothing is faked. + } +} + +/** True only when a real browser notification can be constructed right now. */ +function notificationsAllowed() { + return ( + typeof globalThis.Notification === "function" && + globalThis.isSecureContext === true && + globalThis.Notification.permission === "granted" + ); +} + +/** Persist only the asked flag; never a permission claim, endpoint or credential. */ +function persistNotifyAsked(asked) { + state.notifyAsked = Boolean(asked); + try { + localStorage.setItem(NOTIFY_STORAGE_KEY, encodeNotificationSettings({ asked })); + } catch { + // Storage disabled or full: the in-memory flag still applies for this session. + } +} + +/** The asked flag from storage at boot; anything unreadable means never asked. */ +function loadNotifyAsked() { + try { + return decodeNotificationSettings(localStorage.getItem(NOTIFY_STORAGE_KEY)).asked; + } catch { + return false; + } +} + +/** + * Start the run-event watch for this connected epoch: seed from the list that is + * already in hand, treat the subscribe snapshot as seeds too (the server writes + * it before the ack), then observe deltas. A refused subscribe only means no + * pushes; the page keeps working and Settings stays honest. + */ +async function startRunAlertWatch() { + runAlerts.seed(state.runs); + runAlerts.beginSeed(); + try { + await repo.subscribeRuns(); + } catch { + // No live watch: notifications simply cannot raise on this connection. + } finally { + runAlerts.endSeed(); + } +} + function render() { renderHeader(); renderBanner(); @@ -1111,7 +1199,12 @@ function tabButton(view, label) { */ function renderSettingsView() { const pane = h("div", { class: "settings" }); - pane.append(renderSettingsConnection(), renderSettingsWorkspace(), renderSettingsTemplates()); + pane.append( + renderSettingsConnection(), + renderSettingsWorkspace(), + renderSettingsNotifications(), + renderSettingsTemplates(), + ); return pane; } @@ -1200,6 +1293,75 @@ function renderSettingsConnection() { return section; } +/** + * The Notifications section (L5). The Android rationale is shown verbatim; the + * status line is the pure permission view for this page's real browser facts. + * Only the explicit control asks for permission, never page load. When the API + * is unavailable, the page is insecure or permission is denied, the wording says + * plainly that the in-app Needs you surface is the only channel — no fake + * notification is ever drawn. + */ +function renderSettingsNotifications() { + const view = notificationPermissionState({ + ...notificationEnvironment(), + asked: state.notifyAsked, + }); + const section = h("section", { class: "settings-section", id: "settingsNotifications" }); + section.append(h("h2", { class: "settings-title", text: "Notifications" })); + section.append(h("p", { class: "settings-helper", text: NOTIFICATION_RATIONALE })); + section.append( + h("p", { + id: "settingsNotificationState", + class: `settings-notify-state settings-notify-${view.state}`, + role: "status", + text: view.body, + }), + ); + if (view.canRequest) { + section.append( + h( + "div", + { class: "settings-actions" }, + h("button", { + id: "settingsEnableNotifications", + class: "primary", + type: "button", + text: view.actionLabel, + onclick: requestNotifications, + }), + ), + ); + } + return section; +} + +/** + * Ask for notification permission from the operator's explicit click. The asked + * flag is persisted first and the page re-renders from the browser's real answer; + * a refused/dismissed prompt leaves the honest default/denied wording in place. + */ +function requestNotifications() { + persistNotifyAsked(true); + const ctor = globalThis.Notification; + if (typeof ctor !== "function" || !globalThis.isSecureContext) { + renderContent(); + return; + } + try { + const result = ctor.requestPermission(); + if (result && typeof result.then === "function") { + result.then( + () => renderContent(), + () => renderContent(), + ); + return; + } + } catch { + // A browser that refuses the request keeps the honest fallback wording. + } + renderContent(); +} + /** The trusted-network warning card, SettingsScreen.kt's TrustWarning verbatim. */ function renderTrustWarning() { return h( @@ -6649,6 +6811,9 @@ async function onConnected() { // local, so that path is a single render and nothing is fetched twice). renderBanner(); await loadCurrentView(); + // Seed from the authoritative list first, then watch: the subscribe snapshot + // and its ack are treated as seeds, so a reconnect gap never notifies. + await startRunAlertWatch(); } async function loadCurrentView(force = false) { @@ -6683,11 +6848,13 @@ async function loadCurrentView(force = false) { // history from one that has not arrived yet. const { runs, usage } = await repo.listRuns(); state.runs = runs; + runAlerts.seed(runs); if (usage) state.usage = usage; state.runsLoaded = true; } else { const { runs, usage } = await repo.listRuns(); state.runs = runs; + runAlerts.seed(runs); state.usage = usage; state.runsLoaded = true; } @@ -6931,6 +7098,10 @@ client.addEventListener("state", (event) => { // gone, so no thread keeps claiming to run until a fresh frame proves it. clearChatSubscriptions(); settleChatThreads(); + // Drop the run-status baseline but keep this page session's notified keys: + // the reconnect reseeds from the fresh list before it resubscribes, so a + // transition hidden by the gap can never notify late. + runAlerts.reset(); } // A reconnect (not a first connect): re-attach the open chat's stream and // refresh its history wholesale, so a gap that swallowed the end of a turn is @@ -6949,6 +7120,13 @@ client.addEventListener("state", (event) => { client.addEventListener("frame", (event) => { const message = event.detail; if (!message) return; + if (message.type === Protocol.RUN_EVENT) { + // L5 only: observe the pushed transition for notifications. R10's runs-list + // fold is deliberately not implemented here. + const runFrame = message[Protocol.RUN_EVENT]; + if (runFrame) onRunAlertFrame(runFrame); + return; + } if (message.type === Protocol.CHAT_PERMISSION) { const permission = message[ChatKeys.PERMISSION]; if (permission) onChatPermission(permission); @@ -7022,4 +7200,5 @@ window.addEventListener("online", onForegroundActive); // The attention surface's dismissed identities are loaded once here, before the // first render, so the bell's badge is correct from the very first paint. state.attentionDismissed = loadAttentionDismissed(); +state.notifyAsked = loadNotifyAsked(); render(); diff --git a/web/src/notify.js b/web/src/notify.js new file mode 100644 index 00000000..b51ef555 --- /dev/null +++ b/web/src/notify.js @@ -0,0 +1,315 @@ +// Pure, DOM-free notification model for failed/waiting runs (L5). It mirrors +// android/.../notify/RunAlerts.kt: the same two qualifying kinds, the same +// headlines, the same run line and the same one-notification-per-run+kind rule. +// +// Everything here is pure: no DOM, no clock, no storage access. The page owns +// the Notification constructor, the permission request gesture and localStorage; +// the unit tests own the state machine. The attention model in `attention.js` +// is the single authority for which runs qualify and for the dismissal identity, +// so the in-page "Needs you" surface and the tray can never disagree. +import { AttentionKind, attentionKey, attentionKindOf } from "./attention.js"; + +// --------------------------------------------------------------------------- +// Kinds, headlines and the run line +// --------------------------------------------------------------------------- + +/** The two run events that raise a notification (RunAlerts.kt RunAlertKind). */ +export const RunAlertKind = Object.freeze({ + Decision: AttentionKind.Decision, + Failed: AttentionKind.Failed, +}); + +/** `alertKindOf`: an attention kind is already exactly the notification kind. */ +export function alertKindOf(kind) { + if (kind === AttentionKind.Decision || kind?.name === AttentionKind.Decision.name) { + return AttentionKind.Decision; + } + if (kind === AttentionKind.Failed || kind?.name === AttentionKind.Failed.name) { + return AttentionKind.Failed; + } + return null; +} + +/** The short headline one kind shows (RunAlerts.alertTitle). */ +export function alertTitle(kind) { + switch (alertKindOf(kind)?.name) { + case "Decision": + return "A run needs your decision"; + case "Failed": + return "A run failed"; + default: + return ""; + } +} + +/** The stable run+kind identity, the unit of dedupe (RunAlerts.alertKey). */ +export function alertKey(runId, kind) { + const resolved = alertKindOf(kind); + return resolved ? attentionKey(runId, resolved) : ""; +} + +/** + * The line naming the run (RunAlerts.alertText): the attention label, then the + * pipeline it belongs to. The label is the run's trimmed title, falling back to + * the pipeline name; a blank or equal pipeline is never repeated, so there is no + * trailing separator. + */ +export function alertBody(run) { + const pipeline = String(run?.pipeline ?? run?.name ?? ""); + const title = String(run?.label ?? run?.title ?? "").trim(); + const label = title !== "" ? title : pipeline; + if (pipeline === "" || pipeline === label) return label; + return `${label} \u00b7 ${pipeline}`; +} + +// --------------------------------------------------------------------------- +// The ledger: seed, observe, dedupe +// --------------------------------------------------------------------------- + +/** + * Tracks the last status seen for every run and the run+kind alerts already + * raised in this page session. + * + * - `seed(runs)` records the authoritative list without raising anything, so a + * run that was already failed/waiting when the page loaded (or when the socket + * reconnected) never notifies. + * - `beginSeed()`/`endSeed()` bracket the `subscribe` snapshot: the server writes + * the current state of every watched run before its ack, and those frames are + * seeds too, not transitions. + * - `observe(frame)` raises only when a known run's status changes *into* + * `failed` or `waiting`. A duplicate frame (same status), an unchanged + * qualifying state, an unknown status and a first-seen run all return null. + * - A run+kind key is forgotten when the run leaves that qualifying state, so a + * genuinely new transition (for example failed -> running -> failed again) can + * notify once more; the same transition can never repeat. + * - A key present in the attention surface's dismissed set is suppressed. The + * dismissal is the attention model's own `{runId}:{kind}` identity. + * - `reset()` drops the status baseline on a socket drop but keeps the notified + * keys, so a gap that swallows a transition cannot raise a notification after + * the reconnect; the next seed establishes the new baseline. + */ +export function createAlertLedger() { + const lastStatus = new Map(); + const notified = new Set(); + let seeding = false; + + function seed(runs) { + const next = new Map(); + for (const run of runs ?? []) { + const runId = runIdOf(run?.id ?? run?.run_id); + if (runId == null) continue; + next.set(runId, normalizeStatus(run?.status)); + } + lastStatus.clear(); + for (const [runId, status] of next) lastStatus.set(runId, status); + pruneNotified(next); + } + + function observe(frame, { dismissed } = {}) { + const runId = runIdOf(frame?.run_id ?? frame?.runId ?? frame?.id); + const status = normalizeStatus(frame?.status); + if (runId == null || status === "") return null; + + const previous = lastStatus.get(runId); + lastStatus.set(runId, status); + + const kind = attentionKindOf(status); + if (!kind) { + forget(runId, AttentionKind.Decision); + forget(runId, AttentionKind.Failed); + return null; + } + // A run can only be in one qualifying state; forget the other kind's key so + // a later transition back into it is a new event. + forget(runId, kind === AttentionKind.Decision ? AttentionKind.Failed : AttentionKind.Decision); + if (seeding) return null; + if (previous === undefined || previous === status) return null; + + const key = alertKey(runId, kind); + if (notified.has(key)) return null; + notified.add(key); + const dismissedKeys = + dismissed instanceof Set ? dismissed : new Set(Array.isArray(dismissed) ? dismissed : []); + if (dismissedKeys.has(key)) return null; + + return { + runId, + kind, + key, + title: alertTitle(kind), + body: alertBody(frame), + }; + } + + function reset() { + lastStatus.clear(); + seeding = false; + } + + function beginSeed() { + seeding = true; + } + + function endSeed() { + seeding = false; + } + + function forget(runId, kind) { + const key = alertKey(runId, kind); + if (key !== "") notified.delete(key); + } + + function pruneNotified(statuses) { + for (const key of [...notified]) { + const split = key.lastIndexOf(":"); + if (split < 0) continue; + const runId = runIdOf(key.slice(0, split)); + const kindName = key.slice(split + 1); + const status = runId == null ? undefined : statuses.get(runId); + // A run that is absent from this read tells us nothing; keep its key. + if (status === undefined) continue; + const kind = attentionKindOf(status); + if (!kind || kind.name !== kindName) notified.delete(key); + } + } + + return { + seed, + observe, + reset, + beginSeed, + endSeed, + /** Test/introspection helper; returns a copy, never the live set. */ + notifiedKeys: () => [...notified], + statusOf: (runId) => lastStatus.get(runIdOf(runId)), + }; +} + +/** Trim/lowercase the server's status word; an absent value is "". */ +function normalizeStatus(status) { + return String(status ?? "").trim().toLowerCase(); +} + +/** A positive run id as a number, or null for anything malformed. */ +function runIdOf(value) { + const id = Number(value); + return Number.isFinite(id) && id > 0 ? id : null; +} + +// --------------------------------------------------------------------------- +// Permission wording and persistence +// --------------------------------------------------------------------------- + +/** Android's NOTIFICATION_RATIONALE, verbatim (RunAlerts.kt). */ +export const NOTIFICATION_RATIONALE = + "Pipelines can notify you when a run is waiting for your decision or has failed. " + + "Without it, those runs still appear in the in-app Needs you surface."; + +/** The explicit-gesture control's label; shown only when a request is possible. */ +export const NOTIFICATION_REQUEST_LABEL = "Enable notifications"; + +export const NOTIFICATION_UNSUPPORTED = + "This browser does not support notifications. The in-app Needs you surface is the only channel."; +export const NOTIFICATION_INSECURE = + "Notifications need a secure context (https or localhost). This page is not secure, so the " + + "in-app Needs you surface is the only channel."; +export const NOTIFICATION_GRANTED = + "Notifications are on. Failed and waiting runs will raise a browser notification."; +export const NOTIFICATION_DENIED = + "Notifications are blocked for this site. Allow them in the browser's site settings to use them; " + + "until then the in-app Needs you surface is the only channel."; +export const NOTIFICATION_DEFAULT = + "Notifications are off. Enable them to be told when a run fails or needs your decision."; +export const NOTIFICATION_DEFAULT_ASKED = + "Notifications are still off. Your browser did not grant permission when asked; you can ask " + + "again, or the in-app Needs you surface remains the only channel."; + +/** + * The total permission view for Settings. `supported` and `secureContext` are + * the browser's own facts; `permission` is the Notification API's own word + * (`default` | `granted` | `denied`, anything else treated as default). + * + * Only a supported, secure page whose permission is still `default` offers the + * request control. The request is always an explicit user gesture; nothing here + * asks on its own, and the `asked` flag only changes the honest wording. + */ +export function notificationPermissionState({ + supported = true, + secureContext = true, + permission = "default", + asked = false, +} = {}) { + const state = !supported + ? "unsupported" + : !secureContext + ? "insecure" + : permission === "granted" + ? "granted" + : permission === "denied" + ? "denied" + : "default"; + const canRequest = state === "default"; + let body = NOTIFICATION_DEFAULT; + switch (state) { + case "unsupported": + body = NOTIFICATION_UNSUPPORTED; + break; + case "insecure": + body = NOTIFICATION_INSECURE; + break; + case "granted": + body = NOTIFICATION_GRANTED; + break; + case "denied": + body = NOTIFICATION_DENIED; + break; + default: + body = asked ? NOTIFICATION_DEFAULT_ASKED : NOTIFICATION_DEFAULT; + } + return { + state, + body, + canRequest, + actionLabel: canRequest ? NOTIFICATION_REQUEST_LABEL : null, + asked: Boolean(asked), + }; +} + +/** + * The browser facts the permission view needs. Pure enough to unit-test with a + * fake scope; the real page passes `globalThis`. An unrecognised permission + * value is read as `default` rather than guessed. + */ +export function notificationEnvironment(scope = globalThis) { + const ctor = scope?.Notification; + const supported = typeof ctor === "function"; + const raw = supported ? ctor.permission : "default"; + const permission = raw === "granted" || raw === "denied" ? raw : "default"; + return { supported, secureContext: scope?.isSecureContext === true, permission }; +} + +/** The one localStorage key for this page's notification preference. */ +export const NOTIFY_STORAGE_KEY = "pipelines.web.notify.v1"; + +/** Encode only the asked flag; no endpoint, credential or permission claim. */ +export function encodeNotificationSettings(settings) { + return JSON.stringify({ asked: Boolean(settings?.asked) }); +} + +/** + * Decode the stored preference. Total: blank, unreadable JSON, a non-object, a + * non-boolean or a throwing getter all mean "never asked", so a malformed value + * can never throw into the page or claim the operator was asked. + */ +export function decodeNotificationSettings(stored) { + const text = stored == null ? "" : String(stored).trim(); + if (text === "") return { asked: false }; + let parsed; + try { + parsed = JSON.parse(text); + } catch { + return { asked: false }; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { asked: false }; + return { asked: parsed.asked === true }; +} diff --git a/web/src/protocol.js b/web/src/protocol.js index 21a74550..fbef45fb 100644 --- a/web/src/protocol.js +++ b/web/src/protocol.js @@ -27,6 +27,14 @@ export const Protocol = Object.freeze({ GET_RUN: "get_run", RUN: "run", + // Live run state (internal/protocol/runevents.go, L5/R10). `subscribe` sends + // the current state of the watched runs as `run_event` frames and then a + // compact delta on each transition; `unsubscribe` stops the watch. The page + // uses the frames for run notifications without changing R10's runs-list fold. + SUBSCRIBE: "subscribe", + UNSUBSCRIBE: "unsubscribe", + RUN_EVENT: "run_event", + // Omni-search (internal/protocol/search.go): the command and its reply type. // The per-kind payloads and the kind/limit vocabulary live in src/search.js. SEARCH: "search", diff --git a/web/src/repository.js b/web/src/repository.js index 1126f410..37161da4 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -115,6 +115,24 @@ export class PipelinesRepository { return response.run_detail; } + /** + * Watches run state (L5), mirroring `PipelinesRepository.subscribeRuns` for the + * blank "any workspace" scope the runs list shows: exactly `{type:'subscribe', + * workspace:''}` and no `run_ids` (an empty list would watch the whole scope, + * but omitting the field is the shape the Android client sends). The server + * replies with the current state of every matching run as unsolicited + * `run_event` frames, then an id-matched ack, then deltas. Awaiting the ack is + * how the page knows the snapshot has been delivered. + */ + async subscribeRuns() { + return this.#client.call({ type: Protocol.SUBSCRIBE, workspace: "" }); + } + + /** Stops this connection's run-state watch. Best effort; a disconnect drops it. */ + async unsubscribeRuns() { + return this.#client.call({ type: Protocol.UNSUBSCRIBE }); + } + /** * Omni-search. Sends exactly `SearchRequest{query, kind, limit}` from * internal/protocol/search.go: `kind` is the empty string for every kind, and diff --git a/web/styles.css b/web/styles.css index 89b47ead..5d667d0f 100644 --- a/web/styles.css +++ b/web/styles.css @@ -2028,6 +2028,19 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- } .settings-warning-title { margin: 0; font-weight: 600; color: var(--bad); } .settings-warning-body { margin: 0; font-size: 12.5px; color: var(--muted); } +.settings-notify-state { + margin: 0; + border: 1px solid var(--border); + border-radius: 10px; + background: var(--surface-2); + padding: 12px 14px; + font-size: 13px; + color: var(--muted); +} +.settings-notify-granted { border-color: color-mix(in srgb, var(--ok) 45%, var(--border)); color: var(--ok); } +.settings-notify-denied, +.settings-notify-insecure, +.settings-notify-unsupported { color: var(--warn); } .settings-saved { margin: 0; font-size: 12px; color: var(--muted); } .settings-save { justify-self: start; } .settings-card { diff --git a/web/test/notify.test.mjs b/web/test/notify.test.mjs new file mode 100644 index 00000000..34d3f8af --- /dev/null +++ b/web/test/notify.test.mjs @@ -0,0 +1,214 @@ +// The pure notification model (L5): qualifying transitions, exactly-once +// dedupe, pre-existing/dismissed suppression, the app's exact wording and the +// total permission/storage helpers. No DOM, no timer, no live server. +import { test } from "node:test"; +import assert from "node:assert/strict"; + +import { AttentionKind, attentionKey } from "../src/attention.js"; +import { + NOTIFICATION_DEFAULT, + NOTIFICATION_DEFAULT_ASKED, + NOTIFICATION_DENIED, + NOTIFICATION_GRANTED, + NOTIFICATION_INSECURE, + NOTIFICATION_UNSUPPORTED, + NOTIFY_STORAGE_KEY, + alertBody, + alertKey, + alertTitle, + createAlertLedger, + decodeNotificationSettings, + encodeNotificationSettings, + notificationEnvironment, + notificationPermissionState, +} from "../src/notify.js"; + +const frame = (runId, status, extra = {}) => ({ + run_id: runId, + status, + name: "release", + title: "Ship it", + ...extra, +}); + +test("headlines are exactly the app's two, and unknown kinds are blank", () => { + assert.equal(alertTitle(AttentionKind.Failed), "A run failed"); + assert.equal(alertTitle(AttentionKind.Decision), "A run needs your decision"); + assert.equal(alertTitle({ name: "Failed" }), "A run failed"); + assert.equal(alertTitle({ name: "Other" }), ""); +}); + +test("the alert identity is the attention identity", () => { + assert.equal(alertKey(7, AttentionKind.Failed), attentionKey(7, AttentionKind.Failed)); + assert.equal(alertKey(7, AttentionKind.Decision), "7:Decision"); +}); + +test("alert body is the title then the pipeline, with the pipeline fallback", () => { + assert.equal(alertBody({ label: "Ship it", pipeline: "release" }), "Ship it \u00b7 release"); + assert.equal(alertBody({ title: " Ship it ", name: "release" }), "Ship it \u00b7 release"); + assert.equal(alertBody({ title: " ", name: "release" }), "release"); + assert.equal(alertBody({ label: "release", pipeline: "release" }), "release"); + assert.equal(alertBody({ label: "Ship it", pipeline: "" }), "Ship it"); + assert.equal(alertBody(frame(7, "failed")), "Ship it \u00b7 release"); +}); + +test("queued -> failed raises one alert and duplicate frames never repeat it", () => { + const ledger = createAlertLedger(); + ledger.seed([{ id: 4, status: "queued", name: "release", title: "Ship it" }]); + const alert = ledger.observe(frame(4, "failed")); + assert.equal(alert.title, "A run failed"); + assert.equal(alert.body, "Ship it \u00b7 release"); + assert.equal(alert.key, "4:Failed"); + assert.equal(ledger.observe(frame(4, "failed")), null); + assert.equal(ledger.observe(frame(4, "failed")), null); +}); + +test("running -> waiting raises the decision alert; unchanged waiting raises none", () => { + const ledger = createAlertLedger(); + ledger.seed([{ id: 9, status: "running", name: "release", title: "Ship it" }]); + const alert = ledger.observe(frame(9, "waiting")); + assert.equal(alert.title, "A run needs your decision"); + assert.equal(alert.key, "9:Decision"); + assert.equal(ledger.observe(frame(9, "waiting")), null); +}); + +test("succeeded, canceled, interrupted and unknown statuses raise nothing", () => { + for (const status of ["succeeded", "canceled", "interrupted", "mystery", ""]) { + const ledger = createAlertLedger(); + ledger.seed([{ id: 11, status: "running" }]); + assert.equal(ledger.observe(frame(11, status)), null, `status ${status}`); + } +}); + +test("a first-seen failed/waiting run (a snapshot seed) raises nothing", () => { + const ledger = createAlertLedger(); + assert.equal(ledger.observe(frame(21, "failed")), null); + assert.equal(ledger.observe(frame(22, "waiting")), null); +}); + +test("a run already failed/waiting in the seed raises nothing", () => { + const ledger = createAlertLedger(); + ledger.seed([ + { id: 31, status: "failed" }, + { id: 32, status: "waiting" }, + ]); + assert.equal(ledger.observe(frame(31, "failed")), null); + assert.equal(ledger.observe(frame(32, "waiting")), null); +}); + +test("the subscribe snapshot is seeded, so a queued run that failed in the gap does not notify", () => { + const ledger = createAlertLedger(); + ledger.seed([{ id: 41, status: "queued" }]); + ledger.beginSeed(); + assert.equal(ledger.observe(frame(41, "failed")), null); + ledger.endSeed(); + assert.equal(ledger.observe(frame(41, "failed")), null); + // A later real transition still raises exactly once. + assert.equal(ledger.observe(frame(41, "running")), null); + assert.equal(ledger.observe(frame(41, "failed")).key, "41:Failed"); +}); + +test("leaving the qualifying state forgets the key for a genuinely new transition", () => { + const ledger = createAlertLedger(); + ledger.seed([{ id: 51, status: "queued" }]); + assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed"); + assert.equal(ledger.observe(frame(51, "running")), null); + assert.equal(ledger.observe(frame(51, "failed")).key, "51:Failed"); + // And a failed -> waiting hand-off raises the other kind once. + assert.equal(ledger.observe(frame(51, "waiting")).key, "51:Decision"); + assert.equal(ledger.observe(frame(51, "waiting")), null); +}); + +test("a dismissed attention key notifies nothing, even on a real transition", () => { + const ledger = createAlertLedger(); + ledger.seed([{ id: 61, status: "queued" }]); + const alert = ledger.observe(frame(61, "failed"), { + dismissed: new Set([attentionKey(61, AttentionKind.Failed)]), + }); + assert.equal(alert, null); + assert.deepEqual(ledger.notifiedKeys(), ["61:Failed"]); +}); + +test("reset drops the status baseline but keeps the page session's dedupe", () => { + const ledger = createAlertLedger(); + ledger.seed([{ id: 71, status: "queued" }]); + assert.equal(ledger.observe(frame(71, "failed")).key, "71:Failed"); + ledger.reset(); + // Re-seeding the fresh (still failed) list is not a transition. + ledger.seed([{ id: 71, status: "failed" }]); + assert.equal(ledger.observe(frame(71, "failed")), null); + assert.deepEqual(ledger.notifiedKeys(), ["71:Failed"]); +}); + +test("a malformed frame is ignored, never crashed on", () => { + const ledger = createAlertLedger(); + assert.equal(ledger.observe(null), null); + assert.equal(ledger.observe({}), null); + assert.equal(ledger.observe({ run_id: 0, status: "failed" }), null); +}); + +test("permission wording is honest for every browser state", () => { + assert.equal(notificationPermissionState({ supported: false }).body, NOTIFICATION_UNSUPPORTED); + assert.equal( + notificationPermissionState({ supported: true, secureContext: false }).body, + NOTIFICATION_INSECURE, + ); + assert.equal(notificationPermissionState({ permission: "denied" }).body, NOTIFICATION_DENIED); + assert.equal(notificationPermissionState({ permission: "granted" }).body, NOTIFICATION_GRANTED); + assert.equal(notificationPermissionState({ asked: false }).body, NOTIFICATION_DEFAULT); + assert.equal(notificationPermissionState({ asked: true }).body, NOTIFICATION_DEFAULT_ASKED); +}); + +test("only a supported, secure default permission offers the request control", () => { + const defaultView = notificationPermissionState({ asked: false }); + assert.equal(defaultView.state, "default"); + assert.equal(defaultView.canRequest, true); + assert.equal(defaultView.actionLabel, "Enable notifications"); + + for (const options of [ + { supported: false }, + { supported: true, secureContext: false }, + { permission: "granted" }, + { permission: "denied" }, + ]) { + const view = notificationPermissionState(options); + assert.equal(view.canRequest, false, JSON.stringify(options)); + assert.equal(view.actionLabel, null, JSON.stringify(options)); + } + // Having been asked once does not remove the control while permission stays + // default (the browser itself decides whether it may prompt again). + assert.equal(notificationPermissionState({ asked: true }).canRequest, true); +}); + +test("the asked flag round-trips and malformed storage decodes safely", () => { + assert.equal(NOTIFY_STORAGE_KEY, "pipelines.web.notify.v1"); + const stored = encodeNotificationSettings({ asked: true }); + assert.deepEqual(JSON.parse(stored), { asked: true }); + assert.equal(decodeNotificationSettings(stored).asked, true); + assert.equal(decodeNotificationSettings(encodeNotificationSettings({ asked: false })).asked, false); + + for (const bad of ["", " ", "not json", "[]", "null", '"asked"', "{", '{"asked":"yes"}', "42"]) { + assert.deepEqual(decodeNotificationSettings(bad), { asked: false }, bad); + } + assert.deepEqual(decodeNotificationSettings(null), { asked: false }); +}); + +test("notificationEnvironment reads the browser facts without guessing", () => { + const granted = notificationEnvironment({ + Notification: Object.assign(function Notification() {}, { permission: "granted" }), + isSecureContext: true, + }); + assert.deepEqual(granted, { supported: true, secureContext: true, permission: "granted" }); + + assert.deepEqual(notificationEnvironment({}), { + supported: false, + secureContext: false, + permission: "default", + }); + + const odd = notificationEnvironment({ + Notification: Object.assign(function Notification() {}, { permission: "maybe" }), + isSecureContext: false, + }); + assert.deepEqual(odd, { supported: true, secureContext: false, permission: "default" }); +}); diff --git a/web/test/repository.test.mjs b/web/test/repository.test.mjs index 59014c63..fbcf4424 100644 --- a/web/test/repository.test.mjs +++ b/web/test/repository.test.mjs @@ -293,6 +293,30 @@ test("a run action throws when the reply has no run detail", async () => { await assert.rejects(() => repo.cancelRun(7), ProtocolError); }); +test("subscribeRuns sends exactly the blank any-workspace watch and no run_ids", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "subscribe" }); + + await repo.subscribeRuns(); + assert.deepEqual(lastFrame(ws), { type: "subscribe", workspace: "" }); +}); + +test("unsubscribeRuns sends exactly {type:'unsubscribe'}", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "unsubscribe" }); + + await repo.unsubscribeRuns(); + assert.deepEqual(lastFrame(ws), { type: "unsubscribe" }); +}); + +test("subscribeRuns is not sent while the page is not connected", async () => { + FakeWebSocket.instances = []; + const client = new PipelinesClient({ WebSocketImpl: FakeWebSocket }); + const repo = new PipelinesRepository(client); + await assert.rejects(() => repo.subscribeRuns(), { name: "NotConnectedError" }); + assert.equal(FakeWebSocket.instances.length, 0); +}); + // ---- The composer's own commands (C8/C9) ---------------------------------- test("chatPrompt trims the text, sends the operation and native message ids, and omits files when empty", async () => { diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 474e4f06..ca534ab1 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -32,6 +32,12 @@ import { WORKSPACE_PLACEHOLDER, WORKSPACE_STORAGE_KEY, } from "../src/settings.js"; +import { + NOTIFICATION_DEFAULT, + NOTIFICATION_DENIED, + NOTIFICATION_GRANTED, + NOTIFY_STORAGE_KEY, +} from "../src/notify.js"; const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), ".."); @@ -59,6 +65,8 @@ const out = resolve( // Scratch mode: only the P5 create-from-template flow runs, against a throwaway // server with its own database. The default (live) run sends no submit. const scratch = process.argv.includes("--scratch"); +// Focused notification evidence only; skips the unrelated live-suite steps. +const notifyOnly = process.argv.includes("--notify"); // The page must connect through its own proxy (the server rejects a cross-origin // upgrade), but serve.mjs only proxies /connect — not /artifacts. Point the URL @@ -372,6 +380,225 @@ const drag = (dx, dy) => return true; })()`); +// L5: the notification Settings states and the synthetic transition assertions. +// Extracted so `--notify` can run exactly this evidence without the unrelated +// live-suite steps; the default full run calls it in its L1/L5 position. +async function runNotificationChecks() { + // L5: notifications. A real OS notification cannot be captured reliably in + // headless Chrome, so the browser's Notification constructor is stubbed and + // recorded before this document loads; the qualifying transitions are then + // pushed through the page's own socket `onmessage`/`frame` path and matched + // against the pure ledger's decisions. The Settings states are real renders. + // The stub also pre-dismisses one synthetic run+kind so suppression is proven + // through the same attention identity the page loads at boot. + step("L5: notification settings and synthetic run transitions"); + await page.addInitScript(`(() => { + if (window.__notificationStubInstalled) return; + window.__notificationStubInstalled = true; + window.__notificationCalls = []; + window.__notificationObjects = []; + window.__notificationRequests = 0; + window.__notificationPermission = "default"; + function FakeNotification(title, options) { + const call = { + title: String(title), + body: String(options && options.body != null ? options.body : ""), + tag: String(options && options.tag != null ? options.tag : ""), + }; + window.__notificationCalls.push(call); + window.__notificationObjects.push(this); + this.title = call.title; + this.body = call.body; + this.tag = call.tag; + this.onclick = null; + this.close = function () {}; + } + Object.defineProperty(FakeNotification, "permission", { + configurable: true, + get: function () { return window.__notificationPermission; }, + }); + FakeNotification.requestPermission = function () { + window.__notificationRequests += 1; + window.__notificationPermission = "granted"; + return Promise.resolve("granted"); + }; + Object.defineProperty(window, "Notification", { + configurable: true, + writable: true, + value: FakeNotification, + }); + localStorage.setItem("pipelines.web.attention.v1", JSON.stringify(["990001:Failed"])); + })()`); + await page.evaluate(`location.reload()`); + await page.waitForSelector("#url", { timeout: 15000 }); + await page.fill("#url", `ws://127.0.0.1:${port}/connect`); + await page.click("#connectBtn"); + await page.waitForSelector(".conn-banner.conn-ok", { timeout: 25000 }); + // The watch is sent once per connected epoch, after the list has seeded the + // ledger. Wait for that send (and its ack continuation) so the synthetic + // frames below are observed as deltas rather than as part of the snapshot. + await eventually( + () => page.evaluate(`(window.__pipelinesSentTypes || []).includes("subscribe")`), + { timeout: 15000, what: "the run-event subscribe frame" }, + ); + await page.evaluate(`new Promise((resolve) => setTimeout(resolve, 250))`); + await page.clickText("nav.tabs button.tab", "Settings"); + await page.waitForSelector("#settingsNotificationState", { timeout: 15000 }); + + // Default state: honest wording, one explicit control, and nothing asked on + // load or on connect. + const defaultNotificationState = await text("#settingsNotificationState"); + if (defaultNotificationState !== NOTIFICATION_DEFAULT) { + throw new Error(`default notification copy: ${defaultNotificationState}`); + } + const notificationsOnLoad = await page.evaluate(`window.__notificationRequests`); + if (notificationsOnLoad !== 0) { + throw new Error(`the page requested notification permission on load: ${notificationsOnLoad}`); + } + const enableControl = await page.evaluate( + `document.querySelector("#settingsEnableNotifications")?.textContent ?? ""`, + ); + if (enableControl !== "Enable notifications") { + throw new Error(`notification request control: ${enableControl}`); + } + await page.evaluate(`document.querySelector("#settingsNotifications")?.scrollIntoView({ block: "center" })`); + await shot("L5-notifications-settings.png"); + console.log(` notifications default: "${defaultNotificationState}" (0 permission requests on load)`); + + // The explicit control grants through the stub; the page must remember that it + // asked and stop offering the control. + await page.click("#settingsEnableNotifications"); + await eventually( + () => page.evaluate(`document.querySelector("#settingsNotificationState")?.textContent === ${JSON.stringify(NOTIFICATION_GRANTED)}`), + { timeout: 10000, what: "the granted notification wording" }, + ); + const grantState = await page.evaluate(`({ + requests: window.__notificationRequests, + stored: localStorage.getItem(${JSON.stringify(NOTIFY_STORAGE_KEY)}), + control: !!document.querySelector("#settingsEnableNotifications"), + })`); + if (grantState.requests !== 1 || grantState.control) { + throw new Error(`grant state: ${JSON.stringify(grantState)}`); + } + if (grantState.stored !== JSON.stringify({ asked: true })) { + throw new Error(`asked flag not stored: ${grantState.stored}`); + } + await page.evaluate(`document.querySelector("#settingsNotifications")?.scrollIntoView({ block: "center" })`); + await shot("L5-notifications-granted.png"); + console.log(` notifications granted after one explicit click; asked=${grantState.stored}`); + + // Drive the real frame path. The run id is a real run so the notification's + // click can open it through the page's existing Runs navigation (L6 is todo). + await page.clickText("nav.tabs button.tab", "Runs"); + await page.waitForSelector(".list.runs .run-row-meta[data-run-id]", { timeout: 25000 }); + const realRunId = await page.evaluate( + `Number(document.querySelector(".list.runs .run-row-meta[data-run-id]")?.getAttribute("data-run-id"))`, + ); + if (!(realRunId > 0)) throw new Error(`no real run id for the notification click: ${realRunId}`); + const runFrame = (runId, status, extra = {}) => ({ + run_id: runId, + status, + name: "Smoke pipeline", + title: "Smoke run", + ...extra, + }); + const replayRunEvents = (frames) => + page.evaluate(`(() => { + const ws = window.__pipelinesSocket; + if (!ws || typeof ws.onmessage !== "function") return false; + for (const frame of ${JSON.stringify(frames)}) { + ws.onmessage({ data: JSON.stringify({ type: "run_event", run_event: frame }) }); + } + return true; + })()`); + const notificationCount = () => page.evaluate(`window.__notificationCalls.length`); + const notifications = () => page.evaluate(`window.__notificationCalls`); + + // queued -> failed raises exactly one; duplicate/terminal/unknown frames add none. + if (!(await replayRunEvents([runFrame(realRunId, "queued")]))) { + throw new Error("L5: the socket shim did not expose the live socket for run events"); + } + await replayRunEvents([runFrame(realRunId, "failed")]); + if ((await notificationCount()) !== 1) { + throw new Error(`queued->failed should notify once: ${JSON.stringify(await notifications())}`); + } + const failedAlert = (await notifications())[0]; + const failedTag = `${realRunId}:Failed`; + if ( + failedAlert.title !== "A run failed" || + failedAlert.body !== "Smoke run \u00b7 Smoke pipeline" || + failedAlert.tag !== failedTag + ) { + throw new Error(`failed alert wording/tag: ${JSON.stringify(failedAlert)}`); + } + await replayRunEvents([runFrame(realRunId, "failed")]); + if ((await notificationCount()) !== 1) throw new Error("a duplicate failed frame repeated the notification"); + for (const status of ["succeeded", "canceled", "interrupted", "mystery"]) { + await replayRunEvents([runFrame(realRunId, status)]); + } + if ((await notificationCount()) !== 1) { + throw new Error(`a non-qualifying status raised a notification: ${JSON.stringify(await notifications())}`); + } + console.log(` queued -> failed raised one: ${JSON.stringify(failedAlert)}`); + + // running -> waiting raises exactly one decision alert; a duplicate adds none. + await replayRunEvents([runFrame(realRunId, "running"), runFrame(realRunId, "waiting")]); + if ((await notificationCount()) !== 2) { + throw new Error(`running->waiting should notify once: ${JSON.stringify(await notifications())}`); + } + const waitingAlert = (await notifications())[1]; + if ( + waitingAlert.title !== "A run needs your decision" || + waitingAlert.body !== "Smoke run \u00b7 Smoke pipeline" || + waitingAlert.tag !== `${realRunId}:Decision` + ) { + throw new Error(`waiting alert wording/tag: ${JSON.stringify(waitingAlert)}`); + } + await replayRunEvents([runFrame(realRunId, "waiting")]); + if ((await notificationCount()) !== 2) throw new Error("a duplicate waiting frame repeated the notification"); + + // First-seen failed/waiting (the subscribe/seed rule) and a dismissed key + // raise nothing; the dismissed identity is the one loaded at boot. + await replayRunEvents([ + runFrame(990002, "failed"), + runFrame(990003, "waiting"), + runFrame(990001, "queued"), + runFrame(990001, "failed"), + ]); + if ((await notificationCount()) !== 2) { + throw new Error(`pre-existing/dismissed runs notified: ${JSON.stringify(await notifications())}`); + } + console.log(" running -> waiting raised one; duplicates, terminal/unknown statuses, first-seen and dismissed runs raised none"); + + // The click focuses the page and uses the existing Runs navigation to select + // the run (L6's URL route is still todo; no route is invented). + await page.evaluate(`window.__notificationObjects[0]?.onclick?.()`); + await eventually( + () => + page.evaluate( + `!!document.querySelector('.list.runs .run-row.selected .run-row-meta[data-run-id="${realRunId}"]')`, + ), + { timeout: 20000, what: "the notification click to open Runs with the run selected" }, + ); + console.log(` notification click opened Runs with run ${realRunId} selected`); + + // The denied state is rendered from the same pure wording and offers no control. + await page.evaluate(`window.__notificationPermission = "denied"`); + await page.clickText("nav.tabs button.tab", "Settings"); + await eventually( + () => page.evaluate(`document.querySelector("#settingsNotificationState")?.textContent === ${JSON.stringify(NOTIFICATION_DENIED)}`), + { timeout: 10000, what: "the denied notification wording" }, + ); + const deniedControl = await page.evaluate(`!!document.querySelector("#settingsEnableNotifications")`); + if (deniedControl) throw new Error("the denied state still offers the request control"); + await page.evaluate(`document.querySelector("#settingsNotifications")?.scrollIntoView({ block: "center" })`); + await shot("L5-notifications-denied.png"); + console.log(` notifications denied: "${NOTIFICATION_DENIED}" (no request control)`); + console.log( + " NOTE: the notification frames above are synthetic and the browser Notification was recorded by a stub; no real OS notification was observed", + ); +} + try { await mkdir(out, { recursive: true }); @@ -509,7 +736,11 @@ try { for (const shot of shots) console.log(` ${shot}`); } - if (!scratch) { + if (notifyOnly) { + await runNotificationChecks(); + console.log("\nUI SMOKE PASS"); + for (const shot of shots) console.log(` ${shot}`); + } else if (!scratch) { const pipelineCount = await page.evaluate( `document.querySelectorAll("#pipelineRows button.row").length`, ); @@ -4651,6 +4882,8 @@ try { } console.log(` reload restored url=${restoredUrl} workspace=${restoredWorkspace}`); + await runNotificationChecks(); + // C11: the background-tasks bar. The live server has no running shell to read // safely, so the bar is driven from synthetic `shell` frames replayed through // the page's own socket handler (the same shim) and the bounded output pages are From f98cb50f8c5346d405727c883e04a68d696fc0c5 Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 14:17:08 +0100 Subject: [PATCH 7/8] web/PARITY: record L5's full-smoke result and the unrelated C13 failure --- web/PARITY.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/PARITY.md b/web/PARITY.md index 5257cd8d..eac0ddd3 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -149,7 +149,7 @@ delete command). | L2 | Wide layout: left rail + two panes | client-side | todo | | L3 | Narrow layout: bottom section strip + bottom navigation | client-side | todo | | L4 | Responsive switch by viewport width (no hardcoded device) | `WindowSize.kt` analogue | todo | -| L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived from `subscribe` / `run_event` | **partial** — the browser notification path is implemented and captured in Settings, but **no real OS notification was observed**, so the row is not `done`. The exact reason: headless Chrome cannot reliably show or capture an OS notification; the smoke stubs and records the `Notification` constructor, while the transition decisions run through the page's real socket `onmessage`/`frame` path. Pure logic lives in `src/notify.js` and mirrors `notify/RunAlerts.kt` + `ui/Attention.kt`: only a run becoming `failed` (headline `A run failed`) or `waiting` (headline `A run needs your decision`) notifies; `queued`, `running`, `succeeded`, `canceled`, `interrupted` and unknown statuses never do. Body is the attention label (trimmed title else pipeline) then ` · {pipeline}`, with no separator when the pipeline is blank or equal; identity/tag is the attention key `{runId}:{kind}` so one run+kind notifies once, duplicate frames repeat nothing, a key is forgotten when the run leaves that qualifying state, and a genuinely new transition may notify again. First-seen `failed`/`waiting` from the initial `list_runs` or the `subscribe` snapshot raises nothing (the snapshot is bracketed as a seed); a disconnect drops the baseline but keeps the page session's dedupe set and reseeds before resubscribing, so a gap never notifies. A key present in the attention surface's `dismissed` set (`state.attentionDismissed`) is suppressed. Settings now shows the Android rationale verbatim (`Pipelines can notify you when a run is waiting for your decision or has failed. Without it, those runs still appear in the in-app Needs you surface.`) and honest copy for unsupported, insecure context, default, granted and denied; only `default` on a supported secure page offers the explicit `Enable notifications` control, which is the only call to `Notification.requestPermission()` (never on load). Only `{asked:true|false}` is stored under `pipelines.web.notify.v1`; malformed storage decodes to never-asked and the wording never claims consent. Clicking a notification focuses the page and opens Runs with the run selected through the **existing** navigation; **L6's `/runs/:id` URL route is still `todo`**, so no URL route is invented. `subscribeRuns`/`unsubscribeRuns` send exactly `{type:'subscribe',workspace:''}` and `{type:'unsubscribe'}` (no `run_ids`, no polling timer) and are sent only after the page is connected. Unit-tested in `test/notify.test.mjs` (qualification, wording/body, per-run dedupe, seed/snapshot suppression, dismissed keys, permission copy, asked storage) and `test/repository.test.mjs` (both request shapes + the not-connected guard). Captured 2026-10-19: `captures/L5-notifications-settings.png` (default state, control offered, 0 requests on load), `captures/L5-notifications-granted.png` (after the one explicit grant) and `captures/L5-notifications-denied.png` (honest denied copy, no control). The same checks live in `test/ui-smoke.mjs` behind `--notify` (a focused mode that runs exactly this evidence); that run finished `UI SMOKE PASS` and logged: queued→failed and running→waiting each raised exactly one recorded notification, duplicates/terminal/unknown statuses/first-seen/dismissed raised none, and the click opened the run. **Not observed:** the OS notification itself. The default full live suite could not reach this block cleanly on 2026-10-19 because unrelated live chat steps (C8/C9/C12) raced the shared operator session (another live worktree was streaming into it); the captured Settings states and transition assertions above are from the focused `--notify` run, not a full-suite pass | +| L5 | Notifications for failed/waiting runs (browser Notification API; HTTPS/localhost only) | derived from `subscribe` / `run_event` | **partial** — the browser notification path is implemented and captured in Settings, but **no real OS notification was observed**, so the row is not `done`. The exact reason: headless Chrome cannot reliably show or capture an OS notification; the smoke stubs and records the `Notification` constructor, while the transition decisions run through the page's real socket `onmessage`/`frame` path. Pure logic lives in `src/notify.js` and mirrors `notify/RunAlerts.kt` + `ui/Attention.kt`: only a run becoming `failed` (headline `A run failed`) or `waiting` (headline `A run needs your decision`) notifies; `queued`, `running`, `succeeded`, `canceled`, `interrupted` and unknown statuses never do. Body is the attention label (trimmed title else pipeline) then ` · {pipeline}`, with no separator when the pipeline is blank or equal; identity/tag is the attention key `{runId}:{kind}` so one run+kind notifies once, duplicate frames repeat nothing, a key is forgotten when the run leaves that qualifying state, and a genuinely new transition may notify again. First-seen `failed`/`waiting` from the initial `list_runs` or the `subscribe` snapshot raises nothing (the snapshot is bracketed as a seed); a disconnect drops the baseline but keeps the page session's dedupe set and reseeds before resubscribing, so a gap never notifies. A key present in the attention surface's `dismissed` set (`state.attentionDismissed`) is suppressed. Settings now shows the Android rationale verbatim (`Pipelines can notify you when a run is waiting for your decision or has failed. Without it, those runs still appear in the in-app Needs you surface.`) and honest copy for unsupported, insecure context, default, granted and denied; only `default` on a supported secure page offers the explicit `Enable notifications` control, which is the only call to `Notification.requestPermission()` (never on load). Only `{asked:true|false}` is stored under `pipelines.web.notify.v1`; malformed storage decodes to never-asked and the wording never claims consent. Clicking a notification focuses the page and opens Runs with the run selected through the **existing** navigation; **L6's `/runs/:id` URL route is still `todo`**, so no URL route is invented. `subscribeRuns`/`unsubscribeRuns` send exactly `{type:'subscribe',workspace:''}` and `{type:'unsubscribe'}` (no `run_ids`, no polling timer) and are sent only after the page is connected. Unit-tested in `test/notify.test.mjs` (qualification, wording/body, per-run dedupe, seed/snapshot suppression, dismissed keys, permission copy, asked storage) and `test/repository.test.mjs` (both request shapes + the not-connected guard). Captured 2026-10-19: `captures/L5-notifications-settings.png` (default state, control offered, 0 requests on load), `captures/L5-notifications-granted.png` (after the one explicit grant) and `captures/L5-notifications-denied.png` (honest denied copy, no control). The same checks live in `test/ui-smoke.mjs` behind `--notify` (a focused mode that runs exactly this evidence); that run finished `UI SMOKE PASS` and logged: queued→failed and running→waiting each raised exactly one recorded notification, duplicates/terminal/unknown statuses/first-seen/dismissed raised none, and the click opened the run. **Not observed:** the OS notification itself. On 2026-10-19 the default full live suite reached and passed this block with the same logged assertions, then failed later in an unrelated C13 hit-test (`the last row's menu item is not clickable`, its centre at y=919.5 in a 900 px viewport after the list's re-render reset the scroll); the L5 captures and assertions above come from the focused `--notify` run, which finished `UI SMOKE PASS`. | | L6 | Deep links to a run (`pipelines://run/…` analogue → URL route) | — | todo | | L7 | Accessibility: focus order, labels, keyboard operation | — | todo | From a7872c3f31e5e04fb6133072796b0ee48a773d7a Mon Sep 17 00:00:00 2001 From: Alan Silva <alanfortlink@gmail.com> Date: Mon, 19 Oct 2026 14:25:42 +0100 Subject: [PATCH 8/8] web: create a chat through the directory picker (C2) --- web/PARITY.md | 30 +++-- web/src/app.js | 254 +++++++++++++++++++++++++++++++++-- web/src/chat.js | 95 +++++++++++++ web/src/protocol.js | 7 + web/src/repository.js | 12 ++ web/styles.css | 64 +++++++++ web/test/chat.test.mjs | 129 ++++++++++++++++++ web/test/repository.test.mjs | 35 +++++ web/test/ui-smoke.mjs | 251 ++++++++++++++++++++++++++++++++-- 9 files changed, 841 insertions(+), 36 deletions(-) diff --git a/web/PARITY.md b/web/PARITY.md index aafa0796..c7991592 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -88,15 +88,15 @@ the pipeline list already carries — rather than a pluralised verb. ## Chat | # | Feature | Protocol | Status | | --- | --- | --- | --- | -| C1 | Session list (operator sessions, closed grouped as history) | `chat_sessions` | done — captured 2026-10-19: `captures/44-chat-sessions.png` (the live server's one operator session: "New chat", the `Operator` kind chip, the meta line `Idle · /Users/alan/repos/pipelines` and a `Close chat…` row action) and `captures/50-chat-no-match.png` (the narrowed-to-nothing state `No chats match "zzz-no-such-chat".` with its `Clear search` action). A row is the title (`sessionTitle`: the server title, else the id's first 18 characters, else `Untitled chat`), the kind chip derived from the server tag (`operator` → `Operator`, any other tag verbatim, a blank tag no chip), a `Closed` chip only when closed, the activity badge word (`Streaming` / `New` / `Open`, `Open` only while its conversation is open), and meta = work label · directory · model with blanks omitted (`Running` / `Running {tool}` / `Running {N} tools` while a turn is in flight, else `Busy · read-only`, else `Idle`). Active sessions are grouped by directory only when there is more than one group (header = the directory or `No directory`); closed sessions sit below under a `Closed` header, each reopenable. The search field is labelled `Search chats` and narrows by title or directory, case-insensitively, never re-sorting; the empties are `Loading chats…`, `No chat sessions on this server yet.` with a `New chat` action placeholder (wired by C2) and `No chats match "{query}".` with `Clear search`. The `Loading chats…` and `No chat sessions on this server yet.`/`New chat` states are implemented but not captured: the live server always lists its one operator session, so neither state is reachable against it | -| C2 | Create a chat (directory picker) | `chat_directories`, `chat_create` | todo | +| C1 | Session list (operator sessions, closed grouped as history) | `chat_sessions` | done — captured 2026-10-19: `captures/44-chat-sessions.png` (the live server's one operator session: "New chat", the `Operator` kind chip, the meta line `Idle · /Users/alan/repos/pipelines` and a `Close chat…` row action) and `captures/50-chat-no-match.png` (the narrowed-to-nothing state `No chats match "zzz-no-such-chat".` with its `Clear search` action). A row is the title (`sessionTitle`: the server title, else the id's first 18 characters, else `Untitled chat`), the kind chip derived from the server tag (`operator` → `Operator`, any other tag verbatim, a blank tag no chip), a `Closed` chip only when closed, the activity badge word (`Streaming` / `New` / `Open`, `Open` only while its conversation is open), and meta = work label · directory · model with blanks omitted (`Running` / `Running {tool}` / `Running {N} tools` while a turn is in flight, else `Busy · read-only`, else `Idle`). Active sessions are grouped by directory only when there is more than one group (header = the directory or `No directory`); closed sessions sit below under a `Closed` header, each reopenable. The search field is labelled `Search chats` and narrows by title or directory, case-insensitively, never re-sorting; the empties are `Loading chats…`, `No chat sessions on this server yet.` with a `New chat` action (C2) and `No chats match "{query}".` with `Clear search`. The `Loading chats…` and `No chat sessions on this server yet.`/`New chat` states are implemented but not captured: the live server always lists its one operator session, so neither state is reachable against it | +| C2 | Create a chat (directory picker) | `chat_directories`, `chat_create` | done — captured 2026-10-19: `captures/75-chat-create-picker.png` (the list's `New chat` action opens `Start a chat`; back `Cancel new chat`, prompt `Where should this chat live?`, home `Home (~)` first and selected with `/Users/alan` beneath it, two recents labelled by their full paths, the model note, and the footer `Start in ~` / `Cancel` / `New chat`), `captures/76-chat-created-list.png` (the one real session `ses_eabc47a91ffe31C6zNX4ieXN6e`, titled `New chat`, created with exactly `{title:"New chat",directory:"~",operation_id:"…"}`, at the head of the list and active with its empty history) and `captures/77-chat-created-closed.png` (the same session closed through the `Close chat…` → `chat_close` confirm, now carrying the `Closed` chip as history). Blank directory entries are dropped, an empty reply still yields home, `~` is sent for home and the absolute path for a recent, and the create is guarded against double submission; a refusal stays in the open pane with the server's own text. The operator's own `ses_eae413f50ffeLQDExlg8cYnscN` was not selected, closed, reopened or prompted by this item. The smoke created exactly one real session and closed it; nothing was deleted | | C3 | Open / close / reopen a session | `chat_close`, `chat_reopen` | done — captured 2026-10-19: `captures/49-chat-close-confirm.png`. Selecting a row opens the conversation (see C4); an open row offers `Close chat…` and a closed row offers `Reopen`. The confirm is the Android copy verbatim: title `Close chat?`, the body naming the session title (`Closes "{title}" and marks it closed on every device. A turn that is running is stopped first. Nothing is deleted — the chat and its history are kept, and you can reopen it from the list.`), confirm `Close chat`, dismiss `Cancel`; only the confirm sends `chat_close` (and `Reopen` sends `chat_reopen`), then the list is refreshed from the server. The `Close chat…` action is offered on every open row, so its confirm is rendered from the pane's overlays **whether or not a conversation is open** — the smoke exercises the row-level path with no session selected (`ui-smoke` asserts the confirm appears and dismisses it), not only the path after opening the row. **Shown, not executed**: the live server has exactly one session — `ses_eae413f50ffeLQDExlg8cYnscN`, the operator's own — so the dialog was shown, captured and dismissed with `Cancel`; **no `chat_close` was sent** and that session was not closed or reopened by this stage | | C4 | History with paging / "load older" | `chat_messages` | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (the opened `ses_eae413f50ffeLQDExlg8cYnscN` transcript with the `Load older messages` control beside the conversation's identity while the server reports `has_more`) and `captures/48-chat-load-older-empty.png` (after pressing it: the live session's own opaque cursor returned an empty older page, so `has_more` went false and the control disappeared — the honest result of the server's cursor, distinct from 45). The request is exactly `{type:"chat_messages",chat_query:{session_id,limit:200,cursor}}`; the newest page is read with an empty cursor and an older page with the server's own opaque `next_cursor` passed back verbatim (never interpreted), and the reply is `chat_history.{messages,next_cursor,has_more}` with an older server's bare `chat_messages` falling back to `hasMore:false`. `mergeHistoryPage` prepends an older page, dedupes by id (order-preserving, the page's copy winning) and replaces `nextCursor`/`hasMore`; the prepend itself is unit-tested (`test/chat.test.mjs`) because the live server returned no older rows. Nothing auto-loads on scroll and there is no end-of-history row | | C5 | Live transcript: user/assistant text, one reply = one turn | `chat_subscribe`, `chat_event` | done — captured 2026-10-19: `captures/56-chat-live-turn.png` (the answer text growing inside the existing single agent bubble while the reasoning step count grows), `captures/57-chat-running.png` (the running indicator: spinner + `Running a tool…` + `· 1s` + the `shell npm run build` line), `captures/58-chat-long-call.png` (a 61 s-old call tinted ` · long`), `captures/59-chat-settled.png` (the tools completed and the step ended: no indicator, the same one agent bubble). Opening a conversation attaches its shared live stream with exactly `{type:'chat_subscribe',chat_subscribe:{session_id}}` (the `chat_subscribe` field, **not** `chat_query`; internal/protocol/message.go, chat_stream.go) and folds every pushed `chat_event` into the open thread; the session is never read-only and any number of clients may watch it. `client.js` surfaces an envelope with no matching pending id as a DOM-free `frame` event (a matched reply is still resolved by id and not broadcast) and `src/app.js` folds only `chat_event` frames for a session this client has open. There is **no** `chat_unsubscribe` on the wire: the server detaches a subscription when the connection closes (chat_hub.detachClient / websocket.go), so on a socket drop the page clears its subscription set and settles every running thread, and on reconnect re-subscribes the open chat and replaces its conversation with the newest history page wholesale (`historyResync`, no stale held turn) — captured by the smoke's own reconnect. The pure fold lives in `src/chat.js` (`applyChatEvent` and helpers) and is unit-tested: a `user` frame needs a non-blank message id and text, is ignored when the id already exists and keeps the sender's `client` label (the server never echoes this client's own prompt); `text`/`reasoning` deltas append to the part their kind started (`deltaPartId`, so the two kinds can never share a part) and a live turn that spans several assistant message ids stays one `transcriptRows` agent bubble; `tool` frames merge field by field (a non-empty incoming field wins, `state.status/input/content/metadata/error` each retained when omitted, `executed` sticky, `time` retained), so a later frame never blanks what an earlier one taught; `step` runs the turn unless the status is `ended`; a `shell` frame is C11's and never marks the turn running; `usage` is not folded; any frame clears `queued`. The live badge uses the same words as the run badge — `live` while subscribed on a connected socket, `reconnecting` while the socket is coming back, `not live` when idle/refused (`chatStreamState`, unit-tested; the smoke logs all three). The running indicator (under the transcript, after the last agent turn) is a spinner plus the phase headline (`Thinking…` / `Running a tool…` / `Waiting…`) and ` · {elapsed}`, then one line per running tool with its own elapsed; a call at or past 60 s is tinted and marked ` · long`. **Replayed vs real, stated plainly**: the live server had no turn to prompt (its only session is the operator's, and this stage does not write to it), so `ui-smoke.mjs` subscribes through the real server and every history reply is real, then replays exact `chat_event` frames through the socket's own `onmessage` (a WebSocket recorder shim installed before the page's scripts via `Page.addScriptToEvaluateOnNewDocument`); the smoke log names the replayed frames and asserts the subscribe ack and history came from the real server | | C6 | Reasoning block + tool calls with name/input for the whole lifecycle | `chat_event` | done — the assistant turn draws, in order, its one collapsible reasoning block and its one tool-call chip (then the answer). Reasoning labels match the app: `Thinking…` / `Reasoning` for a single step and `Thinking · {N} steps` / `Reasoning · {N} steps` for several, with ` · {duration}` appended when the parts' timing gives a settled span (earliest start → latest completed), through chevrons named `Show reasoning` / `Hide reasoning`. The chip reads `1 tool called` / `{N} tools called`, announces `… expand for details`, wears the shared spinner while a call is in flight and an error tint once one failed, and opens a fixed overlay panel under the chip (flipped above / clamped into the viewport when there is no room) with the same count, a `Close tool calls` control and an internally scrolling, independently-expandable row per call: the name (else `tool`), the first of `description`/`command`/`filePath`/`file_path`/`path`/`pattern`/`query`/`url` collapsed and elided to 72 characters, the `+N -M` edit stat when present, the `formatToolDuration` value (`340ms`/`1.2s`/`2m 3s`), and `Expand {name}`/`Collapse {name}`; a failed row is marked `Failed tool call`. An expanded row shows INPUT (pretty-printed JSON, or the raw partial string), the LCS edit diff (at most 200 rendered lines with the remaining `… {N} more changed line(s) not shown`), then ERROR (the server's `error.message`, else the output) or OUTPUT (`(no output)` when settled and empty, nothing while in flight). Lifecycle words `streaming`/`running` are in flight and `completed`/`error` settled; a settled call never spins or wears the ` · long` mark. Because the panel is a fixed overlay, opening or closing it never re-flows the transcript nor moves its scroll (C14). Captured 2026-10-19 against `ses_eae413f50ffeLQDExlg8cYnscN` (one folded turn, 80 reasoning steps, 122 tool calls): `captures/51-chat-reasoning-collapsed.png`, `captures/52-chat-reasoning-expanded.png`, `captures/53-chat-tool-chip.png`, `captures/54-chat-tool-panel.png` (an opened `read` row showing INPUT + OUTPUT) and `captures/55-chat-edit-diff-sample.png`. The live history carries no failed or edit-family call, so that capture renders a labelled page-rendered sample — a `shell` row marked `Failed tool call` with INPUT + ERROR and an `edit` row with a `+2 -1` diff — through the page's own row builder; the transcript stayed put across open/close (top 43065 → 43065). **Live arrival over `chat_event` is C5**: the renderer is built from the same part shapes (`ChatPart{type,name,state{status,input,content,error},time}`) and takes a `streaming` flag plus a live elapsed source so C5 can drive in-flight calls; the chip's in-flight spinner, the ` · long` 60s mark, the panel flip-above and an edit-family call are not reachable against the live server, so they are unit-tested (`test/chat.test.mjs`) rather than claimed as captured | | C7 | Markdown rendering + code blocks | — | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (opened at the newest content: bold, bullet lists, a `|` table with its `---` delimiter row and inline code spans from the live assistant answer), `captures/47b-chat-markdown-code.png` (a rendered fenced code block — label `js`, the pre body `const answer = 42;` — drawn in the live browser by the page's own `renderMarkdown`, the same function that renders the answer) and `captures/47-chat-reasoning-code.png`. The subset is exactly `Markdown.kt`: paragraphs, `#`–`######` headings, fenced code (```/~~~, the language label else `code`), block quotes, bullet/ordered lists, `|` tables with a `---` delimiter row, thematic rules, inline code, bold, italic (underscore only at word boundaries, so `snake_case` stays plain), `[label](url)` links and bare http(s) autolinks; HTML entities are decoded first in one pass, and HTML, reference links, strikethrough and nested lists render as plain text and are never dropped. **Code-block caveat, stated plainly**: the live assistant answer carries **no** fenced block — its four fences live in the reasoning transcript, which the app draws as plain text, not as markdown (`captures/47-chat-reasoning-code.png` shows one such fence as muted plain text; that is C6 material, not the markdown path). So the rendered `<pre>` code block is captured from a labelled sample through the page's real renderer (`47b`), and the same path plus its `code`-else-language label is unit-tested in `test/markdown.test.mjs`. Only `http(s)` link targets become clickable — the transcript is untrusted model output, so a `javascript:`/`data:` target renders as its label, never as a live link | | 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) | +| 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 (one step, separate from C2's picker) 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` | 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. | @@ -104,9 +104,10 @@ the pipeline list already carries — rather than a pluralised verb. | 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 | Three decisions in Chat, recorded here as the browser client's own choices where -the app has no exact counterpart. The list's `New chat` action is rendered but -deliberately disabled (with a note that C2 wires it), because C2's create dialog -is a separate item. The conversation pane outside a selection reads +the app has no exact counterpart. The list's `New chat` action — in the toolbar +and in the empty state — opens C2's create pane (`Start a chat`), which owns the +detail slot while it is open and leaves the list visible beside it. The +conversation pane outside a selection reads `Select a chat to open it.`: the browser always shows a two-pane split (the app's narrow layout covers the list instead), so this stands in for `PaneIdentity`'s covered-pane title rather than a second feature. And the markdown renderer only @@ -120,9 +121,9 @@ choices and dependencies. **Attachments are not delivered to the agent yet**: th server's prompt path (`internal/server/chat_stream.go`) consumes only `text` today, so the browser collects, validates and blocks on a failed attachment and then sends it best-effort as the file's own reference string, but the file is not -yet forwarded to OpenCode. **`/new` sends `chat_create` directly** because C2's -create dialog is a separate item; it creates a session titled `New chat` in the -current directory and opens it. **`/rename` is a local, per-device rename** until +yet forwarded to OpenCode. **`/new` sends `chat_create` directly** as a one-step +create in the current directory (C2's pane is the directory chooser); it creates +a session titled `New chat` and opens it. **`/rename` is a local, per-device rename** until C13 lands (the browser item mirrors C13's dependency rather than inventing a server rename). And the **draft is held per chat in memory and mirrored into `localStorage`** (`pipelines.web.chatDraft.v1`), the web analogue of per-device @@ -134,10 +135,13 @@ as Android's `onStop` does) rather than the submit path, and the smoke clicks it the throwaway turn. Accepting `/close` finishes the session locally too: the running/queued bits clear and the conversation leaves the pane for the list (mirrors Android's `finishSession`); the rest of the live-transcript fold is C5's -item. The UI smoke creates one throwaway session per run (via `/new`), really -prompts and really interrupts it, then closes it again; the server keeps a closed -chat as history, so repeated runs accumulate closed `New chat` rows (there is no -delete command). +item. The UI smoke creates one throwaway session per run (via `/new`, marked ephemeral +so it never enters the operator registry), really prompts and really interrupts +it, then closes it again. C2's step separately creates one **real** session, +captures it and closes it with `chat_close`; the server keeps a closed chat as +history, so that row stays as closed history (there is no delete command). The +page keeps its own ephemeral throwaway row in memory so the check can switch back +to it, but the server never lists it and a reload drops it. ## Settings, layout, platform | # | Feature | Protocol | Status | diff --git a/web/src/app.js b/web/src/app.js index ee4f0661..c00ec6d7 100644 --- a/web/src/app.js +++ b/web/src/app.js @@ -2,7 +2,7 @@ // Deliberately small and DOM-only (no framework, no build step). Every value // that came from the server is set with textContent, never innerHTML. import { PipelinesClient } from "./client.js"; -import { PipelinesRepository, SHELL_OUTPUT_LIMIT } from "./repository.js"; +import { PipelinesRepository, SHELL_OUTPUT_LIMIT, newChatOperationId } from "./repository.js"; import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js"; import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js"; import { @@ -232,6 +232,13 @@ import { CHAT_COMMAND_DISMISS_LABEL, CHAT_COMMAND_GLYPH, CHAT_COMPOSER_PLACEHOLDER, + CHAT_CREATE_BACK_LABEL, + CHAT_CREATE_CANCEL, + CHAT_CREATE_CONFIRM, + CHAT_CREATE_LOADING, + CHAT_CREATE_MODEL_NOTE, + CHAT_CREATE_PROMPT, + CHAT_CREATE_TITLE, CHAT_EMPTY, CHAT_FOLLOW_THRESHOLD_PX, CHAT_LOADING, @@ -283,6 +290,9 @@ import { chatCommandEffect, chatCommandHelp, chatCommandSuggestions, + chatCreateFailed, + chatCreateSucceeded, + chatStartInLabel, chatFirstScroll, chatFollowsAt, chatHeaderMeta, @@ -296,6 +306,8 @@ import { composerCanSend, composerSendEnabled, composerSubmit, + defaultDirectoryChoice, + directoryChoices, directoryLabel, dismissChatNotice as dismissChatNoticeModel, filterSessions, @@ -304,6 +316,7 @@ import { makeChatNotice, mergeHistoryPage, mergeShellFrame, + newChatCreateState, newChatThread, parseChatInput, queuedAfterFrame, @@ -317,6 +330,7 @@ import { sessionChipLabel, sessionMeta, sessionStatusLabel, + selectChatDirectory as selectChatDirectoryModel, sessionTitle, sessionWorkLabel, settledThread, @@ -502,6 +516,11 @@ const state = { // is set with textContent and the markdown renderer builds DOM nodes, never // innerHTML. chatSessions: [], + // The verification chats this page itself created (C2's automation flag). The + // server deliberately never lists them; the page keeps its own in-memory row so + // the creator can keep working with the chat it just opened. The set is + // memory-only, so a reload cannot turn one into a permanent list entry. + chatEphemeralIds: new Set(), chatLoading: false, chatLoaded: false, chatError: "", @@ -538,6 +557,14 @@ const state = { // re-established for the open chat on reconnect. A refused subscription simply // never joins the set, so the badge reads "not live" honestly. chatSubscriptions: new Set(), + // C2: the create flow. `chatCreate` is the ChatCreateState analogue (null until + // the New chat entry point is used); the directory reply is cached so cancelling + // and reopening does not re-ask, and a failed load keeps its own reason. + chatDirectories: [], + chatDirectoriesLoading: false, + chatDirectoriesLoaded: false, + chatDirectoriesError: "", + chatCreate: null, }; let runPoll = null; @@ -1055,7 +1082,9 @@ function renderContent() { } else if (state.view === "runs") { split.append(renderRunList(), renderRunDetail()); } else if (state.view === "chat") { - split.append(renderChatList(), renderChatConversation()); + // While the create flow is open it owns the detail pane; the session list + // stays visible beside it, exactly as the app's two-pane chat stack does. + split.append(renderChatList(), state.chatCreate ? renderChatCreate() : renderChatConversation()); } else { split.append(renderTemplateGallery(), renderTemplateDetail()); } @@ -3983,7 +4012,15 @@ async function loadChatSessions(force = false) { state.chatError = ""; renderContent(); try { - state.chatSessions = await repo.chatSessions(); + const listed = await repo.chatSessions(); + // Keep this page's own verification chats, which the server intentionally + // never returns, at the head of the in-memory list (memory-only; see + // chatEphemeralIds). Everything else is the server's list, in its order. + const held = state.chatSessions.filter( + (session) => + state.chatEphemeralIds.has(session.id) && !listed.some((entry) => entry.id === session.id), + ); + state.chatSessions = [...held, ...listed]; state.chatLoaded = true; } catch (error) { state.chatError = describeError(error); @@ -3992,6 +4029,85 @@ async function loadChatSessions(force = false) { renderContent(); } +// --------------------------------------------------------------------------- +// The create flow (C2, ChatCreatePane.kt) +// --------------------------------------------------------------------------- + +/** + * Open the create pane with a fresh operation id. The id is minted once per + * intent, so a retry after a refusal reuses it and the server can dedupe the + * create rather than starting a second session. + */ +function startNewChat() { + state.chatCreate = newChatCreateState(newChatOperationId()); + state.chatDirectoriesError = ""; + renderContent(); + loadChatDirectories(); +} + +/** + * Fetch `chat_directories` for the open picker. A failure keeps the reason for the + * pane's error state; blank entries are dropped here as well as in the pure model + * so a malformed reply can never produce an empty row. An already-loaded list is + * reused unless [force] (the error state's Retry) asks again. + */ +async function loadChatDirectories(force = false) { + if (!state.chatCreate || state.chatDirectoriesLoading) return; + if (state.chatDirectoriesLoaded && !force) return; + state.chatDirectoriesLoading = true; + state.chatDirectoriesError = ""; + renderContent(); + try { + const directories = await repo.chatDirectories(); + state.chatDirectories = (directories ?? []).filter((entry) => String(entry ?? "").trim() !== ""); + state.chatDirectoriesLoaded = true; + } catch (error) { + state.chatDirectoriesError = describeError(error); + } + state.chatDirectoriesLoading = false; + renderContent(); +} + +/** Select one directory row (the value is what chat_create will send). */ +function selectChatDirectory(value) { + if (!state.chatCreate) return; + state.chatCreate = selectChatDirectoryModel(state.chatCreate, value); + renderContent(); +} + +/** Leave the create flow without creating anything. */ +function cancelNewChat() { + state.chatCreate = null; + renderContent(); +} + +/** + * Create the chat in the chosen directory. Guarded against a double submit: the + * guard reads the held state, so a second click while the request is in flight + * sends nothing. On success the pane closes, the created session goes to the head + * of the list, becomes the open conversation and loads its (empty) history; on + * failure the server's own reason stays in the pane, which does not close. + */ +async function createNewChat() { + const create = state.chatCreate; + if (!create || create.creating) return; + state.chatCreate = { ...create, creating: true, error: "" }; + renderContent(); + try { + // Not ephemeral: this is the operator's own create path (the UI smoke uses the + // same path for its one real session and closes it afterwards). + const created = await repo.chatCreate("New chat", create.directory, create.operationId); + state.chatCreate = null; + state.chatSessions = chatCreateSucceeded(state.chatSessions, created); + await openChatSession(created.id); + await loadChatSessions(); + } catch (error) { + if (!state.chatCreate) return; + state.chatCreate = chatCreateFailed(state.chatCreate, describeError(error)); + renderContent(); + } +} + /** Open a session: select it, subscribe its stream and load its newest history page. */ async function openChatSession(id) { if (state.chatActiveId === id && state.chatThreads.get(id)?.loaded) return; @@ -4585,9 +4701,9 @@ async function startChatSession(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, - }); + const ephemeral = globalThis.__pipelinesEphemeralChat === true; + const created = await repo.chatCreate("New chat", directory, undefined, { ephemeral }); + if (ephemeral) state.chatEphemeralIds = new Set(state.chatEphemeralIds).add(created.id); // 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)]; @@ -4776,6 +4892,14 @@ function renderChatList() { fillChatRows(rows); }, }), + // C2: the create path stays one tap away while the list is narrowed, the same + // trailing action the app keeps beside its search control. + h("button", { + class: "ghost chat-new", + type: "button", + text: CHAT_NEW_ACTION, + onclick: startNewChat, + }), ); list.append(toolbar); const rows = h("div", { id: "chatRows", class: "chat-rows" }); @@ -4817,16 +4941,13 @@ function fillChatRows(rows) { return; } if (filtered.length === 0) { - // The create path is the C2 item; the action is shown but deliberately not - // wired here, exactly as the item says. const empty = chatEmpty(CHAT_EMPTY); empty.append( h("button", { class: "ghost chat-new", type: "button", text: CHAT_NEW_ACTION, - disabled: true, - title: "Creating a chat lands with the C2 item", + onclick: startNewChat, }), ); rows.append(empty); @@ -4935,6 +5056,119 @@ function renderChatRow(session) { return row; } +/** + * The create pane (C2): the app's NewChatPane. A back control leaves without + * creating, then the directory error / loading / picker states in the app's own + * order, the model note and the footer naming the value that will be sent. Every + * server string is set with textContent. + */ +function renderChatCreate() { + const create = state.chatCreate; + const pane = h("div", { class: "detail chat-detail chat-create" }); + + const bar = h("div", { class: "chat-bar chat-create-bar" }); + bar.append( + h( + "button", + { + class: "ghost chat-create-back", + type: "button", + "aria-label": CHAT_CREATE_BACK_LABEL, + title: CHAT_CREATE_BACK_LABEL, + onclick: cancelNewChat, + }, + h("span", { class: "chat-create-back-glyph", "aria-hidden": "true", text: "←" }), + ), + h("h2", { class: "chat-bar-title chat-create-title", text: CHAT_CREATE_TITLE }), + ); + pane.append(bar); + + if (state.chatDirectoriesError && !state.chatDirectoriesLoaded) { + const empty = chatEmpty(state.chatDirectoriesError); + empty.classList.add("chat-create-directories-error"); + empty.append( + h("button", { + class: "ghost chat-create-retry", + type: "button", + text: "Retry", + onclick: () => loadChatDirectories(true), + }), + ); + pane.append(empty); + } else if (!state.chatDirectoriesLoaded) { + pane.append(h("div", { class: "chat-create-loading muted", text: CHAT_CREATE_LOADING })); + } else { + pane.append(h("div", { class: "chat-create-prompt muted", text: CHAT_CREATE_PROMPT })); + + const choices = directoryChoices(state.chatDirectories); + const selected = + choices.find((choice) => choice.createDirectory === create.directory) ?? + defaultDirectoryChoice(choices); + const list = h("div", { + class: "chat-create-choices", + role: "listbox", + "aria-label": CHAT_CREATE_PROMPT, + }); + for (const choice of choices) { + const active = choice.createDirectory === selected?.createDirectory; + const row = h("button", { + class: `row chat-create-choice${active ? " selected" : ""}`, + type: "button", + role: "option", + "aria-selected": active ? "true" : "false", + "data-directory": choice.createDirectory, + onclick: () => selectChatDirectory(choice.createDirectory), + }); + row.append(h("span", { class: "row-title chat-create-choice-label", text: choice.label })); + if (choice.secondary) { + row.append(h("span", { class: "row-meta chat-create-choice-path", text: choice.secondary })); + } + list.append(row); + } + pane.append(list); + + // A refresh that failed after a successful first load keeps the choices and + // says why the list may be stale (the app's own bodySmall error line). + if (state.chatDirectoriesError) { + pane.append(h("div", { class: "chat-create-directories-error", text: state.chatDirectoriesError })); + } + if (create.error) { + pane.append(h("div", { class: "chat-create-error", text: create.error })); + } + pane.append(h("p", { class: "chat-create-model-note muted", text: CHAT_CREATE_MODEL_NOTE })); + + const directory = selected?.createDirectory ?? create.directory; + const footer = h("div", { class: "chat-create-footer" }); + footer.append(h("span", { class: "chat-create-start", text: chatStartInLabel(directory) })); + footer.append( + h("button", { + class: "ghost chat-create-cancel", + type: "button", + text: CHAT_CREATE_CANCEL, + disabled: create.creating, + onclick: cancelNewChat, + }), + ); + const confirm = h("button", { + class: "chat-create-confirm", + type: "button", + "aria-label": CHAT_CREATE_CONFIRM, + disabled: create.creating, + onclick: createNewChat, + }); + if (create.creating) { + confirm.append(h("span", { class: "spinner chat-create-spinner", "aria-hidden": "true" })); + } else { + confirm.append(document.createTextNode(CHAT_CREATE_CONFIRM)); + } + footer.append(confirm); + pane.append(footer); + } + + appendChatDialogs(pane); + return pane; +} + /** The active conversation: identity, context, transcript and its controls. */ function renderChatConversation() { const pane = h("div", { class: "detail chat-detail" }); diff --git a/web/src/chat.js b/web/src/chat.js index c42453a9..f77c3621 100644 --- a/web/src/chat.js +++ b/web/src/chat.js @@ -16,6 +16,10 @@ // toolLongRunning (the chip and its panel) // ui/chat/ChatListFilter.kt sessionMatchesQuery, filterChatSessions, // groupChatSessionsByDirectory +// ui/chat/ChatDirectories.kt HOME_DIRECTORY, directoryChoices, +// defaultDirectoryChoice (the create picker) +// ui/chat/ChatCreatePane.kt the create flow's wording, NewChatActions footer +// and the create state transitions // ui/chat/ChatScroll.kt chatBottomDistancePx, chatFollowsAt, // chatShowJumpToLatest, chatOpensAtNewest, // chatFirstScroll @@ -114,6 +118,25 @@ export const CONVERSATION_EMPTY = "This chat has no messages yet. Ask something export const LOAD_OLDER_ACTION = "Load older messages"; export const SELECT_CHAT_HINT = "Select a chat to open it."; +// The create flow (C2, ChatCreatePane.kt), verbatim. The home choice's row is +// `Home (~)` while chat_create sends the `~` the server documents; the footer +// names the value that will be sent (see chatStartInLabel). +export const HOME_DIRECTORY = "~"; +export const HOME_LABEL = `Home (${HOME_DIRECTORY})`; +export const CHAT_CREATE_TITLE = "Start a chat"; +export const CHAT_CREATE_BACK_LABEL = "Cancel new chat"; +export const CHAT_CREATE_LOADING = "Loading directories…"; +export const CHAT_CREATE_PROMPT = "Where should this chat live?"; +export const CHAT_CREATE_MODEL_NOTE = + "This server has no request for choosing a chat's model, so a new chat uses the server's default."; +export const CHAT_CREATE_CONFIRM = "New chat"; +export const CHAT_CREATE_CANCEL = "Cancel"; + +/** The create footer's line: `Start in {directory}` with the value that is sent. */ +export function chatStartInLabel(directory) { + return `Start in ${str(directory)}`; +} + /** The listing's narrowed-to-nothing message: `No chats match "{query}".` */ export function chatNoMatchMessage(query) { return `No chats match "${str(query).trim()}".`; @@ -610,6 +633,78 @@ export function directoryLabel(directory) { return isBlank(directory) ? NO_DIRECTORY_LABEL : str(directory); } +// --------------------------------------------------------------------------- +// The create flow's directory choices (ChatDirectories.kt) +// --------------------------------------------------------------------------- + +/** + * The picker's choices from the server's reported directories. The first entry is + * the operator's home — the one entry the server always returns first — and the + * rest keep the server's most-recently-used order. A blank entry is dropped, and a + * reply with nothing in it still yields the home choice, so the picker is never + * empty. A recent's `label` is its full path; only the home row carries the path + * as `secondary`, because its own label is `Home (~)`. + */ +export function directoryChoices(directories) { + const cleaned = (directories ?? []).map((entry) => str(entry)).filter((entry) => !isBlank(entry)); + const home = cleaned.length > 0 ? cleaned[0] : HOME_DIRECTORY; + return [ + { + label: HOME_LABEL, + path: home, + home: true, + createDirectory: HOME_DIRECTORY, + secondary: home, + }, + ...cleaned.slice(1).map((path) => ({ + label: path, + path, + home: false, + createDirectory: path, + secondary: null, + })), + ]; +} + +/** The choice a freshly opened picker starts on: home, first. */ +export function defaultDirectoryChoice(choices) { + return (choices ?? [])[0] ?? null; +} + +/** A fresh create state: home selected, the caller's operation id, not sending. */ +export function newChatCreateState(operationId) { + return { + directory: HOME_DIRECTORY, + operationId: str(operationId), + creating: false, + error: "", + }; +} + +/** + * Choose one directory for the create. Kept pure so the view can re-render from a + * single state object; the error a previous refusal left is cleared because it + * described the old choice, not this one. + */ +export function selectChatDirectory(create, choice) { + const directory = + typeof choice === "string" ? choice : str(choice?.createDirectory ?? ""); + if (isBlank(directory)) return { ...create }; + return { ...create, directory, error: "" }; +} + +/** The create failed: stop sending and keep the server's own reason in the pane. */ +export function chatCreateFailed(create, message) { + return { ...create, creating: false, error: str(message) }; +} + +/** The create succeeded: the new session goes to the head of the list, deduped by id. */ +export function chatCreateSucceeded(sessions, session) { + const list = sessions ?? []; + if (!session) return list; + return [session, ...list.filter((entry) => entry?.id !== session.id)]; +} + // --------------------------------------------------------------------------- // Transcript (ChatFormat.kt) // --------------------------------------------------------------------------- diff --git a/web/src/protocol.js b/web/src/protocol.js index 21a74550..fc1f9347 100644 --- a/web/src/protocol.js +++ b/web/src/protocol.js @@ -64,6 +64,10 @@ export const Protocol = Object.freeze({ CHAT_PROMPT: "chat_prompt", CHAT_INTERRUPT: "chat_interrupt", CHAT_CREATE: "chat_create", + // The create flow's directory choices (C2): `chat_directories` has no body and + // replies in the `chat_directories` field, home first then recent operator + // directories (internal/protocol/chat.go ChatDirectories). + CHAT_DIRECTORIES: "chat_directories", // The approval card (C10): the server pushes `chat_permission` frames (one // pending request, later re-pushed with the resolution) and the phone answers // with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply). @@ -102,6 +106,9 @@ export const ChatKeys = Object.freeze({ // separate field name here would put it on the wrong part of the envelope. PROMPT: "chat_prompt", CREATE: "chat_create", + // The `chat_directories` reply (C2), home first then recents; mirrors + // internal/protocol/message.go `ChatDirectories []string`. + DIRECTORIES: "chat_directories", QUEUED: "chat_queued", // C10: the pushed approval frame (`chat_permission`) and the answer body // (`chat_reply`), both distinct Message fields in internal/protocol/message.go. diff --git a/web/src/repository.js b/web/src/repository.js index 1126f410..3bac10fe 100644 --- a/web/src/repository.js +++ b/web/src/repository.js @@ -383,6 +383,18 @@ export class PipelinesRepository { }); } + /** + * Lists the directories a new chat can live in (C2), mirroring + * `PipelinesRepository.chatDirectories`: a bare `{type:'chat_directories'}` with + * no body, replying in `chat_directories` (home first, then recent operator + * directories). An older server that returns no field answers with an empty + * list; the view still offers home so the picker is never empty. + */ + async chatDirectories() { + const response = await this.#client.call({ type: Protocol.CHAT_DIRECTORIES }); + return response[ChatKeys.DIRECTORIES] ?? []; + } + /** * Creates one session in an explicit directory (mirrors * `PipelinesRepository.chatCreate`). The directory is always sent, so a chat is diff --git a/web/styles.css b/web/styles.css index 89b47ead..1f4c12e0 100644 --- a/web/styles.css +++ b/web/styles.css @@ -1435,6 +1435,70 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font- .chat-list { display: flex; flex-direction: column; } .chat-search { flex: 1 1 auto; min-width: 0; } +.chat-toolbar .chat-new { white-space: nowrap; } + +/* C2: the create pane — the directory picker, the model note and the footer that + names the value chat_create will send. */ +.chat-create { gap: 12px; } +.chat-bar.chat-create-bar { align-items: center; justify-content: flex-start; gap: 10px; } +.chat-create-back { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + flex: none; +} +.chat-create-back-glyph { font-size: 16px; line-height: 1; } +.detail .chat-create-title { margin: 0; } +.chat-create-loading { padding: 18px 4px; } +.chat-create-prompt { padding: 2px 2px 0; font-size: 13px; } +.chat-create-choices { + display: flex; + flex-direction: column; + border: 1px solid var(--border); + border-radius: 10px; + overflow: hidden; +} +.chat-create-choice { cursor: pointer; } +.chat-create-choice-path { + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 11px; +} +.chat-create-directories-error { color: var(--bad); } +.chat-create-error { color: var(--bad); font-size: 13px; } +.chat-create-model-note { margin: 0; font-size: 12px; line-height: 1.5; max-width: 64ch; } +.chat-create-footer { + display: flex; + gap: 10px; + align-items: center; + margin-top: auto; + padding: 12px; + background: var(--surface-2); + border: 1px solid var(--border); + border-radius: 10px; +} +.chat-create-start { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 13px; +} +.chat-create-confirm { + min-width: 88px; + display: inline-flex; + align-items: center; + justify-content: center; + border-color: var(--accent); + color: var(--accent); + font-weight: 600; +} +.chat-create-confirm:disabled, +.chat-create-cancel:disabled { opacity: 0.55; } +.chat-create-spinner { width: 14px; height: 14px; border-width: 2px; } .chat-group-header { padding: 8px 12px 4px; diff --git a/web/test/chat.test.mjs b/web/test/chat.test.mjs index b87ee274..1b4d5c53 100644 --- a/web/test/chat.test.mjs +++ b/web/test/chat.test.mjs @@ -12,6 +12,13 @@ import { CHAT_COMMAND_FAILED_LABEL, CHAT_COMMAND_GLYPH, CHAT_COMMAND_LABEL, + CHAT_CREATE_BACK_LABEL, + CHAT_CREATE_CANCEL, + CHAT_CREATE_CONFIRM, + CHAT_CREATE_LOADING, + CHAT_CREATE_MODEL_NOTE, + CHAT_CREATE_PROMPT, + CHAT_CREATE_TITLE, CHAT_FOLLOW_THRESHOLD_PX, CHAT_QUEUED_NOTICE, COMPOSER_SEND, @@ -60,12 +67,16 @@ import { attachmentDisplayName, attachmentError, attachmentFiles, + HOME_DIRECTORY, + HOME_LABEL, backgroundTasksRunningLabel, chatBottomDistancePx, chatCommandEffect, chatCommandForEnter, chatCommandHelp, chatCommandSuggestions, + chatCreateFailed, + chatCreateSucceeded, chatFirstScroll, chatFollowsAt, chatHeaderMeta, @@ -73,6 +84,7 @@ import { chatNoticeLabel, chatOpensAtNewest, chatShowJumpToLatest, + chatStartInLabel, chatStreamState, closeChatConfirmation, composerAction, @@ -80,7 +92,9 @@ import { composerSendEnabled, composerSubmit, decisionLabel, + defaultDirectoryChoice, deltaPartId, + directoryChoices, directoryLabel, dismissChatNotice, filterSessions, @@ -92,6 +106,7 @@ import { mergeHistoryPage, mergeShellFrame, mergeToolPart, + newChatCreateState, newChatThread, parseChatInput, partRendering, @@ -104,6 +119,7 @@ import { runningBackgroundShells, runningToolElapsedMillis, runningToolStamps, + selectChatDirectory, sessionActivity, sessionActivityBadge, sessionChipLabel, @@ -1612,3 +1628,116 @@ test("a step that ends does not clear a background shell that outlives the turn" assert.equal(resumed.selectedShellId, null); assert.equal(resumed.shellOutput, null); }); + +// ---- The create flow's directory picker (C2, ChatDirectories.kt) ----------- + +test("directoryChoices makes the first non-blank directory home and keeps recents in server order", () => { + const choices = directoryChoices(["/Users/alan", "", "/work/one", " ", "/work/two"]); + assert.deepEqual(choices, [ + { + label: "Home (~)", + path: "/Users/alan", + home: true, + createDirectory: "~", + secondary: "/Users/alan", + }, + { + label: "/work/one", + path: "/work/one", + home: false, + createDirectory: "/work/one", + secondary: null, + }, + { + label: "/work/two", + path: "/work/two", + home: false, + createDirectory: "/work/two", + secondary: null, + }, + ]); +}); + +test("directoryChoices always yields home first, even for an empty or blank reply", () => { + for (const reply of [[], ["", " "], null, undefined]) { + const choices = directoryChoices(reply); + assert.equal(choices.length, 1); + assert.deepEqual(choices[0], { + label: HOME_LABEL, + path: HOME_DIRECTORY, + home: true, + createDirectory: HOME_DIRECTORY, + secondary: HOME_DIRECTORY, + }); + } +}); + +test("the home row is the only one with a secondary path; recents are labelled by full path", () => { + const choices = directoryChoices(["/home/operator", "/repo/a", "/repo/b"]); + assert.deepEqual( + choices.map((choice) => [choice.label, choice.secondary]), + [ + ["Home (~)", "/home/operator"], + ["/repo/a", null], + ["/repo/b", null], + ], + ); + assert.equal(defaultDirectoryChoice(choices)?.label, HOME_LABEL); + assert.equal(defaultDirectoryChoice([]), null); +}); + +test("newChatCreateState starts on home, not sending, with the caller's operation id", () => { + assert.deepEqual(newChatCreateState("web-chat-op"), { + directory: HOME_DIRECTORY, + operationId: "web-chat-op", + creating: false, + error: "", + }); +}); + +test("selectChatDirectory sends the chosen value and clears a previous refusal", () => { + const state = { ...newChatCreateState("op"), error: "refused" }; + const recent = { label: "/repo/a", path: "/repo/a", home: false, createDirectory: "/repo/a", secondary: null }; + assert.deepEqual(selectChatDirectory(state, recent), { + directory: "/repo/a", + operationId: "op", + creating: false, + error: "", + }); + assert.equal(selectChatDirectory(state, "~").directory, "~"); + assert.deepEqual(selectChatDirectory(state, ""), state); +}); + +test("chatCreateFailed keeps the pane open with the server's message; success stops sending", () => { + const creating = { ...newChatCreateState("op"), creating: true }; + assert.deepEqual(chatCreateFailed(creating, "the directory is not available"), { + directory: "~", + operationId: "op", + creating: false, + error: "the directory is not available", + }); +}); + +test("chatCreateSucceeded puts the created session at the head and dedupes by id", () => { + const a = { id: "a", title: "A" }; + const b = { id: "b", title: "B" }; + const created = { id: "b", title: "New chat" }; + assert.deepEqual(chatCreateSucceeded([a, b], created), [created, a]); + assert.deepEqual(chatCreateSucceeded([], created), [created]); + assert.deepEqual(chatCreateSucceeded([a], null), [a]); +}); + +test("the create flow's wording is the app's verbatim", () => { + assert.equal(CHAT_CREATE_TITLE, "Start a chat"); + assert.equal(CHAT_CREATE_BACK_LABEL, "Cancel new chat"); + assert.equal(CHAT_CREATE_LOADING, "Loading directories…"); + assert.equal(CHAT_CREATE_PROMPT, "Where should this chat live?"); + assert.equal( + CHAT_CREATE_MODEL_NOTE, + "This server has no request for choosing a chat's model, so a new chat uses the server's default.", + ); + assert.equal(CHAT_CREATE_CONFIRM, "New chat"); + assert.equal(CHAT_CREATE_CANCEL, "Cancel"); + assert.equal(chatStartInLabel(HOME_DIRECTORY), "Start in ~"); + assert.equal(chatStartInLabel("/repo/a"), "Start in /repo/a"); +}); diff --git a/web/test/repository.test.mjs b/web/test/repository.test.mjs index 59014c63..e7a3dd6e 100644 --- a/web/test/repository.test.mjs +++ b/web/test/repository.test.mjs @@ -345,6 +345,41 @@ test("chatInterrupt sends the session as chat_query (not a chat_interrupt body)" assert.deepEqual(lastFrame(ws), { type: "chat_interrupt", chat_query: { session_id: "s1" } }); }); +test("chatDirectories sends exactly {type:'chat_directories'} and returns the list", async () => { + const { repo, ws } = connected(); + const directories = ["/home/operator", "/repo/one", "/repo/two"]; + ws.reply = (frame) => ({ id: frame.id, type: "chat_directories", chat_directories: directories }); + + assert.deepEqual(await repo.chatDirectories(), directories); + assert.deepEqual(lastFrame(ws), { type: "chat_directories" }); +}); + +test("chatDirectories returns [] when the reply carries no directories", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "chat_directories" }); + assert.deepEqual(await repo.chatDirectories(), []); +}); + +test("chatDirectories surfaces a server refusal as a ProtocolError", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "error", error: "unknown command: chat_directories" }); + await assert.rejects(() => repo.chatDirectories(), { + name: "ProtocolError", + message: "unknown command: chat_directories", + }); +}); + +test("chatCreate sends home as ~ and carries the exact title/directory/operation_id body", async () => { + const { repo, ws } = connected(); + ws.reply = (frame) => ({ id: frame.id, type: "chat_create", chat_session: { id: "ses_new" } }); + + await repo.chatCreate("New chat", "~", "op-4"); + assert.deepEqual(lastFrame(ws), { + type: "chat_create", + chat_create: { title: "New chat", directory: "~", operation_id: "op-4" }, + }); +}); + test("chatCreate sends title/directory/operation_id and returns chat_session", async () => { const { repo, ws } = connected(); const created = { id: "ses_new", title: "New chat" }; diff --git a/web/test/ui-smoke.mjs b/web/test/ui-smoke.mjs index 474e4f06..dbaf78c3 100644 --- a/web/test/ui-smoke.mjs +++ b/web/test/ui-smoke.mjs @@ -75,6 +75,9 @@ let failed = false; // The throwaway chat session this run creates for the running-turn capture. It // is closed again in cleanup; null once closed (or when none was created). let throwawaySessionId = null; +// C2's one real session. It is closed in its own step; kept here only so a +// failure before that step can still close it rather than leave it in the list. +let createdSessionId = null; function step(label) { console.log(`• ${label}`); @@ -443,6 +446,13 @@ try { frame.chat_prompt?.text ?? "", ); } + // C2: the create bodies this page actually sent, so the smoke can prove + // the picker's chosen value reached chat_create. + if (frame.type === "chat_create") { + (window.__chatCreateBodies = window.__chatCreateBodies || []).push( + frame.chat_create ?? null, + ); + } if (frame.type === "chat_reply") { const requestId = frame.chat_reply && frame.chat_reply.request_id; if (window.__suppressChatReplyIds.includes(requestId)) { @@ -1484,11 +1494,18 @@ try { }; })()`), { timeout: 15000, what: "the live run's active stage" }, - ); - 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`)); + ).catch(() => null); + // The row was running when it was picked but may have stopped while its + // detail loaded; this capture is documented as best effort, so say so rather + // than fail an unrelated step on live-data timing. + if (!live) { + console.log(` -- run ${liveRunId} stopped before its active stage rendered; skipped the live halo capture`); + } else { + 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. @@ -2383,6 +2400,10 @@ try { await page.clickText("nav.tabs button.tab", "Chat"); await page.waitForSelector("#chatRows .chat-row", { timeout: 25000 }); + // The operator's own session is the one this step reads; the list may lead with + // another run's closed row (C2 closes its create, and history sits by recency), + // so pick the operator row rather than assuming the first. + const expectedSession = "ses_eae413f50ffeLQDExlg8cYnscN"; const chatList = await page.evaluate(`(() => ({ label: document.querySelector("#chatSearch")?.getAttribute("aria-label") ?? "", placeholder: document.querySelector("#chatSearch")?.getAttribute("placeholder") ?? "", @@ -2392,26 +2413,31 @@ try { chips: [...row.querySelectorAll(".chip")].map((chip) => chip.textContent), meta: row.querySelector(".chat-row-meta")?.textContent ?? "", close: !!row.querySelector(".chat-close"), + closed: !!row.querySelector(".chat-closed-chip"), })), }))()`); if (chatList.label !== "Search chats") throw new Error(`chat search label: ${chatList.label}`); if (chatList.placeholder !== "Search chats") throw new Error(`chat search placeholder: ${chatList.placeholder}`); if (chatList.rows.length === 0) throw new Error("no chat sessions rendered"); - if (!chatList.rows[0].title) throw new Error("the first chat row has no title"); - if (!chatList.rows[0].chips.includes("Operator")) { - throw new Error(`chat kind chip: ${chatList.rows[0].chips.join(", ")}`); + const operatorRow = + chatList.rows.find((row) => row.id === expectedSession) ?? + chatList.rows.find((row) => !row.closed && row.close); + if (!operatorRow) throw new Error("no open chat row rendered"); + if (!operatorRow.title) throw new Error("the operator chat row has no title"); + if (!operatorRow.chips.includes("Operator")) { + throw new Error(`chat kind chip: ${operatorRow.chips.join(", ")}`); } - if (!chatList.rows[0].close) throw new Error("the open chat row offers no Close chat action"); + if (!operatorRow.close) throw new Error("the open chat row offers no Close chat action"); console.log( - ` chat list: ${chatList.rows.length} session(s); "${chatList.rows[0].title}" ` + - `[${chatList.rows[0].chips.join(", ")}] — ${chatList.rows[0].meta}`, + ` chat list: ${chatList.rows.length} session(s); "${operatorRow.title}" ` + + `[${operatorRow.chips.join(", ")}] — ${operatorRow.meta}`, ); await shot("44-chat-sessions.png"); // The row's own Close chat… action with NO conversation open: the list offers // it on every open row, so the confirm must still appear. Shown and dismissed // with Cancel; no chat_close is ever sent for the operator's live session. - await page.click(`#chatRows .chat-row[data-session="${chatList.rows[0].id}"] .chat-close`); + await page.click(`#chatRows .chat-row[data-session="${operatorRow.id}"] .chat-close`); await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); const listClose = await page.evaluate( `document.querySelector(".confirm-chat-close .confirm-message")?.textContent ?? ""`, @@ -2440,12 +2466,179 @@ try { throw new Error(`Clear search left the query: ${JSON.stringify(clearedQuery)}`); } + // C2: create a chat through the directory picker. This step creates exactly one + // REAL session (the app's own path, not the ephemeral `/new` verification path), + // captures it, then closes it with `chat_close` so it moves to closed history + // instead of sitting active in the operator's list. The operator's own session + // is never selected, closed or prompted here. + step("C2: the create pane — directory picker, one real create, then close"); + await ensureConnected(); + await page.evaluate(`(() => { + window.__pipelinesEphemeralChat = false; + window.__chatCreateBodies = []; + return true; + })()`); + await page.click(".chat-toolbar .chat-new"); + await page.waitForSelector(".chat-create", { timeout: 15000 }); + await page.waitForSelector(".chat-create-choice", { timeout: 20000 }); + + const picker = await page.evaluate(`(() => ({ + title: document.querySelector(".chat-create-title")?.textContent ?? "", + back: document.querySelector(".chat-create-back")?.getAttribute("aria-label") ?? "", + backTitle: document.querySelector(".chat-create-back")?.getAttribute("title") ?? "", + prompt: document.querySelector(".chat-create-prompt")?.textContent ?? "", + loading: !!document.querySelector(".chat-create-loading"), + note: document.querySelector(".chat-create-model-note")?.textContent ?? "", + start: document.querySelector(".chat-create-start")?.textContent ?? "", + cancel: document.querySelector(".chat-create-cancel")?.textContent ?? "", + cancelDisabled: document.querySelector(".chat-create-cancel")?.disabled ?? null, + confirm: document.querySelector(".chat-create-confirm")?.textContent ?? "", + confirmDisabled: document.querySelector(".chat-create-confirm")?.disabled ?? null, + rows: [...document.querySelectorAll(".chat-create-choice")].map((row) => ({ + label: row.querySelector(".chat-create-choice-label")?.textContent ?? "", + path: row.querySelector(".chat-create-choice-path")?.textContent ?? "", + directory: row.dataset.directory ?? "", + selected: row.getAttribute("aria-selected") === "true", + })), + }))()`); + if (picker.title !== "Start a chat") throw new Error(`C2 title: ${picker.title}`); + if (picker.back !== "Cancel new chat" || picker.backTitle !== "Cancel new chat") { + throw new Error(`C2 back label: ${JSON.stringify({ aria: picker.back, title: picker.backTitle })}`); + } + if (picker.prompt !== "Where should this chat live?") { + throw new Error(`C2 prompt: ${picker.prompt}`); + } + if (picker.loading) throw new Error("C2 still shows Loading directories… after the choices rendered"); + if ( + picker.note !== + "This server has no request for choosing a chat's model, so a new chat uses the server's default." + ) { + throw new Error(`C2 model note: ${picker.note}`); + } + if (picker.start !== "Start in ~") throw new Error(`C2 footer: ${picker.start}`); + if (picker.cancel !== "Cancel") throw new Error(`C2 cancel: ${picker.cancel}`); + if (picker.cancelDisabled !== false || picker.confirmDisabled !== false) { + throw new Error(`C2 controls disabled before sending: ${JSON.stringify(picker)}`); + } + if (picker.confirm.trim() !== "New chat") throw new Error(`C2 confirm: ${picker.confirm}`); + if (picker.rows.length === 0) throw new Error("C2 rendered no directory choices"); + const homeRow = picker.rows[0]; + if (homeRow.label !== "Home (~)" || homeRow.directory !== "~" || !homeRow.selected) { + throw new Error(`C2 home row is not first and selected: ${JSON.stringify(homeRow)}`); + } + if (homeRow.path === "" || homeRow.path === "~") { + throw new Error(`C2 home row has no absolute path beneath it: ${JSON.stringify(homeRow)}`); + } + const recents = picker.rows.slice(1); + // A recent's own label is its full path (only the home row carries a separate + // secondary path), so the data-directory value and the label must agree. + if (recents.some((row) => row.label !== row.directory || row.directory === "")) { + throw new Error(`C2 recent rows are not labelled by full path: ${JSON.stringify(recents)}`); + } + console.log( + ` create pane: "${picker.title}" (back "${picker.back}"); home "${homeRow.label}" ` + + `${homeRow.path} selected; ${recents.length} recent(s); footer "${picker.start}"`, + ); + await shot("75-chat-create-picker.png"); + + // Choose home explicitly (it is already the default), then create exactly one + // session. The request body is recorded by the socket shim. + await page.click(".chat-create-choice"); + await page.evaluate(`window.__chatCreateBodies = []`); + await page.click(".chat-create-confirm"); + const beforeCreate = await page.evaluate( + `document.querySelector(".chat-row.selected")?.dataset.session ?? ""`, + ); + const createdId = await eventually( + async () => { + const id = await page.evaluate(`document.querySelector(".chat-row.selected")?.dataset.session ?? ""`); + return id && id !== beforeCreate ? id : false; + }, + { timeout: 30000, what: "the C2-created session to be selected" }, + ); + createdSessionId = createdId; + const created = await page.evaluate(`(() => { + const rows = [...document.querySelectorAll("#chatRows .chat-row")]; + const row = document.querySelector('.chat-row[data-session="${createdId}"]'); + return { + first: rows[0]?.dataset.session ?? "", + title: row?.querySelector(".chat-row-title")?.textContent ?? "", + selected: row?.classList.contains("selected") ?? false, + closed: !!row?.querySelector(".chat-closed-chip"), + header: document.querySelector(".chat-bar-title")?.textContent ?? "", + empty: document.querySelector(".chat-detail .chat-transcript-empty")?.textContent ?? "", + composer: !!document.querySelector("#chatComposer"), + pickerGone: !document.querySelector(".chat-create"), + }; + })()`); + const createBodies = await page.evaluate(`window.__chatCreateBodies || []`); + if (createBodies.length !== 1) { + throw new Error(`C2 sent ${createBodies.length} chat_create request(s) for one create`); + } + const body = createBodies[0] ?? {}; + if ( + body.title !== "New chat" || + body.directory !== "~" || + typeof body.operation_id !== "string" || + body.operation_id === "" || + Object.keys(body).sort().join(",") !== "directory,operation_id,title" + ) { + throw new Error(`C2 chat_create body: ${JSON.stringify(body)}`); + } + if (!created.pickerGone || !created.selected || created.closed) { + throw new Error(`C2 did not close the pane onto the new conversation: ${JSON.stringify(created)}`); + } + if (created.first !== createdId) { + throw new Error(`C2 created row is not at the head: first=${created.first} created=${createdId}`); + } + if (created.title !== "New chat" || created.header !== "New chat") { + throw new Error(`C2 created title: ${JSON.stringify(created)}`); + } + if (created.empty !== "This chat has no messages yet. Ask something below." || !created.composer) { + throw new Error(`C2 did not load the empty conversation: ${JSON.stringify(created)}`); + } + console.log( + ` chat_create sent exactly {title:"New chat",directory:"~",operation_id:${JSON.stringify(body.operation_id)}}; ` + + `session ${createdId} at the head, active with empty history`, + ); + await shot("76-chat-created-list.png"); + + // Close the one real session it created (chat_close through the C3 confirm) and + // capture the Closed chip. Nothing is deleted; the row stays as closed history. + await page.click(`#chatRows .chat-row[data-session="${createdId}"] .chat-close`); + await page.waitForSelector(".confirm-chat-close", { timeout: 15000 }); + await page.click(".confirm-chat-close .confirm-accept"); + await eventually( + () => + page.evaluate( + `!!document.querySelector('.chat-row[data-session="${createdId}"] .chat-closed-chip')`, + ), + { timeout: 20000, what: "the C2 session to show as closed" }, + ); + const createdClosed = await page.evaluate(`(() => { + const row = document.querySelector('.chat-row[data-session="${createdId}"]'); + row?.scrollIntoView({ block: "center" }); + return { + closed: !!row?.querySelector(".chat-closed-chip"), + hasClose: !!row?.querySelector(".chat-close"), + hasReopen: !!row?.querySelector(".chat-reopen"), + }; + })()`); + if (!createdClosed.closed || createdClosed.hasClose || !createdClosed.hasReopen) { + throw new Error(`C2 closed row: ${JSON.stringify(createdClosed)}`); + } + console.log( + ` C2: created real session ${createdId} ("New chat" in ~) and closed it via chat_close; ` + + "it now shows the Closed chip (kept as history, not deleted)", + ); + await shot("77-chat-created-closed.png"); + createdSessionId = null; + // The live session set changes between runs: the first row can be a // freshly-created empty "New chat" (which renders the empty state, not a // transcript). Prefer the operator's own session; otherwise try the listed rows // in order until one carries a real transcript, and say plainly if none does, // rather than waiting on a hard-coded session that the server no longer lists. - const expectedSession = "ses_eae413f50ffeLQDExlg8cYnscN"; const preferred = chatList.rows.find((row) => row.id === expectedSession); const openRows = chatList.rows.filter((row) => row.close).map((row) => row.id); const candidates = [ @@ -5004,6 +5197,38 @@ try { } } } finally { + // Best-effort cleanup of C2's real session: if the run failed between creating + // it and its own close, close it now so it never sits active in the operator's + // list. Nothing is deleted either way. + if (createdSessionId && page) { + try { + const closed = await page.evaluate( + `!!document.querySelector('.chat-row[data-session="${createdSessionId}"] .chat-closed-chip')`, + ); + if (!closed) { + await page.evaluate( + `document.querySelector('#chatRows .chat-row[data-session="${createdSessionId}"]')?.click()`, + ); + await page.waitForSelector("#chatInput", { timeout: 8000 }).catch(() => {}); + await page.evaluate(`(async () => { + const input = document.querySelector("#chatInput"); + if (!input) return; + input.value = "/close"; + input.dispatchEvent(new Event("input", { bubbles: true })); + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true })); + await new Promise((resolve) => setTimeout(resolve, 400)); + document.querySelector(".confirm-chat-close .confirm-accept")?.click(); + })()`); + await eventually(() => page.evaluate(`!document.querySelector(".confirm-chat-close")`), { + timeout: 8000, + what: "the C2 cleanup close to finish", + }).catch(() => {}); + console.log(` cleanup: closed the C2-created session ${createdSessionId}`); + } + } catch { + // the page may already be gone; the failure above is the real signal + } + } // Best-effort cleanup of the throwaway session this run created: if the run // failed before its `/close` step, close it now so it is never left open. if (throwawaySessionId && page) {