@devries-cameron20 / t3code-1 / commits / 8a4ad9452a
Fork 0

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

refactor(web): root notification and toast coordinators start with the app (#25233)

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

Julius Marminge committed Oct 25, 2026 at 21:22 UTC 8a4ad9452a7b999fa7c9f80e0875aed4212737fa
21 files changed +729 -594
apps/web/src/appInit.tsx
+21 -3
@@ -7,19 +7,29 @@ import { applyAppearanceFontVariables } from "./appearanceFonts";
7 import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
8 import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
9 import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
10 +import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
11 +import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
12 +import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
13 import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
14 import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
15 +import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
16 +import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
17 import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
18 import { resolveServerBackedAppDisplayName } from "./branding.logic";
19 import { isElectron } from "./env";
20 import { useComposerDraftStore } from "./composerDraftStore";
16 -import { getClientSettings, subscribeClientSettings } from "./hooks/useSettings";
21 +import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
22 +import {
23 + getClientSettings,
24 + startModelPreferencesMigration,
25 + subscribeClientSettings,
26 +} from "./hooks/useSettings";
27 import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
28 import {
29 syncDocumentElectronPlatformClasses,
30 syncDocumentWindowControlsOverlayClass,
31 } from "./lib/windowControlsOverlay";
22 -import { prepareProviderAuthDelivery } from "./providerAuthDelivery";
32 +import { startProviderAuthDelivery } from "./providerAuthDelivery";
33 import { getRouter, type AppRouter } from "./router";
34 import { appAtomRegistry } from "./rpc/atomRegistry";
35 import { primaryServerConfigAtom } from "./state/server";
@@ -116,7 +126,7 @@ function startThreadOverlayRetention(router: AppRouter): void {
126 */
127 export function startAppServices(): AppRouter {
128 // Ahead of the history: the provider auth code must leave the address before anything reads it.
119 - prepareProviderAuthDelivery();
129 + startProviderAuthDelivery();
130
131 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
132 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
@@ -128,6 +138,8 @@ export function startAppServices(): AppRouter {
138
139 startClientAppearance();
140 startDocumentTitle();
141 + startDefaultThemeAdoption();
142 + startModelPreferencesMigration();
143 startAgentOpenedPreviews();
144 startThreadOverlayRetention(router);
145 startMainAppLocationTracking(router);
@@ -135,5 +147,11 @@ export function startAppServices(): AppRouter {
147 startThreadVisitedMigration(appAtomRegistry);
148 startSshPasswordPromptQueue();
149
150 + startHostFreezeToasts();
151 + startLegacyThreadMigrationToast();
152 + startPermissionUpdateNotices(router);
153 + startThreadNotifications(appAtomRegistry, router);
154 + if (isElectron) startDesktopUpdateLaunchNotice();
155 +
156 return router;
157 }
apps/web/src/components/HostFreezeToastCoordinator.ts new
+33
@@ -0,0 +1,33 @@
1 +import { hostFreezeNotice } from "@t3tools/client-runtime/connection";
2 +
3 +import { appAtomRegistry } from "../rpc/atomRegistry";
4 +import { environmentSummaries } from "../state/presentation";
5 +import { environmentServerConfigsAtom } from "../state/server";
6 +import { toastManager } from "./ui/toast";
7 +
8 +/** Tells the user why a host dropped, once per stall, when it reports one on reconnect. */
9 +export function startHostFreezeToasts(): () => void {
10 + const shown = new Set<string>();
11 + return appAtomRegistry.subscribe(
12 + environmentServerConfigsAtom,
13 + (configs) => {
14 + for (const [environmentId, config] of configs) {
15 + const stall = config.lastEventLoopStall;
16 + if (stall === undefined) continue;
17 + const key = `${environmentId}:${stall.detectedAt}`;
18 + if (shown.has(key)) continue;
19 + shown.add(key);
20 + const label =
21 + appAtomRegistry
22 + .get(environmentSummaries.identitiesAtom)
23 + .find((identity) => identity.environmentId === environmentId)?.label ??
24 + config.environment.label;
25 + const notice = hostFreezeNotice(label, stall);
26 + if (notice !== null) {
27 + toastManager.add({ type: "warning", ...notice });
28 + }
29 + }
30 + },
31 + { immediate: true },
32 + );
33 +}
apps/web/src/components/HostFreezeToastCoordinator.tsx deleted
-33
@@ -1,33 +0,0 @@
1 -import { useAtomValue } from "@effect/atom-react";
2 -import { hostFreezeNotice } from "@t3tools/client-runtime/connection";
3 -import { useEffect, useRef } from "react";
4 -
5 -import { environmentSummaries } from "../state/presentation";
6 -import { environmentServerConfigsAtom } from "../state/server";
7 -import { toastManager } from "./ui/toast";
8 -
9 -/** Tells the user why a host dropped, once per stall, when it reports one on reconnect. */
10 -export function HostFreezeToastCoordinator() {
11 - const configs = useAtomValue(environmentServerConfigsAtom);
12 - const identities = useAtomValue(environmentSummaries.identitiesAtom);
13 - const shownRef = useRef(new Set<string>());
14 -
15 - useEffect(() => {
16 - for (const [environmentId, config] of configs) {
17 - const stall = config.lastEventLoopStall;
18 - if (stall === undefined) continue;
19 - const key = `${environmentId}:${stall.detectedAt}`;
20 - if (shownRef.current.has(key)) continue;
21 - shownRef.current.add(key);
22 - const label =
23 - identities.find((identity) => identity.environmentId === environmentId)?.label ??
24 - config.environment.label;
25 - const notice = hostFreezeNotice(label, stall);
26 - if (notice !== null) {
27 - toastManager.add({ type: "warning", ...notice });
28 - }
29 - }
30 - }, [configs, identities]);
31 -
32 - return null;
33 -}
apps/web/src/components/LegacyThreadMigrationToast.ts new
+39
@@ -0,0 +1,39 @@
1 +import { appAtomRegistry } from "../rpc/atomRegistry";
2 +import { primaryServerLegacyThreadMigrationAtom } from "../state/server";
3 +import { toastManager } from "./ui/toast";
4 +
5 +type MigrationToastId = ReturnType<typeof toastManager.add>;
6 +
7 +/** A loading toast for as long as the primary server reports a legacy thread migration running. */
8 +export function startLegacyThreadMigrationToast(): () => void {
9 + let toastId: MigrationToastId | null = null;
10 +
11 + const unsubscribe = appAtomRegistry.subscribe(
12 + primaryServerLegacyThreadMigrationAtom,
13 + (migration) => {
14 + if (migration?.status === "running") {
15 + if (toastId !== null) return;
16 + toastId = toastManager.add({
17 + type: "loading",
18 + title: "Restoring your threads…",
19 + description: `Migrating ${migration.totalThreadCount.toLocaleString()} ${
20 + migration.totalThreadCount === 1 ? "thread" : "threads"
21 + } from the previous version. You can keep working while this finishes.`,
22 + timeout: 0,
23 + });
24 + return;
25 + }
26 +
27 + if (toastId !== null) {
28 + toastManager.close(toastId);
29 + toastId = null;
30 + }
31 + },
32 + { immediate: true },
33 + );
34 +
35 + return () => {
36 + unsubscribe();
37 + if (toastId !== null) toastManager.close(toastId);
38 + };
39 +}
apps/web/src/components/LegacyThreadMigrationToast.tsx deleted
-45
@@ -1,45 +0,0 @@
1 -import { useAtomValue } from "@effect/atom-react";
2 -import { useEffect, useRef } from "react";
3 -
4 -import { primaryServerLegacyThreadMigrationAtom } from "../state/server";
5 -import { toastManager } from "./ui/toast";
6 -
7 -type MigrationToastId = ReturnType<typeof toastManager.add>;
8 -
9 -export function LegacyThreadMigrationToast() {
10 - const migration = useAtomValue(primaryServerLegacyThreadMigrationAtom);
11 - const toastIdRef = useRef<MigrationToastId | null>(null);
12 -
13 - useEffect(() => {
14 - if (migration?.status === "running") {
15 - if (toastIdRef.current !== null) {
16 - return;
17 - }
18 - toastIdRef.current = toastManager.add({
19 - type: "loading",
20 - title: "Restoring your threads…",
21 - description: `Migrating ${migration.totalThreadCount.toLocaleString()} ${
22 - migration.totalThreadCount === 1 ? "thread" : "threads"
23 - } from the previous version. You can keep working while this finishes.`,
24 - timeout: 0,
25 - });
26 - return;
27 - }
28 -
29 - if (toastIdRef.current !== null) {
30 - toastManager.close(toastIdRef.current);
31 - toastIdRef.current = null;
32 - }
33 - }, [migration]);
34 -
35 - useEffect(
36 - () => () => {
37 - if (toastIdRef.current !== null) {
38 - toastManager.close(toastIdRef.current);
39 - }
40 - },
41 - [],
42 - );
43 -
44 - return null;
45 -}
apps/web/src/components/PermissionUpdateNotice.ts new
+83
@@ -0,0 +1,83 @@
1 +import { sessionHasLegacyPermissions, type EnvironmentId } from "@t3tools/contracts";
2 +import type { AnyRouter } from "@tanstack/react-router";
3 +import * as Schema from "effect/Schema";
4 +import { Atom } from "effect/reactivity";
5 +
6 +import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage";
7 +import { appAtomRegistry } from "../rpc/atomRegistry";
8 +import { environmentSummaries } from "../state/presentation";
9 +import { environmentSession } from "../state/session";
10 +import { toastManager } from "./ui/toast";
11 +
12 +interface LegacyPermissionEnvironment {
13 + readonly environmentId: EnvironmentId;
14 + readonly label: string;
15 +}
16 +
17 +/** Environments whose settled session still carries pre-scope permissions. */
18 +const legacyPermissionEnvironmentsAtom = Atom.make((get) =>
19 + get(environmentSummaries.identitiesAtom).filter(({ environmentId }) => {
20 + const session = get(environmentSession.sessionStateAtom(environmentId));
21 + return (
22 + session._tag === "Success" && !session.waiting && sessionHasLegacyPermissions(session.value)
23 + );
24 + }),
25 +).pipe(Atom.withLabel("web-legacy-permission-environments"));
26 +
27 +const dismissalKey = (environmentId: EnvironmentId) =>
28 + `t3code:permission-update:v1:${environmentId}`;
29 +
30 +function showPermissionNotice(
31 + router: AnyRouter,
32 + { environmentId, label }: LegacyPermissionEnvironment,
33 +) {
34 + const key = dismissalKey(environmentId);
35 + const persistDismissal = () => {
36 + try {
37 + setLocalStorageItem(key, true, Schema.Boolean);
38 + } catch {}
39 + };
40 + const dismiss = () => {
41 + persistDismissal();
42 + toastManager.close(id);
43 + };
44 + const id = toastManager.add({
45 + title: `Permissions have changed for ${label}`,
46 + description:
47 + "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.",
48 + timeout: 0,
49 + onClose: persistDismissal,
50 + actionProps: {
51 + children: "Open Connections",
52 + onClick: () => {
53 + dismiss();
54 + void router.navigate({ to: "/settings/connections" });
55 + },
56 + },
57 + data: {
58 + actionLayout: "stacked-end",
59 + secondaryActionProps: { children: "Dismiss", onClick: dismiss },
60 + secondaryActionVariant: "ghost",
61 + },
62 + });
63 +}
64 +
65 +/** Asks once per environment, until dismissed, to re-pair a connection that predates scoped permissions. */
66 +export function startPermissionUpdateNotices(router: AnyRouter): () => void {
67 + const shown = new Set<EnvironmentId>();
68 + return appAtomRegistry.subscribe(
69 + legacyPermissionEnvironmentsAtom,
70 + (environments) => {
71 + for (const environment of environments) {
72 + if (shown.has(environment.environmentId)) continue;
73 + try {
74 + if (getLocalStorageItem(dismissalKey(environment.environmentId), Schema.Boolean))
75 + continue;
76 + } catch {}
77 + shown.add(environment.environmentId);
78 + showPermissionNotice(router, environment);
79 + }
80 + },
81 + { immediate: true },
82 + );
83 +}
apps/web/src/components/PermissionUpdateNotice.tsx deleted
-74
@@ -1,74 +0,0 @@
1 -import { useAtomValue } from "@effect/atom-react";
2 -import { sessionHasLegacyPermissions, type EnvironmentId } from "@t3tools/contracts";
3 -import { useNavigate } from "@tanstack/react-router";
4 -import * as Schema from "effect/Schema";
5 -import { useEffect } from "react";
6 -
7 -import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage";
8 -import { useEnvironments } from "../state/environments";
9 -import { environmentSession } from "../state/session";
10 -import { toastManager } from "./ui/toast";
11 -
12 -// Keep an active toast across remounts, including Strict Mode effect replay.
13 -const shown = new Set<EnvironmentId>();
14 -
15 -function EnvironmentPermissionNotice({
16 - environmentId,
17 - label,
18 -}: {
19 - environmentId: EnvironmentId;
20 - label: string;
21 -}) {
22 - const session = useAtomValue(environmentSession.sessionStateAtom(environmentId));
23 - const navigate = useNavigate();
24 - useEffect(() => {
25 - if (
26 - session._tag !== "Success" ||
27 - session.waiting ||
28 - !sessionHasLegacyPermissions(session.value)
29 - )
30 - return;
31 - if (shown.has(environmentId)) return;
32 - const key = `t3code:permission-update:v1:${environmentId}`;
33 - try {
34 - if (getLocalStorageItem(key, Schema.Boolean)) return;
35 - } catch {}
36 - shown.add(environmentId);
37 - const persistDismissal = () => {
38 - try {
39 - setLocalStorageItem(key, true, Schema.Boolean);
40 - } catch {}
41 - };
42 - const dismiss = () => {
43 - persistDismissal();
44 - toastManager.close(id);
45 - };
46 - const id = toastManager.add({
47 - title: `Permissions have changed for ${label}`,
48 - description:
49 - "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.",
50 - timeout: 0,
51 - onClose: persistDismissal,
52 - actionProps: {
53 - children: "Open Connections",
54 - onClick: () => {
55 - dismiss();
56 - void navigate({ to: "/settings/connections" });
57 - },
58 - },
59 - data: {
60 - actionLayout: "stacked-end",
61 - secondaryActionProps: { children: "Dismiss", onClick: dismiss },
62 - secondaryActionVariant: "ghost",
63 - },
64 - });
65 - }, [environmentId, label, navigate, session]);
66 - return null;
67 -}
68 -
69 -export function PermissionUpdateNotice() {
70 - const { environments } = useEnvironments();
71 - return environments.map(({ environmentId, label }) => (
72 - <EnvironmentPermissionNotice key={environmentId} environmentId={environmentId} label={label} />
73 - ));
74 -}
apps/web/src/components/ThreadNotificationCoordinator.badge.browser.test.ts renamed
+43 -38
@@ -1,12 +1,12 @@
1 -import { RegistryContext } from "@effect/atom-react";
1 import { WORKING_EXIT_GRACE_MS } from "@t3tools/client-runtime/state/thread-inbox";
2 +import type { AnyRouter } from "@tanstack/react-router";
3 import { EnvironmentId } from "@t3tools/contracts";
4 import * as DateTime from "effect/DateTime";
5 import * as Option from "effect/Option";
6 import { Atom, AtomRegistry } from "effect/reactivity";
7 import { expect, it, vi } from "vite-plus/test";
8
9 -import { fakeTimers, render, stubGlobal, type Screen } from "../../test/render";
9 +import { fakeTimers, stubGlobal } from "../../test/render";
10
11 const state = vi.hoisted(() => ({
12 mode: "notifications",
@@ -16,12 +16,7 @@ const state = vi.hoisted(() => ({
16 navigate: vi.fn(),
17 sound: vi.fn(),
18 badge: vi.fn(),
19 - environmentIds: ["one", "two"],
20 -}));
21 -vi.mock(import("@tanstack/react-router"), async (original) => ({
22 - ...(await original()),
23 - useNavigate: (() => state.navigate) as never,
24 - useParams: (() => ({})) as never,
19 + settingsListeners: new Set<() => void>(),
20 }));
21 vi.mock(import("./ui/toast"), async (original) => {
22 const actual = await original();
@@ -37,16 +32,29 @@ vi.mock(import("../state/shell"), async (original) => {
32 },
33 };
34 });
40 -vi.mock(import("../state/environments"), async (original) => ({
41 - ...(await original()),
42 - useEnvironmentIds: (() => state.environmentIds) as never,
43 -}));
35 +vi.mock(import("../state/presentation"), async (original) => {
36 + const actual = await original();
37 + return {
38 + ...actual,
39 + environmentSummaries: {
40 + ...actual.environmentSummaries,
41 + // Read lazily: the factory runs before this module's own bindings exist.
42 + get environmentIdsAtom() {
43 + return environmentIdsAtom as never;
44 + },
45 + },
46 + };
47 +});
48 vi.mock(import("../hooks/useSettings"), async (original) => ({
49 ...(await original()),
46 - useClientSettings: ((
47 - select: (settings: { notificationMode: string; inAppNotificationsEnabled: boolean }) => unknown,
48 - ) => select({ notificationMode: state.mode, inAppNotificationsEnabled: state.inApp })) as never,
49 - getClientSettings: (() => ({ notificationMode: state.mode })) as never,
50 + subscribeClientSettings: ((listener: () => void) => {
51 + state.settingsListeners.add(listener);
52 + return () => state.settingsListeners.delete(listener);
53 + }) as never,
54 + getClientSettings: (() => ({
55 + notificationMode: state.mode,
56 + inAppNotificationsEnabled: state.inApp,
57 + })) as never,
58 }));
59 vi.mock(import("../threadNotifications"), async (original) => ({
60 ...(await original()),
@@ -55,10 +63,11 @@ vi.mock(import("../threadNotifications"), async (original) => ({
63 setNotificationBadge: state.badge,
64 }));
65
58 -import { ThreadNotificationCoordinator } from "./ThreadNotificationCoordinator";
66 +import { startThreadNotifications } from "./ThreadNotificationCoordinator";
67
68 let registry: AtomRegistry.AtomRegistry;
69 const shellAtom = Atom.family((_id: string) => Atom.make<unknown>(null));
70 +const environmentIdsAtom = Atom.make<ReadonlyArray<string>>([]);
71 state.shells = { set: (id, value) => registry.set(shellAtom(id), value) };
72
73 class TestNotification extends EventTarget {
@@ -155,8 +164,8 @@ function shell(overrides: Partial<typeof thread> = {}, ...others: Partial<typeof
164 }),
165 };
166 }
158 -// The mocked modules read `state`, the registry and the focus flags, so every test starts by
159 -// resetting them. The first render is left to the test because some tests change state first.
167 +// The mocked modules read `state` and the focus flags, so every test resets them before
168 +// starting the service.
169 function setup() {
170 vi.clearAllMocks();
171 const stack = new AsyncDisposableStack();
@@ -165,7 +174,8 @@ function setup() {
174 stack.defer(() => testRegistry.dispose());
175 state.mode = "notifications";
176 state.inApp = false;
168 - state.environmentIds = ["one", "two"];
177 + state.settingsListeners.clear();
178 + registry.set(environmentIdsAtom, ["one", "two"]);
179 state.shells.set("one", shell());
180 state.shells.set("two", shell());
181 focused = false;
@@ -180,19 +190,18 @@ function setup() {
190 .spyOn(document, "visibilityState", "get")
191 .mockImplementation(() => visibility as DocumentVisibilityState),
192 );
183 - const ui = () => (
184 - <RegistryContext.Provider value={testRegistry}>
185 - <ThreadNotificationCoordinator />
186 - </RegistryContext.Provider>
187 - );
188 - let screen: Screen | undefined;
193 + const router = {
194 + state: { matches: [{ params: {} }] },
195 + navigate: state.navigate,
196 + } as unknown as AnyRouter;
197 return {
190 - ui,
191 - async render() {
192 - if (screen) await screen.rerender(ui());
193 - else screen = stack.use(await render(ui()));
198 + start: () => {
199 + stack.defer(startThreadNotifications(testRegistry, router));
200 + },
201 + setEnvironmentIds: (ids: ReadonlyArray<string>) => testRegistry.set(environmentIdsAtom, ids),
202 + changeSettings: () => {
203 + for (const listener of state.settingsListeners) listener();
204 },
195 - unmount: () => screen!.unmount(),
205 [Symbol.asyncDispose]: () => stack.disposeAsync(),
206 };
207 }
@@ -201,9 +210,8 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
210 "badges %s and clears when notifications are disabled",
211 async (flag) => {
212 await using app = setup();
204 - await app.render();
213 + app.start();
214 state.shells.set("one", shell({ [flag]: true }));
206 - await app.render();
215 expect(state.badge).toHaveBeenLastCalledWith(1);
216 const notification = TestNotification.sent[0]!;
217 notification.dispatchEvent(new Event("click"));
@@ -212,7 +220,7 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
220 params: { environmentId: EnvironmentId.make("one"), threadId: "thread" },
221 });
222 state.mode = "sound";
215 - await app.render();
223 + app.changeSettings();
224 expect(state.badge).toHaveBeenLastCalledWith(0);
225 expect(notification.close).toHaveBeenCalled();
226 },
@@ -220,20 +228,17 @@ it.each(["hasPendingApprovals", "hasPendingUserInput"] as const)(
228
229 it("holds a completion through a continuation gap and notifies once it settles", async () => {
230 await using app = setup();
223 - await app.render();
231 + app.start();
232 using _timers = fakeTimers();
233 const finished = (turnId: string, completedAt: string) => ({
234 latestTurn: { turnId, state: "completed", completedAt },
235 });
236 state.shells.set("one", shell(finished("turn-1", "2026-09-13T07:00:01.000Z")));
229 - await app.render();
237 state.shells.set(
238 "one",
239 shell({ latestTurn: { turnId: "turn-2", state: "running", completedAt: null } }),
240 );
234 - await app.render();
241 state.shells.set("one", shell(finished("turn-2", "2026-09-13T07:00:02.000Z")));
236 - await app.render();
242 expect(TestNotification.sent).toEqual([]);
243 await vi.advanceTimersByTimeAsync(WORKING_EXIT_GRACE_MS - 1);
244 expect(TestNotification.sent).toEqual([]);
apps/web/src/components/ThreadNotificationCoordinator.tsx
+170 -124
@@ -4,21 +4,21 @@ import {
4 presentThreadShell,
5 } from "@t3tools/client-runtime/state/models";
6 import { pendingSubagentRequestsByThread } from "@t3tools/client-runtime/state/threads";
7 -import { useAtomValue } from "@effect/atom-react";
8 -import { useNavigate, useParams } from "@tanstack/react-router";
7 +import type { AnyRouter } from "@tanstack/react-router";
8 import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
9 +import type { ClientSettings } from "@t3tools/contracts/settings";
10 import * as Option from "effect/Option";
11 +import type { AtomRegistry } from "effect/reactivity";
12 import {
13 CircleAlertIcon,
14 CircleCheckIcon,
15 MessageCircleQuestionIcon,
16 ShieldQuestionIcon,
17 } from "lucide-react";
17 -import { useEffect, useEffectEvent, useRef } from "react";
18
19 -import { getClientSettings, useClientSettings } from "../hooks/useSettings";
19 +import { getClientSettings, subscribeClientSettings } from "../hooks/useSettings";
20 import { isWindowsPlatform } from "../lib/utils";
21 -import { useEnvironmentIds } from "../state/environments";
21 +import { environmentSummaries } from "../state/presentation";
22 import { environmentShell } from "../state/shell";
23 import {
24 hasDesktopNotifications,
@@ -36,70 +36,6 @@ import {
36 } from "./ThreadNotificationCoordinator.logic";
37 import { toastManager } from "./ui/toast";
38
39 -export function ThreadNotificationCoordinator() {
40 - const environmentIds = useEnvironmentIds();
41 - const mode = useClientSettings((settings) => settings.notificationMode);
42 - const inAppNotificationsEnabled = useClientSettings(
43 - (settings) => settings.inAppNotificationsEnabled,
44 - );
45 - const pending = useRef(
46 - new Map<string, { environmentId: EnvironmentId; notification: Notification }>(),
47 - );
48 - const onNotification = (environmentId: EnvironmentId, notification: Notification) => {
49 - pending.current.get(notification.tag)?.notification.close();
50 - pending.current.set(notification.tag, { environmentId, notification });
51 - setNotificationBadge(pending.current.size);
52 - };
53 -
54 - useEffect(() => {
55 - const activeIds = new Set(environmentIds);
56 - const count = pending.current.size;
57 - for (const [tag, entry] of pending.current) {
58 - if (activeIds.has(entry.environmentId)) continue;
59 - entry.notification.close();
60 - pending.current.delete(tag);
61 - }
62 - if (count !== pending.current.size) setNotificationBadge(pending.current.size);
63 - }, [environmentIds]);
64 -
65 - useEffect(() => {
66 - const clear = () => {
67 - for (const { notification } of pending.current.values()) notification.close();
68 - pending.current.clear();
69 - setNotificationBadge(0);
70 - };
71 - clear();
72 - if (!hasDesktopNotifications(mode)) return;
73 - const unsubscribe = window.desktopBridge?.onNotificationBadgeClear?.(clear);
74 - window.addEventListener("focus", clear);
75 - return () => {
76 - unsubscribe?.();
77 - window.removeEventListener("focus", clear);
78 - clear();
79 - };
80 - }, [mode]);
81 -
82 - useEffect(() => {
83 - if (!hasNotificationSound(mode)) return;
84 - document.addEventListener("pointerdown", unlockNotificationAudio);
85 - document.addEventListener("keydown", unlockNotificationAudio);
86 - return () => {
87 - document.removeEventListener("pointerdown", unlockNotificationAudio);
88 - document.removeEventListener("keydown", unlockNotificationAudio);
89 - };
90 - }, [mode]);
91 -
92 - if (mode === "off" && !inAppNotificationsEnabled) return null;
93 -
94 - return environmentIds.map((environmentId) => (
95 - <EnvironmentNotifications
96 - key={environmentId}
97 - environmentId={environmentId}
98 - onNotification={onNotification}
99 - />
100 - ));
101 -}
102 -
39 interface NotificationState extends ThreadNotificationObservation {
40 readonly raw: OrchestrationV2ThreadShell;
41 readonly subagentRequest: PendingSubagentRequest | null;
@@ -107,31 +43,46 @@ interface NotificationState extends ThreadNotificationObservation {
43 readonly status: SidebarThreadStatus;
44 }
45
110 -function EnvironmentNotifications({
111 - environmentId,
112 - onNotification,
113 -}: {
114 - environmentId: EnvironmentId;
115 - onNotification: (environmentId: EnvironmentId, notification: Notification) => void;
116 -}) {
117 - const shell = useAtomValue(environmentShell.stateValueAtom(environmentId));
118 - const threads =
119 - shell.status === "live" && Option.isSome(shell.snapshot) ? shell.snapshot.value.threads : null;
120 - const mode = useClientSettings((settings) => settings.notificationMode);
121 - const inAppNotificationsEnabled = useClientSettings(
122 - (settings) => settings.inAppNotificationsEnabled,
123 - );
124 - const navigate = useNavigate();
125 - const { environmentId: activeEnvironmentId, threadId: activeThreadId } = useParams({
126 - strict: false,
127 - });
128 - const previous = useRef(new Map<ThreadId, NotificationState>());
46 +interface WatchedEnvironment {
47 + unsubscribe: () => void;
48 + previous: Map<ThreadId, NotificationState>;
49 + readonly gate: ReturnType<typeof createThreadNotificationGate<ThreadId>>;
50 +}
51 +
52 +/**
53 + * Turns thread status transitions in every connected environment into sounds, in-app toasts,
54 + * and desktop notifications, and keeps the dock badge in step with the unread ones.
55 + */
56 +export function startThreadNotifications(
57 + registry: AtomRegistry.AtomRegistry,
58 + router: AnyRouter,
59 +): () => void {
60 + const pending = new Map<string, { environmentId: EnvironmentId; notification: Notification }>();
61 + const watched = new Map<EnvironmentId, WatchedEnvironment>();
62 +
63 + const trackNotification = (environmentId: EnvironmentId, notification: Notification) => {
64 + pending.get(notification.tag)?.notification.close();
65 + pending.set(notification.tag, { environmentId, notification });
66 + setNotificationBadge(pending.size);
67 + };
68 + const clearPending = () => {
69 + for (const { notification } of pending.values()) notification.close();
70 + pending.clear();
71 + setNotificationBadge(0);
72 + };
73
74 // Completions fire from a timer, so read settings, focus and route when presenting.
131 - const present = useEffectEvent((threadId: ThreadId, kind: ThreadNotificationKind) => {
132 - const entry = previous.current.get(threadId);
133 - if (!entry) return;
134 - const { thread, status } = entry;
75 + const present = (
76 + environmentId: EnvironmentId,
77 + state: NotificationState,
78 + kind: ThreadNotificationKind,
79 + ) => {
80 + const { thread, status } = state;
81 + const { notificationMode: mode, inAppNotificationsEnabled } = getClientSettings();
82 + const active = (router.state.matches.at(-1)?.params ?? {}) as {
83 + environmentId?: string;
84 + threadId?: string;
85 + };
86 const title =
87 kind === "completion"
88 ? "Thread completed"
@@ -153,7 +104,7 @@ function EnvironmentNotifications({
104 inAppNotificationsEnabled &&
105 document.visibilityState === "visible" &&
106 document.hasFocus() &&
156 - (activeEnvironmentId !== environmentId || activeThreadId !== thread.id)
107 + (active.environmentId !== environmentId || active.threadId !== thread.id)
108 ) {
109 const toastId = toastManager.add({
110 type: kind === "completion" ? "success" : status === "failed" ? "error" : "warning",
@@ -176,7 +127,7 @@ function EnvironmentNotifications({
127 children: "Open thread",
128 onClick: () => {
129 toastManager.close(toastId);
179 - void navigate({
130 + void router.navigate({
131 to: "/$environmentId/$threadId",
132 params: { environmentId, threadId: thread.id },
133 });
@@ -200,12 +151,12 @@ function EnvironmentNotifications({
151 // Windows drops clicks after a toast moves into Notification Center.
152 requireInteraction: kind === "completion" && isWindowsPlatform(navigator.platform),
153 });
203 - onNotification(environmentId, notification);
154 + trackNotification(environmentId, notification);
155 notification.addEventListener("click", () => {
156 notification.close();
157 window.focus();
158 void window.desktopBridge?.revealWindow?.().catch(() => undefined);
208 - void navigate({
159 + void router.navigate({
160 to: "/$environmentId/$threadId",
161 params: { environmentId, threadId: thread.id },
162 });
@@ -213,35 +164,20 @@ function EnvironmentNotifications({
164 } catch {
165 // Some browsers expose Notification but reject desktop presentation.
166 }
216 - });
217 - const gate = useRef<ReturnType<typeof createThreadNotificationGate<ThreadId>>>(null);
218 - useEffect(() => {
219 - const created = createThreadNotificationGate<ThreadId>((threadId, kind) =>
220 - present(threadId, kind),
221 - );
222 - gate.current = created;
223 - return () => {
224 - created.clear();
225 - gate.current = null;
226 - // A new gate has no pending completions, so forget the states they compared against.
227 - previous.current.clear();
228 - };
229 - }, []);
167 + };
168
231 - useEffect(() => {
232 - const pendingCompletions = gate.current;
233 - if (!pendingCompletions) return;
234 - if (threads === null) {
235 - pendingCompletions.clear();
236 - previous.current.clear();
237 - return;
238 - }
169 + const observeThreads = (
170 + environmentId: EnvironmentId,
171 + entry: WatchedEnvironment,
172 + threads: ReadonlyArray<OrchestrationV2ThreadShell>,
173 + ) => {
174 + const previous = entry.previous;
175 const next = new Map<ThreadId, NotificationState>();
176 const subagentRequests = pendingSubagentRequestsByThread(threads);
177 const changed: Array<[NotificationState | undefined, NotificationState]> = [];
178 for (const rawThread of threads) {
179 if (rawThread.lineage.relationshipToParent === "subagent") continue;
244 - const prior = previous.current.get(rawThread.id);
180 + const prior = previous.get(rawThread.id);
181 const subagentRequest = subagentRequests.get(rawThread.id) ?? null;
182 if (prior?.raw === rawThread && prior.subagentRequest === subagentRequest) {
183 next.set(rawThread.id, prior);
@@ -272,15 +208,125 @@ function EnvironmentNotifications({
208 next.set(thread.id, state);
209 changed.push([prior, state]);
210 }
275 - previous.current = next;
276 - pendingCompletions.retain(new Set(next.keys()));
211 + entry.previous = next;
212 + entry.gate.retain(new Set(next.keys()));
213 for (const [prior, state] of changed) {
278 - pendingCompletions.observe(state.thread.id, prior, state, {
214 + entry.gate.observe(state.thread.id, prior, state, {
215 archived: state.thread.archivedAt !== null,
216 quiet: state.raw.latestRunStopRequested === true,
217 });
218 }
283 - }, [environmentId, threads]);
219 + };
220 +
221 + const watchEnvironment = (environmentId: EnvironmentId): WatchedEnvironment => {
222 + const entry: WatchedEnvironment = {
223 + previous: new Map(),
224 + unsubscribe: () => {},
225 + gate: createThreadNotificationGate<ThreadId>((threadId, kind) => {
226 + const state = entry.previous.get(threadId);
227 + if (state) present(environmentId, state, kind);
228 + }),
229 + };
230 + const unsubscribeShell = registry.subscribe(
231 + environmentShell.stateValueAtom(environmentId),
232 + (shell) => {
233 + const threads =
234 + shell.status === "live" && Option.isSome(shell.snapshot)
235 + ? shell.snapshot.value.threads
236 + : null;
237 + if (threads !== null) {
238 + observeThreads(environmentId, entry, threads);
239 + return;
240 + }
241 + entry.gate.clear();
242 + entry.previous = new Map();
243 + },
244 + { immediate: true },
245 + );
246 + entry.unsubscribe = () => {
247 + unsubscribeShell();
248 + entry.gate.clear();
249 + };
250 + return entry;
251 + };
252 +
253 + const syncEnvironments = () => {
254 + const { notificationMode, inAppNotificationsEnabled } = getClientSettings();
255 + const enabled = notificationMode !== "off" || inAppNotificationsEnabled;
256 + const environmentIds = enabled ? registry.get(environmentSummaries.environmentIdsAtom) : [];
257 + const activeIds = new Set(environmentIds);
258 + for (const [environmentId, entry] of watched) {
259 + if (activeIds.has(environmentId)) continue;
260 + entry.unsubscribe();
261 + watched.delete(environmentId);
262 + }
263 + for (const environmentId of environmentIds) {
264 + if (!watched.has(environmentId)) watched.set(environmentId, watchEnvironment(environmentId));
265 + }
266 + };
267 +
268 + const pruneRemovedEnvironments = () => {
269 + const activeIds = new Set(registry.get(environmentSummaries.environmentIdsAtom));
270 + const count = pending.size;
271 + for (const [tag, entry] of pending) {
272 + if (activeIds.has(entry.environmentId)) continue;
273 + entry.notification.close();
274 + pending.delete(tag);
275 + }
276 + if (count !== pending.size) setNotificationBadge(pending.size);
277 + };
278 +
279 + // Listeners that only exist for some notification modes, rebuilt when the mode changes.
280 + let appliedMode: ClientSettings["notificationMode"] | null = null;
281 + let stopModeListeners = () => {};
282 + const applyMode = () => {
283 + const nextMode = getClientSettings().notificationMode;
284 + if (nextMode === appliedMode) return;
285 + appliedMode = nextMode;
286 + stopModeListeners();
287 + clearPending();
288 + const stops: Array<() => void> = [];
289 + if (hasDesktopNotifications(nextMode)) {
290 + const unsubscribeBadgeClear = window.desktopBridge?.onNotificationBadgeClear?.(clearPending);
291 + window.addEventListener("focus", clearPending);
292 + stops.push(() => {
293 + unsubscribeBadgeClear?.();
294 + window.removeEventListener("focus", clearPending);
295 + clearPending();
296 + });
297 + }
298 + if (hasNotificationSound(nextMode)) {
299 + document.addEventListener("pointerdown", unlockNotificationAudio);
300 + document.addEventListener("keydown", unlockNotificationAudio);
301 + stops.push(() => {
302 + document.removeEventListener("pointerdown", unlockNotificationAudio);
303 + document.removeEventListener("keydown", unlockNotificationAudio);
304 + });
305 + }
306 + stopModeListeners = () => {
307 + for (const stop of stops) stop();
308 + };
309 + };
310
285 - return null;
311 + const onSettings = () => {
312 + applyMode();
313 + syncEnvironments();
314 + };
315 + const unsubscribeSettings = subscribeClientSettings(onSettings);
316 + const unsubscribeEnvironmentIds = registry.subscribe(
317 + environmentSummaries.environmentIdsAtom,
318 + () => {
319 + pruneRemovedEnvironments();
320 + syncEnvironments();
321 + },
322 + );
323 + onSettings();
324 +
325 + return () => {
326 + unsubscribeSettings();
327 + unsubscribeEnvironmentIds();
328 + for (const entry of watched.values()) entry.unsubscribe();
329 + watched.clear();
330 + stopModeListeners();
331 + };
332 }
apps/web/src/components/settings/ProviderAuthCallbackCoordinator.tsx deleted
-50
@@ -1,50 +0,0 @@
1 -import { useEffect, useRef, useState } from "react";
2 -import { pendingProviderAuthDelivery, clearProviderAuthDelivery } from "../../providerAuthDelivery";
3 -import { serverEnvironment } from "../../state/server";
4 -import { useEnvironments } from "../../state/environments";
5 -import { useAtomCommand } from "../../state/use-atom-command";
6 -import { toastManager } from "../ui/toast";
7 -
8 -/** Hosted web receives only the one-time code; the selected environment verifies and stores tokens. */
9 -export function ProviderAuthCallbackCoordinator() {
10 - const completeAuth = useAtomCommand(serverEnvironment.completeProviderAuth, {
11 - reportFailure: false,
12 - });
13 - const { environments } = useEnvironments();
14 - const [delivery, setDelivery] = useState(pendingProviderAuthDelivery);
15 - const started = useRef(false);
16 - const environmentId = delivery?.environmentId;
17 - const connected = environments.some(
18 - (environment) =>
19 - environment.environmentId === environmentId && environment.connection.phase === "connected",
20 - );
21 - useEffect(() => {
22 - const input = delivery;
23 - if (!input || started.current || !connected) return;
24 - started.current = true;
25 - void completeAuth({
26 - environmentId: input.environmentId,
27 - input: { instanceId: input.instanceId, flowId: input.flowId, callbackUrl: input.callbackUrl },
28 - })
29 - .then((result) => {
30 - if (result._tag === "Failure")
31 - toastManager.add({
32 - type: "error",
33 - title: "ChatGPT sign-in couldn't finish",
34 - description: "Return to the provider and try again.",
35 - });
36 - })
37 - .catch(() =>
38 - toastManager.add({
39 - type: "error",
40 - title: "ChatGPT sign-in couldn't finish",
41 - description: "Reconnect to the environment and try again.",
42 - }),
43 - )
44 - .finally(() => {
45 - setDelivery(undefined);
46 - clearProviderAuthDelivery();
47 - });
48 - }, [completeAuth, connected, delivery]);
49 - return null;
50 -}
apps/web/src/components/settings/useScopedSettings.ts
+1 -6
@@ -14,11 +14,7 @@ import {
14 type UnifiedSettings,
15 } from "@t3tools/contracts";
16
17 -import {
18 - persistClientSettingsPatch,
19 - useMergedSettings,
20 - useMigrateModelPreferences,
21 -} from "../../hooks/useSettings";
17 +import { persistClientSettingsPatch, useMergedSettings } from "../../hooks/useSettings";
18 import { serverEnvironment } from "../../state/server";
19 import { useAtomCommand } from "../../state/use-atom-command";
20 import { toastManager } from "../ui/toast";
@@ -38,7 +34,6 @@ export function useScopedSettings<T = UnifiedSettings>(
34 selector?: (settings: UnifiedSettings) => T,
35 ): T {
36 const { target } = useSettingsScope();
41 - useMigrateModelPreferences(target?.environmentId ?? null, target?.settings ?? null);
37 return useMergedSettings(target?.settings ?? DEFAULT_SERVER_SETTINGS, selector);
38 }
39
apps/web/src/components/sidebar/updateEverythingRun.tsx
+25 -25
@@ -2,12 +2,11 @@ import { useAtomValue } from "@effect/atom-react";
2 import { EnvironmentId } from "@t3tools/contracts";
3 import * as Option from "effect/Option";
4 import * as Schema from "effect/Schema";
5 -import { Atom } from "effect/reactivity";
6 -import { useEffect } from "react";
5 +import { AsyncResult, Atom } from "effect/reactivity";
6
7 import { APP_VERSION } from "~/branding";
8 import { appAtomRegistry } from "~/rpc/atomRegistry";
10 -import { useDesktopUpdateState } from "~/state/desktopUpdate";
9 +import { desktopUpdateStateAtom } from "~/state/desktopUpdate";
10 import { serverEnvironment } from "~/state/server";
11 import { resolveVersionMismatch } from "~/versionSkew";
12 import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction";
@@ -307,30 +306,31 @@ function followHandedOffServers(servers: ReadonlyArray<HandedOffServer>): void {
306 }
307 }
308
310 -let notifiedNotAppliedVersion: string | null = null;
311 -
312 -export function DesktopUpdateLaunchNotice() {
313 - const notAppliedVersion = useDesktopUpdateState()?.notAppliedVersion ?? null;
314 -
315 - useEffect(() => {
316 - const saved = takeSavedUpdateEverythingResult();
317 - if (!saved) return;
309 +/** Reports, once per launch, how the update run that restarted the app ended. */
310 +export function startDesktopUpdateLaunchNotice(): () => void {
311 + const saved = takeSavedUpdateEverythingResult();
312 + if (saved) {
313 const handedOff = saved.handedOff ?? [];
314 showUpdateEverythingResult({ ...saved, restarting: handedOff.map((server) => server.label) });
315 followHandedOffServers(handedOff);
321 - }, []);
322 -
323 - useEffect(() => {
324 - if (notAppliedVersion === null || notifiedNotAppliedVersion === notAppliedVersion) return;
325 - notifiedNotAppliedVersion = notAppliedVersion;
326 - toastManager.add(
327 - stackedThreadToast({
328 - type: "error",
329 - title: "Update did not apply",
330 - description: `T3 Code is still on ${APP_VERSION}. Install ${notAppliedVersion} again from the update button.`,
331 - }),
332 - );
333 - }, [notAppliedVersion]);
316 + }
317
335 - return null;
318 + let notifiedNotAppliedVersion: string | null = null;
319 + return appAtomRegistry.subscribe(
320 + desktopUpdateStateAtom,
321 + (result) => {
322 + const notAppliedVersion =
323 + AsyncResult.getOrElse(result, () => null)?.notAppliedVersion ?? null;
324 + if (notAppliedVersion === null || notifiedNotAppliedVersion === notAppliedVersion) return;
325 + notifiedNotAppliedVersion = notAppliedVersion;
326 + toastManager.add(
327 + stackedThreadToast({
328 + type: "error",
329 + title: "Update did not apply",
330 + description: `T3 Code is still on ${APP_VERSION}. Install ${notAppliedVersion} again from the update button.`,
331 + }),
332 + );
333 + },
334 + { immediate: true },
335 + );
336 }
apps/web/src/components/ui/toast.browser.test.tsx new
+15
@@ -0,0 +1,15 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +import { page } from "vite-plus/test/browser";
3 +
4 +import { render } from "../../../test/render";
5 +import { ToastProvider, toastManager } from "./toast";
6 +
7 +describe("toastManager", () => {
8 + it("shows a toast added before any provider mounted", async () => {
9 + toastManager.add({ type: "info", title: "Raised before the first render" });
10 +
11 + await using _screen = await render(<ToastProvider>{null}</ToastProvider>);
12 +
13 + await expect.element(page.getByText("Raised before the first render")).toBeVisible();
14 + });
15 +});
apps/web/src/components/ui/toast.tsx
+34 -2
@@ -62,8 +62,40 @@ export type ThreadToastData = {
62 | "secondary";
63 };
64
65 -const toastManager = Toast.createToastManager<ThreadToastData>();
66 -const anchoredToastManager = Toast.createToastManager<ThreadToastData>();
65 +type BaseToastManager = ReturnType<typeof Toast.createToastManager<ThreadToastData>>;
66 +type ToastManagerListener = Parameters<BaseToastManager[" subscribe"]>[0];
67 +type ToastManagerEvent = Parameters<ToastManagerListener>[0];
68 +
69 +/**
70 + * base-ui's manager drops events while no provider is subscribed. App services raise toasts
71 + * from before the first render (and while the root error view replaces the providers), so hold
72 + * those until a provider listens.
73 + */
74 +function createBufferedToastManager(): BaseToastManager {
75 + const manager = Toast.createToastManager<ThreadToastData>();
76 + const listeners = new Set<ToastManagerListener>();
77 + const pending: ToastManagerEvent[] = [];
78 + manager[" subscribe"]((event) => {
79 + if (listeners.size === 0) {
80 + pending.push(event);
81 + return;
82 + }
83 + for (const listener of listeners) listener(event);
84 + });
85 + return {
86 + ...manager,
87 + " subscribe"(listener) {
88 + listeners.add(listener);
89 + for (const event of pending.splice(0)) listener(event);
90 + return () => {
91 + listeners.delete(listener);
92 + };
93 + },
94 + };
95 +}
96 +
97 +const toastManager = createBufferedToastManager();
98 +const anchoredToastManager = createBufferedToastManager();
99 type ToastId = ReturnType<typeof toastManager.add>;
100 const threadToastVisibleTimeoutRemainingMs = new Map<ToastId, number>();
101
apps/web/src/hooks/useDefaultTheme.ts
+43 -33
@@ -1,10 +1,8 @@
1 -import { useAtomValue } from "@effect/atom-react";
2 -import { useEffect, useSyncExternalStore } from "react";
3 -
1 +import { appAtomRegistry } from "../rpc/atomRegistry";
2 import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
3 import { primaryServerSettingsAtom } from "../state/server";
4 import { getThemeDefinition, singleAppearanceOf, subscribeToCustomThemes } from "../themePalette";
7 -import { useTheme } from "./useTheme";
5 +import { setAppearanceMode, setTheme } from "./useTheme";
6
7 const APPLIED_DEFAULT_THEME_STORAGE_PREFIX = "t3code:default-theme-applied:v2:";
8
@@ -23,7 +21,9 @@ export function defaultThemeToApply(input: {
21 if (input.environmentId === null || input.defaultTheme.length === 0) return null;
22 const generation = defaultThemeGeneration(input.defaultTheme, input.defaultThemeSetAt);
23 if (input.appliedGeneration === generation) return null;
26 - // Settings and palettes arrive independently; an unresolved theme must retry when palettes arrive.
24 + // The setting and the palette it names arrive independently, so an id that
25 + // does not resolve yet is not a failure -- adoption re-checks when the
26 + // published set changes.
27 if (!input.resolves) return null;
28 return generation;
29 }
@@ -43,34 +43,44 @@ function writeAppliedGeneration(storageKey: string, generation: string): void {
43 } catch {}
44 }
45
46 -export function useDefaultThemeAdoption(): void {
47 - const environmentId = useAtomValue(primaryEnvironmentIdAtom);
48 - const settings = useAtomValue(primaryServerSettingsAtom);
49 - const { defaultTheme, defaultThemeSetAt } = settings;
50 - const { setTheme, setAppearanceMode } = useTheme();
51 - const definition = useSyncExternalStore(
52 - subscribeToCustomThemes,
53 - () => getThemeDefinition(defaultTheme),
54 - () => null,
55 - );
46 +function adoptDefaultTheme(): void {
47 + if (typeof window === "undefined") return;
48 + const environmentId = appAtomRegistry.get(primaryEnvironmentIdAtom);
49 + if (environmentId === null) return;
50 + const { defaultTheme, defaultThemeSetAt } = appAtomRegistry.get(primaryServerSettingsAtom);
51 + const definition = getThemeDefinition(defaultTheme);
52 + const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;
53 + const generation = defaultThemeToApply({
54 + environmentId,
55 + defaultTheme,
56 + defaultThemeSetAt,
57 + appliedGeneration: readAppliedGeneration(storageKey),
58 + resolves: definition !== null,
59 + });
60 + if (generation === null || definition === null) return;
61
57 - useEffect(() => {
58 - if (typeof window === "undefined" || environmentId === null) return;
59 - const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;
60 - const generation = defaultThemeToApply({
61 - environmentId,
62 - defaultTheme,
63 - defaultThemeSetAt,
64 - appliedGeneration: readAppliedGeneration(storageKey),
65 - resolves: definition !== null,
66 - });
67 - if (generation === null || definition === null) return;
62 + // A single-appearance theme needs both preference and appearance writes to take effect.
63 + if (!setTheme(defaultTheme)) return;
64 + const half = singleAppearanceOf(definition);
65 + // Only record adoption after both writes succeed, so an appearance failure remains retryable.
66 + if (half !== null && !setAppearanceMode(half)) return;
67 + writeAppliedGeneration(storageKey, generation);
68 +}
69
69 - // A single-appearance theme needs both preference and appearance writes to take effect.
70 - if (!setTheme(defaultTheme)) return;
71 - const half = singleAppearanceOf(definition);
72 - // Only record adoption after both writes succeed, so an appearance failure remains retryable.
73 - if (half !== null && !setAppearanceMode(half)) return;
74 - writeAppliedGeneration(storageKey, generation);
75 - }, [environmentId, defaultTheme, defaultThemeSetAt, definition, setTheme, setAppearanceMode]);
70 +/**
71 + * Applies the primary environment's default theme once per generation. Start it after the
72 + * environment theme sync so a first-run client adopting the environment's own theme finds it
73 + * already in the library; it re-checks when published or custom palettes change, so a theme
74 + * that resolves late still applies.
75 + */
76 +export function startDefaultThemeAdoption(): () => void {
77 + const unsubscribes = [
78 + appAtomRegistry.subscribe(primaryEnvironmentIdAtom, adoptDefaultTheme),
79 + appAtomRegistry.subscribe(primaryServerSettingsAtom, adoptDefaultTheme),
80 + subscribeToCustomThemes(adoptDefaultTheme),
81 + ];
82 + adoptDefaultTheme();
83 + return () => {
84 + for (const unsubscribe of unsubscribes) unsubscribe();
85 + };
86 }
apps/web/src/hooks/useSettings.favorites.browser.test.tsx
+56 -42
@@ -19,6 +19,10 @@ import { describe, expect, it, vi } from "vite-plus/test";
19 import { act, render, type Screen } from "../../test/render";
20
21 const state = vi.hoisted(() => ({
22 + catalog: null as unknown as Atom.Writable<{
23 + readonly isReady: boolean;
24 + readonly entries: ReadonlyMap<string, unknown>;
25 + }>,
26 settings: new Map<string, unknown>(),
27 connections: new Map<
28 EnvironmentId,
@@ -29,10 +33,18 @@ const state = vi.hoisted(() => ({
33
34 vi.mock(import("~/connection/catalog"), async (original) => {
35 const actual = await original();
36 + const { Atom } = await import("effect/reactivity");
37 + state.catalog = Atom.keepAlive(
38 + Atom.make<{ readonly isReady: boolean; readonly entries: ReadonlyMap<string, unknown> }>({
39 + isReady: true,
40 + entries: new Map(),
41 + }),
42 + );
43 return {
44 ...actual,
45 environmentCatalog: {
46 ...actual.environmentCatalog,
47 + catalogValueAtom: state.catalog as never,
48 stateAtom: ((id: EnvironmentId) => state.connections.get(id)) as never,
49 },
50 };
@@ -52,6 +64,10 @@ vi.mock(import("~/state/server"), async (original) => {
64 serverEnvironment: {
65 ...actual.serverEnvironment,
66 settingsValueAtom: ((id: EnvironmentId) => state.settings.get(id)) as never,
67 + updateSettings: {
68 + ...actual.serverEnvironment.updateSettings,
69 + run: (_registry: unknown, input: unknown) => state.persist(input),
70 + } as never,
71 },
72 };
73 });
@@ -60,7 +76,12 @@ vi.mock(import("~/state/use-atom-command"), async (original) => ({
76 useAtomCommand: (() => state.persist) as never,
77 }));
78
63 -import { useEnvironmentModelPreferences, useToggleEnvironmentModelFavorite } from "./useSettings";
79 +import { appAtomRegistry } from "~/rpc/atomRegistry";
80 +import {
81 + ensureClientSettingsHydrated,
82 + startModelPreferencesMigration,
83 + useToggleEnvironmentModelFavorite,
84 +} from "./useSettings";
85
86 const primaryId = EnvironmentId.make("primary");
87 const remoteId = EnvironmentId.make("remote");
@@ -242,17 +263,11 @@ describe("environment favorite toggles", () => {
263 });
264 });
265
245 -function ModelPreferencesReader({ environmentId }: { environmentId: EnvironmentId }) {
246 - useEnvironmentModelPreferences(environmentId);
247 - return null;
248 -}
249 -
266 describe("legacy model preferences migration", () => {
267 it.each(["succeeds", "fails"] as const)(
268 "waits for connection and retries only after reconnect when the first save %s",
269 async (outcome) => {
254 - await using fixture = await setup();
255 - const { registry, show } = fixture;
270 + await using _fixture = await setup();
271 const environmentId = EnvironmentId.make(`migration-${outcome}`);
272 const otherId = EnvironmentId.make(`other-${outcome}`);
273 for (const id of [environmentId, otherId]) {
@@ -281,59 +296,58 @@ describe("legacy model preferences migration", () => {
296 state.persist
297 .mockReturnValueOnce(firstSave)
298 .mockResolvedValue(AsyncResult.success(DEFAULT_SERVER_SETTINGS));
284 - const renderReader = (id = environmentId) =>
285 - show(<ModelPreferencesReader key={id} environmentId={id} />);
299 const connect = (id: EnvironmentId, generation: number) =>
287 - act(() =>
288 - registry.set(
289 - state.connections.get(id)!,
290 - AsyncResult.success({
291 - ...AVAILABLE_CONNECTION_STATE,
292 - desired: true,
293 - generation,
294 - phase: "connected",
295 - }),
296 - ),
300 + appAtomRegistry.set(
301 + state.connections.get(id)!,
302 + AsyncResult.success({
303 + ...AVAILABLE_CONNECTION_STATE,
304 + desired: true,
305 + generation,
306 + phase: "connected",
307 + }),
308 );
309 const pushSettings = (id = environmentId) =>
299 - act(() => registry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS }));
310 + appAtomRegistry.set(settingsAtom(id), { ...DEFAULT_SERVER_SETTINGS });
311 const migration = (id: EnvironmentId) => ({
312 environmentId: id,
313 input: { patch: { migrateModelPreferences: { favorites: [{ provider, model }] } } },
314 });
315
305 - await renderReader();
306 - await pushSettings();
316 + appAtomRegistry.set(state.catalog, {
317 + isReady: true,
318 + entries: new Map([
319 + [environmentId, {}],
320 + [otherId, {}],
321 + ]),
322 + });
323 + using _migration = { [Symbol.dispose]: startModelPreferencesMigration() };
324 + await ensureClientSettingsHydrated();
325 + pushSettings();
326 expect(state.persist).not.toHaveBeenCalled();
327
309 - await connect(environmentId, 1);
328 + connect(environmentId, 1);
329 expect(state.persist).toHaveBeenCalledExactlyOnceWith(migration(environmentId));
311 - await pushSettings();
330 + pushSettings();
331 expect(state.persist).toHaveBeenCalledTimes(1);
313 - await act(finishFirstSave);
314 - await pushSettings();
315 - await pushSettings();
332 + finishFirstSave();
333 + await firstSave;
334 + pushSettings();
335 + pushSettings();
336 expect(state.persist).toHaveBeenCalledTimes(1);
337
318 - await connect(otherId, 7);
319 - await pushSettings(otherId);
320 - expect(state.persist).toHaveBeenCalledTimes(1);
321 - await renderReader(otherId);
338 + connect(otherId, 7);
339 expect(state.persist).toHaveBeenLastCalledWith(migration(otherId));
323 - await renderReader();
324 - await pushSettings();
340 + pushSettings(otherId);
341 expect(state.persist).toHaveBeenCalledTimes(2);
342
327 - await act(() =>
328 - registry.set(
329 - state.connections.get(environmentId)!,
330 - AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }),
331 - ),
343 + appAtomRegistry.set(
344 + state.connections.get(environmentId)!,
345 + AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, generation: 1 }),
346 );
333 - await pushSettings();
347 + pushSettings();
348 expect(state.persist).toHaveBeenCalledTimes(2);
335 - await connect(environmentId, 2);
336 - await pushSettings();
349 + connect(environmentId, 2);
350 + pushSettings();
351 expect(state.persist.mock.calls).toEqual([
352 [migration(environmentId)],
353 [migration(otherId)],
apps/web/src/hooks/useSettings.ts
+50 -43
@@ -1,4 +1,4 @@
1 -import { useEffect, useRef, useSyncExternalStore, use } from "react";
1 +import { useRef, useSyncExternalStore, use } from "react";
2 import { useSyncExternalStoreWithSelector } from "use-sync-external-store/with-selector";
3 import { RegistryContext, useAtomValue } from "@effect/atom-react";
4 import {
@@ -22,6 +22,7 @@ import {
22 import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
23 import {
24 isAtomCommandInterrupted,
25 + runAtomCommand,
26 squashAtomCommandFailure,
27 } from "@t3tools/client-runtime/state/runtime";
28 import {
@@ -313,46 +314,59 @@ export function mergeEnvironmentSettings(
314 };
315 }
316
316 -// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
317 -const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
318 -const connectionGenerationAtom = Atom.family((environmentId: EnvironmentId | null) =>
319 - Atom.make((get) =>
320 - environmentId === null
321 - ? null
322 - : Option.match(AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))), {
323 - onNone: () => null,
324 - onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),
325 - }),
326 - ),
327 -);
328 -
317 const selectLegacyModelPreferences = (settings: ClientSettings) => ({
318 favorites: settings.favorites,
319 providerModelPreferences: settings.providerModelPreferences,
320 });
321
334 -export function useMigrateModelPreferences(
335 - environmentId: EnvironmentId | null,
336 - settings: ServerSettings | null,
337 -) {
338 - const clientSettings = useClientSettings(selectLegacyModelPreferences);
339 - const hydrated = useClientSettingsHydrated();
340 - const connectionGeneration = useAtomValue(connectionGenerationAtom(environmentId));
341 - const migrate = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
342 - useEffect(() => {
343 - if (
344 - !environmentId ||
345 - !settings ||
346 - !hydrated ||
347 - connectionGeneration === null ||
348 - attemptedMigrationGenerations.get(environmentId) === connectionGeneration
349 - )
350 - return;
351 - const patch = modelPreferencesMigrationPatch(settings, clientSettings);
352 - if (!patch) return;
353 - attemptedMigrationGenerations.set(environmentId, connectionGeneration);
354 - void migrate({ environmentId, input: { patch } });
355 - }, [clientSettings, connectionGeneration, environmentId, hydrated, migrate, settings]);
322 +// Servers that predate `migrateModelPreferences` drop it and keep reporting null favorites.
323 +const attemptedMigrationGenerations = new Map<EnvironmentId, number>();
324 +
325 +const modelPreferencesMigrationTargetsAtom = Atom.make((get) =>
326 + [...get(environmentCatalog.catalogValueAtom).entries.keys()].flatMap((environmentId) => {
327 + const generation = Option.match(
328 + AsyncResult.value(get(environmentCatalog.stateAtom(environmentId))),
329 + {
330 + onNone: () => null,
331 + onSome: (connection) => (connection.phase === "connected" ? connection.generation : null),
332 + },
333 + );
334 + const settings = get(serverEnvironment.settingsValueAtom(environmentId));
335 + return generation === null || settings === null
336 + ? []
337 + : [{ environmentId, generation, settings }];
338 + }),
339 +).pipe(Atom.withLabel("web-model-preferences-migration-targets"));
340 +
341 +function migrateModelPreferences(): void {
342 + if (clientSettingsHydrationStatus !== "ready") return;
343 + for (const { environmentId, generation, settings } of appAtomRegistry.get(
344 + modelPreferencesMigrationTargetsAtom,
345 + )) {
346 + if (attemptedMigrationGenerations.get(environmentId) === generation) continue;
347 + const patch = modelPreferencesMigrationPatch(settings, clientSettingsSnapshot);
348 + if (!patch) continue;
349 + attemptedMigrationGenerations.set(environmentId, generation);
350 + void runAtomCommand(
351 + appAtomRegistry,
352 + serverEnvironment.updateSettings,
353 + { environmentId, input: { patch } },
354 + { reportFailure: false },
355 + );
356 + }
357 +}
358 +
359 +/** Moves this client's legacy model preferences onto each server, once per connection. */
360 +export function startModelPreferencesMigration(): () => void {
361 + const unsubscribes = [
362 + appAtomRegistry.subscribe(modelPreferencesMigrationTargetsAtom, migrateModelPreferences),
363 + subscribeClientSettings(migrateModelPreferences),
364 + subscribeClientSettingsHydration(migrateModelPreferences),
365 + ];
366 + migrateModelPreferences();
367 + return () => {
368 + for (const unsubscribe of unsubscribes) unsubscribe();
369 + };
370 }
371
372 export function useMergedSettings<T = UnifiedSettings>(
@@ -505,7 +519,6 @@ export function useEnvironmentModelPreferences(environmentId: EnvironmentId | nu
519 environmentId ? serverEnvironment.settingsValueAtom(environmentId) : noEnvironmentSettingsAtom,
520 );
521 const legacy = useClientSettings(selectLegacyModelPreferences);
508 - useMigrateModelPreferences(environmentId, settings);
522 return resolveModelPreferences(settings ?? DEFAULT_SERVER_SETTINGS, legacy);
523 }
524
@@ -514,7 +527,6 @@ export function useEnvironmentSettings<T = UnifiedSettings>(
527 selector?: (settings: UnifiedSettings) => T,
528 ): T {
529 const serverSettings = useAtomValue(serverEnvironment.settingsValueAtom(environmentId));
517 - useMigrateModelPreferences(environmentId, serverSettings);
530 return useMergedSettings(serverSettings ?? DEFAULT_SERVER_SETTINGS, selector);
531 }
532
@@ -532,12 +544,7 @@ export function usePersistEnvironmentProviderInstanceMutation(environmentId: Env
544 export function usePrimarySettings<T = UnifiedSettings>(
545 selector?: (settings: UnifiedSettings) => T,
546 ): T {
535 - const environment = usePrimaryEnvironment();
547 const settings = useAtomValue(primaryServerSettingsAtom);
537 - useMigrateModelPreferences(
538 - environment?.environmentId ?? null,
539 - environment?.serverConfig?.settings ?? null,
540 - );
548 return useMergedSettings(settings, selector);
549 }
550
apps/web/src/hooks/useTheme.ts
+2 -2
@@ -509,7 +509,7 @@ export function useRenderedAppearance() {
509 return previewAppearance ?? resolvedTheme;
510 }
511
512 -function setTheme(next: Theme): boolean {
512 +export function setTheme(next: Theme): boolean {
513 if (typeof window === "undefined") return false;
514 try {
515 // 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 {
549 return true;
550 }
551
552 -function setAppearanceMode(nextAppearanceMode: ThemePreferenceMode): boolean {
552 +export function setAppearanceMode(nextAppearanceMode: ThemePreferenceMode): boolean {
553 if (typeof window === "undefined") return false;
554 try {
555 writeAppearanceModePreference(nextAppearanceMode);
apps/web/src/providerAuthDelivery.ts
+57 -9
@@ -1,19 +1,67 @@
1 +import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
2 import { readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
3
3 -let pending: ReturnType<typeof readCodexAuthDelivery>;
4 +import { toastManager } from "./components/ui/toast";
5 +import { appAtomRegistry } from "./rpc/atomRegistry";
6 +import { environmentPresentations } from "./state/presentation";
7 +import { serverEnvironment } from "./state/server";
8
5 -/** Remove the code before the router, tracing, or welcome screen sees the incoming address. */
6 -export function prepareProviderAuthDelivery() {
9 +type ProviderAuthDelivery = NonNullable<ReturnType<typeof readCodexAuthDelivery>>;
10 +
11 +/**
12 + * Remove the code before the router, tracing, or welcome screen sees the incoming address,
13 + * then hand it to its environment once that environment connects. Hosted web receives only
14 + * the one-time code; the selected environment verifies and stores tokens.
15 + */
16 +export function startProviderAuthDelivery(): void {
17 if (!window.location.hash.startsWith("#codex-auth=")) return;
8 - pending = readCodexAuthDelivery(window.location.href);
18 + const delivery = readCodexAuthDelivery(window.location.href);
19 window.history.replaceState(
20 window.history.state,
21 "",
12 - pending?.returnUrl ?? `${window.location.pathname}${window.location.search}`,
22 + delivery?.returnUrl ?? `${window.location.pathname}${window.location.search}`,
23 );
24 + if (!delivery) return;
25 +
26 + const presentationAtom = environmentPresentations.presentationAtom(delivery.environmentId);
27 + if (appAtomRegistry.get(presentationAtom)?.connection.phase === "connected") {
28 + void completeProviderAuth(delivery);
29 + return;
30 + }
31 + const unsubscribe = appAtomRegistry.subscribe(presentationAtom, (presentation) => {
32 + if (presentation?.connection.phase !== "connected") return;
33 + unsubscribe();
34 + void completeProviderAuth(delivery);
35 + });
36 }
37
16 -export const pendingProviderAuthDelivery = () => pending;
17 -export const clearProviderAuthDelivery = () => {
18 - pending = undefined;
19 -};
38 +async function completeProviderAuth(delivery: ProviderAuthDelivery): Promise<void> {
39 + try {
40 + const result = await runAtomCommand(
41 + appAtomRegistry,
42 + serverEnvironment.completeProviderAuth,
43 + {
44 + environmentId: delivery.environmentId,
45 + input: {
46 + instanceId: delivery.instanceId,
47 + flowId: delivery.flowId,
48 + callbackUrl: delivery.callbackUrl,
49 + },
50 + },
51 + { reportFailure: false },
52 + );
53 + if (result._tag === "Failure") {
54 + toastManager.add({
55 + type: "error",
56 + title: "ChatGPT sign-in couldn't finish",
57 + description: "Return to the provider and try again.",
58 + });
59 + }
60 + } catch {
61 + toastManager.add({
62 + type: "error",
63 + title: "ChatGPT sign-in couldn't finish",
64 + description: "Reconnect to the environment and try again.",
65 + });
66 + }
67 +}
apps/web/src/routes/__root.tsx
+56 -64
@@ -1,4 +1,3 @@
1 -import { PermissionUpdateNotice } from "../components/PermissionUpdateNotice";
1 import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";
2 import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
3 import {
@@ -30,19 +29,13 @@ import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";
29 import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";
30 import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkCoordinator";
31 import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
33 -import { DesktopUpdateLaunchNotice } from "../components/sidebar/updateEverythingRun";
34 -import { LegacyThreadMigrationToast } from "../components/LegacyThreadMigrationToast";
35 -import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";
32 import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";
33 import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
34 import { PullRequestGuideRunCoordinator } from "../components/pullRequest/guide/PullRequestGuideRunCoordinator";
39 -import { HostFreezeToastCoordinator } from "../components/HostFreezeToastCoordinator";
35 import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
36 import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
42 -import { ProviderAuthCallbackCoordinator } from "../components/settings/ProviderAuthCallbackCoordinator";
37 import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
38 import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
45 -import { useDefaultThemeAdoption } from "../hooks/useDefaultTheme";
39 import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
40 import { Button } from "../components/ui/button";
41 import { MorphIcon } from "~/components/MorphIcon";
@@ -151,6 +144,18 @@ function RootRouteNotFoundView() {
144 }
145
146 function RootRouteView() {
147 + // Above every branch: app services raise toasts for the whole page, so the surface they write to
148 + // must not unmount when the root switches branches (for example /welcome to the app shell).
149 + return (
150 + <ToastProvider>
151 + <AnchoredToastProvider>
152 + <RootRouteBranch />
153 + </AnchoredToastProvider>
154 + </ToastProvider>
155 + );
156 +}
157 +
158 +function RootRouteBranch() {
159 useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
160 const pathname = useLocation({ select: (location) => location.pathname });
161 const { authGateState } = Route.useRouteContext();
@@ -185,20 +190,17 @@ function RootRouteView() {
190
191 if (pathname === "/welcome") {
192 return (
188 - <ToastProvider>
189 - <AnchoredToastProvider>
190 - <BrowserChromeThemeSync key={pathname} />
191 - <EnvironmentThemeSync />
192 - <ProviderAuthCallbackCoordinator />
193 - <CustomSnoozeDialogHost />
194 - <GuestShareDialogHost />
195 - <CommandPalette>
196 - <AppSidebarLayout>
197 - <Outlet />
198 - </AppSidebarLayout>
199 - </CommandPalette>
200 - </AnchoredToastProvider>
201 - </ToastProvider>
193 + <>
194 + <BrowserChromeThemeSync key={pathname} />
195 + <EnvironmentThemeSync />
196 + <CustomSnoozeDialogHost />
197 + <GuestShareDialogHost />
198 + <CommandPalette>
199 + <AppSidebarLayout>
200 + <Outlet />
201 + </AppSidebarLayout>
202 + </CommandPalette>
203 + </>
204 );
205 }
206
@@ -220,54 +222,44 @@ function RootRouteView() {
222 );
223
224 return (
223 - <ToastProvider>
224 - <AnchoredToastProvider>
225 - <BrowserChromeThemeSync key={pathname} />
226 - <EnvironmentThemeSync />
227 - <ProviderAuthCallbackCoordinator />
228 - <ChatGptWelcomeCoordinator />
229 - <FirstRunGate
230 - enabled={primaryEnvironmentAuthenticated}
231 - hostedStatic={authGateState.status === "hosted-static"}
232 - >
233 - {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
234 - {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
235 - {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
236 - {isElectron ? <RunningThreadKeepAlive /> : null}
237 - <RelayClientInstallDialog />
238 - <ConnectOnboardingDialog />
239 - <SshPasswordPromptDialog />
240 - <SnapShotCoordinator />
241 - <ThreadNotificationCoordinator />
242 - <ReopenClosedViewShortcut />
243 - <ConfirmDialogHost />
244 - <CustomSnoozeDialogHost />
245 - <GuestShareDialogHost />
246 - <SlowRpcRequestToastCoordinator />
247 - <HostFreezeToastCoordinator />
248 - <PermissionUpdateNotice />
249 - {primaryEnvironmentAuthenticated ? <LegacyThreadMigrationToast /> : null}
250 - <ProjectCloneToastCoordinator />
251 - <AddProjectToMachineDialogHost />
252 - <PullRequestGuideRunCoordinator />
253 - <HostedStaticEnvironmentBootstrap />
254 - {primaryEnvironmentAuthenticated ? (
255 - <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
256 - ) : null}
257 - {isElectron ? <DesktopUpdateLaunchNotice /> : null}
258 - {appShell}
259 - {/* Keep the theme editor above the router so drafts survive navigation. */}
260 - <ThemeEditorHost />
261 - </FirstRunGate>
262 - </AnchoredToastProvider>
263 - </ToastProvider>
225 + <>
226 + <BrowserChromeThemeSync key={pathname} />
227 + <EnvironmentThemeSync />
228 + <ChatGptWelcomeCoordinator />
229 + <FirstRunGate
230 + enabled={primaryEnvironmentAuthenticated}
231 + hostedStatic={authGateState.status === "hosted-static"}
232 + >
233 + {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
234 + {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
235 + {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
236 + {isElectron ? <RunningThreadKeepAlive /> : null}
237 + <RelayClientInstallDialog />
238 + <ConnectOnboardingDialog />
239 + <SshPasswordPromptDialog />
240 + <SnapShotCoordinator />
241 + <ReopenClosedViewShortcut />
242 + <ConfirmDialogHost />
243 + <CustomSnoozeDialogHost />
244 + <GuestShareDialogHost />
245 + <SlowRpcRequestToastCoordinator />
246 + <ProjectCloneToastCoordinator />
247 + <AddProjectToMachineDialogHost />
248 + <PullRequestGuideRunCoordinator />
249 + <HostedStaticEnvironmentBootstrap />
250 + {primaryEnvironmentAuthenticated ? (
251 + <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
252 + ) : null}
253 + {appShell}
254 + {/* Keep the theme editor above the router so drafts survive navigation. */}
255 + <ThemeEditorHost />
256 + </FirstRunGate>
257 + </>
258 );
259 }
260
261 function EnvironmentThemeSync() {
262 useEnvironmentThemeSync();
269 - // Sync palettes before adopting the environment theme so it is already in the library.
270 - useDefaultThemeAdoption();
263 return null;
264 }
265
apps/web/src/state/desktopUpdate.ts
+1 -1
@@ -79,7 +79,7 @@ export function createDesktopUpdateStateAtom(getBridge: () => DesktopUpdateBridg
79 );
80 }
81
82 -const desktopUpdateStateAtom = createDesktopUpdateStateAtom(getDesktopUpdateBridge);
82 +export const desktopUpdateStateAtom = createDesktopUpdateStateAtom(getDesktopUpdateBridge);
83
84 export function useDesktopUpdateState(): DesktopUpdateState | null {
85 return AsyncResult.getOrElse(useAtomValue(desktopUpdateStateAtom), () => null);