@devries-cameron20 / t3code-1 / commits / 148d2fdc0e
Fork 0

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

refactor(web): root theme, toast and chrome sync start with the app (#25461)

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

Julius Marminge committed Oct 26, 2026 at 07:00 UTC 148d2fdc0ee0ccf2b909c10b13001a61cf19b281
13 files changed +340 -307
apps/web/src/appInit.tsx
+22
@@ -9,11 +9,13 @@ import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRe
9 import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
10 import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
11 import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
12 +import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
13 import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
14 import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
15 import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
16 import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
17 import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
18 +import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
19 import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
20 import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
21 import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
@@ -21,12 +23,15 @@ import { resolveServerBackedAppDisplayName } from "./branding.logic";
23 import { isElectron } from "./env";
24 import { useComposerDraftStore } from "./composerDraftStore";
25 import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
26 +import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
27 import {
28 getClientSettings,
29 startModelPreferencesMigration,
30 subscribeClientSettings,
31 } from "./hooks/useSettings";
32 +import { syncBrowserChromeTheme } from "./hooks/useTheme";
33 import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
34 +import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
35 import {
36 syncDocumentElectronPlatformClasses,
37 syncDocumentWindowControlsOverlayClass,
@@ -104,6 +109,17 @@ function startDocumentTitle(): void {
109 );
110 }
111
112 +/**
113 + * Each route paints its own surface, which the browser chrome samples once it is on screen.
114 + * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
115 + * can swap the root between the bare outlet and the shell at the same address.
116 + */
117 +function startBrowserChromeThemeSync(router: AppRouter): void {
118 + const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
119 + router.subscribe("onRendered", resync);
120 + router.subscribe("onResolved", resync);
121 +}
122 +
123 /** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
124 function startThreadOverlayRetention(router: AppRouter): void {
125 router.subscribe("onResolved", () => {
@@ -138,8 +154,12 @@ export function startAppServices(): AppRouter {
154 syncDocumentWindowControlsOverlayClass();
155 }
156
157 + installDesktopPasteAsText(window.desktopBridge, window);
158 +
159 startClientAppearance();
160 startDocumentTitle();
161 + startEnvironmentThemeRepaint();
162 + startBrowserChromeThemeSync(router);
163 startDefaultThemeAdoption();
164 startModelPreferencesMigration();
165 startAgentOpenedPreviews();
@@ -150,6 +170,8 @@ export function startAppServices(): AppRouter {
170 startThreadVisitedMigration(appAtomRegistry);
171 startSshPasswordPromptQueue();
172
173 + startKeybindingsUpdateToasts();
174 + startSlowRpcRequestToasts();
175 startHostFreezeToasts();
176 startLegacyThreadMigrationToast();
177 startPermissionUpdateNotices(router);
apps/web/src/components/KeybindingsUpdateToast.test.ts new
+65
@@ -0,0 +1,65 @@
1 +import type { ServerConfigStreamEvent } from "@t3tools/contracts";
2 +import { describe, expect, it, vi } from "vite-plus/test";
3 +
4 +const mocks = vi.hoisted(() => ({
5 + state: null as unknown as import("effect/reactivity").Atom.Writable<{
6 + readonly latestEvent: ServerConfigStreamEvent | null;
7 + }>,
8 + addToast: vi.fn<(toast: { readonly title?: unknown }) => void>(),
9 +}));
10 +
11 +// The event atom is derived from server state, as in production; nothing else reads it.
12 +vi.mock(import("../state/server"), async () => {
13 + const { Atom } = await import("effect/reactivity");
14 + mocks.state = Atom.make<{ readonly latestEvent: ServerConfigStreamEvent | null }>({
15 + latestEvent: null,
16 + });
17 + return {
18 + primaryServerConfigAtom: Atom.make(null),
19 + primaryServerConfigEventAtom: Atom.make((get) => get(mocks.state).latestEvent),
20 + } as never;
21 +});
22 +vi.mock(import("../state/primaryEnvironment"), async () => {
23 + const { Atom } = await import("effect/reactivity");
24 + return { primaryEnvironmentIdAtom: Atom.make(null) } as never;
25 +});
26 +vi.mock(
27 + import("./KeybindingsConfigWarning"),
28 + () => ({ KeybindingsConfigWarning: () => null }) as never,
29 +);
30 +vi.mock(
31 + import("./ui/toast"),
32 + () =>
33 + ({
34 + toastManager: { add: mocks.addToast },
35 + stackedThreadToast: (toast: unknown) => toast,
36 + }) as never,
37 +);
38 +
39 +import { appAtomRegistry } from "../rpc/atomRegistry";
40 +import { startKeybindingsUpdateToasts } from "./KeybindingsUpdateToast";
41 +
42 +function keybindingsUpdated(issues: ReadonlyArray<unknown>): ServerConfigStreamEvent {
43 + return { type: "keybindingsUpdated", payload: { keybindings: [], issues } } as never;
44 +}
45 +
46 +describe("startKeybindingsUpdateToasts", () => {
47 + it("toasts reloads the server reports after start", () => {
48 + const stop = startKeybindingsUpdateToasts();
49 + try {
50 + appAtomRegistry.set(mocks.state, { latestEvent: keybindingsUpdated([]) });
51 + appAtomRegistry.set(mocks.state, {
52 + latestEvent: keybindingsUpdated([
53 + { kind: "keybindings.malformed-config", message: "Unexpected token" },
54 + ]),
55 + });
56 +
57 + expect(mocks.addToast.mock.calls.map(([toast]) => toast.title)).toEqual([
58 + "Keybindings updated",
59 + "Invalid keybindings configuration",
60 + ]);
61 + } finally {
62 + stop();
63 + }
64 + });
65 +});
apps/web/src/components/KeybindingsUpdateToast.tsx new
+40
@@ -0,0 +1,40 @@
1 +import { appAtomRegistry, subscribeAtomChanges } from "../rpc/atomRegistry";
2 +import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
3 +import { primaryServerConfigAtom, primaryServerConfigEventAtom } from "../state/server";
4 +import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
5 +import { createKeybindingsUpdateToastController } from "./KeybindingsUpdateToast.logic";
6 +import { stackedThreadToast, toastManager } from "./ui/toast";
7 +
8 +/** Toasts each keybindings reload the primary server reports. */
9 +export function startKeybindingsUpdateToasts(): () => void {
10 + const controller = createKeybindingsUpdateToastController({});
11 + return subscribeAtomChanges(primaryServerConfigEventAtom, (event) => {
12 + const decision = controller.handle(event);
13 + if (!decision) return;
14 +
15 + if (decision._tag === "Success") {
16 + toastManager.add({
17 + type: "success",
18 + title: "Keybindings updated",
19 + description: "Keybindings configuration reloaded successfully.",
20 + });
21 + return;
22 + }
23 +
24 + const serverConfig = appAtomRegistry.get(primaryServerConfigAtom);
25 + toastManager.add(
26 + stackedThreadToast({
27 + type: "warning",
28 + title: "Invalid keybindings configuration",
29 + description: (
30 + <KeybindingsConfigWarning
31 + message={decision.message}
32 + environmentId={appAtomRegistry.get(primaryEnvironmentIdAtom)}
33 + configPath={serverConfig?.keybindingsConfigPath ?? null}
34 + availableEditors={serverConfig?.availableEditors ?? []}
35 + />
36 + ),
37 + }),
38 + );
39 + });
40 +}
apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
+4 -1
@@ -47,7 +47,10 @@ vi.mock(import("../connection/catalog"), async (original) => {
47 ...actual,
48 environmentCatalog: {
49 ...actual.environmentCatalog,
50 - catalogValueAtom: Atom.make({ isReady: true, entries: new Map([["remote", {}]]) }) as never,
50 + catalogValueAtom: Atom.make({
51 + isReady: true,
52 + entries: new Map([["remote", { target: { _tag: "DirectConnectionTarget" } }]]),
53 + }) as never,
54 },
55 };
56 });
apps/web/src/components/SlowRpcRequestToastCoordinator.tsx
+16 -24
@@ -1,6 +1,4 @@
1 -import { useEffect, useRef } from "react";
2 -
3 -import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
1 +import { type SlowRpcAckRequest, subscribeSlowRpcAckRequests } from "../rpc/requestLatencyState";
2 import { toastManager } from "./ui/toast";
3
4 function describeSlowRequests(requests: ReadonlyArray<SlowRpcAckRequest>): string {
@@ -30,15 +28,15 @@ function SlowRequestDetails({ requests }: { requests: ReadonlyArray<SlowRpcAckRe
28 );
29 }
30
33 -export function SlowRpcRequestToastCoordinator() {
34 - const slowRequests = useSlowRpcAckRequests();
35 - const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
31 +/** One warning toast that tracks the set of slow requests while any are outstanding. */
32 +export function startSlowRpcRequestToasts(): () => void {
33 + let toastId: ReturnType<typeof toastManager.add> | null = null;
34
37 - useEffect(() => {
35 + const unsubscribe = subscribeSlowRpcAckRequests((slowRequests) => {
36 if (slowRequests.length === 0) {
39 - if (toastIdRef.current !== null) {
40 - toastManager.close(toastIdRef.current);
41 - toastIdRef.current = null;
37 + if (toastId !== null) {
38 + toastManager.close(toastId);
39 + toastId = null;
40 }
41 return;
42 }
@@ -55,21 +53,15 @@ export function SlowRpcRequestToastCoordinator() {
53 type: "warning" as const,
54 };
55
58 - if (toastIdRef.current === null) {
59 - toastIdRef.current = toastManager.add(nextToast);
56 + if (toastId === null) {
57 + toastId = toastManager.add(nextToast);
58 } else {
61 - toastManager.update(toastIdRef.current, nextToast);
59 + toastManager.update(toastId, nextToast);
60 }
63 - }, [slowRequests]);
64 -
65 - useEffect(
66 - () => () => {
67 - if (toastIdRef.current !== null) {
68 - toastManager.close(toastIdRef.current);
69 - }
70 - },
71 - [],
72 - );
61 + });
62
74 - return null;
63 + return () => {
64 + unsubscribe();
65 + if (toastId !== null) toastManager.close(toastId);
66 + };
67 }
apps/web/src/hooks/useEnvironmentTheme.test.ts
+43 -5
@@ -1,11 +1,25 @@
1 +import type { EnvironmentTheme } from "@t3tools/contracts";
2 import { afterEach, describe, expect, it, vi } from "vite-plus/test";
3
3 -import { environmentThemeDefinition, publishedThemeDefinitions } from "./useEnvironmentTheme";
4 +const publishedThemes = vi.hoisted(() => ({
5 + atom: null as unknown as import("effect/reactivity").Atom.Writable<
6 + ReadonlyArray<EnvironmentTheme>
7 + >,
8 +}));
9 +vi.mock(import("../state/server"), async () => {
10 + const { Atom } = await import("effect/reactivity");
11 + publishedThemes.atom = Atom.make<ReadonlyArray<EnvironmentTheme>>([]);
12 + return { primaryServerEnvironmentThemesAtom: publishedThemes.atom } as never;
13 +});
14 +const refreshTheme = vi.hoisted(() => vi.fn());
15 +vi.mock(import("./useTheme"), () => ({ refreshTheme }) as never);
16 +
17 +import { appAtomRegistry } from "../rpc/atomRegistry";
18 import {
19 getThemeDefinition,
20 installCustomTheme,
21 invalidateCustomThemes,
8 - setEnvironmentThemes,
22 + publishedThemeDefinitions,
23 } from "../themePalette";
24
25 const NIGHTFALL_THEME = {
@@ -17,7 +31,7 @@ const NIGHTFALL_THEME = {
31 } as const;
32
33 afterEach(() => {
20 - setEnvironmentThemes([]);
34 + appAtomRegistry.set(publishedThemes.atom, []);
35 });
36
37 describe("environment themes", () => {
@@ -72,6 +86,15 @@ describe("environment themes", () => {
86 ]);
87 });
88
89 + // Routes without the old root sync component (/connect, prompt-link landings) never saw them.
90 + it("resolves published themes without a React subscriber mounted", () => {
91 + appAtomRegistry.set(publishedThemes.atom, [NIGHTFALL_THEME]);
92 + expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
93 +
94 + appAtomRegistry.set(publishedThemes.atom, [{ ...NIGHTFALL_THEME, name: "Nightfall 2" }]);
95 + expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall 2");
96 + });
97 +
98 it("lets a theme the user saved win an id collision", () => {
99 const store = new Map<string, string>();
100 vi.stubGlobal("window", {
@@ -85,8 +108,10 @@ describe("environment themes", () => {
108 });
109 invalidateCustomThemes();
110 try {
88 - const environment = environmentThemeDefinition(NIGHTFALL_THEME);
89 - setEnvironmentThemes([environment]);
111 + appAtomRegistry.set(publishedThemes.atom, [NIGHTFALL_THEME]);
112 + expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
113 + const environment = getThemeDefinition("nightfall");
114 + if (!environment) throw new Error("expected the published theme");
115 installCustomTheme({ ...environment, label: "My Nightfall" });
116
117 expect(getThemeDefinition("nightfall")?.label).toBe("My Nightfall");
@@ -96,4 +121,17 @@ describe("environment themes", () => {
121 }
122 expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
123 });
124 +
125 + it("repaints when the environment publishes themes nothing has read yet", async () => {
126 + vi.resetModules();
127 + const { appAtomRegistry: registry } = await import("../rpc/atomRegistry");
128 + const { startEnvironmentThemeRepaint } = await import("./useEnvironmentTheme");
129 + const stop = startEnvironmentThemeRepaint();
130 + try {
131 + registry.set(publishedThemes.atom, [NIGHTFALL_THEME]);
132 + expect(refreshTheme).toHaveBeenCalledTimes(1);
133 + } finally {
134 + stop();
135 + }
136 + });
137 });
apps/web/src/hooks/useEnvironmentTheme.ts
+12 -89
@@ -1,96 +1,19 @@
1 -import type { EnvironmentTheme } from "@t3tools/contracts";
1 import { useAtomValue } from "@effect/atom-react";
3 -import * as Equal from "effect/Equal";
4 -import { useEffect, useRef, useSyncExternalStore } from "react";
2
6 -import { primaryServerEnvironmentThemesAtom } from "../state/server";
7 -import {
8 - createVividThemeColors,
9 - getDefaultThemeColors,
10 - getEnvironmentThemes,
11 - isReservedThemeId,
12 - lenientThemeColorOverrides,
13 - setEnvironmentThemes,
14 - subscribeToCustomThemes,
15 - type ThemeAppearance,
16 - type ThemeColors,
17 - type ThemeDefinition,
18 -} from "../themePalette";
19 -import { useTheme } from "./useTheme";
20 -
21 -function publishedThemeColors(
22 - theme: EnvironmentTheme,
23 - appearance: ThemeAppearance,
24 - colors: Readonly<Record<string, string>> | undefined,
25 -): ThemeColors {
26 - // The generator follows canvas luminance; dark seeds would make a light variant unreadable.
27 - const base =
28 - appearance === theme.appearance && theme.canvas !== undefined && theme.accent !== undefined
29 - ? createVividThemeColors(appearance, theme.canvas, theme.accent)
30 - : getDefaultThemeColors(appearance);
31 - return { ...base, ...lenientThemeColorOverrides(colors ?? {}) };
32 -}
33 -
34 -export function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
35 - const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
36 - for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {
37 - if (variantAppearance === theme.appearance) continue;
38 - variants[variantAppearance as ThemeAppearance] = publishedThemeColors(
39 - theme,
40 - variantAppearance as ThemeAppearance,
41 - variantColors,
42 - );
43 - }
44 -
45 - return {
46 - id: theme.id,
47 - label: theme.name,
48 - appearance: theme.appearance,
49 - colors: publishedThemeColors(theme, theme.appearance, theme.colors),
50 - ...(Object.keys(variants).length > 0 ? { variants } : {}),
51 - // Guided editing regenerates from seeds, so hand-tuned role overrides must use the advanced editor.
52 - ...(theme.canvas !== undefined &&
53 - theme.accent !== undefined &&
54 - theme.colors === undefined &&
55 - theme.variants === undefined
56 - ? { managed: true }
57 - : {}),
58 - };
59 -}
60 -
61 -/** Filters reserved ids that would select built-ins instead of the published palette. */
62 -export function publishedThemeDefinitions(
63 - themes: ReadonlyArray<EnvironmentTheme>,
64 -): ReadonlyArray<ThemeDefinition> {
65 - return themes
66 - .filter((theme) => {
67 - if (isReservedThemeId(theme.id)) return false;
68 - if (theme.canvas !== undefined && theme.accent !== undefined) return true;
69 - const otherAppearance = theme.appearance === "dark" ? "light" : "dark";
70 - return [theme.colors, theme.variants?.[otherAppearance]].some(
71 - (colors) =>
72 - colors !== undefined && Object.keys(lenientThemeColorOverrides(colors)).length > 0,
73 - );
74 - })
75 - .map(environmentThemeDefinition);
76 -}
3 +import { subscribeAtomChanges } from "../rpc/atomRegistry";
4 +import { environmentThemeDefinitionsAtom, type ThemeDefinition } from "../themePalette";
5 +import { refreshTheme } from "./useTheme";
6
7 export function useEnvironmentThemeDefinitions(): ReadonlyArray<ThemeDefinition> {
79 - return useSyncExternalStore(subscribeToCustomThemes, getEnvironmentThemes, () => []);
8 + return useAtomValue(environmentThemeDefinitionsAtom);
9 }
10
82 -export function useEnvironmentThemeSync(): void {
83 - const published = useAtomValue(primaryServerEnvironmentThemesAtom);
84 - const { refreshTheme } = useTheme();
85 - const lastPublished = useRef<ReadonlyArray<EnvironmentTheme> | null>(null);
86 -
87 - useEffect(() => {
88 - if (lastPublished.current !== null && Equal.equals(lastPublished.current, published)) return;
89 - lastPublished.current = published;
90 -
91 - // Active palettes are snapshots; changed colors require reapplying the theme.
92 - if (setEnvironmentThemes(publishedThemeDefinitions(published))) {
93 - refreshTheme({ preservePreview: true });
94 - }
95 - }, [published, refreshTheme]);
11 +/**
12 + * The palette is painted from a snapshot taken when the theme last changed, so new colors
13 + * only land if the active theme is re-applied.
14 + */
15 +export function startEnvironmentThemeRepaint(): () => void {
16 + return subscribeAtomChanges(environmentThemeDefinitionsAtom, () => {
17 + refreshTheme({ preservePreview: true });
18 + });
19 }
apps/web/src/hooks/useTheme.ts
+1 -1
@@ -626,7 +626,7 @@ function clearThemeHalves(): boolean {
626 return true;
627 }
628
629 -function refreshTheme({ preservePreview = false } = {}): void {
629 +export function refreshTheme({ preservePreview = false } = {}): void {
630 if (typeof window === "undefined") return;
631 lastAppliedTheme = null;
632 applyTheme(getStored(), { suppressTransitions: true, preservePreview });
apps/web/src/routes/__root.tsx
+10 -156
@@ -20,7 +20,6 @@ import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
20 import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
21 import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
22 import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
23 -import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
23 import { FirstRunGate } from "../components/onboarding/FirstRunGate";
24 import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
25 import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
@@ -31,20 +30,13 @@ import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkC
30 import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
31 import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";
32 import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
34 -import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
33 import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
34 import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
35 import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
38 -import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
36 import { Button } from "../components/ui/button";
37 import { MorphIcon } from "~/components/MorphIcon";
38 import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
42 -import {
43 - AnchoredToastProvider,
44 - stackedThreadToast,
45 - ToastProvider,
46 - toastManager,
47 -} from "../components/ui/toast";
39 +import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
40 import { isElectron } from "../env";
41 import { cn } from "../lib/utils";
42 import { useClientSettings } from "../hooks/useSettings";
@@ -54,7 +46,6 @@ import {
46 selectProjectGroupingSettings,
47 } from "../logicalProject";
48 import { useUiStateStore } from "../uiStateStore";
57 -import { syncBrowserChromeTheme } from "../hooks/useTheme";
49 import { configureClientTracing } from "../observability/clientTracing";
50 import { resolveInitialServerAuthGateState } from "../environments/primary";
51 import { GUEST_PAGE_PATH } from "../guestPage";
@@ -62,20 +53,10 @@ import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
53 import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
54 import { isLocalEnvironmentDisabled } from "../localEnvironment";
55 import { useAtomValue } from "@effect/atom-react";
65 -import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
66 -import {
67 - primaryServerConfigAtom,
68 - primaryServerConfigEventAtom,
69 - primaryServerWelcomeAtom,
70 -} from "../state/server";
71 -import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
72 -import {
73 - createKeybindingsUpdateToastController,
74 - type KeybindingsUpdateToastController,
75 -} from "../components/KeybindingsUpdateToast.logic";
56 +import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../state/server";
57 +import { readProject } from "../state/entities";
58
59 import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
78 -import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
60 import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
61
62 export const Route = createRootRoute({
@@ -107,6 +88,10 @@ export const Route = createRootRoute({
88 }
89
90 const authGateState = await resolveInitialServerAuthGateState();
91 + if (authGateState.status === "authenticated") {
92 + // Idempotent, so every navigation can ask for it.
93 + void configureClientTracing();
94 + }
95 if (
96 authGateState.status === "authenticated" &&
97 getDesktopSnapShotBridge() &&
@@ -155,7 +140,6 @@ function RootRouteView() {
140 }
141
142 function RootRouteBranch() {
158 - useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
143 const pathname = useLocation({ select: (location) => location.pathname });
144 const { authGateState } = Route.useRouteContext();
145 const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
@@ -169,29 +153,17 @@ function RootRouteBranch() {
153 if (pathname === GUEST_PAGE_PATH) return <Outlet />;
154
155 if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
172 - return (
173 - <>
174 - <BrowserChromeThemeSync key={pathname} />
175 - <Outlet />
176 - </>
177 - );
156 + return <Outlet />;
157 }
158
159 // Handle links before onboarding redirects lose them.
160 if (hostedPromptLinkLanding !== null) {
182 - return (
183 - <>
184 - <BrowserChromeThemeSync key={pathname} />
185 - {hostedPromptLinkLanding}
186 - </>
187 - );
161 + return hostedPromptLinkLanding;
162 }
163
164 if (pathname === "/welcome") {
165 return (
166 <>
193 - <BrowserChromeThemeSync key={pathname} />
194 - <EnvironmentThemeSync />
167 <CustomSnoozeDialogHost />
168 <GuestShareDialogHost />
169 <CommandPalette>
@@ -204,12 +176,7 @@ function RootRouteBranch() {
176 }
177
178 if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
207 - return (
208 - <>
209 - <BrowserChromeThemeSync key={pathname} />
210 - <Outlet />
211 - </>
212 - );
179 + return <Outlet />;
180 }
181
182 const appShell = (
@@ -222,14 +189,11 @@ function RootRouteBranch() {
189
190 return (
191 <>
225 - <BrowserChromeThemeSync key={pathname} />
226 - <EnvironmentThemeSync />
192 <ChatGptWelcomeCoordinator />
193 <FirstRunGate
194 enabled={primaryEnvironmentAuthenticated}
195 hostedStatic={authGateState.status === "hosted-static"}
196 >
232 - {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
197 {primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
198 {primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
199 {isElectron ? <RunningThreadKeepAlive /> : null}
@@ -241,10 +205,8 @@ function RootRouteBranch() {
205 <ConfirmDialogHost />
206 <CustomSnoozeDialogHost />
207 <GuestShareDialogHost />
244 - <SlowRpcRequestToastCoordinator />
208 <ProjectCloneToastCoordinator />
209 <AddProjectToMachineDialogHost />
247 - <HostedStaticEnvironmentBootstrap />
210 {primaryEnvironmentAuthenticated ? (
211 <EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
212 ) : null}
@@ -256,52 +218,6 @@ function RootRouteBranch() {
218 );
219 }
220
259 -function EnvironmentThemeSync() {
260 - useEnvironmentThemeSync();
261 - return null;
262 -}
263 -
264 -// Each route paints its own surface for browser chrome to sample.
265 -function BrowserChromeThemeSync() {
266 - useEffect(() => {
267 - const frame = window.requestAnimationFrame(() => {
268 - syncBrowserChromeTheme();
269 - });
270 - return () => {
271 - window.cancelAnimationFrame(frame);
272 - };
273 - }, []);
274 - return null;
275 -}
276 -
277 -function HostedStaticEnvironmentBootstrap() {
278 - const { environments } = useEnvironments();
279 - const activeEnvironmentId = useActiveEnvironmentId();
280 -
281 - useEffect(() => {
282 - if (
283 - environments.some(
284 - (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
285 - )
286 - ) {
287 - return;
288 - }
289 -
290 - if (activeEnvironmentId) {
291 - return;
292 - }
293 -
294 - const firstSavedEnvironment = environments[0];
295 - if (!firstSavedEnvironment) {
296 - return;
297 - }
298 -
299 - setActiveEnvironmentId(firstSavedEnvironment.environmentId);
300 - }, [activeEnvironmentId, environments]);
301 -
302 - return null;
303 -}
304 -
221 function RootRouteErrorView({ error }: ErrorComponentProps) {
222 const router = useRouter();
223 const message = errorMessage(error);
@@ -395,14 +311,6 @@ function errorReport(error: unknown, pathname: string): string {
311 return lines.join("\n");
312 }
313
398 -function AuthenticatedTracingBootstrap() {
399 - useEffect(() => {
400 - void configureClientTracing();
401 - }, []);
402 -
403 - return null;
404 -}
405 -
314 function EventRouter({
315 skipInitialBootstrapNavigation,
316 }: {
@@ -411,22 +319,15 @@ function EventRouter({
319 const navigate = useNavigate();
320 const pathname = useLocation({ select: (loc) => loc.pathname });
321 const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
414 - const primaryEnvironment = usePrimaryEnvironment();
322 const serverConfig = useAtomValue(primaryServerConfigAtom);
416 - const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
323 const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
324 const readPathname = useEffectEvent(() => pathname);
325 const handledBootstrapThreadIdRef = useRef<string | null>(null);
326 const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
421 - const handledConfigEventRef = useRef(serverConfigEvent);
422 - const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
423 - createKeybindingsUpdateToastController({}),
424 - );
327
328 const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
329 if (!payload) return;
330
429 - setActiveEnvironmentId(payload.environment.environmentId);
331 void (async () => {
332 if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
333 return;
@@ -469,56 +370,9 @@ function EventRouter({
370 })().catch(() => undefined);
371 });
372
472 - const handleServerConfigUpdated = useEffectEvent(() => {
473 - const decision = keybindingsToastController.handle(serverConfigEvent);
474 - if (!decision) {
475 - return;
476 - }
477 -
478 - if (decision._tag === "Success") {
479 - toastManager.add({
480 - type: "success",
481 - title: "Keybindings updated",
482 - description: "Keybindings configuration reloaded successfully.",
483 - });
484 - return;
485 - }
486 -
487 - toastManager.add(
488 - stackedThreadToast({
489 - type: "warning",
490 - title: "Invalid keybindings configuration",
491 - description: (
492 - <KeybindingsConfigWarning
493 - message={decision.message}
494 - environmentId={primaryEnvironment?.environmentId ?? null}
495 - configPath={serverConfig?.keybindingsConfigPath ?? null}
496 - availableEditors={serverConfig?.availableEditors ?? []}
497 - />
498 - ),
499 - }),
500 - );
501 - });
502 -
503 - useEffect(() => {
504 - if (!serverConfig) {
505 - return;
506 - }
507 -
508 - setActiveEnvironmentId(serverConfig.environment.environmentId);
509 - }, [serverConfig]);
510 -
373 useEffect(() => {
374 handleWelcome(serverWelcome);
375 }, [serverWelcome]);
376
515 - useEffect(() => {
516 - if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
517 - return;
518 - }
519 - handledConfigEventRef.current = serverConfigEvent;
520 - handleServerConfigUpdated();
521 - }, [serverConfigEvent]);
522 -
377 return null;
378 }
apps/web/src/rpc/atomRegistry.ts
+23 -1
@@ -1,5 +1,5 @@
1 import { RegistryContext } from "@effect/atom-react";
2 -import { AtomRegistry } from "effect/reactivity";
2 +import { type Atom, AtomRegistry } from "effect/reactivity";
3 import { createElement } from "react";
4
5 export const appAtomRegistry = AtomRegistry.make();
@@ -7,3 +7,25 @@ export const appAtomRegistry = AtomRegistry.make();
7 export function AppAtomRegistryProvider({ children }: React.PropsWithChildren) {
8 return createElement(RegistryContext.Provider, { value: appAtomRegistry }, children);
9 }
10 +
11 +/**
12 + * Calls `listener` with each value after the current one. A bare `subscribe` never computes a
13 + * derived atom nobody has read, so it never learns its parents and never fires.
14 + */
15 +export function subscribeAtomChanges<A>(
16 + atom: Atom.Atom<A>,
17 + listener: (value: A) => void,
18 +): () => void {
19 + let current = true;
20 + return appAtomRegistry.subscribe(
21 + atom,
22 + (value) => {
23 + if (current) {
24 + current = false;
25 + return;
26 + }
27 + listener(value);
28 + },
29 + { immediate: true },
30 + );
31 +}
apps/web/src/rpc/requestLatencyState.ts
+4 -3
@@ -1,4 +1,3 @@
1 -import { useAtomValue } from "@effect/atom-react";
1 import { WS_METHODS } from "@t3tools/contracts";
2 import { Atom } from "effect/reactivity";
3
@@ -136,6 +135,8 @@ function evictOldestPendingRpcRequestIfNeeded(): void {
135 }
136 }
137
139 -export function useSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
140 - return useAtomValue(slowRpcAckRequestsAtom);
138 +export function subscribeSlowRpcAckRequests(
139 + listener: (requests: ReadonlyArray<SlowRpcAckRequest>) => void,
140 +): () => void {
141 + return appAtomRegistry.subscribe(slowRpcAckRequestsAtom, listener);
142 }
apps/web/src/state/entities.ts
-13
@@ -75,19 +75,6 @@ const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HIST
75 Atom.withLabel("web-thread-history:empty"),
76 );
77
78 -const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
79 - Atom.keepAlive,
80 - Atom.withLabel("web-active-environment-id"),
81 -);
82 -
83 -export function useActiveEnvironmentId(): EnvironmentId | null {
84 - return useAtomValue(activeEnvironmentIdAtom);
85 -}
86 -
87 -export function setActiveEnvironmentId(environmentId: EnvironmentId | null): void {
88 - appAtomRegistry.set(activeEnvironmentIdAtom, environmentId);
89 -}
90 -
78 export function useThreadRefs(enabled = true): ReadonlyArray<ScopedThreadRef> {
79 return useAtomValue(enabled ? environmentThreadShells.threadRefsAtom : EMPTY_THREAD_REFS_ATOM);
80 }
apps/web/src/themePalette.ts
+100 -14
@@ -1,5 +1,8 @@
1 +import type { EnvironmentTheme } from "@t3tools/contracts";
2 import * as Equal from "effect/Equal";
3 +import * as Option from "effect/Option";
4 import * as Schema from "effect/Schema";
5 +import { Atom } from "effect/reactivity";
6 import "culori/css";
7 import { converter, parse } from "culori/fn";
8 import {
@@ -20,6 +23,9 @@ import {
23 type ThemeVariants,
24 } from "@t3tools/shared/themePalettes";
25
26 +import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
27 +import { primaryServerEnvironmentThemesAtom } from "./state/server";
28 +
29 export { EMBER_THEME, GROVE_THEME, IRIS_THEME, OCEAN_THEME, T3_CHAT_THEME, THEME_COLOR_ROLES };
30 export type { ThemeAppearance, ThemeColorRole, ThemeColors, ThemeDefinition, ThemeVariants };
31
@@ -55,9 +61,6 @@ export type ThemeFile = Readonly<{
61 managed?: boolean;
62 }>;
63
58 -// Do not persist server-published palettes; they become stale when the environment theme changes.
59 -let environmentThemeDefinitions: ReadonlyArray<ThemeDefinition> = [];
60 -
64 const customThemeListeners = new Set<() => void>();
65 type CustomThemeLibrarySnapshot =
66 | Readonly<{
@@ -120,7 +123,7 @@ function parseThemeCollection(value: unknown): ThemeCollection | undefined {
123 : undefined;
124 }
125
123 -export function lenientThemeColorOverrides(
126 +function lenientThemeColorOverrides(
127 value: Readonly<Record<string, unknown>>,
128 ): Partial<Record<ThemeColorRole, string>> {
129 const overrides: Partial<Record<ThemeColorRole, string>> = {};
@@ -236,16 +239,92 @@ export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {
239 return snapshot.status === "ready" ? snapshot.themes : EMPTY_CUSTOM_THEMES;
240 }
241
239 -export function getEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
240 - return environmentThemeDefinitions;
242 +function publishedThemeColors(
243 + theme: EnvironmentTheme,
244 + appearance: ThemeAppearance,
245 + colors: Readonly<Record<string, string>> | undefined,
246 +): ThemeColors {
247 + // A variant builds on that appearance's stock defaults: the generator follows
248 + // the seed canvas's luminance, so dark seeds would give a light variant
249 + // unreadable colors.
250 + const base =
251 + appearance === theme.appearance && theme.canvas !== undefined && theme.accent !== undefined
252 + ? createVividThemeColors(appearance, theme.canvas, theme.accent)
253 + : getDefaultThemeColors(appearance);
254 + return { ...base, ...lenientThemeColorOverrides(colors ?? {}) };
255 }
256
243 -/** Returns structural change; reconnects recreate arrays with identical colors. */
244 -export function setEnvironmentThemes(themes: ReadonlyArray<ThemeDefinition>): boolean {
245 - if (Equal.equals(environmentThemeDefinitions, themes)) return false;
246 - environmentThemeDefinitions = themes;
247 - notifyCustomThemeListeners();
248 - return true;
257 +function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
258 + const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
259 + for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {
260 + if (variantAppearance === theme.appearance) continue;
261 + variants[variantAppearance as ThemeAppearance] = publishedThemeColors(
262 + theme,
263 + variantAppearance as ThemeAppearance,
264 + variantColors,
265 + );
266 + }
267 +
268 + return {
269 + id: theme.id,
270 + label: theme.name,
271 + appearance: theme.appearance,
272 + colors: publishedThemeColors(theme, theme.appearance, theme.colors),
273 + ...(Object.keys(variants).length > 0 ? { variants } : {}),
274 + // Only the pure seeded form is guided-generator output. An exported file,
275 + // or seeds carrying explicit role overrides, must open Duplicate in the
276 + // advanced editor -- the guided one regenerates from canvas and accent and
277 + // would discard whatever the machine hand-tuned.
278 + ...(theme.canvas !== undefined &&
279 + theme.accent !== undefined &&
280 + theme.colors === undefined &&
281 + theme.variants === undefined
282 + ? { managed: true }
283 + : {}),
284 + };
285 +}
286 +
287 +/**
288 + * Published palettes this client can render. Reserved ids are dropped here rather
289 + * than rendered: a published `t3-iris.json` would show this palette on its
290 + * card while "Use" resolved the built-in, and a published `dark.json` would
291 + * capture everyone whose stored preference is the stock `"dark"`.
292 + */
293 +export function publishedThemeDefinitions(
294 + themes: ReadonlyArray<EnvironmentTheme>,
295 +): ReadonlyArray<ThemeDefinition> {
296 + return themes
297 + .filter((theme) => {
298 + if (isReservedThemeId(theme.id)) return false;
299 + if (theme.canvas !== undefined && theme.accent !== undefined) return true;
300 + const otherAppearance = theme.appearance === "dark" ? "light" : "dark";
301 + return [theme.colors, theme.variants?.[otherAppearance]].some(
302 + (colors) =>
303 + colors !== undefined && Object.keys(lenientThemeColorOverrides(colors)).length > 0,
304 + );
305 + })
306 + .map(environmentThemeDefinition);
307 +}
308 +
309 +// Every reconnect snapshot delivers a fresh but usually identical array; keeping the
310 +// previous one skips regenerating palettes and repainting the document for it.
311 +const publishedThemesAtom = Atom.make((get): ReadonlyArray<EnvironmentTheme> => {
312 + const next = get(primaryServerEnvironmentThemesAtom);
313 + const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentTheme>>());
314 + return previous !== null && Equal.equals(previous, next) ? previous : next;
315 +}).pipe(Atom.withLabel("web-published-environment-themes"));
316 +
317 +/**
318 + * The environment's palettes are not saved: they are republished by the server
319 + * on every change and would go stale the moment the machine's theme moved on.
320 + * Kept alive because theme lookups read it outside React on every repaint.
321 + */
322 +export const environmentThemeDefinitionsAtom = Atom.make((get) =>
323 + publishedThemeDefinitions(get(publishedThemesAtom)),
324 +).pipe(Atom.keepAlive, Atom.withLabel("web-environment-theme-definitions"));
325 +
326 +function getEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
327 + return appAtomRegistry.get(environmentThemeDefinitionsAtom);
328 }
329
330 export function isReservedThemeId(themeId: string): boolean {
@@ -262,8 +341,14 @@ export function getStoredCustomThemeCollection(
341
342 export function subscribeToCustomThemes(listener: () => void): () => void {
343 customThemeListeners.add(listener);
344 + const unsubscribeEnvironment = subscribeAtomChanges(environmentThemeDefinitionsAtom, () =>
345 + listener(),
346 + );
347 if (typeof window === "undefined") {
266 - return () => customThemeListeners.delete(listener);
348 + return () => {
349 + customThemeListeners.delete(listener);
350 + unsubscribeEnvironment();
351 + };
352 }
353 const handleStorage = (event: StorageEvent) => {
354 if (event.key === CUSTOM_THEMES_STORAGE_KEY || event.key === null) {
@@ -274,6 +359,7 @@ export function subscribeToCustomThemes(listener: () => void): () => void {
359
360 return () => {
361 customThemeListeners.delete(listener);
362 + unsubscribeEnvironment();
363 window.removeEventListener("storage", handleStorage);
364 };
365 }
@@ -1022,7 +1108,7 @@ export function getThemeDefinition(theme: ThemePreference): ThemeDefinition | nu
1108 return (
1109 BUILT_IN_THEME_DEFINITIONS.find((definition) => definition.id === themeId) ??
1110 getCustomThemes().find((definition) => definition.id === themeId) ??
1025 - environmentThemeDefinitions.find((definition) => definition.id === themeId) ??
1111 + getEnvironmentThemes().find((definition) => definition.id === themeId) ??
1112 null
1113 );
1114 }