Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

appInit.tsx

223 lines9.6 KB

1import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
2import type { ClientSettings } from "@t3tools/contracts/settings";
3import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
4import * as Schema from "effect/Schema";
5​
6import { applyAppearanceContrast } from "./appearanceContrast";
7import { applyAppearanceFontVariables, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "./appearanceFonts";
8import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
9import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter";
10import { startPreviewTitleRecording } from "./browserHistoryStore";
11import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
12import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
13import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
14import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
15import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
16import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
17import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
18import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
19import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
20import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
21import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
22import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
23import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
24import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
25import { resolveServerBackedAppDisplayName } from "./branding.logic";
26import { isElectron } from "./env";
27import {
28 subscribeComposerDraftModelReconciliation,
29 subscribeDraftThreadPromotion,
30 useComposerDraftStore,
31} from "./composerDraftStore";
32import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
33import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
34import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage";
35import {
36 getClientSettings,
37 startModelPreferencesMigration,
38 subscribeClientSettings,
39} from "./hooks/useSettings";
40import { syncBrowserChromeTheme } from "./hooks/useTheme";
41import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
42import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
43import {
44 syncDocumentElectronPlatformClasses,
45 syncDocumentWindowControlsOverlayClass,
46} from "./lib/windowControlsOverlay";
47import { startProviderAuthDelivery } from "./providerAuthDelivery";
48import { getRouter, type AppRouter } from "./router";
49import { appAtomRegistry } from "./rpc/atomRegistry";
50import { primaryServerConfigAtom } from "./state/server";
51import { environmentShell } from "./state/shell";
52import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
53import { startWorkspaceFocus } from "./lib/workspaceFocus";
54import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
55import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
56import { environmentThreadShells } from "./state/threads";
57import { resolveThreadRouteTarget } from "./threadRoutes";
58​
59/** Writes appearance settings onto the document, touching only the groups that changed. */
60function startClientAppearance(): void {
61 const root = document.documentElement;
62 let applied: ClientSettings | null = null;
63 let appliedSeparateFonts: boolean | null = null;
64 const apply = () => {
65 const settings = getClientSettings();
66 const previous = applied;
67 applied = settings;
68 const separateFonts = readLocalStorageValue(
69 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
70 false,
71 Schema.Boolean,
72 );
73 const previousSeparateFonts = appliedSeparateFonts;
74 appliedSeparateFonts = separateFonts;
75 if (previous?.diffColorScheme !== settings.diffColorScheme) {
76 root.dataset.diffColorScheme = settings.diffColorScheme;
77 }
78 if (previous?.chatWidth !== settings.chatWidth) {
79 root.dataset.chatWidth = settings.chatWidth;
80 }
81 if (previous?.appearanceContrast !== settings.appearanceContrast) {
82 applyAppearanceContrast(root, settings.appearanceContrast);
83 }
84 if (previous?.glassOpacity !== settings.glassOpacity) {
85 root.style.setProperty("--glass-opacity", `${settings.glassOpacity}%`);
86 if (settings.glassOpacity === 100) {
87 root.style.setProperty("--glass-blur", "0px");
88 } else {
89 root.style.removeProperty("--glass-blur");
90 }
91 }
92 if (
93 previous?.fontFamilySans !== settings.fontFamilySans ||
94 previous.fontFamilyCode !== settings.fontFamilyCode ||
95 previous.fontFamilyComposer !== settings.fontFamilyComposer ||
96 previous.fontSizeInterface !== settings.fontSizeInterface ||
97 previous.fontSizePrompt !== settings.fontSizePrompt ||
98 previous.fontSizeCode !== settings.fontSizeCode ||
99 previous.fontSmoothing !== settings.fontSmoothing ||
100 previousSeparateFonts !== separateFonts
101 ) {
102 applyAppearanceFontVariables(root, {
103 sans: settings.fontFamilySans,
104 code: settings.fontFamilyCode,
105 composer: settings.fontFamilyComposer,
106 sizeInterface: settings.fontSizeInterface,
107 sizePrompt: settings.fontSizePrompt,
108 sizeCode: settings.fontSizeCode,
109 smoothing: settings.fontSmoothing,
110 separate: separateFonts,
111 });
112 }
113 };
114 subscribeClientSettings(apply);
115 subscribeLocalStorageKey(TYPOGRAPHY_ADVANCED_STORAGE_KEY, apply);
116 apply();
118​
119function startDocumentTitle(): void {
120 appAtomRegistry.subscribe(
121 primaryServerConfigAtom,
122 (config) => {
123 document.title = resolveServerBackedAppDisplayName({
124 baseName: APP_BASE_NAME,
125 fallbackDisplayName: APP_DISPLAY_NAME,
126 fallbackStageLabel: APP_STAGE_LABEL,
127 primaryServerVersion: config?.environment.serverVersion ?? null,
128 });
129 },
130 { immediate: true },
131 );
133​
134/**
135 * Each route paints its own surface, which the browser chrome samples once it is on screen.
136 * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
137 * can swap the root between the bare outlet and the shell at the same address.
138 */
139function startBrowserChromeThemeSync(router: AppRouter): void {
140 const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
141 router.subscribe("onRendered", resync);
142 router.subscribe("onResolved", resync);
144​
145/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
146function startThreadOverlayRetention(router: AppRouter): void {
147 router.subscribe("onResolved", () => {
148 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
149 const draftSession =
150 target?.kind === "draft"
151 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
152 : null;
153 const threadRef =
154 target?.kind === "server"
155 ? target.threadRef
156 : draftSession
157 ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
158 : null;
159 retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
160 });
162​
163/**
164 * Starts every app-lifetime service once, before the first render, and returns the router.
165 * They run for the life of the page, so their disposers are dropped here.
166 */
167export function startAppServices(): AppRouter {
168 // Ahead of the history: the provider auth code must leave the address before anything reads it.
169 startProviderAuthDelivery();
170​
171 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
172 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
173​
174 if (isElectron) {
175 syncDocumentElectronPlatformClasses(navigator.platform);
176 syncDocumentWindowControlsOverlayClass();
177 }
178​
179 installDesktopPasteAsText(window.desktopBridge, window);
180​
181 startClientAppearance();
182 startDocumentTitle();
183 startEnvironmentThemeRepaint();
184 startBrowserChromeThemeSync(router);
185 startDefaultThemeAdoption();
186 startModelPreferencesMigration();
187 startAgentOpenedPreviews();
188 if (isElectron) startElectronBrowserHost();
189 startPreviewTitleRecording();
190 startBrowserProfileReporting();
191 installChatRouteCommands(router);
192 installCommandPaletteCommands(router);
193 registerOpenFavoriteEditorCommand();
194 startThreadOverlayRetention(router);
195 // Drafts promote as their server threads arrive, wherever the user is.
196 subscribeDraftThreadPromotion({
197 registry: appAtomRegistry,
198 threadShellAtom: environmentThreadShells.quietThreadShellAtom,
199 threadRefsAtom: environmentThreadShells.threadRefsAtom,
200 });
201 subscribeComposerDraftModelReconciliation({
202 registry: appAtomRegistry,
203 threadShellAtom: environmentThreadShells.threadShellAtom,
204 threadRefsAtom: environmentThreadShells.threadRefsAtom,
205 shellStateAtom: environmentShell.stateAtom,
206 });
207 startMainAppLocationTracking(router);
208 startWorkspaceFocus(router);
209 startBackgroundThreadAnnouncements(appAtomRegistry, router);
210 startThreadVisitedMigration(appAtomRegistry);
211 startSshPasswordPromptQueue();
212​
213 startKeybindingsUpdateToasts();
214 startSlowRpcRequestToasts();
215 startHostFreezeToasts();
216 startLegacyThreadMigrationToast();
217 startPermissionUpdateNotices(router);
218 startThreadNotifications(appAtomRegistry, router);
219 startGuideRunNotifications(appAtomRegistry, router);
220 if (isElectron) startDesktopUpdateLaunchNotice();
221​
222 return router;