TypeScript
fix(web): SSH password prompts wait for their dialog, and the app shell drops its sync effects (#25239)
Julius Marminge02f4ba75a20f
diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsxindex 884cff29254..64f98a87322 100644--- a/apps/web/src/appInit.tsx+++ b/apps/web/src/appInit.tsx@@ -5,12 +5,16 @@ import { createBrowserHistory, createHashHistory } from "@tanstack/react-router"import { applyAppearanceContrast } from "./appearanceContrast";import { applyAppearanceFontVariables } from "./appearanceFonts";import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";+import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";+import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";+import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";import { resolveServerBackedAppDisplayName } from "./branding.logic";import { isElectron } from "./env";import { useComposerDraftStore } from "./composerDraftStore";import { getClientSettings, subscribeClientSettings } from "./hooks/useSettings";+import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";import {syncDocumentElectronPlatformClasses,syncDocumentWindowControlsOverlayClass,@@ -126,6 +130,10 @@ export function startAppServices(): AppRouter {startDocumentTitle();startAgentOpenedPreviews();startThreadOverlayRetention(router);+ startMainAppLocationTracking(router);+ startBackgroundThreadAnnouncements(appAtomRegistry, router);+ startThreadVisitedMigration(appAtomRegistry);+ startSshPasswordPromptQueue();return router;}diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex 9f03774f2ac..f7b3209f661 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -38,10 +38,9 @@ import {} from "../panelAnimations";import { BackgroundThreadAnnouncer } from "./BackgroundThreadAnnouncer";import LegacyThreadSidebar from "./LegacySidebar";-import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration";import ThreadSidebar from "./Sidebar";import { SidebarBrandWidthProbe } from "./sidebar/SidebarChrome";-import { isAppModalPage, MainAppLocationTracker } from "./sidebar/mainAppLocation";+import { isAppModalPage } from "./sidebar/mainAppLocation";import type { SidebarRouteReveal } from "./sidebar/routeReveal";import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";import {@@ -171,6 +170,28 @@ export function registerNavigationHistoryCommands(router: AnyRouter): () => void);}+// Escape leaves the pull requests page when no scope (a selection, a dialog,+// a drag) claimed it, so it observes after every other scope.+function registerPullRequestsEscapeCommand(router: AnyRouter): () => void {+ return registerCommands(+ {},+ {+ observe: (event, consumed) => {+ if (consumed || event.repeat || event.isComposing || event.key !== "Escape") return;+ if (router.state.location.pathname !== "/pull-requests") return;+ event.preventDefault();+ const activeElement = document.activeElement;+ if (activeElement instanceof HTMLElement) activeElement.blur();+ if (router.state.location.state.__TSR_index !== 0) {+ window.history.back();+ return;+ }+ void router.navigate({ to: "/" });+ },+ },+ );+}+const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);// A held key undoes once. Module state: undoing an archive navigates, and the@@ -251,6 +272,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): ()const disposers = [registerThreadUndoCommands(router, readSidebarVisible),registerNavigationHistoryCommands(router),+ registerPullRequestsEscapeCommand(router),registerMenuAction("open-settings", () => {if (!/^\/settings(\/|$)/.test(router.state.location.pathname))void router.navigate({ to: "/settings" });@@ -359,7 +381,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {}));const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } =usePanelAnimationSettings();- useThreadVisitedMigration();const pathname = useLocation({ select: (location) => location.pathname });const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;@@ -429,7 +450,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {{children}<BackgroundThreadAnnouncer /><SidebarControl />- <MainAppLocationTracker /></SidebarProvider></PanelAnimationSuppressionProvider>);diff --git a/apps/web/src/components/BackgroundThreadAnnouncer.tsx b/apps/web/src/components/BackgroundThreadAnnouncer.tsxindex 40e0ebf3a0b..82c280e6e56 100644--- a/apps/web/src/components/BackgroundThreadAnnouncer.tsx+++ b/apps/web/src/components/BackgroundThreadAnnouncer.tsx@@ -1,14 +1,13 @@-import { useAtomValue } from "@effect/atom-react";import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";import { effectiveSnoozed } from "@t3tools/client-runtime/state/thread-settled";-import { useEffect, useRef } from "react";+import type { AnyRouter } from "@tanstack/react-router";+import type { AtomRegistry } from "effect/reactivity";import { useComposerDraftStore } from "../composerDraftStore";-import { useLiveRegion } from "../hooks/useLiveRegion";-import { useThreadRouteTarget } from "../hooks/useThreadRouteTarget";-import { useQuietThreadShells } from "../state/entities";+import { createLiveRegion } from "../hooks/useLiveRegion";import { liveShellEnvironmentIdsAtom } from "../state/shell";-import { resolveActiveThreadRouteRef } from "../threadRoutes";+import { environmentThreadShells } from "../state/threads";+import { resolveActiveThreadRouteRef, resolveThreadRouteTarget } from "../threadRoutes";import {type BackgroundThreadMemory,type BackgroundThreadSnapshot,@@ -16,23 +15,30 @@ import {resolveBackgroundThreadRequest,} from "./backgroundThreadAnnouncement";-/**- * Speaks status changes for threads other than the open one. It lives outside- * the sidebar because a collapsed sidebar is inert, which silences its rows.- */-export function BackgroundThreadAnnouncer() {- const threads = useQuietThreadShells();- const liveEnvironmentIds = useAtomValue(liveShellEnvironmentIdsAtom);- const routeTarget = useThreadRouteTarget();- const routeDraftThread = useComposerDraftStore((store) =>- routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,- );- const openThreadRef = resolveActiveThreadRouteRef(routeTarget, routeDraftThread);- const openThreadKey = openThreadRef === null ? null : scopedThreadKey(openThreadRef);- const { regionRef, announce } = useLiveRegion();- const memoryRef = useRef<BackgroundThreadMemory>(new Map());+const backgroundThreadLiveRegion = createLiveRegion();+const attachBackgroundThreadRegion = backgroundThreadLiveRegion.attach;++function readOpenThreadKey(router: AnyRouter): string | null {+ const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});+ const draft =+ target?.kind === "draft"+ ? useComposerDraftStore.getState().getDraftSession(target.draftId)+ : null;+ const ref = resolveActiveThreadRouteRef(target, draft);+ return ref === null ? null : scopedThreadKey(ref);+}++/** Speaks status changes for threads other than the open one, for the life of the app. */+export function startBackgroundThreadAnnouncements(+ registry: AtomRegistry.AtomRegistry,+ router: AnyRouter,+): () => void {+ let memory: BackgroundThreadMemory = new Map();+ let openThreadKey = readOpenThreadKey(router);- useEffect(() => {+ const update = () => {+ const threads = registry.get(environmentThreadShells.quietThreadShellsAtom);+ const liveEnvironmentIds = registry.get(liveShellEnvironmentIdsAtom);const now = new Date().toISOString();const snapshots: BackgroundThreadSnapshot[] = [];for (const thread of threads) {@@ -50,15 +56,36 @@ export function BackgroundThreadAnnouncer() {snoozed: effectiveSnoozed(thread, { now }),});}- const { memory, announcement } = nextBackgroundThreadAnnouncement(- memoryRef.current,- snapshots,- openThreadKey,- );- memoryRef.current = memory;- if (announcement !== null) announce(announcement);- }, [threads, liveEnvironmentIds, openThreadKey, announce]);+ const next = nextBackgroundThreadAnnouncement(memory, snapshots, openThreadKey);+ memory = next.memory;+ if (next.announcement !== null) backgroundThreadLiveRegion.announce(next.announcement);+ };+ // The draft store changes on every keystroke; only a new open thread matters here.+ const updateOpenThread = () => {+ const next = readOpenThreadKey(router);+ if (next === openThreadKey) return;+ openThreadKey = next;+ update();+ };++ const unsubscribes = [+ registry.subscribe(environmentThreadShells.quietThreadShellsAtom, update),+ registry.subscribe(liveShellEnvironmentIdsAtom, update),+ router.subscribe("onResolved", updateOpenThread),+ useComposerDraftStore.subscribe(updateOpenThread),+ ];+ update();+ return () => {+ for (const unsubscribe of unsubscribes) unsubscribe();+ };+}++/**+ * The region the background announcements are spoken through. It lives outside+ * the sidebar because a collapsed sidebar is inert, which silences its rows.+ */+export function BackgroundThreadAnnouncer() {// No role="status": Orca 50 maps it to a status bar in Chromium and drops its updates.- return <div ref={regionRef} aria-live="polite" className="sr-only" />;+ return <div ref={attachBackgroundThreadRegion} aria-live="polite" className="sr-only" />;}diff --git a/apps/web/src/components/ConfirmDialogHost.tsx b/apps/web/src/components/ConfirmDialogHost.tsxindex 92477801eb7..8992dc43d7c 100644--- a/apps/web/src/components/ConfirmDialogHost.tsx+++ b/apps/web/src/components/ConfirmDialogHost.tsx@@ -1,11 +1,10 @@-import { useEffect, useSyncExternalStore } from "react";+import { useSyncExternalStore } from "react";import {completeConfirmDialogClose,readConfirmDialogState,- registerConfirmDialogHost,respondToConfirmDialog,- subscribeConfirmDialog,+ subscribeConfirmDialogHost,} from "../confirmDialog";import {AlertDialog,@@ -53,13 +52,11 @@ function resolveConfirmDialogCopy(message: string): ConfirmationCopy {export function ConfirmDialogHost() {const state = useSyncExternalStore(- subscribeConfirmDialog,+ subscribeConfirmDialogHost,readConfirmDialogState,readConfirmDialogState,);- useEffect(() => registerConfirmDialogHost(), []);-const copy = resolveConfirmDialogCopy(state.status === "idle" ? "" : state.message);const confirmVariant = state.status === "idle" ? "default" : state.variant;const onCancel = () => respondToConfirmDialog(false);diff --git a/apps/web/src/components/QuitHoldOverlay.tsx b/apps/web/src/components/QuitHoldOverlay.tsxindex 25d6a745de9..819455b68f3 100644--- a/apps/web/src/components/QuitHoldOverlay.tsx+++ b/apps/web/src/components/QuitHoldOverlay.tsx@@ -1,35 +1,55 @@-import { useEffect, useState } from "react";+import { useSyncExternalStore } from "react";import { isMacPlatform } from "../lib/utils";const HOLD_HINT_LINGER_MS = 1200;+type QuitHintMode = "hold" | "double-click";++let visibleMode: QuitHintMode | null = null;+let pressedMode: QuitHintMode = "hold";+let hideTimer: number | undefined;+const listeners = new Set<() => void>();+let stopBridge: (() => void) | null = null;++function setVisibleMode(next: QuitHintMode | null) {+ if (next === visibleMode) return;+ visibleMode = next;+ for (const listener of listeners) listener();+}++function subscribeQuitHint(listener: () => void): () => void {+ listeners.add(listener);+ if (listeners.size === 1) {+ stopBridge =+ window.desktopBridge?.onQuitShortcut?.((hint) => {+ window.clearTimeout(hideTimer);+ if (hint.state === "down") {+ pressedMode = hint.mode;+ setVisibleMode(hint.mode);+ return;+ }+ if (pressedMode === "double-click") {+ setVisibleMode(null);+ return;+ }+ hideTimer = window.setTimeout(() => setVisibleMode(null), HOLD_HINT_LINGER_MS);+ }) ?? null;+ }+ return () => {+ listeners.delete(listener);+ if (listeners.size > 0) return;+ window.clearTimeout(hideTimer);+ stopBridge?.();+ stopBridge = null;+ visibleMode = null;+ };+}++const readQuitHint = () => visibleMode;+export function QuitHoldOverlay() {- const [visibleMode, setVisibleMode] = useState<"hold" | "double-click" | null>(null);-- useEffect(() => {- const subscribe = window.desktopBridge?.onQuitShortcut;- if (!subscribe) return;- let hideTimer: number | undefined;- let pressedMode: "hold" | "double-click" = "hold";- const unsubscribe = subscribe((hint) => {- window.clearTimeout(hideTimer);- if (hint.state === "down") {- pressedMode = hint.mode;- setVisibleMode(hint.mode);- return;- }- if (pressedMode === "double-click") {- setVisibleMode(null);- return;- }- hideTimer = window.setTimeout(() => setVisibleMode(null), HOLD_HINT_LINGER_MS);- });- return () => {- window.clearTimeout(hideTimer);- unsubscribe();- };- }, []);+ const visibleMode = useSyncExternalStore(subscribeQuitHint, readQuitHint, readQuitHint);if (!visibleMode) return null;const shortcut = isMacPlatform(navigator.platform) ? "⌘Q" : "Ctrl+Q";diff --git a/apps/web/src/components/desktop/SshPasswordPromptDialog.browser.test.tsx b/apps/web/src/components/desktop/SshPasswordPromptDialog.browser.test.tsxnew file mode 100644index 00000000000..53eaec18222--- /dev/null+++ b/apps/web/src/components/desktop/SshPasswordPromptDialog.browser.test.tsx@@ -0,0 +1,32 @@+import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";+import { expect, it } from "vite-plus/test";++import { render, stubGlobal } from "../../../test/render";+import { SshPasswordPromptDialog, startSshPasswordPromptQueue } from "./SshPasswordPromptDialog";++it("shows a prompt that arrived before the dialog mounted", async () => {+ const listeners: Array<(request: DesktopSshPasswordPromptRequest) => void> = [];+ using _bridge = stubGlobal("desktopBridge", {+ onSshPasswordPrompt: (listener: (request: DesktopSshPasswordPromptRequest) => void) => {+ listeners.push(listener);+ return () => listeners.splice(listeners.indexOf(listener), 1);+ },+ resolveSshPasswordPrompt: async () => undefined,+ });+ const stopQueue = startSshPasswordPromptQueue();+ using _queue = { [Symbol.dispose]: stopQueue };++ // The desktop asks while the app is still on a page without the dialog (pairing, sign-in).+ for (const listener of listeners) {+ listener({+ requestId: "ssh-1",+ destination: "devbox",+ username: "julius",+ prompt: "julius@devbox's password:",+ expiresAt: "2999-01-01T00:00:00.000Z",+ });+ }++ await using screen = await render(<SshPasswordPromptDialog />);+ await expect.element(screen.getByText("SSH verification required")).toBeVisible();+});diff --git a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsxindex 0d63558e896..4ed3b3afc44 100644--- a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx+++ b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx@@ -2,7 +2,10 @@ import { settlePromise } from "@t3tools/client-runtime/state/runtime";import type { DesktopSshPasswordPromptRequest } from "@t3tools/contracts";import * as AsyncResult from "effect/reactivity/AsyncResult";import * as Cause from "effect/Cause";-import { useEffect, useId, useRef, useState } from "react";+import { useId, useRef, useState, useSyncExternalStore } from "react";++import { useDeadlinePassed } from "../../hooks/useDeadline";+import { useNowSecond } from "../../hooks/useNowSecond";import { Button } from "../ui/button";import {@@ -31,75 +34,70 @@ function getPromptErrorMessage(error: unknown): string {: message;}-export function SshPasswordPromptDialog() {- const [queue, setQueue] = useState<readonly DesktopSshPasswordPromptRequest[]>([]);- const currentRequest = queue[0] ?? null;+let promptQueue: readonly DesktopSshPasswordPromptRequest[] = [];+const promptQueueListeners = new Set<() => void>();- useEffect(() => {- const bridge = window.desktopBridge;- if (!bridge?.onSshPasswordPrompt) {- return;- }+function setPromptQueue(next: readonly DesktopSshPasswordPromptRequest[]) {+ promptQueue = next;+ for (const listener of promptQueueListeners) listener();+}++/**+ * Queues the desktop's SSH password prompts for the life of the page, so a prompt+ * that arrives while no dialog is mounted still waits for one.+ */+export function startSshPasswordPromptQueue(): () => void {+ return (+ window.desktopBridge?.onSshPasswordPrompt?.((request) => {+ setPromptQueue([...promptQueue, request]);+ }) ?? (() => undefined)+ );+}++function subscribePromptQueue(listener: () => void): () => void {+ promptQueueListeners.add(listener);+ return () => {+ promptQueueListeners.delete(listener);+ };+}++const readPromptQueue = () => promptQueue;- return bridge.onSshPasswordPrompt((request) => {- setQueue((currentQueue) => [...currentQueue, request]);- });- }, []);+function removeSshPasswordPrompt(requestId: string) {+ if (promptQueue[0]?.requestId === requestId) setPromptQueue(promptQueue.slice(1));+}++export function SshPasswordPromptDialog() {+ const queue = useSyncExternalStore(subscribePromptQueue, readPromptQueue, readPromptQueue);+ const currentRequest = queue[0] ?? null;if (!currentRequest) {return null;}- return (- <ActiveSshPasswordPrompt- key={currentRequest.requestId}- request={currentRequest}- onRemove={(requestId) => {- setQueue((currentQueue) =>- currentQueue[0]?.requestId === requestId ? currentQueue.slice(1) : currentQueue,- );- }}- />- );+ return <ActiveSshPasswordPrompt key={currentRequest.requestId} request={currentRequest} />;}function ActiveSshPasswordPrompt({request,- onRemove,}: {readonly request: DesktopSshPasswordPromptRequest;- readonly onRemove: (requestId: string) => void;}) {const [password, setPassword] = useState("");const [isResponding, setIsResponding] = useState(false);- const [now, setNow] = useState(() => Date.now());const [responseError, setResponseError] = useState<string | null>(null);const inputRef = useRef<HTMLInputElement | null>(null);const isRespondingRef = useRef(false);const formId = useId();- useEffect(() => {- const frame = window.requestAnimationFrame(() => {- inputRef.current?.focus();- inputRef.current?.select();- });- return () => {- window.cancelAnimationFrame(frame);- };- }, []);-- useEffect(() => {- const interval = window.setInterval(() => {- setNow(Date.now());- }, 1_000);- return () => {- window.clearInterval(interval);- };- }, []);-const expiresAtMs = Date.parse(request.expiresAt);- const remainingMs = Number.isFinite(expiresAtMs) ? Math.max(0, expiresAtMs - now) : null;- const isExpired = remainingMs !== null && remainingMs <= 0;+ const now = useNowSecond();+ const isExpired = useDeadlinePassed(Number.isFinite(expiresAtMs) ? expiresAtMs : null);+ const remainingMs = Number.isFinite(expiresAtMs)+ ? isExpired+ ? 0+ : Math.max(0, expiresAtMs - now)+ : null;const remainingSeconds = remainingMs === null ? null : Math.ceil(remainingMs / 1_000);const remainingLabel =remainingSeconds === null ? null : formatRemainingSeconds(remainingSeconds);@@ -125,7 +123,7 @@ function ActiveSshPasswordPrompt({window.desktopBridge?.resolveSshPasswordPrompt(requestId, nextPassword),);if (AsyncResult.isSuccess(result) || nextPassword === null) {- onRemove(requestId);+ removeSshPasswordPrompt(requestId);} else {setResponseError(getPromptErrorMessage(Cause.squash(result.cause)));}@@ -134,7 +132,7 @@ function ActiveSshPasswordPrompt({};const dismissExpiredPrompt = () => {- onRemove(request.requestId);+ removeSshPasswordPrompt(request.requestId);};const cancelPrompt = () => {@@ -156,7 +154,7 @@ function ActiveSshPasswordPrompt({}}}>- <DialogPopup className="max-w-md" showCloseButton={false}>+ <DialogPopup className="max-w-md" initialFocus={inputRef} showCloseButton={false}><DialogHeader><DialogTitle>SSH verification required</DialogTitle><DialogDescription>diff --git a/apps/web/src/components/pullRequest/PullRequestsPage.tsx b/apps/web/src/components/pullRequest/PullRequestsPage.tsxindex b2574b31ba7..3c746721d0a 100644--- a/apps/web/src/components/pullRequest/PullRequestsPage.tsx+++ b/apps/web/src/components/pullRequest/PullRequestsPage.tsx@@ -89,7 +89,6 @@ import { useStableCallback } from "~/hooks/useStableCallback";import { useOpenPanelPullRequestUrl } from "~/hooks/useOpenPanelPullRequestUrl";import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";import { toastManager } from "../ui/toast";-import { useEscapeToGoBack } from "~/hooks/useNavigateBack";import { usePanelAnimationSettings, usePanelPresence } from "~/panelAnimations";import {PULL_REQUESTS_PANEL_REF,@@ -140,7 +139,6 @@ const EMPTY_PREVIEW_DESKTOP_STATE = {};const EMPTY_TERMINAL_LABELS = new Map<string, string>();const EMPTY_PENDING_SURFACES = new Set<string>();export function PullRequestsPage() {- useEscapeToGoBack();const search = useSearch({ from: "/_chat/pull-requests" });const sort = search.sort ?? "ready";const statsPolicy: PullRequestStatsPolicy =diff --git a/apps/web/src/components/sidebar/mainAppLocation.ts b/apps/web/src/components/sidebar/mainAppLocation.tsindex 9bdc2720300..a732d9f435b 100644--- a/apps/web/src/components/sidebar/mainAppLocation.ts+++ b/apps/web/src/components/sidebar/mainAppLocation.ts@@ -1,5 +1,6 @@-import { useLocation, useNavigate } from "@tanstack/react-router";-import { useEffect } from "react";+import { useNavigate, type AnyRouter } from "@tanstack/react-router";++import { GUEST_PAGE_PATH } from "../../guestPage";/** Settings and Usage open as modals over the last main-app view. */export function isAppModalPage(pathname: string) {@@ -10,18 +11,24 @@ export function isSidebarUtilityPage(pathname: string) {return pathname.startsWith("/projects/") || pathname === "/pull-requests";}+// Pages the root route always renders without the app shell, so they are never+// a page to return to. Other paths seen before auth or on a prompt-link landing+// are still recorded; they are real app URLs, so returning to one is harmless.+const SHELL_LESS_PATHS = new Set(["/pair", "/connect", "/connect-agent", GUEST_PAGE_PATH]);+let mainAppHref: string | null = null;let appModalReturnHref: string | null = null;-export function MainAppLocationTracker() {- const href = useLocation({ select: (location) => location.href });- const pathname = useLocation({ select: (location) => location.pathname });- useEffect(() => {- if (isAppModalPage(pathname)) return;+/** Remembers where Settings, Usage, and the utility pages lead back to. */+export function startMainAppLocationTracking(router: AnyRouter): () => void {+ const record = () => {+ const { pathname, href } = router.state.location;+ if (isAppModalPage(pathname) || SHELL_LESS_PATHS.has(pathname)) return;appModalReturnHref = href;if (!isSidebarUtilityPage(pathname)) mainAppHref = href;- }, [href, pathname]);- return null;+ };+ record();+ return router.subscribe("onResolved", record);}export function useNavigateToMainApp() {diff --git a/apps/web/src/confirmDialog.test.ts b/apps/web/src/confirmDialog.test.tsindex 72429536300..ea2d242b6be 100644--- a/apps/web/src/confirmDialog.test.ts+++ b/apps/web/src/confirmDialog.test.ts@@ -3,12 +3,14 @@ import { beforeEach, describe, expect, it } from "vite-plus/test";import {completeConfirmDialogClose,readConfirmDialogState,- registerConfirmDialogHost,requestConfirmDialog,resetConfirmDialogForTests,respondToConfirmDialog,+ subscribeConfirmDialogHost,} from "./confirmDialog";+const mountHost = () => subscribeConfirmDialogHost(() => {});+function requireConfirmation(confirmation: Promise<boolean> | undefined): Promise<boolean> {if (!confirmation) {throw new Error("Expected a registered confirmation host.");@@ -22,7 +24,7 @@ describe("confirm dialog coordinator", () => {});it("serializes concurrent confirmations", async () => {- const unregister = registerConfirmDialogHost();+ const unregister = mountHost();const first = requireConfirmation(requestConfirmDialog("Delete the project?"));const second = requireConfirmation(requestConfirmDialog("Delete the worktree too?"));@@ -49,7 +51,7 @@ describe("confirm dialog coordinator", () => {});it("cancels active and queued confirmations if the last host unmounts", async () => {- const unregister = registerConfirmDialogHost();+ const unregister = mountHost();const active = requireConfirmation(requestConfirmDialog("Delete the thread?"));const queued = requireConfirmation(requestConfirmDialog("Delete the worktree too?"));@@ -59,8 +61,16 @@ describe("confirm dialog coordinator", () => {expect(readConfirmDialogState()).toEqual({ status: "idle" });});+ it("has no host until one subscribes", () => {+ expect(requestConfirmDialog("Continue?")).toBeUndefined();+ const unsubscribe = mountHost();+ expect(requestConfirmDialog("Continue?")).toBeDefined();+ unsubscribe();+ expect(requestConfirmDialog("Continue?")).toBeUndefined();+ });+it("ignores responses after the active dialog has been closed", () => {- const unregister = registerConfirmDialogHost();+ const unregister = mountHost();const confirmation = requireConfirmation(requestConfirmDialog("Continue?"));respondToConfirmDialog(true);diff --git a/apps/web/src/confirmDialog.ts b/apps/web/src/confirmDialog.tsindex 00cde8742c2..dcbc79a6a16 100644--- a/apps/web/src/confirmDialog.ts+++ b/apps/web/src/confirmDialog.ts@@ -23,7 +23,6 @@ const idleState: ConfirmDialogState = { status: "idle" };let state: ConfirmDialogState = idleState;let activeConfirmation: PendingConfirmation | null = null;let queuedConfirmations: PendingConfirmation[] = [];-let registeredHostCount = 0;const listeners = new Set<() => void>();function publish(next: ConfirmDialogState): void {@@ -46,26 +45,16 @@ export function readConfirmDialogState(): ConfirmDialogState {return state;}-export function subscribeConfirmDialog(listener: () => void): () => void {+/**+ * Only themed hosts subscribe, so a subscriber is a mounted host. When the last+ * one leaves, pending confirmations resolve as cancelled.+ */+export function subscribeConfirmDialogHost(listener: () => void): () => void {listeners.add(listener);return () => {- listeners.delete(listener);- };-}--export function registerConfirmDialogHost(): () => void {- registeredHostCount += 1;- let registered = true;-- return () => {- if (!registered) return;- registered = false;- registeredHostCount = Math.max(0, registeredHostCount - 1);-- if (registeredHostCount === 0) {- resolvePendingConfirmations(false);- publish(idleState);- }+ if (!listeners.delete(listener) || listeners.size > 0) return;+ resolvePendingConfirmations(false);+ publish(idleState);};}@@ -74,7 +63,7 @@ export function requestConfirmDialog(message: string,options?: ConfirmDialogOptions,): Promise<boolean> | undefined {- if (registeredHostCount === 0) return undefined;+ if (listeners.size === 0) return undefined;const confirmation = new Promise<boolean>((resolve) => {const pending = {@@ -121,8 +110,7 @@ export function completeConfirmDialogClose(): void {}export function resetConfirmDialogForTests(): void {+ listeners.clear();resolvePendingConfirmations(false);- registeredHostCount = 0;publish(idleState);- listeners.clear();}diff --git a/apps/web/src/connection/useDesktopLocalBootstraps.ts b/apps/web/src/connection/useDesktopLocalBootstraps.tsindex ee8cf2e296a..75c6904731e 100644--- a/apps/web/src/connection/useDesktopLocalBootstraps.ts+++ b/apps/web/src/connection/useDesktopLocalBootstraps.ts@@ -1,22 +1,26 @@+import { useAtomValue } from "@effect/atom-react";import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";-import { useEffect, useState } from "react";+import { Atom } from "effect/reactivity";import { readDesktopSecondaryBootstraps } from "./desktopLocal";const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;-/** The bridge has no change event. Poll, retaining the snapshot on failure and clearing on empty reads. */-export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {- const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(- readDesktopSecondaryBootstraps,+/**+ * The bridge exposes no change event, so this re-reads on an interval while+ * anything reads it; failed reads retain the latest successful snapshot, while+ * a successful empty read clears it. The reader returns the same array while+ * nothing changed, so an unchanged poll notifies no one.+ */+const desktopLocalBootstrapsAtom = Atom.make((get) => {+ const interval = setInterval(+ () => get.setSelf(readDesktopSecondaryBootstraps()),+ DESKTOP_LOCAL_BOOTSTRAP_POLL_MS,);+ get.addFinalizer(() => clearInterval(interval));+ return readDesktopSecondaryBootstraps();+}).pipe(Atom.withLabel("desktop-local-bootstraps"));- useEffect(() => {- const read = () => setBootstraps(readDesktopSecondaryBootstraps());- read();- const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);- return () => clearInterval(interval);- }, []);-- return bootstraps;+export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {+ return useAtomValue(desktopLocalBootstrapsAtom);}diff --git a/apps/web/src/hooks/useLiveRegion.ts b/apps/web/src/hooks/useLiveRegion.tsindex edc43cf69ce..fcfb6cf2fda 100644--- a/apps/web/src/hooks/useLiveRegion.ts+++ b/apps/web/src/hooks/useLiveRegion.ts@@ -1,41 +1,46 @@-import { useEffect, useRef } from "react";+import { useState } from "react";// NVDA reads a polite region's leftover text again when focus returns from a// dialog, so an announcement is cleared once it has had time to be spoken.// Clearing doesn't cut off speech that already started.const CLEAR_AFTER_MS = 7_000;-/** A polite live region written straight to the DOM, so speaking never re-renders. */-export function useLiveRegion() {- const regionRef = useRef<HTMLDivElement>(null);- const clearTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+/**+ * A polite live region written straight to the DOM, so speaking never+ * re-renders. `attach` is the region element's ref callback; writes while no+ * region is attached are dropped.+ */+export function createLiveRegion() {+ let region: HTMLElement | null = null;+ let clearTimer: ReturnType<typeof setTimeout> | null = null;const cancelClear = () => {- if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);- clearTimerRef.current = null;+ if (clearTimer !== null) clearTimeout(clearTimer);+ clearTimer = null;};const clear = () => {cancelClear();- if (regionRef.current !== null) regionRef.current.textContent = "";+ if (region !== null) region.textContent = "";};const announce = (text: string) => {- const region = regionRef.current;if (region === null) return;cancelClear();// Screen readers ignore a write that leaves the text unchanged, so a repeat// gets a trailing non-breaking space to count as new.- region.textContent = region.textContent === text ? `${text} ` : text;- clearTimerRef.current = setTimeout(clear, CLEAR_AFTER_MS);+ region.textContent = region.textContent === text ? `${text}\u00A0` : text;+ clearTimer = setTimeout(clear, CLEAR_AFTER_MS);};- useEffect(- () => () => {- if (clearTimerRef.current !== null) clearTimeout(clearTimerRef.current);- },- [],- );+ const attach = (node: HTMLElement | null) => {+ region = node;+ };- return { regionRef, announce, clear };+ return { attach, announce, clear };+}++export function useLiveRegion() {+ const [liveRegion] = useState(createLiveRegion);+ return { regionRef: liveRegion.attach, announce: liveRegion.announce, clear: liveRegion.clear };}diff --git a/apps/web/src/hooks/useNavigateBack.ts b/apps/web/src/hooks/useNavigateBack.tsdeleted file mode 100644index 6487d584958..00000000000--- a/apps/web/src/hooks/useNavigateBack.ts+++ /dev/null@@ -1,38 +0,0 @@-import { useCanGoBack, useNavigate } from "@tanstack/react-router";-import { useEffect } from "react";--function useNavigateBack() {- const navigate = useNavigate();- const canGoBack = useCanGoBack();-- return () => {- if (canGoBack) {- window.history.back();- return;- }- void navigate({ to: "/" });- };-}--export function useEscapeToGoBack(onEscape?: () => void) {- const navigateBack = useNavigateBack();- const handleEscape = onEscape ?? navigateBack;-- useEffect(() => {- const onKeyDown = (event: KeyboardEvent) => {- if (event.defaultPrevented || event.repeat || event.isComposing || event.key !== "Escape")- return;- event.preventDefault();-- const activeElement = document.activeElement;- if (activeElement instanceof HTMLElement) {- activeElement.blur();- }-- handleEscape();- };-- window.addEventListener("keydown", onKeyDown);- return () => window.removeEventListener("keydown", onKeyDown);- }, [handleEscape]);-}diff --git a/apps/web/src/hooks/useThreadVisitedMigration.ts b/apps/web/src/hooks/useThreadVisitedMigration.tsindex b02cb05bb5f..2d01d800360 100644--- a/apps/web/src/hooks/useThreadVisitedMigration.ts+++ b/apps/web/src/hooks/useThreadVisitedMigration.ts@@ -1,19 +1,19 @@-import { RegistryContext } from "@effect/atom-react";import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";-import { useContext, useEffect, useEffectEvent } from "react";+import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";+import type { AtomRegistry } from "effect/reactivity";import { environmentThreadShells, threadEnvironment } from "../state/threads";-import { useAtomCommand } from "../state/use-atom-command";import { useUiStateStore } from "../uiStateStore";-const migratedThreadKeys = new Set<string>();--// Subscribe outside render; shell updates must not re-render the layout for this one-time migration.-export function useThreadVisitedMigration(): void {- const registry = useContext(RegistryContext);- const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });- const migrate = useEffectEvent((threads: ReadonlyArray<EnvironmentThreadShell>) => {+/**+ * Hands visit times recorded locally (before servers tracked visits) to each+ * server once. Subscribed outside render: it only acts on threads it has not+ * seen, so a shell update must not re-render anything.+ */+export function startThreadVisitedMigration(registry: AtomRegistry.AtomRegistry): () => void {+ const migratedThreadKeys = new Set<string>();+ const migrate = (threads: ReadonlyArray<EnvironmentThreadShell>) => {for (const thread of threads) {// Missing means unsupported; retain the local value until the server upgrades.if (thread.lastVisitedAt === undefined) continue;@@ -26,15 +26,15 @@ export function useThreadVisitedMigration(): void {if (!Number.isFinite(localMs)) continue;const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt);if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue;- void visitThreadMutation({- environmentId: thread.environmentId,- input: { threadId: thread.id, visitedAt: local },- });+ void runAtomCommand(+ registry,+ threadEnvironment.visit,+ { environmentId: thread.environmentId, input: { threadId: thread.id, visitedAt: local } },+ { reportFailure: false },+ );}+ };+ return registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, {+ immediate: true,});- useEffect(- () =>- registry.subscribe(environmentThreadShells.threadShellsAtom, migrate, { immediate: true }),- [registry],- );}diff --git a/apps/web/src/panelAnimations.ts b/apps/web/src/panelAnimations.tsindex efbdfa526d5..aee2f7a0a6c 100644--- a/apps/web/src/panelAnimations.ts+++ b/apps/web/src/panelAnimations.ts@@ -12,6 +12,7 @@ export function usePanelNavigationSuppression(navigationKey: string): boolean {const [paintedNavigationKey, setPaintedNavigationKey] = useState<string | null>(null);const suppressed = paintedNavigationKey !== navigationKey;+ // 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.useEffect(() => {if (!suppressed) return;let releaseFrame = 0;@@ -55,6 +56,7 @@ export function usePanelPresence<T>(if (open && !present) setPresent(true);if (!open && !animated && present) setPresent(false);+ // 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.useEffect(() => {if (open || !animated) return;const timeout = window.setTimeout(() => setPresent(false), durationMs);diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.tsindex d2099711180..741f6f3c60c 100644--- a/apps/web/src/remoteOpen.ts+++ b/apps/web/src/remoteOpen.ts@@ -9,7 +9,6 @@ import * as Option from "effect/Option";import * as Schema from "effect/Schema";import { Atom } from "effect/reactivity";import { useAtomValue } from "@effect/atom-react";-import { useEffect, useState } from "react";import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";import { isLoopbackHostname } from "~/environments/primary/target";@@ -147,41 +146,21 @@ export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOconst REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];-let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;--export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {- const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(- () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,+// Probed once per page: installed editors rarely change, and the probe spawns processes.+const remoteCapableEditorsAtom = Atom.make((get): ReadonlyArray<EditorId> => {+ const probe = window.desktopBridge?.probeRemoteEditors;+ probe?.().then(+ (ids) => {+ const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));+ if (remoteCapable.length > 0) get.setSelf(remoteCapable);+ },+ () => undefined,);+ return REMOTE_FALLBACK_EDITORS;+}).pipe(Atom.keepAlive, Atom.withLabel("remote-capable-editors"));- useEffect(() => {- if (cachedProbedEditors !== null) {- return;- }- const probe = window.desktopBridge?.probeRemoteEditors;- if (probe === undefined) {- cachedProbedEditors = REMOTE_FALLBACK_EDITORS;- return;- }- let cancelled = false;- probe().then(- (ids) => {- const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));- cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;- if (!cancelled) {- setEditors(cachedProbedEditors);- }- },- () => {- cachedProbedEditors = REMOTE_FALLBACK_EDITORS;- },- );- return () => {- cancelled = true;- };- }, []);-- return editors;+export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {+ return useAtomValue(remoteCapableEditorsAtom);}/** Resolves false when the desktop refuses the URL, including unsupported editor schemes. */