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

appInit.tsx

197 lines8.6 KB

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