web: local rename/hide, seen markers and per-device persistence (C13)

This commit is contained in:
2026-10-19 13:50:13 +01:00
parent bcc3835fba
commit 3d7ad54e68
6 changed files with 1336 additions and 92 deletions
+8 -5
View File
@@ -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
+448 -45
View File
@@ -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.
+262
View File
@@ -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)
// ---------------------------------------------------------------------------
+64 -2
View File
@@ -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); }
+191
View File
@@ -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);
});
+363 -40
View File
@@ -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}`);
}