Skip to content
TypeScript

perf(web): opening chat and usage dialogs no longer re-renders the whole page (#20859)

Julius Marminged56c47934531
diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts
index 0e200d0cd92..58ceb88fbf1 100644
--- a/apps/web/src/components/ChatView.logic.ts
+++ b/apps/web/src/components/ChatView.logic.ts
@@ -786,11 +786,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
return previewUrls;
}
-export interface PullRequestDialogState {
- initialReference: string | null;
- key: number;
-}
-
export { readFileAsDataUrl } from "../lib/imageCompression";
export function resolveSendEnvMode(input: {
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index c070bf2a2d9..62ead8cc786 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -251,9 +251,6 @@ import { threadPullRequestPanelTarget } from "./pullRequest/pullRequestDetail.lo
import { RightPanelTabs } from "./RightPanelTabs";
import { LinkPullRequestDialogHost } from "./pullRequest/LinkPullRequestDialog";
import { useDeviceState } from "~/state/device";
-import { DeviceSetup } from "./device/DeviceSetup";
-import { Dialog } from "./ui/dialog";
-import { WizardPopup } from "./ui/wizard";
import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
import { isEditableFocused } from "../lib/editableFocus";
@@ -391,7 +388,16 @@ import { createPageScrollController, type PageScrollKey } from "./chat/pageScrol
import { isTimelineScrollTarget } from "./chat/timelineScrollTarget";
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
-import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
+import {
+ BranchRestoreConfirmHost,
+ DeviceSetupDialogHost,
+ openBranchRestoreConfirm,
+ openDeviceSetupDialog,
+ openPullRequestThreadDialog,
+ openRevertConfirm,
+ PullRequestThreadDialogHost,
+ RevertConfirmHost,
+} from "./chat/ChatOverlayHosts";
import type { AssistantCitationRequest } from "./chat/AssistantCitationSource";
import { MessagesTimeline, type MessagesTimelineHistoryControls } from "./chat/MessagesTimeline";
import { ProviderSubagentBar } from "./chat/ProviderSubagentBar";
@@ -483,7 +489,6 @@ import {
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
- PullRequestDialogState,
cloneComposerImageForRetry,
deriveLockedProvider,
readFileAsDataUrl,
@@ -523,15 +528,6 @@ import { useAtomCommand } from "../state/use-atom-command";
import { useOrchestrationCommand } from "../state/use-orchestration-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { Button, InlineButton } from "./ui/button";
-import {
- AlertDialog,
- AlertDialogClose,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogPopup,
- AlertDialogTitle,
-} from "./ui/alert-dialog";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { ServerUpdateAction } from "./ServerUpdateAction";
import { useAutoBalanceUpdateBanner } from "./chat/useAutoBalanceUpdateBanner";
@@ -1333,8 +1329,6 @@ export default function ChatView(props: ChatViewProps) {
const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);
const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
- const [pullRequestDialogState, setPullRequestDialogState] =
- useState<PullRequestDialogState | null>(null);
const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
useState<TerminalLaunchContext | null>(null);
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
@@ -2094,17 +2088,11 @@ export default function ChatView(props: ChatViewProps) {
if (!canCheckoutPullRequestIntoThread) {
return;
}
- setPullRequestDialogState({
- initialReference: reference ?? null,
- key: Date.now(),
- });
+ if (activeThreadKey === null) return;
+ openPullRequestThreadDialog(activeThreadKey, reference);
};
const openPullRequestDialogStable = useStableCallback(openPullRequestDialog);
- const closePullRequestDialog = () => {
- setPullRequestDialogState(null);
- };
-
const openOrReuseProjectDraftThread = async (input: {
branch: string;
worktreePath: string | null;
@@ -3738,11 +3726,10 @@ export default function ChatView(props: ChatViewProps) {
const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState(
activeThreadRef?.environmentId ?? null,
);
- const [deviceSetupThread, setDeviceSetupThread] = useState<ScopedThreadRef | null>(null);
const addDeviceSurface = () => {
if (!activeThreadRef) return;
if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
- setDeviceSetupThread(activeThreadRef);
+ openDeviceSetupDialog(scopedThreadKey(activeThreadRef));
return;
}
useRightPanelStore.getState().open(activeThreadRef, "device");
@@ -4572,7 +4559,6 @@ export default function ChatView(props: ChatViewProps) {
if (timelineThreadReset.threadKey !== activeThreadKey) {
const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });
- setPullRequestDialogState(null);
setTimelineLiveFollowEnabled(followEnd);
setShowScrollToBottom(!followEnd);
}
@@ -4996,7 +4982,6 @@ export default function ChatView(props: ChatViewProps) {
};
const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread);
const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);
- const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);
const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);
const [, setBranchMismatchDismissTick] = useState(0);
const composerHasDraftContent = useComposerDraftStore((store) =>
@@ -5083,6 +5068,9 @@ export default function ChatView(props: ChatViewProps) {
setIsRestoringThreadBranch(false);
scheduleComposerFocus();
};
+ const handleSwitchCheckoutToThreadStable = useStableCallback(() => {
+ void handleSwitchCheckoutToThread();
+ });
// The interrupt path also accepts a completed run while its provider still
// has background work.
const activeBackgroundTasks = !isWorking && activeThread ? pendingBackgroundTasks : [];
@@ -5409,7 +5397,7 @@ export default function ChatView(props: ChatViewProps) {
const handleRestoreThreadBranch = () => {
if (!canWriteSourceControl) return;
if (gitStatusQuery.data?.hasWorkingTreeChanges) {
- setBranchRestoreConfirmOpen(true);
+ if (activeThreadKey !== null) openBranchRestoreConfirm(activeThreadKey);
return;
}
void handleSwitchCheckoutToThread();
@@ -5765,16 +5753,6 @@ export default function ChatView(props: ChatViewProps) {
};
}, [activeThreadId, composerRef]);
- const [pendingRevert, setPendingRevert] = useState<{
- turnCount: number;
- messageId: MessageId;
- routeThreadKey: string;
- } | null>(null);
-
- if (pendingRevert && pendingRevert.routeThreadKey !== routeThreadKey) {
- setPendingRevert(null);
- }
-
const onRevertToTurnCount = async (
turnCount: number,
messageId: MessageId,
@@ -5823,7 +5801,7 @@ export default function ChatView(props: ChatViewProps) {
return;
}
if (restoreFiles === undefined) {
- setPendingRevert({ turnCount, messageId, routeThreadKey });
+ openRevertConfirm(routeThreadKey, { turnCount, messageId });
return;
}
@@ -5862,6 +5840,10 @@ export default function ChatView(props: ChatViewProps) {
}
};
const onRevertToTurnCountStable = useStableCallback(onRevertToTurnCount);
+ const onConfirmRevert = (turnCount: number, messageId: MessageId, restoreFiles: boolean) => {
+ void onRevertToTurnCount(turnCount, messageId, restoreFiles);
+ };
+ const onConfirmRevertStable = useStableCallback(onConfirmRevert);
const onRollbackCheckpoint = async (input: {
readonly checkpointId: string;
@@ -7957,29 +7939,11 @@ export default function ChatView(props: ChatViewProps) {
ref={setWorkspaceLayoutElement}
className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background"
>
- <Dialog
- open={
- deviceSetupThread !== null &&
- deviceSetupThread.environmentId === activeThreadRef?.environmentId &&
- deviceSetupThread.threadId === activeThreadRef?.threadId
- }
- onOpenChange={(open) => {
- if (!open) setDeviceSetupThread(null);
- }}
- >
- <WizardPopup>
- {activeThreadRef ? (
- <DeviceSetup
- environmentId={activeThreadRef.environmentId}
- state={deviceState}
- onComplete={() => {
- useRightPanelStore.getState().open(activeThreadRef, "device");
- setDeviceSetupThread(null);
- }}
- />
- ) : null}
- </WizardPopup>
- </Dialog>
+ <DeviceSetupDialogHost
+ threadKey={activeThreadKey}
+ threadRef={activeThreadRef}
+ state={deviceState}
+ />
{rightPanelControlsAtRoot ? panelLayoutControls : null}
<div
className={cn(
@@ -8564,55 +8528,22 @@ export default function ChatView(props: ChatViewProps) {
/>
) : null}
- <AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>
- <AlertDialogPopup>
- <AlertDialogHeader>
- <AlertDialogTitle>
- Switch to{" "}
- <code className="font-medium">
- {localCheckoutBranchMismatch?.threadBranch ?? ""}
- </code>
- ?
- </AlertDialogTitle>
- <AlertDialogDescription>
- You have uncommitted changes. They'll carry over to the other branch, or block
- the switch if they conflict.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
- <Button
- variant="default"
- disabled={!canWriteSourceControl}
- onClick={() => {
- setBranchRestoreConfirmOpen(false);
- void handleSwitchCheckoutToThread();
- }}
- >
- Switch branch
- </Button>
- </AlertDialogFooter>
- </AlertDialogPopup>
- </AlertDialog>
+ <BranchRestoreConfirmHost
+ threadKey={activeThreadKey}
+ threadBranch={localCheckoutBranchMismatch?.threadBranch ?? ""}
+ canWriteSourceControl={canWriteSourceControl}
+ onConfirm={handleSwitchCheckoutToThreadStable}
+ />
<ThreadDetailsPanel {...threadDetailsPanelProps} />
- {pullRequestDialogState ? (
- <PullRequestThreadDialog
- key={pullRequestDialogState.key}
- open
- environmentId={activeThread.environmentId}
- threadId={activeThread.id}
- cwd={activeProject?.workspaceRoot ?? null}
- initialReference={pullRequestDialogState.initialReference}
- onOpenChange={(open) => {
- if (!open) {
- closePullRequestDialog();
- }
- }}
- onPrepared={handlePreparedPullRequestThreadStable}
- />
- ) : null}
+ <PullRequestThreadDialogHost
+ threadKey={activeThreadKey}
+ environmentId={activeThread.environmentId}
+ threadId={activeThread.id}
+ cwd={activeProject?.workspaceRoot ?? null}
+ onPrepared={handlePreparedPullRequestThreadStable}
+ />
</ThreadFindCanvas>
</div>
@@ -8739,44 +8670,7 @@ export default function ChatView(props: ChatViewProps) {
</RightPanelSheet>
) : null}
- <AlertDialog
- open={pendingRevert !== null && pendingRevert.routeThreadKey === routeThreadKey}
- onOpenChange={(open) => {
- if (!open) setPendingRevert(null);
- }}
- >
- <AlertDialogPopup>
- <AlertDialogHeader>
- <AlertDialogTitle>Edit from here?</AlertDialogTitle>
- <AlertDialogDescription>
- Rewind chat to before this message. Your prompt and attachments return to the
- composer.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
- <Button
- variant="destructive"
- onClick={() => {
- if (!pendingRevert || pendingRevert.routeThreadKey !== routeThreadKey) return;
- setPendingRevert(null);
- void onRevertToTurnCount(pendingRevert.turnCount, pendingRevert.messageId, true);
- }}
- >
- Revert files too
- </Button>
- <Button
- onClick={() => {
- if (!pendingRevert || pendingRevert.routeThreadKey !== routeThreadKey) return;
- setPendingRevert(null);
- void onRevertToTurnCount(pendingRevert.turnCount, pendingRevert.messageId, false);
- }}
- >
- Revert and keep changes
- </Button>
- </AlertDialogFooter>
- </AlertDialogPopup>
- </AlertDialog>
+ <RevertConfirmHost threadKey={routeThreadKey} onConfirm={onConfirmRevertStable} />
<LinkPullRequestDialogHost />
{expandedImage && (
<ExpandedImageDialog
diff --git a/apps/web/src/components/chat/ChatOverlayHosts.browser.test.tsx b/apps/web/src/components/chat/ChatOverlayHosts.browser.test.tsx
new file mode 100644
index 00000000000..2e36c714761
--- /dev/null
+++ b/apps/web/src/components/chat/ChatOverlayHosts.browser.test.tsx
@@ -0,0 +1,54 @@
+import { MessageId } from "@t3tools/contracts";
+import { act } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { AppAtomRegistryProvider } from "~/rpc/atomRegistry";
+import { openRevertConfirm, RevertConfirmHost } from "./ChatOverlayHosts";
+
+let root: Root;
+let container: HTMLDivElement;
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+});
+
+afterEach(async () => {
+ await act(() => root.unmount());
+ container.remove();
+ vi.unstubAllGlobals();
+});
+
+const messageId = MessageId.make("message-1");
+const dialog = () => document.querySelector('[role="alertdialog"]');
+
+describe("RevertConfirmHost", () => {
+ it("shows only its thread's request, confirms it once, and drops it when the thread changes", async () => {
+ const onConfirm = vi.fn();
+ const host = (threadKey: string) => (
+ <AppAtomRegistryProvider>
+ <RevertConfirmHost threadKey={threadKey} onConfirm={onConfirm} />
+ </AppAtomRegistryProvider>
+ );
+ await act(() => root.render(host("env:a")));
+
+ await act(() => openRevertConfirm("env:b", { turnCount: 2, messageId }));
+ expect(dialog()).toBeNull();
+
+ await act(() => openRevertConfirm("env:a", { turnCount: 2, messageId }));
+ const keep = [...(dialog()?.querySelectorAll("button") ?? [])].find(
+ (button) => button.textContent === "Revert and keep changes",
+ );
+ await act(() => keep?.click());
+ expect(onConfirm).toHaveBeenCalledExactlyOnceWith(2, messageId, false);
+ await vi.waitFor(() => expect(dialog()).toBeNull());
+
+ await act(() => openRevertConfirm("env:a", { turnCount: 3, messageId }));
+ expect(dialog()).not.toBeNull();
+ await act(() => root.render(host("env:b")));
+ await vi.waitFor(() => expect(dialog()).toBeNull());
+ });
+});
diff --git a/apps/web/src/components/chat/ChatOverlayHosts.tsx b/apps/web/src/components/chat/ChatOverlayHosts.tsx
new file mode 100644
index 00000000000..94dad6e78f9
--- /dev/null
+++ b/apps/web/src/components/chat/ChatOverlayHosts.tsx
@@ -0,0 +1,228 @@
+import type {
+ DeviceServiceState,
+ EnvironmentId,
+ MessageId,
+ ScopedThreadRef,
+ ThreadId,
+} from "@t3tools/contracts";
+import { useAtomValue } from "@effect/atom-react";
+import { Atom } from "effect/reactivity";
+import { useEffect } from "react";
+
+import { appAtomRegistry } from "~/rpc/atomRegistry";
+import { useRightPanelStore } from "~/rightPanelStore";
+import { DeviceSetup } from "../device/DeviceSetup";
+import { PullRequestThreadDialog } from "../PullRequestThreadDialog";
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogPopup,
+ AlertDialogTitle,
+} from "../ui/alert-dialog";
+import { Button } from "../ui/button";
+import { Dialog } from "../ui/dialog";
+import { WizardPopup } from "../ui/wizard";
+
+/**
+ * Open state for overlays the chat view hosts. It lives in atoms rather than
+ * ChatView state so opening or closing one renders only its host, not the
+ * whole chat chrome. Each entry carries the thread it was opened for; a host
+ * shows only its own thread's entry and drops it when the thread changes.
+ */
+type ThreadOverlayAtom<T> = Atom.Writable<{ readonly threadKey: string; readonly value: T } | null>;
+
+function makeThreadOverlayAtom<T>(label: string): ThreadOverlayAtom<T> {
+ return Atom.make<{ readonly threadKey: string; readonly value: T } | null>(null).pipe(
+ Atom.keepAlive,
+ Atom.withLabel(`chat:${label}`),
+ );
+}
+
+function closeThreadOverlay<T>(atom: ThreadOverlayAtom<T>): void {
+ appAtomRegistry.set(atom, null);
+}
+
+function useThreadOverlay<T>(atom: ThreadOverlayAtom<T>, threadKey: string | null): T | null {
+ const entry = useAtomValue(atom);
+ useEffect(
+ () => () => {
+ if (appAtomRegistry.get(atom)?.threadKey === threadKey) closeThreadOverlay(atom);
+ },
+ [atom, threadKey],
+ );
+ return threadKey !== null && entry?.threadKey === threadKey ? entry.value : null;
+}
+
+const pullRequestThreadDialogAtom = makeThreadOverlayAtom<{
+ readonly initialReference: string | null;
+ readonly key: number;
+}>("pull-request-thread-dialog");
+
+export function openPullRequestThreadDialog(threadKey: string, reference?: string): void {
+ appAtomRegistry.set(pullRequestThreadDialogAtom, {
+ threadKey,
+ value: { initialReference: reference ?? null, key: Date.now() },
+ });
+}
+
+export function PullRequestThreadDialogHost(props: {
+ readonly threadKey: string | null;
+ readonly environmentId: EnvironmentId;
+ readonly threadId: ThreadId;
+ readonly cwd: string | null;
+ readonly onPrepared: (input: {
+ branch: string;
+ worktreePath: string | null;
+ }) => Promise<void> | void;
+}) {
+ const state = useThreadOverlay(pullRequestThreadDialogAtom, props.threadKey);
+ if (state === null) return null;
+ return (
+ <PullRequestThreadDialog
+ key={state.key}
+ open
+ environmentId={props.environmentId}
+ threadId={props.threadId}
+ cwd={props.cwd}
+ initialReference={state.initialReference}
+ onOpenChange={(open) => {
+ if (!open) closeThreadOverlay(pullRequestThreadDialogAtom);
+ }}
+ onPrepared={props.onPrepared}
+ />
+ );
+}
+
+const deviceSetupDialogAtom = makeThreadOverlayAtom<true>("device-setup-dialog");
+
+export function openDeviceSetupDialog(threadKey: string): void {
+ appAtomRegistry.set(deviceSetupDialogAtom, { threadKey, value: true });
+}
+
+export function DeviceSetupDialogHost(props: {
+ readonly threadKey: string | null;
+ readonly threadRef: ScopedThreadRef | null;
+ readonly state: DeviceServiceState;
+}) {
+ const open = useThreadOverlay(deviceSetupDialogAtom, props.threadKey) !== null;
+ const { threadRef } = props;
+ return (
+ <Dialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen) closeThreadOverlay(deviceSetupDialogAtom);
+ }}
+ >
+ <WizardPopup>
+ {threadRef ? (
+ <DeviceSetup
+ environmentId={threadRef.environmentId}
+ state={props.state}
+ onComplete={() => {
+ useRightPanelStore.getState().open(threadRef, "device");
+ closeThreadOverlay(deviceSetupDialogAtom);
+ }}
+ />
+ ) : null}
+ </WizardPopup>
+ </Dialog>
+ );
+}
+
+const branchRestoreConfirmAtom = makeThreadOverlayAtom<true>("branch-restore-confirm");
+
+export function openBranchRestoreConfirm(threadKey: string): void {
+ appAtomRegistry.set(branchRestoreConfirmAtom, { threadKey, value: true });
+}
+
+export function BranchRestoreConfirmHost(props: {
+ readonly threadKey: string | null;
+ readonly threadBranch: string;
+ readonly canWriteSourceControl: boolean;
+ readonly onConfirm: () => void;
+}) {
+ const open = useThreadOverlay(branchRestoreConfirmAtom, props.threadKey) !== null;
+ return (
+ <AlertDialog
+ open={open}
+ onOpenChange={(nextOpen) => {
+ if (!nextOpen) closeThreadOverlay(branchRestoreConfirmAtom);
+ }}
+ >
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ Switch to <code className="font-medium">{props.threadBranch}</code>?
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ You have uncommitted changes. They'll carry over to the other branch, or block the
+ switch if they conflict.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
+ <Button
+ variant="default"
+ disabled={!props.canWriteSourceControl}
+ onClick={() => {
+ closeThreadOverlay(branchRestoreConfirmAtom);
+ props.onConfirm();
+ }}
+ >
+ Switch branch
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
+ );
+}
+
+interface PendingRevert {
+ readonly turnCount: number;
+ readonly messageId: MessageId;
+}
+
+const revertConfirmAtom = makeThreadOverlayAtom<PendingRevert>("revert-confirm");
+
+export function openRevertConfirm(threadKey: string, pending: PendingRevert): void {
+ appAtomRegistry.set(revertConfirmAtom, { threadKey, value: pending });
+}
+
+export function RevertConfirmHost(props: {
+ readonly threadKey: string;
+ readonly onConfirm: (turnCount: number, messageId: MessageId, restoreFiles: boolean) => void;
+}) {
+ const pending = useThreadOverlay(revertConfirmAtom, props.threadKey);
+ const confirm = (restoreFiles: boolean) => {
+ if (pending === null) return;
+ closeThreadOverlay(revertConfirmAtom);
+ props.onConfirm(pending.turnCount, pending.messageId, restoreFiles);
+ };
+ return (
+ <AlertDialog
+ open={pending !== null}
+ onOpenChange={(open) => {
+ if (!open) closeThreadOverlay(revertConfirmAtom);
+ }}
+ >
+ <AlertDialogPopup>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Edit from here?</AlertDialogTitle>
+ <AlertDialogDescription>
+ Rewind chat to before this message. Your prompt and attachments return to the composer.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
+ <Button variant="destructive" onClick={() => confirm(true)}>
+ Revert files too
+ </Button>
+ <Button onClick={() => confirm(false)}>Revert and keep changes</Button>
+ </AlertDialogFooter>
+ </AlertDialogPopup>
+ </AlertDialog>
+ );
+}
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index 34c3c489a6c..b24e455c396 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -2,6 +2,7 @@ import { ChatGptUsageButton } from "../settings/ChatGptUsageButton";
import { usesChatGptSharing } from "@t3tools/shared/usageLimits";
import { RefreshIcon } from "~/components/ui/refresh-icon";
import { useAtomValue } from "@effect/atom-react";
+import { Atom } from "effect/reactivity";
import {
ProviderDriverKind,
USAGE_CONTRACT_VERSION,
@@ -34,6 +35,7 @@ import {
import { isElectron } from "../../env";
import { cn } from "../../lib/utils";
+import { appAtomRegistry } from "~/rpc/atomRegistry";
import { environmentPresentations } from "../../state/presentation";
import { primaryServerKeybindingsAtom, serverEnvironment } from "../../state/server";
import { isCommandPaletteOpen } from "../../commandPaletteBus";
@@ -133,6 +135,47 @@ function usageLoading(
};
}
+/**
+ * The model whose detail dialog is open. It lives outside UsagePage so opening
+ * or closing the dialog renders only its host, not the whole usage page.
+ */
+const selectedUsageModelKeyAtom = Atom.make<string | null>(null).pipe(
+ Atom.keepAlive,
+ Atom.withLabel("usage:selected-model-key"),
+);
+
+function selectUsageModel(key: string | null): void {
+ appAtomRegistry.set(selectedUsageModelKeyAtom, key);
+}
+
+function UsageModelDialogHost({
+ models,
+ onSetPrice,
+ ...dialogProps
+}: Omit<Parameters<typeof UsageModelDialog>[0], "model" | "onSetPrice" | "onClose"> & {
+ readonly models: MergedUsage["models"];
+ readonly onSetPrice: (model: string) => void;
+}) {
+ const selectedKey = useAtomValue(selectedUsageModelKeyAtom);
+ useEffect(() => () => selectUsageModel(null), []);
+ const model =
+ selectedKey === null
+ ? undefined
+ : models.find((candidate) => `${candidate.provider}:${candidate.model}` === selectedKey);
+ if (model === undefined) return null;
+ return (
+ <UsageModelDialog
+ {...dialogProps}
+ model={model}
+ onSetPrice={() => {
+ selectUsageModel(null);
+ onSetPrice(model.model);
+ }}
+ onClose={() => selectUsageModel(null)}
+ />
+ );
+}
+
export function UsagePage() {
const [preferences, setPreferences] = useState(readUsagePagePreferences);
useEscapeToGoBack();
@@ -159,7 +202,6 @@ export function UsagePage() {
const [limitsNow, setLimitsNow] = useState(() => Date.now());
const refreshingRef = useRef(false);
const [priceDialog, setPriceDialog] = useState<{ readonly model?: string } | null>(null);
- const [selectedModelKey, setSelectedModelKey] = useState<string | null>(null);
const [selectedEnvironmentIds, setSelectedEnvironmentIds] =
useState<ReadonlySet<EnvironmentId> | null>(null);
const hiddenProviders = new Set(preferences.hiddenProviders);
@@ -303,11 +345,6 @@ export function UsagePage() {
shownWindow.sinceTime === undefined || shownWindow.untilTime === undefined
? []
: enumerateHourStarts(shownWindow.sinceTime, shownWindow.untilTime);
- const selectedModel =
- selectedModelKey === null
- ? undefined
- : merged.models.find((model) => `${model.provider}:${model.model}` === selectedModelKey);
-
const showChatGptSharing =
!hiddenProviders.has("codex") &&
[...presentations].some(
@@ -521,15 +558,15 @@ export function UsagePage() {
void refresh();
void refreshLimits(false, true);
}}
- onSelectModel={setSelectedModelKey}
+ onSelectModel={selectUsageModel}
/>
)}
</WorkspacePageContainer>
</ScrollArea>
</div>
- {selectedModel !== undefined && !showingLimits ? (
- <UsageModelDialog
- model={selectedModel}
+ {showingLimits ? null : (
+ <UsageModelDialogHost
+ models={merged.models}
environments={selectedEnvironments}
metric={metric === "tokens" ? "tokens" : "cost"}
chartWindow={{
@@ -539,13 +576,9 @@ export function UsagePage() {
timeZone: shownWindow.timeZone,
referenceTime: shownWindow.untilTime,
}}
- onSetPrice={() => {
- setSelectedModelKey(null);
- setPriceDialog({ model: selectedModel.model });
- }}
- onClose={() => setSelectedModelKey(null)}
+ onSetPrice={(model) => setPriceDialog({ model })}
/>
- ) : null}
+ )}
{priceDialog ? (
<UsagePriceOverrides
usage={environments}