Merge branch 'main' into web-settings
This commit is contained in:
+1
-1
@@ -97,7 +97,7 @@ the pipeline list already carries — rather than a pluralised verb.
|
||||
| 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) |
|
||||
| C10 | Permission/approval cards (allow once/always/reject) | `chat_permission`, `chat_reply` | todo |
|
||||
| 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 |
|
||||
|
||||
+446
-12
@@ -2,7 +2,7 @@
|
||||
// Deliberately small and DOM-only (no framework, no build step). Every value
|
||||
// that came from the server is set with textContent, never innerHTML.
|
||||
import { PipelinesClient } from "./client.js";
|
||||
import { PipelinesRepository } from "./repository.js";
|
||||
import { PipelinesRepository, SHELL_OUTPUT_LIMIT } from "./repository.js";
|
||||
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
|
||||
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
|
||||
import {
|
||||
@@ -227,6 +227,7 @@ import {
|
||||
retryRequestKey,
|
||||
} from "./actions.js";
|
||||
import {
|
||||
BACKGROUND_TASKS_TITLE,
|
||||
CHAT_ATTACH_LABEL,
|
||||
CHAT_COMMAND_GLYPH,
|
||||
CHAT_COMPOSER_PLACEHOLDER,
|
||||
@@ -253,10 +254,29 @@ import {
|
||||
LOAD_OLDER_ACTION,
|
||||
REOPEN_ACTION,
|
||||
SELECT_CHAT_HINT,
|
||||
APPROVAL_CONTROL_ALWAYS,
|
||||
APPROVAL_CONTROL_ONCE,
|
||||
APPROVAL_CONTROL_REJECT,
|
||||
DECISION_ALWAYS,
|
||||
DECISION_ONCE,
|
||||
DECISION_REJECT,
|
||||
RISK_REVIEW_LABEL,
|
||||
WAITING_FOR_APPROVAL_LABEL,
|
||||
SHELL_DETAILS_LABEL,
|
||||
SHELL_OUTPUT_EMPTY,
|
||||
SHELL_OUTPUT_ERROR,
|
||||
SHELL_OUTPUT_LABELS,
|
||||
SHELL_OUTPUT_LOADING,
|
||||
SHELL_OUTPUT_READY,
|
||||
SHELL_OUTPUT_UNAVAILABLE,
|
||||
SHELL_ROW_LABEL,
|
||||
applyChatEvent,
|
||||
applyChatPermission,
|
||||
approvalCard,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
backgroundTasksRunningLabel,
|
||||
chatBottomDistancePx,
|
||||
chatCommandEffect,
|
||||
chatCommandHelp,
|
||||
@@ -278,11 +298,14 @@ import {
|
||||
groupSessionsByDirectory,
|
||||
historyResync,
|
||||
mergeHistoryPage,
|
||||
mergeShellFrame,
|
||||
newChatThread,
|
||||
parseChatInput,
|
||||
queuedAfterFrame,
|
||||
reasoningLabel,
|
||||
resumedThread,
|
||||
runningAfterFrame,
|
||||
runningBackgroundShells,
|
||||
runningToolElapsedMillis,
|
||||
sessionActivity,
|
||||
sessionActivityBadge,
|
||||
@@ -292,6 +315,9 @@ import {
|
||||
sessionTitle,
|
||||
sessionWorkLabel,
|
||||
settledThread,
|
||||
shellCommandSummary,
|
||||
shellOutputState,
|
||||
shellsLoaded,
|
||||
formatToolDuration,
|
||||
threadElapsedMillis,
|
||||
threadPhase,
|
||||
@@ -3990,6 +4016,9 @@ async function openChatSession(id) {
|
||||
// Attach the shared live stream once per session per connection; its failure is
|
||||
// non-fatal — history stays usable and the badge reads "not live".
|
||||
subscribeChatSession(id);
|
||||
// Load the session's background shells (C11) so the bar appears on open, not
|
||||
// only after the next pushed shell frame.
|
||||
loadChatShells(id);
|
||||
await loadChatHistory(id);
|
||||
}
|
||||
|
||||
@@ -4024,13 +4053,18 @@ function clearChatSubscriptions() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Settle every conversation that was running. A socket drop (or a close) removes
|
||||
* the frames feeding the turn, so no thread keeps claiming to run until a fresh
|
||||
* frame proves otherwise.
|
||||
* Settle every conversation that was running, and drop its observed shells. A
|
||||
* socket drop (or a close) removes the frames feeding the turn, so no thread
|
||||
* keeps claiming to run until a fresh frame proves otherwise; a shell's exit may
|
||||
* have been swallowed by the same gap, so the retained shells are forgotten and
|
||||
* re-learned from `chat_shells` on reconnect (mirrors ChatStore.streamResumed).
|
||||
*/
|
||||
function settleChatThreads() {
|
||||
for (const [id, thread] of state.chatThreads) {
|
||||
if (thread?.running || thread?.queued) state.chatThreads.set(id, settledThread(thread));
|
||||
const hasShells = (thread?.shells ?? []).length > 0;
|
||||
if (thread?.running || thread?.queued || hasShells) {
|
||||
state.chatThreads.set(id, resumedThread(thread));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4048,24 +4082,173 @@ function onChatEvent(frame) {
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fold one pushed `chat_permission` frame into its conversation (C10). Only a
|
||||
* conversation this client has open is folded — the server only pushes a
|
||||
* permission frame for sessions this connection is subscribed to, but the guard
|
||||
* keeps a frame for a session nobody opened from creating a thread. The card is
|
||||
* derived from the stored frame plus the local answer, so a resolved re-push
|
||||
* always clears the controls.
|
||||
*/
|
||||
function onChatPermission(frame) {
|
||||
const sessionId = String(frame?.session_id ?? "").trim();
|
||||
if (!sessionId || !state.chatThreads.has(sessionId)) return;
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
const next = applyChatPermission(thread, frame);
|
||||
// A different request replaces the card, so the previous refusal's reason (and
|
||||
// the error line it owns) no longer describes what is on screen.
|
||||
const replaced =
|
||||
String(thread?.permission?.request_id ?? "") !== String(next.permission?.request_id ?? "");
|
||||
if (replaced && thread?.permissionError) {
|
||||
next.error = thread.error === thread.permissionError ? "" : next.error;
|
||||
next.permissionError = "";
|
||||
}
|
||||
state.chatThreads.set(sessionId, next);
|
||||
if (sessionId === state.chatActiveId) renderContent();
|
||||
}
|
||||
|
||||
/**
|
||||
* Answer the pending permission request (C10): settle the matching card
|
||||
* optimistically so the buttons are never left offering a decision already made,
|
||||
* then send `chat_reply`. A refused reply reopens the same request (the local
|
||||
* answer is cleared) and surfaces the server's reason through the thread's own
|
||||
* error line, so an unaccepted decision is never shown as accepted. A refusal
|
||||
* that arrives after a different request replaced the card is ignored.
|
||||
*/
|
||||
async function answerPermission(sessionId, requestId, decision) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
const permission = thread?.permission;
|
||||
if (!thread || String(permission?.request_id ?? "") !== requestId) return;
|
||||
setThread(sessionId, { permissionAnswer: decision });
|
||||
renderContent();
|
||||
try {
|
||||
await repo.chatReply(sessionId, requestId, decision);
|
||||
// A retried answer the server accepted clears the reason a previous refusal
|
||||
// left on the thread's error line — and only that reason, never an unrelated
|
||||
// error the conversation is carrying.
|
||||
const settled = state.chatThreads.get(sessionId);
|
||||
if (settled?.permissionError && settled.error === settled.permissionError) {
|
||||
setThread(sessionId, { error: "", permissionError: "" });
|
||||
renderContent();
|
||||
}
|
||||
} catch (error) {
|
||||
const current = state.chatThreads.get(sessionId);
|
||||
if (!current || String(current.permission?.request_id ?? "") !== requestId) return;
|
||||
const reason = describeError(error);
|
||||
setThread(sessionId, { permissionAnswer: "", error: reason, permissionError: reason });
|
||||
renderContent();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The reconnect repair (C5): re-attach the open chat's stream and replace its
|
||||
* conversation with the newest history page wholesale. Everything the gap could
|
||||
* have missed is repaired; a turn that was in flight is settled. Only the open
|
||||
* conversation is repaired — the others are not on screen.
|
||||
* Fetch a session's currently verified shells (C11) and retain only the exits
|
||||
* this client itself observed, so an exited task never reappears as running and a
|
||||
* shell the server no longer lists drops out. Called when the conversation opens
|
||||
* and on every stream reconnect (a gap may have swallowed an exit). A failure is
|
||||
* non-fatal: the transcript stays usable and the bar keeps its last known state.
|
||||
*/
|
||||
async function loadChatShells(id) {
|
||||
if (!id || state.connection.kind !== "connected") return;
|
||||
try {
|
||||
const running = await repo.chatShells(id);
|
||||
const thread = state.chatThreads.get(id);
|
||||
if (!thread) return;
|
||||
state.chatThreads.set(id, { ...thread, shells: shellsLoaded(thread.shells, running) });
|
||||
renderContent();
|
||||
} catch {
|
||||
// The shell list is a background convenience; leave the thread untouched.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle a running task's detail pane (C11). Selecting a shell fetches its
|
||||
* bounded output page; selecting the selected one again closes it. Mirrors
|
||||
* ChatStore.selectShell: an id that is not a known shell is ignored.
|
||||
*/
|
||||
function selectChatShell(shellId) {
|
||||
const sessionId = state.chatActiveId;
|
||||
const thread = sessionId ? state.chatThreads.get(sessionId) : null;
|
||||
if (!thread) return;
|
||||
const closing = thread.selectedShellId === shellId;
|
||||
if (!closing && !(thread.shells ?? []).some((shell) => shell.id === shellId)) return;
|
||||
const next = closing ? null : shellId;
|
||||
state.chatThreads.set(sessionId, { ...thread, selectedShellId: next, shellOutput: null });
|
||||
renderContent();
|
||||
if (next) refreshChatShellOutput(next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reread a selected task's bounded output page (C11) from the page's start. The
|
||||
* cursor is always 0 and the limit is the server's 64 KiB bound, so the client
|
||||
* never grows output unbounded and a Refresh never appends. A reply for a shell
|
||||
* that is no longer selected is ignored, exactly like ChatStore.shellOutput*.
|
||||
*/
|
||||
async function refreshChatShellOutput(shellId) {
|
||||
const sessionId = state.chatActiveId;
|
||||
if (!sessionId || !shellId) return;
|
||||
shellOutputLoading(sessionId, shellId);
|
||||
renderContent();
|
||||
try {
|
||||
const page = await repo.chatShellOutput(sessionId, shellId, { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
|
||||
shellOutputLoaded(sessionId, shellId, page);
|
||||
} catch (error) {
|
||||
shellOutputFailed(sessionId, shellId, describeError(error));
|
||||
}
|
||||
renderContent();
|
||||
}
|
||||
|
||||
/** Mark a selected task's output pane loading (ignored for a stale selection). */
|
||||
function shellOutputLoading(sessionId, shellId) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread || thread.selectedShellId !== shellId) return;
|
||||
state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: true, error: "", page: null } });
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a loaded output page, merging a shell the page reports back into the
|
||||
* retained list (keeping the command already learned when the page omits it).
|
||||
*/
|
||||
function shellOutputLoaded(sessionId, shellId, page) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread || thread.selectedShellId !== shellId) return;
|
||||
const reported = page?.shell;
|
||||
const shells = reported && String(reported.id ?? "").trim() !== ""
|
||||
? mergeShellFrame(thread.shells, reported)
|
||||
: thread.shells ?? [];
|
||||
state.chatThreads.set(sessionId, { ...thread, shells, shellOutput: { loading: false, error: "", page } });
|
||||
}
|
||||
|
||||
/** Report a failed output read against the still-selected task (Retry is offered). */
|
||||
function shellOutputFailed(sessionId, shellId, message) {
|
||||
const thread = state.chatThreads.get(sessionId);
|
||||
if (!thread || thread.selectedShellId !== shellId) return;
|
||||
state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: false, error: message, page: null } });
|
||||
}
|
||||
|
||||
/**
|
||||
* The reconnect repair (C5/C11): re-attach the open chat's stream, replace its
|
||||
* conversation with the newest history page wholesale and re-learn its shells.
|
||||
* Everything the gap could have missed is repaired; a turn that was in flight is
|
||||
* settled and the retained shells are dropped before the fresh snapshot arrives.
|
||||
* Only the open conversation is repaired — the others are not on screen.
|
||||
*/
|
||||
async function resyncOpenChat() {
|
||||
const id = state.chatActiveId;
|
||||
if (!id || state.connection.kind !== "connected") return;
|
||||
await subscribeChatSession(id);
|
||||
const previous = state.chatThreads.get(id) ?? newChatThread(id);
|
||||
state.chatThreads.set(id, settledThread(previous));
|
||||
state.chatThreads.set(id, resumedThread(previous));
|
||||
try {
|
||||
const page = await repo.chatHistory(id);
|
||||
state.chatThreads.set(id, historyResync(previous, page));
|
||||
} catch {
|
||||
// The history refresh failed; the settled thread stands and the badge is honest.
|
||||
}
|
||||
await loadChatShells(id);
|
||||
renderContent();
|
||||
}
|
||||
|
||||
@@ -4751,6 +4934,11 @@ function renderChatConversation() {
|
||||
const session = state.chatSessions.find((candidate) => candidate.id === state.chatActiveId) ?? null;
|
||||
const thread = state.chatThreads.get(state.chatActiveId) ?? null;
|
||||
const title = session ? sessionTitle(session) : 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).
|
||||
const approval = approvalCard(thread?.permission, thread?.permissionAnswer);
|
||||
const awaiting = approval?.actionable === true;
|
||||
|
||||
const bar = h("div", { class: "chat-bar" });
|
||||
const titles = h("div", { class: "chat-bar-titles" });
|
||||
@@ -4773,6 +4961,10 @@ function renderChatConversation() {
|
||||
}),
|
||||
);
|
||||
}
|
||||
// The approval jump control appears only while a request is actionable, and
|
||||
// brings its card (the transcript's last item) into view — the one scroll path,
|
||||
// so a pending request is reached the same way new content is.
|
||||
if (awaiting) bar.append(approvalJumpButton());
|
||||
pane.append(bar);
|
||||
|
||||
// The context line: the kind chip, the activity word and directory · model.
|
||||
@@ -4800,6 +4992,12 @@ function renderChatConversation() {
|
||||
if (contextMeta !== "") context.append(h("span", { class: "chat-context-meta muted", text: contextMeta }));
|
||||
pane.append(context);
|
||||
|
||||
// The background-tasks bar (C11) sits above the transcript, outside the
|
||||
// scroller so the C14 scroll positions are untouched. It is present only while
|
||||
// a shell is still running and disappears with the last exit.
|
||||
const backgroundTasks = renderBackgroundTasks(thread);
|
||||
if (backgroundTasks) pane.append(backgroundTasks);
|
||||
|
||||
const notices = thread?.notices ?? [];
|
||||
if (thread?.loading && !thread?.loaded) {
|
||||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_LOADING }));
|
||||
@@ -4816,11 +5014,16 @@ function renderChatConversation() {
|
||||
pane.append(empty);
|
||||
} else {
|
||||
const rows = transcriptRows(thread?.messages ?? []);
|
||||
const running = thread?.running === true;
|
||||
if (rows.length === 0 && notices.length === 0 && !running) {
|
||||
// The running indicator stands down while an approval is pending (C10): a turn
|
||||
// blocked on a decision is not generating, so neither the spinner nor its clock
|
||||
// shows. The composer's Stop control stays governed by thread.running.
|
||||
const running = thread?.running === true && !awaiting;
|
||||
if (rows.length === 0 && notices.length === 0 && !running && !approval) {
|
||||
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
|
||||
} else {
|
||||
pane.append(renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now() }));
|
||||
pane.append(
|
||||
renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now(), approval }),
|
||||
);
|
||||
}
|
||||
if (thread?.error && thread?.loaded) {
|
||||
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
|
||||
@@ -4845,6 +5048,126 @@ function appendChatDialogs(pane) {
|
||||
if (state.actionError) pane.append(renderActionFailedDialog());
|
||||
}
|
||||
|
||||
/**
|
||||
* The background-tasks bar (C11): the running shells this conversation still
|
||||
* owns. It returns null (renders nothing) unless at least one shell is running,
|
||||
* so it disappears the moment the last task exits. Heading `Background tasks` +
|
||||
* `{n} running`; the list shows at most BACKGROUND_TASK_VISIBLE_ROWS rows and
|
||||
* scrolls beyond; a selected row reveals its bounded, read-only output pane.
|
||||
* Every server string is set with textContent (never innerHTML).
|
||||
*/
|
||||
function renderBackgroundTasks(thread) {
|
||||
const running = runningBackgroundShells(thread?.shells ?? []);
|
||||
if (running.length === 0) return null;
|
||||
const wrap = h("section", { class: "chat-bg-tasks", id: "chatBackgroundTasks" });
|
||||
const head = h("div", { class: "chat-bg-tasks-head" });
|
||||
head.append(h("span", { class: "chat-bg-tasks-title", text: BACKGROUND_TASKS_TITLE }));
|
||||
head.append(
|
||||
h("span", { class: "chat-bg-tasks-count muted", text: backgroundTasksRunningLabel(running.length) }),
|
||||
);
|
||||
wrap.append(head);
|
||||
const list = h("div", { class: "chat-bg-tasks-list" });
|
||||
const selectedId = thread?.selectedShellId ?? null;
|
||||
running.forEach((shell) => list.append(renderBackgroundTaskRow(shell, shell.id === selectedId)));
|
||||
wrap.append(list);
|
||||
const selected = running.find((shell) => shell.id === selectedId) ?? null;
|
||||
if (selected) wrap.append(renderBackgroundTaskDetail(thread, selected));
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** One running shell task; tapping it toggles its detail pane. */
|
||||
function renderBackgroundTaskRow(shell, selected) {
|
||||
const row = h("button", {
|
||||
class: `chat-bg-task${selected ? " selected" : ""}`,
|
||||
type: "button",
|
||||
"data-shell": shell.id,
|
||||
"aria-pressed": selected ? "true" : "false",
|
||||
onclick: () => selectChatShell(shell.id),
|
||||
});
|
||||
// A CSS play glyph, decorative only (the row's own text names the task).
|
||||
row.append(h("span", { class: "chat-bg-task-glyph", "aria-hidden": "true" }));
|
||||
row.append(h("span", { class: "chat-bg-task-status", text: SHELL_ROW_LABEL }));
|
||||
row.append(
|
||||
h("span", {
|
||||
class: "chat-bg-task-command",
|
||||
text: shellCommandSummary(shell.command),
|
||||
title: String(shell.command ?? ""),
|
||||
}),
|
||||
);
|
||||
if (selected) row.append(h("span", { class: "chat-bg-task-details muted", text: SHELL_DETAILS_LABEL }));
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* The selected task's read-only detail: its command, its identity in monospace
|
||||
* and `Status: running`, then the output area — the exact label order and wording
|
||||
* of ChatTranscript.BackgroundProcessDetail. Reload is always a bounded reread
|
||||
* from the page's start (`Refresh`; `Retry` after a failure).
|
||||
*/
|
||||
function renderBackgroundTaskDetail(thread, shell) {
|
||||
const labels = SHELL_OUTPUT_LABELS;
|
||||
const pane = h("div", { class: "chat-bg-task-detail" });
|
||||
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.COMMAND }));
|
||||
const command = String(shell.command ?? "").trim();
|
||||
pane.append(
|
||||
h("div", {
|
||||
class: "chat-bg-task-command-full",
|
||||
text: command === "" ? labels.UNAVAILABLE : shell.command,
|
||||
}),
|
||||
);
|
||||
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.TASK_IDENTITY }));
|
||||
pane.append(h("div", { class: "chat-bg-task-id monospace", text: String(shell.id ?? "") }));
|
||||
pane.append(h("div", { class: "chat-bg-task-status-line", text: labels.STATUS_RUNNING }));
|
||||
|
||||
const output = thread?.shellOutput ?? null;
|
||||
switch (shellOutputState(output)) {
|
||||
case SHELL_OUTPUT_LOADING:
|
||||
pane.append(h("span", { class: "spinner chat-bg-task-spinner", "aria-hidden": "true" }));
|
||||
break;
|
||||
case SHELL_OUTPUT_ERROR: {
|
||||
const row = h("div", { class: "chat-bg-task-error-row" });
|
||||
row.append(h("span", { class: "chat-bg-task-error", text: output.error }));
|
||||
row.append(
|
||||
h("button", {
|
||||
class: "ghost chat-bg-task-retry",
|
||||
type: "button",
|
||||
text: labels.RETRY,
|
||||
onclick: () => refreshChatShellOutput(shell.id),
|
||||
}),
|
||||
);
|
||||
pane.append(row);
|
||||
break;
|
||||
}
|
||||
case SHELL_OUTPUT_UNAVAILABLE:
|
||||
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_UNAVAILABLE }));
|
||||
break;
|
||||
case SHELL_OUTPUT_EMPTY:
|
||||
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.NO_OUTPUT }));
|
||||
break;
|
||||
case SHELL_OUTPUT_READY: {
|
||||
const page = output.page;
|
||||
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.OUTPUT }));
|
||||
// Untrusted shell text: set as textContent, never parsed as markup.
|
||||
pane.append(h("pre", { class: "chat-bg-task-output", text: String(page.output ?? "") }));
|
||||
if (page.truncated) {
|
||||
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_BOUNDED }));
|
||||
}
|
||||
pane.append(
|
||||
h("button", {
|
||||
class: "ghost chat-bg-task-refresh",
|
||||
type: "button",
|
||||
text: labels.REFRESH,
|
||||
onclick: () => refreshChatShellOutput(shell.id),
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return pane;
|
||||
}
|
||||
|
||||
/**
|
||||
* The transcript: one column of turns. An operator message is its own
|
||||
* right-aligned bubble (with the sending client's label when the server echoed
|
||||
@@ -4852,7 +5175,11 @@ function appendChatDialogs(pane) {
|
||||
* in order as the reasoning block, then the tool-call chip, then the answer
|
||||
* markdown. No timestamps, model or agent are shown inside the transcript.
|
||||
*/
|
||||
function renderChatTranscript(sessionId, rows, { notices = [], running = false, now = Date.now() } = {}) {
|
||||
function renderChatTranscript(
|
||||
sessionId,
|
||||
rows,
|
||||
{ notices = [], running = false, now = Date.now(), approval = null } = {},
|
||||
) {
|
||||
const wrap = h("div", { class: "chat-transcript-wrap" });
|
||||
const transcript = h("div", {
|
||||
class: "chat-transcript",
|
||||
@@ -4879,6 +5206,10 @@ function renderChatTranscript(sessionId, rows, { notices = [], running = false,
|
||||
// The conversation's local command lines sit after the turns, full width and
|
||||
// deliberately unlike a message bubble (see ChatCommandNoticeItem).
|
||||
for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice));
|
||||
// The approval card is the transcript's last item (C10) — after the notices and
|
||||
// after the running indicator when it is shown — so the top bar's jump control
|
||||
// and a fresh card both land at the end.
|
||||
if (approval) transcript.append(renderChatApproval(sessionId, approval));
|
||||
wrap.append(transcript);
|
||||
wrap.append(
|
||||
h("button", {
|
||||
@@ -4898,6 +5229,102 @@ function renderChatTranscript(sessionId, rows, { notices = [], running = false,
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** The top bar's approval jump control (C10), naming the pending request. */
|
||||
function approvalJumpButton() {
|
||||
return h("button", {
|
||||
class: "ghost chat-approval-jump",
|
||||
type: "button",
|
||||
text: WAITING_FOR_APPROVAL_LABEL,
|
||||
onclick: () => {
|
||||
// The card is the transcript's last item, so the transcript's own end is the
|
||||
// card; the one scroll path shared with jump-to-latest.
|
||||
const el = document.getElementById("chatTranscript");
|
||||
if (!el) return;
|
||||
state.chatFollowing = true;
|
||||
el.scrollTop = el.scrollHeight;
|
||||
updateChatJump(el);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One approval request as a card (C10), the browser's port of
|
||||
* `ui/chat/ChatApprovalCard.kt`: a shield and the headline, the status line, the
|
||||
* request's resources newline-joined in monospace (blank entries dropped, at most
|
||||
* six lines), the amber `RISK REVIEW` panel only while the app shows it, and the
|
||||
* once/always/reject controls only while the request is actionable. Every server
|
||||
* string is set with textContent and every node is built by hand.
|
||||
*/
|
||||
function renderChatApproval(sessionId, card) {
|
||||
const node = h("div", {
|
||||
class: `chat-approval${card.actionable ? " chat-approval-pending" : ""}`,
|
||||
id: "chatApproval",
|
||||
"data-request-id": card.requestId,
|
||||
});
|
||||
const head = h("div", { class: "chat-approval-head" });
|
||||
head.append(shieldIcon("chat-approval-shield"));
|
||||
const titles = h("div", { class: "chat-approval-titles" });
|
||||
titles.append(h("div", { class: "chat-approval-headline", text: card.headline }));
|
||||
titles.append(h("div", { class: "chat-approval-status muted", text: card.statusLine }));
|
||||
head.append(titles);
|
||||
node.append(head);
|
||||
if (card.resourceText !== "") {
|
||||
// The padded frame around a padding-free clamp block: clamping the padded
|
||||
// element itself lets the seventh line paint into its bottom padding.
|
||||
const box = h("div", { class: "chat-approval-resources" });
|
||||
box.append(h("pre", { class: "chat-approval-resources-text", text: card.resourceText }));
|
||||
node.append(box);
|
||||
}
|
||||
if (card.showRisk && card.risk.trim() !== "") {
|
||||
const risk = h("div", { class: "chat-approval-risk" });
|
||||
const riskHead = h("div", { class: "chat-approval-risk-head" });
|
||||
riskHead.append(shieldIcon("chat-approval-risk-shield"));
|
||||
riskHead.append(h("span", { class: "chat-approval-risk-label", text: RISK_REVIEW_LABEL }));
|
||||
risk.append(riskHead);
|
||||
risk.append(h("div", { class: "chat-approval-risk-text", text: card.risk }));
|
||||
node.append(risk);
|
||||
}
|
||||
if (card.actionable) {
|
||||
const controls = h("div", { class: "chat-approval-controls" });
|
||||
controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary"));
|
||||
controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
|
||||
controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId));
|
||||
node.append(controls);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/**
|
||||
* The app's amber outlined Shield (`Icons.Outlined.Shield`): an inline SVG stroked
|
||||
* with `currentColor` so the palette's warn hue actually tints it, unlike the
|
||||
* colour emoji it replaces. Decorative — the headline carries the meaning.
|
||||
*/
|
||||
function shieldIcon(className) {
|
||||
const NS = "http://www.w3.org/2000/svg";
|
||||
const svg = document.createElementNS(NS, "svg");
|
||||
svg.setAttribute("class", className);
|
||||
svg.setAttribute("viewBox", "0 0 24 24");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
svg.setAttribute("focusable", "false");
|
||||
const path = document.createElementNS(NS, "path");
|
||||
path.setAttribute("d", "M12 3 5 6v5.5c0 4.2 2.8 8.1 7 9.5 4.2-1.4 7-5.3 7-9.5V6l-7-3z");
|
||||
path.setAttribute("fill", "none");
|
||||
path.setAttribute("stroke", "currentColor");
|
||||
path.setAttribute("stroke-width", "1.8");
|
||||
path.setAttribute("stroke-linejoin", "round");
|
||||
svg.append(path);
|
||||
return svg;
|
||||
}
|
||||
|
||||
function approvalControl(label, decision, sessionId, requestId, extraClass = "") {
|
||||
return h("button", {
|
||||
class: `chat-approval-control${extraClass ? ` ${extraClass}` : ""}`,
|
||||
type: "button",
|
||||
text: label,
|
||||
onclick: () => answerPermission(sessionId, requestId, decision),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The in-flight turn's indicator: a spinner, the phase headline (`Thinking…` /
|
||||
* `Running a tool…` / `Waiting…`), `· {elapsed}`, then one line per running tool
|
||||
@@ -6414,7 +6841,8 @@ function refreshChatClock() {
|
||||
stopChatClock();
|
||||
chatNow = Date.now();
|
||||
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
|
||||
if (state.view === "chat" && thread?.running) {
|
||||
const awaiting = approvalCard(thread?.permission, thread?.permissionAnswer)?.actionable === true;
|
||||
if (state.view === "chat" && thread?.running && !awaiting) {
|
||||
chatClock = setInterval(() => {
|
||||
chatNow = Date.now();
|
||||
updateChatIndicator(chatNow);
|
||||
@@ -6491,7 +6919,13 @@ client.addEventListener("state", (event) => {
|
||||
// type is ignored.
|
||||
client.addEventListener("frame", (event) => {
|
||||
const message = event.detail;
|
||||
if (!message || message.type !== Protocol.CHAT_EVENT) return;
|
||||
if (!message) return;
|
||||
if (message.type === Protocol.CHAT_PERMISSION) {
|
||||
const permission = message[ChatKeys.PERMISSION];
|
||||
if (permission) onChatPermission(permission);
|
||||
return;
|
||||
}
|
||||
if (message.type !== Protocol.CHAT_EVENT) return;
|
||||
const frame = message[ChatKeys.EVENT];
|
||||
if (frame) onChatEvent(frame);
|
||||
onChatFrame(message);
|
||||
|
||||
+353
-6
@@ -302,6 +302,21 @@ export function toolDetail(part) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one-line command a background process is running, collapsed to a single
|
||||
* line and elided past [TOOL_DETAIL_MAX_LENGTH] like a tool call's detail, so a
|
||||
* long command line cannot flood the bar. A shell that reported no command reads
|
||||
* as a generic `background process` rather than a blank line (ChatFormat.kt
|
||||
* shellCommandSummary, which shares the tool-detail regex and bound).
|
||||
*/
|
||||
export function shellCommandSummary(command) {
|
||||
const text = str(command).trim().replace(/\s+/g, " ");
|
||||
if (text === "") return "background process";
|
||||
return text.length <= TOOL_DETAIL_MAX_LENGTH
|
||||
? text
|
||||
: text.slice(0, TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…";
|
||||
}
|
||||
|
||||
/**
|
||||
* The INPUT section of a tool call: pretty-printed JSON once the arguments are an
|
||||
* object/array, the raw partial-JSON string while still streaming, or empty when
|
||||
@@ -795,6 +810,141 @@ export function chatStreamState(connectionKind, subscribed) {
|
||||
return { tone: "not-live", label: STREAM_OFFLINE };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Background shells (C11: ChatTranscript.kt BackgroundProcessBar, ChatStore.kt
|
||||
// applyShell/shellsLoaded, ChatFormat.kt runningBackgroundShells/shellCommandSummary)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* ChatShell.Status values (internal/protocol/chat.go). A running shell is one
|
||||
* whose command has started and not yet exited; `exited` is final.
|
||||
*/
|
||||
export const SHELL_RUNNING = "running";
|
||||
export const SHELL_EXITED = "exited";
|
||||
|
||||
/**
|
||||
* Per-session in-memory observation bound (ChatStore.OBSERVED_SHELL_LIMIT): the
|
||||
* retained shell tail a selected task can settle against. This is not task
|
||||
* history, only what this client itself observed.
|
||||
*/
|
||||
export const OBSERVED_SHELL_LIMIT = 16;
|
||||
|
||||
/**
|
||||
* How many running-task rows the bar draws before the list scrolls instead of
|
||||
* growing (ChatTranscript.BACKGROUND_TASK_VISIBLE_ROWS).
|
||||
*/
|
||||
export const BACKGROUND_TASK_VISIBLE_ROWS = 3;
|
||||
|
||||
/** The bar's heading; its count line is `{n} running`. */
|
||||
export const BACKGROUND_TASKS_TITLE = "Background tasks";
|
||||
export function backgroundTasksRunningLabel(count) {
|
||||
return `${count} running`;
|
||||
}
|
||||
|
||||
/** A row's own words (ChatTranscript.BackgroundProcessLine). */
|
||||
export const SHELL_ROW_LABEL = "Running";
|
||||
export const SHELL_DETAILS_LABEL = "Details";
|
||||
|
||||
/**
|
||||
* The detail pane's exact wording, verbatim from
|
||||
* ChatTranscript.BackgroundProcessDetail. Kept as one frozen map so the pane and
|
||||
* its unit test share one string instead of the copy drifting.
|
||||
*/
|
||||
export const SHELL_OUTPUT_LABELS = Object.freeze({
|
||||
COMMAND: "Command",
|
||||
UNAVAILABLE: "Unavailable",
|
||||
TASK_IDENTITY: "Task identity",
|
||||
STATUS_RUNNING: "Status: running",
|
||||
OUTPUT_UNAVAILABLE: "Output unavailable for this task.",
|
||||
NO_OUTPUT: "No output yet.",
|
||||
OUTPUT: "Output",
|
||||
OUTPUT_BOUNDED: "Output is bounded to 64 KiB.",
|
||||
RETRY: "Retry",
|
||||
REFRESH: "Refresh",
|
||||
});
|
||||
|
||||
/**
|
||||
* The background processes still running for a session, in the order they
|
||||
* started, from the shells the server reported and the session retains. A shell
|
||||
* that has exited is never listed — that is what clears the bar — and the set is
|
||||
* independent of the turn, because a background process outlives the tool call
|
||||
* (and often the turn) that started it. Mirrors ChatFormat.runningBackgroundShells:
|
||||
* only a non-blank id with status `running` is a task, and the list is never
|
||||
* truncated here (the visible-row cap is a view concern).
|
||||
*/
|
||||
export function runningBackgroundShells(shells) {
|
||||
return (shells ?? []).filter(
|
||||
(shell) => !isBlank(shell?.id) && str(shell?.status) === SHELL_RUNNING,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds one shell frame (or a snapshot entry) into the retained shells, keyed by
|
||||
* id and kept in observation order. A blank incoming command keeps the command
|
||||
* already learned, so a later frame that omits it never blanks the row, and the
|
||||
* list is trimmed to the last [OBSERVED_SHELL_LIMIT] entries (ChatStore.applyShell).
|
||||
*/
|
||||
export function mergeShellFrame(shells, shell) {
|
||||
const id = str(shell?.id);
|
||||
if (shell == null || isBlank(id)) return shells ?? [];
|
||||
const list = (shells ?? []).slice();
|
||||
const index = list.findIndex((candidate) => str(candidate?.id) === id);
|
||||
const prior = index >= 0 ? list[index] : null;
|
||||
const merged = {
|
||||
...shell,
|
||||
id,
|
||||
command: isBlank(shell?.command) ? str(prior?.command) : shell.command,
|
||||
};
|
||||
if (index >= 0) list[index] = merged;
|
||||
else list.push(merged);
|
||||
return list.slice(-OBSERVED_SHELL_LIMIT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the retained shells with the authoritative running snapshot while
|
||||
* keeping only exits this client itself observed, capped like every other shell
|
||||
* list (ChatStore.shellsLoaded). A shell the server no longer lists and that this
|
||||
* client never saw exit simply drops out.
|
||||
*/
|
||||
export function shellsLoaded(shells, running) {
|
||||
const byId = new Map();
|
||||
for (const shell of shells ?? []) {
|
||||
if (!isBlank(shell?.id) && str(shell?.status) === SHELL_EXITED) byId.set(shell.id, shell);
|
||||
}
|
||||
for (const shell of running ?? []) {
|
||||
if (isBlank(shell?.id)) continue;
|
||||
// Map.set keeps the first-insertion position and replaces the value, exactly
|
||||
// like Kotlin's `observedExits + live` LinkedHashMap merge.
|
||||
byId.set(shell.id, shell);
|
||||
}
|
||||
return [...byId.values()].slice(-OBSERVED_SHELL_LIMIT);
|
||||
}
|
||||
|
||||
/** The five shapes a selected task's output area can take. */
|
||||
export const SHELL_OUTPUT_LOADING = "loading";
|
||||
export const SHELL_OUTPUT_ERROR = "error";
|
||||
export const SHELL_OUTPUT_UNAVAILABLE = "unavailable";
|
||||
export const SHELL_OUTPUT_EMPTY = "empty";
|
||||
export const SHELL_OUTPUT_READY = "output";
|
||||
|
||||
/**
|
||||
* Which branch the detail pane's output area shows for a selected task's
|
||||
* [output] state, or null when there is nothing to show yet — the same decision
|
||||
* order as ChatTranscript.BackgroundProcessDetail's `when` (loading, then error,
|
||||
* then the server's `unavailable`, then an empty page, then a readable page), so
|
||||
* the pane and its unit test share one derivation.
|
||||
*/
|
||||
export function shellOutputState(output) {
|
||||
if (output == null) return null;
|
||||
if (output.loading) return SHELL_OUTPUT_LOADING;
|
||||
if (str(output.error) !== "") return SHELL_OUTPUT_ERROR;
|
||||
const page = output.page ?? null;
|
||||
if (page == null) return null;
|
||||
if (page.unavailable === true) return SHELL_OUTPUT_UNAVAILABLE;
|
||||
if (str(page.output) === "") return SHELL_OUTPUT_EMPTY;
|
||||
return SHELL_OUTPUT_READY;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape an open conversation holds. The first six fields are the ones a
|
||||
* history page fills; the rest is the live stream (see `ChatThread` in
|
||||
@@ -815,6 +965,20 @@ export function newChatThread(sessionId = "") {
|
||||
toolStartedAt: {},
|
||||
lastDeltaAt: 0,
|
||||
queued: false,
|
||||
// C10: the session's current permission request (the last `chat_permission`
|
||||
// frame the server pushed) and the operator's local answer to it
|
||||
// (`once`/`always`/`reject`, or blank). The approval card and its controls
|
||||
// derive from the two (see `approvalCard`).
|
||||
permission: null,
|
||||
permissionAnswer: "",
|
||||
// The reason a refused `chat_reply` left on the thread's error line, kept
|
||||
// apart from any other error so a later accepted answer clears only this one.
|
||||
permissionError: "",
|
||||
// The background shells this session has observed (C11), in observation
|
||||
// order, the selected task and its bounded output pane.
|
||||
shells: [],
|
||||
selectedShellId: null,
|
||||
shellOutput: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -841,6 +1005,19 @@ export function setThreadRunning(thread, running, now) {
|
||||
return settledThread({ ...thread });
|
||||
}
|
||||
|
||||
/**
|
||||
* The reconnect repair for one thread (C5/C11): the settled form plus the shell
|
||||
* observations dropped — a shell's exit may have been swallowed by the gap, so
|
||||
* the retained shells are forgotten and re-learned from the re-subscribe's
|
||||
* `chat_shells` snapshot. This is deliberately separate from [settledThread],
|
||||
* which the step-ended frame also uses: a turn ending must never clear a
|
||||
* background process that outlives it (ChatStore.streamResumed drops shells;
|
||||
* ChatStore.setRunning does not).
|
||||
*/
|
||||
export function resumedThread(thread) {
|
||||
return { ...settledThread(thread), shells: [], selectedShellId: null, shellOutput: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it has
|
||||
* settled. Pure, so the running indicator and its unit test share the derivation.
|
||||
@@ -966,8 +1143,8 @@ export function threadPhase(thread, nowMillis) {
|
||||
* thread. Any frame clears `queued` (the turn moved on); `user` echoes another
|
||||
* client's prompt once (never this client's own), `text`/`reasoning` append to the
|
||||
* part their kind started, `tool` merges field by field, `step` drives the running
|
||||
* flag, and `shell`/`usage` are recognised but not folded here (C11 owns shells
|
||||
* and the turn totals are not shown). The message that a delta or tool frame
|
||||
* flag, and `shell` folds one background process into the retained set without
|
||||
* ever marking the turn running (C11). The message that a delta or tool frame
|
||||
* targets is created on first sight, so a live turn never gains a second bubble.
|
||||
*/
|
||||
export function applyChatEvent(thread, frame, now = Date.now()) {
|
||||
@@ -984,9 +1161,12 @@ export function applyChatEvent(thread, frame, now = Date.now()) {
|
||||
return applyTool(current, frame, now);
|
||||
case EVENT_STEP:
|
||||
return setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now);
|
||||
// `shell` is C11's (it never marks the turn running) and `usage` is not
|
||||
// folded; both still clear `queued`, which happened above.
|
||||
// A shell frame only folds its shell into the retained set: it NEVER marks
|
||||
// the thread running, because a background process is not the turn — a shell
|
||||
// that outlives the turn keeps showing after the turn's own indicator is gone.
|
||||
case EVENT_SHELL:
|
||||
return { ...current, shells: mergeShellFrame(current.shells, frame?.shell) };
|
||||
// `usage` is recognised but not folded; it still cleared `queued` above.
|
||||
case EVENT_USAGE:
|
||||
default:
|
||||
return current;
|
||||
@@ -1085,10 +1265,12 @@ function upsertParts(thread, frame, now, deltaArrivedAt, upsert) {
|
||||
* The reconnect/resync replacement: the newest history page is authoritative, so
|
||||
* the whole turn is replaced (no stale held message survives), the cursor and
|
||||
* `hasMore` are replaced from the page, and any in-flight state is settled —
|
||||
* every frame that was feeding a running turn is gone.
|
||||
* every frame that was feeding a running turn is gone. The retained shells are
|
||||
* dropped too (the reconnect re-fetches `chat_shells`), exactly like the Android
|
||||
* `streamResumed` path.
|
||||
*/
|
||||
export function historyResync(thread, page) {
|
||||
const settled = settledThread(thread ?? newChatThread());
|
||||
const settled = resumedThread(thread ?? newChatThread());
|
||||
return {
|
||||
...settled,
|
||||
messages: (page?.messages ?? []).slice(),
|
||||
@@ -1471,3 +1653,168 @@ export function chatCommandEffect(input, thread) {
|
||||
return { kind: "report", text: `“/${command.name}” is not a command.` };
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Permission approvals (C10) — ui/chat/ChatFormat.kt ApprovalCard/approvalCard/
|
||||
// permissionRiskText/decisionLabel and the ChatProtocol.DECISION_* values
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** The three decision values the server accepts (ChatProtocol.DECISION_*). */
|
||||
export const DECISION_ONCE = "once";
|
||||
export const DECISION_ALWAYS = "always";
|
||||
export const DECISION_REJECT = "reject";
|
||||
|
||||
/** Every acceptable decision, in the Android client's own order. */
|
||||
export const DECISIONS = Object.freeze([DECISION_ONCE, DECISION_ALWAYS, DECISION_REJECT]);
|
||||
|
||||
/** A decision's human label (ChatFormat.kt decisionLabel), blank-safe. */
|
||||
export const DECISION_LABEL_ONCE = "Allowed once";
|
||||
export const DECISION_LABEL_ALWAYS = "Always allowed";
|
||||
export const DECISION_LABEL_REJECT = "Rejected";
|
||||
export const DECISION_LABEL_RESOLVED = "Resolved";
|
||||
|
||||
export function decisionLabel(decision) {
|
||||
switch (str(decision)) {
|
||||
case DECISION_ONCE:
|
||||
return DECISION_LABEL_ONCE;
|
||||
case DECISION_ALWAYS:
|
||||
return DECISION_LABEL_ALWAYS;
|
||||
case DECISION_REJECT:
|
||||
return DECISION_LABEL_REJECT;
|
||||
default:
|
||||
return DECISION_LABEL_RESOLVED;
|
||||
}
|
||||
}
|
||||
|
||||
/** How one approval request stands (ChatFormat.kt ApprovalState). */
|
||||
export const APPROVAL_PENDING = "pending";
|
||||
export const APPROVAL_ANSWERED = "answered";
|
||||
export const APPROVAL_RESOLVED = "resolved";
|
||||
|
||||
/** The card's fixed wording (ChatFormat.kt ApprovalCard and ApprovalCardItem). */
|
||||
export const APPROVAL_BLANK_ACTION = "tool call";
|
||||
export const APPROVAL_HEADLINE_RESOLVED = "Already resolved";
|
||||
export const APPROVAL_STATUS_PENDING = "Waiting for your response";
|
||||
export const APPROVAL_STATUS_ANSWERED = "Waiting for the agent to continue…";
|
||||
export const APPROVAL_STATUS_RESOLVED = "Another client already answered this request.";
|
||||
export const RISK_REVIEW_LABEL = "RISK REVIEW";
|
||||
export const WAITING_FOR_APPROVAL_LABEL = "Waiting for your approval";
|
||||
|
||||
/** The once/always/reject control labels (ChatApprovalCard.kt), in their order. */
|
||||
export const APPROVAL_CONTROL_ONCE = "Allow once";
|
||||
export const APPROVAL_CONTROL_ALWAYS = "Always allow";
|
||||
export const APPROVAL_CONTROL_REJECT = "Reject";
|
||||
|
||||
/** How many resource lines the card shows before the remainder is elided. */
|
||||
export const MAX_APPROVAL_RESOURCE_LINES = 6;
|
||||
|
||||
/**
|
||||
* The text in the amber risk-review box (ChatFormat.kt permissionRiskText): the
|
||||
* server's own summary when it carries one, otherwise a neutral sentence naming
|
||||
* the action (or `a tool call`) so the box is never blank.
|
||||
*/
|
||||
export function permissionRiskText(permission) {
|
||||
const message = str(permission?.message);
|
||||
if (!isBlank(message)) return message;
|
||||
const what = isBlank(permission?.action) ? "a tool call" : str(permission.action);
|
||||
return `The agent is asking to run ${what}; review the request before allowing.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The request's resources with the blanks dropped, in the server's own order
|
||||
* (ChatFormat.kt ApprovalCard.resources). No entry is discarded here: the line
|
||||
* cap belongs to the joined text, so an embedded newline counts as its own line
|
||||
* instead of hiding a later resource.
|
||||
*/
|
||||
export function approvalResources(permission) {
|
||||
return (permission?.resources ?? [])
|
||||
.filter((resource) => !isBlank(resource))
|
||||
.map((resource) => str(resource));
|
||||
}
|
||||
|
||||
/**
|
||||
* The resource block as the card renders it (ChatFormat.kt
|
||||
* `resources.joinToString("\n")` with `maxLines = 6, overflow = Ellipsis`): the
|
||||
* non-blank resources joined by newlines and capped at
|
||||
* [MAX_APPROVAL_RESOURCE_LINES] lines, an embedded newline counting as a line,
|
||||
* with an ellipsis on the last kept line when the rest was dropped. The rendered
|
||||
* box clamps to the same six lines (styles.css), so a single long resource that
|
||||
* wraps is elided too rather than spilling onto a seventh line.
|
||||
*/
|
||||
export function approvalResourceText(permission) {
|
||||
const lines = approvalResources(permission).flatMap((resource) => resource.split("\n"));
|
||||
if (lines.length <= MAX_APPROVAL_RESOURCE_LINES) return lines.join("\n");
|
||||
const kept = lines.slice(0, MAX_APPROVAL_RESOURCE_LINES);
|
||||
kept[kept.length - 1] = `${kept[kept.length - 1]}\u2026`;
|
||||
return kept.join("\n");
|
||||
}
|
||||
|
||||
/** The card headline (ChatFormat.kt ApprovalCard.headline). */
|
||||
export function approvalHeadline(state, decision, action) {
|
||||
if (state === APPROVAL_PENDING) {
|
||||
return `Approve ${isBlank(action) ? APPROVAL_BLANK_ACTION : str(action)}`;
|
||||
}
|
||||
if (state === APPROVAL_ANSWERED) return decisionLabel(decision);
|
||||
return isBlank(decision) ? APPROVAL_HEADLINE_RESOLVED : decisionLabel(decision);
|
||||
}
|
||||
|
||||
/** The card's one-line status (ChatFormat.kt ApprovalCard.statusLine). */
|
||||
export function approvalStatusLine(state, note) {
|
||||
if (state === APPROVAL_PENDING) return APPROVAL_STATUS_PENDING;
|
||||
if (state === APPROVAL_ANSWERED) return APPROVAL_STATUS_ANSWERED;
|
||||
return isBlank(note) ? APPROVAL_STATUS_RESOLVED : str(note);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the conversation renders for one permission request (ChatFormat.kt
|
||||
* approvalCard): derived purely from the server's [permission] frame plus the
|
||||
* operator's local [answer], so a server resolution always outranks a local
|
||||
* answer and a stale tap can never reopen controls for a request already done.
|
||||
* Returns null when there is no request to show (a null frame or a blank
|
||||
* request id). `actionable` is true only while the request is open; `showRisk`
|
||||
* mirrors the app (open, or answered with a rejection).
|
||||
*/
|
||||
export function approvalCard(permission, answer) {
|
||||
if (permission == null || isBlank(permission.request_id)) return null;
|
||||
const resolvedByServer = permission.resolved === true || !isBlank(permission.decision);
|
||||
const state = resolvedByServer
|
||||
? APPROVAL_RESOLVED
|
||||
: !isBlank(answer)
|
||||
? APPROVAL_ANSWERED
|
||||
: APPROVAL_PENDING;
|
||||
const decision = resolvedByServer ? str(permission.decision) : str(answer);
|
||||
const note = resolvedByServer ? str(permission.message) : "";
|
||||
return {
|
||||
requestId: str(permission.request_id),
|
||||
action: str(permission.action),
|
||||
resources: approvalResources(permission),
|
||||
resourceText: approvalResourceText(permission),
|
||||
risk: permissionRiskText(permission),
|
||||
state,
|
||||
decision,
|
||||
note,
|
||||
actionable: state === APPROVAL_PENDING,
|
||||
showRisk:
|
||||
state === APPROVAL_PENDING || (state === APPROVAL_ANSWERED && decision === DECISION_REJECT),
|
||||
headline: approvalHeadline(state, decision, str(permission.action)),
|
||||
statusLine: approvalStatusLine(state, note),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds one pushed `chat_permission` frame into [thread] (ChatStore.permission):
|
||||
* a frame for a *new* request replaces any settled card and clears the local
|
||||
* answer, while a frame for the *same* request (for example a resolved re-push)
|
||||
* keeps the answer the operator already gave. The frame itself is stored; the
|
||||
* card derives from it, so a server resolution always wins.
|
||||
*/
|
||||
export function applyChatPermission(thread, frame) {
|
||||
const current = thread ?? newChatThread(str(frame?.session_id));
|
||||
const requestId = str(frame?.request_id);
|
||||
const sameRequest = requestId !== "" && str(current.permission?.request_id) === requestId;
|
||||
return {
|
||||
...current,
|
||||
permission: frame ?? null,
|
||||
permissionAnswer: sameRequest ? str(current.permissionAnswer) : "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,6 +64,17 @@ export const Protocol = Object.freeze({
|
||||
CHAT_PROMPT: "chat_prompt",
|
||||
CHAT_INTERRUPT: "chat_interrupt",
|
||||
CHAT_CREATE: "chat_create",
|
||||
// The approval card (C10): the server pushes `chat_permission` frames (one
|
||||
// pending request, later re-pushed with the resolution) and the phone answers
|
||||
// with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply).
|
||||
CHAT_PERMISSION: "chat_permission",
|
||||
CHAT_REPLY: "chat_reply",
|
||||
// The background shells a chat session owns (C11). `chat_shells` lists the
|
||||
// session's currently verified shells (body: `chat_query`); `chat_shell_output`
|
||||
// reads a bounded, lazy output page from one of them (body:
|
||||
// `chat_shell_output_query`). Mirrors internal/protocol/chat.go and Message.kt.
|
||||
CHAT_SHELLS: "chat_shells",
|
||||
CHAT_SHELL_OUTPUT: "chat_shell_output",
|
||||
|
||||
SUCCESS_END: "#success",
|
||||
FAILURE_END: "#failure",
|
||||
@@ -92,6 +103,17 @@ export const ChatKeys = Object.freeze({
|
||||
PROMPT: "chat_prompt",
|
||||
CREATE: "chat_create",
|
||||
QUEUED: "chat_queued",
|
||||
// C10: the pushed approval frame (`chat_permission`) and the answer body
|
||||
// (`chat_reply`), both distinct Message fields in internal/protocol/message.go.
|
||||
PERMISSION: "chat_permission",
|
||||
REPLY: "chat_reply",
|
||||
// The shell commands (C11, internal/protocol/message.go). `chat_shells` carries
|
||||
// its body in `chat_query` (like the other session-scoped commands) and replies
|
||||
// in `chat_shells`; `chat_shell_output` carries `chat_shell_output_query`
|
||||
// ({session_id,shell_id,cursor,limit}) and replies in `chat_shell_output`.
|
||||
SHELLS: "chat_shells",
|
||||
SHELL_OUTPUT: "chat_shell_output",
|
||||
SHELL_OUTPUT_QUERY: "chat_shell_output_query",
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,10 +3,26 @@
|
||||
// divergent field names. Mirrors android/.../data/PipelinesRepository.kt.
|
||||
import { ChatKeys, Protocol } from "./protocol.js";
|
||||
import { ProtocolError } from "./client.js";
|
||||
import { DECISIONS } from "./chat.js";
|
||||
|
||||
/** The server default history page the app asks for (CHAT_HISTORY_LIMIT, 200). */
|
||||
export const CHAT_HISTORY_LIMIT = 200;
|
||||
|
||||
/**
|
||||
* The label this browser client records with a permission answer, so every other
|
||||
* watching client can see which device resolved the request (the Android analogue
|
||||
* is the device name). It is always sent; the server records it with the outcome.
|
||||
*/
|
||||
export const WEB_CHAT_CLIENT = "Web";
|
||||
|
||||
/**
|
||||
* The largest shell-output page the server accepts (ChatShellOutputLimit,
|
||||
* 64 KiB). The browser always reads from the page's start and never sends more
|
||||
* than this, so a background task's output can never grow unbounded on the
|
||||
* client.
|
||||
*/
|
||||
export const SHELL_OUTPUT_LIMIT = 64 << 10;
|
||||
|
||||
export class PipelinesRepository {
|
||||
#client;
|
||||
|
||||
@@ -240,6 +256,57 @@ export class PipelinesRepository {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists the currently verified shells this operator chat session owns (C11),
|
||||
* so the conversation can show a background-tasks bar while one is running.
|
||||
* The body is the session-scoped `chat_query` (like chat_messages); the reply
|
||||
* is `chat_shells`, and an older server that returns none answers with an empty
|
||||
* list. A blank session id is refused here, exactly like
|
||||
* PipelinesRepository.chatShells.
|
||||
*/
|
||||
async chatShells(sessionId) {
|
||||
if (!String(sessionId ?? "").trim()) {
|
||||
throw new ProtocolError("Select a chat session first.");
|
||||
}
|
||||
const response = await this.#client.call({
|
||||
type: Protocol.CHAT_SHELLS,
|
||||
[ChatKeys.QUERY]: { session_id: sessionId },
|
||||
});
|
||||
return response[ChatKeys.SHELLS] ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads one bounded output page from a verified shell (C11), mirroring
|
||||
* PipelinesRepository.chatShellOutput. The body is exactly
|
||||
* `chat_shell_output_query` — {session_id, shell_id, cursor, limit}, **not** the
|
||||
* `chat_query` the other session commands use — with the cursor always sent so
|
||||
* a refresh rereads from the page's start rather than appending. A blank
|
||||
* session/shell, an out-of-bounds cursor/limit or a reply with no page is
|
||||
* refused with the same reason the Android client uses.
|
||||
*/
|
||||
async chatShellOutput(sessionId, shellId, { cursor = 0, limit = SHELL_OUTPUT_LIMIT } = {}) {
|
||||
if (!String(sessionId ?? "").trim() || !String(shellId ?? "").trim()) {
|
||||
throw new ProtocolError("Select a shell first.");
|
||||
}
|
||||
if (!(cursor >= 0) || !(limit > 0) || limit > SHELL_OUTPUT_LIMIT) {
|
||||
throw new ProtocolError("Shell output bounds are invalid.");
|
||||
}
|
||||
const response = await this.#client.call({
|
||||
type: Protocol.CHAT_SHELL_OUTPUT,
|
||||
[ChatKeys.SHELL_OUTPUT_QUERY]: {
|
||||
session_id: sessionId,
|
||||
shell_id: shellId,
|
||||
cursor,
|
||||
limit,
|
||||
},
|
||||
});
|
||||
const page = response[ChatKeys.SHELL_OUTPUT];
|
||||
if (!page) {
|
||||
throw new ProtocolError("The server returned no shell output page.");
|
||||
}
|
||||
return page;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finishes a session and records it closed on the server (nothing is
|
||||
* deleted). The reply echoes the updated session (`chat_session`) and the
|
||||
@@ -334,6 +401,37 @@ export class PipelinesRepository {
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
/**
|
||||
* Answers one pending permission request (C10). Sends exactly
|
||||
* `{type:'chat_reply', chat_reply:{session_id,request_id,decision,client}}` —
|
||||
* `message` rides only when non-blank (mirrors ChatReplyRequest's omitempty).
|
||||
* A blank session/request/decision, or a decision outside `once`/`always`/
|
||||
* `reject`, is refused here before anything is sent, so an unaccepted decision
|
||||
* can never reach the server. The server pushes the shared resolution back to
|
||||
* every watching client once the first answer is recorded.
|
||||
*/
|
||||
async chatReply(sessionId, requestId, decision, { message = "", client = WEB_CHAT_CLIENT } = {}) {
|
||||
const session = String(sessionId ?? "").trim();
|
||||
const request = String(requestId ?? "").trim();
|
||||
const chosen = String(decision ?? "").trim();
|
||||
if (session === "") throw new ProtocolError("Select a chat session first.");
|
||||
if (request === "") {
|
||||
throw new ProtocolError("This approval request is no longer available.");
|
||||
}
|
||||
if (!DECISIONS.includes(chosen)) {
|
||||
throw new ProtocolError("Choose once, always or reject.");
|
||||
}
|
||||
const body = {
|
||||
session_id: session,
|
||||
request_id: request,
|
||||
decision: chosen,
|
||||
client: String(client ?? "").trim() || WEB_CHAT_CLIENT,
|
||||
};
|
||||
const trimmed = String(message ?? "").trim();
|
||||
if (trimmed !== "") body.message = trimmed;
|
||||
await this.#client.call({ type: Protocol.CHAT_REPLY, [ChatKeys.REPLY]: body });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+156
@@ -1557,6 +1557,162 @@ code { background: var(--surface-2); padding: 1px 6px; border-radius: 6px; font-
|
||||
.chat-running-tool-elapsed { font-size: 11px; }
|
||||
.chat-running-tool-long { color: var(--bad); }
|
||||
|
||||
/* C10: the permission/approval card — the transcript's last item. A pending card
|
||||
wears an amber hairline border, echoing ChatApprovalCard.kt's 50%-alpha amber
|
||||
border; the amber RISK REVIEW box is the app's 12%-alpha amber panel. */
|
||||
.chat-approval {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
padding: 12px;
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
/* Background tasks (C11): running shells only, three visible rows then scroll. */
|
||||
.chat-bg-tasks { display: grid; gap: 6px; }
|
||||
.chat-bg-tasks-head { display: flex; align-items: baseline; gap: 8px; }
|
||||
.chat-bg-tasks-title { font-size: 13px; font-weight: 600; }
|
||||
.chat-bg-tasks-count { font-size: 12px; }
|
||||
.chat-bg-tasks-list {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
/* Exactly BACKGROUND_TASK_VISIBLE_ROWS (3) rows of 40px + their 2 gaps of 4px
|
||||
(the Android derivation `(minTouch + SPACING_XS) * 3`); past that it scrolls. */
|
||||
max-height: 128px;
|
||||
overflow-y: auto;
|
||||
padding-right: 2px;
|
||||
}
|
||||
.chat-bg-task {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-height: 40px;
|
||||
padding: 4px 10px;
|
||||
text-align: left;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.chat-bg-task:hover { background: var(--surface-2); }
|
||||
.chat-bg-task.selected { border-color: var(--accent); }
|
||||
.chat-bg-task:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.chat-bg-task-glyph {
|
||||
flex: 0 0 auto;
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 7px solid var(--accent);
|
||||
border-top: 5px solid transparent;
|
||||
border-bottom: 5px solid transparent;
|
||||
}
|
||||
.chat-bg-task-status { flex: 0 0 auto; color: var(--accent); }
|
||||
.chat-bg-task-command {
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.chat-bg-task-details { flex: 0 0 auto; font-size: 11px; }
|
||||
.chat-bg-task-detail {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
padding: 10px;
|
||||
background: var(--surface-2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
}
|
||||
.chat-approval-pending { border-color: color-mix(in srgb, var(--warn) 50%, var(--border)); }
|
||||
.chat-approval-head { display: flex; gap: 10px; align-items: center; }
|
||||
.chat-approval-shield { flex: 0 0 auto; width: 16px; height: 16px; color: var(--warn); }
|
||||
.chat-approval-titles { display: grid; gap: 2px; min-width: 0; }
|
||||
.chat-approval-headline { font-weight: 600; }
|
||||
.chat-approval-status { font-size: 12px; }
|
||||
/* The resources box is a padded frame around a padding-free clamp block. The
|
||||
clamp must sit on an element with no bottom padding: `overflow:hidden` clips at
|
||||
the padding box, so clamping the padded element itself still paints the top of
|
||||
the seventh line into that 8px strip. The inner block clips at its own content
|
||||
edge, so no seventh glyph is visible. */
|
||||
.chat-approval-resources {
|
||||
padding: 8px 10px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
.chat-approval-resources-text {
|
||||
margin: 0;
|
||||
font: inherit;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
/* The six-visible-line cap (ChatApprovalCard.kt maxLines = 6, Ellipsis): -webkit
|
||||
-line-clamp counts *rendered* lines, so a long resource that wraps is elided
|
||||
on the sixth line instead of spilling past it, exactly like the app. */
|
||||
display: -webkit-box;
|
||||
-webkit-box-orient: vertical;
|
||||
-webkit-line-clamp: 6;
|
||||
overflow: hidden;
|
||||
}
|
||||
.chat-approval-risk {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
background: color-mix(in srgb, var(--warn) 12%, transparent);
|
||||
}
|
||||
.chat-approval-risk-head { display: flex; gap: 4px; align-items: center; }
|
||||
.chat-approval-risk-shield { flex: 0 0 auto; width: 12px; height: 12px; color: var(--warn); }
|
||||
.chat-approval-risk-label { color: var(--warn); font-size: 11px; letter-spacing: 0.06em; }
|
||||
.chat-approval-risk-text { font-size: 12px; }
|
||||
.chat-approval-controls { display: flex; gap: 10px; }
|
||||
.chat-approval-control { padding: 6px 12px; }
|
||||
/* The app renders Allow once as a filled Button and the other two as
|
||||
TextButtons (ChatApprovalCard.kt:98-100); the browser matches that hierarchy
|
||||
with the filled accent treatment on the primary control. */
|
||||
.chat-approval-control.primary {
|
||||
background: var(--accent);
|
||||
border-color: var(--accent);
|
||||
color: var(--bg);
|
||||
font-weight: 600;
|
||||
}
|
||||
.chat-approval-control.primary:hover {
|
||||
background: color-mix(in srgb, var(--accent) 88%, white);
|
||||
border-color: color-mix(in srgb, var(--accent) 88%, white);
|
||||
}
|
||||
.chat-approval-jump { white-space: nowrap; font-size: 12px; border-color: var(--warn); color: var(--warn); }
|
||||
.chat-bg-task-label { font-size: 11px; }
|
||||
.chat-bg-task-command-full { font-size: 12px; overflow-wrap: anywhere; }
|
||||
.chat-bg-task-id { font-size: 12px; }
|
||||
.chat-bg-task-status-line { font-size: 12px; }
|
||||
.chat-bg-task-output {
|
||||
margin: 0;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
padding: 8px;
|
||||
font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
}
|
||||
.chat-bg-task-note { font-size: 11px; }
|
||||
.chat-bg-task-spinner { width: 12px; height: 12px; border-width: 2px; }
|
||||
.chat-bg-task-error-row { display: flex; align-items: center; gap: 8px; }
|
||||
.chat-bg-task-error { font-size: 12px; color: var(--bad); }
|
||||
.chat-bg-task-retry,
|
||||
.chat-bg-task-refresh { align-self: flex-start; padding: 2px 10px; font-size: 12px; }
|
||||
|
||||
.chat-tool-panel {
|
||||
position: fixed;
|
||||
z-index: 40;
|
||||
|
||||
@@ -5,6 +5,8 @@ import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
BACKGROUND_TASKS_TITLE,
|
||||
BACKGROUND_TASK_VISIBLE_ROWS,
|
||||
CHAT_COMMANDS,
|
||||
CHAT_COMMAND_GLYPH,
|
||||
CHAT_FOLLOW_THRESHOLD_PX,
|
||||
@@ -12,8 +14,34 @@ import {
|
||||
COMPOSER_SEND,
|
||||
COMPOSER_STOP,
|
||||
ChatTurn,
|
||||
APPROVAL_ANSWERED,
|
||||
APPROVAL_HEADLINE_RESOLVED,
|
||||
APPROVAL_PENDING,
|
||||
APPROVAL_RESOLVED,
|
||||
APPROVAL_STATUS_ANSWERED,
|
||||
APPROVAL_STATUS_PENDING,
|
||||
APPROVAL_STATUS_RESOLVED,
|
||||
DECISION_ALWAYS,
|
||||
DECISION_LABEL_ALWAYS,
|
||||
DECISION_LABEL_ONCE,
|
||||
DECISION_LABEL_REJECT,
|
||||
DECISION_LABEL_RESOLVED,
|
||||
DECISION_ONCE,
|
||||
DECISION_REJECT,
|
||||
MAX_APPROVAL_RESOURCE_LINES,
|
||||
MAX_ATTACHMENT_BYTES,
|
||||
MAX_RENDERED_DIFF_LINES,
|
||||
OBSERVED_SHELL_LIMIT,
|
||||
SHELL_DETAILS_LABEL,
|
||||
SHELL_EXITED,
|
||||
SHELL_OUTPUT_EMPTY,
|
||||
SHELL_OUTPUT_ERROR,
|
||||
SHELL_OUTPUT_LABELS,
|
||||
SHELL_OUTPUT_LOADING,
|
||||
SHELL_OUTPUT_READY,
|
||||
SHELL_OUTPUT_UNAVAILABLE,
|
||||
SHELL_ROW_LABEL,
|
||||
SHELL_RUNNING,
|
||||
TOOL_DETAIL_MAX_LENGTH,
|
||||
TOOL_LONG_RUNNING_MILLIS,
|
||||
TURN_PHASE_THINKING,
|
||||
@@ -21,9 +49,14 @@ import {
|
||||
TURN_PHASE_WAITING,
|
||||
TURN_THINKING_WINDOW_MILLIS,
|
||||
applyChatEvent,
|
||||
applyChatPermission,
|
||||
approvalCard,
|
||||
approvalResources,
|
||||
approvalResourceText,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
backgroundTasksRunningLabel,
|
||||
chatBottomDistancePx,
|
||||
chatCommandEffect,
|
||||
chatCommandForEnter,
|
||||
@@ -41,6 +74,7 @@ import {
|
||||
composerCanSend,
|
||||
composerSendEnabled,
|
||||
composerSubmit,
|
||||
decisionLabel,
|
||||
deltaPartId,
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
@@ -49,14 +83,18 @@ import {
|
||||
historyResync,
|
||||
lineDiff,
|
||||
mergeHistoryPage,
|
||||
mergeShellFrame,
|
||||
mergeToolPart,
|
||||
newChatThread,
|
||||
parseChatInput,
|
||||
partRendering,
|
||||
permissionRiskText,
|
||||
prettyToolInput,
|
||||
queuedAfterFrame,
|
||||
reasoningLabel,
|
||||
resumedThread,
|
||||
runningAfterFrame,
|
||||
runningBackgroundShells,
|
||||
runningToolElapsedMillis,
|
||||
runningToolStamps,
|
||||
sessionActivity,
|
||||
@@ -68,6 +106,9 @@ import {
|
||||
sessionTitle,
|
||||
sessionWorkLabel,
|
||||
settledThread,
|
||||
shellCommandSummary,
|
||||
shellOutputState,
|
||||
shellsLoaded,
|
||||
threadElapsedMillis,
|
||||
threadPhase,
|
||||
threadRunningTools,
|
||||
@@ -1168,3 +1209,301 @@ test("the running indicator's elapsed and per-tool timing use the thread's own s
|
||||
assert.deepEqual(runningToolStamps({ t1: 42 }, thread.messages, 9999), { t1: 42 });
|
||||
assert.deepEqual(runningToolStamps({ t1: 42 }, [], 9999), {});
|
||||
});
|
||||
|
||||
// ---- Permission approvals (C10) -------------------------------------------
|
||||
|
||||
/** A `chat_permission` frame (internal/protocol/chat.go ChatPermissionFrame). */
|
||||
const permissionFrame = (extra = {}) => ({
|
||||
session_id: "s1",
|
||||
request_id: "req-1",
|
||||
action: "bash",
|
||||
...extra,
|
||||
});
|
||||
|
||||
test("approvalCard names the action while pending, a blank action falling back to tool call", () => {
|
||||
const card = approvalCard(permissionFrame(), "");
|
||||
assert.equal(card.state, APPROVAL_PENDING);
|
||||
assert.equal(card.actionable, true);
|
||||
assert.equal(card.showRisk, true);
|
||||
assert.equal(card.headline, "Approve bash");
|
||||
assert.equal(card.statusLine, APPROVAL_STATUS_PENDING);
|
||||
assert.equal(approvalCard(permissionFrame({ action: " " }), "").headline, "Approve tool call");
|
||||
assert.equal(approvalCard(permissionFrame({ resources: ["r1", "r2"] }), "").resourceText, "r1\nr2");
|
||||
// No request to show.
|
||||
assert.equal(approvalCard(null, ""), null);
|
||||
assert.equal(approvalCard({ request_id: " " }, ""), null);
|
||||
});
|
||||
|
||||
test("an answered card reads its decision label and waits for the agent", () => {
|
||||
assert.equal(approvalCard(permissionFrame(), DECISION_ONCE).headline, DECISION_LABEL_ONCE);
|
||||
assert.equal(approvalCard(permissionFrame(), DECISION_ALWAYS).headline, DECISION_LABEL_ALWAYS);
|
||||
const rejected = approvalCard(permissionFrame(), DECISION_REJECT);
|
||||
assert.equal(rejected.headline, DECISION_LABEL_REJECT);
|
||||
assert.equal(rejected.statusLine, APPROVAL_STATUS_ANSWERED);
|
||||
assert.equal(rejected.actionable, false);
|
||||
// Risk box: the app shows it while pending and after a deny, not for an accept.
|
||||
assert.equal(rejected.showRisk, true);
|
||||
assert.equal(approvalCard(permissionFrame(), DECISION_ONCE).showRisk, false);
|
||||
// An unknown decision still settles to the blank-safe label.
|
||||
assert.equal(approvalCard(permissionFrame(), "whatever").headline, DECISION_LABEL_RESOLVED);
|
||||
});
|
||||
|
||||
test("a server-resolved card uses its decision label and note, else Already resolved", () => {
|
||||
const resolvedWith = approvalCard(
|
||||
permissionFrame({ resolved: true, decision: DECISION_ALWAYS, message: "Another client allowed this." }),
|
||||
DECISION_ONCE,
|
||||
);
|
||||
assert.equal(resolvedWith.state, APPROVAL_RESOLVED);
|
||||
assert.equal(resolvedWith.headline, DECISION_LABEL_ALWAYS);
|
||||
assert.equal(resolvedWith.statusLine, "Another client allowed this.");
|
||||
assert.equal(resolvedWith.actionable, false);
|
||||
assert.equal(resolvedWith.showRisk, false);
|
||||
// A non-blank decision alone counts as resolved; a blank one reads Already resolved.
|
||||
const bare = approvalCard(permissionFrame({ decision: DECISION_REJECT }), "");
|
||||
assert.equal(bare.state, APPROVAL_RESOLVED);
|
||||
assert.equal(bare.headline, DECISION_LABEL_REJECT);
|
||||
assert.equal(bare.statusLine, APPROVAL_STATUS_RESOLVED);
|
||||
const noDecision = approvalCard(permissionFrame({ resolved: true }), DECISION_ONCE);
|
||||
assert.equal(noDecision.headline, APPROVAL_HEADLINE_RESOLVED);
|
||||
assert.equal(noDecision.statusLine, APPROVAL_STATUS_RESOLVED);
|
||||
// The server resolution outranks the local answer.
|
||||
assert.equal(noDecision.decision, "");
|
||||
});
|
||||
|
||||
test("decisionLabel is blank-safe", () => {
|
||||
assert.equal(decisionLabel(DECISION_ONCE), DECISION_LABEL_ONCE);
|
||||
assert.equal(decisionLabel(DECISION_ALWAYS), DECISION_LABEL_ALWAYS);
|
||||
assert.equal(decisionLabel(DECISION_REJECT), DECISION_LABEL_REJECT);
|
||||
assert.equal(decisionLabel(""), DECISION_LABEL_RESOLVED);
|
||||
assert.equal(decisionLabel(undefined), DECISION_LABEL_RESOLVED);
|
||||
});
|
||||
|
||||
test("permissionRiskText prefers the server message, else names the action, else a tool call", () => {
|
||||
assert.equal(
|
||||
permissionRiskText(permissionFrame({ message: "Runs a shell as root." })),
|
||||
"Runs a shell as root.",
|
||||
);
|
||||
assert.equal(
|
||||
permissionRiskText(permissionFrame()),
|
||||
"The agent is asking to run bash; review the request before allowing.",
|
||||
);
|
||||
assert.equal(
|
||||
permissionRiskText(permissionFrame({ action: " " })),
|
||||
"The agent is asking to run a tool call; review the request before allowing.",
|
||||
);
|
||||
});
|
||||
|
||||
test("approvalResources drops blanks but keeps every resource entry", () => {
|
||||
const shown = approvalResources({ resources: ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", " "] });
|
||||
assert.deepEqual(shown, ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"]);
|
||||
assert.deepEqual(approvalResources({}), []);
|
||||
});
|
||||
|
||||
test("approvalResourceText joins the resources and caps the visible lines at six", () => {
|
||||
// A blank resource is no line; an embedded newline is its own line.
|
||||
assert.equal(approvalResourceText({ resources: ["a", " ", "b\nc"] }), "a\nb\nc");
|
||||
// Eight resources cap to six lines, the sixth carrying the ellipsis so the
|
||||
// elided remainder is not silent (Android's maxLines = 6, Ellipsis).
|
||||
assert.equal(
|
||||
approvalResourceText({ resources: ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"] }),
|
||||
"r1\nr2\nr3\nr4\nr5\nr6\u2026",
|
||||
);
|
||||
// A resource carrying embedded newlines counts toward the cap too: six lines
|
||||
// from one entry plus one more entry still yields six lines.
|
||||
const capped = approvalResourceText({ resources: ["a\nb\nc\nd\ne\nf", "g"] });
|
||||
assert.equal(capped.split("\n").length, MAX_APPROVAL_RESOURCE_LINES);
|
||||
assert.equal(capped.split("\n")[MAX_APPROVAL_RESOURCE_LINES - 1], "f\u2026");
|
||||
assert.equal(approvalResourceText({}), "");
|
||||
});
|
||||
|
||||
test("applyChatPermission keeps the answer for the same request and clears it for a new one", () => {
|
||||
let thread = newChatThread("s1");
|
||||
thread = applyChatPermission(thread, permissionFrame());
|
||||
assert.equal(thread.permission.request_id, "req-1");
|
||||
assert.equal(thread.permissionAnswer, "");
|
||||
|
||||
thread = { ...thread, permissionAnswer: DECISION_ONCE };
|
||||
// The same request re-pushed keeps the operator's local answer.
|
||||
thread = applyChatPermission(thread, permissionFrame());
|
||||
assert.equal(thread.permissionAnswer, DECISION_ONCE);
|
||||
|
||||
// A resolved re-push of the same request applies the outcome (which wins) and
|
||||
// still keeps the stored answer.
|
||||
thread = applyChatPermission(
|
||||
thread,
|
||||
permissionFrame({ resolved: true, decision: DECISION_ALWAYS, message: "done elsewhere" }),
|
||||
);
|
||||
assert.equal(thread.permissionAnswer, DECISION_ONCE);
|
||||
const card = approvalCard(thread.permission, thread.permissionAnswer);
|
||||
assert.equal(card.state, APPROVAL_RESOLVED);
|
||||
assert.equal(card.headline, DECISION_LABEL_ALWAYS);
|
||||
assert.equal(card.statusLine, "done elsewhere");
|
||||
|
||||
// A new request replaces the settled card and clears the answer.
|
||||
thread = applyChatPermission(thread, permissionFrame({ request_id: "req-2" }));
|
||||
assert.equal(thread.permission.request_id, "req-2");
|
||||
assert.equal(thread.permissionAnswer, "");
|
||||
});
|
||||
|
||||
// --- C11: background tasks (shells) -----------------------------------------
|
||||
// The pure model the background-tasks bar is built on: running-only filtering,
|
||||
// the visible-row cap, the one-line command summary, shell-frame folding and the
|
||||
// detail pane's state selection and wording. Mirror of
|
||||
// ChatFormat.runningBackgroundShells/shellCommandSummary, ChatStore.applyShell/
|
||||
// shellsLoaded and ChatTranscript.BackgroundProcessBar/-Detail.
|
||||
|
||||
const shell = (overrides = {}) => ({ id: "sh1", status: "running", command: "go test ./...", ...overrides });
|
||||
|
||||
test("runningBackgroundShells lists only non-blank running shells, in order", () => {
|
||||
const shells = [
|
||||
shell({ id: "a", command: "one" }),
|
||||
shell({ id: "b", status: SHELL_EXITED, command: "two" }),
|
||||
shell({ id: "", command: "three" }),
|
||||
shell({ id: "d", status: "running", command: "four" }),
|
||||
shell({ id: "e", status: undefined }),
|
||||
];
|
||||
assert.deepEqual(
|
||||
runningBackgroundShells(shells).map((s) => s.id),
|
||||
["a", "d"],
|
||||
);
|
||||
assert.deepEqual(runningBackgroundShells([]), []);
|
||||
assert.deepEqual(runningBackgroundShells(undefined), []);
|
||||
});
|
||||
|
||||
test("the visible-row cap is three and never truncates the model", () => {
|
||||
assert.equal(BACKGROUND_TASK_VISIBLE_ROWS, 3);
|
||||
const running = Array.from({ length: 5 }, (_, i) => shell({ id: `s${i}` }));
|
||||
// The cap is a view/CSS concern; every running shell stays in the model.
|
||||
assert.equal(runningBackgroundShells(running).length, 5);
|
||||
});
|
||||
|
||||
test("shellCommandSummary collapses whitespace, names a blank command and elides past 72", () => {
|
||||
assert.equal(SHELL_ROW_LABEL, "Running");
|
||||
assert.equal(shellCommandSummary(""), "background process");
|
||||
assert.equal(shellCommandSummary(" "), "background process");
|
||||
assert.equal(shellCommandSummary(null), "background process");
|
||||
assert.equal(shellCommandSummary(" go test\n./...\t-x "), "go test ./... -x");
|
||||
// Exactly 72 characters is not elided.
|
||||
const seventyTwo = "a".repeat(TOOL_DETAIL_MAX_LENGTH);
|
||||
assert.equal(shellCommandSummary(seventyTwo), seventyTwo);
|
||||
// Longer: 71 kept characters, trailing whitespace trimmed, then one ellipsis.
|
||||
const long = `${"b".repeat(TOOL_DETAIL_MAX_LENGTH)} tail`;
|
||||
const elided = shellCommandSummary(long);
|
||||
assert.equal(elided, `${"b".repeat(TOOL_DETAIL_MAX_LENGTH - 1)}…`);
|
||||
assert.equal(elided.length, TOOL_DETAIL_MAX_LENGTH);
|
||||
assert.ok(elided.endsWith("…"));
|
||||
// A 71-char word followed by a space then more trims the trailing space first.
|
||||
const word = `${"c".repeat(TOOL_DETAIL_MAX_LENGTH - 1)} rest`;
|
||||
assert.equal(shellCommandSummary(word), `${"c".repeat(TOOL_DETAIL_MAX_LENGTH - 1)}…`);
|
||||
});
|
||||
|
||||
test("mergeShellFrame keeps a blank command from the previous frame and caps the list", () => {
|
||||
const first = mergeShellFrame([], shell({ id: "a", command: "go build" }));
|
||||
assert.deepEqual(first, [shell({ id: "a", command: "go build" })]);
|
||||
|
||||
// A later frame that omits the command never blanks the retained one.
|
||||
const merged = mergeShellFrame(first, shell({ id: "a", command: "" }));
|
||||
assert.equal(merged.length, 1);
|
||||
assert.equal(merged[0].command, "go build");
|
||||
|
||||
// A frame that carries a command replaces it; the position is preserved.
|
||||
const renamed = mergeShellFrame(merged, shell({ id: "a", command: "go vet" }));
|
||||
assert.equal(renamed[0].command, "go vet");
|
||||
|
||||
// A blank id (or null shell) is ignored outright.
|
||||
assert.equal(mergeShellFrame(renamed, shell({ id: "" })).length, 1);
|
||||
assert.deepEqual(mergeShellFrame(renamed, null), renamed);
|
||||
|
||||
// The retained list is capped at OBSERVED_SHELL_LIMIT, keeping the newest.
|
||||
let many = [];
|
||||
for (let i = 0; i < OBSERVED_SHELL_LIMIT + 4; i += 1) {
|
||||
many = mergeShellFrame(many, shell({ id: `s${i}`, command: `c${i}` }));
|
||||
}
|
||||
assert.equal(many.length, OBSERVED_SHELL_LIMIT);
|
||||
assert.equal(many.at(-1).id, `s${OBSERVED_SHELL_LIMIT + 3}`);
|
||||
assert.equal(many[0].id, "s4");
|
||||
});
|
||||
|
||||
test("shellsLoaded replaces the live set but retains exits this client observed", () => {
|
||||
const existing = [
|
||||
shell({ id: "r1", status: SHELL_RUNNING, command: "old run" }),
|
||||
shell({ id: "e1", status: SHELL_EXITED, command: "finished" }),
|
||||
];
|
||||
const loaded = shellsLoaded(existing, [shell({ id: "r2", status: SHELL_RUNNING, command: "new run" })]);
|
||||
assert.deepEqual(loaded.map((s) => s.id), ["e1", "r2"]);
|
||||
// r1 is neither in the snapshot nor a locally observed exit, so it drops out.
|
||||
assert.ok(!loaded.some((s) => s.id === "r1"));
|
||||
// An exit the client never saw exit is not invented.
|
||||
assert.ok(!loaded.some((s) => s.id === "r1"));
|
||||
});
|
||||
|
||||
test("shellOutputState picks the detail pane's branch in the app's order", () => {
|
||||
assert.equal(shellOutputState(null), null);
|
||||
assert.equal(shellOutputState(undefined), null);
|
||||
assert.equal(shellOutputState({}), null);
|
||||
assert.equal(shellOutputState({ loading: true }), SHELL_OUTPUT_LOADING);
|
||||
assert.equal(shellOutputState({ error: "boom" }), SHELL_OUTPUT_ERROR);
|
||||
// Error outranks a page if both were set.
|
||||
assert.equal(shellOutputState({ error: "boom", page: { output: "x" } }), SHELL_OUTPUT_ERROR);
|
||||
assert.equal(shellOutputState({ page: { unavailable: true } }), SHELL_OUTPUT_UNAVAILABLE);
|
||||
assert.equal(shellOutputState({ page: { output: "" } }), SHELL_OUTPUT_EMPTY);
|
||||
assert.equal(shellOutputState({ page: { output: "line\n" } }), SHELL_OUTPUT_READY);
|
||||
assert.equal(shellOutputState({ page: { output: "x", truncated: true } }), SHELL_OUTPUT_READY);
|
||||
});
|
||||
|
||||
test("the detail pane's wording is the app's verbatim copy", () => {
|
||||
assert.equal(BACKGROUND_TASKS_TITLE, "Background tasks");
|
||||
assert.equal(backgroundTasksRunningLabel(3), "3 running");
|
||||
assert.equal(SHELL_DETAILS_LABEL, "Details");
|
||||
assert.deepEqual(SHELL_OUTPUT_LABELS, {
|
||||
COMMAND: "Command",
|
||||
UNAVAILABLE: "Unavailable",
|
||||
TASK_IDENTITY: "Task identity",
|
||||
STATUS_RUNNING: "Status: running",
|
||||
OUTPUT_UNAVAILABLE: "Output unavailable for this task.",
|
||||
NO_OUTPUT: "No output yet.",
|
||||
OUTPUT: "Output",
|
||||
OUTPUT_BOUNDED: "Output is bounded to 64 KiB.",
|
||||
RETRY: "Retry",
|
||||
REFRESH: "Refresh",
|
||||
});
|
||||
});
|
||||
|
||||
test("a shell frame folds into the thread and never marks the turn running", () => {
|
||||
const folded = applyChatEvent(
|
||||
newChatThread("s1"),
|
||||
evt("shell", { shell: { id: "sh1", status: "running", command: "sleep 5" } }),
|
||||
1000,
|
||||
);
|
||||
assert.equal(folded.running, false);
|
||||
assert.equal(folded.runningSince, 0);
|
||||
assert.deepEqual(folded.shells, [{ id: "sh1", status: "running", command: "sleep 5" }]);
|
||||
|
||||
// A shell frame that ends the shell removes it from the running set at once.
|
||||
const exited = applyChatEvent(
|
||||
folded,
|
||||
evt("shell", { shell: { id: "sh1", status: "exited", command: "" } }),
|
||||
1001,
|
||||
);
|
||||
assert.equal(exited.shells[0].status, "exited");
|
||||
assert.equal(exited.shells[0].command, "sleep 5");
|
||||
assert.equal(runningBackgroundShells(exited.shells).length, 0);
|
||||
});
|
||||
|
||||
test("a step that ends does not clear a background shell that outlives the turn", () => {
|
||||
let thread = applyChatEvent(
|
||||
newChatThread("s1"),
|
||||
evt("shell", { shell: { id: "sh1", status: "running", command: "sleep 5" } }),
|
||||
1000,
|
||||
);
|
||||
thread = applyChatEvent(thread, evt("step", { step: { status: "started" } }), 1000);
|
||||
thread = applyChatEvent(thread, evt("step", { step: { status: "ended" } }), 2000);
|
||||
assert.equal(thread.running, false);
|
||||
assert.equal(runningBackgroundShells(thread.shells).length, 1);
|
||||
// settledThread alone keeps the shell; only the reconnect repair drops it.
|
||||
assert.equal(settledThread(thread).shells.length, 1);
|
||||
const resumed = resumedThread(thread);
|
||||
assert.deepEqual(resumed.shells, []);
|
||||
assert.equal(resumed.selectedShellId, null);
|
||||
assert.equal(resumed.shellOutput, null);
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { PipelinesClient, ProtocolError } from "../src/client.js";
|
||||
import { PipelinesRepository, nativeChatMessageId, newChatOperationId } from "../src/repository.js";
|
||||
import { PipelinesRepository, SHELL_OUTPUT_LIMIT, nativeChatMessageId, newChatOperationId } from "../src/repository.js";
|
||||
import { validateServerUrl } from "../src/serverUrl.js";
|
||||
|
||||
const VALID = validateServerUrl("ws://host:8080/connect");
|
||||
@@ -396,3 +396,148 @@ test("subscribeChat surfaces a server refusal as a ProtocolError", async () => {
|
||||
message: "unknown command: chat_subscribe",
|
||||
});
|
||||
});
|
||||
|
||||
// ---- The approval reply (C10) ---------------------------------------------
|
||||
|
||||
test("chatReply sends exactly {type:'chat_reply', chat_reply:{session_id,request_id,decision,client}}", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_reply" });
|
||||
|
||||
await repo.chatReply("s1", "req-1", "once");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_reply",
|
||||
chat_reply: { session_id: "s1", request_id: "req-1", decision: "once", client: "Web" },
|
||||
});
|
||||
});
|
||||
|
||||
test("chatReply includes message only when non-blank", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_reply" });
|
||||
|
||||
await repo.chatReply("s1", "req-1", "always", { message: " looks fine " });
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_reply",
|
||||
chat_reply: {
|
||||
session_id: "s1",
|
||||
request_id: "req-1",
|
||||
decision: "always",
|
||||
client: "Web",
|
||||
message: "looks fine",
|
||||
},
|
||||
});
|
||||
|
||||
await repo.chatReply("s1", "req-1", "reject", { message: " " });
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_reply",
|
||||
chat_reply: { session_id: "s1", request_id: "req-1", decision: "reject", client: "Web" },
|
||||
});
|
||||
});
|
||||
|
||||
test("chatReply refuses blank ids or a decision outside once/always/reject without sending", async () => {
|
||||
const { repo, ws } = connected();
|
||||
await assert.rejects(() => repo.chatReply(" ", "req-1", "once"), ProtocolError);
|
||||
await assert.rejects(() => repo.chatReply("s1", " ", "once"), ProtocolError);
|
||||
await assert.rejects(() => repo.chatReply("s1", "req-1", "maybe"), ProtocolError);
|
||||
await assert.rejects(() => repo.chatReply("s1", "req-1", ""), ProtocolError);
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
// --- C11: background shells -------------------------------------------------
|
||||
|
||||
test("chatShells sends the session as chat_query and returns the list", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({
|
||||
id: frame.id,
|
||||
type: "chat_shells",
|
||||
chat_shells: [{ id: "sh1", status: "running", command: "go test ./..." }],
|
||||
});
|
||||
|
||||
const shells = await repo.chatShells("ses_eae413f50ffeLQDExlg8cYnscN");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_shells",
|
||||
chat_query: { session_id: "ses_eae413f50ffeLQDExlg8cYnscN" },
|
||||
});
|
||||
assert.deepEqual(shells, [{ id: "sh1", status: "running", command: "go test ./..." }]);
|
||||
});
|
||||
|
||||
test("chatShells returns [] when the reply carries none", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_shells" });
|
||||
assert.deepEqual(await repo.chatShells("ses_1"), []);
|
||||
});
|
||||
|
||||
test("chatShells refuses a blank session id without sending anything", async () => {
|
||||
const { repo, ws } = connected();
|
||||
await assert.rejects(() => repo.chatShells(" "), {
|
||||
name: "ProtocolError",
|
||||
message: "Select a chat session first.",
|
||||
});
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
|
||||
test("chatShellOutput sends chat_shell_output_query with cursor 0 and the 64 KiB limit", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({
|
||||
id: frame.id,
|
||||
type: "chat_shell_output",
|
||||
chat_shell_output: { shell: { id: "sh1", status: "running" }, output: "hello", cursor: 5, size: 5 },
|
||||
});
|
||||
|
||||
const page = await repo.chatShellOutput("ses_1", "sh1");
|
||||
assert.deepEqual(lastFrame(ws), {
|
||||
type: "chat_shell_output",
|
||||
chat_shell_output_query: { session_id: "ses_1", shell_id: "sh1", cursor: 0, limit: 64 << 10 },
|
||||
});
|
||||
assert.equal(SHELL_OUTPUT_LIMIT, 65536);
|
||||
assert.equal(page.output, "hello");
|
||||
});
|
||||
|
||||
test("a refresh always rereads from cursor 0, never appending", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({
|
||||
id: frame.id,
|
||||
type: "chat_shell_output",
|
||||
chat_shell_output: { shell: { id: "sh1", status: "running" }, output: "full page", truncated: true },
|
||||
});
|
||||
await repo.chatShellOutput("ses_1", "sh1", { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
|
||||
await repo.chatShellOutput("ses_1", "sh1", { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
|
||||
const frames = ws.sent.filter((frame) => frame.type === "chat_shell_output");
|
||||
assert.equal(frames.length, 2);
|
||||
for (const frame of frames) {
|
||||
assert.equal(frame.chat_shell_output_query.cursor, 0);
|
||||
assert.equal(frame.chat_shell_output_query.limit, 65536);
|
||||
}
|
||||
});
|
||||
|
||||
test("chatShellOutput refuses blank ids and out-of-bounds reads", async () => {
|
||||
const { repo, ws } = connected();
|
||||
await assert.rejects(() => repo.chatShellOutput("", "sh1"), {
|
||||
name: "ProtocolError",
|
||||
message: "Select a shell first.",
|
||||
});
|
||||
await assert.rejects(() => repo.chatShellOutput("ses_1", " "), {
|
||||
name: "ProtocolError",
|
||||
message: "Select a shell first.",
|
||||
});
|
||||
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1", { cursor: -1 }), {
|
||||
name: "ProtocolError",
|
||||
message: "Shell output bounds are invalid.",
|
||||
});
|
||||
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1", { limit: 0 }), {
|
||||
name: "ProtocolError",
|
||||
message: "Shell output bounds are invalid.",
|
||||
});
|
||||
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1", { limit: SHELL_OUTPUT_LIMIT + 1 }), {
|
||||
name: "ProtocolError",
|
||||
message: "Shell output bounds are invalid.",
|
||||
});
|
||||
assert.equal(ws.sent.length, 0);
|
||||
});
|
||||
|
||||
test("chatShellOutput throws when the reply carries no page", async () => {
|
||||
const { repo, ws } = connected();
|
||||
ws.reply = (frame) => ({ id: frame.id, type: "chat_shell_output" });
|
||||
await assert.rejects(() => repo.chatShellOutput("ses_1", "sh1"), {
|
||||
name: "ProtocolError",
|
||||
message: "The server returned no shell output page.",
|
||||
});
|
||||
});
|
||||
|
||||
+889
-19
@@ -396,10 +396,64 @@ try {
|
||||
if (!Native || window.__pipelinesSocketShim) return;
|
||||
window.__pipelinesSocketShim = true;
|
||||
window.__pipelinesSockets = [];
|
||||
// C10: the synthetic approval request ids whose outgoing chat_reply the smoke
|
||||
// records and suppresses, acking them locally so the page's own optimistic
|
||||
// answer path is exercised without ever sending a real decision to the server.
|
||||
window.__suppressChatReplyIds = [];
|
||||
// C10: request ids whose reply is answered with a server error instead of an
|
||||
// ack, so the card's refusal path (reopen with the reason) is exercised.
|
||||
window.__failChatReplyIds = [];
|
||||
window.__chatReplyCounts = { suppressed: 0, forwarded: 0, failed: 0 };
|
||||
function Shim(url, protocols) {
|
||||
const ws = protocols === undefined ? new Native(url) : new Native(url, protocols);
|
||||
const nativeSend = ws.send.bind(ws);
|
||||
window.__pipelinesSockets.push(ws);
|
||||
window.__pipelinesSocket = ws;
|
||||
// One send path for every scripted hook, in order: record the frame type for
|
||||
// assertions (C11/C10), suppress a synthetic chat_reply (C10, answering it
|
||||
// locally so no real decision reaches the server), then honour the generic
|
||||
// scripted-reply hook (C5/C10/C11), and otherwise send natively.
|
||||
ws.send = function (data) {
|
||||
let frame = null;
|
||||
try {
|
||||
frame = JSON.parse(data);
|
||||
} catch (_) {
|
||||
frame = null;
|
||||
}
|
||||
if (frame) {
|
||||
(window.__pipelinesSentTypes = window.__pipelinesSentTypes || []).push(frame.type);
|
||||
if (frame.type === "chat_reply") {
|
||||
const requestId = frame.chat_reply && frame.chat_reply.request_id;
|
||||
if (window.__suppressChatReplyIds.includes(requestId)) {
|
||||
window.__chatReplyCounts.suppressed += 1;
|
||||
const failed = window.__failChatReplyIds.includes(requestId);
|
||||
if (failed) window.__chatReplyCounts.failed += 1;
|
||||
if (typeof ws.onmessage === "function") {
|
||||
ws.onmessage({
|
||||
data: JSON.stringify(
|
||||
failed
|
||||
? { id: frame.id, type: "error", error: "This approval request is no longer available." }
|
||||
: { id: frame.id, type: "chat_reply" },
|
||||
),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
window.__chatReplyCounts.forwarded += 1;
|
||||
}
|
||||
const reply = window.__pipelinesIntercept ? window.__pipelinesIntercept(frame) : null;
|
||||
if (reply) {
|
||||
const delay = (window.__pipelinesInterceptDelay ?? 0) || 0;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
if (typeof ws.onmessage === "function") ws.onmessage({ data: JSON.stringify(reply) });
|
||||
} catch (_) {}
|
||||
}, delay);
|
||||
return;
|
||||
}
|
||||
}
|
||||
return nativeSend(data);
|
||||
};
|
||||
return ws;
|
||||
}
|
||||
Shim.prototype = Native.prototype;
|
||||
@@ -2394,6 +2448,16 @@ try {
|
||||
if (openedId !== expectedSession) {
|
||||
console.log(` -- the live server's first session with history is ${openedId}, not ${expectedSession}`);
|
||||
}
|
||||
// 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(
|
||||
() => page.evaluate(`(window.__pipelinesSentTypes || []).includes("chat_shells")`),
|
||||
{ timeout: 15000, what: "chat_shells to be fetched when the conversation opens (C11)" },
|
||||
);
|
||||
console.log(" chat_shells fetched when the conversation opened (real request)");
|
||||
|
||||
const transcript = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatTranscript");
|
||||
@@ -2401,6 +2465,23 @@ try {
|
||||
return {
|
||||
userBubbles: el.querySelectorAll(".chat-turn-user").length,
|
||||
agentBubbles: el.querySelectorAll(".chat-turn-agent").length,
|
||||
// The folding invariant that is independent of how the live session grows:
|
||||
// two agent bubbles must never be adjacent, because consecutive assistant
|
||||
// messages fold into one turn. A window that starts mid-turn may legitimately
|
||||
// begin with an agent bubble, so the count alone is not the invariant.
|
||||
adjacentAgentTurns: (() => {
|
||||
const turns = [...el.querySelectorAll(".chat-turn-user, .chat-turn-agent")];
|
||||
let adjacent = 0;
|
||||
for (let i = 1; i < turns.length; i += 1) {
|
||||
if (
|
||||
turns[i].classList.contains("chat-turn-agent") &&
|
||||
turns[i - 1].classList.contains("chat-turn-agent")
|
||||
) {
|
||||
adjacent += 1;
|
||||
}
|
||||
}
|
||||
return adjacent;
|
||||
})(),
|
||||
markdown: el.querySelectorAll(".markdown").length,
|
||||
tables: el.querySelectorAll(".md-table").length,
|
||||
inlineCode: el.querySelectorAll(".md-code").length,
|
||||
@@ -2412,13 +2493,21 @@ try {
|
||||
};
|
||||
})()`);
|
||||
if (!transcript) throw new Error("the opened transcript did not render");
|
||||
// The live session may have grown since the row was authored, so the counts are
|
||||
// lower bounds: at least one operator turn, at least one folded agent turn, at
|
||||
// least one tool chip.
|
||||
if (transcript.userBubbles < 1) throw new Error(`expected at least one user bubble, got ${transcript.userBubbles}`);
|
||||
// The live session grows as the operator uses it, so the folding invariant is
|
||||
// asserted directly rather than by count: every run of consecutive assistant
|
||||
// messages is exactly one agent bubble, which means two agent bubbles are never
|
||||
// adjacent. (A count such as "no more agent bubbles than user prompts" breaks as
|
||||
// soon as the newest page begins mid-turn, which the operator session now does.)
|
||||
if (transcript.userBubbles < 1) throw new Error(`expected a user bubble, got ${transcript.userBubbles}`);
|
||||
if (transcript.agentBubbles < 1) {
|
||||
throw new Error(`expected at least one folded agent turn, got ${transcript.agentBubbles}`);
|
||||
}
|
||||
if (transcript.adjacentAgentTurns !== 0) {
|
||||
throw new Error(
|
||||
`consecutive assistant messages did not fold: ${transcript.adjacentAgentTurns} adjacent ` +
|
||||
`agent turn pair(s) among ${transcript.agentBubbles} agent bubble(s)`,
|
||||
);
|
||||
}
|
||||
if (transcript.markdown === 0) throw new Error("the agent turn rendered no markdown");
|
||||
if (transcript.tables === 0) throw new Error("the agent answer rendered no markdown table");
|
||||
if (transcript.inlineCode === 0) throw new Error("the agent answer rendered no inline code");
|
||||
@@ -2426,9 +2515,9 @@ try {
|
||||
throw new Error(`expected at least one tool-call chip, got ${transcript.toolChips.length}`);
|
||||
}
|
||||
console.log(
|
||||
` transcript: ${transcript.userBubbles} user + ${transcript.agentBubbles} folded agent turn; ` +
|
||||
` transcript: ${transcript.userBubbles} user + ${transcript.agentBubbles} folded agent turn(s); ` +
|
||||
`markdown ${transcript.tables} table(s), ${transcript.inlineCode} inline code span(s), ` +
|
||||
`${transcript.toolChips[0]}; client label "${transcript.client}"`,
|
||||
`${transcript.toolChips.length} tool chip(s) ("${transcript.toolChips[0]}"); client label "${transcript.client}"`,
|
||||
);
|
||||
await shot("45-chat-transcript-newest.png");
|
||||
|
||||
@@ -2589,12 +2678,14 @@ try {
|
||||
const chip = document.querySelector("#chatTranscript .chat-tool-chip");
|
||||
if (!chip) return null;
|
||||
chip.scrollIntoView({ block: "center" });
|
||||
const tools = chip.closest(".chat-tools");
|
||||
// The rows belong to *this* chip's own panel: the live session may carry more
|
||||
// than one agent turn, and a document-wide count would sum every panel.
|
||||
const wrap = chip.closest(".chat-tools");
|
||||
return {
|
||||
text: chip.textContent ?? "",
|
||||
aria: chip.getAttribute("aria-label") ?? "",
|
||||
chevron: chip.querySelector(".chat-tool-chevron")?.getAttribute("aria-label") ?? "",
|
||||
rows: tools.querySelectorAll(".chat-tool-row").length,
|
||||
rows: wrap?.querySelectorAll(".chat-tool-panel .chat-tool-row").length ?? 0,
|
||||
};
|
||||
})()`);
|
||||
if (!chipInfo) throw new Error("C6: no tool-call chip rendered in the live transcript");
|
||||
@@ -2776,17 +2867,44 @@ try {
|
||||
await page.evaluate(`document.querySelector("#chatToolSample")?.remove()`);
|
||||
|
||||
if (transcript.hasLoadOlder) {
|
||||
// The control was present in capture 45. Press it and capture the honest
|
||||
// result: the live session's own cursor returns an empty older page, so the
|
||||
// control disappears (the prepend path itself is unit-tested).
|
||||
await page.evaluate(`document.querySelector(".chat-load-older")?.click()`);
|
||||
await eventually(() => page.evaluate(`!document.querySelector(".chat-load-older")`), {
|
||||
timeout: 15000,
|
||||
what: "the empty older history page to settle",
|
||||
});
|
||||
await shot("48-chat-load-older-empty.png");
|
||||
// The control was present in capture 45. Press it and assert the paging
|
||||
// invariant that does not depend on how large the operator's live session has
|
||||
// grown: an older page either prepends turns (the control stays while the
|
||||
// server still reports has_more) or exhausts the history (the control
|
||||
// disappears). Turns must never shrink, and the control must eventually
|
||||
// settle within a bounded number of presses.
|
||||
const readPaging = () =>
|
||||
page.evaluate(`({
|
||||
present: !!document.querySelector(".chat-load-older"),
|
||||
turns: document.querySelectorAll("#chatTranscript .chat-turn-user, #chatTranscript .chat-turn-agent").length,
|
||||
})`);
|
||||
let paging = await readPaging();
|
||||
const startTurns = paging.turns;
|
||||
let presses = 0;
|
||||
while (paging.present && presses < 5) {
|
||||
await page.evaluate(`document.querySelector(".chat-load-older")?.click()`);
|
||||
// The control is disabled while the page is in flight (thread.loading), so
|
||||
// "settled" means it is gone or enabled again — independent of whether the
|
||||
// older page added a visible turn.
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`(() => { const b = document.querySelector(".chat-load-older"); return !b || !b.disabled; })()`,
|
||||
),
|
||||
{ timeout: 15000, what: "an older history page to settle" },
|
||||
);
|
||||
paging = await readPaging();
|
||||
if (paging.turns < startTurns) {
|
||||
throw new Error(`load older shrank the transcript: ${startTurns} -> ${paging.turns}`);
|
||||
}
|
||||
presses += 1;
|
||||
}
|
||||
await shot("48-chat-load-older.png");
|
||||
console.log(
|
||||
" 'Load older messages' was shown while has_more (capture 45); the server's own next_cursor returned an empty older page and the control disappeared",
|
||||
` 'Load older messages' was shown while has_more (capture 45); ${presses} press(es) ` +
|
||||
`${paging.turns > startTurns ? `prepended ${paging.turns - startTurns} turn(s)` : "loaded no more turns"}; ` +
|
||||
`${paging.present ? "older pages still remain (bounded check stopped)" : "history exhausted and the control disappeared"}`,
|
||||
);
|
||||
} else {
|
||||
console.log(" -- no 'Load older messages' control: the server did not report has_more");
|
||||
@@ -2831,7 +2949,13 @@ try {
|
||||
jumpHidden: document.querySelector("#chatJump")?.hidden ?? null,
|
||||
};
|
||||
})()`);
|
||||
if (Math.abs((whileDialog.top ?? -1) - beforeDialog.top) > 2 || whileDialog.jumpHidden !== false) {
|
||||
// The dialog must not move the view or change what the scroll affordance offers:
|
||||
// compare against the state captured immediately before opening it (the earlier
|
||||
// wheel-gesture step already proves the control is offered when it should be).
|
||||
if (
|
||||
Math.abs((whileDialog.top ?? -1) - beforeDialog.top) > 2 ||
|
||||
whileDialog.jumpHidden !== beforeDialog.jumpHidden
|
||||
) {
|
||||
throw new Error(
|
||||
`opening the close dialog moved the transcript: ${JSON.stringify(beforeDialog)} -> ${JSON.stringify(whileDialog)}`,
|
||||
);
|
||||
@@ -3407,6 +3531,415 @@ try {
|
||||
' after reconnect: chat badge "live" again and history replaced the replayed turn wholesale (marker gone)',
|
||||
);
|
||||
|
||||
// C10: the permission/approval card. A real pending approval is not guaranteed
|
||||
// to occur, so the card is driven by synthetic `chat_permission` frames replayed
|
||||
// through the page's own socket handler (the same shim as C5) while the real
|
||||
// session stays subscribed. The page answers on its real `chat_reply` path, but
|
||||
// the shim records and suppresses that frame for the synthetic request id and
|
||||
// acks it locally, so no approval decision ever reaches the operator's server.
|
||||
step("C10: the approval card — replayed chat_permission frames, no real decision sent");
|
||||
const approvalRequestId = "cap-approval-1";
|
||||
await page.evaluate(`window.__suppressChatReplyIds = ${JSON.stringify([approvalRequestId])}`);
|
||||
|
||||
const replayPermission = (frame) =>
|
||||
page.evaluate(`(() => {
|
||||
const ws = window.__pipelinesSocket;
|
||||
if (!ws || typeof ws.onmessage !== "function") return false;
|
||||
ws.onmessage({ data: JSON.stringify({ type: "chat_permission", chat_permission: ${JSON.stringify(frame)} }) });
|
||||
return true;
|
||||
})()`);
|
||||
|
||||
// A synthetic in-flight turn, so the running indicator would be showing before
|
||||
// the approval arrives — and must stand down while the request is pending.
|
||||
await applyFrames(
|
||||
[sessionFrame({ message_id: "cap-approval-turn", kind: "step", step: { status: "started" } })],
|
||||
"the synthetic in-flight turn",
|
||||
);
|
||||
await eventually(() => page.evaluate(`!!document.querySelector("#chatRunning")`), {
|
||||
timeout: 8000,
|
||||
what: "the running indicator before the approval",
|
||||
});
|
||||
const runningBeforeApproval = await page.evaluate(`!!document.querySelector("#chatRunning")`);
|
||||
|
||||
const readApproval = () =>
|
||||
page.evaluate(`(() => {
|
||||
const card = document.querySelector("#chatApproval");
|
||||
const transcript = document.querySelector("#chatTranscript");
|
||||
const top = document.querySelector(".chat-approval-jump");
|
||||
return {
|
||||
present: !!card,
|
||||
last: !!card && !!transcript && transcript.lastElementChild === card,
|
||||
headline: card?.querySelector(".chat-approval-headline")?.textContent ?? "",
|
||||
status: card?.querySelector(".chat-approval-status")?.textContent ?? "",
|
||||
resources: (card?.querySelector(".chat-approval-resources")?.textContent ?? "").split("\\n").filter((line) => line !== ""),
|
||||
resourceLines: (() => {
|
||||
const el = card?.querySelector(".chat-approval-resources-text");
|
||||
if (!el) return 0;
|
||||
const lineHeight = parseFloat(getComputedStyle(el).lineHeight) || 0;
|
||||
return lineHeight > 0 ? Math.round(el.clientHeight / lineHeight) : 0;
|
||||
})(),
|
||||
resourceFullLines: (() => {
|
||||
// The same content without the six-line clamp, so the capture can prove
|
||||
// the clamp actually did work rather than the sample merely fitting.
|
||||
const el = card?.querySelector(".chat-approval-resources-text");
|
||||
if (!el) return 0;
|
||||
const clone = el.cloneNode(true);
|
||||
clone.style.webkitLineClamp = "unset";
|
||||
clone.style.display = "block";
|
||||
clone.style.position = "absolute";
|
||||
clone.style.visibility = "hidden";
|
||||
clone.style.width = el.clientWidth + "px";
|
||||
document.body.appendChild(clone);
|
||||
const cs = getComputedStyle(clone);
|
||||
const lineHeight = parseFloat(cs.lineHeight) || 0;
|
||||
const padding = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.paddingBottom) || 0);
|
||||
const lines = lineHeight > 0 ? Math.round((clone.getBoundingClientRect().height - padding) / lineHeight) : 0;
|
||||
clone.remove();
|
||||
return lines;
|
||||
})(),
|
||||
resourceClip: (() => {
|
||||
// The clamp block must itself be padding-free and end exactly at the
|
||||
// frame's content edge: a padded clamp element clips at its *padding*
|
||||
// box, which paints the top of the seventh line into that strip.
|
||||
const el = card?.querySelector(".chat-approval-resources-text");
|
||||
const frame = card?.querySelector(".chat-approval-resources");
|
||||
if (!el || !frame) return null;
|
||||
const cs = getComputedStyle(el);
|
||||
const fcs = getComputedStyle(frame);
|
||||
const lineHeight = parseFloat(cs.lineHeight) || 0;
|
||||
const bottomPadding = parseFloat(cs.paddingBottom) || 0;
|
||||
const framePadding = parseFloat(fcs.paddingBottom) || 0;
|
||||
const frameBorder = parseFloat(fcs.borderBottomWidth) || 0;
|
||||
const frameRect = frame.getBoundingClientRect();
|
||||
const elRect = el.getBoundingClientRect();
|
||||
return {
|
||||
lineHeight,
|
||||
bottomPadding,
|
||||
framePadding,
|
||||
frameBorder,
|
||||
clippedLines: lineHeight > 0 ? Math.round(el.clientHeight / lineHeight) : 0,
|
||||
overflows: el.scrollHeight > el.clientHeight,
|
||||
// How much content the six-line box hides. A full line or more proves
|
||||
// the clamp is genuinely exercised (the clone-based unclamped measure
|
||||
// is unreliable once the block sits inside a clamped frame).
|
||||
scrollOverflow: el.scrollHeight - el.clientHeight,
|
||||
// The frame's content edge sits above its bottom border and padding.
|
||||
endsAtFrameContentEdge:
|
||||
Math.abs(frameRect.bottom - frameBorder - framePadding - elRect.bottom) < 0.5,
|
||||
overflow: cs.overflowY,
|
||||
};
|
||||
})(),
|
||||
primaryFilled: (() => {
|
||||
// The Allow once control is the app's filled Button, the other two its
|
||||
// TextButtons (ChatApprovalCard.kt:98-100), so its computed background
|
||||
// must differ from Always allow's once the primary rule exists.
|
||||
const controls = [...(card?.querySelectorAll(".chat-approval-control") ?? [])];
|
||||
if (controls.length < 2) return false;
|
||||
return getComputedStyle(controls[0]).backgroundColor !== getComputedStyle(controls[1]).backgroundColor;
|
||||
})(),
|
||||
riskLabel: card?.querySelector(".chat-approval-risk-label")?.textContent ?? "",
|
||||
riskText: card?.querySelector(".chat-approval-risk-text")?.textContent ?? "",
|
||||
shield: (() => {
|
||||
// The app's amber outlined Shield: an SVG stroked with currentColor, so
|
||||
// the warn hue actually tints it (a colour emoji would not).
|
||||
const el = card?.querySelector(".chat-approval-shield");
|
||||
if (!el) return null;
|
||||
const stroke = el.querySelector("path")?.getAttribute("stroke") ?? "";
|
||||
return {
|
||||
svg: el.tagName.toLowerCase() === "svg",
|
||||
stroke,
|
||||
color: getComputedStyle(el).color,
|
||||
tinted: getComputedStyle(el).color !== "rgb(0, 0, 0)",
|
||||
};
|
||||
})(),
|
||||
controls: [...(card?.querySelectorAll(".chat-approval-control") ?? [])].map((b) => b.textContent),
|
||||
topControl: top?.textContent ?? "",
|
||||
running: !!document.querySelector("#chatRunning"),
|
||||
};
|
||||
})()`);
|
||||
|
||||
const pendingPermission = {
|
||||
session_id: sessionId,
|
||||
request_id: approvalRequestId,
|
||||
action: "bash",
|
||||
resources: [
|
||||
"",
|
||||
"/repo/src/app.js",
|
||||
// A long, wrapping resource kept inside the first six lines, so the rendered
|
||||
// six-line clamp is actually exercised (a short sample would fit anyway).
|
||||
"/Users/alan/repos/pipelines/internal/server/chat_stream_handlers/approval_and_permission_frames/very_long_segment_name/another_deep_segment/file_with_a_deliberately_long_name.js",
|
||||
// A second long path, so the clamped sample overflows by enough lines that the
|
||||
// six-line clamp is exercised at any realistic card width (a single long path
|
||||
// shrank to exactly six unclamped lines after the merged layout).
|
||||
"/Users/alan/repos/pipelines/internal/server/another/deeply/nested/segment/that/wraps/across/several/rendered/lines/in/the/approval/resources/panel/and_keeps_going.js",
|
||||
"/repo/src/repository.js",
|
||||
"/repo/src/protocol.js",
|
||||
"/repo/styles.css",
|
||||
"/repo/test/chat.test.mjs",
|
||||
"/repo/test/repository.test.mjs",
|
||||
"/repo/PARITY.md",
|
||||
],
|
||||
message: "Runs a shell command in the workspace.",
|
||||
};
|
||||
const replayedPending = await replayPermission(pendingPermission);
|
||||
if (!replayedPending) {
|
||||
throw new Error("C10: the socket shim did not expose the live socket for the permission replay");
|
||||
}
|
||||
await eventually(() => page.evaluate(`!!document.querySelector("#chatApproval")`), {
|
||||
timeout: 8000,
|
||||
what: "the approval card to render",
|
||||
});
|
||||
|
||||
const pending = await readApproval();
|
||||
if (!pending.present || !pending.last) {
|
||||
throw new Error(`C10: the pending card is not the transcript's last element: ${JSON.stringify(pending)}`);
|
||||
}
|
||||
if (pending.headline !== "Approve bash") throw new Error(`C10: pending headline: ${JSON.stringify(pending.headline)}`);
|
||||
if (pending.status !== "Waiting for your response") throw new Error(`C10: pending status: ${JSON.stringify(pending.status)}`);
|
||||
if (pending.resources.length !== 6) {
|
||||
throw new Error(`C10: expected six resource lines, got ${JSON.stringify(pending.resources)}`);
|
||||
}
|
||||
if (pending.resourceLines > 6) {
|
||||
throw new Error(
|
||||
`C10: the resource block rendered ${pending.resourceLines} lines, above the six-line cap ` +
|
||||
`(unclamped it would be ${pending.resourceFullLines})`,
|
||||
);
|
||||
}
|
||||
if (pending.resourceLines !== 6) {
|
||||
throw new Error(`C10: the six-line clamp did not land on exactly six lines: ${pending.resourceLines}`);
|
||||
}
|
||||
const clip = pending.resourceClip;
|
||||
if (
|
||||
!clip ||
|
||||
clip.bottomPadding !== 0 ||
|
||||
clip.framePadding <= 0 ||
|
||||
!clip.overflows ||
|
||||
clip.overflow !== "hidden" ||
|
||||
!clip.endsAtFrameContentEdge
|
||||
) {
|
||||
throw new Error(
|
||||
`C10: the clamp block would let a seventh line paint into the frame's padding: ${JSON.stringify(clip)}`,
|
||||
);
|
||||
}
|
||||
if (!clip || !(clip.scrollOverflow >= clip.lineHeight)) {
|
||||
throw new Error(
|
||||
`C10: the resource sample did not overflow by a full line, so the six-line clamp was not ` +
|
||||
`exercised: ${JSON.stringify(clip)}`,
|
||||
);
|
||||
}
|
||||
if (!pending.primaryFilled) {
|
||||
throw new Error("C10: the Allow once control is not visually distinct from Always allow");
|
||||
}
|
||||
if (pending.riskLabel !== "RISK REVIEW" || pending.riskText !== "Runs a shell command in the workspace.") {
|
||||
throw new Error(`C10: risk panel: ${JSON.stringify([pending.riskLabel, pending.riskText])}`);
|
||||
}
|
||||
if (!pending.shield || !pending.shield.svg || pending.shield.stroke !== "currentColor" || !pending.shield.tinted) {
|
||||
throw new Error(`C10: the card's shield is not the tinted outlined SVG: ${JSON.stringify(pending.shield)}`);
|
||||
}
|
||||
if (JSON.stringify(pending.controls) !== JSON.stringify(["Allow once", "Always allow", "Reject"])) {
|
||||
throw new Error(`C10: controls: ${JSON.stringify(pending.controls)}`);
|
||||
}
|
||||
if (pending.topControl !== "Waiting for your approval") {
|
||||
throw new Error(`C10: top-bar control: ${JSON.stringify(pending.topControl)}`);
|
||||
}
|
||||
if (runningBeforeApproval && pending.running) {
|
||||
throw new Error("C10: the running indicator did not stand down while the approval is pending");
|
||||
}
|
||||
console.log(
|
||||
` pending card: "${pending.headline}" / "${pending.status}", ${pending.resources.length} resource lines ` +
|
||||
`(rendered ${pending.resourceLines} of ${pending.resourceFullLines} unclamped), risk "${pending.riskLabel}", ` +
|
||||
`controls ${JSON.stringify(pending.controls)} (Allow once filled: ${pending.primaryFilled}), ` +
|
||||
`top-bar "${pending.topControl}", #chatRunning ${pending.running ? "present" : "absent"}`,
|
||||
);
|
||||
await shot("65-chat-approval-pending.png");
|
||||
|
||||
// Answer Allow once: the card settles optimistically, the controls and the
|
||||
// top-bar control go, and the reply is recorded/suppressed by the shim.
|
||||
await page.evaluate(`document.querySelectorAll("#chatApproval .chat-approval-control")[0].click()`);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelectorAll("#chatApproval .chat-approval-control").length === 0`),
|
||||
{ timeout: 8000, what: "the answered card to drop its controls" },
|
||||
);
|
||||
const answered = await readApproval();
|
||||
if (answered.headline !== "Allowed once") throw new Error(`C10: answered headline: ${JSON.stringify(answered.headline)}`);
|
||||
if (answered.status !== "Waiting for the agent to continue…") {
|
||||
throw new Error(`C10: answered status: ${JSON.stringify(answered.status)}`);
|
||||
}
|
||||
if (answered.controls.length !== 0 || answered.topControl !== "") {
|
||||
throw new Error(`C10: answered card kept a control: ${JSON.stringify(answered)}`);
|
||||
}
|
||||
console.log(
|
||||
` after Allow once: "${answered.headline}" / "${answered.status}", controls gone, top-bar control gone, no decision sent`,
|
||||
);
|
||||
await shot("66-chat-approval-answered.png");
|
||||
|
||||
// The same request re-pushed keeps the local answer; a server-resolved frame
|
||||
// then wins and shows its note with no controls and no risk panel.
|
||||
await replayPermission(pendingPermission);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector("#chatApproval .chat-approval-headline")?.textContent === "Allowed once"`),
|
||||
{ timeout: 8000, what: "the same-request re-push to keep the local answer" },
|
||||
);
|
||||
const repushed = await readApproval();
|
||||
if (repushed.headline !== "Allowed once" || repushed.controls.length !== 0) {
|
||||
throw new Error(`C10: the same-request re-push did not keep the local answer: ${JSON.stringify(repushed)}`);
|
||||
}
|
||||
await replayPermission({
|
||||
...pendingPermission,
|
||||
resolved: true,
|
||||
decision: "always",
|
||||
resolved_by: "Pixel 10 Pro Fold",
|
||||
message: "Another client already allowed this.",
|
||||
});
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector("#chatApproval .chat-approval-headline")?.textContent === "Always allowed"`),
|
||||
{ timeout: 8000, what: "the server resolution to win over the local answer" },
|
||||
);
|
||||
const resolved = await readApproval();
|
||||
if (resolved.status !== "Another client already allowed this.") {
|
||||
throw new Error(`C10: resolved status: ${JSON.stringify(resolved.status)}`);
|
||||
}
|
||||
if (resolved.controls.length !== 0 || resolved.topControl !== "") {
|
||||
throw new Error(`C10: resolved card kept a control: ${JSON.stringify(resolved)}`);
|
||||
}
|
||||
if (resolved.riskLabel !== "") throw new Error(`C10: resolved card kept its risk panel: ${JSON.stringify(resolved.riskLabel)}`);
|
||||
console.log(
|
||||
` resolved by another client: "${resolved.headline}" / "${resolved.status}", no controls, no risk panel, no top-bar control`,
|
||||
);
|
||||
await shot("67-chat-approval-resolved.png");
|
||||
|
||||
// A brand-new request replaces the settled card and clears the answer; a
|
||||
// refused chat_reply must reopen it with the server's reason (never show an
|
||||
// unaccepted decision as accepted), and a rejection keeps the risk panel.
|
||||
const secondRequestId = "cap-approval-2";
|
||||
await page.evaluate(
|
||||
`window.__suppressChatReplyIds = ${JSON.stringify([approvalRequestId, secondRequestId])}`,
|
||||
);
|
||||
await page.evaluate(`window.__failChatReplyIds = ${JSON.stringify([secondRequestId])}`);
|
||||
const secondPermission = {
|
||||
session_id: sessionId,
|
||||
request_id: secondRequestId,
|
||||
action: "",
|
||||
resources: ["/repo/src/app.js"],
|
||||
message: "",
|
||||
};
|
||||
await replayPermission(secondPermission);
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`document.querySelector("#chatApproval")?.getAttribute("data-request-id") === ${JSON.stringify(secondRequestId)}`,
|
||||
),
|
||||
{ timeout: 8000, what: "the new request to replace the settled card" },
|
||||
);
|
||||
const replaced = await readApproval();
|
||||
if (replaced.headline !== "Approve tool call" || replaced.status !== "Waiting for your response") {
|
||||
throw new Error(`C10: the new request did not replace the settled card: ${JSON.stringify(replaced)}`);
|
||||
}
|
||||
if (replaced.controls.length !== 3 || replaced.topControl !== "Waiting for your approval") {
|
||||
throw new Error(`C10: the new request is not actionable: ${JSON.stringify(replaced)}`);
|
||||
}
|
||||
if (replaced.riskText !== "The agent is asking to run a tool call; review the request before allowing.") {
|
||||
throw new Error(`C10: the blank-action risk fallback: ${JSON.stringify(replaced.riskText)}`);
|
||||
}
|
||||
console.log(` a new request replaced the settled card: "${replaced.headline}", controls back, risk fallback shown`);
|
||||
|
||||
// Always allow -> the shim answers with a server error, so the card must reopen
|
||||
// with the reason and the thread's error line, and no accepted decision shows.
|
||||
await page.evaluate(`[...document.querySelectorAll("#chatApproval .chat-approval-control")].find((b) => b.textContent === "Always allow").click()`);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector("#chatApproval .chat-approval-headline")?.textContent === "Approve tool call"`),
|
||||
{ timeout: 8000, what: "the refused reply to reopen the request" },
|
||||
);
|
||||
const reopened = await page.evaluate(`(() => {
|
||||
const card = document.querySelector("#chatApproval");
|
||||
return {
|
||||
headline: card?.querySelector(".chat-approval-headline")?.textContent ?? "",
|
||||
controls: [...card.querySelectorAll(".chat-approval-control")].map((b) => b.textContent),
|
||||
error: document.querySelector(".chat-transcript-error")?.textContent ?? "",
|
||||
topControl: document.querySelector(".chat-approval-jump")?.textContent ?? "",
|
||||
};
|
||||
})()`);
|
||||
if (
|
||||
reopened.headline !== "Approve tool call" ||
|
||||
reopened.controls.length !== 3 ||
|
||||
reopened.topControl !== "Waiting for your approval" ||
|
||||
reopened.error !== "This approval request is no longer available."
|
||||
) {
|
||||
throw new Error(`C10: a refused reply did not reopen the request with its reason: ${JSON.stringify(reopened)}`);
|
||||
}
|
||||
console.log(
|
||||
` a refused chat_reply reopened "${reopened.headline}" with its reason: "${reopened.error}", controls back`,
|
||||
);
|
||||
|
||||
// Reject now succeeds (the shim acks it): the card reads Rejected and keeps the
|
||||
// amber risk panel, matching Android's showRisk for a denial.
|
||||
await page.evaluate(`window.__failChatReplyIds = []`);
|
||||
await page.evaluate(`[...document.querySelectorAll("#chatApproval .chat-approval-control")].find((b) => b.textContent === "Reject").click()`);
|
||||
await eventually(
|
||||
() => page.evaluate(`document.querySelector("#chatApproval .chat-approval-headline")?.textContent === "Rejected"`),
|
||||
{ timeout: 8000, what: "the rejected card to settle" },
|
||||
);
|
||||
const rejected = await readApproval();
|
||||
if (rejected.status !== "Waiting for the agent to continue…" || rejected.controls.length !== 0) {
|
||||
throw new Error(`C10: the rejected card did not settle: ${JSON.stringify(rejected)}`);
|
||||
}
|
||||
if (rejected.riskLabel !== "RISK REVIEW" || rejected.riskText === "") {
|
||||
throw new Error(`C10: a rejected card dropped its risk panel: ${JSON.stringify(rejected)}`);
|
||||
}
|
||||
const errorCleared = await page.evaluate(
|
||||
`!document.querySelector(".chat-transcript-error")`,
|
||||
);
|
||||
if (!errorCleared) {
|
||||
throw new Error("C10: the accepted Reject left the previous refusal's reason on the error line");
|
||||
}
|
||||
console.log(
|
||||
` after Reject: "${rejected.headline}" / "${rejected.status}", risk panel kept ("${rejected.riskLabel}"), ` +
|
||||
`controls gone, the refusal's error line cleared`,
|
||||
);
|
||||
await shot("68-chat-approval-rejected.png");
|
||||
|
||||
// The blank-decision server resolution: a request settled without a decision
|
||||
// reads `Already resolved` and falls back to the neutral status sentence.
|
||||
const thirdRequestId = "cap-approval-3";
|
||||
await replayPermission({
|
||||
session_id: sessionId,
|
||||
request_id: thirdRequestId,
|
||||
action: "edit",
|
||||
resources: ["/repo/src/app.js"],
|
||||
resolved: true,
|
||||
});
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`document.querySelector("#chatApproval .chat-approval-headline")?.textContent === "Already resolved"`,
|
||||
),
|
||||
{ timeout: 8000, what: "the blank-decision resolution to render" },
|
||||
);
|
||||
const alreadyResolved = await readApproval();
|
||||
if (
|
||||
alreadyResolved.status !== "Another client already answered this request." ||
|
||||
alreadyResolved.controls.length !== 0 ||
|
||||
alreadyResolved.topControl !== "" ||
|
||||
alreadyResolved.riskLabel !== ""
|
||||
) {
|
||||
throw new Error(`C10: the blank-decision resolution: ${JSON.stringify(alreadyResolved)}`);
|
||||
}
|
||||
console.log(
|
||||
` a resolution with no decision: "${alreadyResolved.headline}" / "${alreadyResolved.status}", no controls, no risk panel`,
|
||||
);
|
||||
|
||||
const replyCounts = await page.evaluate(`window.__chatReplyCounts`);
|
||||
if (replyCounts.suppressed !== 3 || replyCounts.failed !== 1 || replyCounts.forwarded !== 0) {
|
||||
throw new Error(`C10: unexpected chat_reply counters: ${JSON.stringify(replyCounts)}`);
|
||||
}
|
||||
console.log(
|
||||
` suppressed outgoing chat_reply for the synthetic requests: ${replyCounts.suppressed} ` +
|
||||
`(one refused with a server error: ${replyCounts.failed}); forwarded real chat_reply: ${replyCounts.forwarded}`,
|
||||
);
|
||||
console.log(
|
||||
" NOTE: the approval card above was driven by replayed chat_permission frames; no real approval decision was sent to the server",
|
||||
);
|
||||
|
||||
// The third word: disconnecting entirely reads `not live`.
|
||||
await page.click("#connectBtn");
|
||||
await eventually(
|
||||
@@ -3806,6 +4339,343 @@ try {
|
||||
}
|
||||
console.log(` reload restored url=${restoredUrl} workspace=${restoredWorkspace}`);
|
||||
|
||||
// C11: the background-tasks bar. The live server has no running shell to read
|
||||
// safely, so the bar is driven from synthetic `shell` frames replayed through
|
||||
// the page's own socket handler (the same shim) and the bounded output pages are
|
||||
// answered by a controlled reply hook on that socket. Every other frame — the
|
||||
// chat_shells list, the subscribe ack and history — still comes from the real
|
||||
// server. This log states the split plainly.
|
||||
step("C11: the background-tasks bar (replayed shell frames + bounded output pages)");
|
||||
// The C5 section ends on a deliberate Disconnect (idle), which the browser's
|
||||
// `online` handler deliberately does not auto-recover; use the header's own
|
||||
// Reconnect/Connect control to bring the page back before the bar is captured.
|
||||
const c11Reconnected = await page.evaluate(`(() => {
|
||||
if (document.querySelector(".conn-banner")?.classList.contains("conn-ok")) return true;
|
||||
const control = document.querySelector("#reconnectBtn") || document.querySelector("#connectBtn");
|
||||
if (control) {
|
||||
control.click();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
})()`);
|
||||
if (!c11Reconnected) throw new Error("C11: no header control to reconnect the page");
|
||||
await ensureConnected(30000);
|
||||
// The conversation pane persists across the reconnect; bring it back explicitly
|
||||
// if a render left another view, clicking through the page's own controls.
|
||||
const c11Transcript = await page.evaluate(`!!document.querySelector("#chatTranscript")`);
|
||||
if (!c11Transcript) {
|
||||
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 });
|
||||
await page.evaluate(
|
||||
`document.querySelector('#chatRows .chat-row[data-session="${sessionId}"]')?.click()`,
|
||||
);
|
||||
}
|
||||
await page.waitForSelector("#chatTranscript", { timeout: 25000 });
|
||||
await page.evaluate(`document.querySelector("#chatJump")?.click()`);
|
||||
|
||||
// The bounded output pages the page will read are replayed synthetic wire
|
||||
// replies; the request shape (chat_shell_output_query, cursor 0, limit 65536)
|
||||
// is the client's own and is unit-tested in repository.test.mjs.
|
||||
await page.evaluate(`(() => {
|
||||
window.__pipelinesInterceptDelay = 0;
|
||||
window.__pipelinesPages = {
|
||||
"cap-run": { shell: { id: "cap-run", status: "running", command: "go test ./... -count=1" }, output: "ok \\tpipelines\\t0.42s\\n", cursor: 0, size: 20 },
|
||||
"cap-empty": { shell: { id: "cap-empty", status: "running", command: "true" }, output: "", cursor: 0, size: 0 },
|
||||
"cap-unavail": { shell: { id: "cap-unavail", status: "running", command: "sleep 30" }, unavailable: true },
|
||||
"cap-trunc": { shell: { id: "cap-trunc", status: "running", command: "yes | head -c 200000" }, output: "x".repeat(400), cursor: 400, size: 200000, truncated: true },
|
||||
"cap-slow": { shell: { id: "cap-slow", status: "running", command: "sleep 60" }, output: "slow page\\n" },
|
||||
};
|
||||
window.__pipelinesIntercept = (frame) => {
|
||||
if (frame.type !== "chat_shell_output") return null;
|
||||
const query = frame.chat_shell_output_query || {};
|
||||
(window.__pipelinesShellReads = window.__pipelinesShellReads || []).push({
|
||||
shell_id: query.shell_id,
|
||||
cursor: query.cursor,
|
||||
limit: query.limit,
|
||||
});
|
||||
const page = window.__pipelinesPages[query.shell_id];
|
||||
if (!page) return null;
|
||||
return { id: frame.id, type: "chat_shell_output", chat_shell_output: page };
|
||||
};
|
||||
return true;
|
||||
})()`);
|
||||
|
||||
const shellFrame = (id, command, status) => ({ session_id: sessionId, kind: "shell", shell: { id, status, command } });
|
||||
const replayShells = (frames) =>
|
||||
page.evaluate(`(() => {
|
||||
const ws = window.__pipelinesSocket;
|
||||
if (!ws || typeof ws.onmessage !== "function") return false;
|
||||
for (const frame of ${JSON.stringify(
|
||||
[
|
||||
shellFrame("cap-run", "go test ./... -count=1", "running"),
|
||||
shellFrame("cap-empty", "true", "running"),
|
||||
shellFrame("cap-unavail", "sleep 30", "running"),
|
||||
shellFrame("cap-trunc", "yes | head -c 200000", "running"),
|
||||
shellFrame("cap-slow", "sleep 60", "running"),
|
||||
],
|
||||
)}) {
|
||||
ws.onmessage({ data: JSON.stringify({ type: "chat_event", chat_event: frame }) });
|
||||
}
|
||||
return true;
|
||||
})()`);
|
||||
|
||||
const ok = await replayShells();
|
||||
if (!ok) throw new Error("C11: the socket shim did not expose the live socket for the shell frames");
|
||||
await eventually(() => page.evaluate(`!!document.querySelector("#chatBackgroundTasks")`), {
|
||||
timeout: 10000,
|
||||
what: "the background-tasks bar to render",
|
||||
});
|
||||
|
||||
// A transient ping failure during the section's own reconnect can leave the
|
||||
// page-level `Error:` banner up (a pre-existing surface from onConnected's
|
||||
// ping). Clicking the active tab is the page's own way to clear it, and the
|
||||
// conversation and the bar are rebuilt from thread state, so the capture shows
|
||||
// the feature rather than a stale unrelated error.
|
||||
const clearBanner = () =>
|
||||
page.evaluate(`(() => {
|
||||
if (!document.querySelector(".banner.error")) return true;
|
||||
const tab = [...document.querySelectorAll("nav.tabs button.tab")].find((b) => b.classList.contains("active"));
|
||||
if (tab) tab.click();
|
||||
return !document.querySelector(".banner.error");
|
||||
})()`);
|
||||
|
||||
const c11Bar = await page.evaluate(`(() => {
|
||||
const el = document.querySelector("#chatBackgroundTasks");
|
||||
if (!el) return null;
|
||||
const list = el.querySelector(".chat-bg-tasks-list");
|
||||
const rows = [...el.querySelectorAll(".chat-bg-task")];
|
||||
return {
|
||||
title: el.querySelector(".chat-bg-tasks-title")?.textContent ?? "",
|
||||
count: el.querySelector(".chat-bg-tasks-count")?.textContent ?? "",
|
||||
rows: rows.length,
|
||||
scrollable: list ? list.scrollHeight > list.clientHeight + 1 : false,
|
||||
listHeight: list ? list.clientHeight : 0,
|
||||
rowHeight: rows[0] ? Math.round(rows[0].getBoundingClientRect().height) : 0,
|
||||
commands: rows.map((r) => r.querySelector(".chat-bg-task-command")?.textContent ?? ""),
|
||||
glyphs: el.querySelectorAll(".chat-bg-task-glyph").length,
|
||||
statuses: rows.map((r) => r.querySelector(".chat-bg-task-status")?.textContent ?? ""),
|
||||
};
|
||||
})()`);
|
||||
if (!c11Bar) throw new Error("C11: the background-tasks bar did not render");
|
||||
if (c11Bar.title !== "Background tasks") throw new Error(`C11: bar title ${JSON.stringify(c11Bar.title)}`);
|
||||
if (c11Bar.count !== "5 running") throw new Error(`C11: bar count ${JSON.stringify(c11Bar.count)}`);
|
||||
if (c11Bar.rows !== 5) throw new Error(`C11: expected 5 rows, got ${c11Bar.rows}`);
|
||||
if (!c11Bar.scrollable) throw new Error(`C11: a 5-row list did not scroll (height ${c11Bar.listHeight}px)`);
|
||||
if (c11Bar.listHeight > c11Bar.rowHeight * 3 + 16) {
|
||||
throw new Error(`C11: the list is not capped near three rows (${c11Bar.listHeight}px for ${c11Bar.rowHeight}px rows)`);
|
||||
}
|
||||
if (c11Bar.glyphs !== 5) throw new Error(`C11: every row should carry a play glyph, got ${c11Bar.glyphs}`);
|
||||
if (!c11Bar.statuses.every((word) => word === "Running")) {
|
||||
throw new Error(`C11: row statuses: ${JSON.stringify(c11Bar.statuses)}`);
|
||||
}
|
||||
console.log(
|
||||
` background-tasks bar "${c11Bar.title}" (${c11Bar.count}); ${c11Bar.rows} rows, ` +
|
||||
`3-row cap (list ${c11Bar.listHeight}px, row ${c11Bar.rowHeight}px), scrolling: ${c11Bar.scrollable}`,
|
||||
);
|
||||
console.log(
|
||||
" NOTE: the shell frames above are replayed synthetic chat_event frames; every other frame (chat_shells, subscribe, history) came from the real server",
|
||||
);
|
||||
await clearBanner();
|
||||
await shot("65-chat-background-tasks.png");
|
||||
|
||||
// A selected task's detail pane: the exact label order and wording, and the
|
||||
// bounded output page it read from its own request. Rows are clicked through
|
||||
// their own handler (and scrolled into view) so a row below the three-row fold
|
||||
// is reachable without a coordinate click landing on the clipped list. A
|
||||
// spurious socket drop can fail a single bounded read (the client refuses to
|
||||
// send while reconnecting), so each read is retried a bounded number of times
|
||||
// through the page's own controls after the socket settles.
|
||||
const clickShellRow = (id) =>
|
||||
page.evaluate(`(() => {
|
||||
const el = document.querySelector('#chatBackgroundTasks .chat-bg-task[data-shell="${id}"]');
|
||||
if (!el) return false;
|
||||
el.scrollIntoView({ block: "center" });
|
||||
el.click();
|
||||
return true;
|
||||
})()`);
|
||||
|
||||
const openShell = async (shellId, readyExpr, what) => {
|
||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||
// A transient drop can clear the connection and (on reconnect) the replayed
|
||||
// shells; settle the socket and re-establish the bar before selecting.
|
||||
await ensureConnected(30000).catch(() => {});
|
||||
if (!(await page.evaluate(`!!document.querySelector("#chatBackgroundTasks")`))) {
|
||||
await replayShells();
|
||||
await eventually(() => page.evaluate(`!!document.querySelector("#chatBackgroundTasks")`), {
|
||||
timeout: 5000,
|
||||
what: "the bar to render again after a reconnect",
|
||||
});
|
||||
}
|
||||
const selected = await page.evaluate(
|
||||
`document.querySelector("#chatBackgroundTasks .chat-bg-task.selected")?.dataset.shell ?? ""`,
|
||||
);
|
||||
// Selecting the already-selected row is the documented toggle, so close it
|
||||
// first to force a fresh bounded read.
|
||||
if (selected === shellId && !(await clickShellRow(shellId))) {
|
||||
throw new Error(`C11: the ${shellId} row was not present`);
|
||||
}
|
||||
if (!(await clickShellRow(shellId))) throw new Error(`C11: the ${shellId} row was not present`);
|
||||
try {
|
||||
await eventually(() => page.evaluate(readyExpr), { timeout: 8000, what });
|
||||
return;
|
||||
} catch {
|
||||
console.log(` ${shellId}: the read did not land (attempt ${attempt}); settling the socket and retrying`);
|
||||
await page.evaluate(`window.dispatchEvent(new Event("online"))`);
|
||||
}
|
||||
}
|
||||
throw new Error(`C11: ${what} never rendered for ${shellId}`);
|
||||
};
|
||||
|
||||
await openShell(
|
||||
"cap-run",
|
||||
`!!document.querySelector("#chatBackgroundTasks .chat-bg-task-output")`,
|
||||
"the output pane for cap-run",
|
||||
);
|
||||
const c11Detail = await page.evaluate(`(() => {
|
||||
const detail = document.querySelector("#chatBackgroundTasks .chat-bg-task-detail");
|
||||
return {
|
||||
labels: [...detail.querySelectorAll(".chat-bg-task-label")].map((n) => n.textContent),
|
||||
command: detail.querySelector(".chat-bg-task-command-full")?.textContent ?? "",
|
||||
id: detail.querySelector(".chat-bg-task-id")?.textContent ?? "",
|
||||
idMono: !!detail.querySelector(".chat-bg-task-id.monospace"),
|
||||
status: detail.querySelector(".chat-bg-task-status-line")?.textContent ?? "",
|
||||
output: detail.querySelector(".chat-bg-task-output")?.textContent ?? "",
|
||||
refresh: detail.querySelector(".chat-bg-task-refresh")?.textContent ?? "",
|
||||
selected: document.querySelector("#chatBackgroundTasks .chat-bg-task.selected")?.dataset.shell ?? "",
|
||||
detailsWord: document.querySelector("#chatBackgroundTasks .chat-bg-task.selected .chat-bg-task-details")?.textContent ?? "",
|
||||
};
|
||||
})()`);
|
||||
if (!c11Detail.labels.includes("Command")) throw new Error(`C11: missing Command label: ${JSON.stringify(c11Detail.labels)}`);
|
||||
if (!c11Detail.labels.includes("Task identity")) throw new Error(`C11: missing Task identity label`);
|
||||
if (!c11Detail.labels.includes("Output")) throw new Error(`C11: missing Output label`);
|
||||
if (c11Detail.command !== "go test ./... -count=1") throw new Error(`C11: command ${JSON.stringify(c11Detail.command)}`);
|
||||
if (c11Detail.id !== "cap-run" || !c11Detail.idMono) throw new Error(`C11: task identity ${JSON.stringify(c11Detail.id)} mono=${c11Detail.idMono}`);
|
||||
if (c11Detail.status !== "Status: running") throw new Error(`C11: status ${JSON.stringify(c11Detail.status)}`);
|
||||
if (!c11Detail.output.includes("ok")) throw new Error(`C11: output ${JSON.stringify(c11Detail.output)}`);
|
||||
if (c11Detail.refresh !== "Refresh") throw new Error(`C11: refresh control ${JSON.stringify(c11Detail.refresh)}`);
|
||||
if (c11Detail.selected !== "cap-run") throw new Error(`C11: selected row ${JSON.stringify(c11Detail.selected)}`);
|
||||
if (c11Detail.detailsWord !== "Details") throw new Error(`C11: details word ${JSON.stringify(c11Detail.detailsWord)}`);
|
||||
console.log(
|
||||
` selected task detail: labels [${c11Detail.labels.join(", ")}], command "${c11Detail.command}", ` +
|
||||
`id "${c11Detail.id}" (monospace), "${c11Detail.status}", output ${JSON.stringify(c11Detail.output)}`,
|
||||
);
|
||||
await clearBanner();
|
||||
await shot("66-chat-background-task-detail.png");
|
||||
|
||||
// Refresh always rereads the bounded page from cursor 0 and never appends: the
|
||||
// page's own Refresh control issues a second read with the same bounds (the
|
||||
// intercepted request is the page's real wire frame).
|
||||
await page.evaluate(`window.__pipelinesShellReads = []`);
|
||||
await page.evaluate(`document.querySelector("#chatBackgroundTasks .chat-bg-task-refresh").click()`);
|
||||
await eventually(
|
||||
() =>
|
||||
page.evaluate(
|
||||
`(window.__pipelinesShellReads || []).some((r) => r.shell_id === "cap-run" && r.cursor === 0 && r.limit === 65536)`,
|
||||
),
|
||||
{ timeout: 8000, what: "the Refresh re-read at cursor 0 / 64 KiB" },
|
||||
);
|
||||
const refreshReads = await page.evaluate(`window.__pipelinesShellReads`);
|
||||
console.log(
|
||||
` Refresh re-read: ${refreshReads.length} read(s), ` +
|
||||
refreshReads.map((r) => `{shell:${r.shell_id},cursor:${r.cursor},limit:${r.limit}}`).join(", "),
|
||||
);
|
||||
|
||||
// The empty page, the server-reported unavailable page and a truncated page.
|
||||
const noteIs = (expected) =>
|
||||
`document.querySelector("#chatBackgroundTasks .chat-bg-task-note")?.textContent === ${JSON.stringify(expected)}`;
|
||||
await openShell("cap-empty", noteIs("No output yet."), "the No output yet. note");
|
||||
console.log(" cap-empty: \"No output yet.\"");
|
||||
await clearBanner();
|
||||
await shot("67-chat-background-task-empty.png");
|
||||
await openShell("cap-unavail", noteIs("Output unavailable for this task."), "the unavailable note");
|
||||
console.log(" cap-unavail: \"Output unavailable for this task.\"");
|
||||
await clearBanner();
|
||||
await shot("68-chat-background-task-unavailable.png");
|
||||
|
||||
await openShell("cap-trunc", noteIs("Output is bounded to 64 KiB."), "the 64 KiB bound note");
|
||||
const c11Truncated = await page.evaluate(`(() => {
|
||||
const detail = document.querySelector("#chatBackgroundTasks .chat-bg-task-detail");
|
||||
return {
|
||||
note: detail.querySelector(".chat-bg-task-note")?.textContent ?? "",
|
||||
length: detail.querySelector(".chat-bg-task-output")?.textContent.length ?? 0,
|
||||
refresh: !!detail.querySelector(".chat-bg-task-refresh"),
|
||||
};
|
||||
})()`);
|
||||
if (c11Truncated.note !== "Output is bounded to 64 KiB.") throw new Error(`C11: truncated note ${JSON.stringify(c11Truncated.note)}`);
|
||||
if (c11Truncated.length !== 400) throw new Error(`C11: truncated output length ${c11Truncated.length}`);
|
||||
if (!c11Truncated.refresh) throw new Error("C11: a truncated page should still offer Refresh");
|
||||
console.log(` cap-trunc: "${c11Truncated.note}" (${c11Truncated.length}-char page, Refresh offered)`);
|
||||
await clearBanner();
|
||||
await shot("69-chat-background-task-truncated.png");
|
||||
|
||||
// The loading spinner: the same select, with the replayed page delayed.
|
||||
await page.evaluate(`window.__pipelinesInterceptDelay = 1500`);
|
||||
if (!(await clickShellRow("cap-slow"))) throw new Error("C11: the cap-slow row was not present");
|
||||
await eventually(
|
||||
() => page.evaluate(`!!document.querySelector("#chatBackgroundTasks .chat-bg-task-detail .spinner")`),
|
||||
{ timeout: 5000, what: "the loading spinner for cap-slow" },
|
||||
);
|
||||
const loading = await page.evaluate(`(() => ({
|
||||
spinner: !!document.querySelector("#chatBackgroundTasks .chat-bg-task-detail .spinner"),
|
||||
status: document.querySelector("#chatBackgroundTasks .chat-bg-task-status-line")?.textContent ?? "",
|
||||
output: !!document.querySelector("#chatBackgroundTasks .chat-bg-task-output"),
|
||||
}))()`);
|
||||
if (!loading.spinner || loading.output) throw new Error(`C11: loading pane ${JSON.stringify(loading)}`);
|
||||
console.log(` cap-slow: spinner while loading ("${loading.status}")`);
|
||||
await clearBanner();
|
||||
await shot("70-chat-background-task-loading.png");
|
||||
for (let attempt = 1; attempt <= 3; attempt += 1) {
|
||||
let loaded = true;
|
||||
try {
|
||||
await eventually(
|
||||
() => page.evaluate(`!!document.querySelector("#chatBackgroundTasks .chat-bg-task-output")`),
|
||||
{ timeout: 8000, what: "the slow page to arrive" },
|
||||
);
|
||||
} catch {
|
||||
loaded = false;
|
||||
}
|
||||
if (loaded) break;
|
||||
console.log(` cap-slow: the page did not arrive (attempt ${attempt}); settling and retrying`);
|
||||
await page.evaluate(`window.dispatchEvent(new Event("online"))`);
|
||||
await ensureConnected(30000).catch(() => {});
|
||||
if (!(await page.evaluate(`!!document.querySelector("#chatBackgroundTasks")`))) await replayShells();
|
||||
await page.evaluate(`document.querySelector("#chatBackgroundTasks .chat-bg-task-retry")?.click()`);
|
||||
}
|
||||
await page.evaluate(`window.__pipelinesInterceptDelay = 0`);
|
||||
|
||||
// The last exit clears the bar: replay an exited frame for every task and assert
|
||||
// the bar disappears (an exited shell is never listed as a task).
|
||||
await page.evaluate(`(() => {
|
||||
const ws = window.__pipelinesSocket;
|
||||
const ids = ["cap-run", "cap-empty", "cap-unavail", "cap-trunc", "cap-slow"];
|
||||
for (const id of ids) {
|
||||
ws.onmessage({ data: JSON.stringify({ type: "chat_event", chat_event: { session_id: ${JSON.stringify(sessionId)}, kind: "shell", shell: { id, status: "exited", command: "" } } }) });
|
||||
}
|
||||
return true;
|
||||
})()`);
|
||||
await eventually(() => page.evaluate(`!document.querySelector("#chatBackgroundTasks")`), {
|
||||
timeout: 5000,
|
||||
what: "the bar to disappear with the last exit",
|
||||
});
|
||||
console.log(" all shells exited: the background-tasks bar is gone");
|
||||
await clearBanner();
|
||||
await shot("71-chat-background-tasks-exited.png");
|
||||
|
||||
// The list is re-learned on a stream reconnect: a real chat_shells request is
|
||||
// sent after the drop (real traffic), so a gap that swallowed an exit is repaired.
|
||||
await page.evaluate(`window.__pipelinesSentTypes = []`);
|
||||
await page.evaluate(`window.__pipelinesSocket && window.__pipelinesSocket.close(4000, "c11 drop")`);
|
||||
await ensureConnected(30000);
|
||||
await eventually(
|
||||
() => page.evaluate(`(window.__pipelinesSentTypes || []).includes("chat_shells")`),
|
||||
{ timeout: 20000, what: "chat_shells after the stream reconnect" },
|
||||
);
|
||||
console.log(" chat_shells re-fetched after the stream reconnect (real request)");
|
||||
|
||||
console.log("\nUI SMOKE PASS");
|
||||
for (const shot of shots) console.log(` ${shot}`);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user