@devries-cameron20 / t3code-1 / commits / 02f4ba75a2
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): SSH password prompts wait for their dialog, and the app shell drops its sync effects (#25239)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 20:59 UTC 02f4ba75a20f28a5383bdb95a1c250e6892556e9
17 files changed +334 -277
apps/web/src/appInit.tsx
+8
@@ -5,12 +5,16 @@ import { createBrowserHistory, createHashHistory } from "@tanstack/react-router"
5 import { applyAppearanceContrast } from "./appearanceContrast";
6 import { applyAppearanceFontVariables } from "./appearanceFonts";
7 import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
8 +import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
9 +import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
10 import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
11 +import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
12 import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
13 import { resolveServerBackedAppDisplayName } from "./branding.logic";
14 import { isElectron } from "./env";
15 import { useComposerDraftStore } from "./composerDraftStore";
16 import { getClientSettings, subscribeClientSettings } from "./hooks/useSettings";
17 +import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
18 import {
19 syncDocumentElectronPlatformClasses,
20 syncDocumentWindowControlsOverlayClass,
@@ -126,6 +130,10 @@ export function startAppServices(): AppRouter {
130 startDocumentTitle();
131 startAgentOpenedPreviews();
132 startThreadOverlayRetention(router);
133 + startMainAppLocationTracking(router);
134 + startBackgroundThreadAnnouncements(appAtomRegistry, router);
135 + startThreadVisitedMigration(appAtomRegistry);
136 + startSshPasswordPromptQueue();
137
138 return router;
139 }
apps/web/src/components/AppSidebarLayout.tsx
+24 -4
@@ -38,10 +38,9 @@ import {
38 } from "../panelAnimations";
39 import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";
40 import LegacyThreadSidebar from "./LegacySidebar";
41 -import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";
41 import ThreadSidebar from "./Sidebar";
42 import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";
44 -import { isAppModalPage, MainAppLocationTracker } from "./sidebar/mainAppLocation";
43 +import { isAppModalPage } from "./sidebar/mainAppLocation";
44 import type { SidebarRouteReveal } from "./sidebar/routeReveal";
45 import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
46 import {
@@ -171,6 +170,28 @@ export function registerNavigationHistoryCommands(router: AnyRouter): () => void
170 );
171 }
172
173 +// Escape leaves the pull requests page when no scope (a selection, a dialog,
174 +// a drag) claimed it, so it observes after every other scope.
175 +function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {
176 + return registerCommands(
177 + {},
178 + {
179 + observe: (event, consumed) => {
180 + if (consumed || event.repeat || event.isComposing || event.key !== "Escape") return;
181 + if (router.state.location.pathname !== "/pull-requests") return;
182 + event.preventDefault();
183 + const activeElement = document.activeElement;
184 + if (activeElement instanceof HTMLElement) activeElement.blur();
185 + if (router.state.location.state.__TSR_index !== 0) {
186 + window.history.back();
187 + return;
188 + }
189 + void router.navigate({ to: "/" });
190 + },
191 + },
192 + );
193 +}
194 +
195 const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
196
197 // A held key undoes once. Module state: undoing an archive navigates, and the
@@ -251,6 +272,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): ()
272 const disposers = [
273 registerThreadUndoCommands(router, readSidebarVisible),
274 registerNavigationHistoryCommands(router),
275 + registerPullRequestsEscapeCommand(router),
276 registerMenuAction("open-settings", () => {
277 if (!/^\/settings(\/|$)/.test(router.state.location.pathname))
278 void router.navigate({ to: "/settings" });
@@ -359,7 +381,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
381 }));
382 const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =
383 usePanelAnimationSettings();
362 - useThreadVisitedMigration();
384 const pathname = useLocation({ select: (location) => location.pathname });
385 const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
386 const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
@@ -429,7 +450,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
450 {children}
451 <BackgroundThreadAnnouncer />
452 <SidebarControl />
432 - <MainAppLocationTracker />
453 </SidebarProvider>
454 </PanelAnimationSuppressionProvider>
455 );
apps/web/src/components/BackgroundThreadAnnouncer.tsx
+58 -31
@@ -1,14 +1,13 @@
1 -import { useAtomValue } from "@effect/atom-react";
1 import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
2 import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";
4 -import { useEffect, useRef } from "react";
3 +import type { AnyRouter } from "@tanstack/react-router";
4 +import type { AtomRegistry } from "effect/reactivity";
5
6 import { useComposerDraftStore } from "../composerDraftStore";
7 -import { useLiveRegion } from "../hooks/useLiveRegion";
8 -import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";
9 -import { useQuietThreadShells } from "../state/entities";
7 +import { createLiveRegion } from "../hooks/useLiveRegion";
8 import { liveShellEnvironmentIdsAtom } from "../state/shell";
11 -import { resolveActiveThreadRouteRef } from "../threadRoutes";
9 +import { environmentThreadShells } from "../state/threads";
10 +import { resolveActiveThreadRouteRef, resolveThreadRouteTarget } from "../threadRoutes";
11 import {
12 type BackgroundThreadMemory,
13 type BackgroundThreadSnapshot,
@@ -16,23 +15,30 @@ import {
15 resolveBackgroundThreadRequest,
16 } from "./backgroundThreadAnnouncement";
17
19 -/**
20 - * Speaks status changes for threads other than the open one. It lives outside
21 - * the sidebar because a collapsed sidebar is inert, which silences its rows.
22 - */
23 -export function BackgroundThreadAnnouncer() {
24 - const threads = useQuietThreadShells();
25 - const liveEnvironmentIds = useAtomValue(liveShellEnvironmentIdsAtom);
26 - const routeTarget = useThreadRouteTarget();
27 - const routeDraftThread = useComposerDraftStore((store) =>
28 - routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
29 - );
30 - const openThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);
31 - const openThreadKey = openThreadRef === null ? null : scopedThreadKey(openThreadRef);
32 - const { regionRef, announce } = useLiveRegion();
33 - const memoryRef = useRef<BackgroundThreadMemory>(new Map());
18 +const backgroundThreadLiveRegion = createLiveRegion();
19 +const attachBackgroundThreadRegion = backgroundThreadLiveRegion.attach;
20 +
21 +function readOpenThreadKey(router: AnyRouter): string | null {
22 + const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
23 + const draft =
24 + target?.kind === "draft"
25 + ? useComposerDraftStore.getState().getDraftSession(target.draftId)
26 + : null;
27 + const ref = resolveActiveThreadRouteRef(target, draft);
28 + return ref === null ? null : scopedThreadKey(ref);
29 +}
30 +
31 +/** Speaks status changes for threads other than the open one, for the life of the app. */
32 +export function startBackgroundThreadAnnouncements(
33 + registry: AtomRegistry.AtomRegistry,
34 + router: AnyRouter,
35 +): () => void {
36 + let memory: BackgroundThreadMemory = new Map();
37 + let openThreadKey = readOpenThreadKey(router);
38
35 - useEffect(() => {
39 + const update = () => {
40 + const threads = registry.get(environmentThreadShells.quietThreadShellsAtom);
41 + const liveEnvironmentIds = registry.get(liveShellEnvironmentIdsAtom);
42 const now = new Date().toISOString();
43 const snapshots: BackgroundThreadSnapshot[] = [];
44 for (const thread of threads) {
@@ -50,15 +56,36 @@ export function BackgroundThreadAnnouncer() {
56 snoozed: effectiveSnoozed(thread, { now }),
57 });
58 }
53 - const { memory, announcement } = nextBackgroundThreadAnnouncement(
54 - memoryRef.current,
55 - snapshots,
56 - openThreadKey,
57 - );
58 - memoryRef.current = memory;
59 - if (announcement !== null) announce(announcement);
60 - }, [threads, liveEnvironmentIds, openThreadKey, announce]);
59 + const next = nextBackgroundThreadAnnouncement(memory, snapshots, openThreadKey);
60 + memory = next.memory;
61 + if (next.announcement !== null) backgroundThreadLiveRegion.announce(next.announcement);
62 + };
63
64 + // The draft store changes on every keystroke; only a new open thread matters here.
65 + const updateOpenThread = () => {
66 + const next = readOpenThreadKey(router);
67 + if (next === openThreadKey) return;
68 + openThreadKey = next;
69 + update();
70 + };
71 +
72 + const unsubscribes = [
73 + registry.subscribe(environmentThreadShells.quietThreadShellsAtom, update),
74 + registry.subscribe(liveShellEnvironmentIdsAtom, update),
75 + router.subscribe("onResolved", updateOpenThread),
76 + useComposerDraftStore.subscribe(updateOpenThread),
77 + ];
78 + update();
79 + return () => {
80 + for (const unsubscribe of unsubscribes) unsubscribe();
81 + };
82 +}
83 +
84 +/**
85 + * The region the background announcements are spoken through. It lives outside
86 + * the sidebar because a collapsed sidebar is inert, which silences its rows.
87 + */
88 +export function BackgroundThreadAnnouncer() {
89 // No role="status": Orca 50 maps it to a status bar in Chromium and drops its updates.
63 - return <div ref={regionRef} aria-live="polite" className="sr-only" />;
90 + return <div ref={attachBackgroundThreadRegion} aria-live="polite" className="sr-only" />;
91 }
apps/web/src/components/ConfirmDialogHost.tsx
+3 -6
@@ -1,11 +1,10 @@
1 -import { useEffect, useSyncExternalStore } from "react";
1 +import { useSyncExternalStore } from "react";
2
3 import {
4 completeConfirmDialogClose,
5 readConfirmDialogState,
6 - registerConfirmDialogHost,
6 respondToConfirmDialog,
8 - subscribeConfirmDialog,
7 + subscribeConfirmDialogHost,
8 } from "../confirmDialog";
9 import {
10 AlertDialog,
@@ -53,13 +52,11 @@ function resolveConfirmDialogCopy(message: string): ConfirmationCopy {
52
53 export function ConfirmDialogHost() {
54 const state = useSyncExternalStore(
56 - subscribeConfirmDialog,
55 + subscribeConfirmDialogHost,
56 readConfirmDialogState,
57 readConfirmDialogState,
58 );
59
61 - useEffect(() => registerConfirmDialogHost(), []);
62 -
60 const copy = resolveConfirmDialogCopy(state.status === "idle" ? "" : state.message);
61 const confirmVariant = state.status === "idle" ? "default" : state.variant;
62 const onCancel = () => respondToConfirmDialog(false);
apps/web/src/components/QuitHoldOverlay.tsx
+46 -26
@@ -1,35 +1,55 @@
1 -import { useEffect, useState } from "react";
1 +import { useSyncExternalStore } from "react";
2
3 import { isMacPlatform } from "../lib/utils";
4
5 const HOLD_HINT_LINGER_MS = 1200;
6
7 +type QuitHintMode = "hold" | "double-click";
8 +
9 +let visibleMode: QuitHintMode | null = null;
10 +let pressedMode: QuitHintMode = "hold";
11 +let hideTimer: number | undefined;
12 +const listeners = new Set<() => void>();
13 +let stopBridge: (() => void) | null = null;
14 +
15 +function setVisibleMode(next: QuitHintMode | null) {
16 + if (next === visibleMode) return;
17 + visibleMode = next;
18 + for (const listener of listeners) listener();
19 +}
20 +
21 +function subscribeQuitHint(listener: () => void): () => void {
22 + listeners.add(listener);
23 + if (listeners.size === 1) {
24 + stopBridge =
25 + window.desktopBridge?.onQuitShortcut?.((hint) => {
26 + window.clearTimeout(hideTimer);
27 + if (hint.state === "down") {
28 + pressedMode = hint.mode;
29 + setVisibleMode(hint.mode);
30 + return;
31 + }
32 + if (pressedMode === "double-click") {
33 + setVisibleMode(null);
34 + return;
35 + }
36 + hideTimer = window.setTimeout(() => setVisibleMode(null), HOLD_HINT_LINGER_MS);
37 + }) ?? null;
38 + }
39 + return () => {
40 + listeners.delete(listener);
41 + if (listeners.size > 0) return;
42 + window.clearTimeout(hideTimer);
43 + stopBridge?.();
44 + stopBridge = null;
45 + visibleMode = null;
46 + };
47 +}
48 +
49 +const readQuitHint = () => visibleMode;
50 +
51 export function QuitHoldOverlay() {
8 - const [visibleMode, setVisibleMode] = useState<"hold" | "double-click" | null>(null);
9 -
10 - useEffect(() => {
11 - const subscribe = window.desktopBridge?.onQuitShortcut;
12 - if (!subscribe) return;
13 - let hideTimer: number | undefined;
14 - let pressedMode: "hold" | "double-click" = "hold";
15 - const unsubscribe = subscribe((hint) => {
16 - window.clearTimeout(hideTimer);
17 - if (hint.state === "down") {
18 - pressedMode = hint.mode;
19 - setVisibleMode(hint.mode);
20 - return;
21 - }
22 - if (pressedMode === "double-click") {
23 - setVisibleMode(null);
24 - return;
25 - }
26 - hideTimer = window.setTimeout(() => setVisibleMode(null), HOLD_HINT_LINGER_MS);
27 - });
28 - return () => {
29 - window.clearTimeout(hideTimer);
30 - unsubscribe();
31 - };
32 - }, []);
52 + const visibleMode = useSyncExternalStore(subscribeQuitHint, readQuitHint, readQuitHint);
53
54 if (!visibleMode) return null;
55 const shortcut = isMacPlatform(navigator.platform) ? "⌘Q" : "Ctrl+Q";
apps/web/src/components/desktop/SshPasswordPromptDialog.browser.test.tsx new
+32
@@ -0,0 +1,32 @@
1 +import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
2 +import { expect, it } from "vite-plus/test";
3 +
4 +import { render, stubGlobal } from "../../../test/render";
5 +import { SshPasswordPromptDialog, startSshPasswordPromptQueue } from "./SshPasswordPromptDialog";
6 +
7 +it("shows a prompt that arrived before the dialog mounted", async () => {
8 + const listeners: Array<(request: DesktopSshPasswordPromptRequest) => void> = [];
9 + using _bridge = stubGlobal("desktopBridge", {
10 + onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => {
11 + listeners.push(listener);
12 + return () => listeners.splice(listeners.indexOf(listener), 1);
13 + },
14 + resolveSshPasswordPrompt: async () => undefined,
15 + });
16 + const stopQueue = startSshPasswordPromptQueue();
17 + using _queue = { [Symbol.dispose]: stopQueue };
18 +
19 + // The desktop asks while the app is still on a page without the dialog (pairing, sign-in).
20 + for (const listener of listeners) {
21 + listener({
22 + requestId: "ssh-1",
23 + destination: "devbox",
24 + username: "julius",
25 + prompt: "julius@devbox's password:",
26 + expiresAt: "2999-01-01T00:00:00.000Z",
27 + });
28 + }
29 +
30 + await using screen = await render(<SshPasswordPromptDialog />);
31 + await expect.element(screen.getByText("SSH verification required")).toBeVisible();
32 +});
apps/web/src/components/desktop/SshPasswordPromptDialog.tsx
+49 -51
@@ -2,7 +2,10 @@ import { settlePromise } from "@t3tools/client-runtime/state/runtime";
2 import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";
3 import * as AsyncResult from "effect/reactivity/AsyncResult";
4 import * as Cause from "effect/Cause";
5 -import { useEffect, useId, useRef, useState } from "react";
5 +import { useId, useRef, useState, useSyncExternalStore } from "react";
6 +
7 +import { useDeadlinePassed } from "../../hooks/useDeadline";
8 +import { useNowSecond } from "../../hooks/useNowSecond";
9
10 import { Button } from "../ui/button";
11 import {
@@ -31,75 +34,70 @@ function getPromptErrorMessage(error: unknown): string {
34 : message;
35 }
36
34 -export function SshPasswordPromptDialog() {
35 - const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);
36 - const currentRequest = queue[0] ?? null;
37 +let promptQueue: readonly DesktopSshPasswordPromptRequest[] = [];
38 +const promptQueueListeners = new Set<() => void>();
39
38 - useEffect(() => {
39 - const bridge = window.desktopBridge;
40 - if (!bridge?.onSshPasswordPrompt) {
41 - return;
42 - }
40 +function setPromptQueue(next: readonly DesktopSshPasswordPromptRequest[]) {
41 + promptQueue = next;
42 + for (const listener of promptQueueListeners) listener();
43 +}
44 +
45 +/**
46 + * Queues the desktop's SSH password prompts for the life of the page, so a prompt
47 + * that arrives while no dialog is mounted still waits for one.
48 + */
49 +export function startSshPasswordPromptQueue(): () => void {
50 + return (
51 + window.desktopBridge?.onSshPasswordPrompt?.((request) => {
52 + setPromptQueue([...promptQueue, request]);
53 + }) ?? (() => undefined)
54 + );
55 +}
56 +
57 +function subscribePromptQueue(listener: () => void): () => void {
58 + promptQueueListeners.add(listener);
59 + return () => {
60 + promptQueueListeners.delete(listener);
61 + };
62 +}
63 +
64 +const readPromptQueue = () => promptQueue;
65
44 - return bridge.onSshPasswordPrompt((request) => {
45 - setQueue((currentQueue) => [...currentQueue, request]);
46 - });
47 - }, []);
66 +function removeSshPasswordPrompt(requestId: string) {
67 + if (promptQueue[0]?.requestId === requestId) setPromptQueue(promptQueue.slice(1));
68 +}
69 +
70 +export function SshPasswordPromptDialog() {
71 + const queue = useSyncExternalStore(subscribePromptQueue, readPromptQueue, readPromptQueue);
72 + const currentRequest = queue[0] ?? null;
73
74 if (!currentRequest) {
75 return null;
76 }
77
53 - return (
54 - <ActiveSshPasswordPrompt
55 - key={currentRequest.requestId}
56 - request={currentRequest}
57 - onRemove={(requestId) => {
58 - setQueue((currentQueue) =>
59 - currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue,
60 - );
61 - }}
62 - />
63 - );
78 + return <ActiveSshPasswordPrompt key={currentRequest.requestId} request={currentRequest} />;
79 }
80
81 function ActiveSshPasswordPrompt({
82 request,
68 - onRemove,
83 }: {
84 readonly request: DesktopSshPasswordPromptRequest;
71 - readonly onRemove: (requestId: string) => void;
85 }) {
86 const [password, setPassword] = useState("");
87 const [isResponding, setIsResponding] = useState(false);
75 - const [now, setNow] = useState(() => Date.now());
88 const [responseError, setResponseError] = useState<string | null>(null);
89 const inputRef = useRef<HTMLInputElement | null>(null);
90 const isRespondingRef = useRef(false);
91 const formId = useId();
92
81 - useEffect(() => {
82 - const frame = window.requestAnimationFrame(() => {
83 - inputRef.current?.focus();
84 - inputRef.current?.select();
85 - });
86 - return () => {
87 - window.cancelAnimationFrame(frame);
88 - };
89 - }, []);
90 -
91 - useEffect(() => {
92 - const interval = window.setInterval(() => {
93 - setNow(Date.now());
94 - }, 1_000);
95 - return () => {
96 - window.clearInterval(interval);
97 - };
98 - }, []);
99 -
93 const expiresAtMs = Date.parse(request.expiresAt);
101 - const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null;
102 - const isExpired = remainingMs !== null && remainingMs <= 0;
94 + const now = useNowSecond();
95 + const isExpired = useDeadlinePassed(Number.isFinite(expiresAtMs) ? expiresAtMs : null);
96 + const remainingMs = Number.isFinite(expiresAtMs)
97 + ? isExpired
98 + ? 0
99 + : Math.max(0, expiresAtMs - now)
100 + : null;
101 const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);
102 const remainingLabel =
103 remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);
@@ -125,7 +123,7 @@ function ActiveSshPasswordPrompt({
123 window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword),
124 );
125 if (AsyncResult.isSuccess(result) || nextPassword === null) {
128 - onRemove(requestId);
126 + removeSshPasswordPrompt(requestId);
127 } else {
128 setResponseError(getPromptErrorMessage(Cause.squash(result.cause)));
129 }
@@ -134,7 +132,7 @@ function ActiveSshPasswordPrompt({
132 };
133
134 const dismissExpiredPrompt = () => {
137 - onRemove(request.requestId);
135 + removeSshPasswordPrompt(request.requestId);
136 };
137
138 const cancelPrompt = () => {
@@ -156,7 +154,7 @@ function ActiveSshPasswordPrompt({
154 }
155 }}
156 >
159 - <DialogPopup className="max-w-md" showCloseButton={false}>
157 + <DialogPopup className="max-w-md" initialFocus={inputRef} showCloseButton={false}>
158 <DialogHeader>
159 <DialogTitle>SSH verification required</DialogTitle>
160 <DialogDescription>
apps/web/src/components/pullRequest/PullRequestsPage.tsx
-2
@@ -89,7 +89,6 @@ import { useStableCallback } from "~/hooks/useStableCallback";
89 import { useOpenPanelPullRequestUrl } from "~/hooks/useOpenPanelPullRequestUrl";
90 import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
91 import { toastManager } from "../ui/toast";
92 -import { useEscapeToGoBack } from "~/hooks/useNavigateBack";
92 import { usePanelAnimationSettings, usePanelPresence } from "~/panelAnimations";
93 import {
94 PULL_REQUESTS_PANEL_REF,
@@ -140,7 +139,6 @@ const EMPTY_PREVIEW_DESKTOP_STATE = {};
139 const EMPTY_TERMINAL_LABELS = new Map<string, string>();
140 const EMPTY_PENDING_SURFACES = new Set<string>();
141 export function PullRequestsPage() {
143 - useEscapeToGoBack();
142 const search = useSearch({ from: "/_chat/pull-requests" });
143 const sort = search.sort ?? "ready";
144 const statsPolicy: PullRequestStatsPolicy =
apps/web/src/components/sidebar/mainAppLocation.ts
+16 -9
@@ -1,5 +1,6 @@
1 -import { useLocation, useNavigate } from "@tanstack/react-router";
2 -import { useEffect } from "react";
1 +import { useNavigate, type AnyRouter } from "@tanstack/react-router";
2 +
3 +import { GUEST_PAGE_PATH } from "../../guestPage";
4
5 /** Settings and Usage open as modals over the last main-app view. */
6 export function isAppModalPage(pathname: string) {
@@ -10,18 +11,24 @@ export function isSidebarUtilityPage(pathname: string) {
11 return pathname.startsWith("/projects/") || pathname === "/pull-requests";
12 }
13
14 +// Pages the root route always renders without the app shell, so they are never
15 +// a page to return to. Other paths seen before auth or on a prompt-link landing
16 +// are still recorded; they are real app URLs, so returning to one is harmless.
17 +const SHELL_LESS_PATHS = new Set(["/pair", "/connect", "/connect-agent", GUEST_PAGE_PATH]);
18 +
19 let mainAppHref: string | null = null;
20 let appModalReturnHref: string | null = null;
21
16 -export function MainAppLocationTracker() {
17 - const href = useLocation({ select: (location) => location.href });
18 - const pathname = useLocation({ select: (location) => location.pathname });
19 - useEffect(() => {
20 - if (isAppModalPage(pathname)) return;
22 +/** Remembers where Settings, Usage, and the utility pages lead back to. */
23 +export function startMainAppLocationTracking(router: AnyRouter): () => void {
24 + const record = () => {
25 + const { pathname, href } = router.state.location;
26 + if (isAppModalPage(pathname) || SHELL_LESS_PATHS.has(pathname)) return;
27 appModalReturnHref = href;
28 if (!isSidebarUtilityPage(pathname)) mainAppHref = href;
23 - }, [href, pathname]);
24 - return null;
29 + };
30 + record();
31 + return router.subscribe("onResolved", record);
32 }
33
34 export function useNavigateToMainApp() {
apps/web/src/confirmDialog.test.ts
+14 -4
@@ -3,12 +3,14 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";
3 import {
4 completeConfirmDialogClose,
5 readConfirmDialogState,
6 - registerConfirmDialogHost,
6 requestConfirmDialog,
7 resetConfirmDialogForTests,
8 respondToConfirmDialog,
9 + subscribeConfirmDialogHost,
10 } from "./confirmDialog";
11
12 +const mountHost = () => subscribeConfirmDialogHost(() => {});
13 +
14 function requireConfirmation(confirmation: Promise<boolean> | undefined): Promise<boolean> {
15 if (!confirmation) {
16 throw new Error("Expected a registered confirmation host.");
@@ -22,7 +24,7 @@ describe("confirm dialog coordinator", () => {
24 });
25
26 it("serializes concurrent confirmations", async () => {
25 - const unregister = registerConfirmDialogHost();
27 + const unregister = mountHost();
28 const first = requireConfirmation(requestConfirmDialog("Delete the project?"));
29 const second = requireConfirmation(requestConfirmDialog("Delete the worktree too?"));
30
@@ -49,7 +51,7 @@ describe("confirm dialog coordinator", () => {
51 });
52
53 it("cancels active and queued confirmations if the last host unmounts", async () => {
52 - const unregister = registerConfirmDialogHost();
54 + const unregister = mountHost();
55 const active = requireConfirmation(requestConfirmDialog("Delete the thread?"));
56 const queued = requireConfirmation(requestConfirmDialog("Delete the worktree too?"));
57
@@ -59,8 +61,16 @@ describe("confirm dialog coordinator", () => {
61 expect(readConfirmDialogState()).toEqual({ status: "idle" });
62 });
63
64 + it("has no host until one subscribes", () => {
65 + expect(requestConfirmDialog("Continue?")).toBeUndefined();
66 + const unsubscribe = mountHost();
67 + expect(requestConfirmDialog("Continue?")).toBeDefined();
68 + unsubscribe();
69 + expect(requestConfirmDialog("Continue?")).toBeUndefined();
70 + });
71 +
72 it("ignores responses after the active dialog has been closed", () => {
63 - const unregister = registerConfirmDialogHost();
73 + const unregister = mountHost();
74 const confirmation = requireConfirmation(requestConfirmDialog("Continue?"));
75
76 respondToConfirmDialog(true);
apps/web/src/confirmDialog.ts
+10 -22
@@ -23,7 +23,6 @@ const idleState: ConfirmDialogState = { status: "idle" };
23 let state: ConfirmDialogState = idleState;
24 let activeConfirmation: PendingConfirmation | null = null;
25 let queuedConfirmations: PendingConfirmation[] = [];
26 -let registeredHostCount = 0;
26 const listeners = new Set<() => void>();
27
28 function publish(next: ConfirmDialogState): void {
@@ -46,26 +45,16 @@ export function readConfirmDialogState(): ConfirmDialogState {
45 return state;
46 }
47
49 -export function subscribeConfirmDialog(listener: () => void): () => void {
48 +/**
49 + * Only themed hosts subscribe, so a subscriber is a mounted host. When the last
50 + * one leaves, pending confirmations resolve as cancelled.
51 + */
52 +export function subscribeConfirmDialogHost(listener: () => void): () => void {
53 listeners.add(listener);
54 return () => {
52 - listeners.delete(listener);
53 - };
54 -}
55 -
56 -export function registerConfirmDialogHost(): () => void {
57 - registeredHostCount += 1;
58 - let registered = true;
59 -
60 - return () => {
61 - if (!registered) return;
62 - registered = false;
63 - registeredHostCount = Math.max(0, registeredHostCount - 1);
64 -
65 - if (registeredHostCount === 0) {
66 - resolvePendingConfirmations(false);
67 - publish(idleState);
68 - }
55 + if (!listeners.delete(listener) || listeners.size > 0) return;
56 + resolvePendingConfirmations(false);
57 + publish(idleState);
58 };
59 }
60
@@ -74,7 +63,7 @@ export function requestConfirmDialog(
63 message: string,
64 options?: ConfirmDialogOptions,
65 ): Promise<boolean> | undefined {
77 - if (registeredHostCount === 0) return undefined;
66 + if (listeners.size === 0) return undefined;
67
68 const confirmation = new Promise<boolean>((resolve) => {
69 const pending = {
@@ -121,8 +110,7 @@ export function completeConfirmDialogClose(): void {
110 }
111
112 export function resetConfirmDialogForTests(): void {
113 + listeners.clear();
114 resolvePendingConfirmations(false);
125 - registeredHostCount = 0;
115 publish(idleState);
127 - listeners.clear();
116 }
apps/web/src/connection/useDesktopLocalBootstraps.ts
+17 -13
@@ -1,22 +1,26 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";
2 -import { useEffect, useState } from "react";
3 +import { Atom } from "effect/reactivity";
4
5 import { readDesktopSecondaryBootstraps } from "./desktopLocal";
6
7 const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
8
8 -/** The bridge has no change event. Poll, retaining the snapshot on failure and clearing on empty reads. */
9 -export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
10 - const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(
11 - readDesktopSecondaryBootstraps,
9 +/**
10 + * The bridge exposes no change event, so this re-reads on an interval while
11 + * anything reads it; failed reads retain the latest successful snapshot, while
12 + * a successful empty read clears it. The reader returns the same array while
13 + * nothing changed, so an unchanged poll notifies no one.
14 + */
15 +const desktopLocalBootstrapsAtom = Atom.make((get) => {
16 + const interval = setInterval(
17 + () => get.setSelf(readDesktopSecondaryBootstraps()),
18 + DESKTOP_LOCAL_BOOTSTRAP_POLL_MS,
19 );
20 + get.addFinalizer(() => clearInterval(interval));
21 + return readDesktopSecondaryBootstraps();
22 +}).pipe(Atom.withLabel("desktop-local-bootstraps"));
23
14 - useEffect(() => {
15 - const read = () => setBootstraps(readDesktopSecondaryBootstraps());
16 - read();
17 - const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
18 - return () => clearInterval(interval);
19 - }, []);
20 -
21 - return bootstraps;
24 +export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
25 + return useAtomValue(desktopLocalBootstrapsAtom);
26 }
apps/web/src/hooks/useLiveRegion.ts
+23 -18
@@ -1,41 +1,46 @@
1 -import { useEffect, useRef } from "react";
1 +import { useState } from "react";
2
3 // NVDA reads a polite region's leftover text again when focus returns from a
4 // dialog, so an announcement is cleared once it has had time to be spoken.
5 // Clearing doesn't cut off speech that already started.
6 const CLEAR_AFTER_MS = 7_000;
7
8 -/** A polite live region written straight to the DOM, so speaking never re-renders. */
9 -export function useLiveRegion() {
10 - const regionRef = useRef<HTMLDivElement>(null);
11 - const clearTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
8 +/**
9 + * A polite live region written straight to the DOM, so speaking never
10 + * re-renders. `attach` is the region element's ref callback; writes while no
11 + * region is attached are dropped.
12 + */
13 +export function createLiveRegion() {
14 + let region: HTMLElement | null = null;
15 + let clearTimer: ReturnType<typeof setTimeout> | null = null;
16
17 const cancelClear = () => {
14 - if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);
15 - clearTimerRef.current = null;
18 + if (clearTimer !== null) clearTimeout(clearTimer);
19 + clearTimer = null;
20 };
21
22 const clear = () => {
23 cancelClear();
20 - if (regionRef.current !== null) regionRef.current.textContent = "";
24 + if (region !== null) region.textContent = "";
25 };
26
27 const announce = (text: string) => {
24 - const region = regionRef.current;
28 if (region === null) return;
29 cancelClear();
30 // Screen readers ignore a write that leaves the text unchanged, so a repeat
31 // gets a trailing non-breaking space to count as new.
29 - region.textContent = region.textContent === text ? `${text} ` : text;
30 - clearTimerRef.current = setTimeout(clear, CLEAR_AFTER_MS);
32 + region.textContent = region.textContent === text ? `${text}\u00A0` : text;
33 + clearTimer = setTimeout(clear, CLEAR_AFTER_MS);
34 };
35
33 - useEffect(
34 - () => () => {
35 - if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);
36 - },
37 - [],
38 - );
36 + const attach = (node: HTMLElement | null) => {
37 + region = node;
38 + };
39
40 - return { regionRef, announce, clear };
40 + return { attach, announce, clear };
41 +}
42 +
43 +export function useLiveRegion() {
44 + const [liveRegion] = useState(createLiveRegion);
45 + return { regionRef: liveRegion.attach, announce: liveRegion.announce, clear: liveRegion.clear };
46 }
apps/web/src/hooks/useNavigateBack.ts deleted
-38
@@ -1,38 +0,0 @@
1 -import { useCanGoBack, useNavigate } from "@tanstack/react-router";
2 -import { useEffect } from "react";
3 -
4 -function useNavigateBack() {
5 - const navigate = useNavigate();
6 - const canGoBack = useCanGoBack();
7 -
8 - return () => {
9 - if (canGoBack) {
10 - window.history.back();
11 - return;
12 - }
13 - void navigate({ to: "/" });
14 - };
15 -}
16 -
17 -export function useEscapeToGoBack(onEscape?: () => void) {
18 - const navigateBack = useNavigateBack();
19 - const handleEscape = onEscape ?? navigateBack;
20 -
21 - useEffect(() => {
22 - const onKeyDown = (event: KeyboardEvent) => {
23 - if (event.defaultPrevented || event.repeat || event.isComposing || event.key !== "Escape")
24 - return;
25 - event.preventDefault();
26 -
27 - const activeElement = document.activeElement;
28 - if (activeElement instanceof HTMLElement) {
29 - activeElement.blur();
30 - }
31 -
32 - handleEscape();
33 - };
34 -
35 - window.addEventListener("keydown", onKeyDown);
36 - return () => window.removeEventListener("keydown", onKeyDown);
37 - }, [handleEscape]);
38 -}
apps/web/src/hooks/useThreadVisitedMigration.ts
+19 -19
@@ -1,19 +1,19 @@
1 -import { RegistryContext } from "@effect/atom-react";
1 import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
2 import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
4 -import { useContext, useEffect, useEffectEvent } from "react";
3 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
4 +import type { AtomRegistry } from "effect/reactivity";
5
6 import { environmentThreadShells, threadEnvironment } from "../state/threads";
7 -import { useAtomCommand } from "../state/use-atom-command";
7 import { useUiStateStore } from "../uiStateStore";
8
10 -const migratedThreadKeys = new Set<string>();
11 -
12 -// Subscribe outside render; shell updates must not re-render the layout for this one-time migration.
13 -export function useThreadVisitedMigration(): void {
14 - const registry = useContext(RegistryContext);
15 - const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
16 - const migrate = useEffectEvent((threads: ReadonlyArray<EnvironmentThreadShell>) => {
9 +/**
10 + * Hands visit times recorded locally (before servers tracked visits) to each
11 + * server once. Subscribed outside render: it only acts on threads it has not
12 + * seen, so a shell update must not re-render anything.
13 + */
14 +export function startThreadVisitedMigration(registry: AtomRegistry.AtomRegistry): () => void {
15 + const migratedThreadKeys = new Set<string>();
16 + const migrate = (threads: ReadonlyArray<EnvironmentThreadShell>) => {
17 for (const thread of threads) {
18 // Missing means unsupported; retain the local value until the server upgrades.
19 if (thread.lastVisitedAt === undefined) continue;
@@ -26,15 +26,15 @@ export function useThreadVisitedMigration(): void {
26 if (!Number.isFinite(localMs)) continue;
27 const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt);
28 if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue;
29 - void visitThreadMutation({
30 - environmentId: thread.environmentId,
31 - input: { threadId: thread.id, visitedAt: local },
32 - });
29 + void runAtomCommand(
30 + registry,
31 + threadEnvironment.visit,
32 + { environmentId: thread.environmentId, input: { threadId: thread.id, visitedAt: local } },
33 + { reportFailure: false },
34 + );
35 }
36 + };
37 + return registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, {
38 + immediate: true,
39 });
35 - useEffect(
36 - () =>
37 - registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, { immediate: true }),
38 - [registry],
39 - );
40 }
apps/web/src/panelAnimations.ts
+2
@@ -12,6 +12,7 @@ export function usePanelNavigationSuppression(navigationKey: string): boolean {
12 const [paintedNavigationKey, setPaintedNavigationKey] = useState<string | null>(null);
13 const suppressed = paintedNavigationKey !== navigationKey;
14
15 + // oxlint-disable-next-line t3code/react-effect-budget -- Wait two browser frames so the new route paints before panel animations are re-enabled; cancel the frames on change or unmount.
16 useEffect(() => {
17 if (!suppressed) return;
18 let releaseFrame = 0;
@@ -55,6 +56,7 @@ export function usePanelPresence<T>(
56 if (open && !present) setPresent(true);
57 if (!open && !animated && present) setPresent(false);
58
59 + // oxlint-disable-next-line t3code/react-effect-budget -- Keep the closing panel mounted for its CSS exit transition, then unmount it; the timer is cleared on reopen or unmount.
60 useEffect(() => {
61 if (open || !animated) return;
62 const timeout = window.setTimeout(() => setPresent(false), durationMs);
apps/web/src/remoteOpen.ts
+13 -34
@@ -9,7 +9,6 @@ import * as Option from "effect/Option";
9 import * as Schema from "effect/Schema";
10 import { Atom } from "effect/reactivity";
11 import { useAtomValue } from "@effect/atom-react";
12 -import { useEffect, useState } from "react";
12
13 import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
14 import { isLoopbackHostname } from "~/environments/primary/target";
@@ -147,41 +146,21 @@ export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteO
146
147 const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
148
150 -let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;
151 -
152 -export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
153 - const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(
154 - () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,
149 +// Probed once per page: installed editors rarely change, and the probe spawns processes.
150 +const remoteCapableEditorsAtom = Atom.make((get): ReadonlyArray<EditorId> => {
151 + const probe = window.desktopBridge?.probeRemoteEditors;
152 + probe?.().then(
153 + (ids) => {
154 + const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
155 + if (remoteCapable.length > 0) get.setSelf(remoteCapable);
156 + },
157 + () => undefined,
158 );
159 + return REMOTE_FALLBACK_EDITORS;
160 +}).pipe(Atom.keepAlive, Atom.withLabel("remote-capable-editors"));
161
157 - useEffect(() => {
158 - if (cachedProbedEditors !== null) {
159 - return;
160 - }
161 - const probe = window.desktopBridge?.probeRemoteEditors;
162 - if (probe === undefined) {
163 - cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
164 - return;
165 - }
166 - let cancelled = false;
167 - probe().then(
168 - (ids) => {
169 - const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
170 - cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;
171 - if (!cancelled) {
172 - setEditors(cachedProbedEditors);
173 - }
174 - },
175 - () => {
176 - cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
177 - },
178 - );
179 - return () => {
180 - cancelled = true;
181 - };
182 - }, []);
183 -
184 - return editors;
162 +export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
163 + return useAtomValue(remoteCapableEditorsAtom);
164 }
165
166 /** Resolves false when the desktop refuses the URL, including unsupported editor schemes. */