Skip to content
TypeScript

perf(web): visit marks during a reply no longer re-render ChatView (#23124)

Julius Marmingeee33c4c65dfd
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 186fffd9588..856a2b4e548 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -1629,14 +1629,18 @@ export function sendTitleFallbackLabels(snapshot: ComposerSendSnapshot) {
/**
* A thread shell built from its loaded detail, for direct links that hydrate the detail first.
- * `updatedAt` is passed live: the thread structure leaves it out.
+ * `updatedAt` and `lastVisitedAt` are passed live: the thread structure leaves them out.
*/
export function presentThreadShellFromProjection(
environmentId: EnvironmentId,
threadId: ThreadId,
projection: ThreadStructure,
- updatedAt: ThreadProjection["updatedAt"],
+ live: {
+ readonly updatedAt: ThreadProjection["updatedAt"];
+ readonly lastVisitedAt: ThreadProjection["thread"]["lastVisitedAt"];
+ },
) {
+ const { updatedAt, lastVisitedAt } = live;
const latestRun = deriveLatestThreadRun(projection);
const runtime = deriveThreadRuntime({ ...projection, updatedAt });
const pendingRuntimeRequest =
@@ -1645,6 +1649,7 @@ export function presentThreadShellFromProjection(
return {
...presentThreadShell(environmentId, {
...projection.thread,
+ lastVisitedAt,
latestRunId: latestRun?.runId ?? null,
activeRunId: runtime?.activeRunId ?? null,
status: runtime?.status ?? "idle",
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 60a308ec4f0..92707af8ca1 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -236,6 +236,7 @@ import {
useProject,
useQuietThreadProjection,
useThreadUpdatedAt,
+ useThreadLastVisitedAt,
useQuietThreadVisibleTurnItems,
useThreadStatus,
useThreadHistory,
@@ -464,19 +465,17 @@ export default function ChatView(props: ChatViewProps) {
});
const serverThreadProjection = useQuietThreadProjection(routeThreadDetailRef);
const serverProjection = serverThreadProjection?.projection ?? null;
- // Only the shell-less fallback needs it; with a shell, the shell carries it.
- const fallbackUpdatedAt = useThreadUpdatedAt(
- serverThreadShell === null ? routeThreadDetailRef : null,
- );
+ // Only the shell-less fallback needs these; with a shell, the shell carries them.
+ const fallbackDetailRef = serverThreadShell === null ? routeThreadDetailRef : null;
+ const fallbackUpdatedAt = useThreadUpdatedAt(fallbackDetailRef);
+ const fallbackLastVisitedAt = useThreadLastVisitedAt(fallbackDetailRef);
const serverThread =
serverThreadShell !== null || serverProjection === null || fallbackUpdatedAt === null
? serverThreadShell
- : presentThreadShellFromProjection(
- environmentId,
- threadId,
- serverProjection,
- fallbackUpdatedAt,
- );
+ : presentThreadShellFromProjection(environmentId, threadId, serverProjection, {
+ updatedAt: fallbackUpdatedAt,
+ lastVisitedAt: fallbackLastVisitedAt,
+ });
const promptRef = useRef("");
const localComposerRef = useRef<ChatComposerHandle | null>(null);
const composerRef = useComposerHandleContext() ?? localComposerRef;
diff --git a/apps/web/src/lib/contextWindow.ts b/apps/web/src/lib/contextWindow.ts
index 87a7d1808da..32c3bb8de30 100644
--- a/apps/web/src/lib/contextWindow.ts
+++ b/apps/web/src/lib/contextWindow.ts
@@ -1,9 +1,8 @@
-import type { ThreadStructureTurnItem } from "@t3tools/client-runtime/state/shell";
+import type { ThreadStructure, ThreadStructureTurnItem } from "@t3tools/client-runtime/state/shell";
import type {
OrchestrationV2ProviderTurn,
OrchestrationV2ProviderTurnTokenUsage,
OrchestrationV2ProviderThread,
- OrchestrationV2ThreadProjection,
ThreadTokenUsageSnapshot,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
@@ -29,7 +28,7 @@ export type ContextWindowSnapshot = NullableContextWindowUsage & {
by provider thread, not time, so pick by timestamp. */
export function latestProviderTurnTokenUsage(
turns: ReadonlyArray<Pick<OrchestrationV2ProviderTurn, "tokenUsage">>,
- projection?: Pick<OrchestrationV2ThreadProjection, "thread" | "contextTransfers"> | null,
+ projection?: Pick<ThreadStructure, "thread" | "contextTransfers"> | null,
providerThread?: Pick<OrchestrationV2ProviderThread, "contextUsage"> | null,
): OrchestrationV2ProviderTurnTokenUsage | null {
let latest: OrchestrationV2ProviderTurnTokenUsage | null = null;
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index 4327bcaabc7..e88422aa54e 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -65,6 +65,9 @@ const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe(
const EMPTY_CHECKPOINT_SUMMARIES_ATOM = Atom.make<ReadonlyArray<ThreadCheckpointSummary>>(
Object.freeze([]),
).pipe(Atom.withLabel("web-thread-checkpoint-summaries:empty"));
+const EMPTY_LAST_VISITED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
+ Atom.withLabel("web-thread-last-visited:empty"),
+);
const EMPTY_UPDATED_AT_ATOM = Atom.make<DateTime.Utc | null>(null).pipe(
Atom.withLabel("web-thread-updated-at:empty"),
);
@@ -171,6 +174,13 @@ export function useQuietThreadProjection(
);
}
+/** The detail's live visit mark, which the thread structure leaves out. */
+export function useThreadLastVisitedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
+ return useAtomValue(
+ ref === null ? EMPTY_LAST_VISITED_AT_ATOM : environmentThreadDetails.lastVisitedAtAtom(ref),
+ );
+}
+
/** The detail's live `updatedAt`, which the thread structure leaves out. */
export function useThreadUpdatedAt(ref: ScopedThreadRef | null): DateTime.Utc | null {
return useAtomValue(
diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts
index ac32e6f9f68..537f1455a41 100644
--- a/packages/client-runtime/src/state/models.ts
+++ b/packages/client-runtime/src/state/models.ts
@@ -58,10 +58,16 @@ export type ThreadStructureVisibleTurnItem = Omit<
* reader of the quiet thread cannot depend on them and go stale. A full
* projection is assignable to it.
*/
+export type ThreadStructureThread = Omit<
+ OrchestrationV2ThreadProjection["thread"],
+ "updatedAt" | "lastVisitedAt"
+>;
+
export type ThreadStructure = Omit<
OrchestrationV2ThreadProjection,
- "turnItems" | "visibleTurnItems" | "updatedAt"
+ "thread" | "turnItems" | "visibleTurnItems" | "updatedAt"
> & {
+ readonly thread: ThreadStructureThread;
readonly turnItems: ReadonlyArray<ThreadStructureTurnItem>;
readonly visibleTurnItems: ReadonlyArray<ThreadStructureVisibleTurnItem>;
};
diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts
index 22e354b6163..68998403056 100644
--- a/packages/client-runtime/src/state/threadDetail.test.ts
+++ b/packages/client-runtime/src/state/threadDetail.test.ts
@@ -78,11 +78,48 @@ describe("sameThreadStructure", () => {
expect(sameThreadStructure(before, next)).toBe(false);
});
+ it("holds through a visit mark", () => {
+ const thread = { ...before.thread, lastVisitedAt: later, updatedAt: later };
+ expect(sameThreadStructure(before, { ...before, thread })).toBe(true);
+ });
+
+ it("sees other thread changes", () => {
+ const thread = { ...before.thread, title: "Renamed" };
+ expect(sameThreadStructure(before, { ...before, thread })).toBe(false);
+ });
+
it("sees changes outside the turn items", () => {
expect(sameThreadStructure(before, { ...before, runs: [] })).toBe(false);
});
});
+describe("lastVisitedAtAtom", () => {
+ it("follows a visit mark the quiet thread holds through", () => {
+ const projection = withItem(assistant);
+ const state = Atom.make(
+ AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) }),
+ );
+ const details = createEnvironmentThreadDetailAtoms(() => state);
+ const ref = { environmentId: EnvironmentId.make("env"), threadId: v2ThreadId };
+ const registry = AtomRegistry.make();
+ const unmountQuiet = registry.mount(details.quietThreadAtom(ref));
+ const unmountVisit = registry.mount(details.lastVisitedAtAtom(ref));
+ const quietBefore = registry.get(details.quietThreadAtom(ref));
+
+ const visited = { ...projection, thread: { ...projection.thread, lastVisitedAt: later } };
+ registry.set(
+ state,
+ AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(visited) }),
+ );
+
+ expect(registry.get(details.quietThreadAtom(ref))).toBe(quietBefore);
+ expect(registry.get(details.lastVisitedAtAtom(ref))).toBe(later);
+ unmountQuiet();
+ unmountVisit();
+ registry.dispose();
+ });
+});
+
describe("quietThreadAtom", () => {
const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
@@ -125,6 +162,8 @@ describe("quietThreadAtom", () => {
const thread = setup(withItem(assistant));
const projection = thread.read()?.projection;
expect(projection).not.toHaveProperty("updatedAt");
+ expect(projection?.thread).not.toHaveProperty("updatedAt");
+ expect(projection?.thread).not.toHaveProperty("lastVisitedAt");
expect(projection?.turnItems[0]).not.toHaveProperty("text");
expect(projection?.turnItems[0]).not.toHaveProperty("updatedAt");
expect(projection?.visibleTurnItems[0]?.item).not.toHaveProperty("text");
diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts
index 7a91b71a38b..57bdd36027a 100644
--- a/packages/client-runtime/src/state/threadDetail.ts
+++ b/packages/client-runtime/src/state/threadDetail.ts
@@ -1,4 +1,5 @@
import {
+ OrchestrationV2AppThread,
OrchestrationV2TurnItem,
type OrchestrationV2ThreadProjection,
type ScopedThreadRef,
@@ -21,6 +22,7 @@ import type {
EnvironmentThread,
EnvironmentThreadStructure,
ThreadStructure,
+ ThreadStructureThread,
ThreadStructureTurnItem,
ThreadStructureVisibleTurnItem,
} from "./models.ts";
@@ -41,6 +43,7 @@ const EMPTY_CHECKPOINT_SUMMARIES: ReadonlyArray<ThreadCheckpointSummary> = Objec
type TurnItem = OrchestrationV2ThreadProjection["turnItems"][number];
type VisibleTurnItem = OrchestrationV2ThreadProjection["visibleTurnItems"][number];
+type AppThread = OrchestrationV2ThreadProjection["thread"];
// Items are stripped once each: unchanged items keep their identity across
// structure changes, which the incremental timeline relies on.
@@ -76,35 +79,55 @@ export function isCompleteTurnItemRow(row: ThreadStructureVisibleTurnItem): row
return row.item.type !== "assistant_message" && row.item.type !== "reasoning";
}
+// The open thread is marked visited several times while a reply streams. Visit
+// state is read from the shell, or from lastVisitedAtAtom while the thread is
+// not in the shell index yet, so a mark is not structure.
+function toThreadStructureThread(thread: AppThread): ThreadStructureThread {
+ const { updatedAt: _updatedAt, lastVisitedAt: _lastVisitedAt, ...structure } = thread;
+ return structure;
+}
+
function toThreadStructure(projection: OrchestrationV2ThreadProjection): ThreadStructure {
const { updatedAt: _updatedAt, ...structure } = projection;
return {
...structure,
+ thread: toThreadStructureThread(projection.thread),
turnItems: projection.turnItems.map(toThreadStructureTurnItem),
visibleTurnItems: projection.visibleTurnItems.map(toThreadStructureVisibleTurnItem),
};
}
const sameTurnItem = Schema.toEquivalence(OrchestrationV2TurnItem);
+const sameAppThread = Schema.toEquivalence(OrchestrationV2AppThread);
+
+// Overlays previous's structure on next, so the fields the strip functions
+// remove are exactly the ones ignored here.
+function sameApartFromStripped<T extends object>(
+ same: (left: T, right: T) => boolean,
+ previous: T,
+ previousStructure: object,
+ next: T,
+): boolean {
+ return (
+ Object.keys(previous).length === Object.keys(next).length &&
+ same(Object.assign({}, next, previousStructure), next)
+ );
+}
-// Compares through toThreadStructureTurnItem, so the fields it strips are
-// exactly the ones ignored here.
function sameTurnItemStructure(previous: TurnItem, next: TurnItem): boolean {
if (previous === next) return true;
const structure = toThreadStructureTurnItem(previous);
if (previous.id !== next.id || previous.type !== next.type || structure === previous) {
return false;
}
- return (
- Object.keys(previous).length === Object.keys(next).length &&
- sameTurnItem(Object.assign({}, next, structure), next)
- );
+ return sameApartFromStripped(sameTurnItem, previous, structure, next);
}
/**
* Whether `previous` and `next` have the same ThreadStructure: they differ
- * only by text streamed into existing assistant and reasoning items. The same
- * items exist, with the same status, and every other field is unchanged.
+ * only by text streamed into existing assistant and reasoning items or by a
+ * visit mark. The same items exist, with the same status, and every other
+ * field is unchanged.
*/
export function sameThreadStructure(
previous: OrchestrationV2ThreadProjection,
@@ -112,9 +135,27 @@ export function sameThreadStructure(
): boolean {
if (previous === next) return true;
for (const key of Object.keys(next) as Array<keyof OrchestrationV2ThreadProjection>) {
- if (key === "turnItems" || key === "visibleTurnItems" || key === "updatedAt") continue;
+ if (
+ key === "thread" ||
+ key === "turnItems" ||
+ key === "visibleTurnItems" ||
+ key === "updatedAt"
+ ) {
+ continue;
+ }
if (previous[key] !== next[key]) return false;
}
+ if (
+ previous.thread !== next.thread &&
+ !sameApartFromStripped(
+ sameAppThread,
+ previous.thread,
+ toThreadStructureThread(previous.thread),
+ next.thread,
+ )
+ ) {
+ return false;
+ }
if (
previous.turnItems.length !== next.turnItems.length ||
previous.visibleTurnItems.length !== next.visibleTurnItems.length
@@ -304,6 +345,12 @@ export function createEnvironmentThreadDetailAtoms<E>(
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-checkpoint-summaries:${key}`));
});
+ const lastVisitedAtAtomFamily = Atom.family((key: string) =>
+ Atom.make(
+ (get) =>
+ Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.thread.lastVisitedAt ?? null,
+ ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-last-visited:${key}`)),
+ );
const updatedAtAtomFamily = Atom.family((key: string) =>
Atom.make(
(get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.updatedAt ?? null,
@@ -372,6 +419,7 @@ export function createEnvironmentThreadDetailAtoms<E>(
return {
worktreePathAtom: (ref: ScopedThreadRef) => worktreePathAtomFamily(threadKey(ref)),
updatedAtAtom: (ref: ScopedThreadRef) => updatedAtAtomFamily(threadKey(ref)),
+ lastVisitedAtAtom: (ref: ScopedThreadRef) => lastVisitedAtAtomFamily(threadKey(ref)),
pendingRequestsAtom: (ref: ScopedThreadRef) => pendingRequestsAtomFamily(threadKey(ref)),
queueWorkflowAtom: (ref: ScopedThreadRef) => queueWorkflowAtomFamily(threadKey(ref)),
queuedCountAtom: (ref: ScopedThreadRef) => queuedCountAtomFamily(threadKey(ref)),