web: live chat transcript over chat_event (C5)

This commit is contained in:
2026-10-19 07:01:00 +01:00
parent 7df4891f14
commit 7b578498ae
12 changed files with 1252 additions and 23 deletions
+263 -17
View File
@@ -3,7 +3,7 @@
// that came from the server is set with textContent, never innerHTML.
import { PipelinesClient } from "./client.js";
import { PipelinesRepository } from "./repository.js";
import { PROTOCOL_VERSION } from "./protocol.js";
import { PROTOCOL_VERSION, Protocol, ChatKeys } from "./protocol.js";
import { validateServerUrl, resolveArtifactUrl } from "./serverUrl.js";
import {
ForegroundAction,
@@ -216,6 +216,7 @@ import {
LOAD_OLDER_ACTION,
REOPEN_ACTION,
SELECT_CHAT_HINT,
applyChatEvent,
chatBottomDistancePx,
chatFirstScroll,
chatFollowsAt,
@@ -223,11 +224,14 @@ import {
chatNoMatchMessage,
chatOpensAtNewest,
chatShowJumpToLatest,
chatStreamState,
closeChatConfirmation,
directoryLabel,
filterSessions,
groupSessionsByDirectory,
historyResync,
mergeHistoryPage,
newChatThread,
reasoningLabel,
runningToolElapsedMillis,
sessionActivity,
@@ -237,16 +241,26 @@ import {
sessionStatusLabel,
sessionTitle,
sessionWorkLabel,
settledThread,
formatToolDuration,
threadElapsedMillis,
threadPhase,
threadRunningTools,
threadToolElapsedMillis,
TURN_PHASE_WAITING,
toolCallCount,
toolCallRow,
toolCallsAnnouncement,
toolCallsLabel,
toolDetail,
toolFailed,
toolLabel,
toolLongRunning,
toolRunning,
toolsRunning,
transcriptRows,
turnElapsedMillis,
turnPhaseLabel,
} from "./chat.js";
import { codeBlockLabel, parseInline, parseMarkdown } from "./markdown.js";
@@ -404,6 +418,12 @@ const state = {
// report for a refused close/reopen.
chatClose: null,
chatBusy: false,
// C5: the session ids this connection currently has subscribed to their shared
// live stream. The server detaches a subscription when the connection closes
// (there is no chat_unsubscribe), so this is cleared on every socket drop and
// re-established for the open chat on reconnect. A refused subscription simply
// never joins the set, so the badge reads "not live" honestly.
chatSubscriptions: new Set(),
};
let runPoll = null;
@@ -421,6 +441,12 @@ let listNow = Date.now();
let detailClock = null;
let detailNow = Date.now();
// The chat running indicator's own live clock (C5): it ticks once a second only
// while the open conversation has a turn in flight, updating just the indicator
// in place (never a full re-render), so the transcript's scroll is not disturbed.
let chatClock = null;
let chatNow = Date.now();
// ---------------------------------------------------------------------------
// DOM helpers
// ---------------------------------------------------------------------------
@@ -882,8 +908,10 @@ function renderContent() {
afterChatRender();
stopListClock();
stopDetailClock();
refreshChatClock();
return;
}
stopChatClock();
if (state.view === "runs") {
refreshListClock();
refreshDetailClock();
@@ -1556,7 +1584,7 @@ function renderRunToolbar() {
function renderLiveBadge(info) {
return h(
"span",
{ class: `live-badge live-${info.tone}`, title: "Live run stream" },
{ class: `live-badge live-${info.tone}`, title: info.title ?? "Live run stream" },
h("span", { class: "live-dot", "aria-hidden": "true" }),
h("span", { class: "live-word", text: info.label }),
);
@@ -3279,7 +3307,7 @@ async function loadChatSessions(force = false) {
renderContent();
}
/** Open a session: select it and load its newest history page. */
/** Open a session: select it, subscribe its stream and load its newest history page. */
async function openChatSession(id) {
if (state.chatActiveId === id && state.chatThreads.get(id)?.loaded) return;
// Remember where the operator left the conversation being closed.
@@ -3293,23 +3321,94 @@ async function openChatSession(id) {
state.chatToolRows = new Set();
const existing = state.chatThreads.get(id);
state.chatThreads.set(id, {
messages: existing?.messages ?? [],
nextCursor: existing?.nextCursor ?? "",
hasMore: existing?.hasMore ?? false,
...newChatThread(id),
...(existing ?? {}),
loaded: false,
loading: true,
error: "",
});
renderContent();
// 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);
await loadChatHistory(id);
}
/**
* Attach one session's shared live stream (C5): `chat_subscribe` with the session
* id as the body. Idempotent per connection — a session already subscribed is not
* asked for again. A refusal (an older server that does not know the command, or
* any other error) leaves history usable and the live badge `not live`.
*/
async function subscribeChatSession(id) {
if (!id || state.connection.kind !== "connected") return;
if (state.chatSubscriptions.has(id)) return;
try {
await repo.subscribeChat(id);
state.chatSubscriptions = new Set(state.chatSubscriptions).add(id);
} catch {
// The subscription is not live; nothing else changes. The badge says so.
}
renderContent();
}
/** Drop the per-connection subscriptions (the server detaches them on close). */
function clearChatSubscriptions() {
if (state.chatSubscriptions.size > 0) state.chatSubscriptions = new Set();
}
/**
* 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.
*/
function settleChatThreads() {
for (const [id, thread] of state.chatThreads) {
if (thread?.running || thread?.queued) state.chatThreads.set(id, settledThread(thread));
}
}
/**
* Fold one pushed `chat_event` frame into its conversation. Only a conversation
* this client has open is folded (a frame for a session nobody opened is
* ignored); the server only pushes frames for sessions this connection subscribed
* to, so this is a no-op in practice until a chat is opened.
*/
function onChatEvent(frame) {
const sessionId = String(frame?.session_id ?? "").trim();
if (!sessionId || !state.chatThreads.has(sessionId)) return;
const thread = state.chatThreads.get(sessionId);
state.chatThreads.set(sessionId, applyChatEvent(thread, frame, Date.now()));
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.
*/
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));
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.
}
renderContent();
}
/** Load (or reload) a session's newest history page and merge it in. */
async function loadChatHistory(id) {
const previous = state.chatThreads.get(id) ?? { messages: [] };
const previous = state.chatThreads.get(id) ?? newChatThread(id);
try {
const page = await repo.chatHistory(id);
state.chatThreads.set(id, mergeHistoryPage(previous, page, { older: false }));
state.chatThreads.set(id, { ...previous, ...mergeHistoryPage(previous, page, { older: false }) });
} catch (error) {
state.chatThreads.set(id, {
...previous,
@@ -3338,7 +3437,7 @@ async function loadOlderChatHistory(id) {
try {
const page = await repo.chatHistory(id, { cursor: thread.nextCursor });
const current = state.chatThreads.get(id) ?? thread;
state.chatThreads.set(id, mergeHistoryPage(current, page, { older: true }));
state.chatThreads.set(id, { ...current, ...mergeHistoryPage(current, page, { older: true }) });
} catch (error) {
state.chatThreads.set(id, {
...(state.chatThreads.get(id) ?? thread),
@@ -3371,6 +3470,15 @@ async function acceptChatClose(session) {
try {
const { session: updated } = await repo.closeChat(session.id);
applyChatSessionUpdate(session.id, updated, true);
// A closed chat's turn was stopped on the server: settle its conversation and
// stop treating it as a live subscription. Nothing is deleted and it can be
// reopened from the list.
const thread = state.chatThreads.get(session.id);
if (thread) state.chatThreads.set(session.id, settledThread(thread));
if (state.chatSubscriptions.has(session.id)) {
state.chatSubscriptions = new Set(state.chatSubscriptions);
state.chatSubscriptions.delete(session.id);
}
} catch (error) {
state.actionError = describeError(error);
}
@@ -3622,6 +3730,14 @@ function renderChatConversation() {
text: sessionStatusLabel(thread?.running === true, session?.closed === true),
}),
);
// The live-stream badge (C5): live while this session is subscribed, the same
// words as the run badge (`live` / `reconnecting` / `not live`).
context.append(
renderLiveBadge({
...chatStreamState(state.connection.kind, state.chatSubscriptions.has(state.chatActiveId)),
title: "Live chat stream",
}),
);
const contextMeta = [session?.directory, session?.model]
.map((value) => String(value ?? "").trim())
.filter((value) => value !== "")
@@ -3644,10 +3760,11 @@ function renderChatConversation() {
pane.append(empty);
} else {
const rows = transcriptRows(thread?.messages ?? []);
if (rows.length === 0) {
const running = thread?.running === true;
if (rows.length === 0 && !running) {
pane.append(h("div", { class: "chat-transcript-empty muted", text: CONVERSATION_EMPTY }));
} else {
pane.append(renderChatTranscript(state.chatActiveId, rows));
pane.append(renderChatTranscript(state.chatActiveId, rows, { running, now: Date.now() }));
}
if (thread?.error && thread?.loaded) {
pane.append(h("div", { class: "chat-transcript-error", text: thread.error }));
@@ -3675,17 +3792,30 @@ 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) {
function renderChatTranscript(sessionId, rows, { running = false, now = Date.now() } = {}) {
const wrap = h("div", { class: "chat-transcript-wrap" });
const transcript = h("div", {
class: "chat-transcript",
id: "chatTranscript",
"data-session": sessionId,
});
for (const row of rows) {
const thread = state.chatThreads.get(sessionId) ?? null;
let lastAgent = -1;
rows.forEach((row, index) => {
if (row.kind === "agent") lastAgent = index;
});
rows.forEach((row, index) => {
if (row.kind === "user") transcript.append(renderChatUserMessage(row.message));
else transcript.append(renderChatAgentTurn(row.turn));
}
else {
const streaming = running && index === lastAgent;
const elapsed = (part) => threadToolElapsedMillis(thread, part, now);
transcript.append(renderChatAgentTurn(row.turn, streaming, elapsed));
}
});
// The running indicator sits under the transcript, after the last agent turn:
// a spinner, the phase headline, the turn's elapsed, then one line per running
// tool (a call over 60 s is tinted and marked `· long`).
if (running && thread) transcript.append(renderChatRunningIndicator(thread, now));
wrap.append(transcript);
wrap.append(
h("button", {
@@ -3705,6 +3835,53 @@ function renderChatTranscript(sessionId, rows) {
return wrap;
}
/**
* The in-flight turn's indicator: a spinner, the phase headline (`Thinking…` /
* `Running a tool…` / `Waiting…`), `· {elapsed}`, then one line per running tool
* with its own elapsed. A call that has passed [TOOL_LONG_RUNNING_MILLIS] is
* tinted and marked `· long` — the same threshold the tool chip uses.
*/
function renderChatRunningIndicator(thread, now) {
const wrap = h("div", { class: "chat-running", id: "chatRunning" });
const head = h("div", { class: "chat-running-head" });
head.append(h("span", { class: "spinner chat-running-spinner", "aria-hidden": "true" }));
head.append(
h("span", {
class: "chat-running-label",
text: turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING),
}),
);
head.append(
h("span", {
class: "chat-running-elapsed",
text: `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`,
}),
);
wrap.append(head);
for (const part of threadRunningTools(thread.messages)) {
wrap.append(renderChatRunningTool(thread, part, now));
}
return wrap;
}
function renderChatRunningTool(thread, part, now) {
const line = h("div", { class: "chat-running-tool", "data-part-id": String(part?.id ?? "") });
const name = toolLabel(part);
const detail = toolDetail(part);
line.append(h("span", { class: "chat-running-tool-text", text: detail == null ? name : `${name} ${detail}` }));
line.append(
h("span", {
class: "chat-running-tool-elapsed muted",
text: formatToolDuration(threadToolElapsedMillis(thread, part, now)),
}),
);
if (toolLongRunning(threadToolElapsedMillis(thread, part, now))) {
line.classList.add("chat-running-tool-long");
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
}
return line;
}
/** One operator turn, right-aligned, carrying its sender label when present. */
function renderChatUserMessage(message) {
const turn = h("div", { class: "chat-turn chat-turn-user" });
@@ -3722,13 +3899,13 @@ function renderChatUserMessage(message) {
}
/** One folded agent reply, left-aligned: reasoning, tool-call chip, answer. */
function renderChatAgentTurn(turn, streaming = false) {
function renderChatAgentTurn(turn, streaming = false, elapsedMillis = () => 0) {
const wrap = h("div", { class: "chat-turn chat-turn-agent" });
const bubble = h("div", { class: "chat-bubble agent-bubble" });
const steps = turn.reasoningSteps;
if (steps.length > 0) bubble.append(renderChatReasoning(turn, streaming));
if (turn.tools.length > 0) {
const tools = renderChatToolCalls(turn, { streaming });
const tools = renderChatToolCalls(turn, { streaming, elapsedMillis });
if (tools) bubble.append(tools);
}
if (turn.answer.trim() !== "") bubble.append(renderMarkdown(turn.answer));
@@ -4875,6 +5052,53 @@ function stopDetailClock() {
}
}
/**
* (Re)start the chat indicator's clock: it ticks once a second only while the
* open conversation has a turn in flight, updating the phase, the elapsed and the
* per-tool `· long` marks in place (never a full re-render).
*/
function refreshChatClock() {
stopChatClock();
chatNow = Date.now();
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
if (state.view === "chat" && thread?.running) {
chatClock = setInterval(() => {
chatNow = Date.now();
updateChatIndicator(chatNow);
}, 1000);
}
}
function stopChatClock() {
if (chatClock) {
clearInterval(chatClock);
chatClock = null;
}
}
/** Refresh the running indicator in place from the thread's own state at [now]. */
function updateChatIndicator(now) {
const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null;
const el = document.getElementById("chatRunning");
if (!thread?.running || !el) return;
const label = el.querySelector(".chat-running-label");
if (label) label.textContent = turnPhaseLabel(threadPhase(thread, now) ?? TURN_PHASE_WAITING);
const elapsed = el.querySelector(".chat-running-elapsed");
if (elapsed) elapsed.textContent = `\u00b7 ${formatDuration(Math.trunc(threadElapsedMillis(thread, now) / 1000))}`;
for (const part of threadRunningTools(thread.messages)) {
const line = el.querySelector(`.chat-running-tool[data-part-id="${String(part?.id ?? "")}"]`);
if (!line) continue;
const age = threadToolElapsedMillis(thread, part, now);
const toolElapsed = line.querySelector(".chat-running-tool-elapsed");
if (toolElapsed) toolElapsed.textContent = formatToolDuration(age);
const mark = line.querySelector(".chat-tool-long");
if (toolLongRunning(age) && !mark) {
line.classList.add("chat-running-tool-long");
line.append(h("span", { class: "chat-tool-long", text: "\u00b7 long" }));
}
}
}
// ---------------------------------------------------------------------------
// Boot
// ---------------------------------------------------------------------------
@@ -4891,10 +5115,32 @@ client.addEventListener("state", (event) => {
stopRunPoll();
stopListClock();
stopDetailClock();
stopChatClock();
// The socket dropped: the server detaches every chat subscription with it
// (there is no chat_unsubscribe), and the frames feeding any running turn are
// gone, so no thread keeps claiming to run until a fresh frame proves it.
clearChatSubscriptions();
settleChatThreads();
}
// A reconnect (not a first connect): re-attach the open chat's stream and
// refresh its history wholesale, so a gap that swallowed the end of a turn is
// repaired rather than shown stale.
if (next.kind === "connected" && (previousKind === "connecting" || previousKind === "disconnected")) {
resyncOpenChat();
}
render();
});
// The client surfaces every unsolicited envelope as a DOM-free `frame` event
// (client.js). Only the chat stream is folded here; a frame for any other type is
// ignored.
client.addEventListener("frame", (event) => {
const message = event.detail;
if (!message || message.type !== Protocol.CHAT_EVENT) return;
const frame = message[ChatKeys.EVENT];
if (frame) onChatEvent(frame);
});
// The stage pane, the decision sheet, the confirm/Action-failed dialogs, the
// omni-search field and the attention sheet are modal: Escape closes the topmost
// one (the artifact viewer or the diff viewer, when either is above, owns Escape
+353
View File
@@ -738,6 +738,359 @@ export function mergeHistoryPage(previous, page, { older = false } = {}) {
};
}
// ---------------------------------------------------------------------------
// Live stream folding (ChatStore.kt event/applyRemoteUser/applyDelta/applyTool,
// ChatFormat.kt deltaPartId/mergeToolPart/turnPhase)
// ---------------------------------------------------------------------------
/** ChatEvent.Kind values pushed on the `chat_event` stream (internal/protocol/chat.go). */
export const EVENT_STEP = "step";
export const EVENT_USAGE = "usage";
export const EVENT_USER = "user";
export const EVENT_SHELL = "shell";
/** ChatStep.Status values. `ended` is the one status that settles a turn. */
export const STEP_ENDED = "ended";
/**
* How recently a text or reasoning delta must have arrived for a turn to read as
* still thinking. Long enough that the indicator's tick cannot flicker between
* thinking and waiting on a steady stream, short enough that a stalled turn
* starts reading as waiting while the operator still wonders.
*/
export const TURN_THINKING_WINDOW_MILLIS = 2500;
/** The three things an in-flight turn can be doing (ChatFormat.kt TurnPhase). */
export const TURN_PHASE_THINKING = "thinking";
export const TURN_PHASE_TOOL = "tool";
export const TURN_PHASE_WAITING = "waiting";
/**
* The live-stream badge words, shared verbatim with `liveBadgeState` /
* RunStream.kt: the stream is `live` only while a session is subscribed on a
* connected socket, `reconnecting` while the socket is coming back (pushes are
* paused in the gap) and `not live` when idle or when the server refused the
* subscription. The word always carries the meaning, so colour is never the only
* signal.
*/
export const STREAM_LIVE = "live";
export const STREAM_RECONNECTING = "reconnecting";
export const STREAM_OFFLINE = "not live";
/** The badge for [connectionKind] (`connected`/`connecting`/`disconnected`/`idle`). */
export function chatStreamState(connectionKind, subscribed) {
if (connectionKind === "connected" && subscribed) return { tone: "live", label: STREAM_LIVE };
if (connectionKind === "connecting" || connectionKind === "disconnected") {
return { tone: "reconnecting", label: STREAM_RECONNECTING };
}
return { tone: "not-live", label: STREAM_OFFLINE };
}
/**
* 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
* ChatStore.kt). A Map is deliberately not used for [toolStartedAt] so a thread
* stays a plain, comparable value.
*/
export function newChatThread(sessionId = "") {
return {
sessionId,
messages: [],
nextCursor: "",
hasMore: false,
loaded: false,
loading: false,
error: "",
running: false,
runningSince: 0,
toolStartedAt: {},
lastDeltaAt: 0,
queued: false,
};
}
/**
* The settled form of a thread: no turn is in flight, so the elapsed stamps and
* the queued flag are cleared. The one place a thread stops running, so the
* indicator and its stamps can never disagree. A no-op (returns [thread]) when it
* was already settled.
*/
export function settledThread(thread) {
return {
...(thread ?? {}),
running: false,
runningSince: 0,
toolStartedAt: {},
lastDeltaAt: 0,
queued: false,
};
}
/** Applies a running transition, stamping `runningSince` the moment it begins. */
export function setThreadRunning(thread, running, now) {
if (running) return thread.running ? thread : { ...thread, running: true, runningSince: now };
return settledThread({ ...thread });
}
/**
* 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.
*/
export function threadElapsedMillis(thread, nowMillis) {
const since = Number(thread?.runningSince) || 0;
return thread?.running && since >= 1 && since < nowMillis ? nowMillis - since : 0;
}
/** Every tool call still in flight across a conversation's [messages]. */
export function threadRunningTools(messages) {
return runningTools((messages ?? []).flatMap((message) => message?.parts ?? []));
}
/** How long [part] has been running at [nowMillis], using the thread's own stamps. */
export function threadToolElapsedMillis(thread, part, nowMillis) {
const stamps = thread?.toolStartedAt ?? {};
const startedAt = stamps instanceof Map ? (stamps.get(part?.id) ?? 0) : (stamps[part?.id] ?? 0);
return runningToolElapsedMillis(part, startedAt, nowMillis);
}
/**
* The id a text or reasoning delta must be applied to for [kind] within [parts].
* The broker gives the two kinds distinct ids (see `ChatDeltaPartID`), but a peer
* that still shares one bare id between them must never have answer text appended
* into a reasoning part: when another kind already holds the bare id, the delta is
* moved onto a suffixed id of its own. Once a part of this kind exists under
* either id, that part is the one addressed, so a stream keeps growing the part
* it started.
*/
export function deltaPartId(parts, kind, id) {
const list = parts ?? [];
if (list.some((part) => part?.type === kind && part?.id === id)) return id;
const suffixed = `${id}#${kind}`;
if (list.some((part) => part?.type === kind && part?.id === suffixed)) return suffixed;
return list.some((part) => part?.id === id) ? suffixed : id;
}
/**
* Folds one tool frame's part onto the part retained from earlier frames. A tool
* call is reported across several frames that each carry only part of it, so a
* field already learned is never blanked by a later frame that omits it. A
* non-empty incoming field wins; otherwise the retained value is kept.
*/
export function mergeToolPart(previous, incoming) {
if (previous == null) return incoming;
return {
...incoming,
type: isBlank(incoming?.type) ? previous.type : incoming.type,
name: isBlank(incoming?.name) ? previous.name : incoming.name,
executed: Boolean(incoming?.executed || previous?.executed),
time: incoming?.time ?? previous?.time,
state: mergeToolState(previous?.state, incoming?.state),
};
}
function mergeToolState(prior, incoming) {
if (incoming == null) return prior ?? undefined;
if (prior == null) return incoming;
return {
...incoming,
status: isBlank(incoming.status) ? prior.status : incoming.status,
input: incoming.input == null ? prior.input : incoming.input,
content: (incoming.content ?? []).length > 0 ? incoming.content : prior.content,
metadata: incoming.metadata ?? prior.metadata,
error: incoming.error ?? prior.error,
};
}
/**
* The running-tool start stamps after a thread's [messages] changed: every tool
* part in flight keeps the stamp it already had, or is stamped with [now] when it
* has just turned running, and a part that is no longer running loses its stamp.
*/
export function runningToolStamps(current, messages, now) {
const stamps = {};
for (const message of messages ?? []) {
for (const part of message?.parts ?? []) {
if (!isBlank(part?.id) && part?.type === PART_TOOL && toolRunning(part)) {
stamps[part.id] = current?.[part.id] ?? now;
}
}
}
return stamps;
}
/**
* The [TURN_PHASE_*] of a turn in flight. [tools] are the calls the stream still
* reports running; [silentMillis] is how long ago the last text or reasoning
* delta arrived, or null when none has. No percentage, ETA or progress is
* invented — the only inputs are the calls the stream reported and the time since
* the last delta.
*/
export function turnPhase(tools, silentMillis) {
if ((tools ?? []).length > 0) return TURN_PHASE_TOOL;
if (silentMillis != null && silentMillis >= 0 && silentMillis < TURN_THINKING_WINDOW_MILLIS) {
return TURN_PHASE_THINKING;
}
return TURN_PHASE_WAITING;
}
/** The running indicator's headline for [phase], naming what is happening. */
export function turnPhaseLabel(phase) {
if (phase === TURN_PHASE_THINKING) return "Thinking…";
if (phase === TURN_PHASE_TOOL) return "Running a tool…";
return "Waiting…";
}
/**
* The turn's phase at [nowMillis], derived from its running tools and the time
* since its last delta. Null when nothing is running, so a settled turn has no
* phase at all.
*/
export function threadPhase(thread, nowMillis) {
if (!thread?.running) return null;
const last = Number(thread.lastDeltaAt) || 0;
const silent = last >= 1 && last < nowMillis ? nowMillis - last : null;
return turnPhase(threadRunningTools(thread.messages), silent);
}
/**
* Applies one pushed `chat_event` frame to a conversation and returns the next
* 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
* targets is created on first sight, so a live turn never gains a second bubble.
*/
export function applyChatEvent(thread, frame, now = Date.now()) {
const current = thread?.queued
? { ...thread, queued: false }
: (thread ?? newChatThread(str(frame?.session_id)));
switch (frame?.kind) {
case EVENT_USER:
return applyRemoteUser(current, frame);
case PART_TEXT:
case PART_REASONING:
return applyDelta(current, frame, now);
case PART_TOOL:
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.
case EVENT_SHELL:
case EVENT_USAGE:
default:
return current;
}
}
/**
* Folds a user turn another client sent into the transcript, in place, once. The
* server never echoes this client's own prompts, so the sender's own message is
* never duplicated; the message's `client` label says which device sent it.
*/
function applyRemoteUser(thread, frame) {
const text = str(frame?.part?.text);
const messageId = str(frame?.message_id);
if (messageId === "" || text === "") return thread;
const operationId = str(frame?.operation_id);
const messages = thread.messages ?? [];
if (
operationId !== "" &&
messages.some((message) => message?.role === ROLE_USER && str(message?.operation_id) === operationId)
) {
return thread;
}
if (messages.some((message) => message?.id === messageId)) return thread;
const message = {
id: messageId,
session_id: str(frame?.session_id),
role: ROLE_USER,
client: str(frame?.client),
operation_id: operationId,
parts: [{ type: PART_TEXT, text }],
};
return { ...thread, messages: [...messages, message] };
}
function applyDelta(thread, frame, now) {
const rawId = str(frame?.part?.id);
const delta = str(frame?.delta);
if (rawId === "" || delta === "") return thread;
const kind = frame.kind;
return upsertParts(thread, frame, now, now, (parts) => {
const id = deltaPartId(parts, kind, rawId);
const index = parts.findIndex((part) => part?.id === id);
if (index < 0) return [...parts, { type: kind, id, text: delta }];
const next = parts.slice();
next[index] = { ...next[index], text: str(next[index]?.text) + delta };
return next;
});
}
function applyTool(thread, frame, now) {
const incoming = frame?.part ?? null;
if (incoming == null || str(incoming.id) === "") return thread;
return upsertParts(thread, frame, now, null, (parts) => {
const index = parts.findIndex((part) => part?.id === incoming.id && part?.type === PART_TOOL);
if (index < 0) return [...parts, mergeToolPart(null, incoming)];
const next = parts.slice();
next[index] = mergeToolPart(next[index], incoming);
return next;
});
}
/**
* Finds or creates the assistant message [frame] targets and replaces its parts
* with [upsert]'s result, then marks the thread running. The text/reasoning fold
* and the tool upsert share this so the two cannot drift.
*/
function upsertParts(thread, frame, now, deltaArrivedAt, upsert) {
const messageId = str(frame?.message_id);
const messages = (thread.messages ?? []).slice();
let index = -1;
for (let i = messages.length - 1; i >= 0; i -= 1) {
if (messages[i]?.id === messageId) {
index = i;
break;
}
}
if (index < 0) {
messages.push({
id: messageId,
session_id: str(frame?.session_id),
role: ROLE_ASSISTANT,
parts: [],
});
index = messages.length - 1;
}
const message = messages[index];
messages[index] = { ...message, parts: upsert(message.parts ?? []) };
const stamped = runningToolStamps(thread.toolStartedAt, messages, now);
let next = setThreadRunning({ ...thread, messages, toolStartedAt: stamped }, true, now);
if (deltaArrivedAt != null) next = { ...next, lastDeltaAt: deltaArrivedAt };
return next;
}
/**
* 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.
*/
export function historyResync(thread, page) {
const settled = settledThread(thread ?? newChatThread());
return {
...settled,
messages: (page?.messages ?? []).slice(),
nextCursor: str(page?.nextCursor),
hasMore: Boolean(page?.hasMore),
loaded: true,
loading: false,
error: "",
};
}
// ---------------------------------------------------------------------------
// Scroll behaviour (ChatScroll.kt)
// ---------------------------------------------------------------------------
+10 -4
View File
@@ -1,7 +1,9 @@
// A single, reused WebSocket connection to /connect, mirroring
// android/.../data/transport/PipelinesClient.kt: requests are serialized, each
// carries a client-generated stable id, replies are matched by id, and
// unsolicited envelopes are dropped. There is no authentication of any kind.
// carries a client-generated stable id, replies are matched by id, and an
// unsolicited envelope is surfaced as a DOM-free `frame` event (the app folds the
// frames it cares about) rather than misattributed to a request. There is no
// authentication of any kind.
//
// DOM-free on purpose: the browser app and the Node smoke test share this exact
// module, so the smoke test exercises the real client, not a re-implementation.
@@ -184,9 +186,13 @@ export class PipelinesClient extends EventTarget {
this.#pending.delete(message.id);
clearTimeout(entry.timer);
entry.resolve(message);
return;
}
// Unsolicited envelopes (for example the connection's initial pipeline_list)
// have no matching id and are intentionally dropped.
// No pending request matches: the envelope is unsolicited (the connection's
// initial pipeline_list, or a server-pushed frame such as `chat_event`) and is
// surfaced as a DOM-free `frame` event so the app can fold the frames it cares
// about. It is never misattributed to a request, which is still matched by id.
this.dispatchEvent(new CustomEvent("frame", { detail: message }));
}
#failPending(reason) {
+11
View File
@@ -43,6 +43,13 @@ export const Protocol = Object.freeze({
CHAT_MESSAGES: "chat_messages",
CHAT_CLOSE: "chat_close",
CHAT_REOPEN: "chat_reopen",
// The shared live stream (C5). `chat_subscribe` attaches this connection to one
// session's stream (body: the session id); the server then pushes `chat_event`
// frames without a matching request id, so every client watching a session sees
// the same turn. There is no `chat_unsubscribe` on the wire — the server
// detaches a subscription when the connection closes.
CHAT_SUBSCRIBE: "chat_subscribe",
CHAT_EVENT: "chat_event",
SUCCESS_END: "#success",
FAILURE_END: "#failure",
@@ -60,6 +67,10 @@ export const ChatKeys = Object.freeze({
HISTORY: "chat_history",
MESSAGES: "chat_messages",
CLOSE: "chat_close",
// `chat_subscribe` (the request body naming the session) and `chat_event` (the
// unsolicited pushed frame on the shared stream).
SUBSCRIBE: "chat_subscribe",
EVENT: "chat_event",
});
/**
+20
View File
@@ -197,6 +197,26 @@ export class PipelinesRepository {
return { messages: response[ChatKeys.MESSAGES] ?? [], nextCursor: "", hasMore: false };
}
/**
* Attaches this connection to one session's shared live stream (C5). The body
* is exactly `{type:'chat_subscribe', chat_subscribe:{session_id}}` — the
* `chat_subscribe` field, not `chat_query` (internal/protocol/message.go); the
* server replies with an id-matched echo once the subscription is attached and
* then pushes `chat_event` frames without an id, which `client.js` surfaces as a
* `frame` event. Any number of clients may watch one session; the session is
* never read-only. There is no `chat_unsubscribe`: the server drops a
* subscription when the connection closes.
*/
async subscribeChat(sessionId) {
if (!String(sessionId ?? "").trim()) {
throw new ProtocolError("Select a chat session first.");
}
return this.#client.call({
type: Protocol.CHAT_SUBSCRIBE,
[ChatKeys.SUBSCRIBE]: { session_id: sessionId },
});
}
/**
* Finishes a session and records it closed on the server (nothing is
* deleted). The reply echoes the updated session (`chat_session`) and the