Skip to content
TypeScript

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

Julius Marminge148d2fdc0ee0
diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx
index 55cea5c1146..9c1170daf75 100644
--- a/apps/web/src/appInit.tsx
+++ b/apps/web/src/appInit.tsx
@@ -9,11 +9,13 @@ import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRe
import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
+import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
+import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
@@ -21,12 +23,15 @@ import { resolveServerBackedAppDisplayName } from "./branding.logic";
import { isElectron } from "./env";
import { useComposerDraftStore } from "./composerDraftStore";
import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
+import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
import {
getClientSettings,
startModelPreferencesMigration,
subscribeClientSettings,
} from "./hooks/useSettings";
+import { syncBrowserChromeTheme } from "./hooks/useTheme";
import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
+import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
import {
syncDocumentElectronPlatformClasses,
syncDocumentWindowControlsOverlayClass,
@@ -104,6 +109,17 @@ function startDocumentTitle(): void {
);
}
+/**
+ * Each route paints its own surface, which the browser chrome samples once it is on screen.
+ * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
+ * can swap the root between the bare outlet and the shell at the same address.
+ */
+function startBrowserChromeThemeSync(router: AppRouter): void {
+ const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
+ router.subscribe("onRendered", resync);
+ router.subscribe("onResolved", resync);
+}
+
/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
function startThreadOverlayRetention(router: AppRouter): void {
router.subscribe("onResolved", () => {
@@ -138,8 +154,12 @@ export function startAppServices(): AppRouter {
syncDocumentWindowControlsOverlayClass();
}
+ installDesktopPasteAsText(window.desktopBridge, window);
+
startClientAppearance();
startDocumentTitle();
+ startEnvironmentThemeRepaint();
+ startBrowserChromeThemeSync(router);
startDefaultThemeAdoption();
startModelPreferencesMigration();
startAgentOpenedPreviews();
@@ -150,6 +170,8 @@ export function startAppServices(): AppRouter {
startThreadVisitedMigration(appAtomRegistry);
startSshPasswordPromptQueue();
+ startKeybindingsUpdateToasts();
+ startSlowRpcRequestToasts();
startHostFreezeToasts();
startLegacyThreadMigrationToast();
startPermissionUpdateNotices(router);
diff --git a/apps/web/src/components/KeybindingsUpdateToast.test.ts b/apps/web/src/components/KeybindingsUpdateToast.test.ts
new file mode 100644
index 00000000000..01cb26c3f7e
--- /dev/null
+++ b/apps/web/src/components/KeybindingsUpdateToast.test.ts
@@ -0,0 +1,65 @@
+import type { ServerConfigStreamEvent } from "@t3tools/contracts";
+import { describe, expect, it, vi } from "vite-plus/test";
+
+const mocks = vi.hoisted(() => ({
+ state: null as unknown as import("effect/reactivity").Atom.Writable<{
+ readonly latestEvent: ServerConfigStreamEvent | null;
+ }>,
+ addToast: vi.fn<(toast: { readonly title?: unknown }) => void>(),
+}));
+
+// The event atom is derived from server state, as in production; nothing else reads it.
+vi.mock(import("../state/server"), async () => {
+ const { Atom } = await import("effect/reactivity");
+ mocks.state = Atom.make<{ readonly latestEvent: ServerConfigStreamEvent | null }>({
+ latestEvent: null,
+ });
+ return {
+ primaryServerConfigAtom: Atom.make(null),
+ primaryServerConfigEventAtom: Atom.make((get) => get(mocks.state).latestEvent),
+ } as never;
+});
+vi.mock(import("../state/primaryEnvironment"), async () => {
+ const { Atom } = await import("effect/reactivity");
+ return { primaryEnvironmentIdAtom: Atom.make(null) } as never;
+});
+vi.mock(
+ import("./KeybindingsConfigWarning"),
+ () => ({ KeybindingsConfigWarning: () => null }) as never,
+);
+vi.mock(
+ import("./ui/toast"),
+ () =>
+ ({
+ toastManager: { add: mocks.addToast },
+ stackedThreadToast: (toast: unknown) => toast,
+ }) as never,
+);
+
+import { appAtomRegistry } from "../rpc/atomRegistry";
+import { startKeybindingsUpdateToasts } from "./KeybindingsUpdateToast";
+
+function keybindingsUpdated(issues: ReadonlyArray<unknown>): ServerConfigStreamEvent {
+ return { type: "keybindingsUpdated", payload: { keybindings: [], issues } } as never;
+}
+
+describe("startKeybindingsUpdateToasts", () => {
+ it("toasts reloads the server reports after start", () => {
+ const stop = startKeybindingsUpdateToasts();
+ try {
+ appAtomRegistry.set(mocks.state, { latestEvent: keybindingsUpdated([]) });
+ appAtomRegistry.set(mocks.state, {
+ latestEvent: keybindingsUpdated([
+ { kind: "keybindings.malformed-config", message: "Unexpected token" },
+ ]),
+ });
+
+ expect(mocks.addToast.mock.calls.map(([toast]) => toast.title)).toEqual([
+ "Keybindings updated",
+ "Invalid keybindings configuration",
+ ]);
+ } finally {
+ stop();
+ }
+ });
+});
diff --git a/apps/web/src/components/KeybindingsUpdateToast.tsx b/apps/web/src/components/KeybindingsUpdateToast.tsx
new file mode 100644
index 00000000000..63702210b7e
--- /dev/null
+++ b/apps/web/src/components/KeybindingsUpdateToast.tsx
@@ -0,0 +1,40 @@
+import { appAtomRegistry, subscribeAtomChanges } from "../rpc/atomRegistry";
+import { primaryEnvironmentIdAtom } from "../state/primaryEnvironment";
+import { primaryServerConfigAtom, primaryServerConfigEventAtom } from "../state/server";
+import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
+import { createKeybindingsUpdateToastController } from "./KeybindingsUpdateToast.logic";
+import { stackedThreadToast, toastManager } from "./ui/toast";
+
+/** Toasts each keybindings reload the primary server reports. */
+export function startKeybindingsUpdateToasts(): () => void {
+ const controller = createKeybindingsUpdateToastController({});
+ return subscribeAtomChanges(primaryServerConfigEventAtom, (event) => {
+ const decision = controller.handle(event);
+ if (!decision) return;
+
+ if (decision._tag === "Success") {
+ toastManager.add({
+ type: "success",
+ title: "Keybindings updated",
+ description: "Keybindings configuration reloaded successfully.",
+ });
+ return;
+ }
+
+ const serverConfig = appAtomRegistry.get(primaryServerConfigAtom);
+ toastManager.add(
+ stackedThreadToast({
+ type: "warning",
+ title: "Invalid keybindings configuration",
+ description: (
+ <KeybindingsConfigWarning
+ message={decision.message}
+ environmentId={appAtomRegistry.get(primaryEnvironmentIdAtom)}
+ configPath={serverConfig?.keybindingsConfigPath ?? null}
+ availableEditors={serverConfig?.availableEditors ?? []}
+ />
+ ),
+ }),
+ );
+ });
+}
diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
index 28c4a34ff88..c388ec33af0 100644
--- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
+++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
@@ -47,7 +47,10 @@ vi.mock(import("../connection/catalog"), async (original) => {
...actual,
environmentCatalog: {
...actual.environmentCatalog,
- catalogValueAtom: Atom.make({ isReady: true, entries: new Map([["remote", {}]]) }) as never,
+ catalogValueAtom: Atom.make({
+ isReady: true,
+ entries: new Map([["remote", { target: { _tag: "DirectConnectionTarget" } }]]),
+ }) as never,
},
};
});
diff --git a/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx b/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx
index 2300ad7aaf5..4536987ab3b 100644
--- a/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx
+++ b/apps/web/src/components/SlowRpcRequestToastCoordinator.tsx
@@ -1,6 +1,4 @@
-import { useEffect, useRef } from "react";
-
-import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
+import { type SlowRpcAckRequest, subscribeSlowRpcAckRequests } from "../rpc/requestLatencyState";
import { toastManager } from "./ui/toast";
function describeSlowRequests(requests: ReadonlyArray<SlowRpcAckRequest>): string {
@@ -30,15 +28,15 @@ function SlowRequestDetails({ requests }: { requests: ReadonlyArray<SlowRpcAckRe
);
}
-export function SlowRpcRequestToastCoordinator() {
- const slowRequests = useSlowRpcAckRequests();
- const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
+/** One warning toast that tracks the set of slow requests while any are outstanding. */
+export function startSlowRpcRequestToasts(): () => void {
+ let toastId: ReturnType<typeof toastManager.add> | null = null;
- useEffect(() => {
+ const unsubscribe = subscribeSlowRpcAckRequests((slowRequests) => {
if (slowRequests.length === 0) {
- if (toastIdRef.current !== null) {
- toastManager.close(toastIdRef.current);
- toastIdRef.current = null;
+ if (toastId !== null) {
+ toastManager.close(toastId);
+ toastId = null;
}
return;
}
@@ -55,21 +53,15 @@ export function SlowRpcRequestToastCoordinator() {
type: "warning" as const,
};
- if (toastIdRef.current === null) {
- toastIdRef.current = toastManager.add(nextToast);
+ if (toastId === null) {
+ toastId = toastManager.add(nextToast);
} else {
- toastManager.update(toastIdRef.current, nextToast);
+ toastManager.update(toastId, nextToast);
}
- }, [slowRequests]);
-
- useEffect(
- () => () => {
- if (toastIdRef.current !== null) {
- toastManager.close(toastIdRef.current);
- }
- },
- [],
- );
+ });
- return null;
+ return () => {
+ unsubscribe();
+ if (toastId !== null) toastManager.close(toastId);
+ };
}
diff --git a/apps/web/src/hooks/useEnvironmentTheme.test.ts b/apps/web/src/hooks/useEnvironmentTheme.test.ts
index 16ceb4e8c08..80b8fcbc216 100644
--- a/apps/web/src/hooks/useEnvironmentTheme.test.ts
+++ b/apps/web/src/hooks/useEnvironmentTheme.test.ts
@@ -1,11 +1,25 @@
+import type { EnvironmentTheme } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
-import { environmentThemeDefinition, publishedThemeDefinitions } from "./useEnvironmentTheme";
+const publishedThemes = vi.hoisted(() => ({
+ atom: null as unknown as import("effect/reactivity").Atom.Writable<
+ ReadonlyArray<EnvironmentTheme>
+ >,
+}));
+vi.mock(import("../state/server"), async () => {
+ const { Atom } = await import("effect/reactivity");
+ publishedThemes.atom = Atom.make<ReadonlyArray<EnvironmentTheme>>([]);
+ return { primaryServerEnvironmentThemesAtom: publishedThemes.atom } as never;
+});
+const refreshTheme = vi.hoisted(() => vi.fn());
+vi.mock(import("./useTheme"), () => ({ refreshTheme }) as never);
+
+import { appAtomRegistry } from "../rpc/atomRegistry";
import {
getThemeDefinition,
installCustomTheme,
invalidateCustomThemes,
- setEnvironmentThemes,
+ publishedThemeDefinitions,
} from "../themePalette";
const NIGHTFALL_THEME = {
@@ -17,7 +31,7 @@ const NIGHTFALL_THEME = {
} as const;
afterEach(() => {
- setEnvironmentThemes([]);
+ appAtomRegistry.set(publishedThemes.atom, []);
});
describe("environment themes", () => {
@@ -72,6 +86,15 @@ describe("environment themes", () => {
]);
});
+ // Routes without the old root sync component (/connect, prompt-link landings) never saw them.
+ it("resolves published themes without a React subscriber mounted", () => {
+ appAtomRegistry.set(publishedThemes.atom, [NIGHTFALL_THEME]);
+ expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
+
+ appAtomRegistry.set(publishedThemes.atom, [{ ...NIGHTFALL_THEME, name: "Nightfall 2" }]);
+ expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall 2");
+ });
+
it("lets a theme the user saved win an id collision", () => {
const store = new Map<string, string>();
vi.stubGlobal("window", {
@@ -85,8 +108,10 @@ describe("environment themes", () => {
});
invalidateCustomThemes();
try {
- const environment = environmentThemeDefinition(NIGHTFALL_THEME);
- setEnvironmentThemes([environment]);
+ appAtomRegistry.set(publishedThemes.atom, [NIGHTFALL_THEME]);
+ expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
+ const environment = getThemeDefinition("nightfall");
+ if (!environment) throw new Error("expected the published theme");
installCustomTheme({ ...environment, label: "My Nightfall" });
expect(getThemeDefinition("nightfall")?.label).toBe("My Nightfall");
@@ -96,4 +121,17 @@ describe("environment themes", () => {
}
expect(getThemeDefinition("nightfall")?.label).toBe("Nightfall");
});
+
+ it("repaints when the environment publishes themes nothing has read yet", async () => {
+ vi.resetModules();
+ const { appAtomRegistry: registry } = await import("../rpc/atomRegistry");
+ const { startEnvironmentThemeRepaint } = await import("./useEnvironmentTheme");
+ const stop = startEnvironmentThemeRepaint();
+ try {
+ registry.set(publishedThemes.atom, [NIGHTFALL_THEME]);
+ expect(refreshTheme).toHaveBeenCalledTimes(1);
+ } finally {
+ stop();
+ }
+ });
});
diff --git a/apps/web/src/hooks/useEnvironmentTheme.ts b/apps/web/src/hooks/useEnvironmentTheme.ts
index 5f1a3d19ea5..ac13e38fa15 100644
--- a/apps/web/src/hooks/useEnvironmentTheme.ts
+++ b/apps/web/src/hooks/useEnvironmentTheme.ts
@@ -1,96 +1,19 @@
-import type { EnvironmentTheme } from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
-import * as Equal from "effect/Equal";
-import { useEffect, useRef, useSyncExternalStore } from "react";
-import { primaryServerEnvironmentThemesAtom } from "../state/server";
-import {
- createVividThemeColors,
- getDefaultThemeColors,
- getEnvironmentThemes,
- isReservedThemeId,
- lenientThemeColorOverrides,
- setEnvironmentThemes,
- subscribeToCustomThemes,
- type ThemeAppearance,
- type ThemeColors,
- type ThemeDefinition,
-} from "../themePalette";
-import { useTheme } from "./useTheme";
-
-function publishedThemeColors(
- theme: EnvironmentTheme,
- appearance: ThemeAppearance,
- colors: Readonly<Record<string, string>> | undefined,
-): ThemeColors {
- // The generator follows canvas luminance; dark seeds would make a light variant unreadable.
- const base =
- appearance === theme.appearance && theme.canvas !== undefined && theme.accent !== undefined
- ? createVividThemeColors(appearance, theme.canvas, theme.accent)
- : getDefaultThemeColors(appearance);
- return { ...base, ...lenientThemeColorOverrides(colors ?? {}) };
-}
-
-export function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
- const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
- for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {
- if (variantAppearance === theme.appearance) continue;
- variants[variantAppearance as ThemeAppearance] = publishedThemeColors(
- theme,
- variantAppearance as ThemeAppearance,
- variantColors,
- );
- }
-
- return {
- id: theme.id,
- label: theme.name,
- appearance: theme.appearance,
- colors: publishedThemeColors(theme, theme.appearance, theme.colors),
- ...(Object.keys(variants).length > 0 ? { variants } : {}),
- // Guided editing regenerates from seeds, so hand-tuned role overrides must use the advanced editor.
- ...(theme.canvas !== undefined &&
- theme.accent !== undefined &&
- theme.colors === undefined &&
- theme.variants === undefined
- ? { managed: true }
- : {}),
- };
-}
-
-/** Filters reserved ids that would select built-ins instead of the published palette. */
-export function publishedThemeDefinitions(
- themes: ReadonlyArray<EnvironmentTheme>,
-): ReadonlyArray<ThemeDefinition> {
- return themes
- .filter((theme) => {
- if (isReservedThemeId(theme.id)) return false;
- if (theme.canvas !== undefined && theme.accent !== undefined) return true;
- const otherAppearance = theme.appearance === "dark" ? "light" : "dark";
- return [theme.colors, theme.variants?.[otherAppearance]].some(
- (colors) =>
- colors !== undefined && Object.keys(lenientThemeColorOverrides(colors)).length > 0,
- );
- })
- .map(environmentThemeDefinition);
-}
+import { subscribeAtomChanges } from "../rpc/atomRegistry";
+import { environmentThemeDefinitionsAtom, type ThemeDefinition } from "../themePalette";
+import { refreshTheme } from "./useTheme";
export function useEnvironmentThemeDefinitions(): ReadonlyArray<ThemeDefinition> {
- return useSyncExternalStore(subscribeToCustomThemes, getEnvironmentThemes, () => []);
+ return useAtomValue(environmentThemeDefinitionsAtom);
}
-export function useEnvironmentThemeSync(): void {
- const published = useAtomValue(primaryServerEnvironmentThemesAtom);
- const { refreshTheme } = useTheme();
- const lastPublished = useRef<ReadonlyArray<EnvironmentTheme> | null>(null);
-
- useEffect(() => {
- if (lastPublished.current !== null && Equal.equals(lastPublished.current, published)) return;
- lastPublished.current = published;
-
- // Active palettes are snapshots; changed colors require reapplying the theme.
- if (setEnvironmentThemes(publishedThemeDefinitions(published))) {
- refreshTheme({ preservePreview: true });
- }
- }, [published, refreshTheme]);
+/**
+ * The palette is painted from a snapshot taken when the theme last changed, so new colors
+ * only land if the active theme is re-applied.
+ */
+export function startEnvironmentThemeRepaint(): () => void {
+ return subscribeAtomChanges(environmentThemeDefinitionsAtom, () => {
+ refreshTheme({ preservePreview: true });
+ });
}
diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.ts
index 9a729436f04..ddd89eea229 100644
--- a/apps/web/src/hooks/useTheme.ts
+++ b/apps/web/src/hooks/useTheme.ts
@@ -626,7 +626,7 @@ function clearThemeHalves(): boolean {
return true;
}
-function refreshTheme({ preservePreview = false } = {}): void {
+export function refreshTheme({ preservePreview = false } = {}): void {
if (typeof window === "undefined") return;
lastAppliedTheme = null;
applyTheme(getStored(), { suppressTransitions: true, preservePreview });
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index 9188aaaffc2..7444b3623dc 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -20,7 +20,6 @@ import { CustomSnoozeDialogHost } from "../components/CustomSnoozeDialog";
import { GuestShareDialogHost } from "../components/chat/GuestShareControls";
import { AddProjectToMachineDialogHost } from "../components/AddProjectToMachineDialog";
import { ConfirmDialogHost } from "../components/ConfirmDialogHost";
-import { KeybindingsConfigWarning } from "../components/KeybindingsConfigWarning";
import { FirstRunGate } from "../components/onboarding/FirstRunGate";
import { ConnectOnboardingDialog } from "../components/cloud/ConnectOnboardingDialog";
import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallDialog";
@@ -31,20 +30,13 @@ import { DesktopWebLinkCoordinator } from "../components/desktop/DesktopWebLinkC
import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
import { ReopenClosedViewShortcut } from "../components/ReopenClosedViewShortcut";
import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
-import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
import { ChatGptWelcomeCoordinator } from "../components/settings/ChatGptWelcomeCoordinator";
import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
import { useCopyToClipboard } from "../hooks/useCopyToClipboard";
-import { useEnvironmentThemeSync } from "../hooks/useEnvironmentTheme";
import { Button } from "../components/ui/button";
import { MorphIcon } from "~/components/MorphIcon";
import { StandalonePage, StandalonePageHeader } from "../components/ui/standalone-page";
-import {
- AnchoredToastProvider,
- stackedThreadToast,
- ToastProvider,
- toastManager,
-} from "../components/ui/toast";
+import { AnchoredToastProvider, ToastProvider } from "../components/ui/toast";
import { isElectron } from "../env";
import { cn } from "../lib/utils";
import { useClientSettings } from "../hooks/useSettings";
@@ -54,7 +46,6 @@ import {
selectProjectGroupingSettings,
} from "../logicalProject";
import { useUiStateStore } from "../uiStateStore";
-import { syncBrowserChromeTheme } from "../hooks/useTheme";
import { configureClientTracing } from "../observability/clientTracing";
import { resolveInitialServerAuthGateState } from "../environments/primary";
import { GUEST_PAGE_PATH } from "../guestPage";
@@ -62,20 +53,10 @@ import { hasHostedPairingRequest, isHostedStaticApp } from "../hostedPairing";
import { useHostedPromptLinkLanding } from "../components/promptLinks/HostedPromptLinkLanding";
import { isLocalEnvironmentDisabled } from "../localEnvironment";
import { useAtomValue } from "@effect/atom-react";
-import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
-import {
- primaryServerConfigAtom,
- primaryServerConfigEventAtom,
- primaryServerWelcomeAtom,
-} from "../state/server";
-import { readProject, setActiveEnvironmentId, useActiveEnvironmentId } from "../state/entities";
-import {
- createKeybindingsUpdateToastController,
- type KeybindingsUpdateToastController,
-} from "../components/KeybindingsUpdateToast.logic";
+import { primaryServerConfigAtom, primaryServerWelcomeAtom } from "../state/server";
+import { readProject } from "../state/entities";
import { getDesktopSnapShotBridge } from "../lib/desktopSnapShot";
-import { installDesktopPasteAsText } from "../lib/desktopPasteAsText";
import { shouldResumeSnapShotSetupOnStartup } from "../lib/snapShotSetupResume";
export const Route = createRootRoute({
@@ -107,6 +88,10 @@ export const Route = createRootRoute({
}
const authGateState = await resolveInitialServerAuthGateState();
+ if (authGateState.status === "authenticated") {
+ // Idempotent, so every navigation can ask for it.
+ void configureClientTracing();
+ }
if (
authGateState.status === "authenticated" &&
getDesktopSnapShotBridge() &&
@@ -155,7 +140,6 @@ function RootRouteView() {
}
function RootRouteBranch() {
- useEffect(() => installDesktopPasteAsText(window.desktopBridge, window), []);
const pathname = useLocation({ select: (location) => location.pathname });
const { authGateState } = Route.useRouteContext();
const primaryEnvironmentAuthenticated = authGateState.status === "authenticated";
@@ -169,29 +153,17 @@ function RootRouteBranch() {
if (pathname === GUEST_PAGE_PATH) return <Outlet />;
if (pathname === "/pair" || pathname === "/connect" || pathname === "/connect-agent") {
- return (
- <>
- <BrowserChromeThemeSync key={pathname} />
- <Outlet />
- </>
- );
+ return <Outlet />;
}
// Handle links before onboarding redirects lose them.
if (hostedPromptLinkLanding !== null) {
- return (
- <>
- <BrowserChromeThemeSync key={pathname} />
- {hostedPromptLinkLanding}
- </>
- );
+ return hostedPromptLinkLanding;
}
if (pathname === "/welcome") {
return (
<>
- <BrowserChromeThemeSync key={pathname} />
- <EnvironmentThemeSync />
<CustomSnoozeDialogHost />
<GuestShareDialogHost />
<CommandPalette>
@@ -204,12 +176,7 @@ function RootRouteBranch() {
}
if (authGateState.status !== "authenticated" && authGateState.status !== "hosted-static") {
- return (
- <>
- <BrowserChromeThemeSync key={pathname} />
- <Outlet />
- </>
- );
+ return <Outlet />;
}
const appShell = (
@@ -222,14 +189,11 @@ function RootRouteBranch() {
return (
<>
- <BrowserChromeThemeSync key={pathname} />
- <EnvironmentThemeSync />
<ChatGptWelcomeCoordinator />
<FirstRunGate
enabled={primaryEnvironmentAuthenticated}
hostedStatic={authGateState.status === "hosted-static"}
>
- {primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}
{primaryEnvironmentAuthenticated ? <DesktopWebLinkCoordinator /> : null}
{isElectron ? <RunningThreadKeepAlive /> : null}
@@ -241,10 +205,8 @@ function RootRouteBranch() {
<ConfirmDialogHost />
<CustomSnoozeDialogHost />
<GuestShareDialogHost />
- <SlowRpcRequestToastCoordinator />
<ProjectCloneToastCoordinator />
<AddProjectToMachineDialogHost />
- <HostedStaticEnvironmentBootstrap />
{primaryEnvironmentAuthenticated ? (
<EventRouter skipInitialBootstrapNavigation={returningFromWelcome} />
) : null}
@@ -256,52 +218,6 @@ function RootRouteBranch() {
);
}
-function EnvironmentThemeSync() {
- useEnvironmentThemeSync();
- return null;
-}
-
-// Each route paints its own surface for browser chrome to sample.
-function BrowserChromeThemeSync() {
- useEffect(() => {
- const frame = window.requestAnimationFrame(() => {
- syncBrowserChromeTheme();
- });
- return () => {
- window.cancelAnimationFrame(frame);
- };
- }, []);
- return null;
-}
-
-function HostedStaticEnvironmentBootstrap() {
- const { environments } = useEnvironments();
- const activeEnvironmentId = useActiveEnvironmentId();
-
- useEffect(() => {
- if (
- environments.some(
- (environment) => environment.entry.target._tag === "PrimaryConnectionTarget",
- )
- ) {
- return;
- }
-
- if (activeEnvironmentId) {
- return;
- }
-
- const firstSavedEnvironment = environments[0];
- if (!firstSavedEnvironment) {
- return;
- }
-
- setActiveEnvironmentId(firstSavedEnvironment.environmentId);
- }, [activeEnvironmentId, environments]);
-
- return null;
-}
-
function RootRouteErrorView({ error }: ErrorComponentProps) {
const router = useRouter();
const message = errorMessage(error);
@@ -395,14 +311,6 @@ function errorReport(error: unknown, pathname: string): string {
return lines.join("\n");
}
-function AuthenticatedTracingBootstrap() {
- useEffect(() => {
- void configureClientTracing();
- }, []);
-
- return null;
-}
-
function EventRouter({
skipInitialBootstrapNavigation,
}: {
@@ -411,22 +319,15 @@ function EventRouter({
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
- const primaryEnvironment = usePrimaryEnvironment();
const serverConfig = useAtomValue(primaryServerConfigAtom);
- const serverConfigEvent = useAtomValue(primaryServerConfigEventAtom);
const serverWelcome = useAtomValue(primaryServerWelcomeAtom);
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const skipInitialBootstrapNavigationRef = useRef(skipInitialBootstrapNavigation);
- const handledConfigEventRef = useRef(serverConfigEvent);
- const [keybindingsToastController] = useState<KeybindingsUpdateToastController>(() =>
- createKeybindingsUpdateToastController({}),
- );
const handleWelcome = useEffectEvent((payload: ServerLifecycleWelcomePayload | null) => {
if (!payload) return;
- setActiveEnvironmentId(payload.environment.environmentId);
void (async () => {
if (!payload.bootstrapProjectId || !payload.bootstrapThreadId) {
return;
@@ -469,56 +370,9 @@ function EventRouter({
})().catch(() => undefined);
});
- const handleServerConfigUpdated = useEffectEvent(() => {
- const decision = keybindingsToastController.handle(serverConfigEvent);
- if (!decision) {
- return;
- }
-
- if (decision._tag === "Success") {
- toastManager.add({
- type: "success",
- title: "Keybindings updated",
- description: "Keybindings configuration reloaded successfully.",
- });
- return;
- }
-
- toastManager.add(
- stackedThreadToast({
- type: "warning",
- title: "Invalid keybindings configuration",
- description: (
- <KeybindingsConfigWarning
- message={decision.message}
- environmentId={primaryEnvironment?.environmentId ?? null}
- configPath={serverConfig?.keybindingsConfigPath ?? null}
- availableEditors={serverConfig?.availableEditors ?? []}
- />
- ),
- }),
- );
- });
-
- useEffect(() => {
- if (!serverConfig) {
- return;
- }
-
- setActiveEnvironmentId(serverConfig.environment.environmentId);
- }, [serverConfig]);
-
useEffect(() => {
handleWelcome(serverWelcome);
}, [serverWelcome]);
- useEffect(() => {
- if (serverConfigEvent === null || handledConfigEventRef.current === serverConfigEvent) {
- return;
- }
- handledConfigEventRef.current = serverConfigEvent;
- handleServerConfigUpdated();
- }, [serverConfigEvent]);
-
return null;
}
diff --git a/apps/web/src/rpc/atomRegistry.ts b/apps/web/src/rpc/atomRegistry.ts
index f78b6343f95..8865e496a6e 100644
--- a/apps/web/src/rpc/atomRegistry.ts
+++ b/apps/web/src/rpc/atomRegistry.ts
@@ -1,5 +1,5 @@
import { RegistryContext } from "@effect/atom-react";
-import { AtomRegistry } from "effect/reactivity";
+import { type Atom, AtomRegistry } from "effect/reactivity";
import { createElement } from "react";
export const appAtomRegistry = AtomRegistry.make();
@@ -7,3 +7,25 @@ export const appAtomRegistry = AtomRegistry.make();
export function AppAtomRegistryProvider({ children }: React.PropsWithChildren) {
return createElement(RegistryContext.Provider, { value: appAtomRegistry }, children);
}
+
+/**
+ * Calls `listener` with each value after the current one. A bare `subscribe` never computes a
+ * derived atom nobody has read, so it never learns its parents and never fires.
+ */
+export function subscribeAtomChanges<A>(
+ atom: Atom.Atom<A>,
+ listener: (value: A) => void,
+): () => void {
+ let current = true;
+ return appAtomRegistry.subscribe(
+ atom,
+ (value) => {
+ if (current) {
+ current = false;
+ return;
+ }
+ listener(value);
+ },
+ { immediate: true },
+ );
+}
diff --git a/apps/web/src/rpc/requestLatencyState.ts b/apps/web/src/rpc/requestLatencyState.ts
index 1e96e676adb..88990a45213 100644
--- a/apps/web/src/rpc/requestLatencyState.ts
+++ b/apps/web/src/rpc/requestLatencyState.ts
@@ -1,4 +1,3 @@
-import { useAtomValue } from "@effect/atom-react";
import { WS_METHODS } from "@t3tools/contracts";
import { Atom } from "effect/reactivity";
@@ -136,6 +135,8 @@ function evictOldestPendingRpcRequestIfNeeded(): void {
}
}
-export function useSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
- return useAtomValue(slowRpcAckRequestsAtom);
+export function subscribeSlowRpcAckRequests(
+ listener: (requests: ReadonlyArray<SlowRpcAckRequest>) => void,
+): () => void {
+ return appAtomRegistry.subscribe(slowRpcAckRequestsAtom, listener);
}
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index e137548a068..f7c5fc1d756 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -75,19 +75,6 @@ const EMPTY_THREAD_HISTORY_ATOM = Atom.make<ThreadHistoryMeta>(EMPTY_THREAD_HIST
Atom.withLabel("web-thread-history:empty"),
);
-const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
- Atom.keepAlive,
- Atom.withLabel("web-active-environment-id"),
-);
-
-export function useActiveEnvironmentId(): EnvironmentId | null {
- return useAtomValue(activeEnvironmentIdAtom);
-}
-
-export function setActiveEnvironmentId(environmentId: EnvironmentId | null): void {
- appAtomRegistry.set(activeEnvironmentIdAtom, environmentId);
-}
-
export function useThreadRefs(enabled = true): ReadonlyArray<ScopedThreadRef> {
return useAtomValue(enabled ? environmentThreadShells.threadRefsAtom : EMPTY_THREAD_REFS_ATOM);
}
diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts
index b3ed4563fd0..faae797483f 100644
--- a/apps/web/src/themePalette.ts
+++ b/apps/web/src/themePalette.ts
@@ -1,5 +1,8 @@
+import type { EnvironmentTheme } from "@t3tools/contracts";
import * as Equal from "effect/Equal";
+import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
+import { Atom } from "effect/reactivity";
import "culori/css";
import { converter, parse } from "culori/fn";
import {
@@ -20,6 +23,9 @@ import {
type ThemeVariants,
} from "@t3tools/shared/themePalettes";
+import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
+import { primaryServerEnvironmentThemesAtom } from "./state/server";
+
export { EMBER_THEME, GROVE_THEME, IRIS_THEME, OCEAN_THEME, T3_CHAT_THEME, THEME_COLOR_ROLES };
export type { ThemeAppearance, ThemeColorRole, ThemeColors, ThemeDefinition, ThemeVariants };
@@ -55,9 +61,6 @@ export type ThemeFile = Readonly<{
managed?: boolean;
}>;
-// Do not persist server-published palettes; they become stale when the environment theme changes.
-let environmentThemeDefinitions: ReadonlyArray<ThemeDefinition> = [];
-
const customThemeListeners = new Set<() => void>();
type CustomThemeLibrarySnapshot =
| Readonly<{
@@ -120,7 +123,7 @@ function parseThemeCollection(value: unknown): ThemeCollection | undefined {
: undefined;
}
-export function lenientThemeColorOverrides(
+function lenientThemeColorOverrides(
value: Readonly<Record<string, unknown>>,
): Partial<Record<ThemeColorRole, string>> {
const overrides: Partial<Record<ThemeColorRole, string>> = {};
@@ -236,16 +239,92 @@ export function getCustomThemes(): ReadonlyArray<ThemeDefinition> {
return snapshot.status === "ready" ? snapshot.themes : EMPTY_CUSTOM_THEMES;
}
-export function getEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
- return environmentThemeDefinitions;
+function publishedThemeColors(
+ theme: EnvironmentTheme,
+ appearance: ThemeAppearance,
+ colors: Readonly<Record<string, string>> | undefined,
+): ThemeColors {
+ // A variant builds on that appearance's stock defaults: the generator follows
+ // the seed canvas's luminance, so dark seeds would give a light variant
+ // unreadable colors.
+ const base =
+ appearance === theme.appearance && theme.canvas !== undefined && theme.accent !== undefined
+ ? createVividThemeColors(appearance, theme.canvas, theme.accent)
+ : getDefaultThemeColors(appearance);
+ return { ...base, ...lenientThemeColorOverrides(colors ?? {}) };
}
-/** Returns structural change; reconnects recreate arrays with identical colors. */
-export function setEnvironmentThemes(themes: ReadonlyArray<ThemeDefinition>): boolean {
- if (Equal.equals(environmentThemeDefinitions, themes)) return false;
- environmentThemeDefinitions = themes;
- notifyCustomThemeListeners();
- return true;
+function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
+ const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
+ for (const [variantAppearance, variantColors] of Object.entries(theme.variants ?? {})) {
+ if (variantAppearance === theme.appearance) continue;
+ variants[variantAppearance as ThemeAppearance] = publishedThemeColors(
+ theme,
+ variantAppearance as ThemeAppearance,
+ variantColors,
+ );
+ }
+
+ return {
+ id: theme.id,
+ label: theme.name,
+ appearance: theme.appearance,
+ colors: publishedThemeColors(theme, theme.appearance, theme.colors),
+ ...(Object.keys(variants).length > 0 ? { variants } : {}),
+ // Only the pure seeded form is guided-generator output. An exported file,
+ // or seeds carrying explicit role overrides, must open Duplicate in the
+ // advanced editor -- the guided one regenerates from canvas and accent and
+ // would discard whatever the machine hand-tuned.
+ ...(theme.canvas !== undefined &&
+ theme.accent !== undefined &&
+ theme.colors === undefined &&
+ theme.variants === undefined
+ ? { managed: true }
+ : {}),
+ };
+}
+
+/**
+ * Published palettes this client can render. Reserved ids are dropped here rather
+ * than rendered: a published `t3-iris.json` would show this palette on its
+ * card while "Use" resolved the built-in, and a published `dark.json` would
+ * capture everyone whose stored preference is the stock `"dark"`.
+ */
+export function publishedThemeDefinitions(
+ themes: ReadonlyArray<EnvironmentTheme>,
+): ReadonlyArray<ThemeDefinition> {
+ return themes
+ .filter((theme) => {
+ if (isReservedThemeId(theme.id)) return false;
+ if (theme.canvas !== undefined && theme.accent !== undefined) return true;
+ const otherAppearance = theme.appearance === "dark" ? "light" : "dark";
+ return [theme.colors, theme.variants?.[otherAppearance]].some(
+ (colors) =>
+ colors !== undefined && Object.keys(lenientThemeColorOverrides(colors)).length > 0,
+ );
+ })
+ .map(environmentThemeDefinition);
+}
+
+// Every reconnect snapshot delivers a fresh but usually identical array; keeping the
+// previous one skips regenerating palettes and repainting the document for it.
+const publishedThemesAtom = Atom.make((get): ReadonlyArray<EnvironmentTheme> => {
+ const next = get(primaryServerEnvironmentThemesAtom);
+ const previous = Option.getOrNull(get.self<ReadonlyArray<EnvironmentTheme>>());
+ return previous !== null && Equal.equals(previous, next) ? previous : next;
+}).pipe(Atom.withLabel("web-published-environment-themes"));
+
+/**
+ * The environment's palettes are not saved: they are republished by the server
+ * on every change and would go stale the moment the machine's theme moved on.
+ * Kept alive because theme lookups read it outside React on every repaint.
+ */
+export const environmentThemeDefinitionsAtom = Atom.make((get) =>
+ publishedThemeDefinitions(get(publishedThemesAtom)),
+).pipe(Atom.keepAlive, Atom.withLabel("web-environment-theme-definitions"));
+
+function getEnvironmentThemes(): ReadonlyArray<ThemeDefinition> {
+ return appAtomRegistry.get(environmentThemeDefinitionsAtom);
}
export function isReservedThemeId(themeId: string): boolean {
@@ -262,8 +341,14 @@ export function getStoredCustomThemeCollection(
export function subscribeToCustomThemes(listener: () => void): () => void {
customThemeListeners.add(listener);
+ const unsubscribeEnvironment = subscribeAtomChanges(environmentThemeDefinitionsAtom, () =>
+ listener(),
+ );
if (typeof window === "undefined") {
- return () => customThemeListeners.delete(listener);
+ return () => {
+ customThemeListeners.delete(listener);
+ unsubscribeEnvironment();
+ };
}
const handleStorage = (event: StorageEvent) => {
if (event.key === CUSTOM_THEMES_STORAGE_KEY || event.key === null) {
@@ -274,6 +359,7 @@ export function subscribeToCustomThemes(listener: () => void): () => void {
return () => {
customThemeListeners.delete(listener);
+ unsubscribeEnvironment();
window.removeEventListener("storage", handleStorage);
};
}
@@ -1022,7 +1108,7 @@ export function getThemeDefinition(theme: ThemePreference): ThemeDefinition | nu
return (
BUILT_IN_THEME_DEFINITIONS.find((definition) => definition.id === themeId) ??
getCustomThemes().find((definition) => definition.id === themeId) ??
- environmentThemeDefinitions.find((definition) => definition.id === themeId) ??
+ getEnvironmentThemes().find((definition) => definition.id === themeId) ??
null
);
}