Merge branch 'main' into web-settings

This commit is contained in:
2026-10-19 11:31:45 +01:00
9 changed files with 2450 additions and 39 deletions
+446 -12
View File
@@ -2,7 +2,7 @@
// Deliberately small and DOM-only (no framework, no build step). Every value
// that came from the server is set with textContent, never innerHTML.
import { PipelinesClient } from "./client.js";
import { PipelinesRepository } from "./repository.js";
import { PipelinesRepository, SHELL_OUTPUT_LIMIT } from "./repository.js";
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
import {
@@ -227,6 +227,7 @@ import {
retryRequestKey,
} from "./actions.js";
import {
BACKGROUND_TASKS_TITLE,
CHAT_ATTACH_LABEL,
CHAT_COMMAND_GLYPH,
CHAT_COMPOSER_PLACEHOLDER,
@@ -253,10 +254,29 @@ import {
LOAD_OLDER_ACTION,
REOPEN_ACTION,
SELECT_CHAT_HINT,
APPROVAL_CONTROL_ALWAYS,
APPROVAL_CONTROL_ONCE,
APPROVAL_CONTROL_REJECT,
DECISION_ALWAYS,
DECISION_ONCE,
DECISION_REJECT,
RISK_REVIEW_LABEL,
WAITING_FOR_APPROVAL_LABEL,
SHELL_DETAILS_LABEL,
SHELL_OUTPUT_EMPTY,
SHELL_OUTPUT_ERROR,
SHELL_OUTPUT_LABELS,
SHELL_OUTPUT_LOADING,
SHELL_OUTPUT_READY,
SHELL_OUTPUT_UNAVAILABLE,
SHELL_ROW_LABEL,
applyChatEvent,
applyChatPermission,
approvalCard,
attachmentDisplayName,
attachmentError,
attachmentFiles,
backgroundTasksRunningLabel,
chatBottomDistancePx,
chatCommandEffect,
chatCommandHelp,
@@ -278,11 +298,14 @@ import {
groupSessionsByDirectory,
historyResync,
mergeHistoryPage,
mergeShellFrame,
newChatThread,
parseChatInput,
queuedAfterFrame,
reasoningLabel,
resumedThread,
runningAfterFrame,
runningBackgroundShells,
runningToolElapsedMillis,
sessionActivity,
sessionActivityBadge,
@@ -292,6 +315,9 @@ import {
sessionTitle,
sessionWorkLabel,
settledThread,
shellCommandSummary,
shellOutputState,
shellsLoaded,
formatToolDuration,
threadElapsedMillis,
threadPhase,
@@ -3990,6 +4016,9 @@ async function openChatSession(id) {
// Attach the shared live stream once per session per connection; its failure is
// non-fatal — history stays usable and the badge reads "not live".
subscribeChatSession(id);
// Load the session's background shells (C11) so the bar appears on open, not
// only after the next pushed shell frame.
loadChatShells(id);
await loadChatHistory(id);
}
@@ -4024,13 +4053,18 @@ function clearChatSubscriptions() {
}
/**
* Settle every conversation that was running. A socket drop (or a close) removes
* the frames feeding the turn, so no thread keeps claiming to run until a fresh
* frame proves otherwise.
* Settle every conversation that was running, and drop its observed shells. A
* socket drop (or a close) removes the frames feeding the turn, so no thread
* keeps claiming to run until a fresh frame proves otherwise; a shell's exit may
* have been swallowed by the same gap, so the retained shells are forgotten and
* re-learned from `chat_shells` on reconnect (mirrors ChatStore.streamResumed).
*/
function settleChatThreads() {
for (const [id, thread] of state.chatThreads) {
if (thread?.running || thread?.queued) state.chatThreads.set(id, settledThread(thread));
const hasShells = (thread?.shells ?? []).length > 0;
if (thread?.running || thread?.queued || hasShells) {
state.chatThreads.set(id, resumedThread(thread));
}
}
}
@@ -4048,24 +4082,173 @@ function onChatEvent(frame) {
renderContent();
}
/**
* Fold one pushed `chat_permission` frame into its conversation (C10). Only a
* conversation this client has open is folded — the server only pushes a
* permission frame for sessions this connection is subscribed to, but the guard
* keeps a frame for a session nobody opened from creating a thread. The card is
* derived from the stored frame plus the local answer, so a resolved re-push
* always clears the controls.
*/
function onChatPermission(frame) {
const sessionId = String(frame?.session_id ?? "").trim();
if (!sessionId || !state.chatThreads.has(sessionId)) return;
const thread = state.chatThreads.get(sessionId);
const next = applyChatPermission(thread, frame);
// A different request replaces the card, so the previous refusal's reason (and
// the error line it owns) no longer describes what is on screen.
const replaced =
String(thread?.permission?.request_id ?? "") !== String(next.permission?.request_id ?? "");
if (replaced && thread?.permissionError) {
next.error = thread.error === thread.permissionError ? "" : next.error;
next.permissionError = "";
}
state.chatThreads.set(sessionId, next);
if (sessionId === state.chatActiveId) renderContent();
}
/**
* Answer the pending permission request (C10): settle the matching card
* optimistically so the buttons are never left offering a decision already made,
* then send `chat_reply`. A refused reply reopens the same request (the local
* answer is cleared) and surfaces the server's reason through the thread's own
* error line, so an unaccepted decision is never shown as accepted. A refusal
* that arrives after a different request replaced the card is ignored.
*/
async function answerPermission(sessionId, requestId, decision) {
const thread = state.chatThreads.get(sessionId);
const permission = thread?.permission;
if (!thread || String(permission?.request_id ?? "") !== requestId) return;
setThread(sessionId, { permissionAnswer: decision });
renderContent();
try {
await repo.chatReply(sessionId, requestId, decision);
// A retried answer the server accepted clears the reason a previous refusal
// left on the thread's error line — and only that reason, never an unrelated
// error the conversation is carrying.
const settled = state.chatThreads.get(sessionId);
if (settled?.permissionError && settled.error === settled.permissionError) {
setThread(sessionId, { error: "", permissionError: "" });
renderContent();
}
} catch (error) {
const current = state.chatThreads.get(sessionId);
if (!current || String(current.permission?.request_id ?? "") !== requestId) return;
const reason = describeError(error);
setThread(sessionId, { permissionAnswer: "", error: reason, permissionError: reason });
renderContent();
}
}
/**
* The reconnect repair (C5): re-attach the open chat's stream and replace its
* conversation with the newest history page wholesale. Everything the gap could
* have missed is repaired; a turn that was in flight is settled. Only the open
* conversation is repaired — the others are not on screen.
* Fetch a session's currently verified shells (C11) and retain only the exits
* this client itself observed, so an exited task never reappears as running and a
* shell the server no longer lists drops out. Called when the conversation opens
* and on every stream reconnect (a gap may have swallowed an exit). A failure is
* non-fatal: the transcript stays usable and the bar keeps its last known state.
*/
async function loadChatShells(id) {
if (!id || state.connection.kind !== "connected") return;
try {
const running = await repo.chatShells(id);
const thread = state.chatThreads.get(id);
if (!thread) return;
state.chatThreads.set(id, { ...thread, shells: shellsLoaded(thread.shells, running) });
renderContent();
} catch {
// The shell list is a background convenience; leave the thread untouched.
}
}
/**
* Toggle a running task's detail pane (C11). Selecting a shell fetches its
* bounded output page; selecting the selected one again closes it. Mirrors
* ChatStore.selectShell: an id that is not a known shell is ignored.
*/
function selectChatShell(shellId) {
const sessionId = state.chatActiveId;
const thread = sessionId ? state.chatThreads.get(sessionId) : null;
if (!thread) return;
const closing = thread.selectedShellId === shellId;
if (!closing && !(thread.shells ?? []).some((shell) => shell.id === shellId)) return;
const next = closing ? null : shellId;
state.chatThreads.set(sessionId, { ...thread, selectedShellId: next, shellOutput: null });
renderContent();
if (next) refreshChatShellOutput(next);
}
/**
* Reread a selected task's bounded output page (C11) from the page's start. The
* cursor is always 0 and the limit is the server's 64 KiB bound, so the client
* never grows output unbounded and a Refresh never appends. A reply for a shell
* that is no longer selected is ignored, exactly like ChatStore.shellOutput*.
*/
async function refreshChatShellOutput(shellId) {
const sessionId = state.chatActiveId;
if (!sessionId || !shellId) return;
shellOutputLoading(sessionId, shellId);
renderContent();
try {
const page = await repo.chatShellOutput(sessionId, shellId, { cursor: 0, limit: SHELL_OUTPUT_LIMIT });
shellOutputLoaded(sessionId, shellId, page);
} catch (error) {
shellOutputFailed(sessionId, shellId, describeError(error));
}
renderContent();
}
/** Mark a selected task's output pane loading (ignored for a stale selection). */
function shellOutputLoading(sessionId, shellId) {
const thread = state.chatThreads.get(sessionId);
if (!thread || thread.selectedShellId !== shellId) return;
state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: true, error: "", page: null } });
}
/**
* Apply a loaded output page, merging a shell the page reports back into the
* retained list (keeping the command already learned when the page omits it).
*/
function shellOutputLoaded(sessionId, shellId, page) {
const thread = state.chatThreads.get(sessionId);
if (!thread || thread.selectedShellId !== shellId) return;
const reported = page?.shell;
const shells = reported && String(reported.id ?? "").trim() !== ""
? mergeShellFrame(thread.shells, reported)
: thread.shells ?? [];
state.chatThreads.set(sessionId, { ...thread, shells, shellOutput: { loading: false, error: "", page } });
}
/** Report a failed output read against the still-selected task (Retry is offered). */
function shellOutputFailed(sessionId, shellId, message) {
const thread = state.chatThreads.get(sessionId);
if (!thread || thread.selectedShellId !== shellId) return;
state.chatThreads.set(sessionId, { ...thread, shellOutput: { loading: false, error: message, page: null } });
}
/**
* The reconnect repair (C5/C11): re-attach the open chat's stream, replace its
* conversation with the newest history page wholesale and re-learn its shells.
* Everything the gap could have missed is repaired; a turn that was in flight is
* settled and the retained shells are dropped before the fresh snapshot arrives.
* Only the open conversation is repaired — the others are not on screen.
*/
async function resyncOpenChat() {
const id = state.chatActiveId;
if (!id || state.connection.kind !== "connected") return;
await subscribeChatSession(id);
const previous = state.chatThreads.get(id) ?? newChatThread(id);
state.chatThreads.set(id, settledThread(previous));
state.chatThreads.set(id, resumedThread(previous));
try {
const page = await repo.chatHistory(id);
state.chatThreads.set(id, historyResync(previous, page));
} catch {
// The history refresh failed; the settled thread stands and the badge is honest.
}
await loadChatShells(id);
renderContent();
}
@@ -4751,6 +4934,11 @@ function renderChatConversation() {
const session = state.chatSessions.find((candidate) => candidate.id === state.chatActiveId) ?? null;
const thread = state.chatThreads.get(state.chatActiveId) ?? null;
const title = session ? sessionTitle(session) : state.chatActiveId.slice(0, 18);
// The pending approval card (C10), derived from the stored frame plus the local
// answer. While it is actionable the top bar offers a jump control and the
// running indicator stands down (a turn blocked on a decision is not generating).
const approval = approvalCard(thread?.permission, thread?.permissionAnswer);
const awaiting = approval?.actionable === true;
const bar = h("div", { class: "chat-bar" });
const titles = h("div", { class: "chat-bar-titles" });
@@ -4773,6 +4961,10 @@ function renderChatConversation() {
}),
);
}
// The approval jump control appears only while a request is actionable, and
// brings its card (the transcript's last item) into view — the one scroll path,
// so a pending request is reached the same way new content is.
if (awaiting) bar.append(approvalJumpButton());
pane.append(bar);
// The context line: the kind chip, the activity word and directory · model.
@@ -4800,6 +4992,12 @@ function renderChatConversation() {
if (contextMeta !== "") context.append(h("span", { class: "chat-context-meta muted", text: contextMeta }));
pane.append(context);
// The background-tasks bar (C11) sits above the transcript, outside the
// scroller so the C14 scroll positions are untouched. It is present only while
// a shell is still running and disappears with the last exit.
const backgroundTasks = renderBackgroundTasks(thread);
if (backgroundTasks) pane.append(backgroundTasks);
const notices = thread?.notices ?? [];
if (thread?.loading && !thread?.loaded) {
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_LOADING }));
@@ -4816,11 +5014,16 @@ function renderChatConversation() {
pane.append(empty);
} else {
const rows = transcriptRows(thread?.messages ?? []);
const running = thread?.running === true;
if (rows.length === 0 && notices.length === 0 && !running) {
// The running indicator stands down while an approval is pending (C10): a turn
// blocked on a decision is not generating, so neither the spinner nor its clock
// shows. The composer's Stop control stays governed by thread.running.
const running = thread?.running === true && !awaiting;
if (rows.length === 0 && notices.length === 0 && !running && !approval) {
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
} else {
pane.append(renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now() }));
pane.append(
renderChatTranscript(state.chatActiveId, rows, { notices, running, now: Date.now(), approval }),
);
}
if (thread?.error && thread?.loaded) {
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
@@ -4845,6 +5048,126 @@ function appendChatDialogs(pane) {
if (state.actionError) pane.append(renderActionFailedDialog());
}
/**
* The background-tasks bar (C11): the running shells this conversation still
* owns. It returns null (renders nothing) unless at least one shell is running,
* so it disappears the moment the last task exits. Heading `Background tasks` +
* `{n} running`; the list shows at most BACKGROUND_TASK_VISIBLE_ROWS rows and
* scrolls beyond; a selected row reveals its bounded, read-only output pane.
* Every server string is set with textContent (never innerHTML).
*/
function renderBackgroundTasks(thread) {
const running = runningBackgroundShells(thread?.shells ?? []);
if (running.length === 0) return null;
const wrap = h("section", { class: "chat-bg-tasks", id: "chatBackgroundTasks" });
const head = h("div", { class: "chat-bg-tasks-head" });
head.append(h("span", { class: "chat-bg-tasks-title", text: BACKGROUND_TASKS_TITLE }));
head.append(
h("span", { class: "chat-bg-tasks-count muted", text: backgroundTasksRunningLabel(running.length) }),
);
wrap.append(head);
const list = h("div", { class: "chat-bg-tasks-list" });
const selectedId = thread?.selectedShellId ?? null;
running.forEach((shell) => list.append(renderBackgroundTaskRow(shell, shell.id === selectedId)));
wrap.append(list);
const selected = running.find((shell) => shell.id === selectedId) ?? null;
if (selected) wrap.append(renderBackgroundTaskDetail(thread, selected));
return wrap;
}
/** One running shell task; tapping it toggles its detail pane. */
function renderBackgroundTaskRow(shell, selected) {
const row = h("button", {
class: `chat-bg-task${selected ? " selected" : ""}`,
type: "button",
"data-shell": shell.id,
"aria-pressed": selected ? "true" : "false",
onclick: () => selectChatShell(shell.id),
});
// A CSS play glyph, decorative only (the row's own text names the task).
row.append(h("span", { class: "chat-bg-task-glyph", "aria-hidden": "true" }));
row.append(h("span", { class: "chat-bg-task-status", text: SHELL_ROW_LABEL }));
row.append(
h("span", {
class: "chat-bg-task-command",
text: shellCommandSummary(shell.command),
title: String(shell.command ?? ""),
}),
);
if (selected) row.append(h("span", { class: "chat-bg-task-details muted", text: SHELL_DETAILS_LABEL }));
return row;
}
/**
* The selected task's read-only detail: its command, its identity in monospace
* and `Status: running`, then the output area — the exact label order and wording
* of ChatTranscript.BackgroundProcessDetail. Reload is always a bounded reread
* from the page's start (`Refresh`; `Retry` after a failure).
*/
function renderBackgroundTaskDetail(thread, shell) {
const labels = SHELL_OUTPUT_LABELS;
const pane = h("div", { class: "chat-bg-task-detail" });
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.COMMAND }));
const command = String(shell.command ?? "").trim();
pane.append(
h("div", {
class: "chat-bg-task-command-full",
text: command === "" ? labels.UNAVAILABLE : shell.command,
}),
);
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.TASK_IDENTITY }));
pane.append(h("div", { class: "chat-bg-task-id monospace", text: String(shell.id ?? "") }));
pane.append(h("div", { class: "chat-bg-task-status-line", text: labels.STATUS_RUNNING }));
const output = thread?.shellOutput ?? null;
switch (shellOutputState(output)) {
case SHELL_OUTPUT_LOADING:
pane.append(h("span", { class: "spinner chat-bg-task-spinner", "aria-hidden": "true" }));
break;
case SHELL_OUTPUT_ERROR: {
const row = h("div", { class: "chat-bg-task-error-row" });
row.append(h("span", { class: "chat-bg-task-error", text: output.error }));
row.append(
h("button", {
class: "ghost chat-bg-task-retry",
type: "button",
text: labels.RETRY,
onclick: () => refreshChatShellOutput(shell.id),
}),
);
pane.append(row);
break;
}
case SHELL_OUTPUT_UNAVAILABLE:
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_UNAVAILABLE }));
break;
case SHELL_OUTPUT_EMPTY:
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.NO_OUTPUT }));
break;
case SHELL_OUTPUT_READY: {
const page = output.page;
pane.append(h("div", { class: "chat-bg-task-label muted", text: labels.OUTPUT }));
// Untrusted shell text: set as textContent, never parsed as markup.
pane.append(h("pre", { class: "chat-bg-task-output", text: String(page.output ?? "") }));
if (page.truncated) {
pane.append(h("div", { class: "chat-bg-task-note muted", text: labels.OUTPUT_BOUNDED }));
}
pane.append(
h("button", {
class: "ghost chat-bg-task-refresh",
type: "button",
text: labels.REFRESH,
onclick: () => refreshChatShellOutput(shell.id),
}),
);
break;
}
default:
break;
}
return pane;
}
/**
* The transcript: one column of turns. An operator message is its own
* right-aligned bubble (with the sending client's label when the server echoed
@@ -4852,7 +5175,11 @@ function appendChatDialogs(pane) {
* in order as the reasoning block, then the tool-call chip, then the answer
* markdown. No timestamps, model or agent are shown inside the transcript.
*/
function renderChatTranscript(sessionId, rows, { notices = [], running = false, now = Date.now() } = {}) {
function renderChatTranscript(
sessionId,
rows,
{ notices = [], running = false, now = Date.now(), approval = null } = {},
) {
const wrap = h("div", { class: "chat-transcript-wrap" });
const transcript = h("div", {
class: "chat-transcript",
@@ -4879,6 +5206,10 @@ function renderChatTranscript(sessionId, rows, { notices = [], running = false,
// The conversation's local command lines sit after the turns, full width and
// deliberately unlike a message bubble (see ChatCommandNoticeItem).
for (const notice of notices) transcript.append(renderChatCommandNotice(sessionId, notice));
// The approval card is the transcript's last item (C10) — after the notices and
// after the running indicator when it is shown — so the top bar's jump control
// and a fresh card both land at the end.
if (approval) transcript.append(renderChatApproval(sessionId, approval));
wrap.append(transcript);
wrap.append(
h("button", {
@@ -4898,6 +5229,102 @@ function renderChatTranscript(sessionId, rows, { notices = [], running = false,
return wrap;
}
/** The top bar's approval jump control (C10), naming the pending request. */
function approvalJumpButton() {
return h("button", {
class: "ghost chat-approval-jump",
type: "button",
text: WAITING_FOR_APPROVAL_LABEL,
onclick: () => {
// The card is the transcript's last item, so the transcript's own end is the
// card; the one scroll path shared with jump-to-latest.
const el = document.getElementById("chatTranscript");
if (!el) return;
state.chatFollowing = true;
el.scrollTop = el.scrollHeight;
updateChatJump(el);
},
});
}
/**
* One approval request as a card (C10), the browser's port of
* `ui/chat/ChatApprovalCard.kt`: a shield and the headline, the status line, the
* request's resources newline-joined in monospace (blank entries dropped, at most
* six lines), the amber `RISK REVIEW` panel only while the app shows it, and the
* once/always/reject controls only while the request is actionable. Every server
* string is set with textContent and every node is built by hand.
*/
function renderChatApproval(sessionId, card) {
const node = h("div", {
class: `chat-approval${card.actionable ? " chat-approval-pending" : ""}`,
id: "chatApproval",
"data-request-id": card.requestId,
});
const head = h("div", { class: "chat-approval-head" });
head.append(shieldIcon("chat-approval-shield"));
const titles = h("div", { class: "chat-approval-titles" });
titles.append(h("div", { class: "chat-approval-headline", text: card.headline }));
titles.append(h("div", { class: "chat-approval-status muted", text: card.statusLine }));
head.append(titles);
node.append(head);
if (card.resourceText !== "") {
// The padded frame around a padding-free clamp block: clamping the padded
// element itself lets the seventh line paint into its bottom padding.
const box = h("div", { class: "chat-approval-resources" });
box.append(h("pre", { class: "chat-approval-resources-text", text: card.resourceText }));
node.append(box);
}
if (card.showRisk && card.risk.trim() !== "") {
const risk = h("div", { class: "chat-approval-risk" });
const riskHead = h("div", { class: "chat-approval-risk-head" });
riskHead.append(shieldIcon("chat-approval-risk-shield"));
riskHead.append(h("span", { class: "chat-approval-risk-label", text: RISK_REVIEW_LABEL }));
risk.append(riskHead);
risk.append(h("div", { class: "chat-approval-risk-text", text: card.risk }));
node.append(risk);
}
if (card.actionable) {
const controls = h("div", { class: "chat-approval-controls" });
controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary"));
controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId));
node.append(controls);
}
return node;
}
/**
* The app's amber outlined Shield (`Icons.Outlined.Shield`): an inline SVG stroked
* with `currentColor` so the palette's warn hue actually tints it, unlike the
* colour emoji it replaces. Decorative — the headline carries the meaning.
*/
function shieldIcon(className) {
const NS = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(NS, "svg");
svg.setAttribute("class", className);
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const path = document.createElementNS(NS, "path");
path.setAttribute("d", "M12 3 5 6v5.5c0 4.2 2.8 8.1 7 9.5 4.2-1.4 7-5.3 7-9.5V6l-7-3z");
path.setAttribute("fill", "none");
path.setAttribute("stroke", "currentColor");
path.setAttribute("stroke-width", "1.8");
path.setAttribute("stroke-linejoin", "round");
svg.append(path);
return svg;
}
function approvalControl(label, decision, sessionId, requestId, extraClass = "") {
return h("button", {
class: `chat-approval-control${extraClass ? ` ${extraClass}` : ""}`,
type: "button",
text: label,
onclick: () => answerPermission(sessionId, requestId, decision),
});
}
/**
* The in-flight turn's indicator: a spinner, the phase headline (`Thinking…` /
* `Running a tool…` / `Waiting…`), `· {elapsed}`, then one line per running tool
@@ -6414,7 +6841,8 @@ function refreshChatClock() {
stopChatClock();
chatNow = Date.now();
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
if (state.view === "chat" && thread?.running) {
const awaiting = approvalCard(thread?.permission, thread?.permissionAnswer)?.actionable === true;
if (state.view === "chat" && thread?.running && !awaiting) {
chatClock = setInterval(() => {
chatNow = Date.now();
updateChatIndicator(chatNow);
@@ -6491,7 +6919,13 @@ client.addEventListener("state", (event) => {
// type is ignored.
client.addEventListener("frame", (event) => {
const message = event.detail;
if (!message || message.type !== Protocol.CHAT_EVENT) return;
if (!message) return;
if (message.type === Protocol.CHAT_PERMISSION) {
const permission = message[ChatKeys.PERMISSION];
if (permission) onChatPermission(permission);
return;
}
if (message.type !== Protocol.CHAT_EVENT) return;
const frame = message[ChatKeys.EVENT];
if (frame) onChatEvent(frame);
onChatFrame(message);
+353 -6
View File
@@ -302,6 +302,21 @@ export function toolDetail(part) {
return null;
}
/**
* The one-line command a background process is running, collapsed to a single
* line and elided past [TOOL_DETAIL_MAX_LENGTH] like a tool call's detail, so a
* long command line cannot flood the bar. A shell that reported no command reads
* as a generic `background process` rather than a blank line (ChatFormat.kt
* shellCommandSummary, which shares the tool-detail regex and bound).
*/
export function shellCommandSummary(command) {
const text = str(command).trim().replace(/\s+/g, " ");
if (text === "") return "background process";
return text.length <= TOOL_DETAIL_MAX_LENGTH
? text
: text.slice(0, TOOL_DETAIL_MAX_LENGTH - 1).trimEnd() + "…";
}
/**
* The INPUT section of a tool call: pretty-printed JSON once the arguments are an
* object/array, the raw partial-JSON string while still streaming, or empty when
@@ -795,6 +810,141 @@ export function chatStreamState(connectionKind, subscribed) {
return { tone: "not-live", label: STREAM_OFFLINE };
}
// ---------------------------------------------------------------------------
// Background shells (C11: ChatTranscript.kt BackgroundProcessBar, ChatStore.kt
// applyShell/shellsLoaded, ChatFormat.kt runningBackgroundShells/shellCommandSummary)
// ---------------------------------------------------------------------------
/**
* ChatShell.Status values (internal/protocol/chat.go). A running shell is one
* whose command has started and not yet exited; `exited` is final.
*/
export const SHELL_RUNNING = "running";
export const SHELL_EXITED = "exited";
/**
* Per-session in-memory observation bound (ChatStore.OBSERVED_SHELL_LIMIT): the
* retained shell tail a selected task can settle against. This is not task
* history, only what this client itself observed.
*/
export const OBSERVED_SHELL_LIMIT = 16;
/**
* How many running-task rows the bar draws before the list scrolls instead of
* growing (ChatTranscript.BACKGROUND_TASK_VISIBLE_ROWS).
*/
export const BACKGROUND_TASK_VISIBLE_ROWS = 3;
/** The bar's heading; its count line is `{n} running`. */
export const BACKGROUND_TASKS_TITLE = "Background tasks";
export function backgroundTasksRunningLabel(count) {
return `${count} running`;
}
/** A row's own words (ChatTranscript.BackgroundProcessLine). */
export const SHELL_ROW_LABEL = "Running";
export const SHELL_DETAILS_LABEL = "Details";
/**
* The detail pane's exact wording, verbatim from
* ChatTranscript.BackgroundProcessDetail. Kept as one frozen map so the pane and
* its unit test share one string instead of the copy drifting.
*/
export const SHELL_OUTPUT_LABELS = Object.freeze({
COMMAND: "Command",
UNAVAILABLE: "Unavailable",
TASK_IDENTITY: "Task identity",
STATUS_RUNNING: "Status: running",
OUTPUT_UNAVAILABLE: "Output unavailable for this task.",
NO_OUTPUT: "No output yet.",
OUTPUT: "Output",
OUTPUT_BOUNDED: "Output is bounded to 64 KiB.",
RETRY: "Retry",
REFRESH: "Refresh",
});
/**
* The background processes still running for a session, in the order they
* started, from the shells the server reported and the session retains. A shell
* that has exited is never listed — that is what clears the bar — and the set is
* independent of the turn, because a background process outlives the tool call
* (and often the turn) that started it. Mirrors ChatFormat.runningBackgroundShells:
* only a non-blank id with status `running` is a task, and the list is never
* truncated here (the visible-row cap is a view concern).
*/
export function runningBackgroundShells(shells) {
return (shells ?? []).filter(
(shell) => !isBlank(shell?.id) && str(shell?.status) === SHELL_RUNNING,
);
}
/**
* Folds one shell frame (or a snapshot entry) into the retained shells, keyed by
* id and kept in observation order. A blank incoming command keeps the command
* already learned, so a later frame that omits it never blanks the row, and the
* list is trimmed to the last [OBSERVED_SHELL_LIMIT] entries (ChatStore.applyShell).
*/
export function mergeShellFrame(shells, shell) {
const id = str(shell?.id);
if (shell == null || isBlank(id)) return shells ?? [];
const list = (shells ?? []).slice();
const index = list.findIndex((candidate) => str(candidate?.id) === id);
const prior = index >= 0 ? list[index] : null;
const merged = {
...shell,
id,
command: isBlank(shell?.command) ? str(prior?.command) : shell.command,
};
if (index >= 0) list[index] = merged;
else list.push(merged);
return list.slice(-OBSERVED_SHELL_LIMIT);
}
/**
* Replaces the retained shells with the authoritative running snapshot while
* keeping only exits this client itself observed, capped like every other shell
* list (ChatStore.shellsLoaded). A shell the server no longer lists and that this
* client never saw exit simply drops out.
*/
export function shellsLoaded(shells, running) {
const byId = new Map();
for (const shell of shells ?? []) {
if (!isBlank(shell?.id) && str(shell?.status) === SHELL_EXITED) byId.set(shell.id, shell);
}
for (const shell of running ?? []) {
if (isBlank(shell?.id)) continue;
// Map.set keeps the first-insertion position and replaces the value, exactly
// like Kotlin's `observedExits + live` LinkedHashMap merge.
byId.set(shell.id, shell);
}
return [...byId.values()].slice(-OBSERVED_SHELL_LIMIT);
}
/** The five shapes a selected task's output area can take. */
export const SHELL_OUTPUT_LOADING = "loading";
export const SHELL_OUTPUT_ERROR = "error";
export const SHELL_OUTPUT_UNAVAILABLE = "unavailable";
export const SHELL_OUTPUT_EMPTY = "empty";
export const SHELL_OUTPUT_READY = "output";
/**
* Which branch the detail pane's output area shows for a selected task's
* [output] state, or null when there is nothing to show yet — the same decision
* order as ChatTranscript.BackgroundProcessDetail's `when` (loading, then error,
* then the server's `unavailable`, then an empty page, then a readable page), so
* the pane and its unit test share one derivation.
*/
export function shellOutputState(output) {
if (output == null) return null;
if (output.loading) return SHELL_OUTPUT_LOADING;
if (str(output.error) !== "") return SHELL_OUTPUT_ERROR;
const page = output.page ?? null;
if (page == null) return null;
if (page.unavailable === true) return SHELL_OUTPUT_UNAVAILABLE;
if (str(page.output) === "") return SHELL_OUTPUT_EMPTY;
return SHELL_OUTPUT_READY;
}
/**
* The shape an open conversation holds. The first six fields are the ones a
* history page fills; the rest is the live stream (see `ChatThread` in
@@ -815,6 +965,20 @@ export function newChatThread(sessionId = "") {
toolStartedAt: {},
lastDeltaAt: 0,
queued: false,
// C10: the session's current permission request (the last `chat_permission`
// frame the server pushed) and the operator's local answer to it
// (`once`/`always`/`reject`, or blank). The approval card and its controls
// derive from the two (see `approvalCard`).
permission: null,
permissionAnswer: "",
// The reason a refused `chat_reply` left on the thread's error line, kept
// apart from any other error so a later accepted answer clears only this one.
permissionError: "",
// The background shells this session has observed (C11), in observation
// order, the selected task and its bounded output pane.
shells: [],
selectedShellId: null,
shellOutput: null,
};
}
@@ -841,6 +1005,19 @@ export function setThreadRunning(thread, running, now) {
return settledThread({ ...thread });
}
/**
* The reconnect repair for one thread (C5/C11): the settled form plus the shell
* observations dropped — a shell's exit may have been swallowed by the gap, so
* the retained shells are forgotten and re-learned from the re-subscribe's
* `chat_shells` snapshot. This is deliberately separate from [settledThread],
* which the step-ended frame also uses: a turn ending must never clear a
* background process that outlives it (ChatStore.streamResumed drops shells;
* ChatStore.setRunning does not).
*/
export function resumedThread(thread) {
return { ...settledThread(thread), shells: [], selectedShellId: null, shellOutput: null };
}
/**
* Non-negative elapsed time of an in-flight turn at [nowMillis], or 0 once it has
* settled. Pure, so the running indicator and its unit test share the derivation.
@@ -966,8 +1143,8 @@ export function threadPhase(thread, nowMillis) {
* thread. Any frame clears `queued` (the turn moved on); `user` echoes another
* client's prompt once (never this client's own), `text`/`reasoning` append to the
* part their kind started, `tool` merges field by field, `step` drives the running
* flag, and `shell`/`usage` are recognised but not folded here (C11 owns shells
* and the turn totals are not shown). The message that a delta or tool frame
* flag, and `shell` folds one background process into the retained set without
* ever marking the turn running (C11). The message that a delta or tool frame
* targets is created on first sight, so a live turn never gains a second bubble.
*/
export function applyChatEvent(thread, frame, now = Date.now()) {
@@ -984,9 +1161,12 @@ export function applyChatEvent(thread, frame, now = Date.now()) {
return applyTool(current, frame, now);
case EVENT_STEP:
return setThreadRunning(current, str(frame?.step?.status) !== STEP_ENDED, now);
// `shell` is C11's (it never marks the turn running) and `usage` is not
// folded; both still clear `queued`, which happened above.
// A shell frame only folds its shell into the retained set: it NEVER marks
// the thread running, because a background process is not the turn — a shell
// that outlives the turn keeps showing after the turn's own indicator is gone.
case EVENT_SHELL:
return { ...current, shells: mergeShellFrame(current.shells, frame?.shell) };
// `usage` is recognised but not folded; it still cleared `queued` above.
case EVENT_USAGE:
default:
return current;
@@ -1085,10 +1265,12 @@ function upsertParts(thread, frame, now, deltaArrivedAt, upsert) {
* The reconnect/resync replacement: the newest history page is authoritative, so
* the whole turn is replaced (no stale held message survives), the cursor and
* `hasMore` are replaced from the page, and any in-flight state is settled —
* every frame that was feeding a running turn is gone.
* every frame that was feeding a running turn is gone. The retained shells are
* dropped too (the reconnect re-fetches `chat_shells`), exactly like the Android
* `streamResumed` path.
*/
export function historyResync(thread, page) {
const settled = settledThread(thread ?? newChatThread());
const settled = resumedThread(thread ?? newChatThread());
return {
...settled,
messages: (page?.messages ?? []).slice(),
@@ -1471,3 +1653,168 @@ export function chatCommandEffect(input, thread) {
return { kind: "report", text: `“/${command.name}” is not a command.` };
}
}
// ---------------------------------------------------------------------------
// Permission approvals (C10) — ui/chat/ChatFormat.kt ApprovalCard/approvalCard/
// permissionRiskText/decisionLabel and the ChatProtocol.DECISION_* values
// ---------------------------------------------------------------------------
/** The three decision values the server accepts (ChatProtocol.DECISION_*). */
export const DECISION_ONCE = "once";
export const DECISION_ALWAYS = "always";
export const DECISION_REJECT = "reject";
/** Every acceptable decision, in the Android client's own order. */
export const DECISIONS = Object.freeze([DECISION_ONCE, DECISION_ALWAYS, DECISION_REJECT]);
/** A decision's human label (ChatFormat.kt decisionLabel), blank-safe. */
export const DECISION_LABEL_ONCE = "Allowed once";
export const DECISION_LABEL_ALWAYS = "Always allowed";
export const DECISION_LABEL_REJECT = "Rejected";
export const DECISION_LABEL_RESOLVED = "Resolved";
export function decisionLabel(decision) {
switch (str(decision)) {
case DECISION_ONCE:
return DECISION_LABEL_ONCE;
case DECISION_ALWAYS:
return DECISION_LABEL_ALWAYS;
case DECISION_REJECT:
return DECISION_LABEL_REJECT;
default:
return DECISION_LABEL_RESOLVED;
}
}
/** How one approval request stands (ChatFormat.kt ApprovalState). */
export const APPROVAL_PENDING = "pending";
export const APPROVAL_ANSWERED = "answered";
export const APPROVAL_RESOLVED = "resolved";
/** The card's fixed wording (ChatFormat.kt ApprovalCard and ApprovalCardItem). */
export const APPROVAL_BLANK_ACTION = "tool call";
export const APPROVAL_HEADLINE_RESOLVED = "Already resolved";
export const APPROVAL_STATUS_PENDING = "Waiting for your response";
export const APPROVAL_STATUS_ANSWERED = "Waiting for the agent to continue…";
export const APPROVAL_STATUS_RESOLVED = "Another client already answered this request.";
export const RISK_REVIEW_LABEL = "RISK REVIEW";
export const WAITING_FOR_APPROVAL_LABEL = "Waiting for your approval";
/** The once/always/reject control labels (ChatApprovalCard.kt), in their order. */
export const APPROVAL_CONTROL_ONCE = "Allow once";
export const APPROVAL_CONTROL_ALWAYS = "Always allow";
export const APPROVAL_CONTROL_REJECT = "Reject";
/** How many resource lines the card shows before the remainder is elided. */
export const MAX_APPROVAL_RESOURCE_LINES = 6;
/**
* The text in the amber risk-review box (ChatFormat.kt permissionRiskText): the
* server's own summary when it carries one, otherwise a neutral sentence naming
* the action (or `a tool call`) so the box is never blank.
*/
export function permissionRiskText(permission) {
const message = str(permission?.message);
if (!isBlank(message)) return message;
const what = isBlank(permission?.action) ? "a tool call" : str(permission.action);
return `The agent is asking to run ${what}; review the request before allowing.`;
}
/**
* The request's resources with the blanks dropped, in the server's own order
* (ChatFormat.kt ApprovalCard.resources). No entry is discarded here: the line
* cap belongs to the joined text, so an embedded newline counts as its own line
* instead of hiding a later resource.
*/
export function approvalResources(permission) {
return (permission?.resources ?? [])
.filter((resource) => !isBlank(resource))
.map((resource) => str(resource));
}
/**
* The resource block as the card renders it (ChatFormat.kt
* `resources.joinToString("\n")` with `maxLines = 6, overflow = Ellipsis`): the
* non-blank resources joined by newlines and capped at
* [MAX_APPROVAL_RESOURCE_LINES] lines, an embedded newline counting as a line,
* with an ellipsis on the last kept line when the rest was dropped. The rendered
* box clamps to the same six lines (styles.css), so a single long resource that
* wraps is elided too rather than spilling onto a seventh line.
*/
export function approvalResourceText(permission) {
const lines = approvalResources(permission).flatMap((resource) => resource.split("\n"));
if (lines.length <= MAX_APPROVAL_RESOURCE_LINES) return lines.join("\n");
const kept = lines.slice(0, MAX_APPROVAL_RESOURCE_LINES);
kept[kept.length - 1] = `${kept[kept.length - 1]}\u2026`;
return kept.join("\n");
}
/** The card headline (ChatFormat.kt ApprovalCard.headline). */
export function approvalHeadline(state, decision, action) {
if (state === APPROVAL_PENDING) {
return `Approve ${isBlank(action) ? APPROVAL_BLANK_ACTION : str(action)}`;
}
if (state === APPROVAL_ANSWERED) return decisionLabel(decision);
return isBlank(decision) ? APPROVAL_HEADLINE_RESOLVED : decisionLabel(decision);
}
/** The card's one-line status (ChatFormat.kt ApprovalCard.statusLine). */
export function approvalStatusLine(state, note) {
if (state === APPROVAL_PENDING) return APPROVAL_STATUS_PENDING;
if (state === APPROVAL_ANSWERED) return APPROVAL_STATUS_ANSWERED;
return isBlank(note) ? APPROVAL_STATUS_RESOLVED : str(note);
}
/**
* What the conversation renders for one permission request (ChatFormat.kt
* approvalCard): derived purely from the server's [permission] frame plus the
* operator's local [answer], so a server resolution always outranks a local
* answer and a stale tap can never reopen controls for a request already done.
* Returns null when there is no request to show (a null frame or a blank
* request id). `actionable` is true only while the request is open; `showRisk`
* mirrors the app (open, or answered with a rejection).
*/
export function approvalCard(permission, answer) {
if (permission == null || isBlank(permission.request_id)) return null;
const resolvedByServer = permission.resolved === true || !isBlank(permission.decision);
const state = resolvedByServer
? APPROVAL_RESOLVED
: !isBlank(answer)
? APPROVAL_ANSWERED
: APPROVAL_PENDING;
const decision = resolvedByServer ? str(permission.decision) : str(answer);
const note = resolvedByServer ? str(permission.message) : "";
return {
requestId: str(permission.request_id),
action: str(permission.action),
resources: approvalResources(permission),
resourceText: approvalResourceText(permission),
risk: permissionRiskText(permission),
state,
decision,
note,
actionable: state === APPROVAL_PENDING,
showRisk:
state === APPROVAL_PENDING || (state === APPROVAL_ANSWERED && decision === DECISION_REJECT),
headline: approvalHeadline(state, decision, str(permission.action)),
statusLine: approvalStatusLine(state, note),
};
}
/**
* Folds one pushed `chat_permission` frame into [thread] (ChatStore.permission):
* a frame for a *new* request replaces any settled card and clears the local
* answer, while a frame for the *same* request (for example a resolved re-push)
* keeps the answer the operator already gave. The frame itself is stored; the
* card derives from it, so a server resolution always wins.
*/
export function applyChatPermission(thread, frame) {
const current = thread ?? newChatThread(str(frame?.session_id));
const requestId = str(frame?.request_id);
const sameRequest = requestId !== "" && str(current.permission?.request_id) === requestId;
return {
...current,
permission: frame ?? null,
permissionAnswer: sameRequest ? str(current.permissionAnswer) : "",
};
}
+22
View File
@@ -64,6 +64,17 @@ export const Protocol = Object.freeze({
CHAT_PROMPT: "chat_prompt",
CHAT_INTERRUPT: "chat_interrupt",
CHAT_CREATE: "chat_create",
// The approval card (C10): the server pushes `chat_permission` frames (one
// pending request, later re-pushed with the resolution) and the phone answers
// with `chat_reply` (internal/protocol/chat.go ChatPermission/ChatReply).
CHAT_PERMISSION: "chat_permission",
CHAT_REPLY: "chat_reply",
// The background shells a chat session owns (C11). `chat_shells` lists the
// session's currently verified shells (body: `chat_query`); `chat_shell_output`
// reads a bounded, lazy output page from one of them (body:
// `chat_shell_output_query`). Mirrors internal/protocol/chat.go and Message.kt.
CHAT_SHELLS: "chat_shells",
CHAT_SHELL_OUTPUT: "chat_shell_output",
SUCCESS_END: "#success",
FAILURE_END: "#failure",
@@ -92,6 +103,17 @@ export const ChatKeys = Object.freeze({
PROMPT: "chat_prompt",
CREATE: "chat_create",
QUEUED: "chat_queued",
// C10: the pushed approval frame (`chat_permission`) and the answer body
// (`chat_reply`), both distinct Message fields in internal/protocol/message.go.
PERMISSION: "chat_permission",
REPLY: "chat_reply",
// The shell commands (C11, internal/protocol/message.go). `chat_shells` carries
// its body in `chat_query` (like the other session-scoped commands) and replies
// in `chat_shells`; `chat_shell_output` carries `chat_shell_output_query`
// ({session_id,shell_id,cursor,limit}) and replies in `chat_shell_output`.
SHELLS: "chat_shells",
SHELL_OUTPUT: "chat_shell_output",
SHELL_OUTPUT_QUERY: "chat_shell_output_query",
});
/**
+98
View File
@@ -3,10 +3,26 @@
// divergent field names. Mirrors android/.../data/PipelinesRepository.kt.
import { ChatKeys, Protocol } from "./protocol.js";
import { ProtocolError } from "./client.js";
import { DECISIONS } from "./chat.js";
/** The server default history page the app asks for (CHAT_HISTORY_LIMIT, 200). */
export const CHAT_HISTORY_LIMIT = 200;
/**
* The label this browser client records with a permission answer, so every other
* watching client can see which device resolved the request (the Android analogue
* is the device name). It is always sent; the server records it with the outcome.
*/
export const WEB_CHAT_CLIENT = "Web";
/**
* The largest shell-output page the server accepts (ChatShellOutputLimit,
* 64 KiB). The browser always reads from the page's start and never sends more
* than this, so a background task's output can never grow unbounded on the
* client.
*/
export const SHELL_OUTPUT_LIMIT = 64 << 10;
export class PipelinesRepository {
#client;
@@ -240,6 +256,57 @@ export class PipelinesRepository {
});
}
/**
* Lists the currently verified shells this operator chat session owns (C11),
* so the conversation can show a background-tasks bar while one is running.
* The body is the session-scoped `chat_query` (like chat_messages); the reply
* is `chat_shells`, and an older server that returns none answers with an empty
* list. A blank session id is refused here, exactly like
* PipelinesRepository.chatShells.
*/
async chatShells(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
const response = await this.#client.call({
type: Protocol.CHAT_SHELLS,
[ChatKeys.QUERY]: { session_id: sessionId },
});
return response[ChatKeys.SHELLS] ?? [];
}
/**
* Reads one bounded output page from a verified shell (C11), mirroring
* PipelinesRepository.chatShellOutput. The body is exactly
* `chat_shell_output_query` — {session_id, shell_id, cursor, limit}, **not** the
* `chat_query` the other session commands use — with the cursor always sent so
* a refresh rereads from the page's start rather than appending. A blank
* session/shell, an out-of-bounds cursor/limit or a reply with no page is
* refused with the same reason the Android client uses.
*/
async chatShellOutput(sessionId, shellId, { cursor = 0, limit = SHELL_OUTPUT_LIMIT } = {}) {
if (!String(sessionId ?? "").trim() || !String(shellId ?? "").trim()) {
throw new ProtocolError("Select a shell first.");
}
if (!(cursor >= 0) || !(limit > 0) || limit > SHELL_OUTPUT_LIMIT) {
throw new ProtocolError("Shell output bounds are invalid.");
}
const response = await this.#client.call({
type: Protocol.CHAT_SHELL_OUTPUT,
[ChatKeys.SHELL_OUTPUT_QUERY]: {
session_id: sessionId,
shell_id: shellId,
cursor,
limit,
},
});
const page = response[ChatKeys.SHELL_OUTPUT];
if (!page) {
throw new ProtocolError("The server returned no shell output page.");
}
return page;
}
/**
* Finishes a session and records it closed on the server (nothing is
* deleted). The reply echoes the updated session (`chat_session`) and the
@@ -334,6 +401,37 @@ export class PipelinesRepository {
}
return session;
}
/**
* Answers one pending permission request (C10). Sends exactly
* `{type:'chat_reply', chat_reply:{session_id,request_id,decision,client}}` —
* `message` rides only when non-blank (mirrors ChatReplyRequest's omitempty).
* A blank session/request/decision, or a decision outside `once`/`always`/
* `reject`, is refused here before anything is sent, so an unaccepted decision
* can never reach the server. The server pushes the shared resolution back to
* every watching client once the first answer is recorded.
*/
async chatReply(sessionId, requestId, decision, { message = "", client = WEB_CHAT_CLIENT } = {}) {
const session = String(sessionId ?? "").trim();
const request = String(requestId ?? "").trim();
const chosen = String(decision ?? "").trim();
if (session === "") throw new ProtocolError("Select a chat session first.");
if (request === "") {
throw new ProtocolError("This approval request is no longer available.");
}
if (!DECISIONS.includes(chosen)) {
throw new ProtocolError("Choose once, always or reject.");
}
const body = {
session_id: session,
request_id: request,
decision: chosen,
client: String(client ?? "").trim() || WEB_CHAT_CLIENT,
};
const trimmed = String(message ?? "").trim();
if (trimmed !== "") body.message = trimmed;
await this.#client.call({ type: Protocol.CHAT_REPLY, [ChatKeys.REPLY]: body });
}
}
/**