The best way to control Claude Code, Codex and more from any computer or phone
perf(web): ChatView joins the strict React Compiler list (#20418)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 16, 2026 at 18:06 UTC
a09394ec39763716b29f121a8bfbe9afb26dcfc0
4 files changed
+470
-684
apps/web/reactCompiledFiles.ts
+1
-6
@@ -5,6 +5,7 @@
5
* to catch the bailouts lint cannot see.
6
*/
7
export const REACT_COMPILED_FILES = [
8
+ "apps/web/src/components/ChatView.tsx",
9
"apps/web/src/components/PersistentThreadTerminals.tsx",
10
"apps/web/src/components/Sidebar.tsx",
11
"apps/web/src/components/chat/ChatComposer.tsx",
@@ -23,9 +24,3 @@ export const REACT_COMPILED_FILES = [
24
"apps/web/src/hooks/useProactivePanels.ts",
25
"apps/web/src/hooks/useRightPanelSurfaceClose.ts",
26
] as const;
26
-
27
-/**
28
- * Files the compiler already compiles that still carry manual memoization or
29
- * effect-driven state, so only the compile test covers them for now.
30
- */
31
-export const REACT_COMPILED_FILES_PENDING_LINT = ["apps/web/src/components/ChatView.tsx"] as const;
apps/web/src/components/ChatView.tsx
+452
-661
@@ -144,11 +144,9 @@ import {
144
lazy,
145
type SetStateAction,
146
Suspense,
147
- useCallback,
147
useEffect,
148
useEffectEvent,
149
useLayoutEffect,
151
- useMemo,
150
useRef,
151
useState,
152
} from "react";
@@ -911,54 +909,41 @@ function useLocalDispatchState(input: {
909
}) {
910
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
911
914
- const resetLocalDispatch = useCallback(() => {
912
+ const resetLocalDispatch = () => {
913
setLocalDispatch(null);
916
- }, []);
914
+ };
915
918
- const serverAcknowledgedLocalDispatch = useMemo(
919
- () =>
920
- hasServerAcknowledgedLocalDispatch({
921
- localDispatch,
922
- phase: input.phase,
923
- latestRun: input.activeLatestRun,
924
- latestUserMessageId: input.latestUserMessageId,
925
- runtime: input.activeThread?.runtime ?? null,
926
- hasPendingApproval: input.activePendingApproval !== null,
927
- hasPendingUserInput: input.activePendingUserInput !== null,
928
- threadError: input.threadError,
929
- }),
930
- [
931
- input.activeLatestRun,
932
- input.latestUserMessageId,
933
- input.activePendingApproval,
934
- input.activePendingUserInput,
935
- input.activeThread?.runtime,
936
- input.phase,
937
- input.threadError,
938
- localDispatch,
939
- ],
940
- );
916
+ const serverAcknowledgedLocalDispatch = hasServerAcknowledgedLocalDispatch({
917
+ localDispatch,
918
+ phase: input.phase,
919
+ latestRun: input.activeLatestRun,
920
+ latestUserMessageId: input.latestUserMessageId,
921
+ runtime: input.activeThread?.runtime ?? null,
922
+ hasPendingApproval: input.activePendingApproval !== null,
923
+ hasPendingUserInput: input.activePendingUserInput !== null,
924
+ threadError: input.threadError,
925
+ });
926
const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch;
942
- const beginLocalDispatch = useCallback(
943
- (options?: { preparingWorktree?: boolean; submissionIntent?: ComposerSubmissionIntent }) => {
944
- const preparingWorktree = Boolean(options?.preparingWorktree);
945
- setLocalDispatch((current) => {
946
- const active = serverAcknowledgedLocalDispatch ? null : current;
947
- if (active) {
948
- const submissionIntent = options?.submissionIntent ?? active.submissionIntent;
949
- return active.preparingWorktree === preparingWorktree &&
950
- active.submissionIntent === submissionIntent
951
- ? active
952
- : { ...active, preparingWorktree, submissionIntent };
953
- }
954
- return createLocalDispatchSnapshot(input.activeThread, {
955
- ...options,
956
- latestUserMessageId: input.latestUserMessageId,
957
- });
927
+ const beginLocalDispatch = (options?: {
928
+ preparingWorktree?: boolean;
929
+ submissionIntent?: ComposerSubmissionIntent;
930
+ }) => {
931
+ const preparingWorktree = Boolean(options?.preparingWorktree);
932
+ setLocalDispatch((current) => {
933
+ const active = serverAcknowledgedLocalDispatch ? null : current;
934
+ if (active) {
935
+ const submissionIntent = options?.submissionIntent ?? active.submissionIntent;
936
+ return active.preparingWorktree === preparingWorktree &&
937
+ active.submissionIntent === submissionIntent
938
+ ? active
939
+ : { ...active, preparingWorktree, submissionIntent };
940
+ }
941
+ return createLocalDispatchSnapshot(input.activeThread, {
942
+ ...options,
943
+ latestUserMessageId: input.latestUserMessageId,
944
});
959
- },
960
- [input.activeThread, input.latestUserMessageId, serverAcknowledgedLocalDispatch],
961
- );
945
+ });
946
+ };
947
948
return {
949
beginLocalDispatch,
@@ -1075,11 +1060,8 @@ export default function ChatView(props: ChatViewProps) {
1060
const draftId = routeKind === "draft" ? props.draftId : null;
1061
const handleNewThread = useNewThreadHandler();
1062
const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions();
1078
- const routeThreadRef = useMemo(
1079
- () => scopeThreadRef(environmentId, threadId),
1080
- [environmentId, threadId],
1081
- );
1082
- const routeThreadKey = useMemo(() => scopedThreadKey(routeThreadRef), [routeThreadRef]);
1063
+ const routeThreadRef = scopeThreadRef(environmentId, threadId);
1064
+ const routeThreadKey = scopedThreadKey(routeThreadRef);
1065
const currentRouteThreadKeyRef = useRef<string | null>(routeThreadKey);
1066
useLayoutEffect(() => {
1067
currentRouteThreadKeyRef.current = routeThreadKey;
@@ -1133,9 +1115,8 @@ export default function ChatView(props: ChatViewProps) {
1115
const setEnvironmentEnabled = useAtomCommand(environmentCatalog.setEnabled, {
1116
reportFailure: false,
1117
});
1136
- const environmentById = useMemo(
1137
- () => new Map(environments.map((environment) => [environment.environmentId, environment])),
1138
- [environments],
1118
+ const environmentById = new Map(
1119
+ environments.map((environment) => [environment.environmentId, environment]),
1120
);
1121
const baseComposerDraftTarget: ScopedThreadRef | DraftId =
1122
routeKind === "server" ? routeThreadRef : props.draftId;
@@ -1176,13 +1157,12 @@ export default function ChatView(props: ChatViewProps) {
1157
status: threadStatus,
1158
});
1159
const threadDetailLoading = threadSyncPhase === "loading";
1179
- const activeThreadLiveTokenUsage = useMemo(
1180
- () => latestProviderTurnTokenUsage(serverProjection?.providerTurns ?? []),
1181
- [serverProjection?.providerTurns],
1160
+ const activeThreadLiveTokenUsage = latestProviderTurnTokenUsage(
1161
+ serverProjection?.providerTurns ?? [],
1162
);
1163
const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadDetailRef);
1164
const serverThreadHistory = useThreadHistory(routeThreadDetailRef);
1185
- const threadHistoryControls = useMemo<MessagesTimelineHistoryControls | undefined>(() => {
1165
+ const threadHistoryControls = (() => {
1166
if (routeThreadDetailRef === null || !shouldShowLoadEarlierControl(serverThreadHistory)) {
1167
return undefined;
1168
}
@@ -1200,21 +1180,18 @@ export default function ChatView(props: ChatViewProps) {
1180
});
1181
},
1182
};
1203
- }, [loadEarlierThreadHistory, routeThreadDetailRef, serverThreadHistory]);
1204
- const committedServerMessageIds = useMemo(
1205
- () => deriveCommittedServerUserMessageIds(serverVisibleTurnItems),
1206
- [serverVisibleTurnItems],
1207
- );
1183
+ })() as MessagesTimelineHistoryControls | undefined;
1184
+ const committedServerMessageIds = deriveCommittedServerUserMessageIds(serverVisibleTurnItems);
1185
// Queued messages have no turn item until their run starts, so the
1186
// turn-item-derived set alone can never retire their optimistic rows —
1187
// cancelling such a run would leave a phantom "pending" queue row behind.
1211
- const serverAcknowledgedUserMessageIds = useMemo(() => {
1188
+ const serverAcknowledgedUserMessageIds = (() => {
1189
const ids = new Set(committedServerMessageIds);
1190
for (const message of serverProjection?.messages ?? []) {
1191
if (message.role === "user") ids.add(message.id);
1192
}
1193
return ids;
1217
- }, [committedServerMessageIds, serverProjection]);
1194
+ })();
1195
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
1196
const activeThreadLocalLastVisitedAt = useUiStateStore(
1197
(store) => store.threadLastVisitedAtById[routeThreadKey],
@@ -1236,12 +1213,12 @@ export default function ChatView(props: ChatViewProps) {
1213
select: (location) => location.state.assistantCitationActivation ?? location.state.__TSR_key,
1214
});
1215
const citationLocation = { href: citationHref, key: citationKey };
1239
- const citationRequest = useMemo<AssistantCitationRequest | null>(() => {
1216
+ const citationRequest = (() => {
1217
const citation = assistantCitationFromLocation(citationLocation.href);
1218
return citation && citation.environmentId === environmentId && citation.threadId === threadId
1219
? { citation, key: citationLocation.key ?? citationLocation.href }
1220
: null;
1244
- }, [citationLocation.href, citationLocation.key, environmentId, threadId]);
1221
+ })() as AssistantCitationRequest | null;
1222
const { resolvedTheme } = useTheme();
1223
const composerRuntimeMode = useComposerDraftStore(
1224
(store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null,
@@ -1329,11 +1306,6 @@ export default function ChatView(props: ChatViewProps) {
1306
// Keyed by draft id so a bootstrap rotating the thread id keeps it, while
1307
// moving to another draft drops it without an effect.
1308
const [workLocallyResendDraftId, setWorkLocallyResendDraftId] = useState<DraftId | null>(null);
1332
- useEffect(() => {
1333
- if (workLocallyResendDraftId !== null && workLocallyResendDraftId !== draftId) {
1334
- setWorkLocallyResendDraftId(null);
1335
- }
1336
- }, [draftId, workLocallyResendDraftId]);
1309
const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<
1310
Record<string, ReadonlyArray<CodexFeedbackSubmission>>
1311
>({});
@@ -1357,9 +1329,12 @@ export default function ChatView(props: ChatViewProps) {
1329
store.rewindingThreadKeys.has(routeThreadKey),
1330
);
1331
1360
- useEffect(() => {
1332
+ const workspaceFileDragRouteKey = `${routeThreadKey}:${draftId ?? ""}`;
1333
+ const [workspaceFileDragRoute, setWorkspaceFileDragRoute] = useState(workspaceFileDragRouteKey);
1334
+ if (workspaceFileDragRoute !== workspaceFileDragRouteKey) {
1335
+ setWorkspaceFileDragRoute(workspaceFileDragRouteKey);
1336
setIsWorkspaceFileDragActive(false);
1362
- }, [draftId, routeThreadKey]);
1337
+ }
1338
1339
useEffect(() => {
1340
if (!isWorkspaceFileDragActive) return;
@@ -1379,9 +1354,15 @@ export default function ChatView(props: ChatViewProps) {
1354
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
1355
Record<string, string[]>
1356
>({});
1382
- const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =
1383
- useState<DraftThreadEnvMode | null>(null);
1384
- const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();
1357
+ // Overrides chosen before a server thread's first turn; they belong to that thread only.
1358
+ const [pendingServerThreadEnvModeEntry, setPendingServerThreadEnvModeEntry] = useState<{
1359
+ readonly threadId: ThreadId;
1360
+ readonly mode: DraftThreadEnvMode;
1361
+ } | null>(null);
1362
+ const [pendingServerThreadBranchEntry, setPendingServerThreadBranchEntry] = useState<{
1363
+ readonly threadId: ThreadId;
1364
+ readonly branch: string | null;
1365
+ } | null>(null);
1366
const [
1367
pendingServerThreadStartFromOriginByThreadId,
1368
setPendingServerThreadStartFromOriginByThreadId,
@@ -1448,24 +1429,16 @@ export default function ChatView(props: ChatViewProps) {
1429
const storeSetActiveTerminal = useTerminalUiStateStore((s) => s.setActiveTerminal);
1430
const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal);
1431
const serverThreadRefs = useThreadRefs();
1451
- const serverThreadKeys = useMemo(() => serverThreadRefs.map(scopedThreadKey), [serverThreadRefs]);
1432
+ const serverThreadKeys = serverThreadRefs.map(scopedThreadKey);
1433
const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);
1453
- const draftThreadKeys = useMemo(
1454
- () =>
1455
- Object.values(draftThreadsByThreadKey).map((draftThread) =>
1456
- scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
1457
- ),
1458
- [draftThreadsByThreadKey],
1434
+ const draftThreadKeys = Object.values(draftThreadsByThreadKey).map((draftThread) =>
1435
+ scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),
1436
);
1437
const [mountedTerminalThreadKeys, setMountedTerminalThreadKeys] = useState<string[]>([]);
1461
- const mountedTerminalThreadRefs = useMemo(
1462
- () =>
1463
- mountedTerminalThreadKeys.flatMap((mountedThreadKey) => {
1464
- const mountedThreadRef = parseScopedThreadKey(mountedThreadKey);
1465
- return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : [];
1466
- }),
1467
- [mountedTerminalThreadKeys],
1468
- );
1438
+ const mountedTerminalThreadRefs = mountedTerminalThreadKeys.flatMap((mountedThreadKey) => {
1439
+ const mountedThreadRef = parseScopedThreadKey(mountedThreadKey);
1440
+ return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : [];
1441
+ });
1442
1443
const fallbackDraftProjectRef = draftThread
1444
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
@@ -1475,80 +1448,50 @@ export default function ChatView(props: ChatViewProps) {
1448
? null
1449
: ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);
1450
const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;
1478
- useEffect(() => {
1479
- if (!serverThread || !draftId) {
1480
- return;
1481
- }
1482
- const pendingDraftEntry = localDraftErrorsByDraftId[draftId];
1483
- if (pendingDraftEntry === undefined) {
1484
- return;
1451
+ // A draft promoted to its server thread carries its pending error across.
1452
+ const promotedDraftError =
1453
+ serverThread && draftId ? localDraftErrorsByDraftId[draftId] : undefined;
1454
+ if (promotedDraftError !== undefined && draftId) {
1455
+ const remainingDraftErrors = { ...localDraftErrorsByDraftId };
1456
+ delete remainingDraftErrors[draftId];
1457
+ setLocalDraftErrorsByDraftId(remainingDraftErrors);
1458
+ const currentEntry = localServerErrorsByThreadKey[routeThreadKey];
1459
+ if (
1460
+ currentEntry === undefined ||
1461
+ (currentEntry.at <= promotedDraftError.at &&
1462
+ currentEntry.message !== promotedDraftError.message)
1463
+ ) {
1464
+ setLocalServerErrorsByThreadKey({
1465
+ ...localServerErrorsByThreadKey,
1466
+ [routeThreadKey]: promotedDraftError,
1467
+ });
1468
}
1486
- setLocalDraftErrorsByDraftId((existing) => {
1487
- if (existing[draftId] === undefined) {
1488
- return existing;
1489
- }
1490
- const next = { ...existing };
1491
- delete next[draftId];
1492
- return next;
1493
- });
1494
- setLocalServerErrorsByThreadKey((existing) => {
1495
- const currentEntry = existing[routeThreadKey];
1496
- if (
1497
- currentEntry !== undefined &&
1498
- (currentEntry.at > pendingDraftEntry.at ||
1499
- currentEntry.message === pendingDraftEntry.message)
1500
- ) {
1501
- return existing;
1502
- }
1503
- return {
1504
- ...existing,
1505
- [routeThreadKey]: pendingDraftEntry,
1506
- };
1507
- });
1508
- }, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]);
1509
- const localDraftThread = useMemo(
1510
- () =>
1511
- draftThread
1512
- ? buildLocalDraftThread(
1513
- threadId,
1514
- draftThread,
1515
- resolveProjectSettings(
1516
- settings,
1517
- fallbackDraftProject?.id ?? null,
1518
- fallbackDraftProject ?? undefined,
1519
- ).settings.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,
1520
- )
1521
- : undefined,
1522
- [draftThread, fallbackDraftProject, settings, threadId],
1523
- );
1469
+ }
1470
+ const localDraftThread = draftThread
1471
+ ? buildLocalDraftThread(
1472
+ threadId,
1473
+ draftThread,
1474
+ resolveProjectSettings(
1475
+ settings,
1476
+ fallbackDraftProject?.id ?? null,
1477
+ fallbackDraftProject ?? undefined,
1478
+ ).settings.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,
1479
+ )
1480
+ : undefined;
1481
const isServerThread = serverThread !== null;
1482
const activeThread = isServerThread ? serverThread : localDraftThread;
1526
- const serverLatestRun = useMemo(
1527
- () => (serverProjection === null ? null : deriveLatestThreadRun(serverProjection)),
1528
- [serverProjection],
1529
- );
1530
- const serverActivityRun = useMemo(
1531
- () => (serverProjection === null ? null : deriveThreadActivityRun(serverProjection)),
1532
- [serverProjection],
1533
- );
1534
- const serverRuntime = useMemo(
1535
- () => (serverProjection === null ? null : deriveThreadRuntime(serverProjection)),
1536
- [serverProjection],
1537
- );
1538
- const runlessWorkStartedAt = useMemo(
1539
- () => (serverProjection === null ? null : deriveRunlessWorkStartedAt(serverProjection)),
1540
- [serverProjection],
1541
- );
1542
- const providerSubagentStatus = useMemo(
1543
- () => (serverProjection === null ? null : deriveProviderSubagentStatus(serverProjection)),
1544
- [serverProjection],
1545
- );
1483
+ const serverLatestRun =
1484
+ serverProjection === null ? null : deriveLatestThreadRun(serverProjection);
1485
+ const serverActivityRun =
1486
+ serverProjection === null ? null : deriveThreadActivityRun(serverProjection);
1487
+ const serverRuntime = serverProjection === null ? null : deriveThreadRuntime(serverProjection);
1488
+ const runlessWorkStartedAt =
1489
+ serverProjection === null ? null : deriveRunlessWorkStartedAt(serverProjection);
1490
+ const providerSubagentStatus =
1491
+ serverProjection === null ? null : deriveProviderSubagentStatus(serverProjection);
1492
const isProviderSubagent =
1493
serverThread !== null && isProviderNativeSubagentThread(serverThread.source);
1548
- const supportsProviderSwitchingViaHandoff = useMemo(
1549
- () => threadSupportsProviderHandoff(serverProjection),
1550
- [serverProjection],
1551
- );
1494
+ const supportsProviderSwitchingViaHandoff = threadSupportsProviderHandoff(serverProjection);
1495
const activeLatestRun = isServerThread ? serverLatestRun : (activeThread?.latestRun ?? null);
1496
const activeActivityRun = isServerThread ? serverActivityRun : (activeThread?.latestRun ?? null);
1497
const activeRuntime = isServerThread ? serverRuntime : (activeThread?.runtime ?? null);
@@ -1556,7 +1499,7 @@ export default function ChatView(props: ChatViewProps) {
1499
isServerThread &&
1500
serverProjection?.runs.some((run) => run.status === "queued" && run.queueHeld === true) ===
1501
true;
1559
- const resumableRunId = useMemo(() => {
1502
+ const resumableRunId = (() => {
1503
if (!isServerThread || serverProjection === null) return null;
1504
const run = latestExecutedRun(serverProjection.runs);
1505
if (run?.status === "interrupted") return run.id;
@@ -1565,29 +1508,26 @@ export default function ChatView(props: ChatViewProps) {
1508
latestRootProviderFailure(run, serverProjection.turnItems)?.class === "usage_limit"
1509
? run.id
1510
: null;
1568
- }, [isServerThread, serverProjection, serverRuntime?.lastErrorClass]);
1511
+ })();
1512
const parentSubagentThreadId =
1513
activeThread?.lineage.relationshipToParent === "subagent"
1514
? activeThread.lineage.parentThreadId
1515
: null;
1516
const parentSubagentEnvironmentId = activeThread?.environmentId ?? null;
1574
- const parentSubagentThreadRef = useMemo(() => {
1517
+ const parentSubagentThreadRef = (() => {
1518
if (parentSubagentEnvironmentId === null || parentSubagentThreadId === null) {
1519
return null;
1520
}
1521
return scopeThreadRef(parentSubagentEnvironmentId, parentSubagentThreadId);
1579
- }, [parentSubagentEnvironmentId, parentSubagentThreadId]);
1522
+ })();
1523
const parentSubagentThread = useThreadShell(parentSubagentThreadRef);
1581
- const parentThreadLink = useMemo(
1582
- () =>
1583
- parentSubagentThreadRef === null
1584
- ? null
1585
- : {
1586
- threadId: parentSubagentThreadRef.threadId,
1587
- title: parentSubagentThread?.title ?? "Parent thread",
1588
- },
1589
- [parentSubagentThread?.title, parentSubagentThreadRef],
1590
- );
1524
+ const parentThreadLink =
1525
+ parentSubagentThreadRef === null
1526
+ ? null
1527
+ : {
1528
+ threadId: parentSubagentThreadRef.threadId,
1529
+ title: parentSubagentThread?.title ?? "Parent thread",
1530
+ };
1531
const threadError = isServerThread
1532
? (localServerError ?? serverRuntime?.lastError ?? null)
1533
: localDraftError;
@@ -1622,23 +1562,21 @@ export default function ChatView(props: ChatViewProps) {
1562
environmentId: activeThread?.environmentId ?? null,
1563
threadId: activeThreadId,
1564
});
1625
- const activeThreadKnownSessions = useMemo(() => {
1565
+ const activeThreadKnownSessions = (() => {
1566
if (activeThreadId === null || activeThreadKnownSessionsRaw === null) {
1567
return [];
1568
}
1569
return activeThreadKnownSessionsRaw.filter(
1570
(session) => session.target.threadId === activeThreadId,
1571
);
1632
- }, [activeThreadId, activeThreadKnownSessionsRaw]);
1633
- const activeServerOrderedTerminalIds = useMemo(
1634
- () => activeThreadKnownSessions.map((session) => session.target.terminalId),
1635
- [activeThreadKnownSessions],
1636
- );
1637
- const activeKnownTerminalIds = useMemo(
1638
- () => [...new Set([...activeServerOrderedTerminalIds, ...terminalUiState.terminalIds])],
1639
- [activeServerOrderedTerminalIds, terminalUiState.terminalIds],
1572
+ })();
1573
+ const activeServerOrderedTerminalIds = activeThreadKnownSessions.map(
1574
+ (session) => session.target.terminalId,
1575
);
1641
- const activeTerminalLabelsById = useMemo(() => {
1576
+ const activeKnownTerminalIds = [
1577
+ ...new Set([...activeServerOrderedTerminalIds, ...terminalUiState.terminalIds]),
1578
+ ];
1579
+ const activeTerminalLabelsById = (() => {
1580
const labels = new Map<string, string>();
1581
for (const session of activeThreadKnownSessions) {
1582
labels.set(
@@ -1647,7 +1585,7 @@ export default function ChatView(props: ChatViewProps) {
1585
);
1586
}
1587
return labels;
1650
- }, [activeThreadKnownSessions]);
1588
+ })();
1589
const activeThreadRef = useActiveThreadRef(activeThread);
1590
const terminalActions = useThreadTerminalActions(activeThreadRef);
1591
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
@@ -1680,7 +1618,7 @@ export default function ChatView(props: ChatViewProps) {
1618
// time and never recomputes it, so a lingering anchor leaves stale filler
1619
// height behind the composer — phantom scroll range on threads whose content
1620
// fits.
1683
- const anchorRunSettled = useMemo(() => {
1621
+ const anchorRunSettled = (() => {
1622
if (timelineAnchorMessageId === null) return false;
1623
const anchorRun = serverProjection?.runs.find(
1624
(run) => run.userMessageId === timelineAnchorMessageId,
@@ -1693,11 +1631,10 @@ export default function ChatView(props: ChatViewProps) {
1631
anchorRun.status !== "running" &&
1632
anchorRun.status !== "waiting"
1633
);
1696
- }, [serverProjection, timelineAnchorMessageId]);
1697
- useEffect(() => {
1698
- if (!anchorRunSettled) return;
1634
+ })();
1635
+ if (anchorRunSettled) {
1636
setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });
1700
- }, [anchorRunSettled, activeThreadKey]);
1637
+ }
1638
const activeRightPanelKind = useRightPanelStore((state) =>
1639
selectActiveRightPanel(state.byThreadKey, activeThreadRef),
1640
);
@@ -1719,24 +1656,16 @@ export default function ChatView(props: ChatViewProps) {
1656
const activePreviewState = useThreadPreviewState(activeThreadRef);
1657
const activePreviewServerEpoch = activePreviewState.serverEpoch;
1658
const previewSessionsReady = !activeEnvironmentServerBrowser || activePreviewState.listLoaded;
1722
- const resolvePreviewRuntimeTabId = useMemo(
1723
- () =>
1724
- activeThreadRef
1725
- ? (tabId: string) => previewRuntimeTabId(activeThreadRef, activePreviewServerEpoch, tabId)
1726
- : undefined,
1727
- [activeThreadRef, activePreviewServerEpoch],
1728
- );
1659
+ const resolvePreviewRuntimeTabId = activeThreadRef
1660
+ ? (tabId: string) => previewRuntimeTabId(activeThreadRef, activePreviewServerEpoch, tabId)
1661
+ : undefined;
1662
const activePreviewMiniPlayer = usePreviewMiniPlayerStore((state) =>
1663
selectThreadPreviewMiniPlayer(state.byThreadKey, activeThreadRef),
1664
);
1732
- const panelTerminalIds = useMemo(
1733
- () =>
1734
- new Set(
1735
- rightPanelState.surfaces.flatMap((surface) =>
1736
- surface.kind === "terminal" ? surface.terminalIds : [],
1737
- ),
1738
- ),
1739
- [rightPanelState.surfaces],
1665
+ const panelTerminalIds = new Set(
1666
+ rightPanelState.surfaces.flatMap((surface) =>
1667
+ surface.kind === "terminal" ? surface.terminalIds : [],
1668
+ ),
1669
);
1670
const canReuseTerminal = activeThreadKnownSessionsRaw !== null;
1671
const previewPanelOpen = activeRightPanelKind === "preview" && browserAvailable;
@@ -1750,13 +1679,10 @@ export default function ChatView(props: ChatViewProps) {
1679
activeThreadKey,
1680
panelAnimationDurationMs,
1681
);
1753
- const rightPanelPresenceValue = useMemo(
1754
- () => ({
1755
- activeSurface: activeRightPanelSurface,
1756
- surfaces: rightPanelState.surfaces,
1757
- }),
1758
- [activeRightPanelSurface, rightPanelState.surfaces],
1759
- );
1682
+ const rightPanelPresenceValue = {
1683
+ activeSurface: activeRightPanelSurface,
1684
+ surfaces: rightPanelState.surfaces,
1685
+ };
1686
const rightPanelPresence = usePanelPresence(
1687
rightPanelOpen && activeThreadRef !== null,
1688
rightPanelPresenceValue,
@@ -1816,33 +1742,30 @@ export default function ChatView(props: ChatViewProps) {
1742
}
1743
}, [activePreviewMiniPlayer, activePreviewState.sessions, activeThreadRef, previewSessionsReady]);
1744
1819
- const existingOpenTerminalThreadKeys = useMemo(() => {
1745
+ const existingOpenTerminalThreadKeys = (() => {
1746
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
1747
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
1822
- }, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
1823
- useEffect(() => {
1824
- setMountedTerminalThreadKeys((currentThreadIds) => {
1825
- const nextThreadIds = reconcileMountedTerminalThreadIds({
1826
- currentThreadIds,
1827
- openThreadIds: existingOpenTerminalThreadKeys,
1828
- activeThreadId: activeThreadKey,
1829
- activeThreadTerminalOpen: activeTerminalDrawerPresence.present,
1830
- maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
1831
- });
1832
- return currentThreadIds.length === nextThreadIds.length &&
1833
- currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index])
1834
- ? currentThreadIds
1835
- : nextThreadIds;
1836
- });
1837
- }, [activeTerminalDrawerPresence.present, activeThreadKey, existingOpenTerminalThreadKeys]);
1748
+ })();
1749
+ const reconciledMountedTerminalThreadKeys = reconcileMountedTerminalThreadIds({
1750
+ currentThreadIds: mountedTerminalThreadKeys,
1751
+ openThreadIds: existingOpenTerminalThreadKeys,
1752
+ activeThreadId: activeThreadKey,
1753
+ activeThreadTerminalOpen: activeTerminalDrawerPresence.present,
1754
+ maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
1755
+ });
1756
+ if (
1757
+ reconciledMountedTerminalThreadKeys.length !== mountedTerminalThreadKeys.length ||
1758
+ reconciledMountedTerminalThreadKeys.some(
1759
+ (threadKey, index) => threadKey !== mountedTerminalThreadKeys[index],
1760
+ )
1761
+ ) {
1762
+ setMountedTerminalThreadKeys(reconciledMountedTerminalThreadKeys);
1763
+ }
1764
const latestRunSettled = isLatestRunSettled(activeLatestRun, activeRuntime);
1839
- const activePlan = useMemo(
1840
- () => deriveActivePlanState(serverProjection, activeActivityRun?.runId),
1841
- [activeActivityRun?.runId, serverProjection],
1842
- );
1765
+ const activePlan = deriveActivePlanState(serverProjection, activeActivityRun?.runId);
1766
// Tasks progress for the running turn's own plan only — deriveActivePlanState
1767
// falls back to older runs' plans, which must not label fresh work.
1845
- const activeComposerTasksProgress = useMemo(() => {
1768
+ const activeComposerTasksProgress = (() => {
1769
if (
1770
isLatestRunSettled(activeActivityRun, activeRuntime) ||
1771
!activePlan ||
@@ -1858,7 +1781,7 @@ export default function ChatView(props: ChatViewProps) {
1781
activePlan.steps.find((candidate) => candidate.status === "pending")?.step ??
1782
activePlan.steps.at(-1)!.step;
1783
return { step, completedSteps, totalSteps };
1861
- }, [activeActivityRun, activePlan, activeRuntime]);
1784
+ })();
1785
const activeComposerTaskSteps =
1786
activeComposerTasksProgress && activePlan ? activePlan.steps : null;
1787
const activeThreadEnvironmentId = activeThread?.environmentId;
@@ -1868,14 +1791,12 @@ export default function ChatView(props: ChatViewProps) {
1791
? scopeProjectRef(activeThreadEnvironmentId, activeThreadProjectId)
1792
: null;
1793
const activeProject = useProject(activeProjectRef);
1871
- const activeProjectSettings = useMemo(
1872
- () => resolveProjectSettings(settings, activeProject?.id ?? null, activeProject ?? undefined),
1873
- [activeProject, settings],
1874
- );
1875
- const activeProjectScripts = useMemo(
1876
- () => (activeProject ? resolveProjectScripts(settings, activeProject) : []),
1877
- [activeProject, settings],
1794
+ const activeProjectSettings = resolveProjectSettings(
1795
+ settings,
1796
+ activeProject?.id ?? null,
1797
+ activeProject ?? undefined,
1798
);
1799
+ const activeProjectScripts = activeProject ? resolveProjectScripts(settings, activeProject) : [];
1800
const activeProjectClone = useProjectClone(activeProjectRef);
1801
const cancelProjectClone = useAtomCommand(sourceControlEnvironment.cancelProjectClone, {
1802
reportFailure: false,
@@ -1909,7 +1830,7 @@ export default function ChatView(props: ChatViewProps) {
1830
: activeProjectClone.phase === "done"
1831
? null
1832
: "Repository not cloned";
1912
- const projectCloneBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
1833
+ const projectCloneBannerItem = (() => {
1834
if (!activeProjectClone || !activeProjectRef || activeProjectClone.phase === "done") {
1835
return null;
1836
}
@@ -1968,14 +1889,7 @@ export default function ChatView(props: ChatViewProps) {
1889
</>
1890
),
1891
};
1971
- }, [
1972
- activeProjectClone,
1973
- activeProjectRef,
1974
- cancelProjectClone,
1975
- removeClonedProject,
1976
- retryProjectClone,
1977
- runProjectCloneActionStable,
1978
- ]);
1892
+ })() as ComposerBannerStackItem | null;
1893
const activeProjectDefaultModelSelection = activeProjectSettings.settings.defaultModelSelection;
1894
const handleNewThreadInActiveProject = () => {
1895
startNewThreadForProject(activeProjectRef, handleNewThread);
@@ -2023,10 +1937,7 @@ export default function ChatView(props: ChatViewProps) {
1937
});
1938
};
1939
const handleFilePendingChangeStable = useStableCallback(handleFilePendingChange);
2026
- const configuredPreviewUrls = useMemo(
2027
- () => getConfiguredPreviewUrls(activeProjectScripts),
2028
- [activeProjectScripts],
2029
- );
1940
+ const configuredPreviewUrls = getConfiguredPreviewUrls(activeProjectScripts);
1941
1942
useEffect(() => {
1943
if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return;
@@ -2056,14 +1967,13 @@ export default function ChatView(props: ChatViewProps) {
1967
reconnectWarningGraceElapsedEnvironmentId,
1968
);
1969
useEffect(() => {
2059
- setReconnectWarningGraceElapsedEnvironmentId(null);
1970
if (activeReconnectingEnvironmentId === null) return;
1971
return scheduleEnvironmentReconnectWarning(() =>
1972
setReconnectWarningGraceElapsedEnvironmentId(activeReconnectingEnvironmentId),
1973
);
1974
}, [activeReconnectingEnvironmentId]);
1975
const activeEnvironmentUnavailableLabel = activeEnvironment?.label ?? null;
2066
- const activeEnvironmentUnavailableState = useMemo<EnvironmentUnavailableState | null>(() => {
1976
+ const activeEnvironmentUnavailableState = (() => {
1977
if (!activeEnvironmentUnavailable || !activeEnvironmentUnavailableLabel || !activeEnvironment) {
1978
return null;
1979
}
@@ -2073,7 +1983,7 @@ export default function ChatView(props: ChatViewProps) {
1983
label: activeEnvironmentUnavailableLabel,
1984
connection: activeEnvironment.connection,
1985
};
2076
- }, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]);
1986
+ })() as EnvironmentUnavailableState | null;
1987
const handleReconnectActiveEnvironment = async (environmentId: EnvironmentId) => {
1988
const result = await retryEnvironment(environmentId);
1989
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
@@ -2128,7 +2038,7 @@ export default function ChatView(props: ChatViewProps) {
2038
activeProject,
2039
environmentById.get(activeProject.environmentId)?.serverConfig?.scratchWorkspaceRoot ?? null,
2040
);
2131
- const logicalProjectEnvironments = useMemo(() => {
2041
+ const logicalProjectEnvironments = (() => {
2042
if (!activeProject) return [];
2043
const envs: EnvironmentOption[] = [];
2044
const pushEnvironment = (environmentId: EnvironmentId, projectId: ProjectId | null) => {
@@ -2174,17 +2084,7 @@ export default function ChatView(props: ChatViewProps) {
2084
return a.label.localeCompare(b.label);
2085
});
2086
return envs;
2177
- }, [
2178
- activeProject,
2179
- activeProjectIsScratch,
2180
- allProjects,
2181
- draftId,
2182
- environments,
2183
- projectGroupingSettings,
2184
- primaryEnvironmentId,
2185
- environmentById,
2186
- scratchWorkspaceRootFor,
2187
- ]);
2087
+ })();
2088
const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;
2089
const canAutoBalanceEnvironments = hasMultipleEnvironments && !activeProjectIsScratch;
2090
const activeEnvironmentOption =
@@ -2387,16 +2287,12 @@ export default function ChatView(props: ChatViewProps) {
2287
(!draftThread?.branch || draftThread.environmentSelection === "auto") &&
2288
!draftThread?.worktreePath,
2289
);
2390
- const autoUpdateEnvironments = useMemo(
2391
- () =>
2392
- automaticEnvironment
2393
- ? logicalProjectEnvironments.flatMap(({ environmentId }) => {
2394
- const environment = environmentById.get(environmentId);
2395
- return environment ? [environment] : [];
2396
- })
2397
- : [],
2398
- [automaticEnvironment, logicalProjectEnvironments, environmentById],
2399
- );
2290
+ const autoUpdateEnvironments = automaticEnvironment
2291
+ ? logicalProjectEnvironments.flatMap(({ environmentId }) => {
2292
+ const environment = environmentById.get(environmentId);
2293
+ return environment ? [environment] : [];
2294
+ })
2295
+ : [];
2296
const autoBalanceUpdateBanner = useAutoBalanceUpdateBanner(autoUpdateEnvironments);
2297
const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);
2298
const versionMismatchDismissKey =
@@ -2430,7 +2326,7 @@ export default function ChatView(props: ChatViewProps) {
2326
const serverUpdateFailureDismissed =
2327
serverUpdateState === dismissedServerUpdateState ||
2328
isServerUpdateFailureDismissed(serverUpdateState);
2433
- const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
2329
+ const systemComposerBannerItems = (() => {
2330
const items: ComposerBannerStackItem[] = [];
2331
const updateRunning = serverUpdateState.status === "running";
2332
const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null;
@@ -2563,38 +2459,13 @@ export default function ChatView(props: ChatViewProps) {
2459
}
2460
if (autoBalanceUpdateBanner) items.push(autoBalanceUpdateBanner);
2461
return items;
2566
- }, [
2567
- automaticEnvironment,
2568
- autoBalanceUpdateBanner,
2569
- activeEnvironmentUnavailableState,
2570
- handleReconnectActiveEnvironmentStable,
2571
- canDisconnectActiveEnvironment,
2572
- disconnectingEnvironment,
2573
- handleDisconnectActiveEnvironmentStable,
2574
- setDismissedVersionMismatchKey,
2575
- showVersionMismatchBanner,
2576
- reconnectWarningGraceElapsed,
2577
- serverUpdateFailureDismissed,
2578
- serverUpdateState,
2579
- versionMismatch,
2580
- versionMismatchDismissKey,
2581
- serverUpdateEnvironmentId,
2582
- versionMismatchSelfUpdate,
2583
- versionMismatchInstallation,
2584
- versionMismatchDesktopAppUpdate,
2585
- versionMismatchThreadContinuation,
2586
- versionMismatchServerLabel,
2587
- ]);
2588
- const providerInstanceEntries = useMemo(
2589
- () =>
2590
- sortProviderInstanceEntries(
2591
- applyProviderInstanceSettings(
2592
- deriveProviderInstanceEntries(providerStatuses),
2593
- settings,
2594
- activeProject?.id ?? null,
2595
- ),
2596
- ),
2597
- [providerStatuses, settings, activeProject?.id],
2462
+ })() as ComposerBannerStackItem[];
2463
+ const providerInstanceEntries = sortProviderInstanceEntries(
2464
+ applyProviderInstanceSettings(
2465
+ deriveProviderInstanceEntries(providerStatuses),
2466
+ settings,
2467
+ activeProject?.id ?? null,
2468
+ ),
2469
);
2470
const activeThreadModelInstanceId = activeThread?.modelSelection.instanceId;
2471
const { selectedProviderEntry, requestedDriverKind } = resolveComposerProviderSelection({
@@ -2668,12 +2539,12 @@ export default function ChatView(props: ChatViewProps) {
2539
composerRef,
2540
setThreadError,
2541
});
2671
- const activeProposedPlan = useMemo(() => {
2542
+ const activeProposedPlan = (() => {
2543
if (!latestRunSettled) {
2544
return null;
2545
}
2546
return findLatestProposedPlan(serverProjection, activeLatestRun?.runId ?? null);
2676
- }, [activeLatestRun?.runId, latestRunSettled, serverProjection]);
2547
+ })();
2548
const showPlanFollowUpPrompt = shouldShowPlanFollowUpPrompt({
2549
pendingUserInputCount: pendingUserInputs.length,
2550
interactionMode,
@@ -2752,18 +2623,14 @@ export default function ChatView(props: ChatViewProps) {
2623
isConnecting ||
2624
isCompacting ||
2625
runlessWorkStartedAt !== null;
2755
- const activeContextWindow = useMemo(
2756
- () =>
2757
- deriveLatestContextWindowSnapshot(
2758
- serverVisibleTurnItems ?? [],
2759
- activeThreadLiveTokenUsage,
2760
- serverProjection?.providerThreads.find(
2761
- (thread) => thread.id === serverProjection.thread.activeProviderThreadId,
2762
- ),
2763
- ),
2764
- [activeThreadLiveTokenUsage, serverVisibleTurnItems, serverProjection],
2626
+ const activeContextWindow = deriveLatestContextWindowSnapshot(
2627
+ serverVisibleTurnItems ?? [],
2628
+ activeThreadLiveTokenUsage,
2629
+ serverProjection?.providerThreads.find(
2630
+ (thread) => thread.id === serverProjection.thread.activeProviderThreadId,
2631
+ ),
2632
);
2766
- const pendingBackgroundTasks = useMemo(() => {
2633
+ const pendingBackgroundTasks = (() => {
2634
if (serverProjection === null || serverProjection === undefined) {
2635
return [];
2636
}
@@ -2787,7 +2654,7 @@ export default function ChatView(props: ChatViewProps) {
2654
pullRequests: serverProjection.thread.pullRequests,
2655
}),
2656
];
2790
- }, [serverProjection]);
2657
+ })();
2658
const activeWorkStartedAt =
2659
deriveActiveWorkStartedAt(activeActivityRun, activeRuntime, localDispatchStartedAt) ??
2660
runlessWorkStartedAt;
@@ -2892,30 +2759,22 @@ export default function ChatView(props: ChatViewProps) {
2759
}
2760
};
2761
const openFileAttachmentStable = useStableCallback(openFileAttachment);
2895
- const serverAttachmentResources = useMemo(
2896
- () =>
2897
- selectHandoffImageResources(
2898
- Object.keys(attachmentPreviewHandoffByMessageId).length === 0
2899
- ? undefined
2900
- : serverVisibleTurnItems.flatMap(({ item }) =>
2901
- item.type === "user_message"
2902
- ? [{ id: item.messageId, role: "user" as const, attachments: item.attachments }]
2903
- : [],
2904
- ),
2905
- attachmentPreviewHandoffByMessageId,
2906
- ),
2907
- [serverVisibleTurnItems, attachmentPreviewHandoffByMessageId],
2762
+ const serverAttachmentResources = selectHandoffImageResources(
2763
+ Object.keys(attachmentPreviewHandoffByMessageId).length === 0
2764
+ ? undefined
2765
+ : serverVisibleTurnItems.flatMap(({ item }) =>
2766
+ item.type === "user_message"
2767
+ ? [{ id: item.messageId, role: "user" as const, attachments: item.attachments }]
2768
+ : [],
2769
+ ),
2770
+ attachmentPreviewHandoffByMessageId,
2771
);
2772
const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources);
2910
- const serverAttachmentUrlById = useMemo(
2911
- () =>
2912
- new Map(
2913
- serverAttachmentResources.flatMap((resource, index) => {
2914
- const url = serverAttachmentUrls[index];
2915
- return url ? [[resource.attachmentId, url] as const] : [];
2916
- }),
2917
- ),
2918
- [serverAttachmentResources, serverAttachmentUrls],
2773
+ const serverAttachmentUrlById = new Map(
2774
+ serverAttachmentResources.flatMap((resource, index) => {
2775
+ const url = serverAttachmentUrls[index];
2776
+ return url ? [[resource.attachmentId, url] as const] : [];
2777
+ }),
2778
);
2779
useEffect(() => {
2780
if (typeof Image === "undefined" || serverVisibleTurnItems.length === 0) {
@@ -3010,7 +2869,7 @@ export default function ChatView(props: ChatViewProps) {
2869
serverAttachmentUrlById,
2870
serverVisibleTurnItems,
2871
]);
3013
- const timelineAttachmentUrlById = useMemo(() => {
2872
+ const timelineAttachmentUrlById = (() => {
2873
const urls = new Map(serverAttachmentUrlById);
2874
for (const row of serverVisibleTurnItems) {
2875
if (row.item.type !== "user_message") continue;
@@ -3025,18 +2884,14 @@ export default function ChatView(props: ChatViewProps) {
2884
}
2885
}
2886
return urls;
3028
- }, [attachmentPreviewHandoffByMessageId, serverAttachmentUrlById, serverVisibleTurnItems]);
3029
- const anchoredTimelineMessages = useMemo(
3030
- () =>
3031
- feedbackSubmissions.flatMap((submission) =>
3032
- submission.status === "interrupted"
3033
- ? []
3034
- : [
3035
- { ...codexFeedbackMessage(submission), runId: null },
3036
- { ...codexFeedbackMessage(submission, "assistant"), runId: null },
3037
- ],
3038
- ),
3039
- [feedbackSubmissions],
2887
+ })();
2888
+ const anchoredTimelineMessages = feedbackSubmissions.flatMap((submission) =>
2889
+ submission.status === "interrupted"
2890
+ ? []
2891
+ : [
2892
+ { ...codexFeedbackMessage(submission), runId: null },
2893
+ { ...codexFeedbackMessage(submission, "assistant"), runId: null },
2894
+ ],
2895
);
2896
const serverTimelineEntries = useIncrementalTimelineEntries(activeThreadKey, {
2897
visibleTurnItems: serverVisibleTurnItems,
@@ -3051,23 +2906,18 @@ export default function ChatView(props: ChatViewProps) {
2906
plans: serverProjection.plans,
2907
}),
2908
});
3054
- const draftTimelineEntries = useMemo(
3055
- () =>
3056
- optimisticUserMessages.map(
3057
- (message) =>
3058
- ({
3059
- id: message.id,
3060
- kind: "message",
3061
- createdAt: message.createdAt,
3062
- message,
3063
- }) as const,
3064
- ),
3065
- [optimisticUserMessages],
2909
+ const draftTimelineEntries = optimisticUserMessages.map(
2910
+ (message) =>
2911
+ ({
2912
+ id: message.id,
2913
+ kind: "message",
2914
+ createdAt: message.createdAt,
2915
+ message,
2916
+ }) as const,
2917
);
2918
const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries;
3068
- const timelineMessages = useMemo(
3069
- () => timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
3070
- [timelineEntries],
2919
+ const timelineMessages = timelineEntries.flatMap((entry) =>
2920
+ entry.kind === "message" ? [entry.message] : [],
2921
);
2922
const displayedTimeline = resolveThreadSwitchTimeline({
2923
loading: timelineEntries.length === 0 && threadSyncPhase !== null,
@@ -3130,7 +2980,7 @@ export default function ChatView(props: ChatViewProps) {
2980
* File tools are explicit; completed commands are included because a shell
2981
* command can mutate the workspace without reporting the paths it touched.
2982
*/
3133
- const workspaceMutationId = useMemo(() => {
2983
+ const workspaceMutationId = (() => {
2984
let itemId: string | null = null;
2985
for (let index = serverVisibleTurnItems.length - 1; index >= 0; index -= 1) {
2986
const item = serverVisibleTurnItems[index]?.item;
@@ -3146,7 +2996,7 @@ export default function ChatView(props: ChatViewProps) {
2996
return itemId === null && latestCheckpointCompletedAt === null
2997
? null
2998
: JSON.stringify([itemId, latestCheckpointCompletedAt]);
3149
- }, [serverVisibleTurnItems, turnDiffSummaries]);
2999
+ })();
3000
3001
const gitCwd = activeProject
3002
? projectScriptCwd({
@@ -3202,17 +3052,13 @@ export default function ChatView(props: ChatViewProps) {
3052
false,
3053
Schema.Boolean,
3054
);
3205
- const nativeResumeCompactionDismissed = useMemo(
3206
- () =>
3207
- hasDismissedResumeCompaction(
3208
- (serverProjection?.runtimeRequests ?? [])
3209
- .filter((request) => request.kind === "user_input" && request.status === "resolved")
3210
- .map((request) => ({
3211
- kind: "user-input.resolved",
3212
- payload: { answers: request.answers },
3213
- })),
3214
- ),
3215
- [serverProjection?.runtimeRequests],
3055
+ const nativeResumeCompactionDismissed = hasDismissedResumeCompaction(
3056
+ (serverProjection?.runtimeRequests ?? [])
3057
+ .filter((request) => request.kind === "user_input" && request.status === "resolved")
3058
+ .map((request) => ({
3059
+ kind: "user-input.resolved",
3060
+ payload: { answers: request.answers },
3061
+ })),
3062
);
3063
useEffect(() => {
3064
if (nativeResumeCompactionDismissed && !resumeCompactionPermanentlyDismissed) {
@@ -3227,11 +3073,9 @@ export default function ChatView(props: ChatViewProps) {
3073
const [dismissedProviderStatusBannerKey, setDismissedProviderStatusBannerKey] = useState<
3074
string | null
3075
>(null);
3230
- useEffect(() => {
3231
- if (providerStatusBannerKey === null && dismissedProviderStatusBannerKey !== null) {
3232
- setDismissedProviderStatusBannerKey(null);
3233
- }
3234
- }, [dismissedProviderStatusBannerKey, providerStatusBannerKey]);
3076
+ if (providerStatusBannerKey === null && dismissedProviderStatusBannerKey !== null) {
3077
+ setDismissedProviderStatusBannerKey(null);
3078
+ }
3079
const visibleProviderStatus = shouldShowProviderStatusBanner(
3080
activeProviderStatus,
3081
dismissedProviderStatusBannerKey,
@@ -3316,31 +3160,31 @@ export default function ChatView(props: ChatViewProps) {
3160
const mountComposerModelStrip =
3161
routeKind === "server" && !mountComposerContextStrip && !showProviderSubagentBar;
3162
const showComposerModelStrip = mountComposerModelStrip && restingComposerControlsVisible;
3319
- const terminalShortcutLabelOptions = useMemo(
3320
- () => ({
3321
- context: {
3322
- terminalFocus: true,
3323
- terminalOpen: Boolean(terminalUiState.terminalOpen),
3324
- },
3325
- }),
3326
- [terminalUiState.terminalOpen],
3327
- );
3328
- const splitTerminalShortcutLabel = useMemo(
3329
- () => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions),
3330
- [keybindings, terminalShortcutLabelOptions],
3163
+ const terminalShortcutLabelOptions = {
3164
+ context: {
3165
+ terminalFocus: true,
3166
+ terminalOpen: Boolean(terminalUiState.terminalOpen),
3167
+ },
3168
+ };
3169
+ const splitTerminalShortcutLabel = shortcutLabelForCommand(
3170
+ keybindings,
3171
+ "terminal.split",
3172
+ terminalShortcutLabelOptions,
3173
);
3332
- const splitTerminalVerticalShortcutLabel = useMemo(
3333
- () =>
3334
- shortcutLabelForCommand(keybindings, "terminal.splitVertical", terminalShortcutLabelOptions),
3335
- [keybindings, terminalShortcutLabelOptions],
3174
+ const splitTerminalVerticalShortcutLabel = shortcutLabelForCommand(
3175
+ keybindings,
3176
+ "terminal.splitVertical",
3177
+ terminalShortcutLabelOptions,
3178
);
3337
- const newTerminalShortcutLabel = useMemo(
3338
- () => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions),
3339
- [keybindings, terminalShortcutLabelOptions],
3179
+ const newTerminalShortcutLabel = shortcutLabelForCommand(
3180
+ keybindings,
3181
+ "terminal.new",
3182
+ terminalShortcutLabelOptions,
3183
);
3341
- const closeTerminalShortcutLabel = useMemo(
3342
- () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions),
3343
- [keybindings, terminalShortcutLabelOptions],
3184
+ const closeTerminalShortcutLabel = shortcutLabelForCommand(
3185
+ keybindings,
3186
+ "terminal.close",
3187
+ terminalShortcutLabelOptions,
3188
);
3189
const onToggleDiff = () => {
3190
if (!isServerThread) {
@@ -3405,6 +3249,7 @@ export default function ChatView(props: ChatViewProps) {
3249
loadBalancing.environmentId,
3250
draftId,
3251
logicalProjectEnvironments,
3252
+ sendInFlightRef,
3253
setDraftThreadContext,
3254
]);
3255
const onAutoEnvironment = () => {
@@ -3440,14 +3285,24 @@ export default function ChatView(props: ChatViewProps) {
3285
: "Auto balance"
3286
: undefined;
3287
3443
- const environmentChangeRef = useRef<{ readonly environmentId: EnvironmentId } | null>(null);
3444
- const [isEnvironmentChanging, setIsEnvironmentChanging] = useState(false);
3288
+ // A change in flight belongs to the draft and project it started on.
3289
+ const environmentChangeScope = `${draftId ?? ""}:${activeProjectKey ?? ""}`;
3290
+ const environmentChangeRef = useRef<{
3291
+ readonly environmentId: EnvironmentId;
3292
+ readonly scope: string;
3293
+ } | null>(null);
3294
+ const environmentChangeScopeRef = useRef("");
3295
useLayoutEffect(() => {
3446
- return () => {
3447
- environmentChangeRef.current = null;
3448
- setIsEnvironmentChanging(false);
3449
- };
3450
- }, [draftId, activeProjectKey]);
3296
+ environmentChangeScopeRef.current = environmentChangeScope;
3297
+ });
3298
+ const readPendingEnvironmentChange = () => {
3299
+ const pending = environmentChangeRef.current;
3300
+ return pending !== null && pending.scope === environmentChangeScopeRef.current ? pending : null;
3301
+ };
3302
+ const [environmentChangingScope, setEnvironmentChangingScope] = useState<string | null>(null);
3303
+ const isEnvironmentChanging = environmentChangingScope === environmentChangeScope;
3304
+ const setIsEnvironmentChanging = (changing: boolean) =>
3305
+ setEnvironmentChangingScope(changing ? environmentChangeScope : null);
3306
3307
const onEnvironmentChange = (nextEnvironmentId: EnvironmentId) => {
3308
if (envLocked || !draftId || sendInFlightRef.current) return;
@@ -3457,13 +3312,14 @@ export default function ChatView(props: ChatViewProps) {
3312
(env) => env.environmentId === nextEnvironmentId,
3313
);
3314
if (!target) return;
3460
- const request = { environmentId: target.environmentId };
3315
+ const request = { environmentId: target.environmentId, scope: environmentChangeScope };
3316
environmentChangeRef.current = request;
3317
setIsEnvironmentChanging(false);
3318
const retarget = (project: (typeof allProjects)[number]) => {
3319
const currentDraft = getDraftSession(draftId);
3320
if (
3321
environmentChangeRef.current !== request ||
3322
+ environmentChangeScopeRef.current !== request.scope ||
3323
sendInFlightRef.current ||
3324
!currentDraft ||
3325
currentDraft.promotedTo ||
@@ -4393,6 +4249,7 @@ export default function ChatView(props: ChatViewProps) {
4249
};
4250
const scrollToEndStable = useStableCallback(scrollToEnd);
4251
useEffect(() => {
4252
+ const composer = composerRef;
4253
let removeListeners: (() => void) | null = null;
4254
let frame: number | null = null;
4255
const attach = (remainingAttempts: number) => {
@@ -4429,7 +4286,7 @@ export default function ChatView(props: ChatViewProps) {
4286
if (event.deltaY > 0) {
4287
timelineScrollIntentRef.current = "toward-end";
4288
if (isAtEndRef.current) {
4432
- composerRef.current?.restoreAfterTimelineReachedEnd();
4289
+ composer.current?.restoreAfterTimelineReachedEnd();
4290
}
4291
} else if (event.deltaY < 0) {
4292
timelineScrollIntentRef.current = "away-from-end";
@@ -4497,7 +4354,7 @@ export default function ChatView(props: ChatViewProps) {
4354
timelineScrollIntentRef.current = "away-from-end";
4355
if (contentScrollsUp()) {
4356
handleManualNavigation();
4500
- composerRef.current?.collapseForTimelineScrollKey(event.key);
4357
+ composer.current?.collapseForTimelineScrollKey(event.key);
4358
}
4359
break;
4360
case "PageDown":
@@ -4507,9 +4364,9 @@ export default function ChatView(props: ChatViewProps) {
4364
if (viewportIsAwayFromEnd()) {
4365
handleManualNavigation();
4366
}
4510
- composerRef.current?.collapseForTimelineScrollKey(event.key);
4367
+ composer.current?.collapseForTimelineScrollKey(event.key);
4368
if (isTimelineAtLogicalEndStable()) {
4512
- composerRef.current?.restoreAfterTimelineReachedEnd();
4369
+ composer.current?.restoreAfterTimelineReachedEnd();
4370
}
4371
break;
4372
default:
@@ -4542,7 +4399,13 @@ export default function ChatView(props: ChatViewProps) {
4399
}
4400
removeListeners?.();
4401
};
4545
- }, [activeThread?.id, isTimelineAtLogicalEndStable, timelineRealContentOverflowsViewportStable]);
4402
+ }, [
4403
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.
4404
+ activeThread?.id,
4405
+ composerRef,
4406
+ isTimelineAtLogicalEndStable,
4407
+ timelineRealContentOverflowsViewportStable,
4408
+ ]);
4409
4410
const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {
4411
if (pendingTimelineAnchorRef.current === messageId) {
@@ -4692,23 +4555,33 @@ export default function ChatView(props: ChatViewProps) {
4555
timelineLiveFollowEnabled,
4556
]);
4557
4695
- useEffect(() => {
4696
- setPullRequestDialogState(null);
4558
+ // A thread switch restores that thread's remembered follow state; the refs
4559
+ // the scroll handlers read catch up after commit.
4560
+ const [timelineThreadReset, setTimelineThreadReset] = useState({
4561
+ threadKey: activeThreadKey,
4562
+ followEnd: true,
4563
+ });
4564
+ if (timelineThreadReset.threadKey !== activeThreadKey) {
4565
const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
4566
+ setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
4567
+ setPullRequestDialogState(null);
4568
+ setTimelineLiveFollowEnabled(followEnd);
4569
+ setShowScrollToBottom(!followEnd);
4570
+ }
4571
+ useEffect(() => {
4572
+ const { followEnd } = timelineThreadReset;
4573
isAtEndRef.current = followEnd;
4574
timelineScrollIntentRef.current = null;
4575
timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
4576
liveFollowUserScrollGenerationRef.current = followEnd
4577
? anchorUserScrollGenerationRef.current
4578
: null;
4704
- setTimelineLiveFollowEnabled(followEnd);
4579
pendingTimelineAnchorRef.current = null;
4580
positionedTimelineAnchorRef.current = null;
4581
settledTimelineAnchorRef.current = null;
4582
activeTimelineAnchorIndexRef.current = null;
4583
showScrollDebouncer.current.cancel();
4710
- setShowScrollToBottom(!followEnd);
4711
- }, [activeThreadKey]);
4584
+ }, [timelineThreadReset]);
4585
4586
useEffect(() => {
4587
if (!activeThread?.id || terminalUiState.terminalOpen) return;
@@ -4781,16 +4654,22 @@ export default function ChatView(props: ChatViewProps) {
4654
// Keyed on the thread, not the draft: a draft's promotion to its server
4655
// route keeps this instance and drops `draftId`, and the send it is still
4656
// dispatching must survive that swap.
4784
- useEffect(() => {
4785
- setOptimisticUserMessages((existing) => {
4786
- for (const message of existing) {
4787
- revokeUserMessagePreviewUrls(message);
4788
- }
4789
- return [];
4790
- });
4657
+ const [optimisticThreadId, setOptimisticThreadId] = useState(threadId);
4658
+ const [retiredOptimisticMessages, setRetiredOptimisticMessages] = useState<
4659
+ ReadonlyArray<ChatMessage>
4660
+ >([]);
4661
+ if (optimisticThreadId !== threadId) {
4662
+ setOptimisticThreadId(threadId);
4663
+ setRetiredOptimisticMessages(optimisticUserMessages);
4664
+ setOptimisticUserMessages([]);
4665
resetLocalDispatch();
4666
setExpandedImage(null);
4793
- }, [resetLocalDispatch, threadId]);
4667
+ }
4668
+ useEffect(() => {
4669
+ for (const message of retiredOptimisticMessages) {
4670
+ revokeUserMessagePreviewUrls(message);
4671
+ }
4672
+ }, [retiredOptimisticMessages]);
4673
4674
const closeExpandedImage = () => {
4675
setExpandedImage(null);
@@ -4811,12 +4690,31 @@ export default function ChatView(props: ChatViewProps) {
4690
activeThread.worktreePath === null &&
4691
!envLocked,
4692
);
4693
+ if (
4694
+ !canOverrideServerThreadEnvMode &&
4695
+ (pendingServerThreadEnvModeEntry !== null || pendingServerThreadBranchEntry !== null)
4696
+ ) {
4697
+ setPendingServerThreadEnvModeEntry(null);
4698
+ setPendingServerThreadBranchEntry(null);
4699
+ }
4700
+ const pendingServerThreadEnvMode =
4701
+ pendingServerThreadEnvModeEntry !== null &&
4702
+ pendingServerThreadEnvModeEntry.threadId === activeThread?.id
4703
+ ? pendingServerThreadEnvModeEntry.mode
4704
+ : null;
4705
+ const pendingServerThreadBranchEntryForThread =
4706
+ pendingServerThreadBranchEntry?.threadId === activeThread?.id
4707
+ ? pendingServerThreadBranchEntry
4708
+ : null;
4709
+ const setPendingServerThreadBranch = (branch: string | null) => {
4710
+ if (activeThread) setPendingServerThreadBranchEntry({ threadId: activeThread.id, branch });
4711
+ };
4712
const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode
4713
? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode)
4714
: derivedEnvMode;
4715
const activeThreadBranch =
4818
- canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined
4819
- ? pendingServerThreadBranch
4716
+ canOverrideServerThreadEnvMode && pendingServerThreadBranchEntryForThread !== null
4717
+ ? pendingServerThreadBranchEntryForThread.branch
4718
: (activeThread?.branch ?? null);
4719
const startFromOrigin = isLocalDraftThread
4720
? (draftThread?.startFromOrigin ?? false)
@@ -4828,18 +4726,14 @@ export default function ChatView(props: ChatViewProps) {
4726
requestedEnvMode: envMode,
4727
isGitRepo,
4728
});
4831
- const localCheckoutBranchMismatch = useMemo(
4832
- () =>
4833
- isServerThread
4834
- ? resolveLocalCheckoutBranchMismatch({
4835
- effectiveEnvMode: envMode,
4836
- activeWorktreePath,
4837
- activeThreadBranch,
4838
- currentGitBranch: gitStatusQuery.data?.refName ?? null,
4839
- })
4840
- : null,
4841
- [activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],
4842
- );
4729
+ const localCheckoutBranchMismatch = isServerThread
4730
+ ? resolveLocalCheckoutBranchMismatch({
4731
+ effectiveEnvMode: envMode,
4732
+ activeWorktreePath,
4733
+ activeThreadBranch,
4734
+ currentGitBranch: gitStatusQuery.data?.refName ?? null,
4735
+ })
4736
+ : null;
4737
const publishComposerOverlayHeight = (height: number) => {
4738
const nextHeight = Math.ceil(height);
4739
if (nextHeight <= 0) return;
@@ -4901,6 +4795,7 @@ export default function ChatView(props: ChatViewProps) {
4795
if (!composerOverlayElement) return;
4796
composerTimelineInsetRef.current = 0;
4797
publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
4798
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch must re-measure the overlay for the new timeline.
4799
}, [activeThreadKey, composerOverlayElement, publishComposerOverlayHeightStable]);
4800
4801
useLayoutEffect(() => {
@@ -4912,6 +4807,7 @@ export default function ChatView(props: ChatViewProps) {
4807
4808
updateHeight();
4809
return observeResize(composerOverlayElement, updateHeight);
4810
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- The scroll-to-bottom button changes the overlay's height without resizing the observed node first.
4811
}, [composerOverlayElement, publishComposerOverlayHeightStable, showScrollToBottom]);
4812
useLayoutEffect(() => {
4813
if (composerMountedRef.current === composerMounted) return;
@@ -4921,24 +4817,15 @@ export default function ChatView(props: ChatViewProps) {
4817
publishComposerOverlayHeightStable(composerOverlayElement.getBoundingClientRect().height);
4818
}, [composerMounted, composerOverlayElement, publishComposerOverlayHeightStable]);
4819
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(activeThreadRef);
4924
- const activeThreadReferenceCopyTarget = useMemo(
4925
- () =>
4926
- activeThreadId === null || !isServerThread
4927
- ? null
4928
- : resolveThreadReferenceCopyTarget({
4929
- threadId: activeThreadId,
4930
- openPanelPullRequestUrl,
4931
- pullRequests: activeThread?.pullRequests,
4932
- linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
4933
- }),
4934
- [
4935
- activeThreadId,
4936
- isServerThread,
4937
- activeThread?.pullRequests,
4938
- linkedThreadPullRequest?.url,
4939
- openPanelPullRequestUrl,
4940
- ],
4941
- );
4820
+ const activeThreadReferenceCopyTarget =
4821
+ activeThreadId === null || !isServerThread
4822
+ ? null
4823
+ : resolveThreadReferenceCopyTarget({
4824
+ threadId: activeThreadId,
4825
+ openPanelPullRequestUrl,
4826
+ pullRequests: activeThread?.pullRequests,
4827
+ linkedPullRequestUrl: linkedThreadPullRequest?.url ?? null,
4828
+ });
4829
const copyActiveThreadReference = () => {
4830
const target = activeThreadReferenceCopyTarget;
4831
if (target === null) return;
@@ -4989,7 +4876,6 @@ export default function ChatView(props: ChatViewProps) {
4876
effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() });
4877
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
4878
useEffect(() => {
4992
- void snoozeWakeTick;
4879
if (!activeThreadSnoozed) return;
4880
const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");
4881
if (!Number.isFinite(wakeAtMs)) return;
@@ -4998,6 +4884,7 @@ export default function ChatView(props: ChatViewProps) {
4884
Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),
4885
);
4886
return () => window.clearTimeout(id);
4887
+ // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A tick that lands before the wake time (timer clamping, clock skew) re-arms the timer.
4888
}, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);
4889
const activeThreadWokeAt =
4890
activeThreadShell !== null && supportsSnooze
@@ -5119,14 +5006,14 @@ export default function ChatView(props: ChatViewProps) {
5006
wasShownForCurrentMismatch:
5007
revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,
5008
});
5122
- useEffect(() => {
5123
- setRevealedBranchMismatchKey((revealed) => {
5124
- if (showBranchMismatchBanner) {
5125
- return activeBranchMismatchKey;
5126
- }
5127
- return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;
5128
- });
5129
- }, [activeBranchMismatchKey, showBranchMismatchBanner]);
5009
+ const nextRevealedBranchMismatchKey = showBranchMismatchBanner
5010
+ ? activeBranchMismatchKey
5011
+ : revealedBranchMismatchKey !== activeBranchMismatchKey
5012
+ ? null
5013
+ : revealedBranchMismatchKey;
5014
+ if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) {
5015
+ setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey);
5016
+ }
5017
const handleSwitchCheckoutToThread = async () => {
5018
if (!canWriteSourceControl) return;
5019
if (
@@ -5225,7 +5112,7 @@ export default function ChatView(props: ChatViewProps) {
5112
};
5113
const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread);
5114
const childThreadInputs = useChildThreadInputs(activeThreadRef);
5228
- const childInputBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
5115
+ const childInputBannerItem = (() => {
5116
const first = childThreadInputs[0];
5117
const parentAwaitingUser =
5118
activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput;
@@ -5253,13 +5140,7 @@ export default function ChatView(props: ChatViewProps) {
5140
</Button>
5141
),
5142
};
5256
- }, [
5257
- childThreadInputs,
5258
- activePendingApproval,
5259
- activePendingUserInput,
5260
- activeThreadShell?.hasPendingUserInput,
5261
- onOpenRelatedThreadStable,
5262
- ]);
5143
+ })() as ComposerBannerStackItem | null;
5144
5145
const sendStandaloneCommand = async (text: string, failureMessage: string) => {
5146
if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return;
@@ -5323,7 +5204,7 @@ export default function ChatView(props: ChatViewProps) {
5204
};
5205
const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand);
5206
const activeGoal = activeThreadShell?.goal ?? null;
5326
- const goalBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
5207
+ const goalBannerItem = (() => {
5208
if (!activeThread || activeGoal === null) return null;
5209
const presentation = presentProviderGoal(activeGoal, isWorking);
5210
return {
@@ -5359,9 +5240,9 @@ export default function ChatView(props: ChatViewProps) {
5240
</>
5241
),
5242
};
5362
- }, [activeGoal, activeThread, isWorking, sendStandaloneCommandStable]);
5243
+ })() as ComposerBannerStackItem | null;
5244
5364
- const backgroundWorkBannerItem = useMemo<ComposerBannerStackItem | null>(() => {
5245
+ const backgroundWorkBannerItem = (() => {
5246
const presentation = presentPendingBackgroundWork(activeBackgroundTasks);
5247
if (presentation === null || !activeThread) {
5248
return null;
@@ -5420,14 +5301,7 @@ export default function ChatView(props: ChatViewProps) {
5301
</Button>
5302
),
5303
};
5423
- }, [
5424
- activeBackgroundTasks,
5425
- activeThread,
5426
- canOperateThread,
5427
- handleStopBackgroundWorkStable,
5428
- isStoppingBackgroundWork,
5429
- onOpenRelatedThreadStable,
5430
- ]);
5304
+ })() as ComposerBannerStackItem | null;
5305
// The relative times read the clock; nowMinute re-renders them on the minute.
5306
const snoozedUntil = activeThreadShell?.snoozedUntil ?? null;
5307
const settledAt = activeThreadShell?.settledAt ?? null;
@@ -5462,19 +5336,10 @@ export default function ChatView(props: ChatViewProps) {
5336
item.type === "user_message" &&
5337
(item.text.trim().toLowerCase() !== "/compact" || item.attachments.length > 0),
5338
);
5465
- const pendingHandoff = useMemo(
5466
- () =>
5467
- resolvePendingHandoff(
5468
- serverProjection,
5469
- composerSelectedModelSelection ?? activeThread?.modelSelection,
5470
- providerStatuses,
5471
- ),
5472
- [
5473
- serverProjection,
5474
- composerSelectedModelSelection,
5475
- activeThread?.modelSelection,
5476
- providerStatuses,
5477
- ],
5339
+ const pendingHandoff = resolvePendingHandoff(
5340
+ serverProjection,
5341
+ composerSelectedModelSelection ?? activeThread?.modelSelection,
5342
+ providerStatuses,
5343
);
5344
const compactThreadUnavailable =
5345
!canOperateThread ||
@@ -5542,21 +5407,17 @@ export default function ChatView(props: ChatViewProps) {
5407
void handleSwitchCheckoutToThread();
5408
};
5409
const handleRestoreThreadBranchStable = useStableCallback(handleRestoreThreadBranch);
5545
- const feedbackBannerItems = useMemo(
5546
- () =>
5547
- feedbackSubmissions.flatMap((submission) => {
5548
- const item = feedbackBannerItem(submission, () => {
5549
- setFeedbackSubmissionsByThreadKey((current) => ({
5550
- ...current,
5551
- [routeThreadKey]: (current[routeThreadKey] ?? []).filter(
5552
- (entry) => entry.id !== submission.id,
5553
- ),
5554
- }));
5555
- });
5556
- return item ? [item] : [];
5557
- }),
5558
- [feedbackSubmissions, routeThreadKey],
5559
- );
5410
+ const feedbackBannerItems = feedbackSubmissions.flatMap((submission) => {
5411
+ const item = feedbackBannerItem(submission, () => {
5412
+ setFeedbackSubmissionsByThreadKey((current) => ({
5413
+ ...current,
5414
+ [routeThreadKey]: (current[routeThreadKey] ?? []).filter(
5415
+ (entry) => entry.id !== submission.id,
5416
+ ),
5417
+ }));
5418
+ });
5419
+ return item ? [item] : [];
5420
+ });
5421
const limitRecoveryBanner =
5422
serverRuntime?.status === "failed" &&
5423
serverRuntime.lastErrorClass === "usage_limit" &&
@@ -5576,7 +5437,7 @@ export default function ChatView(props: ChatViewProps) {
5437
},
5438
})
5439
: null;
5579
- const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {
5440
+ const composerBannerItems = (() => {
5441
const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner];
5442
const backgroundWorkItems = [
5443
childInputBannerItem,
@@ -5642,80 +5503,23 @@ export default function ChatView(props: ChatViewProps) {
5503
},
5504
},
5505
];
5645
- }, [
5646
- activeBranchMismatchKey,
5647
- activeThreadShell,
5648
- serverRuntime?.usageLimitResetAt,
5649
- canWriteSourceControl,
5650
- feedbackBannerItems,
5651
- limitRecoveryBanner,
5652
- handleRestoreThreadBranchStable,
5653
- isRestoringThreadBranch,
5654
- backgroundWorkBannerItem,
5655
- childInputBannerItem,
5656
- goalBannerItem,
5657
- localCheckoutBranchMismatch,
5658
- projectCloneBannerItem,
5659
- showBranchMismatchBanner,
5660
- systemComposerBannerItems,
5661
- usageLimitsBanner,
5662
- ]);
5663
-
5664
- useEffect(() => {
5665
- setPendingServerThreadEnvMode(null);
5666
- setPendingServerThreadBranch(undefined);
5667
- }, [activeThread?.id]);
5668
-
5669
- useEffect(() => {
5670
- if (canOverrideServerThreadEnvMode) {
5671
- return;
5672
- }
5673
- setPendingServerThreadEnvMode(null);
5674
- setPendingServerThreadBranch(undefined);
5675
- }, [canOverrideServerThreadEnvMode]);
5676
-
5677
- useEffect(() => {
5678
- if (!activeThreadId) {
5679
- setTerminalUiLaunchContext(null);
5680
- return;
5681
- }
5682
- setTerminalUiLaunchContext((current) => {
5683
- if (!current) return current;
5684
- if (current.threadId === activeThreadId) return current;
5685
- return null;
5686
- });
5687
- }, [activeThreadId]);
5688
-
5689
- useEffect(() => {
5690
- if (!activeThreadId || !activeProjectCwd) {
5691
- return;
5692
- }
5693
- setTerminalUiLaunchContext((current) => {
5694
- if (!current || current.threadId !== activeThreadId) {
5695
- return current;
5696
- }
5697
- const settledCwd = projectScriptCwd({
5698
- project: { cwd: activeProjectCwd },
5699
- worktreePath: activeThreadWorktreePath,
5700
- });
5701
- if (
5702
- settledCwd === current.cwd &&
5703
- (activeThreadWorktreePath ?? null) === current.worktreePath
5704
- ) {
5705
- return null;
5706
- }
5707
- return current;
5708
- });
5709
- }, [activeProjectCwd, activeThreadId, activeThreadWorktreePath]);
5710
-
5711
- useEffect(() => {
5712
- if (terminalUiState.terminalOpen) {
5713
- return;
5714
- }
5715
- setTerminalUiLaunchContext((current) =>
5716
- current?.threadId === activeThreadId ? null : current,
5717
- );
5718
- }, [activeThreadId, terminalUiState.terminalOpen]);
5506
+ })() as ComposerBannerStackItem[];
5507
+
5508
+ // A launch context only overrides the drawer's cwd until the thread's own
5509
+ // location catches up, the drawer closes, or the thread changes.
5510
+ if (
5511
+ terminalUiLaunchContext !== null &&
5512
+ (terminalUiLaunchContext.threadId !== activeThreadId ||
5513
+ !terminalUiState.terminalOpen ||
5514
+ (activeProjectCwd !== null &&
5515
+ projectScriptCwd({
5516
+ project: { cwd: activeProjectCwd },
5517
+ worktreePath: activeThreadWorktreePath,
5518
+ }) === terminalUiLaunchContext.cwd &&
5519
+ (activeThreadWorktreePath ?? null) === terminalUiLaunchContext.worktreePath))
5520
+ ) {
5521
+ setTerminalUiLaunchContext(null);
5522
+ }
5523
5524
useEffect(() => {
5525
if (!activeThreadKey) return;
@@ -5874,7 +5678,7 @@ export default function ChatView(props: ChatViewProps) {
5678
"composer.cycleHost": ({ event }) => {
5679
if (envLocked || !draftId || !hasMultipleEnvironments) return false;
5680
if (event.repeat) return;
5877
- const currentId = environmentChangeRef.current?.environmentId ?? environmentId;
5681
+ const currentId = readPendingEnvironmentChange()?.environmentId ?? environmentId;
5682
const index = logicalProjectEnvironments.findIndex(
5683
(env) => env.environmentId === currentId,
5684
);
@@ -6265,7 +6069,7 @@ export default function ChatView(props: ChatViewProps) {
6069
isRevertingCheckpoint ||
6070
!clientSettingsHydrated ||
6071
threadDetailLoading ||
6268
- environmentChangeRef.current !== null ||
6072
+ readPendingEnvironmentChange() !== null ||
6073
sendInFlightRef.current ||
6074
feedbackUploadsInFlightRef.current.has(routeThreadKey)
6075
) {
@@ -7693,26 +7497,16 @@ export default function ChatView(props: ChatViewProps) {
7497
const hasStartedSession = activeRuntime !== null;
7498
const runtimeProviderInstanceId = activeRuntime?.providerInstanceId ?? null;
7499
const currentModelSelection = activeThread?.modelSelection ?? null;
7696
- const getModelDisabledReason = useMemo(
7697
- () =>
7698
- makeModelDisabledReason(
7699
- currentModelSelection
7700
- ? {
7701
- providers: providerStatuses,
7702
- hasStartedSession,
7703
- supportsProviderSwitchingViaHandoff,
7704
- currentModelSelection,
7705
- currentProviderInstanceId: runtimeProviderInstanceId,
7706
- }
7707
- : null,
7708
- ),
7709
- [
7710
- currentModelSelection,
7711
- hasStartedSession,
7712
- providerStatuses,
7713
- runtimeProviderInstanceId,
7714
- supportsProviderSwitchingViaHandoff,
7715
- ],
7500
+ const getModelDisabledReason = makeModelDisabledReason(
7501
+ currentModelSelection
7502
+ ? {
7503
+ providers: providerStatuses,
7504
+ hasStartedSession,
7505
+ supportsProviderSwitchingViaHandoff,
7506
+ currentModelSelection,
7507
+ currentProviderInstanceId: runtimeProviderInstanceId,
7508
+ }
7509
+ : null,
7510
);
7511
7512
const onProviderModelSelect = (
@@ -7794,7 +7588,7 @@ export default function ChatView(props: ChatViewProps) {
7588
const onEnvModeChange = (mode: DraftThreadEnvMode) => {
7589
if (multipleModelSelections !== null) return;
7590
if (canOverrideServerThreadEnvMode) {
7797
- setPendingServerThreadEnvMode(mode);
7591
+ if (activeThread) setPendingServerThreadEnvModeEntry({ threadId: activeThread.id, mode });
7592
scheduleComposerFocus();
7593
return;
7594
}
@@ -7824,35 +7618,30 @@ export default function ChatView(props: ChatViewProps) {
7618
const onComposerSendStable = useStableCallback(onSend);
7619
const onComposerResumeStable = useStableCallback(onResume);
7620
const onComposerCompactContextStable = useStableCallback(onCompactContext);
7827
- const queuedRunsControl = useMemo(
7828
- () =>
7829
- isServerThread && activeThread ? (
7830
- <QueuedRunsControl
7831
- ref={queuedRunsControlRef}
7832
- steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {
7833
- context: { terminalFocus: false },
7834
- })}
7835
- editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {
7836
- context: { composerFocus: true },
7837
- })}
7838
- environmentId={activeThread.environmentId}
7839
- threadId={activeThread.id}
7840
- optimisticMessages={optimisticUserMessages}
7841
- editingRunId={queuedRunEdit.editingRunId}
7842
- onEditQueuedRun={queuedRunEdit.beginEdit}
7843
- onCancelEdit={queuedRunEdit.cancelEdit}
7844
- />
7845
- ) : null,
7846
- [
7847
- activeThread,
7848
- queuedRunEdit.beginEdit,
7849
- queuedRunEdit.cancelEdit,
7850
- queuedRunEdit.editingRunId,
7851
- isServerThread,
7852
- keybindings,
7853
- optimisticUserMessages,
7854
- ],
7855
- );
7621
+ const queuedRunsControl =
7622
+ isServerThread && activeThread ? (
7623
+ <QueuedRunsControl
7624
+ ref={queuedRunsControlRef}
7625
+ steerShortcutLabel={shortcutLabelForCommand(keybindings, "thread.steerQueuedMessage", {
7626
+ context: { terminalFocus: false },
7627
+ })}
7628
+ editShortcutLabel={shortcutLabelForCommand(keybindings, "thread.editQueuedMessage", {
7629
+ context: { composerFocus: true },
7630
+ })}
7631
+ environmentId={activeThread.environmentId}
7632
+ threadId={activeThread.id}
7633
+ optimisticMessages={optimisticUserMessages}
7634
+ editingRunId={queuedRunEdit.editingRunId}
7635
+ onEditQueuedRun={queuedRunEdit.beginEdit}
7636
+ onCancelEdit={queuedRunEdit.cancelEdit}
7637
+ />
7638
+ ) : null;
7639
+ // One-shot: the resend "Work locally" queued fires once, then the marker clears.
7640
+ const resendAfterWorkLocally = () => {
7641
+ setWorkLocallyResendDraftId(null);
7642
+ void onComposerSendStable();
7643
+ };
7644
+ const resendAfterWorkLocallyStable = useStableCallback(resendAfterWorkLocally);
7645
const workLocallyResendReady =
7646
workLocallyResendDraftId !== null &&
7647
workLocallyResendDraftId === draftId &&
@@ -7878,10 +7667,12 @@ export default function ChatView(props: ChatViewProps) {
7667
setDraftThreadContext(composerDraftTarget, { envMode: "local", startFromOrigin: false });
7668
return;
7669
}
7881
- setWorkLocallyResendDraftId(null);
7882
- void onComposerSendStable();
7670
+ resendAfterWorkLocallyStable();
7671
}, [
7672
composerDraftTarget,
7673
+ feedbackUploadsInFlightRef,
7674
+ resendAfterWorkLocallyStable,
7675
+ sendInFlightRef,
7676
routeThreadKey,
7677
sendEnvMode,
7678
setDraftThreadContext,
apps/web/src/lib/openPullRequestLink.ts
+7
-4
@@ -13,8 +13,9 @@ import { stackedThreadToast, toastManager } from "../components/ui/toast";
13
import { useRightPanelStore } from "../rightPanelStore";
14
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
15
16
-import { useProjects, useServerConfigs } from "../state/entities";
17
-import { serverEnvironment } from "../state/server";
16
+import { appAtomRegistry } from "../rpc/atomRegistry";
17
+import { useProjects } from "../state/entities";
18
+import { environmentServerConfigsAtom, serverEnvironment } from "../state/server";
19
import { usePrimaryEnvironmentId } from "../state/environments";
20
21
export {
@@ -120,12 +121,14 @@ export function useOpenChangeRequestLink(
121
) => boolean {
122
const navigate = useNavigate();
123
const allProjects = useProjects();
123
- const serverConfigs = useServerConfigs();
124
const primaryEnvironmentId = usePrimaryEnvironmentId();
125
const openInApp = useClientSettings((settings) => settings.pullRequestLinksOpenInApp);
126
return useCallback(
127
(event, targetUrl, targetThreadRef, targetEnvironmentId) => {
128
if (!openInApp || shouldOpenPullRequestExternally(event)) return false;
129
+ // Read at click time: every provider status push replaces the config map, and
130
+ // subscribing would hand every rendered link a new handler.
131
+ const serverConfigs = appAtomRegistry.get(environmentServerConfigsAtom);
132
const resolvedThreadRef = targetThreadRef ?? threadRef;
133
const resolvedPanelRef = panelRef ?? resolvedThreadRef;
134
const parsed = parseChangeRequestUrl(targetUrl);
@@ -215,7 +218,7 @@ export function useOpenChangeRequestLink(
218
});
219
return true;
220
},
218
- [allProjects, navigate, openInApp, panelRef, primaryEnvironmentId, serverConfigs, threadRef],
221
+ [allProjects, navigate, openInApp, panelRef, primaryEnvironmentId, threadRef],
222
);
223
}
224
apps/web/src/reactCompiledFiles.test.ts
+10
-13
@@ -4,7 +4,7 @@ import * as NodePath from "node:path";
4
import * as NodeURL from "node:url";
5
import { transform } from "oxc-transform-react";
6
import { describe, expect, it } from "vite-plus/test";
7
-import { REACT_COMPILED_FILES, REACT_COMPILED_FILES_PENDING_LINT } from "../reactCompiledFiles";
7
+import { REACT_COMPILED_FILES } from "../reactCompiledFiles";
8
9
const repoRoot = NodePath.resolve(
10
NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)),
@@ -23,16 +23,13 @@ function expandPattern(pattern: string): string[] {
23
// Lint reports most compiler bailouts, but not every one (try/finally, throw
24
// inside try). A skipped file still builds, just unmemoized, so check the output.
25
describe("React Compiler coverage", () => {
26
- it.each([...REACT_COMPILED_FILES, ...REACT_COMPILED_FILES_PENDING_LINT].flatMap(expandPattern))(
27
- "compiles %s",
28
- async (file) => {
29
- const absolute = NodePath.join(repoRoot, file);
30
- const result = await transform(absolute, NodeFS.readFileSync(absolute, "utf8"), {
31
- jsx: { runtime: "automatic", development: false, refresh: false },
32
- reactCompiler: { reportDiagnostics: true },
33
- });
34
- const bailouts = result.errors.map((error) => error.codeframe ?? error.message);
35
- expect(bailouts).toEqual([]);
36
- },
37
- );
26
+ it.each(REACT_COMPILED_FILES.flatMap(expandPattern))("compiles %s", async (file) => {
27
+ const absolute = NodePath.join(repoRoot, file);
28
+ const result = await transform(absolute, NodeFS.readFileSync(absolute, "utf8"), {
29
+ jsx: { runtime: "automatic", development: false, refresh: false },
30
+ reactCompiler: { reportDiagnostics: true },
31
+ });
32
+ const bailouts = result.errors.map((error) => error.codeframe ?? error.message);
33
+ expect(bailouts).toEqual([]);
34
+ });
35
}, 120_000);