TypeScript
perf(web): chat view redraws no longer re-render the composer or side chat timeline (#28564)
Andreibcc6c08d751d
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 55d951d1bdf..6cd1c7775d9 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -382,6 +382,7 @@ const EMPTY_FEEDBACK_SUBMISSIONS: ReadonlyArray<CodexFeedbackSubmission> = [];const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];const EMPTY_TURN_ITEMS: ThreadStructure["turnItems"] = [];const EMPTY_AUTO_UPDATE_ENVIRONMENTS: ReadonlyArray<EnvironmentPresentation> = [];+const EMPTY_COMPOSER_BANNER_ITEMS: ReadonlyArray<ComposerBannerStackItem> = [];const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();@@ -866,20 +867,18 @@ export default function ChatView(props: ChatViewProps) {const sideChatParent = useQuietThreadShell(sideChatParentRef);const parentThreadLink = (() => {if (sideChatParentRef !== null) {+ const title = sideChatParent?.title ?? "Parent thread";+ // Embedded, the parent is the view around it.+ if (embedded) return { title, sideChat: true };return {- title: sideChatParent?.title ?? "Parent thread",+ title,sideChat: true,- // Embedded, the parent is the view around it.- ...(embedded- ? {}- : {- open: (): void => {- void navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(sideChatParentRef),- });- },- }),+ open: (): void => {+ void navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(sideChatParentRef),+ });+ },};}if (parentSubagentThreadRef !== null) {@@ -3586,7 +3585,7 @@ export default function ChatView(props: ChatViewProps) {activeThreadId={activeThreadId}activeThread={activeThread}activeThreadShell={activeThreadShell}- promptHistoryMessages={timelineMessages}+ promptHistoryEntries={timelineEntries}forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}@@ -3621,7 +3620,11 @@ export default function ChatView(props: ChatViewProps) {: projectCloneSendBlockReason}isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup}- bannerItems={isDraftHeroState ? [] : composerBannerItems}+ bannerItems={+ isDraftHeroState || composerBannerItems.length === 0+ ? EMPTY_COMPOSER_BANNER_ITEMS+ : composerBannerItems+ }resumeCompactionTokens={resumeCompactionTokens}keepFullHistory={keepFullHistory}onToggleKeepFullHistory={toggleKeepFullHistoryStable}@@ -3661,7 +3664,9 @@ export default function ChatView(props: ChatViewProps) {}activeThreadModelSelection={activeThread?.modelSelection}activeProjectId={activeProject?.id ?? null}- activeContextWindow={activeContextWindow}+ contextWindowEntries={serverVisibleTurnItems}+ contextWindowLiveUsage={activeThreadLiveTokenUsage}+ contextWindowProviderThread={activeProviderThread}compactThreadUnavailable={compactThreadUnavailable}compactDisabled={compactDisabled}compactDisabledReason={compactDisabledReason}diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 7d1f0ade710..aa2c52443a5 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -239,25 +239,20 @@ import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";import { hasProviderSetup } from "./ProviderStatusBanner";import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";import type { UnifiedSettings } from "@t3tools/contracts/settings";-import {- isVideoAttachment,- type ChatMessage,- type SessionPhase,- type Thread,- type ThreadShell,-} from "../../types";+import { isVideoAttachment, type SessionPhase, type Thread, type ThreadShell } from "../../types";import { type ComposerPromptHistoryPosition } from "./composerPromptHistory";import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";import type {LatestProposedPlanState,PendingApproval,PendingUserInput,+ TimelineEntry,} from "../../session-logic";import {resolveComposerDispatchMode,type ComposerDispatchMode,} from "@t3tools/client-runtime/state/composer-dispatch";-import type { ContextWindowSnapshot } from "../../lib/contextWindow";+import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";import {resolveProviderSkillsForCwd,resolveProviderSlashCommandsForCwd,@@ -371,7 +366,7 @@ export interface ChatComposerProps {activeThreadId: ThreadId | null;activeThread: Thread | undefined;activeThreadShell: ThreadShell | null;- promptHistoryMessages: ReadonlyArray<ChatMessage>;+ promptHistoryEntries: ReadonlyArray<TimelineEntry>;forceExpandedOnMobile: boolean;projectSelectionRequired: boolean;@@ -433,7 +428,9 @@ export interface ChatComposerProps {reportedModelSelection?: ModelSelection | null;activeProjectId: ProjectId | null;- activeContextWindow: ContextWindowSnapshot | null;+ contextWindowEntries: Parameters<typeof deriveLatestContextWindowSnapshot>[0];+ contextWindowLiveUsage: Parameters<typeof deriveLatestContextWindowSnapshot>[1];+ contextWindowProviderThread: Parameters<typeof deriveLatestContextWindowSnapshot>[2];compactThreadUnavailable: boolean;compactDisabled: boolean;compactDisabledReason: string | null;@@ -524,7 +521,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)onMultipleModelSelectionsChange: setMultipleModelSelections,activeThreadId,activeThread,- promptHistoryMessages,+ promptHistoryEntries,forceExpandedOnMobile,projectSelectionRequired,phase,@@ -557,7 +554,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)activeThreadModelSelection,reportedModelSelection,activeProjectId,- activeContextWindow,+ contextWindowEntries,+ contextWindowLiveUsage,+ contextWindowProviderThread,compactThreadUnavailable,compactDisabled,compactDisabledReason,@@ -602,6 +601,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)editingQueuedAttachments,onRemoveEditingQueuedAttachment,} = props;+ const activeContextWindow = deriveLatestContextWindowSnapshot(+ contextWindowEntries,+ contextWindowLiveUsage,+ contextWindowProviderThread,+ );const primaryEnvironmentId = usePrimaryEnvironmentId();const composerDraftTargetKey = composerTargetKey(composerDraftTarget);const {@@ -2210,7 +2214,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)planModeUiEnabled,isLiteralPendingAnswer,pendingUserInputs,- promptHistoryMessages,+ promptHistoryEntries,promptHistoryPositionRef,composerDraftTarget,promptRef,diff --git a/apps/web/src/components/chat/composerCommandKey.ts b/apps/web/src/components/chat/composerCommandKey.tsindex 33a17f1938f..11c7710035b 100644--- a/apps/web/src/components/chat/composerCommandKey.ts+++ b/apps/web/src/components/chat/composerCommandKey.ts@@ -44,7 +44,7 @@ export function composerCommandKeyHandler(input: {readonly planModeUiEnabled: boolean;readonly isLiteralPendingAnswer: boolean;readonly pendingUserInputs: ReadonlyArray<PendingUserInput>;- readonly promptHistoryMessages: ChatComposerProps["promptHistoryMessages"];+ readonly promptHistoryEntries: ChatComposerProps["promptHistoryEntries"];readonly promptHistoryPositionRef: RefObject<{targetKey: string;position: ComposerPromptHistoryPosition;@@ -96,7 +96,7 @@ export function composerCommandKeyHandler(input: {planModeUiEnabled,isLiteralPendingAnswer,pendingUserInputs,- promptHistoryMessages,+ promptHistoryEntries,promptHistoryPositionRef,composerDraftTarget,promptRef,@@ -165,7 +165,9 @@ export function composerCommandKeyHandler(input: {const step = stepComposerPromptHistory({direction,// Built on the keypress, not per render: the timeline changes on every streamed delta.- entries: buildComposerPromptHistoryEntries(promptHistoryMessages),+ entries: buildComposerPromptHistoryEntries(+ promptHistoryEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),+ ),position,currentPrompt: promptRef.current,});diff --git a/apps/web/test/appScenarios.renders.tsx b/apps/web/test/appScenarios.renders.tsxindex 6b07091b23a..0667a9f4950 100644--- a/apps/web/test/appScenarios.renders.tsx+++ b/apps/web/test/appScenarios.renders.tsx@@ -3,6 +3,7 @@// chat and settings routes, the sidebar and the right panel, through the same stores and// atoms the app reads. See renderScenarios.renders.tsx for the counting rules.import { createMemoryHistory } from "@tanstack/react-router";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";import type { ThreadId } from "@t3tools/contracts";import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";import type * as Context from "effect/Context";@@ -13,12 +14,14 @@ import "~/index.css";import { AppRoot } from "~/AppRoot";import { __setClientSettingsForTests } from "~/hooks/useSettings";+import { useRightPanelStore } from "~/rightPanelStore";import { getRouter, type AppRouter } from "~/router";import {ENVIRONMENT_ID,assistantItem,emitTerminalMetadata,emitThreadEvent,+ emitVcsStatus,installFakeEnvironment,isThreadSubscribed,runningRun,@@ -48,6 +51,7 @@ vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({trackRpcRequestSent: () => {},}));+const GIT_STATUS_UPDATES = 20;const HISTORY_TURNS = 20;const STREAM_DELTAS = 30;const TYPED_TEXT = "fix the flaky tests!";@@ -63,7 +67,9 @@ const [WARM, A, B, LIVE] = THREADS.map((thread) => thread.id) as [ThreadId,];-installFakeEnvironment(THREADS);+const SIDE_CHAT = { ...threadWithHistory("thread-side", HISTORY_TURNS), sideChatOf: WARM };++installFakeEnvironment([...THREADS, SIDE_CHAT]);// Desktop-sized, so the sidebar, composer and right panel lay out as they do in the app.await page.viewport(1400, 900);// A returning user: the first-run gate would otherwise wait on onboarding evidence.@@ -320,3 +326,33 @@ it("app-switch-settings-section", async () => {await measure(openSettings(router, "/settings/appearance")),]);});++// ChatView re-renders when the tree goes dirty or clean; the composer and side chat timeline should not.+it("app-git-status-updates-with-side-chat", async () => {+ using _clock = frozenClock();+ useRightPanelStore.getState().openSideChat(scopeThreadRef(ENVIRONMENT_ID, WARM), SIDE_CHAT.id);+ await using _app = (await openThread(WARM)).screen;+ await expect.element(lastAnswer(SIDE_CHAT.id)).toBeVisible();+ const local = (insertions: number) => ({+ isRepo: true,+ hasPrimaryRemote: true,+ isDefaultRef: true,+ refName: "main",+ hasWorkingTreeChanges: insertions % 2 === 1,+ workingTree: {+ files: [{ path: "src/app.ts", insertions, deletions: 0 }],+ insertions,+ deletions: 0,+ },+ });+ await act(() => emitVcsStatus({ _tag: "snapshot", local: local(0), remote: null }));+ const counted = await measure(async () => {+ for (let update = 1; update <= GIT_STATUS_UPDATES; update++) {+ await act(() => emitVcsStatus({ _tag: "localUpdated", local: local(update) }));+ }+ });+ expect(counted.components.ChatView).toBe(GIT_STATUS_UPDATES * 2);+ expect(counted.components.ChatComposer).toBeUndefined();+ expect(counted.components.ConversationTimeline).toBeUndefined();+ await report("app-git-status-updates-with-side-chat", [counted]);+});diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.tsindex b2bbc89ff0e..44cd45d127e 100644--- a/apps/web/test/fakeEnvironment.ts+++ b/apps/web/test/fakeEnvironment.ts@@ -17,6 +17,7 @@ import {TurnItemId,WS_METHODS,WsRpcGroup,+ type VcsStatusStreamEvent,type OrchestrationProjectShell,type OrchestrationV2ProjectedTurnItem,type OrchestrationV2Run,@@ -182,6 +183,8 @@ function run(threadId: ThreadId, id: RunId, ordinal: number, userMessageId: stri}export interface FakeThread {+ /** Makes this a side chat of that thread. */+ readonly sideChatOf?: ThreadId;readonly id: ThreadId;readonly title: string;readonly runs: ReadonlyArray<OrchestrationV2Run>;@@ -224,7 +227,12 @@ function shellOf(thread: FakeThread): OrchestrationV2ThreadShell {branch: "main",worktreePath: null,activeProviderThreadId: null,- lineage: { rootThreadId: thread.id, parentThreadId: null, relationshipToParent: null },+ lineage: {+ rootThreadId: thread.sideChatOf ?? thread.id,+ parentThreadId: thread.sideChatOf ?? null,+ relationshipToParent: null,+ ...(thread.sideChatOf ? { sideChat: true } : {}),+ },forkedFrom: null,createdBy: "user",creationSource: "web",@@ -311,6 +319,7 @@ const threadSubscribers = new Map<string, Queue.Queue<OrchestrationV2ThreadStrealet terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null = null;let threads: ReadonlyArray<FakeThread> = [];let sequence = 1;+let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;const subscribe = <A>(first: ReadonlyArray<A>, register?: (queue: Queue.Queue<A>) => () => void) =>Stream.unwrap(@@ -365,6 +374,13 @@ const handlers: Record<string, (input: never) => unknown> = {},);},+ [WS_METHODS.subscribeVcsStatus]: () =>+ subscribe<VcsStatusStreamEvent>([], (queue) => {+ vcsStatusSubscriber = queue;+ return () => {+ if (vcsStatusSubscriber === queue) vcsStatusSubscriber = null;+ };+ }),[WS_METHODS.subscribeServerConfig]: () =>subscribe([{ version: 1 as const, type: "snapshot" as const, config: serverConfig }]),};@@ -482,3 +498,8 @@ export function runningRun(threadId: ThreadId, id: string, ordinal: number, user}export { userItem };++export async function emitVcsStatus(event: VcsStatusStreamEvent): Promise<void> {+ if (vcsStatusSubscriber === null) throw new Error("No VCS status subscription");+ await Effect.runPromise(Queue.offer(vcsStatusSubscriber, event));+}