The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 05:30 UTC
perf(web): opening chat and usage dialogs no longer re-renders the whole page (#20859)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 17, 2026 at 03:40 UTC
d56c479345312605bda6ce479b58aa97cd2acd11
5 files changed
+372
-168
apps/web/src/components/ChatView.logic.ts
-5
@@ -786,11 +786,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
786
return previewUrls;
787
}
788
789
-export interface PullRequestDialogState {
790
- initialReference: string | null;
791
- key: number;
792
-}
793
-
789
export { readFileAsDataUrl } from "../lib/imageCompression";
790
791
export function resolveSendEnvMode(input: {
apps/web/src/components/ChatView.tsx
+41
-147
@@ -251,9 +251,6 @@ import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.lo
251
import { RightPanelTabs } from "./RightPanelTabs";
252
import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog";
253
import { useDeviceState } from "~/state/device";
254
-import { DeviceSetup } from "./device/DeviceSetup";
255
-import { Dialog } from "./ui/dialog";
256
-import { WizardPopup } from "./ui/wizard";
254
import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
255
import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
256
import { isEditableFocused } from "../lib/editableFocus";
@@ -391,7 +388,16 @@ import { createPageScrollController, type PageScrollKey } from "./chat/pageScrol
388
import { isTimelineScrollTarget } from "./chat/timelineScrollTarget";
389
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
390
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
394
-import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
391
+import {
392
+ BranchRestoreConfirmHost,
393
+ DeviceSetupDialogHost,
394
+ openBranchRestoreConfirm,
395
+ openDeviceSetupDialog,
396
+ openPullRequestThreadDialog,
397
+ openRevertConfirm,
398
+ PullRequestThreadDialogHost,
399
+ RevertConfirmHost,
400
+} from "./chat/ChatOverlayHosts";
401
import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
402
import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
403
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
@@ -483,7 +489,6 @@ import {
489
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
490
LastInvokedScriptByProjectSchema,
491
type LocalDispatchSnapshot,
486
- PullRequestDialogState,
492
cloneComposerImageForRetry,
493
deriveLockedProvider,
494
readFileAsDataUrl,
@@ -523,15 +528,6 @@ import { useAtomCommand } from "../state/use-atom-command";
528
import { useOrchestrationCommand } from "../state/use-orchestration-command";
529
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
530
import { Button, InlineButton } from "./ui/button";
526
-import {
527
- AlertDialog,
528
- AlertDialogClose,
529
- AlertDialogDescription,
530
- AlertDialogFooter,
531
- AlertDialogHeader,
532
- AlertDialogPopup,
533
- AlertDialogTitle,
534
-} from "./ui/alert-dialog";
531
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
532
import { ServerUpdateAction } from "./ServerUpdateAction";
533
import { useAutoBalanceUpdateBanner } from "./chat/useAutoBalanceUpdateBanner";
@@ -1333,8 +1329,6 @@ export default function ChatView(props: ChatViewProps) {
1329
const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);
1330
const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);
1331
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
1336
- const [pullRequestDialogState, setPullRequestDialogState] =
1337
- useState<PullRequestDialogState | null>(null);
1332
const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
1333
useState<TerminalLaunchContext | null>(null);
1334
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
@@ -2094,17 +2088,11 @@ export default function ChatView(props: ChatViewProps) {
2088
if (!canCheckoutPullRequestIntoThread) {
2089
return;
2090
}
2097
- setPullRequestDialogState({
2098
- initialReference: reference ?? null,
2099
- key: Date.now(),
2100
- });
2091
+ if (activeThreadKey === null) return;
2092
+ openPullRequestThreadDialog(activeThreadKey, reference);
2093
};
2094
const openPullRequestDialogStable = useStableCallback(openPullRequestDialog);
2095
2104
- const closePullRequestDialog = () => {
2105
- setPullRequestDialogState(null);
2106
- };
2107
-
2096
const openOrReuseProjectDraftThread = async (input: {
2097
branch: string;
2098
worktreePath: string | null;
@@ -3738,11 +3726,10 @@ export default function ChatView(props: ChatViewProps) {
3726
const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState(
3727
activeThreadRef?.environmentId ?? null,
3728
);
3741
- const [deviceSetupThread, setDeviceSetupThread] = useState<ScopedThreadRef | null>(null);
3729
const addDeviceSurface = () => {
3730
if (!activeThreadRef) return;
3731
if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
3745
- setDeviceSetupThread(activeThreadRef);
3732
+ openDeviceSetupDialog(scopedThreadKey(activeThreadRef));
3733
return;
3734
}
3735
useRightPanelStore.getState().open(activeThreadRef, "device");
@@ -4572,7 +4559,6 @@ export default function ChatView(props: ChatViewProps) {
4559
if (timelineThreadReset.threadKey !== activeThreadKey) {
4560
const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
4561
setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
4575
- setPullRequestDialogState(null);
4562
setTimelineLiveFollowEnabled(followEnd);
4563
setShowScrollToBottom(!followEnd);
4564
}
@@ -4996,7 +4982,6 @@ export default function ChatView(props: ChatViewProps) {
4982
};
4983
const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
4984
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
4999
- const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
4985
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
4986
const [, setBranchMismatchDismissTick] = useState(0);
4987
const composerHasDraftContent = useComposerDraftStore((store) =>
@@ -5083,6 +5068,9 @@ export default function ChatView(props: ChatViewProps) {
5068
setIsRestoringThreadBranch(false);
5069
scheduleComposerFocus();
5070
};
5071
+ const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
5072
+ void handleSwitchCheckoutToThread();
5073
+ });
5074
// The interrupt path also accepts a completed run while its provider still
5075
// has background work.
5076
const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
@@ -5409,7 +5397,7 @@ export default function ChatView(props: ChatViewProps) {
5397
const handleRestoreThreadBranch = () => {
5398
if (!canWriteSourceControl) return;
5399
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
5412
- setBranchRestoreConfirmOpen(true);
5400
+ if (activeThreadKey !== null) openBranchRestoreConfirm(activeThreadKey);
5401
return;
5402
}
5403
void handleSwitchCheckoutToThread();
@@ -5765,16 +5753,6 @@ export default function ChatView(props: ChatViewProps) {
5753
};
5754
}, [activeThreadId, composerRef]);
5755
5768
- const [pendingRevert, setPendingRevert] = useState<{
5769
- turnCount: number;
5770
- messageId: MessageId;
5771
- routeThreadKey: string;
5772
- } | null>(null);
5773
-
5774
- if (pendingRevert && pendingRevert.routeThreadKey !== routeThreadKey) {
5775
- setPendingRevert(null);
5776
- }
5777
-
5756
const onRevertToTurnCount = async (
5757
turnCount: number,
5758
messageId: MessageId,
@@ -5823,7 +5801,7 @@ export default function ChatView(props: ChatViewProps) {
5801
return;
5802
}
5803
if (restoreFiles === undefined) {
5826
- setPendingRevert({ turnCount, messageId, routeThreadKey });
5804
+ openRevertConfirm(routeThreadKey, { turnCount, messageId });
5805
return;
5806
}
5807
@@ -5862,6 +5840,10 @@ export default function ChatView(props: ChatViewProps) {
5840
}
5841
};
5842
const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount);
5843
+ const onConfirmRevert = (turnCount: number, messageId: MessageId, restoreFiles: boolean) => {
5844
+ void onRevertToTurnCount(turnCount, messageId, restoreFiles);
5845
+ };
5846
+ const onConfirmRevertStable = useStableCallback(onConfirmRevert);
5847
5848
const onRollbackCheckpoint = async (input: {
5849
readonly checkpointId: string;
@@ -7957,29 +7939,11 @@ export default function ChatView(props: ChatViewProps) {
7939
ref={setWorkspaceLayoutElement}
7940
className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background"
7941
>
7960
- <Dialog
7961
- open={
7962
- deviceSetupThread !== null &&
7963
- deviceSetupThread.environmentId === activeThreadRef?.environmentId &&
7964
- deviceSetupThread.threadId === activeThreadRef?.threadId
7965
- }
7966
- onOpenChange={(open) => {
7967
- if (!open) setDeviceSetupThread(null);
7968
- }}
7969
- >
7970
- <WizardPopup>
7971
- {activeThreadRef ? (
7972
- <DeviceSetup
7973
- environmentId={activeThreadRef.environmentId}
7974
- state={deviceState}
7975
- onComplete={() => {
7976
- useRightPanelStore.getState().open(activeThreadRef, "device");
7977
- setDeviceSetupThread(null);
7978
- }}
7979
- />
7980
- ) : null}
7981
- </WizardPopup>
7982
- </Dialog>
7942
+ <DeviceSetupDialogHost
7943
+ threadKey={activeThreadKey}
7944
+ threadRef={activeThreadRef}
7945
+ state={deviceState}
7946
+ />
7947
{rightPanelControlsAtRoot ? panelLayoutControls : null}
7948
<div
7949
className={cn(
@@ -8564,55 +8528,22 @@ export default function ChatView(props: ChatViewProps) {
8528
/>
8529
) : null}
8530
8567
- <AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>
8568
- <AlertDialogPopup>
8569
- <AlertDialogHeader>
8570
- <AlertDialogTitle>
8571
- Switch to{" "}
8572
- <code className="font-medium">
8573
- {localCheckoutBranchMismatch?.threadBranch ?? ""}
8574
- </code>
8575
- ?
8576
- </AlertDialogTitle>
8577
- <AlertDialogDescription>
8578
- You have uncommitted changes. They'll carry over to the other branch, or block
8579
- the switch if they conflict.
8580
- </AlertDialogDescription>
8581
- </AlertDialogHeader>
8582
- <AlertDialogFooter>
8583
- <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
8584
- <Button
8585
- variant="default"
8586
- disabled={!canWriteSourceControl}
8587
- onClick={() => {
8588
- setBranchRestoreConfirmOpen(false);
8589
- void handleSwitchCheckoutToThread();
8590
- }}
8591
- >
8592
- Switch branch
8593
- </Button>
8594
- </AlertDialogFooter>
8595
- </AlertDialogPopup>
8596
- </AlertDialog>
8531
+ <BranchRestoreConfirmHost
8532
+ threadKey={activeThreadKey}
8533
+ threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}
8534
+ canWriteSourceControl={canWriteSourceControl}
8535
+ onConfirm={handleSwitchCheckoutToThreadStable}
8536
+ />
8537
8538
<ThreadDetailsPanel {...threadDetailsPanelProps} />
8539
8600
- {pullRequestDialogState ? (
8601
- <PullRequestThreadDialog
8602
- key={pullRequestDialogState.key}
8603
- open
8604
- environmentId={activeThread.environmentId}
8605
- threadId={activeThread.id}
8606
- cwd={activeProject?.workspaceRoot ?? null}
8607
- initialReference={pullRequestDialogState.initialReference}
8608
- onOpenChange={(open) => {
8609
- if (!open) {
8610
- closePullRequestDialog();
8611
- }
8612
- }}
8613
- onPrepared={handlePreparedPullRequestThreadStable}
8614
- />
8615
- ) : null}
8540
+ <PullRequestThreadDialogHost
8541
+ threadKey={activeThreadKey}
8542
+ environmentId={activeThread.environmentId}
8543
+ threadId={activeThread.id}
8544
+ cwd={activeProject?.workspaceRoot ?? null}
8545
+ onPrepared={handlePreparedPullRequestThreadStable}
8546
+ />
8547
</ThreadFindCanvas>
8548
</div>
8549
@@ -8739,44 +8670,7 @@ export default function ChatView(props: ChatViewProps) {
8670
</RightPanelSheet>
8671
) : null}
8672
8742
- <AlertDialog
8743
- open={pendingRevert !== null && pendingRevert.routeThreadKey === routeThreadKey}
8744
- onOpenChange={(open) => {
8745
- if (!open) setPendingRevert(null);
8746
- }}
8747
- >
8748
- <AlertDialogPopup>
8749
- <AlertDialogHeader>
8750
- <AlertDialogTitle>Edit from here?</AlertDialogTitle>
8751
- <AlertDialogDescription>
8752
- Rewind chat to before this message. Your prompt and attachments return to the
8753
- composer.
8754
- </AlertDialogDescription>
8755
- </AlertDialogHeader>
8756
- <AlertDialogFooter>
8757
- <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
8758
- <Button
8759
- variant="destructive"
8760
- onClick={() => {
8761
- if (!pendingRevert || pendingRevert.routeThreadKey !== routeThreadKey) return;
8762
- setPendingRevert(null);
8763
- void onRevertToTurnCount(pendingRevert.turnCount, pendingRevert.messageId, true);
8764
- }}
8765
- >
8766
- Revert files too
8767
- </Button>
8768
- <Button
8769
- onClick={() => {
8770
- if (!pendingRevert || pendingRevert.routeThreadKey !== routeThreadKey) return;
8771
- setPendingRevert(null);
8772
- void onRevertToTurnCount(pendingRevert.turnCount, pendingRevert.messageId, false);
8773
- }}
8774
- >
8775
- Revert and keep changes
8776
- </Button>
8777
- </AlertDialogFooter>
8778
- </AlertDialogPopup>
8779
- </AlertDialog>
8673
+ <RevertConfirmHost threadKey={routeThreadKey} onConfirm={onConfirmRevertStable} />
8674
<LinkPullRequestDialogHost />
8675
{expandedImage && (
8676
<ExpandedImageDialog
apps/web/src/components/chat/ChatOverlayHosts.browser.test.tsx
new
+54
@@ -0,0 +1,54 @@
1
+import { MessageId } from "@t3tools/contracts";
2
+import { act } from "react";
3
+import { createRoot, type Root } from "react-dom/client";
4
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5
+
6
+import { AppAtomRegistryProvider } from "~/rpc/atomRegistry";
7
+import { openRevertConfirm, RevertConfirmHost } from "./ChatOverlayHosts";
8
+
9
+let root: Root;
10
+let container: HTMLDivElement;
11
+
12
+beforeEach(() => {
13
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
14
+ container = document.createElement("div");
15
+ document.body.append(container);
16
+ root = createRoot(container);
17
+});
18
+
19
+afterEach(async () => {
20
+ await act(() => root.unmount());
21
+ container.remove();
22
+ vi.unstubAllGlobals();
23
+});
24
+
25
+const messageId = MessageId.make("message-1");
26
+const dialog = () => document.querySelector('[role="alertdialog"]');
27
+
28
+describe("RevertConfirmHost", () => {
29
+ it("shows only its thread's request, confirms it once, and drops it when the thread changes", async () => {
30
+ const onConfirm = vi.fn();
31
+ const host = (threadKey: string) => (
32
+ <AppAtomRegistryProvider>
33
+ <RevertConfirmHost threadKey={threadKey} onConfirm={onConfirm} />
34
+ </AppAtomRegistryProvider>
35
+ );
36
+ await act(() => root.render(host("env:a")));
37
+
38
+ await act(() => openRevertConfirm("env:b", { turnCount: 2, messageId }));
39
+ expect(dialog()).toBeNull();
40
+
41
+ await act(() => openRevertConfirm("env:a", { turnCount: 2, messageId }));
42
+ const keep = [...(dialog()?.querySelectorAll("button") ?? [])].find(
43
+ (button) => button.textContent === "Revert and keep changes",
44
+ );
45
+ await act(() => keep?.click());
46
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(2, messageId, false);
47
+ await vi.waitFor(() => expect(dialog()).toBeNull());
48
+
49
+ await act(() => openRevertConfirm("env:a", { turnCount: 3, messageId }));
50
+ expect(dialog()).not.toBeNull();
51
+ await act(() => root.render(host("env:b")));
52
+ await vi.waitFor(() => expect(dialog()).toBeNull());
53
+ });
54
+});
apps/web/src/components/chat/ChatOverlayHosts.tsx
new
+228
@@ -0,0 +1,228 @@
1
+import type {
2
+ DeviceServiceState,
3
+ EnvironmentId,
4
+ MessageId,
5
+ ScopedThreadRef,
6
+ ThreadId,
7
+} from "@t3tools/contracts";
8
+import { useAtomValue } from "@effect/atom-react";
9
+import { Atom } from "effect/reactivity";
10
+import { useEffect } from "react";
11
+
12
+import { appAtomRegistry } from "~/rpc/atomRegistry";
13
+import { useRightPanelStore } from "~/rightPanelStore";
14
+import { DeviceSetup } from "../device/DeviceSetup";
15
+import { PullRequestThreadDialog } from "../PullRequestThreadDialog";
16
+import {
17
+ AlertDialog,
18
+ AlertDialogClose,
19
+ AlertDialogDescription,
20
+ AlertDialogFooter,
21
+ AlertDialogHeader,
22
+ AlertDialogPopup,
23
+ AlertDialogTitle,
24
+} from "../ui/alert-dialog";
25
+import { Button } from "../ui/button";
26
+import { Dialog } from "../ui/dialog";
27
+import { WizardPopup } from "../ui/wizard";
28
+
29
+/**
30
+ * Open state for overlays the chat view hosts. It lives in atoms rather than
31
+ * ChatView state so opening or closing one renders only its host, not the
32
+ * whole chat chrome. Each entry carries the thread it was opened for; a host
33
+ * shows only its own thread's entry and drops it when the thread changes.
34
+ */
35
+type ThreadOverlayAtom<T> = Atom.Writable<{ readonly threadKey: string; readonly value: T } | null>;
36
+
37
+function makeThreadOverlayAtom<T>(label: string): ThreadOverlayAtom<T> {
38
+ return Atom.make<{ readonly threadKey: string; readonly value: T } | null>(null).pipe(
39
+ Atom.keepAlive,
40
+ Atom.withLabel(`chat:${label}`),
41
+ );
42
+}
43
+
44
+function closeThreadOverlay<T>(atom: ThreadOverlayAtom<T>): void {
45
+ appAtomRegistry.set(atom, null);
46
+}
47
+
48
+function useThreadOverlay<T>(atom: ThreadOverlayAtom<T>, threadKey: string | null): T | null {
49
+ const entry = useAtomValue(atom);
50
+ useEffect(
51
+ () => () => {
52
+ if (appAtomRegistry.get(atom)?.threadKey === threadKey) closeThreadOverlay(atom);
53
+ },
54
+ [atom, threadKey],
55
+ );
56
+ return threadKey !== null && entry?.threadKey === threadKey ? entry.value : null;
57
+}
58
+
59
+const pullRequestThreadDialogAtom = makeThreadOverlayAtom<{
60
+ readonly initialReference: string | null;
61
+ readonly key: number;
62
+}>("pull-request-thread-dialog");
63
+
64
+export function openPullRequestThreadDialog(threadKey: string, reference?: string): void {
65
+ appAtomRegistry.set(pullRequestThreadDialogAtom, {
66
+ threadKey,
67
+ value: { initialReference: reference ?? null, key: Date.now() },
68
+ });
69
+}
70
+
71
+export function PullRequestThreadDialogHost(props: {
72
+ readonly threadKey: string | null;
73
+ readonly environmentId: EnvironmentId;
74
+ readonly threadId: ThreadId;
75
+ readonly cwd: string | null;
76
+ readonly onPrepared: (input: {
77
+ branch: string;
78
+ worktreePath: string | null;
79
+ }) => Promise<void> | void;
80
+}) {
81
+ const state = useThreadOverlay(pullRequestThreadDialogAtom, props.threadKey);
82
+ if (state === null) return null;
83
+ return (
84
+ <PullRequestThreadDialog
85
+ key={state.key}
86
+ open
87
+ environmentId={props.environmentId}
88
+ threadId={props.threadId}
89
+ cwd={props.cwd}
90
+ initialReference={state.initialReference}
91
+ onOpenChange={(open) => {
92
+ if (!open) closeThreadOverlay(pullRequestThreadDialogAtom);
93
+ }}
94
+ onPrepared={props.onPrepared}
95
+ />
96
+ );
97
+}
98
+
99
+const deviceSetupDialogAtom = makeThreadOverlayAtom<true>("device-setup-dialog");
100
+
101
+export function openDeviceSetupDialog(threadKey: string): void {
102
+ appAtomRegistry.set(deviceSetupDialogAtom, { threadKey, value: true });
103
+}
104
+
105
+export function DeviceSetupDialogHost(props: {
106
+ readonly threadKey: string | null;
107
+ readonly threadRef: ScopedThreadRef | null;
108
+ readonly state: DeviceServiceState;
109
+}) {
110
+ const open = useThreadOverlay(deviceSetupDialogAtom, props.threadKey) !== null;
111
+ const { threadRef } = props;
112
+ return (
113
+ <Dialog
114
+ open={open}
115
+ onOpenChange={(nextOpen) => {
116
+ if (!nextOpen) closeThreadOverlay(deviceSetupDialogAtom);
117
+ }}
118
+ >
119
+ <WizardPopup>
120
+ {threadRef ? (
121
+ <DeviceSetup
122
+ environmentId={threadRef.environmentId}
123
+ state={props.state}
124
+ onComplete={() => {
125
+ useRightPanelStore.getState().open(threadRef, "device");
126
+ closeThreadOverlay(deviceSetupDialogAtom);
127
+ }}
128
+ />
129
+ ) : null}
130
+ </WizardPopup>
131
+ </Dialog>
132
+ );
133
+}
134
+
135
+const branchRestoreConfirmAtom = makeThreadOverlayAtom<true>("branch-restore-confirm");
136
+
137
+export function openBranchRestoreConfirm(threadKey: string): void {
138
+ appAtomRegistry.set(branchRestoreConfirmAtom, { threadKey, value: true });
139
+}
140
+
141
+export function BranchRestoreConfirmHost(props: {
142
+ readonly threadKey: string | null;
143
+ readonly threadBranch: string;
144
+ readonly canWriteSourceControl: boolean;
145
+ readonly onConfirm: () => void;
146
+}) {
147
+ const open = useThreadOverlay(branchRestoreConfirmAtom, props.threadKey) !== null;
148
+ return (
149
+ <AlertDialog
150
+ open={open}
151
+ onOpenChange={(nextOpen) => {
152
+ if (!nextOpen) closeThreadOverlay(branchRestoreConfirmAtom);
153
+ }}
154
+ >
155
+ <AlertDialogPopup>
156
+ <AlertDialogHeader>
157
+ <AlertDialogTitle>
158
+ Switch to <code className="font-medium">{props.threadBranch}</code>?
159
+ </AlertDialogTitle>
160
+ <AlertDialogDescription>
161
+ You have uncommitted changes. They'll carry over to the other branch, or block the
162
+ switch if they conflict.
163
+ </AlertDialogDescription>
164
+ </AlertDialogHeader>
165
+ <AlertDialogFooter>
166
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
167
+ <Button
168
+ variant="default"
169
+ disabled={!props.canWriteSourceControl}
170
+ onClick={() => {
171
+ closeThreadOverlay(branchRestoreConfirmAtom);
172
+ props.onConfirm();
173
+ }}
174
+ >
175
+ Switch branch
176
+ </Button>
177
+ </AlertDialogFooter>
178
+ </AlertDialogPopup>
179
+ </AlertDialog>
180
+ );
181
+}
182
+
183
+interface PendingRevert {
184
+ readonly turnCount: number;
185
+ readonly messageId: MessageId;
186
+}
187
+
188
+const revertConfirmAtom = makeThreadOverlayAtom<PendingRevert>("revert-confirm");
189
+
190
+export function openRevertConfirm(threadKey: string, pending: PendingRevert): void {
191
+ appAtomRegistry.set(revertConfirmAtom, { threadKey, value: pending });
192
+}
193
+
194
+export function RevertConfirmHost(props: {
195
+ readonly threadKey: string;
196
+ readonly onConfirm: (turnCount: number, messageId: MessageId, restoreFiles: boolean) => void;
197
+}) {
198
+ const pending = useThreadOverlay(revertConfirmAtom, props.threadKey);
199
+ const confirm = (restoreFiles: boolean) => {
200
+ if (pending === null) return;
201
+ closeThreadOverlay(revertConfirmAtom);
202
+ props.onConfirm(pending.turnCount, pending.messageId, restoreFiles);
203
+ };
204
+ return (
205
+ <AlertDialog
206
+ open={pending !== null}
207
+ onOpenChange={(open) => {
208
+ if (!open) closeThreadOverlay(revertConfirmAtom);
209
+ }}
210
+ >
211
+ <AlertDialogPopup>
212
+ <AlertDialogHeader>
213
+ <AlertDialogTitle>Edit from here?</AlertDialogTitle>
214
+ <AlertDialogDescription>
215
+ Rewind chat to before this message. Your prompt and attachments return to the composer.
216
+ </AlertDialogDescription>
217
+ </AlertDialogHeader>
218
+ <AlertDialogFooter>
219
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
220
+ <Button variant="destructive" onClick={() => confirm(true)}>
221
+ Revert files too
222
+ </Button>
223
+ <Button onClick={() => confirm(false)}>Revert and keep changes</Button>
224
+ </AlertDialogFooter>
225
+ </AlertDialogPopup>
226
+ </AlertDialog>
227
+ );
228
+}
apps/web/src/components/usage/UsagePage.tsx
+49
-16
@@ -2,6 +2,7 @@ import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";
2
import { usesChatGptSharing } from "@t3tools/shared/usageLimits";
3
import { RefreshIcon } from "~/components/ui/refresh-icon";
4
import { useAtomValue } from "@effect/atom-react";
5
+import { Atom } from "effect/reactivity";
6
import {
7
ProviderDriverKind,
8
USAGE_CONTRACT_VERSION,
@@ -34,6 +35,7 @@ import {
35
36
import { isElectron } from "../../env";
37
import { cn } from "../../lib/utils";
38
+import { appAtomRegistry } from "~/rpc/atomRegistry";
39
import { environmentPresentations } from "../../state/presentation";
40
import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server";
41
import { isCommandPaletteOpen } from "../../commandPaletteBus";
@@ -133,6 +135,47 @@ function usageLoading(
135
};
136
}
137
138
+/**
139
+ * The model whose detail dialog is open. It lives outside UsagePage so opening
140
+ * or closing the dialog renders only its host, not the whole usage page.
141
+ */
142
+const selectedUsageModelKeyAtom = Atom.make<string | null>(null).pipe(
143
+ Atom.keepAlive,
144
+ Atom.withLabel("usage:selected-model-key"),
145
+);
146
+
147
+function selectUsageModel(key: string | null): void {
148
+ appAtomRegistry.set(selectedUsageModelKeyAtom, key);
149
+}
150
+
151
+function UsageModelDialogHost({
152
+ models,
153
+ onSetPrice,
154
+ ...dialogProps
155
+}: Omit<Parameters<typeof UsageModelDialog>[0], "model" | "onSetPrice" | "onClose"> & {
156
+ readonly models: MergedUsage["models"];
157
+ readonly onSetPrice: (model: string) => void;
158
+}) {
159
+ const selectedKey = useAtomValue(selectedUsageModelKeyAtom);
160
+ useEffect(() => () => selectUsageModel(null), []);
161
+ const model =
162
+ selectedKey === null
163
+ ? undefined
164
+ : models.find((candidate) => `${candidate.provider}:${candidate.model}` === selectedKey);
165
+ if (model === undefined) return null;
166
+ return (
167
+ <UsageModelDialog
168
+ {...dialogProps}
169
+ model={model}
170
+ onSetPrice={() => {
171
+ selectUsageModel(null);
172
+ onSetPrice(model.model);
173
+ }}
174
+ onClose={() => selectUsageModel(null)}
175
+ />
176
+ );
177
+}
178
+
179
export function UsagePage() {
180
const [preferences, setPreferences] = useState(readUsagePagePreferences);
181
useEscapeToGoBack();
@@ -159,7 +202,6 @@ export function UsagePage() {
202
const [limitsNow, setLimitsNow] = useState(() => Date.now());
203
const refreshingRef = useRef(false);
204
const [priceDialog, setPriceDialog] = useState<{ readonly model?: string } | null>(null);
162
- const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
205
const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
206
useState<ReadonlySet<EnvironmentId> | null>(null);
207
const hiddenProviders = new Set(preferences.hiddenProviders);
@@ -303,11 +345,6 @@ export function UsagePage() {
345
shownWindow.sinceTime === undefined || shownWindow.untilTime === undefined
346
? []
347
: enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime);
306
- const selectedModel =
307
- selectedModelKey === null
308
- ? undefined
309
- : merged.models.find((model) => `${model.provider}:${model.model}` === selectedModelKey);
310
-
348
const showChatGptSharing =
349
!hiddenProviders.has("codex") &&
350
[...presentations].some(
@@ -521,15 +558,15 @@ export function UsagePage() {
558
void refresh();
559
void refreshLimits(false, true);
560
}}
524
- onSelectModel={setSelectedModelKey}
561
+ onSelectModel={selectUsageModel}
562
/>
563
)}
564
</WorkspacePageContainer>
565
</ScrollArea>
566
</div>
530
- {selectedModel !== undefined && !showingLimits ? (
531
- <UsageModelDialog
532
- model={selectedModel}
567
+ {showingLimits ? null : (
568
+ <UsageModelDialogHost
569
+ models={merged.models}
570
environments={selectedEnvironments}
571
metric={metric === "tokens" ? "tokens" : "cost"}
572
chartWindow={{
@@ -539,13 +576,9 @@ export function UsagePage() {
576
timeZone: shownWindow.timeZone,
577
referenceTime: shownWindow.untilTime,
578
}}
542
- onSetPrice={() => {
543
- setSelectedModelKey(null);
544
- setPriceDialog({ model: selectedModel.model });
545
- }}
546
- onClose={() => setSelectedModelKey(null)}
579
+ onSetPrice={(model) => setPriceDialog({ model })}
580
/>
548
- ) : null}
581
+ )}
582
{priceDialog ? (
583
<UsagePriceOverrides
584
usage={environments}