TypeScript
refactor(web): root notification and toast coordinators start with the app (#25233)
Julius Marminge8a4ad9452a7b
diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsxindex 64f98a87322..3356d51b983 100644--- a/apps/web/src/appInit.tsx+++ b/apps/web/src/appInit.tsx@@ -7,19 +7,29 @@ import { applyAppearanceFontVariables } from "./appearanceFonts";import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";+import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";+import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";+import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";+import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";+import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";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 { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";+import {+ getClientSettings,+ startModelPreferencesMigration,+ subscribeClientSettings,+} from "./hooks/useSettings";import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";import {syncDocumentElectronPlatformClasses,syncDocumentWindowControlsOverlayClass,} from "./lib/windowControlsOverlay";-import { prepareProviderAuthDelivery } from "./providerAuthDelivery";+import { startProviderAuthDelivery } from "./providerAuthDelivery";import { getRouter, type AppRouter } from "./router";import { appAtomRegistry } from "./rpc/atomRegistry";import { primaryServerConfigAtom } from "./state/server";@@ -116,7 +126,7 @@ function startThreadOverlayRetention(router: AppRouter): void {*/export function startAppServices(): AppRouter {// Ahead of the history: the provider auth code must leave the address before anything reads it.- prepareProviderAuthDelivery();+ startProviderAuthDelivery();// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());@@ -128,6 +138,8 @@ export function startAppServices(): AppRouter {startClientAppearance();startDocumentTitle();+ startDefaultThemeAdoption();+ startModelPreferencesMigration();startAgentOpenedPreviews();startThreadOverlayRetention(router);startMainAppLocationTracking(router);@@ -135,5 +147,11 @@ export function startAppServices(): AppRouter {startThreadVisitedMigration(appAtomRegistry);startSshPasswordPromptQueue();+ startHostFreezeToasts();+ startLegacyThreadMigrationToast();+ startPermissionUpdateNotices(router);+ startThreadNotifications(appAtomRegistry, router);+ if (isElectron) startDesktopUpdateLaunchNotice();+return router;}diff --git a/apps/web/src/components/HostFreezeToastCoordinator.ts b/apps/web/src/components/HostFreezeToastCoordinator.tsnew file mode 100644index 00000000000..987be95d7ea--- /dev/null+++ b/apps/web/src/components/HostFreezeToastCoordinator.ts@@ -0,0 +1,33 @@+import { hostFreezeNotice } from "@t3tools/client-runtime/connection";++import { appAtomRegistry } from "../rpc/atomRegistry";+import { environmentSummaries } from "../state/presentation";+import { environmentServerConfigsAtom } from "../state/server";+import { toastManager } from "./ui/toast";++/** Tells the user why a host dropped, once per stall, when it reports one on reconnect. */+export function startHostFreezeToasts(): () => void {+ const shown = new Set<string>();+ return appAtomRegistry.subscribe(+ environmentServerConfigsAtom,+ (configs) => {+ for (const [environmentId, config] of configs) {+ const stall = config.lastEventLoopStall;+ if (stall === undefined) continue;+ const key = `${environmentId}:${stall.detectedAt}`;+ if (shown.has(key)) continue;+ shown.add(key);+ const label =+ appAtomRegistry+ .get(environmentSummaries.identitiesAtom)+ .find((identity) => identity.environmentId === environmentId)?.label ??+ config.environment.label;+ const notice = hostFreezeNotice(label, stall);+ if (notice !== null) {+ toastManager.add({ type: "warning", ...notice });+ }+ }+ },+ { immediate: true },+ );+}diff --git a/apps/web/src/components/HostFreezeToastCoordinator.tsx b/apps/web/src/components/HostFreezeToastCoordinator.tsxdeleted file mode 100644index d04c7344b47..00000000000--- a/apps/web/src/components/HostFreezeToastCoordinator.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import { hostFreezeNotice } from "@t3tools/client-runtime/connection";-import { useEffect, useRef } from "react";--import { environmentSummaries } from "../state/presentation";-import { environmentServerConfigsAtom } from "../state/server";-import { toastManager } from "./ui/toast";--/** Tells the user why a host dropped, once per stall, when it reports one on reconnect. */-export function HostFreezeToastCoordinator() {- const configs = useAtomValue(environmentServerConfigsAtom);- const identities = useAtomValue(environmentSummaries.identitiesAtom);- const shownRef = useRef(new Set<string>());-- useEffect(() => {- for (const [environmentId, config] of configs) {- const stall = config.lastEventLoopStall;- if (stall === undefined) continue;- const key = `${environmentId}:${stall.detectedAt}`;- if (shownRef.current.has(key)) continue;- shownRef.current.add(key);- const label =- identities.find((identity) => identity.environmentId === environmentId)?.label ??- config.environment.label;- const notice = hostFreezeNotice(label, stall);- if (notice !== null) {- toastManager.add({ type: "warning", ...notice });- }- }- }, [configs, identities]);-- return null;-}diff --git a/apps/web/src/components/LegacyThreadMigrationToast.ts b/apps/web/src/components/LegacyThreadMigrationToast.tsnew file mode 100644index 00000000000..3e1e1f7e43d--- /dev/null+++ b/apps/web/src/components/LegacyThreadMigrationToast.ts@@ -0,0 +1,39 @@+import { appAtomRegistry } from "../rpc/atomRegistry";+import { primaryServerLegacyThreadMigrationAtom } from "../state/server";+import { toastManager } from "./ui/toast";++type MigrationToastId = ReturnType<typeof toastManager.add>;++/** A loading toast for as long as the primary server reports a legacy thread migration running. */+export function startLegacyThreadMigrationToast(): () => void {+ let toastId: MigrationToastId | null = null;++ const unsubscribe = appAtomRegistry.subscribe(+ primaryServerLegacyThreadMigrationAtom,+ (migration) => {+ if (migration?.status === "running") {+ if (toastId !== null) return;+ toastId = toastManager.add({+ type: "loading",+ title: "Restoring your threads…",+ description: `Migrating ${migration.totalThreadCount.toLocaleString()} ${+ migration.totalThreadCount === 1 ? "thread" : "threads"+ } from the previous version. You can keep working while this finishes.`,+ timeout: 0,+ });+ return;+ }++ if (toastId !== null) {+ toastManager.close(toastId);+ toastId = null;+ }+ },+ { immediate: true },+ );++ return () => {+ unsubscribe();+ if (toastId !== null) toastManager.close(toastId);+ };+}diff --git a/apps/web/src/components/LegacyThreadMigrationToast.tsx b/apps/web/src/components/LegacyThreadMigrationToast.tsxdeleted file mode 100644index 720e11c429d..00000000000--- a/apps/web/src/components/LegacyThreadMigrationToast.tsx+++ /dev/null@@ -1,45 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import { useEffect, useRef } from "react";--import { primaryServerLegacyThreadMigrationAtom } from "../state/server";-import { toastManager } from "./ui/toast";--type MigrationToastId = ReturnType<typeof toastManager.add>;--export function LegacyThreadMigrationToast() {- const migration = useAtomValue(primaryServerLegacyThreadMigrationAtom);- const toastIdRef = useRef<MigrationToastId | null>(null);-- useEffect(() => {- if (migration?.status === "running") {- if (toastIdRef.current !== null) {- return;- }- toastIdRef.current = toastManager.add({- type: "loading",- title: "Restoring your threads…",- description: `Migrating ${migration.totalThreadCount.toLocaleString()} ${- migration.totalThreadCount === 1 ? "thread" : "threads"- } from the previous version. You can keep working while this finishes.`,- timeout: 0,- });- return;- }-- if (toastIdRef.current !== null) {- toastManager.close(toastIdRef.current);- toastIdRef.current = null;- }- }, [migration]);-- useEffect(- () => () => {- if (toastIdRef.current !== null) {- toastManager.close(toastIdRef.current);- }- },- [],- );-- return null;-}diff --git a/apps/web/src/components/PermissionUpdateNotice.ts b/apps/web/src/components/PermissionUpdateNotice.tsnew file mode 100644index 00000000000..a682adf7fff--- /dev/null+++ b/apps/web/src/components/PermissionUpdateNotice.ts@@ -0,0 +1,83 @@+import { sessionHasLegacyPermissions, type EnvironmentId } from "@t3tools/contracts";+import type { AnyRouter } from "@tanstack/react-router";+import * as Schema from "effect/Schema";+import { Atom } from "effect/reactivity";++import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { environmentSummaries } from "../state/presentation";+import { environmentSession } from "../state/session";+import { toastManager } from "./ui/toast";++interface LegacyPermissionEnvironment {+ readonly environmentId: EnvironmentId;+ readonly label: string;+}++/** Environments whose settled session still carries pre-scope permissions. */+const legacyPermissionEnvironmentsAtom = Atom.make((get) =>+ get(environmentSummaries.identitiesAtom).filter(({ environmentId }) => {+ const session = get(environmentSession.sessionStateAtom(environmentId));+ return (+ session._tag === "Success" && !session.waiting && sessionHasLegacyPermissions(session.value)+ );+ }),+).pipe(Atom.withLabel("web-legacy-permission-environments"));++const dismissalKey = (environmentId: EnvironmentId) =>+ `t3code:permission-update:v1:${environmentId}`;++function showPermissionNotice(+ router: AnyRouter,+ { environmentId, label }: LegacyPermissionEnvironment,+) {+ const key = dismissalKey(environmentId);+ const persistDismissal = () => {+ try {+ setLocalStorageItem(key, true, Schema.Boolean);+ } catch {}+ };+ const dismiss = () => {+ persistDismissal();+ toastManager.close(id);+ };+ const id = toastManager.add({+ title: `Permissions have changed for ${label}`,+ description:+ "This connection still uses the old permissions, so some actions may no longer be available. Pair again using a new link with the permissions you need.",+ timeout: 0,+ onClose: persistDismissal,+ actionProps: {+ children: "Open Connections",+ onClick: () => {+ dismiss();+ void router.navigate({ to: "/settings/connections" });+ },+ },+ data: {+ actionLayout: "stacked-end",+ secondaryActionProps: { children: "Dismiss", onClick: dismiss },+ secondaryActionVariant: "ghost",+ },+ });+}++/** Asks once per environment, until dismissed, to re-pair a connection that predates scoped permissions. */+export function startPermissionUpdateNotices(router: AnyRouter): () => void {+ const shown = new Set<EnvironmentId>();+ return appAtomRegistry.subscribe(+ legacyPermissionEnvironmentsAtom,+ (environments) => {+ for (const environment of environments) {+ if (shown.has(environment.environmentId)) continue;+ try {+ if (getLocalStorageItem(dismissalKey(environment.environmentId), Schema.Boolean))+ continue;+ } catch {}+ shown.add(environment.environmentId);+ showPermissionNotice(router, environment);+ }+ },+ { immediate: true },+ );+}diff --git a/apps/web/src/components/PermissionUpdateNotice.tsx b/apps/web/src/components/PermissionUpdateNotice.tsxdeleted file mode 100644index d1b6756be37..00000000000--- a/apps/web/src/components/PermissionUpdateNotice.tsx+++ /dev/null@@ -1,74 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import { sessionHasLegacyPermissions, type EnvironmentId } from "@t3tools/contracts";-import { useNavigate } from "@tanstack/react-router";-import * as Schema from "effect/Schema";-import { useEffect } from "react";--import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage";-import { useEnvironments } from "../state/environments";-import { environmentSession } from "../state/session";-import { toastManager } from "./ui/toast";--// Keep an active toast across remounts, including Strict Mode effect replay.-const shown = new Set<EnvironmentId>();--function EnvironmentPermissionNotice({- environmentId,- label,-}: {- environmentId: EnvironmentId;- label: string;-}) {- const session = useAtomValue(environmentSession.sessionStateAtom(environmentId));- const navigate = useNavigate();- useEffect(() => {- if (- session._tag !== "Success" ||- session.waiting ||- !sessionHasLegacyPermissions(session.value)- )- return;- if (shown.has(environmentId)) return;- const key = `t3code:permission-update:v1:${environmentId}`;- try {- if (getLocalStorageItem(key, Schema.Boolean)) return;- } catch {}- shown.add(environmentId);- const persistDismissal = () => {- try {- setLocalStorageItem(key, true, Schema.Boolean);- } catch {}- };- const dismiss = () => {- persistDismissal();- toastManager.close(id);- };- const id = toastManager.add({- title: `Permissions have changed for ${label}`,- description:- "This connection still uses the old permissions, so some actions may no longer be available. Pair again using a new link with the permissions you need.",- timeout: 0,- onClose: persistDismissal,- actionProps: {- children: "Open Connections",- onClick: () => {- dismiss();- void navigate({ to: "/settings/connections" });- },- },- data: {- actionLayout: "stacked-end",- secondaryActionProps: { children: "Dismiss", onClick: dismiss },- secondaryActionVariant: "ghost",- },- });- }, [environmentId, label, navigate, session]);- return null;-}--export function PermissionUpdateNotice() {- const { environments } = useEnvironments();- return environments.map(({ environmentId, label }) => (- <EnvironmentPermissionNotice key={environmentId} environmentId={environmentId} label={label} />- ));-}diff --git a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tssimilarity index 80%rename from apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsxrename to apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsindex 70b0d0e3e81..f253dd6be22 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts@@ -1,12 +1,12 @@-import { RegistryContext } from "@effect/atom-react";import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";+import type { AnyRouter } from "@tanstack/react-router";import { EnvironmentId } from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Option from "effect/Option";import { Atom, AtomRegistry } from "effect/reactivity";import { expect, it, vi } from "vite-plus/test";-import { fakeTimers, render, stubGlobal, type Screen } from "../../test/render";+import { fakeTimers, stubGlobal } from "../../test/render";const state = vi.hoisted(() => ({mode: "notifications",@@ -16,12 +16,7 @@ const state = vi.hoisted(() => ({navigate: vi.fn(),sound: vi.fn(),badge: vi.fn(),- environmentIds: ["one", "two"],-}));-vi.mock(import("@tanstack/react-router"), async (original) => ({- ...(await original()),- useNavigate: (() => state.navigate) as never,- useParams: (() => ({})) as never,+ settingsListeners: new Set<() => void>(),}));vi.mock(import("./ui/toast"), async (original) => {const actual = await original();@@ -37,16 +32,29 @@ vi.mock(import("../state/shell"), async (original) => {},};});-vi.mock(import("../state/environments"), async (original) => ({- ...(await original()),- useEnvironmentIds: (() => state.environmentIds) as never,-}));+vi.mock(import("../state/presentation"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ environmentSummaries: {+ ...actual.environmentSummaries,+ // Read lazily: the factory runs before this module's own bindings exist.+ get environmentIdsAtom() {+ return environmentIdsAtom as never;+ },+ },+ };+});vi.mock(import("../hooks/useSettings"), async (original) => ({...(await original()),- useClientSettings: ((- select: (settings: { notificationMode: string; inAppNotificationsEnabled: boolean }) => unknown,- ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp })) as never,- getClientSettings: (() => ({ notificationMode: state.mode })) as never,+ subscribeClientSettings: ((listener: () => void) => {+ state.settingsListeners.add(listener);+ return () => state.settingsListeners.delete(listener);+ }) as never,+ getClientSettings: (() => ({+ notificationMode: state.mode,+ inAppNotificationsEnabled: state.inApp,+ })) as never,}));vi.mock(import("../threadNotifications"), async (original) => ({...(await original()),@@ -55,10 +63,11 @@ vi.mock(import("../threadNotifications"), async (original) => ({setNotificationBadge: state.badge,}));-import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";+import { startThreadNotifications } from "./ThreadNotificationCoordinator";let registry: AtomRegistry.AtomRegistry;const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));+const environmentIdsAtom = Atom.make<ReadonlyArray<string>>([]);state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };class TestNotification extends EventTarget {@@ -155,8 +164,8 @@ function shell(overrides: Partial<typeof thread> = {}, ...others: Partial<typeof}),};}-// The mocked modules read `state`, the registry and the focus flags, so every test starts by-// resetting them. The first render is left to the test because some tests change state first.+// The mocked modules read `state` and the focus flags, so every test resets them before+// starting the service.function setup() {vi.clearAllMocks();const stack = new AsyncDisposableStack();@@ -165,7 +174,8 @@ function setup() {stack.defer(() => testRegistry.dispose());state.mode = "notifications";state.inApp = false;- state.environmentIds = ["one", "two"];+ state.settingsListeners.clear();+ registry.set(environmentIdsAtom, ["one", "two"]);state.shells.set("one", shell());state.shells.set("two", shell());focused = false;@@ -180,19 +190,18 @@ function setup() {.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility as DocumentVisibilityState),);- const ui = () => (- <RegistryContext.Provider value={testRegistry}>- <ThreadNotificationCoordinator />- </RegistryContext.Provider>- );- let screen: Screen | undefined;+ const router = {+ state: { matches: [{ params: {} }] },+ navigate: state.navigate,+ } as unknown as AnyRouter;return {- ui,- async render() {- if (screen) await screen.rerender(ui());- else screen = stack.use(await render(ui()));+ start: () => {+ stack.defer(startThreadNotifications(testRegistry, router));+ },+ setEnvironmentIds: (ids: ReadonlyArray<string>) => testRegistry.set(environmentIdsAtom, ids),+ changeSettings: () => {+ for (const listener of state.settingsListeners) listener();},- unmount: () => screen!.unmount(),[Symbol.asyncDispose]: () => stack.disposeAsync(),};}@@ -201,9 +210,8 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)("badges %s and clears when notifications are disabled",async (flag) => {await using app = setup();- await app.render();+ app.start();state.shells.set("one", shell({ [flag]: true }));- await app.render();expect(state.badge).toHaveBeenLastCalledWith(1);const notification = TestNotification.sent[0]!;notification.dispatchEvent(new Event("click"));@@ -212,7 +220,7 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },});state.mode = "sound";- await app.render();+ app.changeSettings();expect(state.badge).toHaveBeenLastCalledWith(0);expect(notification.close).toHaveBeenCalled();},@@ -220,20 +228,17 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(it("holds a completion through a continuation gap and notifies once it settles", async () => {await using app = setup();- await app.render();+ app.start();using _timers = fakeTimers();const finished = (turnId: string, completedAt: string) => ({latestTurn: { turnId, state: "completed", completedAt },});state.shells.set("one", shell(finished("turn-1", "2026-09-13T07:00:01.000Z")));- await app.render();state.shells.set("one",shell({ latestTurn: { turnId: "turn-2", state: "running", completedAt: null } }),);- await app.render();state.shells.set("one", shell(finished("turn-2", "2026-09-13T07:00:02.000Z")));- await app.render();expect(TestNotification.sent).toEqual([]);await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS - 1);expect(TestNotification.sent).toEqual([]);diff --git a/apps/web/src/components/ThreadNotificationCoordinator.tsx b/apps/web/src/components/ThreadNotificationCoordinator.tsxindex b6b6b119947..a782e24da65 100644--- a/apps/web/src/components/ThreadNotificationCoordinator.tsx+++ b/apps/web/src/components/ThreadNotificationCoordinator.tsx@@ -4,21 +4,21 @@ import {presentThreadShell,} from "@t3tools/client-runtime/state/models";import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads";-import { useAtomValue } from "@effect/atom-react";-import { useNavigate, useParams } from "@tanstack/react-router";+import type { AnyRouter } from "@tanstack/react-router";import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";+import type { ClientSettings } from "@t3tools/contracts/settings";import * as Option from "effect/Option";+import type { AtomRegistry } from "effect/reactivity";import {CircleAlertIcon,CircleCheckIcon,MessageCircleQuestionIcon,ShieldQuestionIcon,} from "lucide-react";-import { useEffect, useEffectEvent, useRef } from "react";-import { getClientSettings, useClientSettings } from "../hooks/useSettings";+import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings";import { isWindowsPlatform } from "../lib/utils";-import { useEnvironmentIds } from "../state/environments";+import { environmentSummaries } from "../state/presentation";import { environmentShell } from "../state/shell";import {hasDesktopNotifications,@@ -36,70 +36,6 @@ import {} from "./ThreadNotificationCoordinator.logic";import { toastManager } from "./ui/toast";-export function ThreadNotificationCoordinator() {- const environmentIds = useEnvironmentIds();- const mode = useClientSettings((settings) => settings.notificationMode);- const inAppNotificationsEnabled = useClientSettings(- (settings) => settings.inAppNotificationsEnabled,- );- const pending = useRef(- new Map<string, { environmentId: EnvironmentId; notification: Notification }>(),- );- const onNotification = (environmentId: EnvironmentId, notification: Notification) => {- pending.current.get(notification.tag)?.notification.close();- pending.current.set(notification.tag, { environmentId, notification });- setNotificationBadge(pending.current.size);- };-- useEffect(() => {- const activeIds = new Set(environmentIds);- const count = pending.current.size;- for (const [tag, entry] of pending.current) {- if (activeIds.has(entry.environmentId)) continue;- entry.notification.close();- pending.current.delete(tag);- }- if (count !== pending.current.size) setNotificationBadge(pending.current.size);- }, [environmentIds]);-- useEffect(() => {- const clear = () => {- for (const { notification } of pending.current.values()) notification.close();- pending.current.clear();- setNotificationBadge(0);- };- clear();- if (!hasDesktopNotifications(mode)) return;- const unsubscribe = window.desktopBridge?.onNotificationBadgeClear?.(clear);- window.addEventListener("focus", clear);- return () => {- unsubscribe?.();- window.removeEventListener("focus", clear);- clear();- };- }, [mode]);-- useEffect(() => {- if (!hasNotificationSound(mode)) return;- document.addEventListener("pointerdown", unlockNotificationAudio);- document.addEventListener("keydown", unlockNotificationAudio);- return () => {- document.removeEventListener("pointerdown", unlockNotificationAudio);- document.removeEventListener("keydown", unlockNotificationAudio);- };- }, [mode]);-- if (mode === "off" && !inAppNotificationsEnabled) return null;-- return environmentIds.map((environmentId) => (- <EnvironmentNotifications- key={environmentId}- environmentId={environmentId}- onNotification={onNotification}- />- ));-}-interface NotificationState extends ThreadNotificationObservation {readonly raw: OrchestrationV2ThreadShell;readonly subagentRequest: PendingSubagentRequest | null;@@ -107,31 +43,46 @@ interface NotificationState extends ThreadNotificationObservation {readonly status: SidebarThreadStatus;}-function EnvironmentNotifications({- environmentId,- onNotification,-}: {- environmentId: EnvironmentId;- onNotification: (environmentId: EnvironmentId, notification: Notification) => void;-}) {- const shell = useAtomValue(environmentShell.stateValueAtom(environmentId));- const threads =- shell.status === "live" && Option.isSome(shell.snapshot) ? shell.snapshot.value.threads : null;- const mode = useClientSettings((settings) => settings.notificationMode);- const inAppNotificationsEnabled = useClientSettings(- (settings) => settings.inAppNotificationsEnabled,- );- const navigate = useNavigate();- const { environmentId: activeEnvironmentId, threadId: activeThreadId } = useParams({- strict: false,- });- const previous = useRef(new Map<ThreadId, NotificationState>());+interface WatchedEnvironment {+ unsubscribe: () => void;+ previous: Map<ThreadId, NotificationState>;+ readonly gate: ReturnType<typeof createThreadNotificationGate<ThreadId>>;+}++/**+ * Turns thread status transitions in every connected environment into sounds, in-app toasts,+ * and desktop notifications, and keeps the dock badge in step with the unread ones.+ */+export function startThreadNotifications(+ registry: AtomRegistry.AtomRegistry,+ router: AnyRouter,+): () => void {+ const pending = new Map<string, { environmentId: EnvironmentId; notification: Notification }>();+ const watched = new Map<EnvironmentId, WatchedEnvironment>();++ const trackNotification = (environmentId: EnvironmentId, notification: Notification) => {+ pending.get(notification.tag)?.notification.close();+ pending.set(notification.tag, { environmentId, notification });+ setNotificationBadge(pending.size);+ };+ const clearPending = () => {+ for (const { notification } of pending.values()) notification.close();+ pending.clear();+ setNotificationBadge(0);+ };// Completions fire from a timer, so read settings, focus and route when presenting.- const present = useEffectEvent((threadId: ThreadId, kind: ThreadNotificationKind) => {- const entry = previous.current.get(threadId);- if (!entry) return;- const { thread, status } = entry;+ const present = (+ environmentId: EnvironmentId,+ state: NotificationState,+ kind: ThreadNotificationKind,+ ) => {+ const { thread, status } = state;+ const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings();+ const active = (router.state.matches.at(-1)?.params ?? {}) as {+ environmentId?: string;+ threadId?: string;+ };const title =kind === "completion"? "Thread completed"@@ -153,7 +104,7 @@ function EnvironmentNotifications({inAppNotificationsEnabled &&document.visibilityState === "visible" &&document.hasFocus() &&- (activeEnvironmentId !== environmentId || activeThreadId !== thread.id)+ (active.environmentId !== environmentId || active.threadId !== thread.id)) {const toastId = toastManager.add({type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",@@ -176,7 +127,7 @@ function EnvironmentNotifications({children: "Open thread",onClick: () => {toastManager.close(toastId);- void navigate({+ void router.navigate({to: "/$environmentId/$threadId",params: { environmentId, threadId: thread.id },});@@ -200,12 +151,12 @@ function EnvironmentNotifications({// Windows drops clicks after a toast moves into Notification Center.requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform),});- onNotification(environmentId, notification);+ trackNotification(environmentId, notification);notification.addEventListener("click", () => {notification.close();window.focus();void window.desktopBridge?.revealWindow?.().catch(() => undefined);- void navigate({+ void router.navigate({to: "/$environmentId/$threadId",params: { environmentId, threadId: thread.id },});@@ -213,35 +164,20 @@ function EnvironmentNotifications({} catch {// Some browsers expose Notification but reject desktop presentation.}- });- const gate = useRef<ReturnType<typeof createThreadNotificationGate<ThreadId>>>(null);- useEffect(() => {- const created = createThreadNotificationGate<ThreadId>((threadId, kind) =>- present(threadId, kind),- );- gate.current = created;- return () => {- created.clear();- gate.current = null;- // A new gate has no pending completions, so forget the states they compared against.- previous.current.clear();- };- }, []);+ };- useEffect(() => {- const pendingCompletions = gate.current;- if (!pendingCompletions) return;- if (threads === null) {- pendingCompletions.clear();- previous.current.clear();- return;- }+ const observeThreads = (+ environmentId: EnvironmentId,+ entry: WatchedEnvironment,+ threads: ReadonlyArray<OrchestrationV2ThreadShell>,+ ) => {+ const previous = entry.previous;const next = new Map<ThreadId, NotificationState>();const subagentRequests = pendingSubagentRequestsByThread(threads);const changed: Array<[NotificationState | undefined, NotificationState]> = [];for (const rawThread of threads) {if (rawThread.lineage.relationshipToParent === "subagent") continue;- const prior = previous.current.get(rawThread.id);+ const prior = previous.get(rawThread.id);const subagentRequest = subagentRequests.get(rawThread.id) ?? null;if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) {next.set(rawThread.id, prior);@@ -272,15 +208,125 @@ function EnvironmentNotifications({next.set(thread.id, state);changed.push([prior, state]);}- previous.current = next;- pendingCompletions.retain(new Set(next.keys()));+ entry.previous = next;+ entry.gate.retain(new Set(next.keys()));for (const [prior, state] of changed) {- pendingCompletions.observe(state.thread.id, prior, state, {+ entry.gate.observe(state.thread.id, prior, state, {archived: state.thread.archivedAt !== null,quiet: state.raw.latestRunStopRequested === true,});}- }, [environmentId, threads]);+ };++ const watchEnvironment = (environmentId: EnvironmentId): WatchedEnvironment => {+ const entry: WatchedEnvironment = {+ previous: new Map(),+ unsubscribe: () => {},+ gate: createThreadNotificationGate<ThreadId>((threadId, kind) => {+ const state = entry.previous.get(threadId);+ if (state) present(environmentId, state, kind);+ }),+ };+ const unsubscribeShell = registry.subscribe(+ environmentShell.stateValueAtom(environmentId),+ (shell) => {+ const threads =+ shell.status === "live" && Option.isSome(shell.snapshot)+ ? shell.snapshot.value.threads+ : null;+ if (threads !== null) {+ observeThreads(environmentId, entry, threads);+ return;+ }+ entry.gate.clear();+ entry.previous = new Map();+ },+ { immediate: true },+ );+ entry.unsubscribe = () => {+ unsubscribeShell();+ entry.gate.clear();+ };+ return entry;+ };++ const syncEnvironments = () => {+ const { notificationMode, inAppNotificationsEnabled } = getClientSettings();+ const enabled = notificationMode !== "off" || inAppNotificationsEnabled;+ const environmentIds = enabled ? registry.get(environmentSummaries.environmentIdsAtom) : [];+ const activeIds = new Set(environmentIds);+ for (const [environmentId, entry] of watched) {+ if (activeIds.has(environmentId)) continue;+ entry.unsubscribe();+ watched.delete(environmentId);+ }+ for (const environmentId of environmentIds) {+ if (!watched.has(environmentId)) watched.set(environmentId, watchEnvironment(environmentId));+ }+ };++ const pruneRemovedEnvironments = () => {+ const activeIds = new Set(registry.get(environmentSummaries.environmentIdsAtom));+ const count = pending.size;+ for (const [tag, entry] of pending) {+ if (activeIds.has(entry.environmentId)) continue;+ entry.notification.close();+ pending.delete(tag);+ }+ if (count !== pending.size) setNotificationBadge(pending.size);+ };++ // Listeners that only exist for some notification modes, rebuilt when the mode changes.+ let appliedMode: ClientSettings["notificationMode"] | null = null;+ let stopModeListeners = () => {};+ const applyMode = () => {+ const nextMode = getClientSettings().notificationMode;+ if (nextMode === appliedMode) return;+ appliedMode = nextMode;+ stopModeListeners();+ clearPending();+ const stops: Array<() => void> = [];+ if (hasDesktopNotifications(nextMode)) {+ const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear?.(clearPending);+ window.addEventListener("focus", clearPending);+ stops.push(() => {+ unsubscribeBadgeClear?.();+ window.removeEventListener("focus", clearPending);+ clearPending();+ });+ }+ if (hasNotificationSound(nextMode)) {+ document.addEventListener("pointerdown", unlockNotificationAudio);+ document.addEventListener("keydown", unlockNotificationAudio);+ stops.push(() => {+ document.removeEventListener("pointerdown", unlockNotificationAudio);+ document.removeEventListener("keydown", unlockNotificationAudio);+ });+ }+ stopModeListeners = () => {+ for (const stop of stops) stop();+ };+ };- return null;+ const onSettings = () => {+ applyMode();+ syncEnvironments();+ };+ const unsubscribeSettings = subscribeClientSettings(onSettings);+ const unsubscribeEnvironmentIds = registry.subscribe(+ environmentSummaries.environmentIdsAtom,+ () => {+ pruneRemovedEnvironments();+ syncEnvironments();+ },+ );+ onSettings();++ return () => {+ unsubscribeSettings();+ unsubscribeEnvironmentIds();+ for (const entry of watched.values()) entry.unsubscribe();+ watched.clear();+ stopModeListeners();+ };}diff --git a/apps/web/src/components/settings/ProviderAuthCallbackCoordinator.tsx b/apps/web/src/components/settings/ProviderAuthCallbackCoordinator.tsxdeleted file mode 100644index a4cf60b60cd..00000000000--- a/apps/web/src/components/settings/ProviderAuthCallbackCoordinator.tsx+++ /dev/null@@ -1,50 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { pendingProviderAuthDelivery, clearProviderAuthDelivery } from "../../providerAuthDelivery";-import { serverEnvironment } from "../../state/server";-import { useEnvironments } from "../../state/environments";-import { useAtomCommand } from "../../state/use-atom-command";-import { toastManager } from "../ui/toast";--/** Hosted web receives only the one-time code; the selected environment verifies and stores tokens. */-export function ProviderAuthCallbackCoordinator() {- const completeAuth = useAtomCommand(serverEnvironment.completeProviderAuth, {- reportFailure: false,- });- const { environments } = useEnvironments();- const [delivery, setDelivery] = useState(pendingProviderAuthDelivery);- const started = useRef(false);- const environmentId = delivery?.environmentId;- const connected = environments.some(- (environment) =>- environment.environmentId === environmentId && environment.connection.phase === "connected",- );- useEffect(() => {- const input = delivery;- if (!input || started.current || !connected) return;- started.current = true;- void completeAuth({- environmentId: input.environmentId,- input: { instanceId: input.instanceId, flowId: input.flowId, callbackUrl: input.callbackUrl },- })- .then((result) => {- if (result._tag === "Failure")- toastManager.add({- type: "error",- title: "ChatGPT sign-in couldn't finish",- description: "Return to the provider and try again.",- });- })- .catch(() =>- toastManager.add({- type: "error",- title: "ChatGPT sign-in couldn't finish",- description: "Reconnect to the environment and try again.",- }),- )- .finally(() => {- setDelivery(undefined);- clearProviderAuthDelivery();- });- }, [completeAuth, connected, delivery]);- return null;-}diff --git a/apps/web/src/components/settings/useScopedSettings.ts b/apps/web/src/components/settings/useScopedSettings.tsindex 9561cfc234a..1254ac4ea8b 100644--- a/apps/web/src/components/settings/useScopedSettings.ts+++ b/apps/web/src/components/settings/useScopedSettings.ts@@ -14,11 +14,7 @@ import {type UnifiedSettings,} from "@t3tools/contracts";-import {- persistClientSettingsPatch,- useMergedSettings,- useMigrateModelPreferences,-} from "../../hooks/useSettings";+import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";import { serverEnvironment } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";import { toastManager } from "../ui/toast";@@ -38,7 +34,6 @@ export function useScopedSettings<T = UnifiedSettings>(selector?: (settings: UnifiedSettings) => T,): T {const { target } = useSettingsScope();- useMigrateModelPreferences(target?.environmentId ?? null, target?.settings ?? null);return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);}diff --git a/apps/web/src/components/sidebar/updateEverythingRun.tsx b/apps/web/src/components/sidebar/updateEverythingRun.tsxindex b53226d4739..82f42a055f0 100644--- a/apps/web/src/components/sidebar/updateEverythingRun.tsx+++ b/apps/web/src/components/sidebar/updateEverythingRun.tsx@@ -2,12 +2,11 @@ import { useAtomValue } from "@effect/atom-react";import { EnvironmentId } from "@t3tools/contracts";import * as Option from "effect/Option";import * as Schema from "effect/Schema";-import { Atom } from "effect/reactivity";-import { useEffect } from "react";+import { AsyncResult, Atom } from "effect/reactivity";import { APP_VERSION } from "~/branding";import { appAtomRegistry } from "~/rpc/atomRegistry";-import { useDesktopUpdateState } from "~/state/desktopUpdate";+import { desktopUpdateStateAtom } from "~/state/desktopUpdate";import { serverEnvironment } from "~/state/server";import { resolveVersionMismatch } from "~/versionSkew";import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";@@ -307,30 +306,31 @@ function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {}}-let notifiedNotAppliedVersion: string | null = null;--export function DesktopUpdateLaunchNotice() {- const notAppliedVersion = useDesktopUpdateState()?.notAppliedVersion ?? null;-- useEffect(() => {- const saved = takeSavedUpdateEverythingResult();- if (!saved) return;+/** Reports, once per launch, how the update run that restarted the app ended. */+export function startDesktopUpdateLaunchNotice(): () => void {+ const saved = takeSavedUpdateEverythingResult();+ if (saved) {const handedOff = saved.handedOff ?? [];showUpdateEverythingResult({ ...saved, restarting: handedOff.map((server) => server.label) });followHandedOffServers(handedOff);- }, []);-- useEffect(() => {- if (notAppliedVersion === null || notifiedNotAppliedVersion === notAppliedVersion) return;- notifiedNotAppliedVersion = notAppliedVersion;- toastManager.add(- stackedThreadToast({- type: "error",- title: "Update did not apply",- description: `T3 Code is still on ${APP_VERSION}. Install ${notAppliedVersion} again from the update button.`,- }),- );- }, [notAppliedVersion]);+ }- return null;+ let notifiedNotAppliedVersion: string | null = null;+ return appAtomRegistry.subscribe(+ desktopUpdateStateAtom,+ (result) => {+ const notAppliedVersion =+ AsyncResult.getOrElse(result, () => null)?.notAppliedVersion ?? null;+ if (notAppliedVersion === null || notifiedNotAppliedVersion === notAppliedVersion) return;+ notifiedNotAppliedVersion = notAppliedVersion;+ toastManager.add(+ stackedThreadToast({+ type: "error",+ title: "Update did not apply",+ description: `T3 Code is still on ${APP_VERSION}. Install ${notAppliedVersion} again from the update button.`,+ }),+ );+ },+ { immediate: true },+ );}diff --git a/apps/web/src/components/ui/toast.browser.test.tsx b/apps/web/src/components/ui/toast.browser.test.tsxnew file mode 100644index 00000000000..d826ab6bdc4--- /dev/null+++ b/apps/web/src/components/ui/toast.browser.test.tsx@@ -0,0 +1,15 @@+import { describe, expect, it } from "vite-plus/test";+import { page } from "vite-plus/test/browser";++import { render } from "../../../test/render";+import { ToastProvider, toastManager } from "./toast";++describe("toastManager", () => {+ it("shows a toast added before any provider mounted", async () => {+ toastManager.add({ type: "info", title: "Raised before the first render" });++ await using _screen = await render(<ToastProvider>{null}</ToastProvider>);++ await expect.element(page.getByText("Raised before the first render")).toBeVisible();+ });+});diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsxindex 025ff357906..e476b308fc4 100644--- a/apps/web/src/components/ui/toast.tsx+++ b/apps/web/src/components/ui/toast.tsx@@ -62,8 +62,40 @@ export type ThreadToastData = {| "secondary";};-const toastManager = Toast.createToastManager<ThreadToastData>();-const anchoredToastManager = Toast.createToastManager<ThreadToastData>();+type BaseToastManager = ReturnType<typeof Toast.createToastManager<ThreadToastData>>;+type ToastManagerListener = Parameters<BaseToastManager[" subscribe"]>[0];+type ToastManagerEvent = Parameters<ToastManagerListener>[0];++/**+ * base-ui's manager drops events while no provider is subscribed. App services raise toasts+ * from before the first render (and while the root error view replaces the providers), so hold+ * those until a provider listens.+ */+function createBufferedToastManager(): BaseToastManager {+ const manager = Toast.createToastManager<ThreadToastData>();+ const listeners = new Set<ToastManagerListener>();+ const pending: ToastManagerEvent[] = [];+ manager[" subscribe"]((event) => {+ if (listeners.size === 0) {+ pending.push(event);+ return;+ }+ for (const listener of listeners) listener(event);+ });+ return {+ ...manager,+ " subscribe"(listener) {+ listeners.add(listener);+ for (const event of pending.splice(0)) listener(event);+ return () => {+ listeners.delete(listener);+ };+ },+ };+}++const toastManager = createBufferedToastManager();+const anchoredToastManager = createBufferedToastManager();type ToastId = ReturnType<typeof toastManager.add>;const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();diff --git a/apps/web/src/hooks/useDefaultTheme.ts b/apps/web/src/hooks/useDefaultTheme.tsindex 3b4ad04cdfe..5731da6eb53 100644--- a/apps/web/src/hooks/useDefaultTheme.ts+++ b/apps/web/src/hooks/useDefaultTheme.ts@@ -1,10 +1,8 @@-import { useAtomValue } from "@effect/atom-react";-import { useEffect, useSyncExternalStore } from "react";-+import { appAtomRegistry } from "../rpc/atomRegistry";import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";import { primaryServerSettingsAtom } from "../state/server";import { getThemeDefinition, singleAppearanceOf, subscribeToCustomThemes } from "../themePalette";-import { useTheme } from "./useTheme";+import { setAppearanceMode, setTheme } from "./useTheme";const APPLIED_DEFAULT_THEME_STORAGE_PREFIX = "t3code:default-theme-applied:v2:";@@ -23,7 +21,9 @@ export function defaultThemeToApply(input: {if (input.environmentId === null || input.defaultTheme.length === 0) return null;const generation = defaultThemeGeneration(input.defaultTheme, input.defaultThemeSetAt);if (input.appliedGeneration === generation) return null;- // Settings and palettes arrive independently; an unresolved theme must retry when palettes arrive.+ // The setting and the palette it names arrive independently, so an id that+ // does not resolve yet is not a failure -- adoption re-checks when the+ // published set changes.if (!input.resolves) return null;return generation;}@@ -43,34 +43,44 @@ function writeAppliedGeneration(storageKey: string, generation: string): void {} catch {}}-export function useDefaultThemeAdoption(): void {- const environmentId = useAtomValue(primaryEnvironmentIdAtom);- const settings = useAtomValue(primaryServerSettingsAtom);- const { defaultTheme, defaultThemeSetAt } = settings;- const { setTheme, setAppearanceMode } = useTheme();- const definition = useSyncExternalStore(- subscribeToCustomThemes,- () => getThemeDefinition(defaultTheme),- () => null,- );+function adoptDefaultTheme(): void {+ if (typeof window === "undefined") return;+ const environmentId = appAtomRegistry.get(primaryEnvironmentIdAtom);+ if (environmentId === null) return;+ const { defaultTheme, defaultThemeSetAt } = appAtomRegistry.get(primaryServerSettingsAtom);+ const definition = getThemeDefinition(defaultTheme);+ const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;+ const generation = defaultThemeToApply({+ environmentId,+ defaultTheme,+ defaultThemeSetAt,+ appliedGeneration: readAppliedGeneration(storageKey),+ resolves: definition !== null,+ });+ if (generation === null || definition === null) return;- useEffect(() => {- if (typeof window === "undefined" || environmentId === null) return;- const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;- const generation = defaultThemeToApply({- environmentId,- defaultTheme,- defaultThemeSetAt,- appliedGeneration: readAppliedGeneration(storageKey),- resolves: definition !== null,- });- if (generation === null || definition === null) return;+ // A single-appearance theme needs both preference and appearance writes to take effect.+ if (!setTheme(defaultTheme)) return;+ const half = singleAppearanceOf(definition);+ // Only record adoption after both writes succeed, so an appearance failure remains retryable.+ if (half !== null && !setAppearanceMode(half)) return;+ writeAppliedGeneration(storageKey, generation);+}- // A single-appearance theme needs both preference and appearance writes to take effect.- if (!setTheme(defaultTheme)) return;- const half = singleAppearanceOf(definition);- // Only record adoption after both writes succeed, so an appearance failure remains retryable.- if (half !== null && !setAppearanceMode(half)) return;- writeAppliedGeneration(storageKey, generation);- }, [environmentId, defaultTheme, defaultThemeSetAt, definition, setTheme, setAppearanceMode]);+/**+ * Applies the primary environment's default theme once per generation. Start it after the+ * environment theme sync so a first-run client adopting the environment's own theme finds it+ * already in the library; it re-checks when published or custom palettes change, so a theme+ * that resolves late still applies.+ */+export function startDefaultThemeAdoption(): () => void {+ const unsubscribes = [+ appAtomRegistry.subscribe(primaryEnvironmentIdAtom, adoptDefaultTheme),+ appAtomRegistry.subscribe(primaryServerSettingsAtom, adoptDefaultTheme),+ subscribeToCustomThemes(adoptDefaultTheme),+ ];+ adoptDefaultTheme();+ return () => {+ for (const unsubscribe of unsubscribes) unsubscribe();+ };}diff --git a/apps/web/src/hooks/useSettings.favorites.browser.test.tsx b/apps/web/src/hooks/useSettings.favorites.browser.test.tsxindex 4e413a76314..434123191db 100644--- a/apps/web/src/hooks/useSettings.favorites.browser.test.tsx+++ b/apps/web/src/hooks/useSettings.favorites.browser.test.tsx@@ -19,6 +19,10 @@ import { describe, expect, it, vi } from "vite-plus/test";import { act, render, type Screen } from "../../test/render";const state = vi.hoisted(() => ({+ catalog: null as unknown as Atom.Writable<{+ readonly isReady: boolean;+ readonly entries: ReadonlyMap<string, unknown>;+ }>,settings: new Map<string, unknown>(),connections: new Map<EnvironmentId,@@ -29,10 +33,18 @@ const state = vi.hoisted(() => ({vi.mock(import("~/connection/catalog"), async (original) => {const actual = await original();+ const { Atom } = await import("effect/reactivity");+ state.catalog = Atom.keepAlive(+ Atom.make<{ readonly isReady: boolean; readonly entries: ReadonlyMap<string, unknown> }>({+ isReady: true,+ entries: new Map(),+ }),+ );return {...actual,environmentCatalog: {...actual.environmentCatalog,+ catalogValueAtom: state.catalog as never,stateAtom: ((id: EnvironmentId) => state.connections.get(id)) as never,},};@@ -52,6 +64,10 @@ vi.mock(import("~/state/server"), async (original) => {serverEnvironment: {...actual.serverEnvironment,settingsValueAtom: ((id: EnvironmentId) => state.settings.get(id)) as never,+ updateSettings: {+ ...actual.serverEnvironment.updateSettings,+ run: (_registry: unknown, input: unknown) => state.persist(input),+ } as never,},};});@@ -60,7 +76,12 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({useAtomCommand: (() => state.persist) as never,}));-import { useEnvironmentModelPreferences, useToggleEnvironmentModelFavorite } from "./useSettings";+import { appAtomRegistry } from "~/rpc/atomRegistry";+import {+ ensureClientSettingsHydrated,+ startModelPreferencesMigration,+ useToggleEnvironmentModelFavorite,+} from "./useSettings";const primaryId = EnvironmentId.make("primary");const remoteId = EnvironmentId.make("remote");@@ -242,17 +263,11 @@ describe("environment favorite toggles", () => {});});-function ModelPreferencesReader({ environmentId }: { environmentId: EnvironmentId }) {- useEnvironmentModelPreferences(environmentId);- return null;-}-describe("legacy model preferences migration", () => {it.each(["succeeds", "fails"] as const)("waits for connection and retries only after reconnect when the first save %s",async (outcome) => {- await using fixture = await setup();- const { registry, show } = fixture;+ await using _fixture = await setup();const environmentId = EnvironmentId.make(`migration-${outcome}`);const otherId = EnvironmentId.make(`other-${outcome}`);for (const id of [environmentId, otherId]) {@@ -281,59 +296,58 @@ describe("legacy model preferences migration", () => {state.persist.mockReturnValueOnce(firstSave).mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));- const renderReader = (id = environmentId) =>- show(<ModelPreferencesReader key={id} environmentId={id} />);const connect = (id: EnvironmentId, generation: number) =>- act(() =>- registry.set(- state.connections.get(id)!,- AsyncResult.success({- ...AVAILABLE_CONNECTION_STATE,- desired: true,- generation,- phase: "connected",- }),- ),+ appAtomRegistry.set(+ state.connections.get(id)!,+ AsyncResult.success({+ ...AVAILABLE_CONNECTION_STATE,+ desired: true,+ generation,+ phase: "connected",+ }),);const pushSettings = (id = environmentId) =>- act(() => registry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS }));+ appAtomRegistry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS });const migration = (id: EnvironmentId) => ({environmentId: id,input: { patch: { migrateModelPreferences: { favorites: [{ provider, model }] } } },});- await renderReader();- await pushSettings();+ appAtomRegistry.set(state.catalog, {+ isReady: true,+ entries: new Map([+ [environmentId, {}],+ [otherId, {}],+ ]),+ });+ using _migration = { [Symbol.dispose]: startModelPreferencesMigration() };+ await ensureClientSettingsHydrated();+ pushSettings();expect(state.persist).not.toHaveBeenCalled();- await connect(environmentId, 1);+ connect(environmentId, 1);expect(state.persist).toHaveBeenCalledExactlyOnceWith(migration(environmentId));- await pushSettings();+ pushSettings();expect(state.persist).toHaveBeenCalledTimes(1);- await act(finishFirstSave);- await pushSettings();- await pushSettings();+ finishFirstSave();+ await firstSave;+ pushSettings();+ pushSettings();expect(state.persist).toHaveBeenCalledTimes(1);- await connect(otherId, 7);- await pushSettings(otherId);- expect(state.persist).toHaveBeenCalledTimes(1);- await renderReader(otherId);+ connect(otherId, 7);expect(state.persist).toHaveBeenLastCalledWith(migration(otherId));- await renderReader();- await pushSettings();+ pushSettings(otherId);expect(state.persist).toHaveBeenCalledTimes(2);- await act(() =>- registry.set(- state.connections.get(environmentId)!,- AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }),- ),+ appAtomRegistry.set(+ state.connections.get(environmentId)!,+ AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }),);- await pushSettings();+ pushSettings();expect(state.persist).toHaveBeenCalledTimes(2);- await connect(environmentId, 2);- await pushSettings();+ connect(environmentId, 2);+ pushSettings();expect(state.persist.mock.calls).toEqual([[migration(environmentId)],[migration(otherId)],diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.tsindex 0c30b6b7c84..c349b692c41 100644--- a/apps/web/src/hooks/useSettings.ts+++ b/apps/web/src/hooks/useSettings.ts@@ -1,4 +1,4 @@-import { useEffect, useRef, useSyncExternalStore, use } from "react";+import { useRef, useSyncExternalStore, use } from "react";import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector";import { RegistryContext, useAtomValue } from "@effect/atom-react";import {@@ -22,6 +22,7 @@ import {import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";import {isAtomCommandInterrupted,+ runAtomCommand,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import {@@ -313,46 +314,59 @@ export function mergeEnvironmentSettings(};}-// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.-const attemptedMigrationGenerations = new Map<EnvironmentId, number>();-const connectionGenerationAtom = Atom.family((environmentId: EnvironmentId | null) =>- Atom.make((get) =>- environmentId === null- ? null- : Option.match(AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), {- onNone: () => null,- onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),- }),- ),-);-const selectLegacyModelPreferences = (settings: ClientSettings) => ({favorites: settings.favorites,providerModelPreferences: settings.providerModelPreferences,});-export function useMigrateModelPreferences(- environmentId: EnvironmentId | null,- settings: ServerSettings | null,-) {- const clientSettings = useClientSettings(selectLegacyModelPreferences);- const hydrated = useClientSettingsHydrated();- const connectionGeneration = useAtomValue(connectionGenerationAtom(environmentId));- const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });- useEffect(() => {- if (- !environmentId ||- !settings ||- !hydrated ||- connectionGeneration === null ||- attemptedMigrationGenerations.get(environmentId) === connectionGeneration- )- return;- const patch = modelPreferencesMigrationPatch(settings, clientSettings);- if (!patch) return;- attemptedMigrationGenerations.set(environmentId, connectionGeneration);- void migrate({ environmentId, input: { patch } });- }, [clientSettings, connectionGeneration, environmentId, hydrated, migrate, settings]);+// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.+const attemptedMigrationGenerations = new Map<EnvironmentId, number>();++const modelPreferencesMigrationTargetsAtom = Atom.make((get) =>+ [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => {+ const generation = Option.match(+ AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),+ {+ onNone: () => null,+ onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),+ },+ );+ const settings = get(serverEnvironment.settingsValueAtom(environmentId));+ return generation === null || settings === null+ ? []+ : [{ environmentId, generation, settings }];+ }),+).pipe(Atom.withLabel("web-model-preferences-migration-targets"));++function migrateModelPreferences(): void {+ if (clientSettingsHydrationStatus !== "ready") return;+ for (const { environmentId, generation, settings } of appAtomRegistry.get(+ modelPreferencesMigrationTargetsAtom,+ )) {+ if (attemptedMigrationGenerations.get(environmentId) === generation) continue;+ const patch = modelPreferencesMigrationPatch(settings, clientSettingsSnapshot);+ if (!patch) continue;+ attemptedMigrationGenerations.set(environmentId, generation);+ void runAtomCommand(+ appAtomRegistry,+ serverEnvironment.updateSettings,+ { environmentId, input: { patch } },+ { reportFailure: false },+ );+ }+}++/** Moves this client's legacy model preferences onto each server, once per connection. */+export function startModelPreferencesMigration(): () => void {+ const unsubscribes = [+ appAtomRegistry.subscribe(modelPreferencesMigrationTargetsAtom, migrateModelPreferences),+ subscribeClientSettings(migrateModelPreferences),+ subscribeClientSettingsHydration(migrateModelPreferences),+ ];+ migrateModelPreferences();+ return () => {+ for (const unsubscribe of unsubscribes) unsubscribe();+ };}export function useMergedSettings<T = UnifiedSettings>(@@ -505,7 +519,6 @@ export function useEnvironmentModelPreferences(environmentId: EnvironmentId | nuenvironmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,);const legacy = useClientSettings(selectLegacyModelPreferences);- useMigrateModelPreferences(environmentId, settings);return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);}@@ -514,7 +527,6 @@ export function useEnvironmentSettings<T = UnifiedSettings>(selector?: (settings: UnifiedSettings) => T,): T {const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));- useMigrateModelPreferences(environmentId, serverSettings);return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);}@@ -532,12 +544,7 @@ export function usePersistEnvironmentProviderInstanceMutation(environmentId: Envexport function usePrimarySettings<T = UnifiedSettings>(selector?: (settings: UnifiedSettings) => T,): T {- const environment = usePrimaryEnvironment();const settings = useAtomValue(primaryServerSettingsAtom);- useMigrateModelPreferences(- environment?.environmentId ?? null,- environment?.serverConfig?.settings ?? null,- );return useMergedSettings(settings, selector);}diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.tsindex 1e1e90cc41e..9a729436f04 100644--- a/apps/web/src/hooks/useTheme.ts+++ b/apps/web/src/hooks/useTheme.ts@@ -509,7 +509,7 @@ export function useRenderedAppearance() {return previewAppearance ?? resolvedTheme;}-function setTheme(next: Theme): boolean {+export function setTheme(next: Theme): boolean {if (typeof window === "undefined") return false;try {// Save the current mode first; inferring it from the new theme can switch dark to light.@@ -549,7 +549,7 @@ function setTheme(next: Theme): boolean {return true;}-function setAppearanceMode(nextAppearanceMode: ThemePreferenceMode): boolean {+export function setAppearanceMode(nextAppearanceMode: ThemePreferenceMode): boolean {if (typeof window === "undefined") return false;try {writeAppearanceModePreference(nextAppearanceMode);diff --git a/apps/web/src/providerAuthDelivery.ts b/apps/web/src/providerAuthDelivery.tsindex 369ef217fd0..f0ff11c5eef 100644--- a/apps/web/src/providerAuthDelivery.ts+++ b/apps/web/src/providerAuthDelivery.ts@@ -1,19 +1,67 @@+import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";import { readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";-let pending: ReturnType<typeof readCodexAuthDelivery>;+import { toastManager } from "./components/ui/toast";+import { appAtomRegistry } from "./rpc/atomRegistry";+import { environmentPresentations } from "./state/presentation";+import { serverEnvironment } from "./state/server";-/** Remove the code before the router, tracing, or welcome screen sees the incoming address. */-export function prepareProviderAuthDelivery() {+type ProviderAuthDelivery = NonNullable<ReturnType<typeof readCodexAuthDelivery>>;++/**+ * Remove the code before the router, tracing, or welcome screen sees the incoming address,+ * then hand it to its environment once that environment connects. Hosted web receives only+ * the one-time code; the selected environment verifies and stores tokens.+ */+export function startProviderAuthDelivery(): void {if (!window.location.hash.startsWith("#codex-auth=")) return;- pending = readCodexAuthDelivery(window.location.href);+ const delivery = readCodexAuthDelivery(window.location.href);window.history.replaceState(window.history.state,"",- pending?.returnUrl ?? `${window.location.pathname}${window.location.search}`,+ delivery?.returnUrl ?? `${window.location.pathname}${window.location.search}`,);+ if (!delivery) return;++ const presentationAtom = environmentPresentations.presentationAtom(delivery.environmentId);+ if (appAtomRegistry.get(presentationAtom)?.connection.phase === "connected") {+ void completeProviderAuth(delivery);+ return;+ }+ const unsubscribe = appAtomRegistry.subscribe(presentationAtom, (presentation) => {+ if (presentation?.connection.phase !== "connected") return;+ unsubscribe();+ void completeProviderAuth(delivery);+ });}-export const pendingProviderAuthDelivery = () => pending;-export const clearProviderAuthDelivery = () => {- pending = undefined;-};+async function completeProviderAuth(delivery: ProviderAuthDelivery): Promise<void> {+ try {+ const result = await runAtomCommand(+ appAtomRegistry,+ serverEnvironment.completeProviderAuth,+ {+ environmentId: delivery.environmentId,+ input: {+ instanceId: delivery.instanceId,+ flowId: delivery.flowId,+ callbackUrl: delivery.callbackUrl,+ },+ },+ { reportFailure: false },+ );+ if (result._tag === "Failure") {+ toastManager.add({+ type: "error",+ title: "ChatGPT sign-in couldn't finish",+ description: "Return to the provider and try again.",+ });+ }+ } catch {+ toastManager.add({+ type: "error",+ title: "ChatGPT sign-in couldn't finish",+ description: "Reconnect to the environment and try again.",+ });+ }+}diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex c65b6ccb6da..0873dad1590 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -1,4 +1,3 @@-import { PermissionUpdateNotice } from "../components/PermissionUpdateNotice";import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";import {@@ -30,19 +29,13 @@ import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator";import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";-import { DesktopUpdateLaunchNotice } from "../components/sidebar/updateEverythingRun";-import { LegacyThreadMigrationToast } from "../components/LegacyThreadMigrationToast";-import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";import { PullRequestGuideRunCoordinator } from "../components/pullRequest/guide/PullRequestGuideRunCoordinator";-import { HostFreezeToastCoordinator } from "../components/HostFreezeToastCoordinator";import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";-import { ProviderAuthCallbackCoordinator } from "../components/settings/ProviderAuthCallbackCoordinator";import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";import { useCopyToClipboard } from "../hooks/useCopyToClipboard";-import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";import { Button } from "../components/ui/button";import { MorphIcon } from "~/components/MorphIcon";@@ -151,6 +144,18 @@ function RootRouteNotFoundView() {}function RootRouteView() {+ // Above every branch: app services raise toasts for the whole page, so the surface they write to+ // must not unmount when the root switches branches (for example /welcome to the app shell).+ return (+ <ToastProvider>+ <AnchoredToastProvider>+ <RootRouteBranch />+ </AnchoredToastProvider>+ </ToastProvider>+ );+}++function RootRouteBranch() {useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);const pathname = useLocation({ select: (location) => location.pathname });const { authGateState } = Route.useRouteContext();@@ -185,20 +190,17 @@ function RootRouteView() {if (pathname === "/welcome") {return (- <ToastProvider>- <AnchoredToastProvider>- <BrowserChromeThemeSync key={pathname} />- <EnvironmentThemeSync />- <ProviderAuthCallbackCoordinator />- <CustomSnoozeDialogHost />- <GuestShareDialogHost />- <CommandPalette>- <AppSidebarLayout>- <Outlet />- </AppSidebarLayout>- </CommandPalette>- </AnchoredToastProvider>- </ToastProvider>+ <>+ <BrowserChromeThemeSync key={pathname} />+ <EnvironmentThemeSync />+ <CustomSnoozeDialogHost />+ <GuestShareDialogHost />+ <CommandPalette>+ <AppSidebarLayout>+ <Outlet />+ </AppSidebarLayout>+ </CommandPalette>+ </>);}@@ -220,54 +222,44 @@ function RootRouteView() {);return (- <ToastProvider>- <AnchoredToastProvider>- <BrowserChromeThemeSync key={pathname} />- <EnvironmentThemeSync />- <ProviderAuthCallbackCoordinator />- <ChatGptWelcomeCoordinator />- <FirstRunGate- enabled={primaryEnvironmentAuthenticated}- hostedStatic={authGateState.status === "hosted-static"}- >- {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}- {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}- {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}- {isElectron ? <RunningThreadKeepAlive /> : null}- <RelayClientInstallDialog />- <ConnectOnboardingDialog />- <SshPasswordPromptDialog />- <SnapShotCoordinator />- <ThreadNotificationCoordinator />- <ReopenClosedViewShortcut />- <ConfirmDialogHost />- <CustomSnoozeDialogHost />- <GuestShareDialogHost />- <SlowRpcRequestToastCoordinator />- <HostFreezeToastCoordinator />- <PermissionUpdateNotice />- {primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}- <ProjectCloneToastCoordinator />- <AddProjectToMachineDialogHost />- <PullRequestGuideRunCoordinator />- <HostedStaticEnvironmentBootstrap />- {primaryEnvironmentAuthenticated ? (- <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />- ) : null}- {isElectron ? <DesktopUpdateLaunchNotice /> : null}- {appShell}- {/* Keep the theme editor above the router so drafts survive navigation. */}- <ThemeEditorHost />- </FirstRunGate>- </AnchoredToastProvider>- </ToastProvider>+ <>+ <BrowserChromeThemeSync key={pathname} />+ <EnvironmentThemeSync />+ <ChatGptWelcomeCoordinator />+ <FirstRunGate+ enabled={primaryEnvironmentAuthenticated}+ hostedStatic={authGateState.status === "hosted-static"}+ >+ {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}+ {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}+ {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}+ {isElectron ? <RunningThreadKeepAlive /> : null}+ <RelayClientInstallDialog />+ <ConnectOnboardingDialog />+ <SshPasswordPromptDialog />+ <SnapShotCoordinator />+ <ReopenClosedViewShortcut />+ <ConfirmDialogHost />+ <CustomSnoozeDialogHost />+ <GuestShareDialogHost />+ <SlowRpcRequestToastCoordinator />+ <ProjectCloneToastCoordinator />+ <AddProjectToMachineDialogHost />+ <PullRequestGuideRunCoordinator />+ <HostedStaticEnvironmentBootstrap />+ {primaryEnvironmentAuthenticated ? (+ <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />+ ) : null}+ {appShell}+ {/* Keep the theme editor above the router so drafts survive navigation. */}+ <ThemeEditorHost />+ </FirstRunGate>+ </>);}function EnvironmentThemeSync() {useEnvironmentThemeSync();- // Sync palettes before adopting the environment theme so it is already in the library.- useDefaultThemeAdoption();return null;}diff --git a/apps/web/src/state/desktopUpdate.ts b/apps/web/src/state/desktopUpdate.tsindex a5fc1d41a1e..ecee6a2ba98 100644--- a/apps/web/src/state/desktopUpdate.ts+++ b/apps/web/src/state/desktopUpdate.ts@@ -79,7 +79,7 @@ export function createDesktopUpdateStateAtom(getBridge: () => DesktopUpdateBridg);}-const desktopUpdateStateAtom = createDesktopUpdateStateAtom(getDesktopUpdateBridge);+export const desktopUpdateStateAtom = createDesktopUpdateStateAtom(getDesktopUpdateBridge);export function useDesktopUpdateState(): DesktopUpdateState | null {return AsyncResult.getOrElse(useAtomValue(desktopUpdateStateAtom), () => null);