Skip to content
TypeScript

fix(web): citations to older responses load their history instead of failing (#25371)

Julius Marminge1316d48b0c68
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 5e19ca708f1..dae9caa8729 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -258,6 +258,7 @@ import {
RevertConfirmHost,
} from "./chat/ChatOverlayHosts";
import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
+import { useCitedHistory } from "./chat/citationProcedure";
import type { MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
import { ThreadTimeline } from "./chat/ThreadTimeline";
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
@@ -566,6 +567,7 @@ export default function ChatView(props: ChatViewProps) {
? { citation, key: citationLocation.key ?? citationLocation.href }
: null;
})() as AssistantCitationRequest | null;
+ const citationHistory = useCitedHistory(citationRequest);
const { resolvedTheme } = useTheme();
const composerRuntimeMode = useComposerDraftStore(
(store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null,
@@ -3217,7 +3219,7 @@ export default function ChatView(props: ChatViewProps) {
readyMarkdownCwd={gitCwd}
readyWorkspaceRoot={activeWorkspaceRoot ?? null}
citationRequest={paintOnlyDisplayedTimeline ? null : citationRequest}
- citationHistoryLoading={threadDetailLoading}
+ citationHistory={citationHistory}
{...(!paintOnlyDisplayedTimeline
? {
onCiteAssistantText: citeAssistantTextStable,
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index bbaf4004e4d..9005cf2808b 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -1,9 +1,16 @@
import { AudioPreview } from "../files/AudioPreview";
import { onTestFinished } from "vite-plus/test";
import { stubGlobal } from "../../../test/render";
-import { EnvironmentId, MessageId, RunId, ScheduledTaskId, ThreadId } from "@t3tools/contracts";
+import {
+ EnvironmentId,
+ MessageId,
+ RunAttemptId,
+ RunId,
+ ScheduledTaskId,
+ ThreadId,
+} from "@t3tools/contracts";
import type { LegendListRef } from "@legendapp/list/react";
-import { createRef, Profiler, type ComponentProps, type ReactElement } from "react";
+import { createRef, Profiler, StrictMode, type ComponentProps, type ReactElement } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
import "~/index.css";
@@ -15,6 +22,8 @@ import { deriveTimelineEntriesFromVisibleTurnItems } from "../../session-logic";
import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
import { collectThreadFindRanges } from "./threadFindHighlights";
+import { toastManager } from "../ui/toast";
+import type { CitedHistory } from "./citationProcedure";
const environmentQuery = vi.hoisted(() => ({
error: "Pull request not found",
@@ -108,10 +117,10 @@ function message(
};
}
-async function renderElement(element: ReactElement) {
+async function renderElement(element: ReactElement, options: { router?: false } = {}) {
const container = document.createElement("div");
container.style.cssText = "height: 1200px; width: 900px; display: flex; flex-direction: column;";
- const screen = await render(element, { container });
+ const screen = await render(element, { container, ...options });
const buttons = (name: string | RegExp) =>
[...container.querySelectorAll<HTMLElement>("button, [role=button]")].filter((button) => {
const label = button.getAttribute("aria-label") ?? button.textContent ?? "";
@@ -237,6 +246,108 @@ describe("MessagesTimeline messages", () => {
});
});
+const CITATION_REQUEST = {
+ key: "activation-1",
+ citation: {
+ version: 1,
+ environmentId: ENVIRONMENT_ID,
+ threadId: ThreadId.make("thread-cited"),
+ messageId: MessageId.make("cited"),
+ text: "the cited answer",
+ start: 0,
+ end: 16,
+ prefix: "",
+ suffix: "",
+ },
+} satisfies NonNullable<TimelineProps["citationRequest"]>;
+
+describe("MessagesTimeline citations", () => {
+ it("lands a citation present at mount under StrictMode", async () => {
+ await using _screen = await renderElement(
+ <StrictMode>
+ <MessagesTimeline
+ {...baseProps()}
+ timelineEntries={[
+ message("A question", {}, "question"),
+ message("the cited answer", { role: "assistant" }, "cited"),
+ ]}
+ citationRequest={CITATION_REQUEST}
+ citationHistory={{ _tag: "found" }}
+ />
+ </StrictMode>,
+ // The test router mounts route content without StrictMode's effect replay.
+ { router: false },
+ );
+ // StrictMode replays effect cleanups on mount; the activation must survive them.
+ await vi.waitFor(() =>
+ expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
+ "the cited answer",
+ ),
+ );
+ });
+
+ it("opens the superseded attempt that folds the cited response", async () => {
+ const runId = RunId.make("run-steered");
+ const attempt = (id: string, ordinal: number, status: "superseded" | "running") => ({
+ id: RunAttemptId.make(id),
+ runId,
+ attemptOrdinal: ordinal,
+ rootNodeId: `node-${id}` as never,
+ status,
+ completedAt: null,
+ });
+ const superseded = attempt("attempt-1", 1, "superseded");
+ const active = attempt("attempt-2", 2, "running");
+ const inAttempt = (entry: Entry, entryAttempt: typeof superseded): Entry => ({
+ ...entry,
+ attempt: entryAttempt,
+ });
+ await using _screen = await renderTimeline(
+ [
+ inAttempt(message("Build it", { runId }, "question"), superseded),
+ inAttempt(message("the cited answer", { role: "assistant", runId }, "cited"), superseded),
+ inAttempt(message("Change direction", { runId }, "steer"), active),
+ inAttempt(message("Current response", { role: "assistant", runId }, "current"), active),
+ ],
+ {
+ latestRun: { runId, status: "running", startedAt: CREATED_AT, completedAt: null },
+ citationRequest: CITATION_REQUEST,
+ citationHistory: { _tag: "found" },
+ },
+ );
+ await vi.waitFor(() =>
+ expect(document.querySelector("[data-citation-highlighted]")?.textContent).toContain(
+ "the cited answer",
+ ),
+ );
+ });
+
+ it("waits for cited history to load before giving up on a response outside the window", async () => {
+ using toast = vi.spyOn(toastManager, "add");
+ const props = baseProps();
+ const citationRequest = CITATION_REQUEST;
+ const recent = message("A recent question", {}, "recent");
+ const timeline = (entries: Entry[], citationHistory: CitedHistory) => (
+ <MessagesTimeline
+ {...props}
+ timelineEntries={entries}
+ citationRequest={citationRequest}
+ citationHistory={citationHistory}
+ />
+ );
+ await using screen = await renderElement(timeline([recent], { _tag: "loading" }));
+ await expect.element(screen.getByText("A recent question")).toBeVisible();
+
+ await screen.rerender(
+ timeline([message("the cited answer", { role: "assistant" }, "cited"), recent], {
+ _tag: "found",
+ }),
+ );
+ await expect.element(screen.getByText("the cited answer")).toBeVisible();
+ expect(toast).not.toHaveBeenCalled();
+ });
+});
+
describe("MessagesTimeline automation prompts", () => {
it("folds an automation prompt into a bubble titled by its task", async () => {
setup({ scheduledTasks: [{ id: TASK_ID, title: "Nightly triage" }] });
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index f7fdef05baf..66b2492d227 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -59,7 +59,8 @@ import {
import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
import { type AssistantCitationRequest } from "./AssistantCitationSource";
-import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
+import { useAssistantCitationTarget } from "./useAssistantCitationTarget";
+import { resolveCitationPhase, type CitedHistory } from "./citationProcedure";
import {
resolveTimelineIsAtEnd,
resolveTimelineMinimapHasPersistentGutter,
@@ -168,6 +169,8 @@ const TIMELINE_MAINTAIN_SCROLL_AT_END_SMOOTH = {
animated: true,
} as const satisfies MaintainScrollAtEndOptions;
+const CITED_HISTORY_LOADING: CitedHistory = { _tag: "loading" };
+
export interface MessagesTimelineHistoryControls {
readonly hasMoreHistory: boolean;
readonly loading: boolean;
@@ -177,7 +180,7 @@ export interface MessagesTimelineHistoryControls {
interface MessagesTimelineProps {
citationRequest?: AssistantCitationRequest | null;
- citationHistoryLoading?: boolean;
+ citationHistory?: CitedHistory;
onCiteAssistantText?: (
citation: AssistantCitation,
sourceAnchor: AssistantCitationSourceAnchor,
@@ -265,7 +268,6 @@ interface MessagesTimelineProps {
emptyPlaceholderInset: number;
topFadeEnabled?: boolean;
historyControls?: MessagesTimelineHistoryControls | undefined;
- loadEarlier?: CitationHistoryPage | null;
findExpanded?: boolean;
findQuery?: string;
activeFindMatch?: ThreadFindMatch | null;
@@ -290,7 +292,7 @@ export function MessagesTimeline(props: MessagesTimelineProps) {
const ConversationTimeline = memo(function ConversationTimeline({
citationRequest = null,
- citationHistoryLoading = false,
+ citationHistory = CITED_HISTORY_LOADING,
onCiteAssistantText,
isWorking,
runlessWorkActive = false,
@@ -362,7 +364,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
emptyPlaceholderInset,
topFadeEnabled = false,
historyControls,
- loadEarlier = null,
}: MessagesTimelineProps) {
const listIdentityKey = displayThreadKey ?? routeThreadKey;
// Snapshot restore positions on identity changes; ongoing scroll writes must not move them.
@@ -406,9 +407,6 @@ const ConversationTimeline = memo(function ConversationTimeline({
}
const citationThreadRef = parseScopedThreadKey(routeThreadKey);
const openPullRequest = useOpenPrLink(citationThreadRef ?? undefined);
- const expandCitedRun = (runId: RunId) => {
- setExpandedRunIds((current) => (current.has(runId) ? current : new Set([...current, runId])));
- };
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const disclosureAnchorKeyRef = useRef<string | null>(null);
@@ -575,6 +573,49 @@ const ConversationTimeline = memo(function ConversationTimeline({
);
}
}
+ // A cited response folded inside a turn opens its fold once per activation;
+ // the user can fold it again. Only a citation that can still land opens one.
+ // The marker stops the O(entries) fold lookup once the entry is found, since
+ // the href stays in the URL after the citation settles.
+ const [citationExpandedFor, setCitationExpandedFor] = useState<string | null>(null);
+ // Back/Forward can restore an earlier activation key, so the marker clears
+ // between activations and a revisit opens the fold again.
+ if (!citationRequest && citationExpandedFor !== null) setCitationExpandedFor(null);
+ const citedEntry =
+ citationRequest &&
+ citationExpandedFor !== citationRequest.key &&
+ citationHistory._tag !== "failed"
+ ? timelineEntries.find(
+ (entry) =>
+ entry.kind === "message" &&
+ entry.message.role === "assistant" &&
+ entry.message.id === citationRequest.citation.messageId,
+ )
+ : undefined;
+ if (citationRequest && citedEntry) {
+ const citedRunId = (
+ findFoldRunIds ??
+ timelineTurnFoldRunIdsByEntryId({
+ timelineEntries,
+ latestRun,
+ runningRunId,
+ isWorking,
+ runlessWorkActive,
+ })
+ ).get(citedEntry.id);
+ setCitationExpandedFor(citationRequest.key);
+ if (citedRunId) {
+ setExpandedRunIds((previous) =>
+ previous.has(citedRunId) ? previous : new Set(previous).add(citedRunId),
+ );
+ }
+ const citedAttempt = citedEntry.attempt;
+ if (citedAttempt?.status === "superseded") {
+ setExpandedAttemptIds((previous) =>
+ previous.has(citedAttempt.id) ? previous : new Set(previous).add(citedAttempt.id),
+ );
+ }
+ }
const visibleExpandedRunIds =
!activeFindRunId || paintedExpandedRunIds.has(activeFindRunId)
? paintedExpandedRunIds
@@ -647,24 +688,15 @@ const ConversationTimeline = memo(function ConversationTimeline({
alwaysRender: citationAlwaysRender,
} = useAssistantCitationTarget({
request: citationRequest,
- entries: timelineEntries,
- rows,
- listRef,
- viewport: timelineViewportElement,
- historyLoading: citationHistoryLoading,
- loadEarlier,
- getTurnFoldRunId: (entryId) =>
- (
- findFoldRunIds ??
- timelineTurnFoldRunIdsByEntryId({
- timelineEntries,
- latestRun,
- runningRunId,
- isWorking,
- runlessWorkActive,
+ phase: citationRequest
+ ? resolveCitationPhase({
+ history: citationHistory,
+ messageId: citationRequest.citation.messageId,
+ entries: timelineEntries,
+ rows,
})
- ).get(entryId),
- onExpandTurn: expandCitedRun,
+ : null,
+ viewport: timelineViewportElement,
onManualNavigation,
});
const [findListReady, setFindListReady] = useState(false);
diff --git a/apps/web/src/components/chat/citationProcedure.test.ts b/apps/web/src/components/chat/citationProcedure.test.ts
new file mode 100644
index 00000000000..d5b70cda1b0
--- /dev/null
+++ b/apps/web/src/components/chat/citationProcedure.test.ts
@@ -0,0 +1,197 @@
+import { MessageId, RunId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+import type { TimelineEntry } from "../../session-logic";
+import {
+ type CitedThreadSnapshot,
+ citedThreadSnapshot,
+ loadCitedHistory,
+ resolveCitationPhase,
+} from "./citationProcedure";
+import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
+
+function scriptedHistory(snapshots: ReadonlyArray<CitedThreadSnapshot | null>) {
+ const controller = new AbortController();
+ let reads = 0;
+ let loads = 0;
+ return {
+ controller,
+ get loads() {
+ return loads;
+ },
+ run: (results: ReadonlyArray<"loaded" | "noop" | "error"> = []) =>
+ loadCitedHistory({
+ signal: controller.signal,
+ readThread: async () => snapshots[Math.min(reads++, snapshots.length - 1)] ?? null,
+ loadThrough: async () => {
+ const result = results[loads++] ?? "loaded";
+ return result === "error" ? { _tag: "error", message: "offline" } : { _tag: result };
+ },
+ }),
+ };
+}
+
+const notLoaded = { message: null, hasMoreHistory: true } satisfies CitedThreadSnapshot;
+
+describe("loadCitedHistory", () => {
+ it("finds a cited response that is already loaded without paging", async () => {
+ const history = scriptedHistory([{ message: "assistant", hasMoreHistory: true }]);
+ await expect(history.run()).resolves.toEqual({ _tag: "found" });
+ expect(history.loads).toBe(0);
+ });
+
+ it("pages history toward a response outside the loaded window", async () => {
+ const history = scriptedHistory([
+ notLoaded,
+ notLoaded,
+ { message: "assistant", hasMoreHistory: true },
+ ]);
+ await expect(history.run()).resolves.toEqual({ _tag: "found" });
+ expect(history.loads).toBe(2);
+ });
+
+ it("reports an unavailable response once the thread has no more history", async () => {
+ const history = scriptedHistory([notLoaded, { message: null, hasMoreHistory: false }]);
+ await expect(history.run()).resolves.toMatchObject({
+ _tag: "failed",
+ title: "The cited response is unavailable",
+ });
+ });
+
+ it("rejects a citation that names a user message", async () => {
+ const history = scriptedHistory([{ message: "other", hasMoreHistory: false }]);
+ await expect(history.run()).resolves.toMatchObject({
+ _tag: "failed",
+ title: "The citation does not refer to an assistant response",
+ });
+ });
+
+ it("stops on a failed page", async () => {
+ const history = scriptedHistory([notLoaded]);
+ await expect(history.run(["error"])).resolves.toMatchObject({
+ _tag: "failed",
+ title: "Could not load the cited response",
+ });
+ expect(history.loads).toBe(1);
+ });
+
+ it("reports an unavailable response when the store has nothing older to page", async () => {
+ const history = scriptedHistory([notLoaded]);
+ await expect(history.run(["noop"])).resolves.toMatchObject({
+ _tag: "failed",
+ title: "The cited response is unavailable",
+ });
+ expect(history.loads).toBe(1);
+ });
+
+ it("gives up after a bounded number of pages that never reach the response", async () => {
+ const history = scriptedHistory([notLoaded]);
+ await expect(history.run()).resolves.toMatchObject({
+ _tag: "failed",
+ title: "Could not load the cited response",
+ });
+ expect(history.loads).toBe(20);
+ });
+
+ it("ends quietly when the citation is left mid-load", async () => {
+ const history = scriptedHistory([notLoaded]);
+ const outcome = history.run();
+ history.controller.abort();
+ await expect(outcome).resolves.toEqual({ _tag: "aborted" });
+ });
+});
+
+describe("citedThreadSnapshot", () => {
+ const settledHistory = {
+ historyCursor: null,
+ hasMoreHistory: false,
+ loading: false,
+ error: null,
+ expanded: false,
+ latestLocalTurnOrdinal: null,
+ };
+ const unloaded = {
+ thread: null,
+ history: settledHistory,
+ status: "synchronizing",
+ error: null,
+ messageId: "cited",
+ } satisfies Parameters<typeof citedThreadSnapshot>[0];
+
+ it("keeps waiting while a thread that has not loaded yet is still synchronizing", () => {
+ expect(citedThreadSnapshot(unloaded)).toBeNull();
+ });
+
+ it("fails the citation when the thread could not load at all", async () => {
+ const snapshot = citedThreadSnapshot({ ...unloaded, error: "Thread not found." });
+ expect(snapshot).not.toBeNull();
+ await expect(scriptedHistory([snapshot]).run()).resolves.toMatchObject({
+ _tag: "failed",
+ title: "Could not load the cited response",
+ });
+ });
+});
+
+describe("resolveCitationPhase", () => {
+ const at = "2026-01-01T00:00:00Z";
+ const messageId = MessageId.make("cited");
+ const runId = RunId.make("run-1");
+ const entry: TimelineEntry = {
+ kind: "message",
+ id: "cited-entry",
+ createdAt: at,
+ message: {
+ id: messageId,
+ role: "assistant",
+ text: "Answer",
+ runId,
+ streaming: false,
+ createdAt: at,
+ updatedAt: at,
+ },
+ };
+ const row = {
+ kind: "message",
+ id: "cited-row",
+ message: entry.message,
+ } as MessagesTimelineRow;
+ const phase = (input: {
+ history?: "loading" | "found" | "failed";
+ entries?: ReadonlyArray<TimelineEntry>;
+ rows?: ReadonlyArray<MessagesTimelineRow>;
+ }) =>
+ resolveCitationPhase({
+ history: { _tag: input.history ?? "loading" },
+ messageId,
+ entries: input.entries ?? [],
+ rows: input.rows ?? [],
+ });
+
+ it("waits while the cited response is not in the timeline yet", () => {
+ expect(phase({ history: "found" })).toEqual({ _tag: "loading" });
+ });
+
+ it("expands the turn that folds the cited response", () => {
+ expect(phase({ entries: [entry] })).toEqual({ _tag: "expanding" });
+ });
+
+ it("is ready once the cited response has a row, even before paging settles", () => {
+ expect(phase({ entries: [entry], rows: [row] })).toEqual({
+ _tag: "ready",
+ rowId: "cited-row",
+ });
+ });
+
+ it("fails for a citation that names a user message", () => {
+ const userEntry: TimelineEntry = {
+ ...entry,
+ message: { ...entry.message, role: "user" },
+ } as TimelineEntry;
+ expect(phase({ entries: [userEntry] })).toEqual({ _tag: "failed" });
+ });
+
+ it("fails when the history procedure failed", () => {
+ expect(phase({ history: "failed", entries: [entry], rows: [row] })).toEqual({
+ _tag: "failed",
+ });
+ });
+});
diff --git a/apps/web/src/components/chat/citationProcedure.ts b/apps/web/src/components/chat/citationProcedure.ts
new file mode 100644
index 00000000000..b7e6bce12ca
--- /dev/null
+++ b/apps/web/src/components/chat/citationProcedure.ts
@@ -0,0 +1,240 @@
+import { useAtomValue } from "@effect/atom-react";
+import { type AtomCommandSuccess, runAtomCommand } from "@t3tools/client-runtime/state/runtime";
+import { Atom, type AtomRegistry } from "effect/reactivity";
+import type { TimelineEntry } from "../../session-logic";
+import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
+import { toastManager } from "../ui/toast";
+import type { AssistantCitationRequest } from "./AssistantCitationSource";
+import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
+
+/** Whether the cited response is in the loaded history, after paging toward it. */
+export type CitedHistory =
+ | { readonly _tag: "loading" }
+ | { readonly _tag: "found" }
+ | { readonly _tag: "failed" };
+
+export type CitationPhase =
+ | { readonly _tag: "loading" }
+ | { readonly _tag: "expanding" }
+ | { readonly _tag: "ready"; readonly rowId: string }
+ | { readonly _tag: "failed" };
+
+export interface CitedThreadSnapshot {
+ readonly message: "assistant" | "other" | null;
+ readonly hasMoreHistory: boolean;
+ readonly loadFailed?: true;
+}
+
+export type CitedHistoryOutcome =
+ | { readonly _tag: "found" }
+ | { readonly _tag: "failed"; readonly title: string; readonly description: string }
+ | { readonly _tag: "aborted" };
+
+type HistoryPageResult = AtomCommandSuccess<
+ Awaited<ReturnType<typeof threadEnvironment.loadEarlierHistory.run>>
+>;
+
+const MAX_CITATION_PAGES = 20;
+
+const COULD_NOT_LOAD = {
+ _tag: "failed",
+ title: "Could not load the cited response",
+ description:
+ "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
+} as const;
+
+const UNAVAILABLE = {
+ _tag: "failed",
+ title: "The cited response is unavailable",
+ description: "It may have been removed. The selected text is still saved in your citation.",
+} as const;
+
+/**
+ * Pages history toward the cited message until it is loaded, the thread runs
+ * out of history, or loading fails. `readThread` resolves once the thread
+ * detail is settled (loaded and no history page in flight), or with null when
+ * the signal aborts.
+ */
+export async function loadCitedHistory(input: {
+ readonly signal: AbortSignal;
+ readonly readThread: () => Promise<CitedThreadSnapshot | null>;
+ readonly loadThrough: () => Promise<HistoryPageResult>;
+}): Promise<CitedHistoryOutcome> {
+ for (let attempts = 0; ; attempts += 1) {
+ const thread = await input.readThread();
+ if (thread === null || input.signal.aborted) return { _tag: "aborted" };
+ if (thread.loadFailed) return COULD_NOT_LOAD;
+ if (thread.message === "assistant") return { _tag: "found" };
+ if (thread.message === "other") {
+ return {
+ _tag: "failed",
+ title: "The citation does not refer to an assistant response",
+ description: "The selected text is still saved in your citation.",
+ };
+ }
+ if (!thread.hasMoreHistory) return UNAVAILABLE;
+ if (attempts >= MAX_CITATION_PAGES) return COULD_NOT_LOAD;
+ const result = await input.loadThrough();
+ if (input.signal.aborted) return { _tag: "aborted" };
+ if (result._tag === "error") return COULD_NOT_LOAD;
+ // A noop page means the store has nothing older to load (no cursor, or the
+ // thread is gone), so re-reading would only spin on the same snapshot.
+ if (result._tag === "noop") return UNAVAILABLE;
+ }
+}
+
+/** Where the citation stands for the rows the timeline currently shows. */
+export function resolveCitationPhase(input: {
+ readonly history: CitedHistory;
+ readonly messageId: string;
+ readonly entries: ReadonlyArray<TimelineEntry>;
+ readonly rows: ReadonlyArray<MessagesTimelineRow>;
+}): CitationPhase {
+ if (input.history._tag === "failed") return { _tag: "failed" };
+ const source = input.entries.find(
+ (entry) => entry.kind === "message" && entry.message.id === input.messageId,
+ );
+ // The history store can hold the message a render before the entries do.
+ if (!source) return { _tag: "loading" };
+ if (source.kind !== "message" || source.message.role !== "assistant") return { _tag: "failed" };
+ const row = input.rows.find(
+ (candidate) => candidate.kind === "message" && candidate.message.id === input.messageId,
+ );
+ if (row) return { _tag: "ready", rowId: row.id };
+ return { _tag: "expanding" };
+}
+
+type ThreadDetail<K extends keyof typeof environmentThreadDetails> = Atom.Type<
+ ReturnType<(typeof environmentThreadDetails)[K]>
+>;
+
+/**
+ * The cited thread as `loadCitedHistory` reads it, or null while it is still
+ * settling. A thread that failed to load before any projection arrived counts
+ * as settled, so the citation fails instead of waiting on the stream's retries.
+ */
+export function citedThreadSnapshot(input: {
+ readonly thread: ThreadDetail<"quietThreadAtom">;
+ readonly history: ThreadDetail<"historyAtom">;
+ readonly status: ThreadDetail<"statusAtom">;
+ readonly error: ThreadDetail<"errorAtom">;
+ readonly messageId: string;
+}): CitedThreadSnapshot | null {
+ if (input.history.loading) return null;
+ if (input.thread === null) {
+ if (input.status === "deleted") return { message: null, hasMoreHistory: false };
+ return input.error === null ? null : { message: null, hasMoreHistory: false, loadFailed: true };
+ }
+ // Older pages merge into the visible turn items, not the message list.
+ const item = input.thread.projection.visibleTurnItems.find(
+ (row) =>
+ (row.item.type === "assistant_message" || row.item.type === "user_message") &&
+ row.item.messageId === input.messageId,
+ )?.item;
+ return {
+ message: item === undefined ? null : item.type === "assistant_message" ? "assistant" : "other",
+ hasMoreHistory: input.history.hasMoreHistory,
+ };
+}
+
+interface CitedHistoryKey {
+ readonly key: string;
+ readonly environmentId: AssistantCitationRequest["citation"]["environmentId"];
+ readonly threadId: AssistantCitationRequest["citation"]["threadId"];
+ readonly messageId: AssistantCitationRequest["citation"]["messageId"];
+}
+
+function waitForSettledThread(
+ registry: AtomRegistry.AtomRegistry,
+ atom: Atom.Atom<CitedThreadSnapshot | null>,
+ signal: AbortSignal,
+): Promise<CitedThreadSnapshot | null> {
+ return new Promise((resolve) => {
+ let unsubscribe: (() => void) | null = null;
+ let settled = false;
+ const finish = (value: CitedThreadSnapshot | null) => {
+ if (settled) return;
+ settled = true;
+ unsubscribe?.();
+ signal.removeEventListener("abort", onAbort);
+ resolve(value);
+ };
+ const onAbort = () => finish(null);
+ const check = (value: CitedThreadSnapshot | null) => {
+ if (value !== null) finish(value);
+ };
+ signal.addEventListener("abort", onAbort);
+ unsubscribe = registry.subscribe(atom, check);
+ if (settled) unsubscribe();
+ else check(registry.get(atom));
+ });
+}
+
+/**
+ * The citation procedure for one activation (the location key). Mounting it
+ * starts paging; leaving the location unmounts it and the finalizer stops it.
+ * Plain-object keys compare structurally, so one activation is one procedure.
+ */
+const citedHistoryAtom = Atom.family(
+ ({ key, environmentId, threadId, messageId }: CitedHistoryKey) => {
+ const ref = { environmentId, threadId };
+ const threadAtom = environmentThreadDetails.quietThreadAtom(ref);
+ const historyAtom = environmentThreadDetails.historyAtom(ref);
+ const statusAtom = environmentThreadDetails.statusAtom(ref);
+ const errorAtom = environmentThreadDetails.errorAtom(ref);
+ const settledThreadAtom = Atom.make((get) =>
+ citedThreadSnapshot({
+ thread: get(threadAtom),
+ history: get(historyAtom),
+ status: get(statusAtom),
+ error: get(errorAtom),
+ messageId,
+ }),
+ );
+ return Atom.make((get): CitedHistory => {
+ const controller = new AbortController();
+ get.addFinalizer(() => controller.abort());
+ void loadCitedHistory({
+ signal: controller.signal,
+ readThread: () => waitForSettledThread(get.registry, settledThreadAtom, controller.signal),
+ loadThrough: async () => {
+ const result = await runAtomCommand(
+ get.registry,
+ threadEnvironment.loadEarlierHistory,
+ { environmentId, input: { threadId, throughEntryId: messageId } },
+ { label: "load cited thread history", reportFailure: false },
+ );
+ return result._tag === "Success"
+ ? result.value
+ : { _tag: "error", message: "Could not load history." };
+ },
+ }).then((outcome) => {
+ if (outcome._tag === "aborted") return;
+ if (outcome._tag === "failed") {
+ toastManager.add({
+ type: "warning",
+ title: outcome.title,
+ description: outcome.description,
+ });
+ }
+ get.setSelf({ _tag: outcome._tag });
+ });
+ return { _tag: "loading" };
+ }).pipe(Atom.withLabel(`assistant-citation:history:${key}`));
+ },
+);
+
+const NO_CITED_HISTORY_ATOM = Atom.make<CitedHistory>({ _tag: "loading" });
+
+export function useCitedHistory(request: AssistantCitationRequest | null): CitedHistory {
+ return useAtomValue(
+ request === null
+ ? NO_CITED_HISTORY_ATOM
+ : citedHistoryAtom({
+ key: request.key,
+ environmentId: request.citation.environmentId,
+ threadId: request.citation.threadId,
+ messageId: request.citation.messageId,
+ }),
+ );
+}
diff --git a/apps/web/src/components/chat/useAssistantCitationTarget.ts b/apps/web/src/components/chat/useAssistantCitationTarget.ts
index 5b6c056eada..c59c68a303c 100644
--- a/apps/web/src/components/chat/useAssistantCitationTarget.ts
+++ b/apps/web/src/components/chat/useAssistantCitationTarget.ts
@@ -1,198 +1,148 @@
-import type { LegendListRef } from "@legendapp/list/react";
-import type { RunId } from "@t3tools/contracts";
-import { useEffect, useRef, useState, type RefObject } from "react";
-import type { TimelineEntry } from "../../session-logic";
-import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
+import { useEffect, useRef, useState } from "react";
import type { AssistantCitationRequest, AssistantCitationTarget } from "./AssistantCitationSource";
-import { toastManager } from "../ui/toast";
+import type { CitationPhase } from "./citationProcedure";
-export interface CitationHistoryPage {
- readonly loading: boolean;
- readonly cursor?: string | null;
- readonly onLoadEarlier: () => void;
+const CITATION_SCROLL_KEYS = new Set([
+ "ArrowUp",
+ "ArrowDown",
+ "PageUp",
+ "PageDown",
+ "Home",
+ "End",
+ " ",
+]);
+
+/** One activation of a citation; virtual row remounts and listeners share it. */
+interface CitationNavigation {
+ readonly target: AssistantCitationTarget;
+ /** Takes over from the live follow for this activation. */
+ readonly activate: () => void;
+ /** Stops this activation for good once another one (or none) replaces it. */
+ readonly retire: () => void;
+ /** Listens for user navigation that stops this activation's pending scroll. */
+ readonly attachDismissal: (viewport: HTMLElement | null) => () => void;
+}
+
+interface CitationSettlement {
+ /** Per activation, not per key: Back/Forward can restore an earlier key. */
+ readonly target: AssistantCitationTarget;
+ /** Dismissed citations also drop their highlight; completed ones keep it. */
+ readonly dismissed: boolean;
}
export function useAssistantCitationTarget({
request,
- entries,
- rows,
- listRef,
+ phase,
viewport,
- historyLoading,
- loadEarlier,
- getTurnFoldRunId,
- onExpandTurn,
onManualNavigation,
}: {
request: AssistantCitationRequest | null;
- entries: ReadonlyArray<TimelineEntry>;
- rows: ReadonlyArray<MessagesTimelineRow>;
- listRef: RefObject<LegendListRef | null>;
+ phase: CitationPhase | null;
viewport: HTMLElement | null;
- historyLoading: boolean;
- loadEarlier: CitationHistoryPage | null;
- getTurnFoldRunId: (entryId: string) => RunId | undefined;
- onExpandTurn: (runId: RunId) => void;
onManualNavigation: () => void;
}) {
- const [ready, setReady] = useState<AssistantCitationTarget | null>(null);
- const [finishedKey, setFinishedKey] = useState<string | null>(null);
+ const [settlement, setSettlement] = useState<CitationSettlement | null>(null);
const [listLoaded, setListLoaded] = useState(false);
const onListLoad = () => setListLoaded(true);
- const navigationRef = useRef<{
- target: AssistantCitationTarget;
- requestedPages: Set<string>;
- done: boolean;
- } | null>(null);
- if (ready !== null && ready.key !== request?.key) {
- setReady(null);
+ // Rows and listeners mutate the activation, so it lives as long as its
+ // request; a target belongs to one request, so returning to an earlier key
+ // never reuses it.
+ const [navigation, setNavigation] = useState<CitationNavigation | null>(null);
+ let current = navigation;
+ if ((request?.key ?? null) !== (navigation?.target.key ?? null)) {
+ current = request ? createCitationNavigation(request) : null;
+ setNavigation(current);
}
- if (!request && finishedKey !== null) {
- setFinishedKey(null);
- }
-
- useEffect(() => {
- if (navigationRef.current && navigationRef.current.target.key !== request?.key) {
- navigationRef.current.target.activationRef.current.dismissed = true;
- navigationRef.current.target.activationRef.current.cancelScroll?.();
- }
- if (!request) {
- navigationRef.current = null;
- return;
- }
- if (navigationRef.current?.target.key !== request.key) {
- const target: AssistantCitationTarget = {
- ...request,
- activationRef: { current: { scrolled: false, dismissed: false } },
- onComplete: () => {
- if (navigationRef.current?.target !== target) return;
- navigationRef.current.done = true;
- // ChatView's thread-open effect can run after our initial opt-out.
- onManualNavigation();
- setFinishedKey(target.key);
- },
- };
- navigationRef.current = {
- target,
- requestedPages: new Set(),
- done: false,
- };
- onManualNavigation();
- }
- if (!viewport || historyLoading) return;
- const navigation = navigationRef.current;
- if (navigation.done || navigation.target.activationRef.current.dismissed) return;
- const fail = (title: string, description: string) => {
- navigation.done = true;
- setFinishedKey(navigation.target.key);
- toastManager.add({ type: "warning", title, description });
+ function createCitationNavigation(next: AssistantCitationRequest): CitationNavigation {
+ let done = false;
+ const activationRef: AssistantCitationTarget["activationRef"] = {
+ current: { scrolled: false, dismissed: false },
};
- const source = entries.find(
- (entry) =>
- entry.kind === "message" && entry.message.id === navigation.target.citation.messageId,
- );
- if (!source) {
- if (loadEarlier) {
- if (loadEarlier.loading) return;
- const cursor = loadEarlier.cursor ?? entries[0]?.id ?? "first";
- if (navigation.requestedPages.has(cursor) || navigation.requestedPages.size >= 20) {
- fail(
- "Could not load the cited response",
- "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
- );
- return;
- }
- navigation.requestedPages.add(cursor);
- loadEarlier.onLoadEarlier();
- return;
- }
- fail(
- "The cited response is unavailable",
- "It may have been removed. The selected text is still saved in your citation.",
- );
- return;
- }
- if (source.kind !== "message" || source.message.role !== "assistant") {
- fail(
- "The citation does not refer to an assistant response",
- "The selected text is still saved in your citation.",
- );
- return;
- }
- const index = rows.findIndex(
- (row) => row.kind === "message" && row.message.id === navigation.target.citation.messageId,
- );
- if (index < 0) {
- const foldRunId = getTurnFoldRunId(source.id);
- if (foldRunId) onExpandTurn(foldRunId);
- return;
- }
- if (listLoaded && listRef.current) setReady(navigation.target);
- }, [
- entries,
- getTurnFoldRunId,
- historyLoading,
- listLoaded,
- listRef,
- loadEarlier,
- onExpandTurn,
- onManualNavigation,
- request,
- rows,
- viewport,
- ]);
-
- useEffect(() => {
- if (!request) return;
- const dismiss = (onlyPending: boolean) => {
- const navigation = navigationRef.current;
- if (!navigation || navigation.target.key !== request.key) return;
- const activation = navigation.target.activationRef.current;
- if (activation.dismissed || (onlyPending && (activation.scrolled || navigation.done))) return;
- activation.dismissed = true;
- activation.cancelScroll?.();
- if (!activation.scrolled && !navigation.done) onManualNavigation();
- navigation.done = true;
- setReady(null);
- setFinishedKey(request.key);
+ const target: AssistantCitationTarget = {
+ ...next,
+ activationRef,
+ onComplete: () => {
+ done = true;
+ // The thread-open follow can run after the scroll started.
+ onManualNavigation();
+ setSettlement({ target, dismissed: false });
+ },
};
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.key === "Escape") {
- dismiss(false);
- } else if (
- viewport?.contains(event.target as Node) &&
- ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key)
- ) {
- dismiss(true);
- }
+ const activate = () => {
+ // The follow must yield before the citation row starts scrolling.
+ if (!done) onManualNavigation();
};
- const onWheel = (event: WheelEvent) => {
- if (event.deltaY !== 0) dismiss(true);
+ const retire = () => {
+ activationRef.current.dismissed = true;
+ activationRef.current.cancelScroll?.();
};
- const onNavigation = () => dismiss(true);
- document.addEventListener("keydown", onKeyDown);
- document.addEventListener("pointerdown", onNavigation, true);
- viewport?.addEventListener("wheel", onWheel, { passive: true });
- viewport?.addEventListener("touchmove", onNavigation, { passive: true });
- return () => {
- document.removeEventListener("keydown", onKeyDown);
- document.removeEventListener("pointerdown", onNavigation, true);
- viewport?.removeEventListener("wheel", onWheel);
- viewport?.removeEventListener("touchmove", onNavigation);
+ const attachDismissal = (citationViewport: HTMLElement | null) => {
+ // User navigation stops a pending citation scroll; Escape dismisses it outright.
+ const dismiss = (onlyPending: boolean) => {
+ const activation = activationRef.current;
+ if (activation.dismissed || (onlyPending && (activation.scrolled || done))) return;
+ activation.dismissed = true;
+ activation.cancelScroll?.();
+ if (!activation.scrolled && !done) onManualNavigation();
+ done = true;
+ setSettlement({ target, dismissed: true });
+ };
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ dismiss(false);
+ } else if (
+ CITATION_SCROLL_KEYS.has(event.key) &&
+ event.target instanceof Node &&
+ citationViewport?.contains(event.target)
+ ) {
+ dismiss(true);
+ }
+ };
+ const onWheel = (event: WheelEvent) => {
+ if (event.deltaY !== 0) dismiss(true);
+ };
+ const onNavigation = () => dismiss(true);
+ document.addEventListener("keydown", onKeyDown);
+ document.addEventListener("pointerdown", onNavigation, true);
+ citationViewport?.addEventListener("wheel", onWheel, { passive: true });
+ citationViewport?.addEventListener("touchmove", onNavigation, { passive: true });
+ return () => {
+ document.removeEventListener("keydown", onKeyDown);
+ document.removeEventListener("pointerdown", onNavigation, true);
+ citationViewport?.removeEventListener("wheel", onWheel);
+ citationViewport?.removeEventListener("touchmove", onNavigation);
+ };
};
- }, [onManualNavigation, request, viewport]);
+ return { target, activate, retire, attachDismissal };
+ }
+
+ // Retiring is one-way, so it runs when the activation is replaced rather than
+ // in a cleanup: StrictMode and <Activity> replay cleanups on a live activation.
+ // Unmounting needs no retire; the rows observing it unmount with the list.
+ const activatedRef = useRef<CitationNavigation | null>(null);
+ useEffect(() => {
+ if (activatedRef.current === current) return;
+ activatedRef.current?.retire();
+ activatedRef.current = current;
+ current?.activate();
+ }, [current]);
+ // Escape and pointerdown dismiss before the viewport mounts; the viewport
+ // listeners join once it exists.
+ useEffect(() => current?.attachDismissal(viewport), [current, viewport]);
+
+ const settled = current !== null && settlement?.target === current.target ? settlement : null;
+ const target =
+ current !== null && phase?._tag === "ready" && listLoaded && settled?.dismissed !== true
+ ? current.target
+ : null;
+ const positioning = current !== null && phase?._tag !== "failed" && settled === null;
- const target = ready?.key === request?.key ? ready : null;
- const positioning = request !== null && finishedKey !== request.key;
- const sourceRow =
- target && positioning
- ? rows.find((row) => row.kind === "message" && row.message.id === target.citation.messageId)
- : undefined;
return {
target,
positioning,
onListLoad,
- alwaysRender: sourceRow ? { keys: [sourceRow.id] } : undefined,
+ alwaysRender:
+ target && positioning && phase?._tag === "ready" ? { keys: [phase.rowId] } : undefined,
};
}