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

This commit is contained in:
chengyongru authored and GitHub committed 2026-10-24 00:43:34 +08:00
1 parent 3d0f8feb77
commit 5ae49a43e7
13 files changed
+378 -374

No files matched your search

+17 -5
View File
@@ -125,11 +125,23 @@ for (const width of [1440, 390]) {
{ event: "stream_end", ...base, stream_id: "legacy", turn_seq: 5, text: "First last" }, { event: "stream_end", ...base, stream_id: "legacy", turn_seq: 5, text: "First last" },
{ event: "turn_end", ...base, turn_seq: 6 }, { event: "turn_end", ...base, turn_seq: 6 },
]); ]);
await expect(page.getByText("First", { exact: true })).toHaveCount(1); const first = page.getByText("First", { exact: true });
await expect(page.getByText("last", { exact: true })).toHaveCount(1); const last = page.getByText("last", { exact: true });
const texts = await page.locator("[data-thread-display-unit]").allTextContents(); await expect(first).toHaveCount(1);
expect(texts.findIndex((text) => text.includes("First"))).toBeLessThan(texts.findIndex((text) => text.includes("Searching the web"))); await expect(last).toHaveCount(1);
expect(texts.findIndex((text) => text.includes("Searching the web"))).toBeLessThan(texts.findIndex((text) => text.includes("last"))); 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([]); expect(errors).toEqual([]);
}); });
+2 -2
View File
@@ -2254,8 +2254,8 @@ function Shell({
}, [client, onModelNameChange]); }, [client, onModelNameChange]);
useEffect(() => { useEffect(() => {
return client.onRunStatus((chatId, startedAt) => { return client.onRunStatus((chatId, state) => {
if (startedAt != null) { if (state.active) {
const nextRunning = new Set(runningChatIdsRef.current); const nextRunning = new Set(runningChatIdsRef.current);
nextRunning.add(chatId); nextRunning.add(chatId);
runningChatIdsRef.current = nextRunning; runningChatIdsRef.current = nextRunning;
+3 -7
View File
@@ -691,15 +691,11 @@ export function ThreadShell({
[displayMessages], [displayMessages],
); );
const currentGoalState = messagesReady ? goalState : undefined; const currentGoalState = messagesReady ? goalState : undefined;
// Decision states freeze the interrupted turn and hand the next action to // Recovery decisions gate queued input, not the ledger-owned run state.
// the recovery notice. ``resuming`` remains active; ``recovered`` is only
// historical metadata and must not suppress a later normal turn.
const recoveryNeedsDecision = recoveryState?.status === "awaiting_user" const recoveryNeedsDecision = recoveryState?.status === "awaiting_user"
|| recoveryState?.status === "failed"; || recoveryState?.status === "failed";
const currentRunStartedAt = messagesReady && !recoveryNeedsDecision ? runStartedAt : null; const currentRunStartedAt = messagesReady ? runStartedAt : null;
const turnActive = messagesReady const turnActive = messagesReady && isStreaming;
&& !recoveryNeedsDecision
&& (isStreaming || currentRunStartedAt !== null);
const restoredViewportTurnId = useMemo( const restoredViewportTurnId = useMemo(
() => turnActive ? latestActiveTurnId(displayMessages, currentRunStartedAt) : null, () => turnActive ? latestActiveTurnId(displayMessages, currentRunStartedAt) : null,
[currentRunStartedAt, displayMessages, turnActive], [currentRunStartedAt, displayMessages, turnActive],
+20 -83
View File
@@ -144,6 +144,7 @@ export function useNanobotStream(
onStreamDetach?: (messages: UIMessage[]) => void, onStreamDetach?: (messages: UIMessage[]) => void,
completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS, completedTurnIds: readonly string[] = EMPTY_COMPLETED_TURN_IDS,
history?: { key: string | null; cache?: ThreadMessageCache }, history?: { key: string | null; cache?: ThreadMessageCache },
historyActiveTurnId: string | null = null,
): { ): {
messages: UIMessage[]; messages: UIMessage[];
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */ /** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
@@ -189,7 +190,13 @@ export function useNanobotStream(
const threadVisible = useThreadVisibility(); const threadVisible = useThreadVisibility();
const threadVisibleRef = useRef(threadVisible); const threadVisibleRef = useRef(threadVisible);
threadVisibleRef.current = 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 [messages, setRenderedMessages] = useState<UIMessage[]>(initialTranscript.messages);
const messagesRef = useRef(messages); const messagesRef = useRef(messages);
// Keep received state ahead of React's batched render: navigation can unmount // 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) !message.turnId || !completedInitialTurns.has(message.turnId)
))); )));
}, [completedTurnIds, initialMessages]); }, [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 [retryStatus, setRetryStatus] = useState<RetryStatus | null>(null);
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined); const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null); const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
@@ -312,14 +314,7 @@ export function useNanobotStream(
return nextMessages; return nextMessages;
}); });
const remainingStartedAt = client.getRunStartedAt(chatId); if (!client.getRunState(chatId).active) {
const hasRemainingRun = (
remainingStartedAt !== null
|| client.hasUnsettledRun(chatId)
);
setRunStartedAt(remainingStartedAt);
setIsStreaming(hasRemainingRun);
if (!hasRemainingRun) {
transcriptRef.current.projection = { transcriptRef.current.projection = {
...transcriptRef.current.projection, ...transcriptRef.current.projection,
suppressUntilTurnEnd: false, suppressUntilTurnEnd: false,
@@ -475,13 +470,10 @@ export function useNanobotStream(
useEffect(() => { useEffect(() => {
if (!chatId) return; if (!chatId) return;
return client.onRunStatus((runChatId, startedAt) => { return client.onRunStatus((runChatId, state) => {
if (runChatId !== chatId) return; if (runChatId !== chatId) return;
if (startedAt !== null) { setRunState(state);
setRunStartedAt(startedAt); if (state.active) return;
setIsStreaming(true);
return;
}
flushPendingStreamEvents(); flushPendingStreamEvents();
setMessages((prev) => { setMessages((prev) => {
const settled = prev.map((message) => ( const settled = prev.map((message) => (
@@ -493,8 +485,6 @@ export function useNanobotStream(
); );
return settled; return settled;
}); });
setRunStartedAt(null);
setIsStreaming(false);
}); });
}, [chatId, client, clearActivitySegment, flushPendingStreamEvents, setMessages]); }, [chatId, client, clearActivitySegment, flushPendingStreamEvents, setMessages]);
@@ -502,18 +492,11 @@ export function useNanobotStream(
// ``initialMessages`` update: a brand-new chat can receive an empty/404 // ``initialMessages`` update: a brand-new chat can receive an empty/404
// history response after the optimistic first message has already rendered. // history response after the optimistic first message has already rendered.
useEffect(() => { useEffect(() => {
const restoredRunStartedAt = chatId ? client.getRunStartedAt(chatId) : null;
transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey); transcriptRef.current = createTranscript(initialMessages, chatId ? messageCache?.get(chatId) : undefined, historyKey);
setMessages(transcriptRef.current.messages); setMessages(transcriptRef.current.messages);
setMessageScope({ chatId, historyKey, client }); setMessageScope({ chatId, historyKey, client });
setIsStreaming( setRunState(chatId ? client.getRunState(chatId) : null);
initialStreaming
|| hasPendingToolCalls
|| transcriptRef.current.paging.hasPendingToolCalls
|| restoredRunStartedAt !== null,
);
setStreamError(null); setStreamError(null);
setRunStartedAt(restoredRunStartedAt);
setRetryStatus(null); setRetryStatus(null);
setGoalState(chatId ? client.getGoalState(chatId) : undefined); setGoalState(chatId ? client.getGoalState(chatId) : undefined);
setRecoveryState(null); setRecoveryState(null);
@@ -522,8 +505,9 @@ export function useNanobotStream(
}, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]); }, [chatId, client, historyKey, clearActivitySegment, clearPendingStreamWork, setMessages]);
useEffect(() => { useEffect(() => {
if (hasPendingToolCalls) setIsStreaming(true); if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return;
}, [hasPendingToolCalls]); client.restorePendingRun(chatId, historyRunGenerationRef.current.generation, historyActiveTurnId);
}, [chatId, client, hasPendingToolCalls, historyActiveTurnId, initialStreaming]);
const applyProjectionEvent = useCallback(( const applyProjectionEvent = useCallback((
event: ThreadProjectionEvent, event: ThreadProjectionEvent,
@@ -581,15 +565,9 @@ export function useNanobotStream(
if (ownRead && chatId && canonical) { if (ownRead && chatId && canonical) {
if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation, if (accepted && settle && client.reconcileCanonicalCompletion(chatId, generation,
canonical.completedTurnIds, canonical.snapshot)) { canonical.completedTurnIds, canonical.snapshot)) {
setIsStreaming(false);
setRunStartedAt(null);
setRetryStatus(null); setRetryStatus(null);
} else client.fenceCanonicalCompletedTurns(chatId, canonical.completedTurnIds); } 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); const cached = webuiThreadCache.get(historyKey);
if (cached && owner.paging.version === 0) install(cached, false, true); if (cached && owner.paging.version === 0) install(cached, false, true);
@@ -703,7 +681,6 @@ export function useNanobotStream(
flushPendingStreamEvents(); flushPendingStreamEvents();
closeActiveAssistantStream(); closeActiveAssistantStream();
clearActivitySegment(); clearActivitySegment();
setIsStreaming(true);
setMessages((prev) => { setMessages((prev) => {
const next = appendProjectedSessionInput(prev, ev); const next = appendProjectedSessionInput(prev, ev);
if (next !== prev) transcriptRef.current.registerInput(next[next.length - 1]); if (next !== prev) transcriptRef.current.registerInput(next[next.length - 1]);
@@ -741,10 +718,6 @@ export function useNanobotStream(
transcriptRef.current.registerInput(row); transcriptRef.current.registerInput(row);
return [...prev, 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; return;
} }
const sideChannelEvent = isSideChannelEvent(ev); const sideChannelEvent = isSideChannelEvent(ev);
@@ -767,7 +740,6 @@ export function useNanobotStream(
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
const chunk = typeof ev.text === "string" ? ev.text : ""; const chunk = typeof ev.text === "string" ? ev.text : "";
if (!chunk) return; if (!chunk) return;
setIsStreaming(true);
pendingStreamEventsRef.current.push({ pendingStreamEventsRef.current.push({
kind: "delta", kind: "delta",
text: chunk, text: chunk,
@@ -784,7 +756,6 @@ export function useNanobotStream(
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return; if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
const chunk = ev.text; const chunk = ev.text;
if (!chunk) return; if (!chunk) return;
setIsStreaming(true);
pendingStreamEventsRef.current.push({ pendingStreamEventsRef.current.push({
kind: "reasoning", kind: "reasoning",
text: chunk, text: chunk,
@@ -800,13 +771,11 @@ export function useNanobotStream(
flushPendingStreamEvents(ev); flushPendingStreamEvents(ev);
if (transcriptRef.current.projection.suppressUntilTurnEnd) return; if (transcriptRef.current.projection.suppressUntilTurnEnd) return;
if (ev.resuming) { if (ev.resuming) {
setIsStreaming(true);
return; return;
} }
// ``stream_end`` closes the current answer segment, not the turn. // ``stream_end`` closes the current answer segment, not the turn.
// Tools and follow-up model segments may still arrive before the // Tools and follow-up model segments may still arrive before the
// definitive ``turn_end`` event. // definitive ``turn_end`` event.
setIsStreaming(true);
return; return;
} }
@@ -824,15 +793,8 @@ export function useNanobotStream(
} }
if (ev.event === "goal_status") { if (ev.event === "goal_status") {
if (ev.status === "running" && typeof ev.started_at === "number") { if (ev.status === "running") setStreamError(null);
setStreamError(null); else setRetryStatus(null);
setRunStartedAt(ev.started_at);
setIsStreaming(true);
} else {
setRunStartedAt(null);
setIsStreaming(false);
setRetryStatus(null);
}
return; return;
} }
@@ -860,7 +822,6 @@ export function useNanobotStream(
: {}), : {}),
...(ev.turn_id ? { turn_id: ev.turn_id } : {}), ...(ev.turn_id ? { turn_id: ev.turn_id } : {}),
}); });
setIsStreaming(true);
} }
return; return;
} }
@@ -870,11 +831,7 @@ export function useNanobotStream(
if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") { if ("goal_state" in ev && ev.goal_state != null && typeof ev.goal_state === "object") {
setGoalState(ev.goal_state); setGoalState(ev.goal_state);
} }
setRunStartedAt(null);
setRetryStatus(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 modelRequestFailed = ev.outcome === "failed" && ev.failure_kind === "model";
const failureAttempts = const failureAttempts =
typeof ev.failure_attempts === "number" typeof ev.failure_attempts === "number"
@@ -917,23 +874,12 @@ export function useNanobotStream(
if (ev.reason === "model_request_failed" || ev.status === "resuming") { if (ev.reason === "model_request_failed" || ev.status === "resuming") {
setStreamError(null); setStreamError(null);
} }
if (ev.status === "resuming") {
setRunStartedAt((current) => current ?? Date.now() / 1000);
setIsStreaming(true);
}
if ( if (
ev.status === "awaiting_user" ev.status === "awaiting_user"
|| ev.status === "recovered" || ev.status === "recovered"
|| ev.status === "failed" || ev.status === "failed"
) { ) {
setRetryStatus(null); 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(); clearPendingStreamWork();
closeActiveAssistantStream(); closeActiveAssistantStream();
clearActivitySegment(); clearActivitySegment();
@@ -949,16 +895,10 @@ export function useNanobotStream(
) { ) {
setStreamError(null); setStreamError(null);
} }
if (ev.recovery_state?.status === "resuming") { if (
setRunStartedAt((current) => current ?? Date.now() / 1000);
setIsStreaming(true);
} else if (
ev.recovery_state?.status === "awaiting_user" ev.recovery_state?.status === "awaiting_user"
|| ev.recovery_state?.status === "failed" || ev.recovery_state?.status === "failed"
) { ) {
setRunStartedAt(null);
setIsStreaming(false);
client.finishRunLocally(chatId);
clearPendingStreamWork(); clearPendingStreamWork();
closeActiveAssistantStream(); closeActiveAssistantStream();
clearActivitySegment(); clearActivitySegment();
@@ -1028,7 +968,7 @@ export function useNanobotStream(
: content; : content;
flushPendingStreamEvents(); flushPendingStreamEvents();
if (finalizeActiveTurn) { if (finalizeActiveTurn) {
setIsStreaming(false); client.finishRunLocally(chatId);
setRetryStatus(null); setRetryStatus(null);
} }
const turnId = crypto.randomUUID(); const turnId = crypto.randomUUID();
@@ -1073,7 +1013,6 @@ export function useNanobotStream(
transcriptRef.current.registerInput(next[next.length - 1]); transcriptRef.current.registerInput(next[next.length - 1]);
return next; return next;
}); });
if (!sideChannel) setIsStreaming(true);
const wireMedia = hasAttachments ? images!.map((i) => i.media) : undefined; const wireMedia = hasAttachments ? images!.map((i) => i.media) : undefined;
const clientOptions = { const clientOptions = {
...options, ...options,
@@ -1099,14 +1038,12 @@ export function useNanobotStream(
const stop = useCallback(() => { const stop = useCallback(() => {
if (!chatId) return; if (!chatId) return;
flushPendingStreamEvents(); flushPendingStreamEvents();
setIsStreaming(false);
setRetryStatus(null); setRetryStatus(null);
setMessages((prev) => { setMessages((prev) => {
const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)); const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
transcriptRef.current.projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled); transcriptRef.current.projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled);
return settled; return settled;
}); });
setRunStartedAt(null);
client.finishRunLocally(chatId); client.finishRunLocally(chatId);
client.sendMessage(chatId, "/stop"); client.sendMessage(chatId, "/stop");
}, [chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages]); }, [chatId, clearActivitySegment, client, flushPendingStreamEvents, setMessages]);
+79 -29
View File
@@ -15,6 +15,7 @@ interface ChatRecord {
generation: number; generation: number;
latestTurnId: string | null; latestTurnId: string | null;
effectiveStartedAt: number | null; effectiveStartedAt: number | null;
anonymousActive: boolean;
turns: Map<string, TurnRecord>; turns: Map<string, TurnRecord>;
/** Closed turns permit late inputs, messages, completions and idle. */ /** Closed turns permit late inputs, messages, completions and idle. */
closed: Set<string>; closed: Set<string>;
@@ -47,7 +48,8 @@ export type RunObservation = Readonly<{
}> & ( }> & (
| { kind: "admission" | "input"; owner?: { turnId: string; startedAt?: number } } | { kind: "admission" | "input"; owner?: { turnId: string; startedAt?: number } }
| { kind: "status"; activity: "running" | "idle"; 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 = type Command =
@@ -55,10 +57,11 @@ type Command =
| ({ kind: "written" | "reject" } & TurnRef) | ({ kind: "written" | "reject" } & TurnRef)
| { kind: "transport-lost" } | { kind: "transport-lost" }
| { kind: "local-stop" | "forget"; chatId: string } | { 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 = export type RunEffect =
| { kind: "run-status"; chatId: string; startedAt: number | null } | { kind: "run-status"; chatId: string; state: RunState }
| { kind: "completion"; chatId: string } | { kind: "completion"; chatId: string }
| ({ kind: "discard-send" } & TurnRef) | ({ kind: "discard-send" } & TurnRef)
| { kind: "prune-inbound"; chatId: string; turnIds: readonly string[] }; | { kind: "prune-inbound"; chatId: string; turnIds: readonly string[] };
@@ -68,7 +71,8 @@ interface ObservationResult {
effects: readonly RunEffect[]; effects: readonly RunEffect[];
} }
interface RunView { export interface RunState {
active: boolean;
generation: number; generation: number;
latestTurnId: string | null; latestTurnId: string | null;
startedAt: number | null; startedAt: number | null;
@@ -81,9 +85,10 @@ const COMPLETED_TURN_FENCE_MAX = 256;
export class ClientRunLedger { export class ClientRunLedger {
private chats = new Map<string, ChatRecord>(); private chats = new Map<string, ChatRecord>();
view(chatId: string): RunView { view(chatId: string): RunState {
const chat = this.chats.get(chatId); const chat = this.chats.get(chatId);
return { return {
active: chat?.anonymousActive === true || chat?.effectiveStartedAt != null || this.hasOpenTurn(chat),
generation: chat?.generation ?? 0, generation: chat?.generation ?? 0,
latestTurnId: chat?.latestTurnId ?? null, latestTurnId: chat?.latestTurnId ?? null,
startedAt: chat?.effectiveStartedAt ?? null, startedAt: chat?.effectiveStartedAt ?? null,
@@ -100,15 +105,13 @@ export class ClientRunLedger {
return this.chats.get(chatId)?.turns.get(turnId)?.delivery != null; return this.chats.get(chatId)?.turns.get(turnId)?.delivery != null;
} }
activeClocks(): readonly Readonly<{ chatId: string; startedAt: number }>[] { states(): readonly Readonly<{ chatId: string; state: RunState }>[] {
return Array.from(this.chats).flatMap(([chatId, chat]) => ( return Array.from(this.chats.keys(), (chatId) => ({ chatId, state: this.view(chatId) }));
chat.effectiveStartedAt === null ? [] : [{ chatId, startedAt: chat.effectiveStartedAt }]
));
} }
unresolvedChatIds(): string[] { unresolvedChatIds(): string[] {
return Array.from(this.chats).flatMap(([chatId, chat]) => ( 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[] { 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[] = []; const effects: RunEffect[] = [];
switch (command.kind) { switch (command.kind) {
case "submit": { case "submit": {
@@ -173,15 +190,21 @@ export class ClientRunLedger {
for (const turnId of openTurnIds) this.rememberClosed(chat, turnId); for (const turnId of openTurnIds) this.rememberClosed(chat, turnId);
for (const turnId of openTurnIds) this.settle(command.chatId, turnId, effects); for (const turnId of openTurnIds) this.settle(command.chatId, turnId, effects);
chat.latestTurnId = null; chat.latestTurnId = null;
this.updateClock(command.chatId, chat, null, effects); chat.anonymousActive = false;
chat.effectiveStartedAt = null;
break; break;
} }
case "forget": { case "forget":
const chat = this.chats.get(command.chatId);
this.chats.delete(command.chatId); this.chats.delete(command.chatId);
if (chat?.effectiveStartedAt != null) { break;
effects.push({ kind: "run-status", chatId: command.chatId, startedAt: null }); 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; break;
} }
case "fence": case "fence":
@@ -196,6 +219,12 @@ export class ClientRunLedger {
} }
observe(observation: RunObservation): ObservationResult { 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; const { chatId, turnId } = observation;
let chat = this.chats.get(chatId); let chat = this.chats.get(chatId);
const effects: RunEffect[] = []; const effects: RunEffect[] = [];
@@ -214,7 +243,6 @@ export class ClientRunLedger {
if (chat.closed.has(owner.turnId) || chat.fenced.has(owner.turnId)) { if (chat.closed.has(owner.turnId) || chat.fenced.has(owner.turnId)) {
if (turnId && turnId !== owner.turnId && chat.turns.get(turnId)?.delivery?.role === "candidate-owner") { if (turnId && turnId !== owner.turnId && chat.turns.get(turnId)?.delivery?.role === "candidate-owner") {
this.reject(chatId, turnId, effects); this.reject(chatId, turnId, effects);
if (!this.hasOpenTurn(chat)) effects.push({ kind: "run-status", chatId, startedAt: null });
} }
forward = "without-owner"; forward = "without-owner";
} else { } else {
@@ -224,7 +252,7 @@ export class ClientRunLedger {
if (chat.latestTurnId !== owner.turnId) this.advance(chat, owner.turnId); if (chat.latestTurnId !== owner.turnId) this.advance(chat, owner.turnId);
if (typeof owner.startedAt === "number") { if (typeof owner.startedAt === "number") {
this.ensureTurn(chat, owner.turnId).startedAt = owner.startedAt; 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 (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" const completion = observation.kind === "completed"
|| (observation.kind === "status" && observation.activity === "idle"); || (observation.kind === "status" && observation.activity === "idle");
const superseded = completion && chat?.latestTurnId != null && turnId !== chat.latestTurnId; const superseded = completion && chat?.latestTurnId != null && turnId !== chat.latestTurnId;
@@ -247,14 +294,15 @@ export class ClientRunLedger {
chat = this.ensureChat(chatId); chat = this.ensureChat(chatId);
this.advance(chat, turnId); this.advance(chat, turnId);
if (turnId) this.ensureTurn(chat, turnId).startedAt = observation.startedAt; 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") { } else if (observation.kind === "status" || observation.kind === "completed") {
// A running status without a numeric start time also settles the turn. // A running status without a numeric start time also settles the turn.
chat = this.ensureChat(chatId); chat = this.ensureChat(chatId);
if (turnId) this.rememberClosed(chat, turnId); if (turnId) this.rememberClosed(chat, turnId);
if (turnId) this.settle(chatId, turnId, effects); if (turnId) this.settle(chatId, turnId, effects);
if (chat.latestTurnId === null || turnId === chat.latestTurnId) { if (chat.latestTurnId === null || turnId === chat.latestTurnId) {
this.updateClock(chatId, chat, null, effects); chat.anonymousActive = false;
chat.effectiveStartedAt = null;
} }
effects.push({ kind: "completion", chatId }); effects.push({ kind: "completion", chatId });
} }
@@ -286,6 +334,12 @@ export class ClientRunLedger {
} }
applyCanonical(request: CanonicalRequest): { accepted: boolean; effects: readonly RunEffect[] } { 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 { chatId, snapshot } = request;
const effects: RunEffect[] = []; const effects: RunEffect[] = [];
this.fence(chatId, request.completedTurnIds, effects); this.fence(chatId, request.completedTurnIds, effects);
@@ -307,7 +361,8 @@ export class ClientRunLedger {
this.removeEmptyTurn(chat, turnId, turn); this.removeEmptyTurn(chat, turnId, turn);
effects.push({ kind: "discard-send", chatId, turnId }); effects.push({ kind: "discard-send", chatId, turnId });
} }
this.updateClock(chatId, chat, null, effects); chat.anonymousActive = false;
chat.effectiveStartedAt = null;
return { accepted: true, effects }; return { accepted: true, effects };
} }
@@ -318,6 +373,7 @@ export class ClientRunLedger {
generation: 0, generation: 0,
latestTurnId: null, latestTurnId: null,
effectiveStartedAt: null, effectiveStartedAt: null,
anonymousActive: false,
turns: new Map(), turns: new Map(),
closed: new Set(), closed: new Set(),
fenced: new Set(), fenced: new Set(),
@@ -340,6 +396,7 @@ export class ClientRunLedger {
chat.generation += 1; chat.generation += 1;
chat.latestTurnId = turnId || null; chat.latestTurnId = turnId || null;
if (turnId) { if (turnId) {
chat.anonymousActive = false;
const turn = this.ensureTurn(chat, turnId); const turn = this.ensureTurn(chat, turnId);
if (turn.openOrder === null) turn.openOrder = chat.generation; if (turn.openOrder === null) turn.openOrder = chat.generation;
} }
@@ -395,14 +452,7 @@ export class ClientRunLedger {
} }
} }
chat.latestTurnId = previous?.turnId ?? null; chat.latestTurnId = previous?.turnId ?? null;
this.updateClock(chatId, chat, previous?.startedAt ?? null, effects); chat.effectiveStartedAt = previous?.startedAt ?? null;
}
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 });
} }
private rememberClosed(chat: ChatRecord, turnId: string): void { private rememberClosed(chat: ChatRecord, turnId: string): void {
+41 -8
View File
@@ -15,9 +15,9 @@ import type {
} from "./types"; } from "./types";
import { createHostWebSocket } from "./runtime"; import { createHostWebSocket } from "./runtime";
import { ClientRunLedger } from "./client-run-ledger"; 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 /** WebSocket readyState constants, referenced by value to stay portable
* across runtimes that don't expose a global ``WebSocket`` (tests, SSR). */ * across runtimes that don't expose a global ``WebSocket`` (tests, SSR). */
@@ -87,7 +87,7 @@ type SessionUpdateHandler = (
workspaceScope?: WorkspaceScopePayload, workspaceScope?: WorkspaceScopePayload,
) => void; ) => void;
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => 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. /** Structured errors surfaced to the UI.
* *
@@ -181,6 +181,9 @@ function runObservation(event: InboundEvent): RunObservation | null {
case "message_accepted": case "message_accepted":
case "user_message": { case "user_message": {
const activeTurnId = event.active_turn_id ?? (event.starts_turn ? event.turn_id : undefined); 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 { return {
...base, ...base,
kind: event.event === "message_accepted" ? "admission" : "input", kind: event.event === "message_accepted" ? "admission" : "input",
@@ -193,6 +196,22 @@ function runObservation(event: InboundEvent): RunObservation | null {
return { ...base, kind: "completed" }; return { ...base, kind: "completed" };
case "error": case "error":
return { ...base, kind: "rejection" }; 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": case "message":
return { ...base, kind: "message" }; return { ...base, kind: "message" };
default: default:
@@ -307,8 +326,8 @@ export class NanobotClient {
onRunStatus(handler: RunStatusHandler): Unsubscribe { onRunStatus(handler: RunStatusHandler): Unsubscribe {
this.runStatusHandlers.add(handler); this.runStatusHandlers.add(handler);
for (const { chatId, startedAt } of this.runs.activeClocks()) { for (const { chatId, state } of this.runs.states()) {
handler(chatId, startedAt); handler(chatId, state);
} }
return () => { return () => {
this.runStatusHandlers.delete(handler); 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. */ /** Last ``goal_status`` ``started_at`` (unix sec) for *chatId*, if the turn is running. */
getRunStartedAt(chatId: string): number | null { getRunStartedAt(chatId: string): number | null {
return this.runs.view(chatId).startedAt; return this.runs.view(chatId).startedAt;
@@ -428,7 +456,7 @@ export class NanobotClient {
for (const effect of effects) { for (const effect of effects) {
switch (effect.kind) { switch (effect.kind) {
case "run-status": case "run-status":
this.emitRunStatus(effect.chatId, effect.startedAt); this.emitRunStatus(effect.chatId, effect.state);
break; break;
case "completion": case "completion":
for (const handler of this.runCompletionHandlers) handler(effect.chatId); for (const handler of this.runCompletionHandlers) handler(effect.chatId);
@@ -703,6 +731,10 @@ export class NanobotClient {
const turnId = options?.turnId ?? crypto.randomUUID(); const turnId = options?.turnId ?? crypto.randomUUID();
const stillConnected = () => this.socket === socket const stillConnected = () => this.socket === socket
&& socket?.readyState === WS_OPEN && this.upload === capability; && socket?.readyState === WS_OPEN && this.upload === capability;
this.applyRunEffects(this.runs.transition({
kind: "submit", chatId, turnId,
role: options?.startsNewRun === false ? "supplement" : "candidate-owner",
}));
try { try {
const references = await uploadAttachments(media, capability, const references = await uploadAttachments(media, capability,
typeof window !== "undefined" ? window.location.href : this.currentUrl, typeof window !== "undefined" ? window.location.href : this.currentUrl,
@@ -714,6 +746,7 @@ export class NanobotClient {
} }
}); });
} catch (error) { } catch (error) {
this.applyRunEffects(this.runs.transition({ kind: "reject", chatId, turnId }));
this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "attachment_rejected", this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "attachment_rejected",
reason: error instanceof Error ? error.message : "Attachment send failed" }); reason: error instanceof Error ? error.message : "Attachment send failed" });
throw error; 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) { for (const handler of this.runStatusHandlers) {
handler(chatId, startedAt); handler(chatId, state);
} }
} }
+14 -8
View File
@@ -6,6 +6,7 @@ import type { Window as HappyWindow } from "happy-dom";
import i18n from "@/i18n"; import i18n from "@/i18n";
import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings"; import { DEFAULT_TRANSCRIPTION_SETTINGS } from "@/components/settings/capabilities/TranscriptionSettings";
import { useSessions } from "@/hooks/useSessions"; import { useSessions } from "@/hooks/useSessions";
import type { RunState } from "@/lib/nanobot-client";
import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache"; import { activateReloadCache, clearReloadCache, writeReloadCache } from "@/lib/reload-cache";
import type { import type {
ChatSummary, ChatSummary,
@@ -33,7 +34,10 @@ const sendMessageSpy = vi.fn();
const sendSystemCommandSpy = vi.fn().mockResolvedValue(undefined); const sendSystemCommandSpy = vi.fn().mockResolvedValue(undefined);
let mockDefaultChatId: string | null = null; let mockDefaultChatId: string | null = null;
const statusHandlers = new Set<(status: ConnectionStatus) => void>(); 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<( const sessionUpdateHandlers = new Set<(
chatId: string, chatId: string,
scope?: string, scope?: string,
@@ -272,11 +276,13 @@ vi.mock("@/lib/nanobot-client", async (importOriginal) => {
sidebarStateUpdateHandlers.add(handler); sidebarStateUpdateHandlers.add(handler);
return () => sidebarStateUpdateHandlers.delete(handler); return () => sidebarStateUpdateHandlers.delete(handler);
}; };
onRunStatus = (handler: (chatId: string, startedAt: number | null) => void) => { onRunStatus = (handler: (chatId: string, state: RunState) => void) => {
runStatusHandlers.add(handler); runStatusHandlers.add(handler);
return () => runStatusHandlers.delete(handler); return () => runStatusHandlers.delete(handler);
}; };
onRunCompletion = () => () => {}; onRunCompletion = () => () => {};
getRunState = () => runState(null);
restorePendingRun = vi.fn();
getRunStartedAt = () => null; getRunStartedAt = () => null;
getRunTurnId = () => null; getRunTurnId = () => null;
getUnsettledRunChatIds = () => []; getUnsettledRunChatIds = () => [];
@@ -2915,12 +2921,12 @@ describe("App layout", () => {
); );
act(() => { 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: "Agent running" })).toBeInTheDocument();
act(() => { 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" })) expect(within(sidebar).queryByRole("img", { name: "Agent running" }))
.not.toBeInTheDocument(); .not.toBeInTheDocument();
@@ -2969,12 +2975,12 @@ describe("App layout", () => {
await waitFor(() => expect(document.title).toContain("Active work")); await waitFor(() => expect(document.title).toContain("Active work"));
act(() => { 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: "Agent running" })).toBeInTheDocument();
act(() => { 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" })) expect(within(sidebar).queryByRole("img", { name: "Agent running" }))
.not.toBeInTheDocument(); .not.toBeInTheDocument();
@@ -3062,12 +3068,12 @@ describe("App layout", () => {
await waitFor(() => expect(attachSpy).toHaveBeenCalledWith("chat-a")); await waitFor(() => expect(attachSpy).toHaveBeenCalledWith("chat-a"));
expect(within(sidebar).queryByRole("img", { name: "Agent running" })).not.toBeInTheDocument(); expect(within(sidebar).queryByRole("img", { name: "Agent running" })).not.toBeInTheDocument();
act(() => { 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: "Agent running" })).toBeInTheDocument();
expect(within(sidebar).getByRole("img", { name: "New activity" })).toBeInTheDocument(); expect(within(sidebar).getByRole("img", { name: "New activity" })).toBeInTheDocument();
act(() => { 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 })); mockSessions = mockSessions.map((session) => ({ ...session }));
rerender(<App />); rerender(<App />);
+14 -8
View File
@@ -630,7 +630,7 @@ describe("NanobotClient", () => {
expect(client.getRunStartedAt("chat-stop")).toBeNull(); expect(client.getRunStartedAt("chat-stop")).toBeNull();
expect(client.hasUnsettledRun("chat-stop")).toBe(false); expect(client.hasUnsettledRun("chat-stop")).toBe(false);
expect(client.isRunCompleted("chat-stop", "turn-stop")).toBe(true); 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 () => { it("preserves durable run clocks and identities through transport reconnect", async () => {
@@ -672,7 +672,7 @@ describe("NanobotClient", () => {
expect(client.getUnsettledRunChatIds()).toEqual([]); expect(client.getUnsettledRunChatIds()).toEqual([]);
expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(true); expect(client.isRunCompleted("chat-strip", "turn-strip")).toBe(true);
expect(client.isRunCompleted("another-chat", "turn-strip")).toBe(false); 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(); client.close();
}); });
@@ -697,7 +697,7 @@ describe("NanobotClient", () => {
chat_id: "chat-strip", chat_id: "chat-strip",
}); });
expect(client.getRunStartedAt("chat-strip")).toBeNull(); 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", () => { it("rejects a completed snapshot when a newer run is not represented", () => {
@@ -1752,7 +1752,7 @@ describe("NanobotClient", () => {
), ),
).toBe(true); ).toBe(true);
expect(client.getRunStartedAt("chat-canonical")).toBeNull(); 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; const deliveredBeforeLateFrames = chatHandler.mock.calls.length;
lastSocket().fakeMessage({ lastSocket().fakeMessage({
@@ -1805,19 +1805,22 @@ describe("NanobotClient", () => {
status: "running", status: "running",
started_at: 12_345, 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(); const lateHandler = vi.fn();
client.onRunStatus(lateHandler); client.onRunStatus(lateHandler);
expect(lateHandler).toHaveBeenCalledWith("chat-status", 12_345); expect(lateHandler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: true, startedAt: 12_345 }));
lastSocket().fakeMessage({ lastSocket().fakeMessage({
event: "goal_status", event: "goal_status",
chat_id: "chat-status", chat_id: "chat-status",
status: "idle", status: "idle",
}); });
expect(handler).toHaveBeenCalledWith("chat-status", null); expect(handler).toHaveBeenCalledWith("chat-status", expect.objectContaining({ active: false, startedAt: null }));
expect(lateHandler).toHaveBeenCalledWith("chat-status", 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", () => { 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", [ const delivery = client.sendAttachments("chat", "look", [
{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }, { data_url: "data:text/plain;base64,eA==", name: "note.txt" },
], { turnId: "slow-upload" }); ], { turnId: "slow-upload" });
expect(client.getRunState("chat")).toMatchObject({ active: true, startedAt: null });
await vi.advanceTimersByTimeAsync(80_000); await vi.advanceTimersByTimeAsync(80_000);
expect(socket.sent.some((frame) => frame.includes("slow-ref"))).toBe(true); expect(socket.sent.some((frame) => frame.includes("slow-ref"))).toBe(true);
socket.fakeMessage({ event: "message_accepted", chat_id: "chat", turn_id: "slow-upload" }); 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" } }); upload: { path: "/api/attachments", token: "cap" } });
const draft = [{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }]; const draft = [{ data_url: "data:text/plain;base64,eA==", name: "note.txt" }];
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("401"); 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(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
expect(draft[0].data_url).toBe("data:text/plain;base64,eA=="); expect(draft[0].data_url).toBe("data:text/plain;base64,eA==");
fetchMock.mockImplementation(async () => { fetchMock.mockImplementation(async () => {
@@ -2644,6 +2649,7 @@ describe("binary attachment transport", () => {
return Response.json({ reference: "old-connection-ref" }); return Response.json({ reference: "old-connection-ref" });
}); });
await expect(client.sendAttachments("chat", "look", draft)).rejects.toThrow("Connection changed"); 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); expect(socket.sent.filter((frame) => JSON.parse(frame).type === "message")).toHaveLength(0);
} finally { client.close(); vi.unstubAllGlobals(); } } finally { client.close(); vi.unstubAllGlobals(); }
}); });
+25
View File
@@ -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);
},
};
}
+50 -140
View File
@@ -23,6 +23,7 @@ import type {
WebuiThreadPersistedPayload, WebuiThreadPersistedPayload,
} from "@/lib/types"; } from "@/lib/types";
import { canonicalThreadPayload } from "./thread-test-payload"; import { canonicalThreadPayload } from "./thread-test-payload";
import { createStreamClient } from "./stream-client";
const HERO_GREETING_PATTERN = const HERO_GREETING_PATTERN =
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/; /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() { function makeClient() {
const { client: lifecycle, receive } = createStreamClient();
const errorHandlers = new Set<(err: StreamError) => void>(); const errorHandlers = new Set<(err: StreamError) => void>();
const statusHandlers = new Set<(status: ConnectionStatus) => void>(); const statusHandlers = new Set<(status: ConnectionStatus) => void>();
const chatHandlers = new Map<string, Set<(ev: import("@/lib/types").InboundEvent) => void>>();
const runtimeModelHandlers = new Set< const runtimeModelHandlers = new Set<
(modelName: string | null, modelPreset?: string | null) => void (modelName: string | null, modelPreset?: string | null) => void
>(); >();
const sessionUpdateHandlers = new Set<(chatId: string, scope?: string) => 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"; let status: ConnectionStatus = "open";
const advanceRunGeneration = (chatId: string, turnId?: string) => { const sendMessage = vi.fn(lifecycle.sendMessage.bind(lifecycle));
runGenerationByChatId.set(chatId, (runGenerationByChatId.get(chatId) ?? 0) + 1); const canReconcileCanonicalCompletion = vi.fn(lifecycle.canReconcileCanonicalCompletion.bind(lifecycle));
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 reconcileCanonicalCompletion = vi.fn(( const reconcileCanonicalCompletion = vi.fn((
chatId: string, chatId: string,
expectedRunGeneration: number, expectedRunGeneration: number,
@@ -108,12 +60,7 @@ function makeClient() {
)) { )) {
return false; return false;
} }
const fences = completedTurnIdsByChatId.get(chatId) ?? new Set<string>(); return lifecycle.reconcileCanonicalCompletion(chatId, expectedRunGeneration, completedTurnIds, snapshot);
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 { return {
get status() { get status() {
@@ -127,17 +74,8 @@ function makeClient() {
statusHandlers.delete(handler); statusHandlers.delete(handler);
}; };
}, },
onRunStatus: (handler: (chatId: string, startedAt: number | null) => void) => { onRunStatus: lifecycle.onRunStatus.bind(lifecycle),
runStatusHandlers.add(handler); onRunCompletion: lifecycle.onRunCompletion.bind(lifecycle),
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); };
},
onRuntimeModelUpdate: ( onRuntimeModelUpdate: (
handler: (modelName: string | null, modelPreset?: string | null) => void, handler: (modelName: string | null, modelPreset?: string | null) => void,
) => { ) => {
@@ -146,40 +84,20 @@ function makeClient() {
runtimeModelHandlers.delete(handler); runtimeModelHandlers.delete(handler);
}; };
}, },
getRunStartedAt: (chatId: string) => runStartedAtByChatId.get(chatId) ?? null, getRunState: lifecycle.getRunState.bind(lifecycle),
getRunTurnId: (chatId: string) => latestRunTurnIdByChatId.get(chatId) ?? null, restorePendingRun: lifecycle.restorePendingRun.bind(lifecycle),
isRunCompleted: (chatId: string, turnId: string) => ( getRunStartedAt: lifecycle.getRunStartedAt.bind(lifecycle),
closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true getRunTurnId: lifecycle.getRunTurnId.bind(lifecycle),
|| completedTurnIdsByChatId.get(chatId)?.has(turnId) === true isRunCompleted: lifecycle.isRunCompleted.bind(lifecycle),
), finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)),
finishRunLocally: vi.fn((chatId: string) => { hasUnsettledRun: lifecycle.hasUnsettledRun.bind(lifecycle),
runStartedAtByChatId.delete(chatId); getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
latestRunTurnIdByChatId.delete(chatId);
}),
hasUnsettledRun: () => false,
getRunGeneration: (chatId: string) => runGenerationByChatId.get(chatId) ?? 0,
canReconcileCanonicalCompletion, canReconcileCanonicalCompletion,
reconcileCanonicalCompletion, reconcileCanonicalCompletion,
fenceCanonicalCompletedTurns: (chatId: string, turnIds: readonly string[]) => { fenceCanonicalCompletedTurns: lifecycle.fenceCanonicalCompletedTurns.bind(lifecycle),
const fences = completedTurnIdsByChatId.get(chatId) ?? new Set<string>(); getGoalState: lifecycle.getGoalState.bind(lifecycle),
for (const turnId of turnIds) fences.add(turnId); onTranscript: lifecycle.onTranscript.bind(lifecycle),
completedTurnIdsByChatId.set(chatId, fences); onChat: lifecycle.onChat.bind(lifecycle),
},
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);
};
},
onError: (handler: (err: StreamError) => void) => { onError: (handler: (err: StreamError) => void) => {
errorHandlers.add(handler); errorHandlers.add(handler);
return () => { return () => {
@@ -193,48 +111,16 @@ function makeClient() {
}; };
}, },
_emitError(err: StreamError) { _emitError(err: StreamError) {
if (err.kind !== "model_request_failed" && err.chatId && err.turnId) { if (err.chatId && err.turnId) receive({
if (latestRunTurnIdByChatId.get(err.chatId) === err.turnId) { event: "error", chat_id: err.chatId, turn_id: err.turnId, detail: err.kind,
latestRunTurnIdByChatId.delete(err.chatId); });
const hadClock = runStartedAtByChatId.delete(err.chatId);
if (hadClock) for (const h of runStatusHandlers) h(err.chatId, null);
}
}
for (const h of errorHandlers) h(err); for (const h of errorHandlers) h(err);
}, },
_emitStatus(nextStatus: ConnectionStatus) { _emitStatus(nextStatus: ConnectionStatus) {
status = nextStatus; status = nextStatus;
for (const h of statusHandlers) h(status); for (const h of statusHandlers) h(status);
}, },
_emitChat(chatId: string, ev: import("@/lib/types").InboundEvent) { _emitChat(_chatId: string, ev: import("@/lib/types").InboundEvent) { receive(ev); },
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);
},
_emitRuntimeModelUpdate(modelName: string | null, modelPreset?: string | null) { _emitRuntimeModelUpdate(modelName: string | null, modelPreset?: string | null) {
for (const h of runtimeModelHandlers) h(modelName, modelPreset); for (const h of runtimeModelHandlers) h(modelName, modelPreset);
}, },
@@ -3300,7 +3186,13 @@ describe("ThreadShell", () => {
detail: "message_rejected", 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(() => expect(historyCalls).toBe(2));
await waitFor(() => await waitFor(() =>
@@ -5357,6 +5249,24 @@ describe("ThreadShell", () => {
await waitFor(() => { await waitFor(() => {
expect(screen.queryByRole("alert")).not.toBeInTheDocument(); 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 () => { 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"); 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(); const client = makeClient();
render(wrap( render(wrap(
client, client,
@@ -5898,7 +5808,7 @@ describe("ThreadShell", () => {
event: "recovery_state", event: "recovery_state",
chat_id: "recovered-chat", chat_id: "recovered-chat",
recovery_id: "recovery-1", recovery_id: "recovery-1",
status: "recovered", status,
}); });
}); });
+69
View File
@@ -45,6 +45,75 @@ function setup() {
} }
describe("completed turn event ordering", () => { 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)( it.each(["turn_end", "idle", "stop", "snapshot", "idle snapshot"] as const)(
"keeps %s terminal despite late lifecycle and ownership frames", "keeps %s terminal despite late lifecycle and ownership frames",
(terminal) => { (terminal) => {
+42 -82
View File
@@ -6,16 +6,16 @@ import { useNanobotStream } from "@/hooks/useNanobotStream";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility"; import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline"; import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import { ThreadMessageCache } from "@/lib/thread-message-cache"; import { ThreadMessageCache } from "@/lib/thread-message-cache";
import type { StreamError } from "@/lib/nanobot-client"; import type { NanobotClient, StreamError } from "@/lib/nanobot-client";
import type { import type {
ConnectionStatus, ConnectionStatus,
GoalStateWsPayload,
InboundEvent, InboundEvent,
UIMediaAttachment, UIMediaAttachment,
UIMessage, UIMessage,
} from "@/lib/types"; } from "@/lib/types";
import { ClientProvider } from "@/providers/ClientProvider"; import { ClientProvider } from "@/providers/ClientProvider";
import projectionFixture from "./fixtures/live-replay-event-projection.json"; import projectionFixture from "./fixtures/live-replay-event-projection.json";
import { createStreamClient } from "./stream-client";
const EMPTY_MESSAGES: UIMessage[] = []; const EMPTY_MESSAGES: UIMessage[] = [];
@@ -72,112 +72,64 @@ function normalizeProjection(messages: UIMessage[]): Array<Record<string, unknow
} }
function fakeClient() { function fakeClient() {
const handlers = new Map<string, Set<(ev: InboundEvent) => void>>(); const { client: lifecycle, receive } = createStreamClient();
const statusHandlers = new Set<(status: ConnectionStatus) => void>(); 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 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({}); const requestMutation = vi.fn().mockResolvedValue({});
let status: ConnectionStatus = "open"; 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 { return {
client: { client: {
get status() { get status() { return status; },
return status;
},
defaultChatId: null as string | null, defaultChatId: null as string | null,
onStatus(handler: (nextStatus: ConnectionStatus) => void) { onStatus(handler: (nextStatus: ConnectionStatus) => void) {
statusHandlers.add(handler); statusHandlers.add(handler);
handler(status); handler(status);
return () => statusHandlers.delete(handler); return () => statusHandlers.delete(handler);
}, },
onRunStatus(handler: (chatId: string, startedAt: number | null) => void) { onRunStatus: lifecycle.onRunStatus.bind(lifecycle),
runStatusHandlers.add(handler); getRunState: lifecycle.getRunState.bind(lifecycle),
for (const [chatId, startedAt] of runStartedAtByChatId) handler(chatId, startedAt); getRunGeneration: lifecycle.getRunGeneration.bind(lifecycle),
return () => runStatusHandlers.delete(handler); 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) { onError(handler: (error: StreamError) => void) {
errorHandlers.add(handler); errorHandlers.add(handler);
return () => errorHandlers.delete(handler); return () => errorHandlers.delete(handler);
}, },
getRunStartedAt(chatId: string) { sendMessage: vi.fn(lifecycle.sendMessage.bind(lifecycle)),
const v = runStartedAtByChatId.get(chatId); sendAttachments: vi.fn(async (...args: Parameters<NanobotClient["sendAttachments"]>) => {
return v === undefined ? null : v; lifecycle.sendMessage(args[0], args[1], undefined, args[3]);
}, }),
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),
requestMutation, requestMutation,
finishRunLocally: vi.fn(), finishRunLocally: vi.fn(lifecycle.finishRunLocally.bind(lifecycle)),
newChat: vi.fn(), newChat: vi.fn(), forkChat: vi.fn(), attach: vi.fn(),
forkChat: vi.fn(), connect: vi.fn(), close: vi.fn(), updateUrl: 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));
}, },
emit(_chatId: string, event: InboundEvent) { receive(event); },
emitStatus(nextStatus: ConnectionStatus) { emitStatus(nextStatus: ConnectionStatus) {
status = nextStatus; status = nextStatus;
statusHandlers.forEach((handler) => handler(status)); statusHandlers.forEach((handler) => handler(status));
}, },
emitRunStatus(chatId: string, startedAt: number | null) { emitRunStatus(chatId: string, startedAt: number | null) {
if (startedAt === null) runStartedAtByChatId.delete(chatId); receive({ event: "goal_status", chat_id: chatId,
else runStartedAtByChatId.set(chatId, startedAt); status: startedAt === null ? "idle" : "running",
runStatusHandlers.forEach((handler) => handler(chatId, startedAt)); ...(startedAt !== null ? { started_at: startedAt } : {}),
});
}, },
emitError(error: StreamError) { 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)); errorHandlers.forEach((handler) => handler(error));
}, },
setUnsettled(chatId: string, unsettled: boolean) { setUnsettled(chatId: string, unsettled: boolean) {
unsettledRunByChatId.set(chatId, unsettled); if (unsettled) lifecycle.sendMessage(chatId, "pending", undefined, { turnId: "pending-fixture" });
else lifecycle.finishRunLocally(chatId);
}, },
requestMutation, requestMutation,
}; };
@@ -295,7 +247,7 @@ describe("useNanobotStream", () => {
}); });
await flushStreamFrame(); await flushStreamFrame();
act(() => { first.result.current.send("/model", undefined, { sideChannel: true }); }); 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(); first.unmount();
const snapshot = cache.get("checkpoint")!; const snapshot = cache.get("checkpoint")!;
expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true); expect(snapshot.sideChannelTurnIds.has(commandTurn)).toBe(true);
@@ -808,7 +760,7 @@ describe("useNanobotStream", () => {
}); });
expect(result.current.isStreaming).toBe(false); expect(result.current.isStreaming).toBe(false);
expect(result.current.runStartedAt).toBeNull(); expect(result.current.runStartedAt).toBeNull();
expect(fake.client.finishRunLocally).toHaveBeenCalledWith("chat-recovery"); expect(fake.client.getRunState("chat-recovery").active).toBe(false);
act(() => { act(() => {
fake.emit("chat-recovery", { fake.emit("chat-recovery", {
@@ -836,7 +788,7 @@ describe("useNanobotStream", () => {
}); });
}); });
expect(result.current.isStreaming).toBe(false); 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)( it.each(["awaiting_user", "resuming"] as const)(
@@ -3787,6 +3739,14 @@ describe("live canonical event projection", () => {
for (const event of fixtureCase.live_events) { for (const event of fixtureCase.live_events) {
act(() => { 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); fake.emit(fixtureCase.chat_id, event);
}); });
} }
+2 -2
View File
@@ -299,8 +299,8 @@ describe("durable run recovery", () => {
running(); running();
sockets[0].receive({ event: "delta", chat_id: "inactive", turn_id: "turn-old", text: "The" }); sockets[0].receive({ event: "delta", chat_id: "inactive", turn_id: "turn-old", text: "The" });
const cachedAtCompletion: WebuiThreadPersistedPayload[] = []; const cachedAtCompletion: WebuiThreadPersistedPayload[] = [];
client.onRunStatus((chatId, startedAt) => { client.onRunStatus((chatId, state) => {
if (startedAt === null) cachedAtCompletion.push(webuiThreadCache.get(`websocket:${chatId}`)!); if (!state.active) cachedAtCompletion.push(webuiThreadCache.get(`websocket:${chatId}`)!);
}); });
await reopen(); await reopen();