Skip to content

Commit b6f8590

Browse files
fix(web): citations open superseded attempts and stop waiting on threads that fail to load
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2a7171c commit b6f8590

4 files changed

Lines changed: 127 additions & 21 deletions

File tree

‎apps/web/src/components/chat/MessagesTimeline.browser.test.tsx‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
11
import { AudioPreview } from "../files/AudioPreview";
22
import { onTestFinished } from "vite-plus/test";
33
import { stubGlobal } from "../../../test/render";
4-
import { EnvironmentId, MessageId, RunId, ScheduledTaskId, ThreadId } from "@t3tools/contracts";
4+
import {
5+
EnvironmentId,
6+
MessageId,
7+
RunAttemptId,
8+
RunId,
9+
ScheduledTaskId,
10+
ThreadId,
11+
} from "@t3tools/contracts";
512
import type { LegendListRef } from "@legendapp/list/react";
613
import { createRef, Profiler, StrictMode, type ComponentProps, type ReactElement } from "react";
714
import { describe, expect, it, vi } from "vite-plus/test";
@@ -279,6 +286,42 @@ describe("MessagesTimeline citations", () => {
279286
);
280287
});
281288

289+
it("opens the superseded attempt that folds the cited response", async () => {
290+
const runId = RunId.make("run-steered");
291+
const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({
292+
id: RunAttemptId.make(id),
293+
runId,
294+
attemptOrdinal: ordinal,
295+
rootNodeId: `node-${id}` as never,
296+
status,
297+
completedAt: null,
298+
});
299+
const superseded = attempt("attempt-1", 1, "superseded");
300+
const active = attempt("attempt-2", 2, "running");
301+
const inAttempt = (entry: Entry, entryAttempt: typeof superseded): Entry => ({
302+
...entry,
303+
attempt: entryAttempt,
304+
});
305+
await using _screen = await renderTimeline(
306+
[
307+
inAttempt(message("Build it", { runId }, "question"), superseded),
308+
inAttempt(message("the cited answer", { role: "assistant", runId }, "cited"), superseded),
309+
inAttempt(message("Change direction", { runId }, "steer"), active),
310+
inAttempt(message("Current response", { role: "assistant", runId }, "current"), active),
311+
],
312+
{
313+
latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
314+
citationRequest: CITATION_REQUEST,
315+
citationHistory: { _tag: "found" },
316+
},
317+
);
318+
await vi.waitFor(() =>
319+
expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
320+
"the cited answer",
321+
),
322+
);
323+
});
324+
282325
it("waits for cited history to load before giving up on a response outside the window", async () => {
283326
using toast = vi.spyOn(toastManager, "add");
284327
const props = baseProps();

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,12 @@ const ConversationTimeline = memo(function ConversationTimeline({
609609
previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
610610
);
611611
}
612+
const citedAttempt = citedEntry.attempt;
613+
if (citedAttempt?.status === "superseded") {
614+
setExpandedAttemptIds((previous) =>
615+
previous.has(citedAttempt.id) ? previous : new Set(previous).add(citedAttempt.id),
616+
);
617+
}
612618
}
613619
const visibleExpandedRunIds =
614620
!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)

‎apps/web/src/components/chat/citationProcedure.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";
33
import type { TimelineEntry } from "../../session-logic";
44
import {
55
type CitedThreadSnapshot,
6+
citedThreadSnapshot,
67
loadCitedHistory,
78
resolveCitationPhase,
89
} from "./citationProcedure";
@@ -99,6 +100,37 @@ describe("loadCitedHistory", () => {
99100
});
100101
});
101102

