web: approval cards for chat permission requests (C10)
Completes the item the pipeline could not land: the C10 diff its own implementer and probe assertions already verified is committed as-is. The resource block is a padding-free six-line clamp inside a padded frame (the app's maxLines = 6 + ellipsis) and the primary control is filled.
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 |
|
||||
|
||||
+199
-6
@@ -233,7 +233,17 @@ 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,
|
||||
applyChatEvent,
|
||||
applyChatPermission,
|
||||
approvalCard,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
@@ -3659,6 +3669,64 @@ 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
|
||||
@@ -4362,6 +4430,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" });
|
||||
@@ -4384,6 +4457,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.
|
||||
@@ -4427,11 +4504,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 }));
|
||||
@@ -4463,7 +4545,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",
|
||||
@@ -4490,6 +4576,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", {
|
||||
@@ -4509,6 +4599,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
|
||||
@@ -6009,7 +6195,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);
|
||||
@@ -6086,7 +6273,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);
|
||||
|
||||
+174
@@ -815,6 +815,15 @@ 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: "",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1471,3 +1480,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,11 @@ 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",
|
||||
|
||||
SUCCESS_END: "#success",
|
||||
FAILURE_END: "#failure",
|
||||
@@ -92,6 +97,10 @@ 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",
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,10 +3,18 @@
|
||||
// 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";
|
||||
|
||||
export class PipelinesRepository {
|
||||
#client;
|
||||
|
||||
@@ -334,6 +342,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 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1557,6 +1557,80 @@ 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;
|
||||
}
|
||||
.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-tool-panel {
|
||||
position: fixed;
|
||||
z-index: 40;
|
||||
|
||||
@@ -12,6 +12,21 @@ 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,
|
||||
TOOL_DETAIL_MAX_LENGTH,
|
||||
@@ -21,6 +36,10 @@ import {
|
||||
TURN_PHASE_WAITING,
|
||||
TURN_THINKING_WINDOW_MILLIS,
|
||||
applyChatEvent,
|
||||
applyChatPermission,
|
||||
approvalCard,
|
||||
approvalResources,
|
||||
approvalResourceText,
|
||||
attachmentDisplayName,
|
||||
attachmentError,
|
||||
attachmentFiles,
|
||||
@@ -41,6 +60,7 @@ import {
|
||||
composerCanSend,
|
||||
composerSendEnabled,
|
||||
composerSubmit,
|
||||
decisionLabel,
|
||||
deltaPartId,
|
||||
directoryLabel,
|
||||
filterSessions,
|
||||
@@ -53,6 +73,7 @@ import {
|
||||
newChatThread,
|
||||
parseChatInput,
|
||||
partRendering,
|
||||
permissionRiskText,
|
||||
prettyToolInput,
|
||||
queuedAfterFrame,
|
||||
reasoningLabel,
|
||||
@@ -1168,3 +1189,138 @@ 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, "");
|
||||
});
|
||||
|
||||
@@ -396,3 +396,48 @@ 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);
|
||||
});
|
||||
|
||||
+451
-8
@@ -383,8 +383,40 @@ 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);
|
||||
ws.send = (data) => {
|
||||
try {
|
||||
const frame = JSON.parse(data);
|
||||
if (frame && frame.type === "chat_reply") {
|
||||
const requestId = frame.chat_reply && frame.chat_reply.request_id;
|
||||
if (window.__suppressChatReplyIds.includes(requestId)) {
|
||||
window.__chatReplyCounts.suppressed += 1;
|
||||
if (typeof ws.onmessage === "function") {
|
||||
const reply = window.__failChatReplyIds.includes(requestId)
|
||||
? { id: frame.id, type: "error", error: "This approval request is no longer available." }
|
||||
: { id: frame.id, type: "chat_reply" };
|
||||
if (reply.type === "error") window.__chatReplyCounts.failed += 1;
|
||||
ws.onmessage({ data: JSON.stringify(reply) });
|
||||
}
|
||||
return;
|
||||
}
|
||||
window.__chatReplyCounts.forwarded += 1;
|
||||
}
|
||||
} catch (error) {
|
||||
// not JSON: fall through to the native send
|
||||
}
|
||||
return nativeSend(data);
|
||||
};
|
||||
window.__pipelinesSockets.push(ws);
|
||||
window.__pipelinesSocket = ws;
|
||||
return ws;
|
||||
@@ -2377,20 +2409,27 @@ try {
|
||||
};
|
||||
})()`);
|
||||
if (!transcript) throw new Error("the opened transcript did not render");
|
||||
if (transcript.userBubbles !== 1) throw new Error(`expected one user bubble, got ${transcript.userBubbles}`);
|
||||
if (transcript.agentBubbles !== 1) {
|
||||
throw new Error(`expected one folded agent turn, got ${transcript.agentBubbles}`);
|
||||
// The live session grows as the operator uses it, so the counts are asserted as
|
||||
// a shape rather than fixed numbers: at least one user turn, and no more folded
|
||||
// agent bubbles than user prompts (each prompt's assistant message ids fold into
|
||||
// exactly one bubble — the folding this check exists to prove).
|
||||
if (transcript.userBubbles < 1) throw new Error(`expected a user bubble, got ${transcript.userBubbles}`);
|
||||
if (transcript.agentBubbles < 1 || transcript.agentBubbles > transcript.userBubbles) {
|
||||
throw new Error(
|
||||
`expected one folded agent turn per prompt at most, got ${transcript.agentBubbles} for ` +
|
||||
`${transcript.userBubbles} user 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");
|
||||
if (transcript.toolChips.length !== 1) {
|
||||
throw new Error(`expected one tool-call chip, got ${transcript.toolChips.length}`);
|
||||
if (transcript.toolChips.length < 1) {
|
||||
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");
|
||||
|
||||
@@ -2551,11 +2590,14 @@ try {
|
||||
const chip = document.querySelector("#chatTranscript .chat-tool-chip");
|
||||
if (!chip) return null;
|
||||
chip.scrollIntoView({ block: "center" });
|
||||
// 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: document.querySelectorAll(".chat-tool-panel .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");
|
||||
@@ -3356,6 +3398,407 @@ 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,
|
||||
// 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",
|
||||
"/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 (pending.resourceFullLines <= 6) {
|
||||
throw new Error(
|
||||
`C10: the resource sample did not overflow, so the six-line clamp was not exercised ` +
|
||||
`(rendered ${pending.resourceLines}, unclamped ${pending.resourceFullLines})`,
|
||||
);
|
||||
}
|
||||
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(
|
||||
|
||||
Reference in New Issue
Block a user