The best way to control Claude Code, Codex and more from any computer or phone
Reset ChatView per thread and simplify derived state handling
- Mount `ChatView` with `key={threadId}` to fully reset UI state on thread switch - Replace effect-driven local state with direct derived values and cleaner cleanup paths - Simplify async command/script flows and minor context memo handling in sidebar/ui components
Julius Marminge committed
Mar 2, 2026 at 11:27 UTC
4fca60469dfc5dab7d8d742e965f4ab260f20c3c
5 files changed
+168
-213
apps/web/src/components/ChatView.tsx
+133
-177
@@ -485,7 +485,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
485
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
486
const [isConnecting, _setIsConnecting] = useState(false);
487
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
488
- const [envMode, setEnvMode] = useState<DraftThreadEnvMode>("local");
488
const [isSwitchingRuntimeMode, setIsSwitchingRuntimeMode] = useState(false);
489
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
490
const [expandedWorkGroups, setExpandedWorkGroups] = useState<Record<string, boolean>>({});
@@ -505,7 +504,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
504
const textareaRef = useRef<HTMLTextAreaElement>(null);
505
const composerFormRef = useRef<HTMLFormElement>(null);
506
const composerFormHeightRef = useRef(0);
508
- const composerCommandInputRef = useRef<HTMLInputElement>(null);
507
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
508
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
509
const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef<Record<string, number>>({});
@@ -558,7 +556,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
556
557
const serverThread = threads.find((t) => t.id === threadId);
558
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
561
- const localDraftError = localDraftErrorsByThreadId[threadId] ?? null;
559
+ const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
560
const localDraftThread = useMemo(
561
() =>
562
draftThread
@@ -584,19 +582,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
582
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
583
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
584
587
- useEffect(() => {
588
- if (!serverThread) {
589
- return;
590
- }
591
- setLocalDraftErrorsByThreadId((existing) => {
592
- if (!(threadId in existing)) {
593
- return existing;
594
- }
595
- const { [threadId]: _removed, ...rest } = existing;
596
- return rest as Record<ThreadId, string | null>;
597
- });
598
- }, [serverThread, threadId]);
599
-
585
useEffect(() => {
586
if (!activeThread?.id) return;
587
if (!latestTurnSettled) return;
@@ -618,27 +603,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
603
const baseThreadModel = resolveModelSlug(activeThread?.model ?? activeProject?.model ?? DEFAULT_MODEL);
604
const selectedModel = resolveModelSlug(composerDraft.model ?? baseThreadModel);
605
const selectedEffort = composerDraft.effort ?? DEFAULT_REASONING;
621
- const modelOptions = useMemo(
622
- () => getAppModelOptions(settings.customCodexModels, selectedModel),
623
- [selectedModel, settings.customCodexModels],
624
- );
606
+ const modelOptions = getAppModelOptions(settings.customCodexModels, selectedModel);
607
const phase = derivePhase(activeThread?.session ?? null);
608
const isSendBusy = sendPhase !== "idle";
609
const isPreparingWorktree = sendPhase === "preparing-worktree";
610
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
611
const nowIso = new Date(nowTick).toISOString();
612
const threadActivities = activeThread?.activities ?? [];
631
- const workLogEntries = useMemo(
632
- () => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
633
- [activeLatestTurn?.turnId, threadActivities],
634
- );
635
- const latestTurnHasToolActivity = useMemo(() => {
636
- return hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId);
637
- }, [activeLatestTurn?.turnId, threadActivities]);
638
- const pendingApprovals = useMemo(
639
- () => derivePendingApprovals(threadActivities),
640
- [threadActivities],
641
- );
613
+ const workLogEntries = deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined);
614
+ const latestTurnHasToolActivity = hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId);
615
+ const pendingApprovals = derivePendingApprovals(threadActivities);
616
useEffect(() => {
617
attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;
618
}, [attachmentPreviewHandoffByMessageId]);
@@ -655,6 +629,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
629
attachmentPreviewHandoffByMessageIdRef.current = {};
630
setAttachmentPreviewHandoffByMessageId({});
631
}, []);
632
+ useEffect(() => {
633
+ return () => {
634
+ clearAttachmentPreviewHandoffs();
635
+ };
636
+ }, [clearAttachmentPreviewHandoffs]);
637
const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {
638
if (previewUrls.length === 0) return;
639
@@ -686,14 +665,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
665
}
666
setAttachmentPreviewHandoffByMessageId((existing) => {
667
if (!(messageId in existing)) return existing;
689
- const { [messageId]: _removed, ...rest } = existing;
690
- attachmentPreviewHandoffByMessageIdRef.current = rest;
691
- return rest;
668
+ const next = { ...existing };
669
+ delete next[messageId];
670
+ attachmentPreviewHandoffByMessageIdRef.current = next;
671
+ return next;
672
});
673
delete attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId];
674
}, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS);
675
}, []);
696
- const timelineMessages = useMemo(() => {
676
+ const timelineMessages = (() => {
677
const serverMessages = activeThread?.messages ?? [];
678
const serverMessagesWithPreviewHandoff =
679
Object.keys(attachmentPreviewHandoffByMessageId).length === 0
@@ -737,11 +717,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
717
return serverMessagesWithPreviewHandoff;
718
}
719
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
740
- }, [activeThread?.messages, attachmentPreviewHandoffByMessageId, optimisticUserMessages]);
741
- const timelineEntries = useMemo(
742
- () => deriveTimelineEntries(timelineMessages, workLogEntries),
743
- [timelineMessages, workLogEntries],
744
- );
720
+ })();
721
+ const timelineEntries = deriveTimelineEntries(timelineMessages, workLogEntries);
722
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
723
useTurnDiffSummaries(activeThread);
724
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
@@ -752,7 +729,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
729
}
730
return byMessageId;
731
}, [turnDiffSummaries]);
755
- const revertTurnCountByUserMessageId = useMemo(() => {
732
+ const revertTurnCountByUserMessageId = (() => {
733
const byUserMessageId = new Map<MessageId, number>();
734
for (let index = 0; index < timelineEntries.length; index += 1) {
735
const entry = timelineEntries[index];
@@ -783,9 +760,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
760
}
761
762
return byUserMessageId;
786
- }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
763
+ })();
764
788
- const completionSummary = useMemo(() => {
765
+ const completionSummary = (() => {
766
if (!latestTurnSettled) return null;
767
if (!activeLatestTurn?.startedAt) return null;
768
if (!activeLatestTurn.completedAt) return null;
@@ -793,13 +770,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
770
771
const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt);
772
return elapsed ? `Worked for ${elapsed}` : null;
796
- }, [
797
- activeLatestTurn?.completedAt,
798
- activeLatestTurn?.startedAt,
799
- latestTurnHasToolActivity,
800
- latestTurnSettled,
801
- ]);
802
- const completionDividerBeforeEntryId = useMemo(() => {
773
+ })();
774
+ const completionDividerBeforeEntryId = (() => {
775
if (!latestTurnSettled) return null;
776
if (!activeLatestTurn?.startedAt) return null;
777
if (!activeLatestTurn.completedAt) return null;
@@ -823,13 +795,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
795
}
796
}
797
return inRangeMatch ?? fallbackMatch;
826
- }, [
827
- activeLatestTurn?.completedAt,
828
- activeLatestTurn?.startedAt,
829
- completionSummary,
830
- latestTurnSettled,
831
- timelineEntries,
832
- ]);
798
+ })();
799
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
800
const composerTrigger = useMemo(
801
() => detectComposerTrigger(prompt, composerCursor),
@@ -918,15 +884,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
884
[nonPersistedComposerImageIds],
885
);
886
const keybindings = keybindingsQuery.data ?? EMPTY_KEYBINDINGS;
887
+ const activeProjectCwd = activeProject?.cwd ?? null;
888
+ const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
889
const threadTerminalRuntimeEnv = useMemo(() => {
922
- if (!activeProject?.cwd) return {};
890
+ if (!activeProjectCwd) return {};
891
return projectScriptRuntimeEnv({
892
project: {
925
- cwd: activeProject.cwd,
893
+ cwd: activeProjectCwd,
894
},
927
- worktreePath: activeThread?.worktreePath ?? null,
895
+ worktreePath: activeThreadWorktreePath,
896
});
929
- }, [activeProject?.cwd, activeThread?.worktreePath]);
897
+ }, [activeProjectCwd, activeThreadWorktreePath]);
898
// Default true while loading to avoid toolbar flicker.
899
const isGitRepo = branchesQuery.data?.isRepo ?? true;
900
const splitTerminalShortcutLabel = useMemo(
@@ -1109,20 +1077,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
1077
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
1078
...(options?.env ? { extraEnv: options.env } : {}),
1079
});
1080
+ const openTerminalInput: Parameters<typeof api.terminal.open>[0] = shouldCreateNewTerminal
1081
+ ? {
1082
+ threadId: activeThreadId,
1083
+ terminalId: targetTerminalId,
1084
+ cwd: targetCwd,
1085
+ env: runtimeEnv,
1086
+ cols: SCRIPT_TERMINAL_COLS,
1087
+ rows: SCRIPT_TERMINAL_ROWS,
1088
+ }
1089
+ : {
1090
+ threadId: activeThreadId,
1091
+ terminalId: targetTerminalId,
1092
+ cwd: targetCwd,
1093
+ env: runtimeEnv,
1094
+ };
1095
1096
try {
1114
- await api.terminal.open({
1115
- threadId: activeThreadId,
1116
- terminalId: targetTerminalId,
1117
- cwd: targetCwd,
1118
- env: runtimeEnv,
1119
- ...(shouldCreateNewTerminal
1120
- ? {
1121
- cols: SCRIPT_TERMINAL_COLS,
1122
- rows: SCRIPT_TERMINAL_ROWS,
1123
- }
1124
- : {}),
1125
- });
1097
+ await api.terminal.open(openTerminalInput);
1098
await api.terminal.write({
1099
threadId: activeThreadId,
1100
terminalId: targetTerminalId,
@@ -1140,12 +1112,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
1112
activeThread,
1113
activeThreadId,
1114
gitCwd,
1143
- isLocalDraftThread,
1115
isServerThread,
1116
setTerminalOpen,
1117
setThreadError,
1118
storeNewTerminal,
1119
storeSetActiveTerminal,
1120
+ terminalState.activeTerminalId,
1121
+ terminalState.runningTerminalIds,
1122
+ terminalState.terminalIds,
1123
],
1124
);
1125
const persistProjectScripts = useCallback(
@@ -1369,24 +1343,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
1343
scheduleStickToBottom();
1344
}, [phase, scheduleStickToBottom, timelineEntries]);
1345
1372
- useEffect(() => {
1373
- setExpandedWorkGroups({});
1374
- }, [activeThread?.id]);
1375
-
1376
- useEffect(() => {
1377
- if (!composerMenuOpen) {
1378
- setComposerHighlightedItemId(null);
1379
- return;
1380
- }
1381
- setComposerHighlightedItemId((existing) =>
1382
- existing && composerMenuItems.some((item) => item.id === existing) ? existing : null,
1383
- );
1384
- }, [composerMenuItems, composerMenuOpen]);
1385
-
1386
- useEffect(() => {
1387
- setIsRevertingCheckpoint(false);
1388
- }, [activeThread?.id]);
1389
-
1346
useEffect(() => {
1347
if (!activeThread?.id || terminalState.terminalOpen) return;
1348
const frame = window.requestAnimationFrame(() => {
@@ -1402,16 +1358,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
1358
}, [composerImages]);
1359
1360
useEffect(() => {
1405
- if (!activeThread?.id) {
1406
- clearAttachmentPreviewHandoffs();
1407
- setOptimisticUserMessages((existing) => {
1408
- for (const message of existing) {
1409
- revokeUserMessagePreviewUrls(message);
1410
- }
1411
- return [];
1412
- });
1413
- return;
1414
- }
1361
+ if (!activeThread?.id) return;
1362
if (activeThread.messages.length === 0) {
1363
return;
1364
}
@@ -1420,7 +1367,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
1367
if (removedMessages.length === 0) {
1368
return;
1369
}
1423
- setOptimisticUserMessages((existing) => existing.filter((message) => !serverIds.has(message.id)));
1370
+ const timer = window.setTimeout(() => {
1371
+ setOptimisticUserMessages((existing) =>
1372
+ existing.filter((message) => !serverIds.has(message.id)),
1373
+ );
1374
+ }, 0);
1375
for (const removedMessage of removedMessages) {
1376
const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);
1377
if (previewUrls.length > 0) {
@@ -1429,10 +1380,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
1380
}
1381
revokeUserMessagePreviewUrls(removedMessage);
1382
}
1383
+ return () => {
1384
+ window.clearTimeout(timer);
1385
+ };
1386
}, [
1387
activeThread?.id,
1388
activeThread?.messages,
1435
- clearAttachmentPreviewHandoffs,
1389
handoffAttachmentPreviews,
1390
optimisticUserMessages,
1391
]);
@@ -1441,21 +1394,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
1394
promptRef.current = prompt;
1395
}, [prompt]);
1396
1444
- useEffect(() => {
1445
- clearAttachmentPreviewHandoffs();
1446
- setOptimisticUserMessages((existing) => {
1447
- for (const message of existing) {
1448
- revokeUserMessagePreviewUrls(message);
1449
- }
1450
- return [];
1451
- });
1452
- setSendPhase("idle");
1453
- setComposerHighlightedItemId(null);
1454
- dragDepthRef.current = 0;
1455
- setIsDragOverComposer(false);
1456
- setExpandedImage(null);
1457
- }, [clearAttachmentPreviewHandoffs, threadId]);
1458
-
1397
useEffect(() => {
1398
let cancelled = false;
1399
void (async () => {
@@ -1463,9 +1401,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
1401
clearComposerDraftPersistedAttachments(threadId);
1402
return;
1403
}
1404
+ const getPersistedAttachmentsForThread = () =>
1405
+ useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
1406
try {
1467
- const currentPersistedAttachments =
1468
- useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
1407
+ const currentPersistedAttachments = getPersistedAttachmentsForThread();
1408
const existingPersistedById = new Map(
1409
currentPersistedAttachments.map((attachment) => [attachment.id, attachment]),
1410
);
@@ -1497,8 +1436,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
1436
syncComposerDraftPersistedAttachments(threadId, serialized);
1437
} catch {
1438
const currentImageIds = new Set(composerImages.map((image) => image.id));
1500
- const fallbackPersistedAttachments =
1501
- useComposerDraftStore.getState().draftsByThreadId[threadId]?.persistedAttachments ?? [];
1439
+ const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
1440
const fallbackPersistedIds = fallbackPersistedAttachments
1441
.map((attachment) => attachment.id)
1442
.filter((id) => currentImageIds.has(id));
@@ -1571,19 +1509,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
1509
}, [closeExpandedImage, expandedImage, navigateExpandedImage]);
1510
1511
const activeWorktreePath = activeThread?.worktreePath;
1574
-
1575
- useEffect(() => {
1576
- if (!activeThread?.id) return;
1577
- if (activeWorktreePath) {
1578
- setEnvMode("worktree");
1579
- return;
1580
- }
1581
- if (isLocalDraftThread) {
1582
- setEnvMode(draftThread?.envMode ?? "local");
1583
- return;
1584
- }
1585
- setEnvMode("local");
1586
- }, [activeThread?.id, activeWorktreePath, draftThread?.envMode, isLocalDraftThread]);
1512
+ const envMode: DraftThreadEnvMode = activeWorktreePath
1513
+ ? "worktree"
1514
+ : isLocalDraftThread
1515
+ ? (draftThread?.envMode ?? "local")
1516
+ : "local";
1517
1518
// Auto-resize textarea
1519
useEffect(() => {
@@ -1609,7 +1539,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
1539
const current = Boolean(terminalState.terminalOpen);
1540
1541
if (!previous && current) {
1612
- setTerminalFocusRequestId((value) => value + 1);
1542
+ terminalOpenByThreadRef.current[activeThreadId] = current;
1543
+ return;
1544
} else if (previous && !current) {
1545
terminalOpenByThreadRef.current[activeThreadId] = current;
1546
const frame = window.requestAnimationFrame(() => {
@@ -1922,7 +1853,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
1853
let turnStartSucceeded = false;
1854
let nextThreadBranch = activeThread.branch;
1855
let nextThreadWorktreePath = activeThread.worktreePath;
1925
- try {
1856
+ await (async () => {
1857
// On first message: lock in branch + create worktree if needed.
1858
if (baseBranchForWorktree) {
1859
setSendPhase("preparing-worktree");
@@ -1948,12 +1879,29 @@ export default function ChatView({ threadId }: ChatViewProps) {
1879
}
1880
}
1881
1951
- const titleSeed =
1952
- trimmed ||
1953
- (composerImagesSnapshot.length > 0
1954
- ? `Image: ${composerImagesSnapshot[0]?.name ?? "attachment"}`
1955
- : "New thread");
1882
+ let firstComposerImageName: string | null = null;
1883
+ if (composerImagesSnapshot.length > 0) {
1884
+ const firstComposerImage = composerImagesSnapshot[0];
1885
+ if (firstComposerImage) {
1886
+ firstComposerImageName = firstComposerImage.name;
1887
+ }
1888
+ }
1889
+ let titleSeed = trimmed;
1890
+ if (!titleSeed) {
1891
+ if (firstComposerImageName) {
1892
+ titleSeed = `Image: ${firstComposerImageName}`;
1893
+ } else {
1894
+ titleSeed = "New thread";
1895
+ }
1896
+ }
1897
const title = truncateTitle(titleSeed);
1898
+ let threadCreateModel = selectedModel;
1899
+ if (!threadCreateModel) {
1900
+ threadCreateModel = activeProject.model;
1901
+ }
1902
+ if (!threadCreateModel) {
1903
+ threadCreateModel = DEFAULT_MODEL;
1904
+ }
1905
1906
if (isLocalDraftThread) {
1907
await api.orchestration.dispatchCommand({
@@ -1962,7 +1910,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
1910
threadId: threadIdForSend,
1911
projectId: activeProject.id,
1912
title,
1965
- model: selectedModel ?? activeProject.model ?? DEFAULT_MODEL,
1913
+ model: threadCreateModel,
1914
branch: nextThreadBranch,
1915
worktreePath: nextThreadWorktreePath,
1916
createdAt: activeThread.createdAt,
@@ -1970,16 +1918,30 @@ export default function ChatView({ threadId }: ChatViewProps) {
1918
createdServerThreadForLocalDraft = true;
1919
}
1920
1973
- const setupScript = baseBranchForWorktree
1974
- ? setupProjectScript(activeProject.scripts)
1975
- : null;
1976
- if (setupScript && (isServerThread || createdServerThreadForLocalDraft)) {
1977
- await runProjectScript(setupScript, {
1978
- worktreePath: nextThreadWorktreePath,
1979
- rememberAsLastInvoked: false,
1980
- allowLocalDraftThread: createdServerThreadForLocalDraft,
1981
- ...(nextThreadWorktreePath ? { cwd: nextThreadWorktreePath } : {}),
1982
- });
1921
+ let setupScript: ProjectScript | null = null;
1922
+ if (baseBranchForWorktree) {
1923
+ setupScript = setupProjectScript(activeProject.scripts);
1924
+ }
1925
+ if (setupScript) {
1926
+ let shouldRunSetupScript = false;
1927
+ if (isServerThread) {
1928
+ shouldRunSetupScript = true;
1929
+ } else {
1930
+ if (createdServerThreadForLocalDraft) {
1931
+ shouldRunSetupScript = true;
1932
+ }
1933
+ }
1934
+ if (shouldRunSetupScript) {
1935
+ const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
1936
+ worktreePath: nextThreadWorktreePath,
1937
+ rememberAsLastInvoked: false,
1938
+ allowLocalDraftThread: createdServerThreadForLocalDraft,
1939
+ };
1940
+ if (nextThreadWorktreePath) {
1941
+ setupScriptOptions.cwd = nextThreadWorktreePath;
1942
+ }
1943
+ await runProjectScript(setupScript, setupScriptOptions);
1944
+ }
1945
}
1946
1947
// Auto-title from first message
@@ -2018,7 +1980,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
1980
if (isFirstMessage) {
1981
clearDraftThread(threadIdForSend);
1982
}
2021
- } catch (err) {
1983
+ })().catch(async (err: unknown) => {
1984
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
1985
await api.orchestration
1986
.dispatchCommand({
@@ -2050,7 +2012,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
2012
threadIdForSend,
2013
err instanceof Error ? err.message : "Failed to send message.",
2014
);
2053
- }
2015
+ });
2016
sendInFlightRef.current = false;
2017
setSendPhase("idle");
2018
};
@@ -2074,23 +2036,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
2036
setRespondingRequestIds((existing) =>
2037
existing.includes(requestId) ? existing : [...existing, requestId],
2038
);
2077
- try {
2078
- await api.orchestration.dispatchCommand({
2039
+ await api.orchestration
2040
+ .dispatchCommand({
2041
type: "thread.approval.respond",
2042
commandId: newCommandId(),
2043
threadId: activeThreadId,
2044
requestId,
2045
decision,
2046
createdAt: new Date().toISOString(),
2047
+ })
2048
+ .catch((err: unknown) => {
2049
+ setStoreThreadError(
2050
+ activeThreadId,
2051
+ err instanceof Error ? err.message : "Failed to submit approval decision.",
2052
+ );
2053
});
2086
- } catch (err) {
2087
- setStoreThreadError(
2088
- activeThreadId,
2089
- err instanceof Error ? err.message : "Failed to submit approval decision.",
2090
- );
2091
- } finally {
2092
- setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
2093
- }
2054
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
2055
},
2056
[activeThreadId, setStoreThreadError],
@@ -2130,7 +2090,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
2090
);
2091
const onEnvModeChange = useCallback(
2092
(mode: DraftThreadEnvMode) => {
2133
- setEnvMode(mode);
2093
if (isLocalDraftThread) {
2094
setDraftThreadContext(threadId, { envMode: mode });
2095
}
@@ -2260,16 +2219,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
2219
},
2220
[navigate, threadId],
2221
);
2263
- const onRevertUserMessage = useCallback(
2264
- (messageId: MessageId) => {
2265
- const targetTurnCount = revertTurnCountByUserMessageId.get(messageId);
2266
- if (typeof targetTurnCount !== "number") {
2267
- return;
2268
- }
2269
- void onRevertToTurnCount(targetTurnCount);
2270
- },
2271
- [onRevertToTurnCount, revertTurnCountByUserMessageId],
2272
- );
2222
+ const onRevertUserMessage = (messageId: MessageId) => {
2223
+ const targetTurnCount = revertTurnCountByUserMessageId.get(messageId);
2224
+ if (typeof targetTurnCount !== "number") {
2225
+ return;
2226
+ }
2227
+ void onRevertToTurnCount(targetTurnCount);
2228
+ };
2229
2230
// Empty state: no active thread
2231
if (!activeThread) {
apps/web/src/components/Sidebar.tsx
+29
-26
@@ -443,38 +443,41 @@ export default function Sidebar() {
443
const cwd = rawCwd.trim();
444
if (!cwd || isAddingProject) return;
445
const api = readNativeApi();
446
+ if (!api) return;
447
448
setIsAddingProject(true);
448
- try {
449
- if (!api) return;
450
- const existing = projects.find((project) => project.cwd === cwd);
451
- if (existing) {
452
- focusMostRecentThreadForProject(existing.id);
453
- } else {
454
- const projectId = newProjectId();
455
- const createdAt = new Date().toISOString();
456
- const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
457
- const projectCreated = await api.orchestration
458
- .dispatchCommand({
459
- type: "project.create",
460
- commandId: newCommandId(),
461
- projectId,
462
- title,
463
- workspaceRoot: cwd,
464
- defaultModel: DEFAULT_MODEL,
465
- createdAt,
466
- })
467
- .then(() => true)
468
- .catch(() => false);
469
- if (projectCreated) {
470
- await handleNewThread(projectId).catch(() => undefined);
471
- }
472
- }
473
- } finally {
449
+ const finishAddingProject = () => {
450
setIsAddingProject(false);
451
setNewCwd("");
452
setAddingProject(false);
453
+ };
454
+
455
+ const existing = projects.find((project) => project.cwd === cwd);
456
+ if (existing) {
457
+ focusMostRecentThreadForProject(existing.id);
458
+ finishAddingProject();
459
+ return;
460
+ }
461
+
462
+ const projectId = newProjectId();
463
+ const createdAt = new Date().toISOString();
464
+ const title = cwd.split(/[/\\]/).findLast(isNonEmptyString) ?? cwd;
465
+ const projectCreated = await api.orchestration
466
+ .dispatchCommand({
467
+ type: "project.create",
468
+ commandId: newCommandId(),
469
+ projectId,
470
+ title,
471
+ workspaceRoot: cwd,
472
+ defaultModel: DEFAULT_MODEL,
473
+ createdAt,
474
+ })
475
+ .then(() => true)
476
+ .catch(() => false);
477
+ if (projectCreated) {
478
+ await handleNewThread(projectId).catch(() => undefined);
479
}
480
+ finishAddingProject();
481
},
482
[focusMostRecentThreadForProject, handleNewThread, isAddingProject, projects],
483
);
apps/web/src/components/ui/combobox.tsx
+2
-3
@@ -20,10 +20,9 @@ function Combobox<Value, Multiple extends boolean | undefined = false>(
20
props: ComboboxPrimitive.Root.Props<Value, Multiple>,
21
) {
22
const chipsRef = React.useRef<Element | null>(null);
23
+ const value = React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple]);
24
return (
24
- <ComboboxContext.Provider
25
- value={React.useMemo(() => ({ chipsRef, multiple: !!props.multiple }), [props.multiple])}
26
- >
25
+ <ComboboxContext.Provider value={value}>
26
<ComboboxPrimitive.Root {...props} />
27
</ComboboxContext.Provider>
28
);
apps/web/src/components/ui/toggle-group.tsx
+2
-5
@@ -22,6 +22,7 @@ function ToggleGroup({
22
children,
23
...props
24
}: ToggleGroupPrimitive.Props & VariantProps<typeof toggleVariants>) {
25
+ const value = React.useMemo(() => ({ size, variant }), [size, variant]);
26
return (
27
<ToggleGroupPrimitive
28
className={cn(
@@ -42,11 +43,7 @@ function ToggleGroup({
43
orientation={orientation}
44
{...props}
45
>
45
- <ToggleGroupContext.Provider
46
- value={React.useMemo(() => ({ size, variant }), [size, variant])}
47
- >
48
- {children}
49
- </ToggleGroupContext.Provider>
46
+ <ToggleGroupContext.Provider value={value}>{children}</ToggleGroupContext.Provider>
47
</ToggleGroupPrimitive>
48
);
49
}
apps/web/src/routes/_chat.$threadId.tsx
+2
-2
@@ -185,7 +185,7 @@ function ChatThreadRouteView() {
185
return (
186
<>
187
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
188
- <ChatView threadId={threadId} />
188
+ <ChatView key={threadId} threadId={threadId} />
189
</SidebarInset>
190
<DiffPanelInlineSidebar diffOpen={diffOpen} onCloseDiff={closeDiff} onOpenDiff={openDiff} />
191
</>
@@ -195,7 +195,7 @@ function ChatThreadRouteView() {
195
return (
196
<>
197
<SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">
198
- <ChatView threadId={threadId} />
198
+ <ChatView key={threadId} threadId={threadId} />
199
</SidebarInset>
200
<DiffPanelSheet diffOpen={diffOpen} onCloseDiff={closeDiff}>
201
<Suspense fallback={<DiffLoadingFallback inline={false} />}>