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

appInit.tsx

309 lines13.0 KB

1import {
2 scopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import type { ScopedThreadRef } from "@t3tools/contracts";
7import type { ClientSettings } from "@t3tools/contracts/settings";
8import { createBrowserHistory, createHashHistory } from "@tanstack/react-router";
9import * as Schema from "effect/Schema";
10​
11import { applyAppearanceContrast } from "./appearanceContrast";
12import { applyAppearanceFontVariables, TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "./appearanceFonts";
13import { startElectronBrowserHost } from "./browser/ElectronBrowserHost";
14import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter";
15import { startPreviewTitleRecording } from "./browserHistoryStore";
16import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention";
17import { resolveWindowTitleThreadStatus } from "./components/Sidebar.logic";
18import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer";
19import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog";
20import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator";
21import { startKeybindingsUpdateToasts } from "./components/KeybindingsUpdateToast";
22import { startLegacyThreadMigrationToast } from "./components/LegacyThreadMigrationToast";
23import { startPermissionUpdateNotices } from "./components/PermissionUpdateNotice";
24import { startAgentOpenedPreviews } from "./components/preview/agentOpenedPreviews";
25import { startMainAppLocationTracking } from "./components/sidebar/mainAppLocation";
26import { startDesktopUpdateLaunchNotice } from "./components/sidebar/updateEverythingRun";
27import { startSlowRpcRequestToasts } from "./components/SlowRpcRequestToastCoordinator";
28import { startThreadNotifications } from "./components/ThreadNotificationCoordinator";
29import { startGuideRunNotifications } from "./components/pullRequest/guide/PullRequestGuideRunCoordinator";
30import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "./branding";
31import { resolveServerBackedAppDisplayName, resolveWindowTitle } from "./branding.logic";
32import { isElectron } from "./env";
33import {
34 subscribeComposerDraftModelReconciliation,
35 subscribeDraftThreadPromotion,
36 useComposerDraftStore,
37} from "./composerDraftStore";
38import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme";
39import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme";
40import { startThemeBackground } from "./themeBackground";
41import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage";
42import { startHostEnvironmentLookup } from "./state/primaryEnvironment";
43import {
44 getClientSettings,
45 startModelPreferencesMigration,
46 subscribeClientSettings,
47} from "./hooks/useSettings";
48import { syncBrowserChromeTheme } from "./hooks/useTheme";
49import { startThreadVisitedMigration } from "./hooks/useThreadVisitedMigration";
50import { installDesktopPasteAsText } from "./lib/desktopPasteAsText";
51import {
52 syncDocumentElectronPlatformClasses,
53 syncDocumentWindowControlsOverlayClass,
54} from "./lib/windowControlsOverlay";
55import { startProviderAuthDelivery } from "./providerAuthDelivery";
56import { getRouter, type AppRouter } from "./router";
57import { appAtomRegistry } from "./rpc/atomRegistry";
58import { environmentProjects } from "./state/projects";
59import { primaryServerConfigAtom } from "./state/server";
60import { environmentShell } from "./state/shell";
61import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
62import { startWorkspaceFocus } from "./lib/workspaceFocus";
63import { startI18n } from "./i18n/runtime";
64import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
65import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
66import { environmentThreadShells, threadEnvironment } from "./state/threads";
67import { resolveActiveThreadRouteRef, resolveThreadRouteTarget } from "./threadRoutes";
68​
69/** Writes appearance settings onto the document, touching only the groups that changed. */
70function startClientAppearance(): void {
71 const root = document.documentElement;
72 let applied: ClientSettings | null = null;
73 let appliedSeparateFonts: boolean | null = null;
74 const apply = () => {
75 const settings = getClientSettings();
76 const previous = applied;
77 applied = settings;
78 const separateFonts = readLocalStorageValue(
79 TYPOGRAPHY_ADVANCED_STORAGE_KEY,
80 false,
81 Schema.Boolean,
82 );
83 const previousSeparateFonts = appliedSeparateFonts;
84 appliedSeparateFonts = separateFonts;
85 if (previous?.diffColorScheme !== settings.diffColorScheme) {
86 root.dataset.diffColorScheme = settings.diffColorScheme;
87 }
88 if (previous?.chatWidth !== settings.chatWidth) {
89 root.dataset.chatWidth = settings.chatWidth;
90 }
91 if (previous?.appearanceContrast !== settings.appearanceContrast) {
92 applyAppearanceContrast(root, settings.appearanceContrast);
93 }
94 if (previous?.glassOpacity !== settings.glassOpacity) {
95 root.style.setProperty("--glass-opacity", `${settings.glassOpacity}%`);
96 if (settings.glassOpacity === 100) {
97 root.style.setProperty("--glass-blur", "0px");
98 } else {
99 root.style.removeProperty("--glass-blur");
100 }
101 }
102 if (
103 previous?.fontFamilySans !== settings.fontFamilySans ||
104 previous.fontFamilyCode !== settings.fontFamilyCode ||
105 previous.fontFamilyComposer !== settings.fontFamilyComposer ||
106 previous.fontSizeInterface !== settings.fontSizeInterface ||
107 previous.fontSizePrompt !== settings.fontSizePrompt ||
108 previous.fontSizeCode !== settings.fontSizeCode ||
109 previous.fontSmoothing !== settings.fontSmoothing ||
110 previousSeparateFonts !== separateFonts
111 ) {
112 applyAppearanceFontVariables(root, {
113 sans: settings.fontFamilySans,
114 code: settings.fontFamilyCode,
115 composer: settings.fontFamilyComposer,
116 sizeInterface: settings.fontSizeInterface,
117 sizePrompt: settings.fontSizePrompt,
118 sizeCode: settings.fontSizeCode,
119 smoothing: settings.fontSmoothing,
120 separate: separateFonts,
121 });
122 }
123 };
124 subscribeClientSettings(apply);
125 subscribeLocalStorageKey(TYPOGRAPHY_ADVANCED_STORAGE_KEY, apply);
126 apply();
128​
129function readOpenThreadRef(router: AppRouter): ScopedThreadRef | null {
130 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
131 const draft =
132 target?.kind === "draft"
133 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
134 : null;
135 return resolveActiveThreadRouteRef(target, draft);
137​
138/**
139 * Names the open thread and its project in the window title, or the app when none is open.
140 * Screen readers read it on Alt+Tab, so it can lead with the thread and what it's doing.
141 */
142function startDocumentTitle(router: AppRouter): void {
143 const readOnGuestPage = () => router.state.matches.some((match) => match.routeId === "/guest");
144 let openThreadRef = readOpenThreadRef(router);
145 let onGuestPage = readOnGuestPage();
146 const write = () => {
147 // GuestPage titles the tab after the shared thread.
148 if (onGuestPage) return;
149 const thread =
150 openThreadRef === null
151 ? null
152 : appAtomRegistry.get(environmentThreadShells.quietThreadShellAtom(openThreadRef));
153 const project =
154 thread === null
155 ? null
156 : appAtomRegistry.get(
157 environmentProjects.projectAtom(
158 scopeProjectRef(thread.environmentId, thread.projectId),
159 ),
160 );
161 const title = resolveWindowTitle({
162 appDisplayName: resolveServerBackedAppDisplayName({
163 baseName: APP_BASE_NAME,
164 fallbackDisplayName: APP_DISPLAY_NAME,
165 fallbackStageLabel: APP_STAGE_LABEL,
166 primaryServerVersion:
167 appAtomRegistry.get(primaryServerConfigAtom)?.environment.serverVersion ?? null,
168 }),
169 projectTitle: project?.title ?? null,
170 threadTitle: thread?.title ?? null,
171 ...(getClientSettings().screenReaderWindowTitle && {
172 screenReader: {
173 threadStatus: thread === null ? null : resolveWindowTitleThreadStatus(thread),
174 },
175 }),
176 desktop: isElectron,
177 });
178 // Projects change whenever any project does; most changes leave the title alone.
179 if (document.title !== title) document.title = title;
180 };
181 // The open thread's own shell, since the shell lists skip threads hidden by a tag filter.
182 let unsubscribeOpenThread = () => {};
183 const watchOpenThread = () => {
184 unsubscribeOpenThread();
185 unsubscribeOpenThread =
186 openThreadRef === null
187 ? () => {}
188 : appAtomRegistry.subscribe(
189 environmentThreadShells.quietThreadShellAtom(openThreadRef),
190 write,
191 );
192 };
193 // The draft store changes on every keystroke; only a new open thread matters here.
194 const updateOpenThread = () => {
195 const next = readOpenThreadRef(router);
196 const nextOnGuestPage = readOnGuestPage();
197 if (
198 nextOnGuestPage === onGuestPage &&
199 (next && scopedThreadKey(next)) === (openThreadRef && scopedThreadKey(openThreadRef))
200 ) {
201 return;
202 }
203 openThreadRef = next;
204 onGuestPage = nextOnGuestPage;
205 watchOpenThread();
206 write();
207 };
208 watchOpenThread();
209 appAtomRegistry.subscribe(primaryServerConfigAtom, write, { immediate: true });
210 appAtomRegistry.subscribe(environmentProjects.projectsAtom, write);
211 subscribeClientSettings(write);
212 router.subscribe("onResolved", updateOpenThread);
213 useComposerDraftStore.subscribe(updateOpenThread);
215​
216/**
217 * Each route paints its own surface, which the browser chrome samples once it is on screen.
218 * onRendered only fires for a new href; onResolved also covers `router.invalidate()`, which
219 * can swap the root between the bare outlet and the shell at the same address.
220 */
221function startBrowserChromeThemeSync(router: AppRouter): void {
222 const resync = () => window.requestAnimationFrame(syncBrowserChromeTheme);
223 router.subscribe("onRendered", resync);
224 router.subscribe("onResolved", resync);
226​
227/** Chat overlays belong to the thread they were opened in, so leaving its route drops them. */
228function startThreadOverlayRetention(router: AppRouter): void {
229 router.subscribe("onResolved", () => {
230 const target = resolveThreadRouteTarget(router.state.matches.at(-1)?.params ?? {});
231 const draftSession =
232 target?.kind === "draft"
233 ? useComposerDraftStore.getState().getDraftSession(target.draftId)
234 : null;
235 const threadRef =
236 target?.kind === "server"
237 ? target.threadRef
238 : draftSession
239 ? scopeThreadRef(draftSession.environmentId, draftSession.threadId)
240 : null;
241 retainThreadOverlaysForThread(threadRef ? scopedThreadKey(threadRef) : null);
242 });
244​
245/**
246 * Starts every app-lifetime service once, before the first render, and returns the router.
247 * They run for the life of the page, so their disposers are dropped here.
248 */
249export function startAppServices(): AppRouter {
250 // Ahead of the history: the provider auth code must leave the address before anything reads it.
251 startProviderAuthDelivery();
252​
253 // Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
254 const router = getRouter(isElectron ? createHashHistory() : createBrowserHistory());
255​
256 if (isElectron) {
257 syncDocumentElectronPlatformClasses(navigator.platform);
258 syncDocumentWindowControlsOverlayClass();
259 }
260​
261 installDesktopPasteAsText(window.desktopBridge, window);
262​
263 startClientAppearance();
264 startI18n();
265 startDocumentTitle(router);
266 startHostEnvironmentLookup();
267 startEnvironmentThemeRepaint();
268 startThemeBackground();
269 startBrowserChromeThemeSync(router);
270 startDefaultThemeAdoption();
271 startModelPreferencesMigration();
272 startAgentOpenedPreviews();
273 if (isElectron) startElectronBrowserHost();
274 startPreviewTitleRecording();
275 startBrowserProfileReporting();
276 installChatRouteCommands(router);
277 installCommandPaletteCommands(router);
278 registerOpenFavoriteEditorCommand();
279 startThreadOverlayRetention(router);
280 // Drafts promote as their server threads arrive, wherever the user is.
281 subscribeDraftThreadPromotion({
282 registry: appAtomRegistry,
283 threadShellAtom: environmentThreadShells.quietThreadShellAtom,
284 threadRefsAtom: environmentThreadShells.threadRefsAtom,
285 });
286 subscribeComposerDraftModelReconciliation({
287 registry: appAtomRegistry,
288 threadShellAtom: environmentThreadShells.threadShellAtom,
289 threadRefsAtom: environmentThreadShells.threadRefsAtom,
290 shellStateAtom: environmentShell.stateAtom,
291 pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom,
292 });
293 startMainAppLocationTracking(router);
294 startWorkspaceFocus(router);
295 startBackgroundThreadAnnouncements(appAtomRegistry, router);
296 startThreadVisitedMigration(appAtomRegistry);
297 startSshPasswordPromptQueue();
298​
299 startKeybindingsUpdateToasts();
300 startSlowRpcRequestToasts();
301 startHostFreezeToasts();
302 startLegacyThreadMigrationToast();
303 startPermissionUpdateNotices(router);
304 startThreadNotifications(appAtomRegistry, router);
305 startGuideRunNotifications(appAtomRegistry, router);
306 if (isElectron) startDesktopUpdateLaunchNotice();
307​
308 return router;