Skip to content

Your lightweight open-source personal agent.

fix(webui): share sidebar and Composer run state (#6337)

chengyongru5ae49a43e799
diff --git a/webui/browser/answer-order.spec.ts b/webui/browser/answer-order.spec.ts
index 77375ea8f..5998cd644 100644
--- a/webui/browser/answer-order.spec.ts
+++ b/webui/browser/answer-order.spec.ts
@@ -125,11 +125,23 @@ for (const width of [1440, 390]) {
{ event: "stream_end", ...base, stream_id: "legacy", turn_seq: 5, text: "First last" },
{ event: "turn_end", ...base, turn_seq: 6 },
]);
- await expect(page.getByText("First", { exact: true })).toHaveCount(1);
- await expect(page.getByText("last", { exact: true })).toHaveCount(1);
- const texts = await page.locator("[data-thread-display-unit]").allTextContents();
- expect(texts.findIndex((text) => text.includes("First"))).toBeLessThan(texts.findIndex((text) => text.includes("Searching the web")));
- expect(texts.findIndex((text) => text.includes("Searching the web"))).toBeLessThan(texts.findIndex((text) => text.includes("last")));
+ const first = page.getByText("First", { exact: true });
+ const last = page.getByText("last", { exact: true });
+ await expect(first).toHaveCount(1);
+ await expect(last).toHaveCount(1);
+ await expect(page.getByRole("button", { name: "Stop response" })).toHaveCount(0);
+ // Completed activity is folded into the answer block, not lost or still running.
+ const lastBlock = last.locator("xpath=ancestor::*[@data-thread-display-unit]");
+ await lastBlock.hover();
+ await lastBlock.getByRole("button", { name: "Message actions" }).click();
+ await page.locator("[data-message-block-activity-action]").click();
+ const tool = page.getByText(/Searched the web/).first();
+ await expect(tool).toBeVisible();
+ const [firstNode, lastNode] = await Promise.all([first.elementHandle(), last.elementHandle()]);
+ expect(await tool.evaluate((node, [before, after]) => (
+ !!(before.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING)
+ && !!(node.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING)
+ ), [firstNode!, lastNode!])).toBe(true);
expect(errors).toEqual([]);
});
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index 1bfd55e65..d43562f86 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -2254,8 +2254,8 @@ function Shell({
}, [client, onModelNameChange]);
useEffect(() => {
- return client.onRunStatus((chatId, startedAt) => {
- if (startedAt != null) {
+ return client.onRunStatus((chatId, state) => {
+ if (state.active) {
const nextRunning = new Set(runningChatIdsRef.current);
nextRunning.add(chatId);
runningChatIdsRef.current = nextRunning;
diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsx
index 54491ae1f..dff5a8fcb 100644
--- a/webui/src/components/thread/ThreadShell.tsx
+++ b/webui/src/components/thread/ThreadShell.tsx
@@ -691,15 +691,11 @@ export function ThreadShell({
[displayMessages],
);
const currentGoalState = messagesReady ? goalState : undefined;
- // Decision states freeze the interrupted turn and hand the next action to
- // the recovery notice. ``resuming`` remains active; ``recovered`` is only
- // historical metadata and must not suppress a later normal turn.
+ // Recovery decisions gate queued input, not the ledger-owned run state.
const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"
|| recoveryState?.status === "failed";
- const currentRunStartedAt = messagesReady && !recoveryNeedsDecision ? runStartedAt : null;
- const turnActive = messagesReady
- && !recoveryNeedsDecision
- && (isStreaming || currentRunStartedAt !== null);
+ const currentRunStartedAt = messagesReady ? runStartedAt : null;
+ const turnActive = messagesReady && isStreaming;
const restoredViewportTurnId = useMemo(
() => turnActive ? latestActiveTurnId(displayMessages, currentRunStartedAt) : null,
[currentRunStartedAt, displayMessages, turnActive],
diff --git a/webui/src/hooks/useNanobotStream.ts b/webui/src/hooks/useNanobotStream.ts
index 0f43d4c01..0ea2c4903 100644
--- a/webui/src/hooks/useNanobotStream.ts
+++ b/webui/src/hooks/useNanobotStream.ts
@@ -144,6 +144,7 @@ export function useNanobotStream(
onStreamDetach?: (messages: UIMessage[]) => void,
completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS,
history?: { key: string | null; cache?: ThreadMessageCache },
+ historyActiveTurnId: string | null = null,
): {
messages: UIMessage[];
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
@@ -189,7 +190,13 @@ export function useNanobotStream(
const threadVisible = useThreadVisibility();
const threadVisibleRef = useRef(threadVisible);
threadVisibleRef.current = threadVisible;
- const initialRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
+ const [runState, setRunState] = useState(() => chatId ? client.getRunState(chatId) : null);
+ const isStreaming = runState?.active ?? false;
+ const runStartedAt = runState?.startedAt ?? null;
+ const historyRunGenerationRef = useRef({ chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 });
+ if (historyRunGenerationRef.current.chatId !== chatId) {
+ historyRunGenerationRef.current = { chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 };
+ }
const [messages, setRenderedMessages] = useState<UIMessage[]>(initialTranscript.messages);
const messagesRef = useRef(messages);
// Keep received state ahead of React's batched render: navigation can unmount
@@ -210,11 +217,6 @@ export function useNanobotStream(
!message.turnId || !completedInitialTurns.has(message.turnId)
)));
}, [completedTurnIds, initialMessages]);
- const [isStreaming, setIsStreaming] = useState(
- initialStreaming || hasPendingToolCalls || initialRunStartedAt !== null,
- );
- /** Unix epoch seconds when the current user turn started; cleared on ``idle``. */
- const [runStartedAt, setRunStartedAt] = useState<number | null>(initialRunStartedAt);
const [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
@@ -312,14 +314,7 @@ export function useNanobotStream(
return nextMessages;
});
- const remainingStartedAt = client.getRunStartedAt(chatId);
- const hasRemainingRun = (
- remainingStartedAt !== null
- || client.hasUnsettledRun(chatId)
- );
- setRunStartedAt(remainingStartedAt);
- setIsStreaming(hasRemainingRun);
- if (!hasRemainingRun) {
+ if (!client.getRunState(chatId).active) {
transcriptRef.current.projection = {
...transcriptRef.current.projection,
suppressUntilTurnEnd: false,
@@ -475,13 +470,10 @@ export function useNanobotStream(
useEffect(() => {
if (!chatId) return;
- return client.onRunStatus((runChatId, startedAt) => {
+ return client.onRunStatus((runChatId, state) => {
if (runChatId !== chatId) return;
- if (startedAt !== null) {
- setRunStartedAt(startedAt);
- setIsStreaming(true);
- return;
- }
+ setRunState(state);
+ if (state.active) return;
flushPendingStreamEvents();
setMessages((prev) => {
const settled = prev.map((message) => (
@@ -493,8 +485,6 @@ export function useNanobotStream(
);
return settled;
});
- setRunStartedAt(null);
- setIsStreaming(false);
});
}, [chatId, client, clearActivitySegment, flushPendingStreamEvents, setMessages]);
@@ -502,18 +492,11 @@ export function useNanobotStream(
// ``initialMessages`` update: a brand-new chat can receive an empty/404
// history response after the optimistic first message has already rendered.
useEffect(() => {
- const restoredRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey);
setMessages(transcriptRef.current.messages);
setMessageScope({ chatId, historyKey, client });
- setIsStreaming(
- initialStreaming
- || hasPendingToolCalls
- || transcriptRef.current.paging.hasPendingToolCalls
- || restoredRunStartedAt !== null,
- );
+ setRunState(chatId ? client.getRunState(chatId) : null);
setStreamError(null);
- setRunStartedAt(restoredRunStartedAt);
setRetryStatus(null);
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null);
@@ -522,8 +505,9 @@ export function useNanobotStream(
}, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]);
useEffect(() => {
- if (hasPendingToolCalls) setIsStreaming(true);
- }, [hasPendingToolCalls]);
+ if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return;
+ client.restorePendingRun(chatId, historyRunGenerationRef.current.generation, historyActiveTurnId);
+ }, [chatId, client, hasPendingToolCalls, historyActiveTurnId, initialStreaming]);
const applyProjectionEvent = useCallback((
event: ThreadProjectionEvent,
@@ -581,15 +565,9 @@ export function useNanobotStream(
if (ownRead && chatId && canonical) {
if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation,
canonical.completedTurnIds, canonical.snapshot)) {
- setIsStreaming(false);
- setRunStartedAt(null);
setRetryStatus(null);
} else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds);
}
- if (accepted && owner.paging.hasPendingToolCalls && chatId
- && !(owner.paging.activeTurnId && client.isRunCompleted(chatId, owner.paging.activeTurnId))) {
- setIsStreaming(true);
- }
};
const cached = webuiThreadCache.get(historyKey);
if (cached && owner.paging.version === 0) install(cached, false, true);
@@ -703,7 +681,6 @@ export function useNanobotStream(
flushPendingStreamEvents();
closeActiveAssistantStream();
clearActivitySegment();
- setIsStreaming(true);
setMessages((prev) => {
const next = appendProjectedSessionInput(prev, ev);
if (next !== prev) transcriptRef.current.registerInput(next[next.length - 1]);
@@ -741,10 +718,6 @@ export function useNanobotStream(
transcriptRef.current.registerInput(row);
return [...prev, row];
});
- if (ev.active_turn_id || ev.starts_turn) {
- setIsStreaming(true);
- if (typeof ev.started_at === "number") setRunStartedAt(ev.started_at);
- }
return;
}
const sideChannelEvent = isSideChannelEvent(ev);
@@ -767,7 +740,6 @@ export function useNanobotStream(
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
const chunk = typeof ev.text === "string" ? ev.text : "";
if (!chunk) return;
- setIsStreaming(true);
pendingStreamEventsRef.current.push({
kind: "delta",
text: chunk,
@@ -784,7 +756,6 @@ export function useNanobotStream(
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
const chunk = ev.text;
if (!chunk) return;
- setIsStreaming(true);
pendingStreamEventsRef.current.push({
kind: "reasoning",
text: chunk,
@@ -800,13 +771,11 @@ export function useNanobotStream(
flushPendingStreamEvents(ev);
if (transcriptRef.current.projection.suppressUntilTurnEnd) return;
if (ev.resuming) {
- setIsStreaming(true);
return;
}
// ``stream_end`` closes the current answer segment, not the turn.
// Tools and follow-up model segments may still arrive before the
// definitive ``turn_end`` event.
- setIsStreaming(true);
return;
}
@@ -824,15 +793,8 @@ export function useNanobotStream(
}
if (ev.event === "goal_status") {
- if (ev.status === "running" && typeof ev.started_at === "number") {
- setStreamError(null);
- setRunStartedAt(ev.started_at);
- setIsStreaming(true);
- } else {
- setRunStartedAt(null);
- setIsStreaming(false);
- setRetryStatus(null);
- }
+ if (ev.status === "running") setStreamError(null);
+ else setRetryStatus(null);
return;
}
@@ -860,7 +822,6 @@ export function useNanobotStream(
: {}),
...(ev.turn_id ? { turn_id: ev.turn_id } : {}),
});
- setIsStreaming(true);
}
return;
}
@@ -870,11 +831,7 @@ export function useNanobotStream(
if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") {
setGoalState(ev.goal_state);
}
- setRunStartedAt(null);
setRetryStatus(null);
- // Definitive signal that the turn is fully complete, so stop the
- // loading indicator immediately.
- setIsStreaming(false);
const modelRequestFailed = ev.outcome === "failed" && ev.failure_kind === "model";
const failureAttempts =
typeof ev.failure_attempts === "number"
@@ -917,23 +874,12 @@ export function useNanobotStream(
if (ev.reason === "model_request_failed" || ev.status === "resuming") {
setStreamError(null);
}
- if (ev.status === "resuming") {
- setRunStartedAt((current) => current ?? Date.now() / 1000);
- setIsStreaming(true);
- }
if (
ev.status === "awaiting_user"
|| ev.status === "recovered"
|| ev.status === "failed"
) {
setRetryStatus(null);
- // Recovery is an explicit boundary. The interrupted turn is no
- // longer running, so do not let the stale start time keep the
- // activity clock (or composer stop state) alive underneath the
- // recovery notice.
- setRunStartedAt(null);
- setIsStreaming(false);
- client.finishRunLocally(chatId);
clearPendingStreamWork();
closeActiveAssistantStream();
clearActivitySegment();
@@ -949,16 +895,10 @@ export function useNanobotStream(
) {
setStreamError(null);
}
- if (ev.recovery_state?.status === "resuming") {
- setRunStartedAt((current) => current ?? Date.now() / 1000);
- setIsStreaming(true);
- } else if (
+ if (
ev.recovery_state?.status === "awaiting_user"
|| ev.recovery_state?.status === "failed"
) {
- setRunStartedAt(null);
- setIsStreaming(false);
- client.finishRunLocally(chatId);
clearPendingStreamWork();
closeActiveAssistantStream();
clearActivitySegment();
@@ -1028,7 +968,7 @@ export function useNanobotStream(
: content;
flushPendingStreamEvents();
if (finalizeActiveTurn) {
- setIsStreaming(false);
+ client.finishRunLocally(chatId);
setRetryStatus(null);
}
const turnId = crypto.randomUUID();
@@ -1073,7 +1013,6 @@ export function useNanobotStream(
transcriptRef.current.registerInput(next[next.length - 1]);
return next;
});
- if (!sideChannel) setIsStreaming(true);
const wireMedia = hasAttachments ? images!.map((i) => i.media) : undefined;
const clientOptions = {
...options,
@@ -1099,14 +1038,12 @@ export function useNanobotStream(
const stop = useCallback(() => {
if (!chatId) return;
flushPendingStreamEvents();
- setIsStreaming(false);
setRetryStatus(null);
setMessages((prev) => {
const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
transcriptRef.current.projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled);
return settled;
});
- setRunStartedAt(null);
client.finishRunLocally(chatId);
client.sendMessage(chatId, "/stop");
}, [chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages]);
diff --git a/webui/src/lib/client-run-ledger.ts b/webui/src/lib/client-run-ledger.ts
index 25f3eda05..0ceb179eb 100644
--- a/webui/src/lib/client-run-ledger.ts
+++ b/webui/src/lib/client-run-ledger.ts
@@ -15,6 +15,7 @@ interface ChatRecord {
generation: number;
latestTurnId: string | null;
effectiveStartedAt: number | null;
+ anonymousActive: boolean;
turns: Map<string, TurnRecord>;
/** Closed turns permit late inputs, messages, completions and idle. */
closed: Set<string>;
@@ -47,7 +48,8 @@ export type RunObservation = Readonly<{
}> & (
| { kind: "admission" | "input"; owner?: { turnId: string; startedAt?: number } }
| { kind: "status"; activity: "running" | "idle"; startedAt?: number }
- | { kind: "completed" | "message" | "progress" | "rejection" }
+ | { kind: "completed" | "message" | "progress" | "activity" | "rejection" }
+ | { kind: "recovery"; active: boolean }
);
type Command =
@@ -55,10 +57,11 @@ type Command =
| ({ kind: "written" | "reject" } & TurnRef)
| { kind: "transport-lost" }
| { kind: "local-stop" | "forget"; chatId: string }
- | { kind: "fence"; chatId: string; completedTurnIds: readonly string[] };
+ | { kind: "fence"; chatId: string; completedTurnIds: readonly string[] }
+ | { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null };
export type RunEffect =
- | { kind: "run-status"; chatId: string; startedAt: number | null }
+ | { kind: "run-status"; chatId: string; state: RunState }
| { kind: "completion"; chatId: string }
| ({ kind: "discard-send" } & TurnRef)
| { kind: "prune-inbound"; chatId: string; turnIds: readonly string[] };
@@ -68,7 +71,8 @@ interface ObservationResult {
effects: readonly RunEffect[];
}
-interface RunView {
+export interface RunState {
+ active: boolean;
generation: number;
latestTurnId: string | null;
startedAt: number | null;
@@ -81,9 +85,10 @@ const COMPLETED_TURN_FENCE_MAX = 256;
export class ClientRunLedger {
private chats = new Map<string, ChatRecord>();
- view(chatId: string): RunView {
+ view(chatId: string): RunState {
const chat = this.chats.get(chatId);
return {
+ active: chat?.anonymousActive === true || chat?.effectiveStartedAt != null || this.hasOpenTurn(chat),
generation: chat?.generation ?? 0,
latestTurnId: chat?.latestTurnId ?? null,
startedAt: chat?.effectiveStartedAt ?? null,
@@ -100,15 +105,13 @@ export class ClientRunLedger {
return this.chats.get(chatId)?.turns.get(turnId)?.delivery != null;
}
- activeClocks(): readonly Readonly<{ chatId: string; startedAt: number }>[] {
- return Array.from(this.chats).flatMap(([chatId, chat]) => (
- chat.effectiveStartedAt === null ? [] : [{ chatId, startedAt: chat.effectiveStartedAt }]
- ));
+ states(): readonly Readonly<{ chatId: string; state: RunState }>[] {
+ return Array.from(this.chats.keys(), (chatId) => ({ chatId, state: this.view(chatId) }));
}
unresolvedChatIds(): string[] {
return Array.from(this.chats).flatMap(([chatId, chat]) => (
- chat.effectiveStartedAt !== null || this.hasOpenTurn(chat) ? [chatId] : []
+ chat.anonymousActive || chat.effectiveStartedAt !== null || this.hasOpenTurn(chat) ? [chatId] : []
));
}
@@ -140,6 +143,20 @@ export class ClientRunLedger {
}
transition(command: Command): readonly RunEffect[] {
+ if (command.kind === "transport-lost") return this.applyCommand(command);
+ const before = this.view(command.chatId);
+ return this.withRunStatus(command.chatId, before, this.applyCommand(command));
+ }
+
+ private withRunStatus(chatId: string, before: RunState, effects: readonly RunEffect[]): readonly RunEffect[] {
+ const state = this.view(chatId);
+ if (state.active === before.active && state.startedAt === before.startedAt
+ && state.latestTurnId === before.latestTurnId && state.generation === before.generation
+ && state.unsettled === before.unsettled) return effects;
+ return [...effects, { kind: "run-status", chatId, state }];
+ }
+
+ private applyCommand(command: Command): readonly RunEffect[] {
const effects: RunEffect[] = [];
switch (command.kind) {
case "submit": {
@@ -173,15 +190,21 @@ export class ClientRunLedger {
for (const turnId of openTurnIds) this.rememberClosed(chat, turnId);
for (const turnId of openTurnIds) this.settle(command.chatId, turnId, effects);
chat.latestTurnId = null;
- this.updateClock(command.chatId, chat, null, effects);
+ chat.anonymousActive = false;
+ chat.effectiveStartedAt = null;
break;
}
- case "forget": {
- const chat = this.chats.get(command.chatId);
+ case "forget":
this.chats.delete(command.chatId);
- if (chat?.effectiveStartedAt != null) {
- effects.push({ kind: "run-status", chatId: command.chatId, startedAt: null });
- }
+ break;
+ case "restore-pending": {
+ if (this.view(command.chatId).generation !== command.generation || this.view(command.chatId).active) break;
+ const chat = this.ensureChat(command.chatId);
+ if (command.turnId
+ ? chat.closed.has(command.turnId) || chat.fenced.has(command.turnId)
+ : chat.generation !== 0 || chat.closed.size > 0 || chat.fenced.size > 0) break;
+ this.advance(chat, command.turnId);
+ chat.anonymousActive = command.turnId === null;
break;
}
case "fence":
@@ -196,6 +219,12 @@ export class ClientRunLedger {
}
observe(observation: RunObservation): ObservationResult {
+ const before = this.view(observation.chatId);
+ const result = this.applyObservation(observation);
+ return { ...result, effects: this.withRunStatus(observation.chatId, before, result.effects) };
+ }
+
+ private applyObservation(observation: RunObservation): ObservationResult {
const { chatId, turnId } = observation;
let chat = this.chats.get(chatId);
const effects: RunEffect[] = [];
@@ -214,7 +243,6 @@ export class ClientRunLedger {
if (chat.closed.has(owner.turnId) || chat.fenced.has(owner.turnId)) {
if (turnId && turnId !== owner.turnId && chat.turns.get(turnId)?.delivery?.role === "candidate-owner") {
this.reject(chatId, turnId, effects);
- if (!this.hasOpenTurn(chat)) effects.push({ kind: "run-status", chatId, startedAt: null });
}
forward = "without-owner";
} else {
@@ -224,7 +252,7 @@ export class ClientRunLedger {
if (chat.latestTurnId !== owner.turnId) this.advance(chat, owner.turnId);
if (typeof owner.startedAt === "number") {
this.ensureTurn(chat, owner.turnId).startedAt = owner.startedAt;
- this.updateClock(chatId, chat, owner.startedAt, effects);
+ chat.effectiveStartedAt = owner.startedAt;
}
}
}
@@ -240,6 +268,25 @@ export class ClientRunLedger {
}
if (turnId) this.accept(chat, turnId);
+ if (observation.kind === "recovery") {
+ if (!observation.active) {
+ if (!turnId || !chat?.latestTurnId || turnId === chat.latestTurnId) {
+ effects.push(...this.applyCommand({ kind: "local-stop", chatId }));
+ }
+ } else {
+ chat = this.ensureChat(chatId);
+ if (turnId) this.advance(chat, turnId);
+ else chat.anonymousActive = true;
+ }
+ return { forward, effects };
+ }
+ if (observation.kind === "activity" && !this.view(chatId).active
+ && (turnId !== null || !chat?.latestTurnId || !this.isCompleted({ chatId, turnId: chat.latestTurnId }))) {
+ chat = this.ensureChat(chatId);
+ this.advance(chat, turnId);
+ chat.anonymousActive = turnId === null;
+ }
+
const completion = observation.kind === "completed"
|| (observation.kind === "status" && observation.activity === "idle");
const superseded = completion && chat?.latestTurnId != null && turnId !== chat.latestTurnId;
@@ -247,14 +294,15 @@ export class ClientRunLedger {
chat = this.ensureChat(chatId);
this.advance(chat, turnId);
if (turnId) this.ensureTurn(chat, turnId).startedAt = observation.startedAt;
- this.updateClock(chatId, chat, observation.startedAt, effects);
+ chat.effectiveStartedAt = observation.startedAt;
} else if (observation.kind === "status" || observation.kind === "completed") {
// A running status without a numeric start time also settles the turn.
chat = this.ensureChat(chatId);
if (turnId) this.rememberClosed(chat, turnId);
if (turnId) this.settle(chatId, turnId, effects);
if (chat.latestTurnId === null || turnId === chat.latestTurnId) {
- this.updateClock(chatId, chat, null, effects);
+ chat.anonymousActive = false;
+ chat.effectiveStartedAt = null;
}
effects.push({ kind: "completion", chatId });
}
@@ -286,6 +334,12 @@ export class ClientRunLedger {
}
applyCanonical(request: CanonicalRequest): { accepted: boolean; effects: readonly RunEffect[] } {
+ const before = this.view(request.chatId);
+ const result = this.applyCanonicalSnapshot(request);
+ return { ...result, effects: this.withRunStatus(request.chatId, before, result.effects) };
+ }
+
+ private applyCanonicalSnapshot(request: CanonicalRequest): { accepted: boolean; effects: readonly RunEffect[] } {
const { chatId, snapshot } = request;
const effects: RunEffect[] = [];
this.fence(chatId, request.completedTurnIds, effects);
@@ -307,7 +361,8 @@ export class ClientRunLedger {
this.removeEmptyTurn(chat, turnId, turn);
effects.push({ kind: "discard-send", chatId, turnId });
}
- this.updateClock(chatId, chat, null, effects);
+ chat.anonymousActive = false;
+ chat.effectiveStartedAt = null;
return { accepted: true, effects };
}
@@ -318,6 +373,7 @@ export class ClientRunLedger {
generation: 0,
latestTurnId: null,
effectiveStartedAt: null,
+ anonymousActive: false,
turns: new Map(),
closed: new Set(),
fenced: new Set(),
@@ -340,6 +396,7 @@ export class ClientRunLedger {
chat.generation += 1;
chat.latestTurnId = turnId || null;
if (turnId) {
+ chat.anonymousActive = false;
const turn = this.ensureTurn(chat, turnId);
if (turn.openOrder === null) turn.openOrder = chat.generation;
}
@@ -395,14 +452,7 @@ export class ClientRunLedger {
}
}
chat.latestTurnId = previous?.turnId ?? null;
- this.updateClock(chatId, chat, previous?.startedAt ?? null, effects);
- }
-
- private updateClock(chatId: string, chat: ChatRecord, startedAt: number | null, effects: RunEffect[]): void {
- // An optimistic latest identity can coexist with an older effective clock.
- const previous = chat.effectiveStartedAt;
- chat.effectiveStartedAt = startedAt;
- if (previous !== startedAt) effects.push({ kind: "run-status", chatId, startedAt });
+ chat.effectiveStartedAt = previous?.startedAt ?? null;
}
private rememberClosed(chat: ChatRecord, turnId: string): void {
diff --git a/webui/src/lib/nanobot-client.ts b/webui/src/lib/nanobot-client.ts
index b7a3b43b7..56c7d753f 100644
--- a/webui/src/lib/nanobot-client.ts
+++ b/webui/src/lib/nanobot-client.ts
@@ -15,9 +15,9 @@ import type {
} from "./types";
import { createHostWebSocket } from "./runtime";
import { ClientRunLedger } from "./client-run-ledger";
-import type { CanonicalRunSnapshot, RunEffect, RunObservation } from "./client-run-ledger";
+import type { CanonicalRunSnapshot, RunEffect, RunObservation, RunState } from "./client-run-ledger";
-export type { CanonicalRunSnapshot } from "./client-run-ledger";
+export type { CanonicalRunSnapshot, RunState } from "./client-run-ledger";
/** WebSocket readyState constants, referenced by value to stay portable
* across runtimes that don't expose a global ``WebSocket`` (tests, SSR). */
@@ -87,7 +87,7 @@ type SessionUpdateHandler = (
workspaceScope?: WorkspaceScopePayload,
) => void;
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => void;
-type RunStatusHandler = (chatId: string, startedAt: number | null) => void;
+type RunStatusHandler = (chatId: string, state: RunState) => void;
/** Structured errors surfaced to the UI.
*
@@ -181,6 +181,9 @@ function runObservation(event: InboundEvent): RunObservation | null {
case "message_accepted":
case "user_message": {
const activeTurnId = event.active_turn_id ?? (event.starts_turn ? event.turn_id : undefined);
+ if (event.event === "user_message" && event.provenance?.session_message && !activeTurnId) {
+ return { ...base, kind: "activity" };
+ }
return {
...base,
kind: event.event === "message_accepted" ? "admission" : "input",
@@ -193,6 +196,22 @@ function runObservation(event: InboundEvent): RunObservation | null {
return { ...base, kind: "completed" };
case "error":
return { ...base, kind: "rejection" };
+ case "delta":
+ case "reasoning_delta":
+ return { ...base, kind: event.text ? "activity" : "progress" };
+ case "stream_end":
+ return { ...base, kind: "activity" };
+ case "retry_status":
+ return { ...base, kind: event.state === "recovered" || event.state === "cleared" ? "progress" : "activity" };
+ case "recovery_state":
+ // Supersession resolves the old recovery, not the new user turn that caused it.
+ return event.status === "recovered" && event.reason === "superseded"
+ ? { ...base, kind: "progress" }
+ : { ...base, kind: "recovery", active: event.status === "resuming" };
+ case "attached":
+ return event.recovery_state && event.recovery_state.status !== "recovered"
+ ? { ...base, kind: "recovery", active: event.recovery_state.status === "resuming" }
+ : { ...base, kind: "progress" };
case "message":
return { ...base, kind: "message" };
default:
@@ -307,8 +326,8 @@ export class NanobotClient {
onRunStatus(handler: RunStatusHandler): Unsubscribe {
this.runStatusHandlers.add(handler);
- for (const { chatId, startedAt } of this.runs.activeClocks()) {
- handler(chatId, startedAt);
+ for (const { chatId, state } of this.runs.states()) {
+ handler(chatId, state);
}
return () => {
this.runStatusHandlers.delete(handler);
@@ -329,6 +348,15 @@ export class NanobotClient {
};
}
+ getRunState(chatId: string): RunState {
+ return this.runs.view(chatId);
+ }
+
+ /** Restore pending history only within its original lifecycle generation. */
+ restorePendingRun(chatId: string, generation: number, turnId: string | null): void {
+ this.applyRunEffects(this.runs.transition({ kind: "restore-pending", chatId, generation, turnId }));
+ }
+
/** Last ``goal_status`` ``started_at`` (unix sec) for *chatId*, if the turn is running. */
getRunStartedAt(chatId: string): number | null {
return this.runs.view(chatId).startedAt;
@@ -428,7 +456,7 @@ export class NanobotClient {
for (const effect of effects) {
switch (effect.kind) {
case "run-status":
- this.emitRunStatus(effect.chatId, effect.startedAt);
+ this.emitRunStatus(effect.chatId, effect.state);
break;
case "completion":
for (const handler of this.runCompletionHandlers) handler(effect.chatId);
@@ -703,6 +731,10 @@ export class NanobotClient {
const turnId = options?.turnId ?? crypto.randomUUID();
const stillConnected = () => this.socket === socket
&& socket?.readyState === WS_OPEN && this.upload === capability;
+ this.applyRunEffects(this.runs.transition({
+ kind: "submit", chatId, turnId,
+ role: options?.startsNewRun === false ? "supplement" : "candidate-owner",
+ }));
try {
const references = await uploadAttachments(media, capability,
typeof window !== "undefined" ? window.location.href : this.currentUrl,
@@ -714,6 +746,7 @@ export class NanobotClient {
}
});
} catch (error) {
+ this.applyRunEffects(this.runs.transition({ kind: "reject", chatId, turnId }));
this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "attachment_rejected",
reason: error instanceof Error ? error.message : "Attachment send failed" });
throw error;
@@ -1037,9 +1070,9 @@ export class NanobotClient {
}
}
- private emitRunStatus(chatId: string, startedAt: number | null): void {
+ private emitRunStatus(chatId: string, state: RunState): void {
for (const handler of this.runStatusHandlers) {
- handler(chatId, startedAt);
+ handler(chatId, state);
}
}
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index 53f56c0f5..e77acca32 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -6,6 +6,7 @@ import type { Window as HappyWindow } from "happy-dom";
import i18n from "@/i18n";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
import { useSessions } from "@/hooks/useSessions";
+import type { RunState } from "@/lib/nanobot-client";
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import type {
ChatSummary,
@@ -33,7 +34,10 @@ const sendMessageSpy = vi.fn();
const sendSystemCommandSpy = vi.fn().mockResolvedValue(undefined);
let mockDefaultChatId: string | null = null;
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
-const runStatusHandlers = new Set<(chatId: string, startedAt: number | null) => void>();
+const runStatusHandlers = new Set<(chatId: string, state: RunState) => void>();
+const runState = (startedAt: number | null): RunState => ({
+ active: startedAt !== null, startedAt, latestTurnId: null, generation: 0, unsettled: false,
+});
const sessionUpdateHandlers = new Set<(
chatId: string,
scope?: string,
@@ -272,11 +276,13 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
sidebarStateUpdateHandlers.add(handler);
return () => sidebarStateUpdateHandlers.delete(handler);
};
- onRunStatus = (handler: (chatId: string, startedAt: number | null) => void) => {
+ onRunStatus = (handler: (chatId: string, state: RunState) => void) => {
runStatusHandlers.add(handler);
return () => runStatusHandlers.delete(handler);
};
onRunCompletion = () => () => {};
+ getRunState = () => runState(null);
+ restorePendingRun = vi.fn();
getRunStartedAt = () => null;
getRunTurnId = () => null;
getUnsettledRunChatIds = () => [];
@@ -2915,12 +2921,12 @@ describe("App layout", () => {
);
act(() => {
- for (const handler of runStatusHandlers) handler("chat-a", 12_345);
+ for (const handler of runStatusHandlers) handler("chat-a", runState(12_345));
});
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
act(() => {
- for (const handler of runStatusHandlers) handler("chat-a", null);
+ for (const handler of runStatusHandlers) handler("chat-a", runState(null));
});
expect(within(sidebar).queryByRole("img", { name: "Agent running" }))
.not.toBeInTheDocument();
@@ -2969,12 +2975,12 @@ describe("App layout", () => {
await waitFor(() => expect(document.title).toContain("Active work"));
act(() => {
- for (const handler of runStatusHandlers) handler("chat-a", 12_345);
+ for (const handler of runStatusHandlers) handler("chat-a", runState(12_345));
});
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
act(() => {
- for (const handler of runStatusHandlers) handler("chat-a", null);
+ for (const handler of runStatusHandlers) handler("chat-a", runState(null));
});
expect(within(sidebar).queryByRole("img", { name: "Agent running" }))
.not.toBeInTheDocument();
@@ -3062,12 +3068,12 @@ describe("App layout", () => {
await waitFor(() => expect(attachSpy).toHaveBeenCalledWith("chat-a"));
expect(within(sidebar).queryByRole("img", { name: "Agent running" })).not.toBeInTheDocument();
act(() => {
- for (const handler of runStatusHandlers) handler("chat-a", 12_345);
+ for (const handler of runStatusHandlers) handler("chat-a", runState(12_345));
});
expect(within(sidebar).getByRole("img", { name: "Agent running" })).toBeInTheDocument();
expect(within(sidebar).getByRole("img", { name: "New activity" })).toBeInTheDocument();
act(() => {
- for (const handler of runStatusHandlers) handler("chat-a", null);
+ for (const handler of runStatusHandlers) handler("chat-a", runState(null));
});
mockSessions = mockSessions.map((session) => ({ ...session }));
rerender(<App />);
diff --git a/webui/src/tests/nanobot-client.test.ts b/webui/src/tests/nanobot-client.test.ts
index 3db7edc0d..c917d2a80 100644
--- a/webui/src/tests/nanobot-client.test.ts
+++ b/webui/src/tests/nanobot-client.test.ts
@@ -630,7 +630,7 @@ describe("NanobotClient", () => {
expect(client.getRunStartedAt("chat-stop")).toBeNull();
expect(client.hasUnsettledRun("chat-stop")).toBe(false);
expect(client.isRunCompleted("chat-stop", "turn-stop")).toBe(true);
- expect(handler).toHaveBeenLastCalledWith("chat-stop", null);
+ expect(handler).toHaveBeenLastCalledWith("chat-stop", expect.objectContaining({ active: false, startedAt: null }));
});
it("preserves durable run clocks and identities through transport reconnect", async () => {
@@ -672,7 +672,7 @@ describe("NanobotClient", () => {
expect(client.getUnsettledRunChatIds()).toEqual([]);
expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(true);
expect(client.isRunCompleted("another-chat", "turn-strip")).toBe(false);
- expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
+ expect(handler).toHaveBeenLastCalledWith("chat-strip", expect.objectContaining({ active: false, startedAt: null }));
client.close();
});
@@ -697,7 +697,7 @@ describe("NanobotClient", () => {
chat_id: "chat-strip",
});
expect(client.getRunStartedAt("chat-strip")).toBeNull();
- expect(handler).toHaveBeenLastCalledWith("chat-strip", null);
+ expect(handler).toHaveBeenLastCalledWith("chat-strip", expect.objectContaining({ active: false, startedAt: null }));
});
it("rejects a completed snapshot when a newer run is not represented", () => {
@@ -1752,7 +1752,7 @@ describe("NanobotClient", () => {
),
).toBe(true);
expect(client.getRunStartedAt("chat-canonical")).toBeNull();
- expect(runHandler).toHaveBeenLastCalledWith("chat-canonical", null);
+ expect(runHandler).toHaveBeenLastCalledWith("chat-canonical", expect.objectContaining({ active: false, startedAt: null }));
const deliveredBeforeLateFrames = chatHandler.mock.calls.length;
lastSocket().fakeMessage({
@@ -1805,19 +1805,22 @@ describe("NanobotClient", () => {
status: "running",
started_at: 12_345,
});
- expect(handler).toHaveBeenCalledWith("chat-status", 12_345);
+ expect(handler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: true, startedAt: 12_345 }));
const lateHandler = vi.fn();
client.onRunStatus(lateHandler);
- expect(lateHandler).toHaveBeenCalledWith("chat-status", 12_345);
+ expect(lateHandler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: true, startedAt: 12_345 }));
lastSocket().fakeMessage({
event: "goal_status",
chat_id: "chat-status",
status: "idle",
});
- expect(handler).toHaveBeenCalledWith("chat-status", null);
- expect(lateHandler).toHaveBeenCalledWith("chat-status", null);
+ expect(handler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
+ expect(lateHandler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
+ const idleSubscriber = vi.fn();
+ client.onRunStatus(idleSubscriber);
+ expect(idleSubscriber).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
});
it("records goal_state per chat_id without an onChat subscriber", () => {
@@ -2567,6 +2570,7 @@ describe("binary attachment transport", () => {
const delivery = client.sendAttachments("chat", "look", [
{ data_url: "data:text/plain;base64,eA==", name: "note.txt" },
], { turnId: "slow-upload" });
+ expect(client.getRunState("chat")).toMatchObject({ active: true, startedAt: null });
await vi.advanceTimersByTimeAsync(80_000);
expect(socket.sent.some((frame) => frame.includes("slow-ref"))).toBe(true);
socket.fakeMessage({ event: "message_accepted", chat_id: "chat", turn_id: "slow-upload" });
@@ -2637,6 +2641,7 @@ describe("binary attachment transport", () => {
upload: { path: "/api/attachments", token: "cap" } });
const draft = [{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }];
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("401");
+ expect(client.getRunState("chat").active).toBe(false);
expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
expect(draft[0].data_url).toBe("data:text/plain;base64,eA==");
fetchMock.mockImplementation(async () => {
@@ -2644,6 +2649,7 @@ describe("binary attachment transport", () => {
return Response.json({ reference: "old-connection-ref" });
});
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("Connection changed");
+ expect(client.getRunState("chat").active).toBe(false);
expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
} finally { client.close(); vi.unstubAllGlobals(); }
});
diff --git a/webui/src/tests/stream-client.ts b/webui/src/tests/stream-client.ts
new file mode 100644
index 000000000..0ebac3475
--- /dev/null
+++ b/webui/src/tests/stream-client.ts
@@ -0,0 +1,25 @@
+import { NanobotClient } from "@/lib/nanobot-client";
+import type { InboundEvent } from "@/lib/types";
+
+/** Real lifecycle and dispatch with an in-memory transport. */
+export function createStreamClient() {
+ const socket = {
+ readyState: 1,
+ onopen: null as (() => void) | null,
+ onmessage: null as ((event: MessageEvent) => void) | null,
+ send() {},
+ close() {},
+ };
+ const client = new NanobotClient({
+ url: "ws://test", reconnect: false,
+ socketFactory: () => socket as unknown as WebSocket,
+ });
+ client.connect();
+ socket.onopen?.();
+ return {
+ client,
+ receive(event: InboundEvent) {
+ socket.onmessage?.({ data: JSON.stringify(event) } as MessageEvent);
+ },
+ };
+}
diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsx
index 7b6b681ab..e6f4653be 100644
--- a/webui/src/tests/thread-shell.test.tsx
+++ b/webui/src/tests/thread-shell.test.tsx
@@ -23,6 +23,7 @@ import type {
WebuiThreadPersistedPayload,
} from "@/lib/types";
import { canonicalThreadPayload } from "./thread-test-payload";
+import { createStreamClient } from "./stream-client";
const HERO_GREETING_PATTERN =
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
@@ -35,65 +36,16 @@ async function openMessageActions(text: string): Promise<HTMLElement> {
}
function makeClient() {
+ const { client: lifecycle, receive } = createStreamClient();
const errorHandlers = new Set<(err: StreamError) => void>();
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
- const chatHandlers = new Map<string, Set<(ev: import("@/lib/types").InboundEvent) => void>>();
const runtimeModelHandlers = new Set<
(modelName: string | null, modelPreset?: string | null) => void
>();
const sessionUpdateHandlers = new Set<(chatId: string, scope?: string) => void>();
- const runStatusHandlers = new Set<(chatId: string, startedAt: number | null) => void>();
- const runCompletionHandlers = new Set<(chatId: string) => void>();
- const runStartedAtByChatId = new Map<string, number>();
- const runGenerationByChatId = new Map<string, number>();
- const latestRunTurnIdByChatId = new Map<string, string>();
- const closedRunTurnIdsByChatId = new Map<string, Set<string>>();
- const completedTurnIdsByChatId = new Map<string, Set<string>>();
- const goalStateByChatId = new Map<string, import("@/lib/types").GoalStateWsPayload>();
let status: ConnectionStatus = "open";
- const advanceRunGeneration = (chatId: string, turnId?: string) => {
- runGenerationByChatId.set(chatId, (runGenerationByChatId.get(chatId) ?? 0) + 1);
- if (turnId) latestRunTurnIdByChatId.set(chatId, turnId);
- else latestRunTurnIdByChatId.delete(chatId);
- };
- const sendMessage = vi.fn((
- chatId: string,
- _content: string,
- _media?: unknown,
- options?: { turnId?: string; startsNewRun?: boolean },
- ) => {
- if (options?.turnId && options.startsNewRun !== false) {
- advanceRunGeneration(chatId, options.turnId);
- }
- });
- const canReconcileCanonicalCompletion = vi.fn((
- chatId: string,
- expectedRunGeneration: number,
- completedTurnIds: readonly string[],
- snapshot?: CanonicalRunSnapshot,
- ) => {
- const existingFences = completedTurnIdsByChatId.get(chatId);
- const prospectiveFences = new Set(completedTurnIds);
- const observedTurnIds = new Set(snapshot?.observedTurnIds ?? []);
- const isRepresented = (turnId: string) => (
- prospectiveFences.has(turnId)
- || existingFences?.has(turnId) === true
- || (
- snapshot?.completionIdsProvided !== true
- && snapshot?.hasPendingToolCalls === false
- && snapshot?.activeTurnId !== turnId
- && observedTurnIds.has(turnId)
- )
- );
- const currentGeneration = runGenerationByChatId.get(chatId) ?? 0;
- const latestTurnId = latestRunTurnIdByChatId.get(chatId);
- if (latestTurnId && !closedRunTurnIdsByChatId.get(chatId)?.has(latestTurnId)
- && !isRepresented(latestTurnId)) return false;
- return (
- currentGeneration === expectedRunGeneration
- || (typeof latestTurnId === "string" && isRepresented(latestTurnId))
- );
- });
+ const sendMessage = vi.fn(lifecycle.sendMessage.bind(lifecycle));
+ const canReconcileCanonicalCompletion = vi.fn(lifecycle.canReconcileCanonicalCompletion.bind(lifecycle));
const reconcileCanonicalCompletion = vi.fn((
chatId: string,
expectedRunGeneration: number,
@@ -108,12 +60,7 @@ function makeClient() {
)) {
return false;
}
- const fences = completedTurnIdsByChatId.get(chatId) ?? new Set<string>();
- for (const turnId of completedTurnIds) fences.add(turnId);
- completedTurnIdsByChatId.set(chatId, fences);
- const hadClock = runStartedAtByChatId.delete(chatId);
- if (hadClock) for (const h of runStatusHandlers) h(chatId, null);
- return true;
+ return lifecycle.reconcileCanonicalCompletion(chatId, expectedRunGeneration, completedTurnIds, snapshot);
});
return {
get status() {
@@ -127,17 +74,8 @@ function makeClient() {
statusHandlers.delete(handler);
};
},
- onRunStatus: (handler: (chatId: string, startedAt: number | null) => void) => {
- runStatusHandlers.add(handler);
- for (const [chatId, startedAt] of runStartedAtByChatId) handler(chatId, startedAt);
- return () => {
- runStatusHandlers.delete(handler);
- };
- },
- onRunCompletion: (handler: (chatId: string) => void) => {
- runCompletionHandlers.add(handler);
- return () => { runCompletionHandlers.delete(handler); };
- },
+ onRunStatus: lifecycle.onRunStatus.bind(lifecycle),
+ onRunCompletion: lifecycle.onRunCompletion.bind(lifecycle),
onRuntimeModelUpdate: (
handler: (modelName: string | null, modelPreset?: string | null) => void,
) => {
@@ -146,40 +84,20 @@ function makeClient() {
runtimeModelHandlers.delete(handler);
};
},
- getRunStartedAt: (chatId: string) => runStartedAtByChatId.get(chatId) ?? null,
- getRunTurnId: (chatId: string) => latestRunTurnIdByChatId.get(chatId) ?? null,
- isRunCompleted: (chatId: string, turnId: string) => (
- closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true
- || completedTurnIdsByChatId.get(chatId)?.has(turnId) === true
- ),
- finishRunLocally: vi.fn((chatId: string) => {
- runStartedAtByChatId.delete(chatId);
- latestRunTurnIdByChatId.delete(chatId);
- }),
- hasUnsettledRun: () => false,
- getRunGeneration: (chatId: string) => runGenerationByChatId.get(chatId) ?? 0,
+ getRunState: lifecycle.getRunState.bind(lifecycle),
+ restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle),
+ getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle),
+ getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle),
+ isRunCompleted: lifecycle.isRunCompleted.bind(lifecycle),
+ finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)),
+ hasUnsettledRun: lifecycle.hasUnsettledRun.bind(lifecycle),
+ getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
canReconcileCanonicalCompletion,
reconcileCanonicalCompletion,
- fenceCanonicalCompletedTurns: (chatId: string, turnIds: readonly string[]) => {
- const fences = completedTurnIdsByChatId.get(chatId) ?? new Set<string>();
- for (const turnId of turnIds) fences.add(turnId);
- completedTurnIdsByChatId.set(chatId, fences);
- },
- getGoalState: (chatId: string) => goalStateByChatId.get(chatId),
- onTranscript(chatId: string, handler: (ev: import("@/lib/types").InboundEvent) => void) {
- return this.onChat(chatId, handler);
- },
- onChat: (chatId: string, handler: (ev: import("@/lib/types").InboundEvent) => void) => {
- let handlers = chatHandlers.get(chatId);
- if (!handlers) {
- handlers = new Set();
- chatHandlers.set(chatId, handlers);
- }
- handlers.add(handler);
- return () => {
- handlers?.delete(handler);
- };
- },
+ fenceCanonicalCompletedTurns: lifecycle.fenceCanonicalCompletedTurns.bind(lifecycle),
+ getGoalState: lifecycle.getGoalState.bind(lifecycle),
+ onTranscript: lifecycle.onTranscript.bind(lifecycle),
+ onChat: lifecycle.onChat.bind(lifecycle),
onError: (handler: (err: StreamError) => void) => {
errorHandlers.add(handler);
return () => {
@@ -193,48 +111,16 @@ function makeClient() {
};
},
_emitError(err: StreamError) {
- if (err.kind !== "model_request_failed" && err.chatId && err.turnId) {
- if (latestRunTurnIdByChatId.get(err.chatId) === err.turnId) {
- latestRunTurnIdByChatId.delete(err.chatId);
- const hadClock = runStartedAtByChatId.delete(err.chatId);
- if (hadClock) for (const h of runStatusHandlers) h(err.chatId, null);
- }
- }
+ if (err.chatId && err.turnId) receive({
+ event: "error", chat_id: err.chatId, turn_id: err.turnId, detail: err.kind,
+ });
for (const h of errorHandlers) h(err);
},
_emitStatus(nextStatus: ConnectionStatus) {
status = nextStatus;
for (const h of statusHandlers) h(status);
},
- _emitChat(chatId: string, ev: import("@/lib/types").InboundEvent) {
- const turnId = "turn_id" in ev && typeof ev.turn_id === "string" ? ev.turn_id : null;
- if (turnId && completedTurnIdsByChatId.get(chatId)?.has(turnId)) return;
- if (
- ev.event === "goal_status"
- && ev.status === "running"
- && typeof ev.started_at === "number"
- ) {
- advanceRunGeneration(chatId, ev.turn_id);
- runStartedAtByChatId.set(chatId, ev.started_at);
- for (const h of runStatusHandlers) h(chatId, ev.started_at);
- } else if (
- (ev.event === "goal_status" && ev.status === "idle")
- || ev.event === "turn_end"
- ) {
- if (turnId) {
- const closed = closedRunTurnIdsByChatId.get(chatId) ?? new Set<string>();
- closed.add(turnId);
- closedRunTurnIdsByChatId.set(chatId, closed);
- }
- runStartedAtByChatId.delete(chatId);
- for (const h of runStatusHandlers) h(chatId, null);
- for (const h of runCompletionHandlers) h(chatId);
- }
- if (ev.event === "goal_state") {
- goalStateByChatId.set(chatId, ev.goal_state);
- }
- for (const h of chatHandlers.get(chatId) ?? []) h(ev);
- },
+ _emitChat(_chatId: string, ev: import("@/lib/types").InboundEvent) { receive(ev); },
_emitRuntimeModelUpdate(modelName: string | null, modelPreset?: string | null) {
for (const h of runtimeModelHandlers) h(modelName, modelPreset);
},
@@ -3300,7 +3186,13 @@ describe("ThreadShell", () => {
detail: "message_rejected",
}));
- act(() => client._emitSessionUpdate("empty-reset-chat", "thread"));
+ act(() => {
+ client._emitError({
+ kind: "turn_rejected", chatId: "empty-reset-chat",
+ turnId: client.sendMessage.mock.calls[0][3]!.turnId!,
+ });
+ client._emitSessionUpdate("empty-reset-chat", "thread");
+ });
await waitFor(() => expect(historyCalls).toBe(2));
await waitFor(() =>
@@ -5357,6 +5249,24 @@ describe("ThreadShell", () => {
await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
+ expect(screen.getByRole("button", { name: "停止响应" })).toBeInTheDocument();
+ const nextTurnId = client.getRunTurnId("chat-model-failure")!;
+ act(() => {
+ client._emitChat("chat-model-failure", {
+ event: "goal_status", chat_id: "chat-model-failure", turn_id: nextTurnId,
+ status: "running", started_at: 1_700_000_000,
+ });
+ client._emitChat("chat-model-failure", {
+ event: "delta", chat_id: "chat-model-failure", turn_id: nextTurnId,
+ text: "New request is running",
+ });
+ });
+ expect(await screen.findByText("New request is running")).toBeVisible();
+ expect(client.getRunState("chat-model-failure")).toMatchObject({ active: true, startedAt: 1_700_000_000 });
+ act(() => client._emitChat("chat-model-failure", {
+ event: "turn_end", chat_id: "chat-model-failure", turn_id: nextTurnId,
+ }));
+ expect(screen.queryByRole("button", { name: "停止响应" })).not.toBeInTheDocument();
});
it("moves a correlated delivery error from the banner into the failed message tooltip", async () => {
@@ -5881,7 +5791,7 @@ describe("ThreadShell", () => {
expect(client.sendMessage).toHaveBeenCalledWith("resuming-chat", "/stop");
});
- it("allows a new turn after a completed recovery state", async () => {
+ it.each(["awaiting_user", "failed", "recovered"] as const)("allows a new turn after a %s recovery state", async (status) => {
const client = makeClient();
render(wrap(
client,
@@ -5898,7 +5808,7 @@ describe("ThreadShell", () => {
event: "recovery_state",
chat_id: "recovered-chat",
recovery_id: "recovery-1",
- status: "recovered",
+ status,
});
});
diff --git a/webui/src/tests/turn-completion.test.tsx b/webui/src/tests/turn-completion.test.tsx
index 4e5f1377d..d09c4697c 100644
--- a/webui/src/tests/turn-completion.test.tsx
+++ b/webui/src/tests/turn-completion.test.tsx
@@ -45,6 +45,75 @@ function setup() {
}
describe("completed turn event ordering", () => {
+ it("does not restore busy state from pending history delivered after completion", () => {
+ const { socket, client, wrapper, running } = setup();
+ const staleHistory: UIMessage[] = [{
+ id: "persisted-user", role: "user", content: "original request", turnId: TURN_ID, createdAt: 0,
+ }];
+ const { result, rerender, unmount } = renderHook(
+ ({ pending, history, active }: { pending: boolean; history: UIMessage[]; active: string | null }) =>
+ useNanobotStream(CHAT_ID, history, pending, undefined, undefined, [], undefined, active),
+ { wrapper, initialProps: { pending: false, history: EMPTY_MESSAGES, active: null as string | null } },
+ );
+ act(() => {
+ socket.receive(running);
+ socket.receive({ event: "stream_end", chat_id: CHAT_ID, turn_id: TURN_ID, text: "done" });
+ socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID });
+ });
+ expect(result.current.isStreaming).toBe(false);
+ rerender({ pending: true, history: staleHistory, active: TURN_ID });
+ expect(result.current.isStreaming).toBe(false);
+ expect(client.hasUnsettledRun(CHAT_ID)).toBe(false);
+ act(() => socket.receive({
+ ...running, turn_id: "next-turn", started_at: 1_700_000_100,
+ }));
+ rerender({ pending: false, history: staleHistory, active: null });
+ expect(result.current.isStreaming).toBe(true);
+ expect(client.getRunTurnId(CHAT_ID)).toBe("next-turn");
+ unmount();
+ client.close();
+ });
+
+ it("shares optimistic activity before a gateway start clock exists", () => {
+ const { socket, client, wrapper } = setup();
+ const status = vi.fn();
+ client.onRunStatus(status);
+ const { result, unmount } = renderHook(
+ () => useNanobotStream(CHAT_ID, EMPTY_MESSAGES), { wrapper },
+ );
+ act(() => { result.current.send("new request"); });
+ expect(result.current.isStreaming).toBe(true);
+ expect(result.current.runStartedAt).toBeNull();
+ expect(status).toHaveBeenLastCalledWith(CHAT_ID,
+ expect.objectContaining({ active: true, startedAt: null }));
+ const turnId = client.getRunTurnId(CHAT_ID)!;
+ act(() => socket.receive({
+ event: "turn_end", chat_id: CHAT_ID, turn_id: turnId,
+ }));
+ expect(result.current.isStreaming).toBe(false);
+ expect(status).toHaveBeenLastCalledWith(CHAT_ID,
+ expect.objectContaining({ active: false, startedAt: null }));
+ unmount();
+ client.close();
+ });
+
+ it("restores the canonical owner rather than a steering input at the history tail", () => {
+ const { socket, client, wrapper } = setup();
+ const initial: UIMessage[] = [{
+ id: "steering", role: "user", content: "additional guidance", turnId: "input-2", createdAt: Date.now(),
+ }];
+ const { result, unmount } = renderHook(
+ () => useNanobotStream(CHAT_ID, initial, true, undefined, undefined, [], undefined, TURN_ID), { wrapper },
+ );
+ expect(result.current.isStreaming).toBe(true);
+ expect(client.getRunTurnId(CHAT_ID)).toBe(TURN_ID);
+ act(() => socket.receive({ event: "turn_end", chat_id: CHAT_ID, turn_id: TURN_ID }));
+ expect(result.current.isStreaming).toBe(false);
+ expect(client.hasUnsettledRun(CHAT_ID)).toBe(false);
+ unmount();
+ client.close();
+ });
+
it.each(["turn_end", "idle", "stop", "snapshot", "idle snapshot"] as const)(
"keeps %s terminal despite late lifecycle and ownership frames",
(terminal) => {
diff --git a/webui/src/tests/useNanobotStream.test.tsx b/webui/src/tests/useNanobotStream.test.tsx
index d907ba21d..b0f71d8e8 100644
--- a/webui/src/tests/useNanobotStream.test.tsx
+++ b/webui/src/tests/useNanobotStream.test.tsx
@@ -6,16 +6,16 @@ import { useNanobotStream } from "@/hooks/useNanobotStream";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
-import type { StreamError } from "@/lib/nanobot-client";
+import type { NanobotClient, StreamError } from "@/lib/nanobot-client";
import type {
ConnectionStatus,
- GoalStateWsPayload,
InboundEvent,
UIMediaAttachment,
UIMessage,
} from "@/lib/types";
import { ClientProvider } from "@/providers/ClientProvider";
import projectionFixture from "./fixtures/live-replay-event-projection.json";
+import { createStreamClient } from "./stream-client";
const EMPTY_MESSAGES: UIMessage[] = [];
@@ -72,112 +72,64 @@ function normalizeProjection(messages: UIMessage[]): Array<Record<string, unknow
}
function fakeClient() {
- const handlers = new Map<string, Set<(ev: InboundEvent) => void>>();
+ const { client: lifecycle, receive } = createStreamClient();
const statusHandlers = new Set<(status: ConnectionStatus) => void>();
- const runStatusHandlers = new Set<(chatId: string, startedAt: number | null) => void>();
const errorHandlers = new Set<(error: StreamError) => void>();
- const runStartedAtByChatId = new Map<string, number>();
- const unsettledRunByChatId = new Map<string, boolean>();
- const goalStateByChatId = new Map<string, GoalStateWsPayload>();
const requestMutation = vi.fn().mockResolvedValue({});
let status: ConnectionStatus = "open";
- function recordGoalStatusForRunStrip(chatId: string, ev: InboundEvent) {
- if (ev.event === "turn_end") {
- runStartedAtByChatId.delete(chatId);
- return;
- }
- if (ev.event !== "goal_status") return;
- if (ev.status === "running" && typeof ev.started_at === "number") {
- runStartedAtByChatId.set(chatId, ev.started_at);
- } else {
- runStartedAtByChatId.delete(chatId);
- }
- }
-
- function recordGoalStateSnapshot(chatId: string, ev: InboundEvent) {
- if (ev.event === "goal_state") {
- goalStateByChatId.set(chatId, ev.goal_state);
- return;
- }
- if (ev.event === "turn_end" && ev.goal_state != null && typeof ev.goal_state === "object") {
- goalStateByChatId.set(chatId, ev.goal_state);
- }
- }
-
return {
client: {
- get status() {
- return status;
- },
+ get status() { return status; },
defaultChatId: null as string | null,
onStatus(handler: (nextStatus: ConnectionStatus) => void) {
statusHandlers.add(handler);
handler(status);
return () => statusHandlers.delete(handler);
},
- onRunStatus(handler: (chatId: string, startedAt: number | null) => void) {
- runStatusHandlers.add(handler);
- for (const [chatId, startedAt] of runStartedAtByChatId) handler(chatId, startedAt);
- return () => runStatusHandlers.delete(handler);
- },
+ onRunStatus: lifecycle.onRunStatus.bind(lifecycle),
+ getRunState: lifecycle.getRunState.bind(lifecycle),
+ getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
+ restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle),
+ getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle),
+ getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle),
+ getGoalState: lifecycle.getGoalState.bind(lifecycle),
+ hasUnsettledRun: lifecycle.hasUnsettledRun.bind(lifecycle),
+ onTranscript: lifecycle.onTranscript.bind(lifecycle),
onError(handler: (error: StreamError) => void) {
errorHandlers.add(handler);
return () => errorHandlers.delete(handler);
},
- getRunStartedAt(chatId: string) {
- const v = runStartedAtByChatId.get(chatId);
- return v === undefined ? null : v;
- },
- getRunTurnId() {
- return null;
- },
- getGoalState(chatId: string) {
- return goalStateByChatId.get(chatId);
- },
- hasUnsettledRun(chatId: string) {
- return unsettledRunByChatId.get(chatId) === true;
- },
- onTranscript(chatId: string, h: (ev: InboundEvent) => void) {
- let set = handlers.get(chatId);
- if (!set) {
- set = new Set();
- handlers.set(chatId, set);
- }
- set.add(h);
- return () => set!.delete(h);
- },
- sendMessage: vi.fn(),
- sendAttachments: vi.fn().mockResolvedValue(undefined),
+ sendMessage: vi.fn(lifecycle.sendMessage.bind(lifecycle)),
+ sendAttachments: vi.fn(async (...args: Parameters<NanobotClient["sendAttachments"]>) => {
+ lifecycle.sendMessage(args[0], args[1], undefined, args[3]);
+ }),
requestMutation,
- finishRunLocally: vi.fn(),
- newChat: vi.fn(),
- forkChat: vi.fn(),
- attach: vi.fn(),
- connect: vi.fn(),
- close: vi.fn(),
- updateUrl: vi.fn(),
- },
- emit(chatId: string, ev: InboundEvent) {
- recordGoalStatusForRunStrip(chatId, ev);
- recordGoalStateSnapshot(chatId, ev);
- const set = handlers.get(chatId);
- set?.forEach((h) => h(ev));
+ finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)),
+ newChat: vi.fn(), forkChat: vi.fn(), attach: vi.fn(),
+ connect: vi.fn(), close: vi.fn(), updateUrl: vi.fn(),
},
+ emit(_chatId: string, event: InboundEvent) { receive(event); },
emitStatus(nextStatus: ConnectionStatus) {
status = nextStatus;
statusHandlers.forEach((handler) => handler(status));
},
emitRunStatus(chatId: string, startedAt: number | null) {
- if (startedAt === null) runStartedAtByChatId.delete(chatId);
- else runStartedAtByChatId.set(chatId, startedAt);
- runStatusHandlers.forEach((handler) => handler(chatId, startedAt));
+ receive({ event: "goal_status", chat_id: chatId,
+ status: startedAt === null ? "idle" : "running",
+ ...(startedAt !== null ? { started_at: startedAt } : {}),
+ });
},
emitError(error: StreamError) {
+ if (error.chatId && error.turnId) receive({
+ event: "error", chat_id: error.chatId, turn_id: error.turnId,
+ detail: error.kind,
+ });
errorHandlers.forEach((handler) => handler(error));
},
setUnsettled(chatId: string, unsettled: boolean) {
- unsettledRunByChatId.set(chatId, unsettled);
+ if (unsettled) lifecycle.sendMessage(chatId, "pending", undefined, { turnId: "pending-fixture" });
+ else lifecycle.finishRunLocally(chatId);
},
requestMutation,
};
@@ -295,7 +247,7 @@ describe("useNanobotStream", () => {
});
await flushStreamFrame();
act(() => { first.result.current.send("/model", undefined, { sideChannel: true }); });
- const commandTurn = fake.client.sendMessage.mock.calls.at(-1)![3]?.turnId;
+ const commandTurn = fake.client.sendMessage.mock.calls.at(-1)![3]!.turnId!;
first.unmount();
const snapshot = cache.get("checkpoint")!;
expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true);
@@ -808,7 +760,7 @@ describe("useNanobotStream", () => {
});
expect(result.current.isStreaming).toBe(false);
expect(result.current.runStartedAt).toBeNull();
- expect(fake.client.finishRunLocally).toHaveBeenCalledWith("chat-recovery");
+ expect(fake.client.getRunState("chat-recovery").active).toBe(false);
act(() => {
fake.emit("chat-recovery", {
@@ -836,7 +788,7 @@ describe("useNanobotStream", () => {
});
});
expect(result.current.isStreaming).toBe(false);
- expect(fake.client.finishRunLocally).toHaveBeenCalledWith("chat-recovery");
+ expect(fake.client.getRunState("chat-recovery").active).toBe(false);
});
it.each(["awaiting_user", "resuming"] as const)(
@@ -3787,6 +3739,14 @@ describe("live canonical event projection", () => {
for (const event of fixtureCase.live_events) {
act(() => {
+ // Projection fixtures omit lifecycle admission between their turns.
+ if ("turn_id" in event && event.turn_id
+ && fake.client.getRunTurnId(fixtureCase.chat_id) !== event.turn_id) {
+ fake.emit(fixtureCase.chat_id, {
+ event: "goal_status", chat_id: fixtureCase.chat_id,
+ turn_id: event.turn_id, status: "running", started_at: 0,
+ });
+ }
fake.emit(fixtureCase.chat_id, event);
});
}
diff --git a/webui/src/tests/useReconnectRuns.test.tsx b/webui/src/tests/useReconnectRuns.test.tsx
index c005feab4..a1fadbdf7 100644
--- a/webui/src/tests/useReconnectRuns.test.tsx
+++ b/webui/src/tests/useReconnectRuns.test.tsx
@@ -299,8 +299,8 @@ describe("durable run recovery", () => {
running();
sockets[0].receive({ event: "delta", chat_id: "inactive", turn_id: "turn-old", text: "The" });
const cachedAtCompletion: WebuiThreadPersistedPayload[] = [];
- client.onRunStatus((chatId, startedAt) => {
- if (startedAt === null) cachedAtCompletion.push(webuiThreadCache.get(`websocket:${chatId}`)!);
+ client.onRunStatus((chatId, state) => {
+ if (!state.active) cachedAtCompletion.push(webuiThreadCache.get(`websocket:${chatId}`)!);
});
await reopen();