103+
describe("citedThreadSnapshot", () => {
104+
const settledHistory = {
105+
historyCursor: null,
106+
hasMoreHistory: false,
107+
loading: false,
108+
error: null,
109+
expanded: false,
110+
latestLocalTurnOrdinal: null,
111+
};
112+
const unloaded = {
113+
thread: null,
114+
history: settledHistory,
115+
status: "synchronizing",
116+
error: null,
117+
messageId: "cited",
118+
} satisfies Parameters<typeof citedThreadSnapshot>[0];
119+
120+
it("keeps waiting while a thread that has not loaded yet is still synchronizing", () => {
121+
expect(citedThreadSnapshot(unloaded)).toBeNull();
122+
});
123+
124+
it("fails the citation when the thread could not load at all", async () => {
125+
const snapshot = citedThreadSnapshot({ ...unloaded, error: "Thread not found." });
126+
expect(snapshot).not.toBeNull();
127+
await expect(scriptedHistory([snapshot]).run()).resolves.toMatchObject({
128+
_tag: "failed",
129+
title: "Could not load the cited response",
130+
});
131+
});
132+
});
133+
102134
describe("resolveCitationPhase", () => {
103135
const at = "2026-01-01T00:00:00Z";
104136
const messageId = MessageId.make("cited");

‎apps/web/src/components/chat/citationProcedure.ts‎

Lines changed: 45 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ export type CitationPhase =
2222
export interface CitedThreadSnapshot {
2323
readonly message: "assistant" | "other" | null;
2424
readonly hasMoreHistory: boolean;
25+
readonly loadFailed?: true;
2526
}
2627

2728
export type CitedHistoryOutcome =
@@ -62,6 +63,7 @@ export async function loadCitedHistory(input: {
6263
for (let attempts = 0; ; attempts += 1) {
6364
const thread = await input.readThread();
6465
if (thread === null || input.signal.aborted) return { _tag: "aborted" };
66+
if (thread.loadFailed) return COULD_NOT_LOAD;
6567
if (thread.message === "assistant") return { _tag: "found" };
6668
if (thread.message === "other") {
6769
return {
@@ -102,6 +104,39 @@ export function resolveCitationPhase(input: {
102104
return { _tag: "expanding" };
103105
}
104106

107+
type ThreadDetail<K extends keyof typeof environmentThreadDetails> = Atom.Type<
108+
ReturnType<(typeof environmentThreadDetails)[K]>
109+
>;
110+
111+
/**
112+
* The cited thread as `loadCitedHistory` reads it, or null while it is still
113+
* settling. A thread that failed to load before any projection arrived counts
114+
* as settled, so the citation fails instead of waiting on the stream's retries.
115+
*/
116+
export function citedThreadSnapshot(input: {
117+
readonly thread: ThreadDetail<"quietThreadAtom">;
118+
readonly history: ThreadDetail<"historyAtom">;
119+
readonly status: ThreadDetail<"statusAtom">;
120+
readonly error: ThreadDetail<"errorAtom">;
121+
readonly messageId: string;
122+
}): CitedThreadSnapshot | null {
123+
if (input.history.loading) return null;
124+
if (input.thread === null) {
125+
if (input.status === "deleted") return { message: null, hasMoreHistory: false };
126+
return input.error === null ? null : { message: null, hasMoreHistory: false, loadFailed: true };
127+
}
128+
// Older pages merge into the visible turn items, not the message list.
129+
const item = input.thread.projection.visibleTurnItems.find(
130+
(row) =>
131+
(row.item.type === "assistant_message" || row.item.type === "user_message") &&
132+
row.item.messageId === input.messageId,
133+
)?.item;
134+
return {
135+
message: item === undefined ? null : item.type === "assistant_message" ? "assistant" : "other",
136+
hasMoreHistory: input.history.hasMoreHistory,
137+
};
138+
}
139+
105140
interface CitedHistoryKey {
106141
readonly key: string;
107142
readonly environmentId: AssistantCitationRequest["citation"]["environmentId"];
@@ -146,26 +181,16 @@ const citedHistoryAtom = Atom.family(
146181
const threadAtom = environmentThreadDetails.quietThreadAtom(ref);
147182
const historyAtom = environmentThreadDetails.historyAtom(ref);
148183
const statusAtom = environmentThreadDetails.statusAtom(ref);
149-
const settledThreadAtom = Atom.make((get): CitedThreadSnapshot | null => {
150-
const thread = get(threadAtom);
151-
const history = get(historyAtom);
152-
const status = get(statusAtom);
153-
if (history.loading) return null;
154-
if (thread === null) {
155-
return status === "deleted" ? { message: null, hasMoreHistory: false } : null;
156-
}
157-
// Older pages merge into the visible turn items, not the message list.
158-
const item = thread.projection.visibleTurnItems.find(
159-
(row) =>
160-
(row.item.type === "assistant_message" || row.item.type === "user_message") &&
161-
row.item.messageId === messageId,
162-
)?.item;
163-
return {
164-
message:
165-
item === undefined ? null : item.type === "assistant_message" ? "assistant" : "other",
166-
hasMoreHistory: history.hasMoreHistory,
167-
};
168-
});
184+
const errorAtom = environmentThreadDetails.errorAtom(ref);
185+
const settledThreadAtom = Atom.make((get) =>
186+
citedThreadSnapshot({
187+
thread: get(threadAtom),
188+
history: get(historyAtom),
189+
status: get(statusAtom),
190+
error: get(errorAtom),
191+
messageId,
192+
}),
193+
);
169194
return Atom.make((get): CitedHistory => {
170195
const controller = new AbortController();
171196
get.addFinalizer(() => controller.abort());

0 commit comments

Comments
 (0)