@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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