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:
2026-10-19 11:08:53 +01:00
parent 27a1605127
commit 5eb13968e3
9 changed files with 1148 additions and 15 deletions
+451 -8
View File
@@ -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(