Merge branch 'main' into web-chat-approvals

Resolve C10 vs C11 in the shared shell:
- keep both send hooks in the smoke's WebSocket shim (recording +
  scripted replies + synthetic approval acknowledgement) instead of the
  second assignment overwriting the first;
- close the .chat-approval CSS rule so the C11 background-task rules are
  not swallowed by it (the list lost its 3-row cap and scrolling);
- assert the folding invariant directly (no adjacent agent bubbles)
  instead of 'agent bubbles <= user prompts', which the growing operator
  session now legitimately breaks;
- exercise the resource clamp by scroll overflow instead of a clone
  measurement that the clamped frame makes unreliable.
This commit is contained in:
2026-10-19 11:26:26 +01:00
8 changed files with 1326 additions and 46 deletions
+247 -6
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 {
@@ -207,6 +207,7 @@ import {
retryRequestKey,
} from "./actions.js";
import {
BACKGROUND_TASKS_TITLE,
CHAT_ATTACH_LABEL,
CHAT_COMMAND_GLYPH,
CHAT_COMPOSER_PLACEHOLDER,
@@ -241,12 +242,21 @@ import {
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,
@@ -268,11 +278,14 @@ import {
groupSessionsByDirectory,
historyResync,
mergeHistoryPage,
mergeShellFrame,
newChatThread,
parseChatInput,
queuedAfterFrame,
reasoningLabel,
resumedThread,
runningAfterFrame,
runningBackgroundShells,
runningToolElapsedMillis,
sessionActivity,
sessionActivityBadge,
@@ -282,6 +295,9 @@ import {
sessionTitle,
sessionWorkLabel,
settledThread,
shellCommandSummary,
shellOutputState,
shellsLoaded,
formatToolDuration,
threadElapsedMillis,
threadPhase,
@@ -3611,6 +3627,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);
}
@@ -3645,13 +3664,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));
}
}
}
@@ -3732,19 +3756,110 @@ async function answerPermission(sessionId, requestId, decision) {
* 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();
}
@@ -4488,6 +4603,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 }));
@@ -4538,6 +4659,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