@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, 04:45 UTC

main
tsx 190 lines 7.24 KB
Raw
1 import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
2 import {
3 AuthPreviewOperateScope,
4 type DesktopPreviewBridge,
5 type DesktopPreviewOpenLinkEvent,
6 type EnvironmentId,
7 FILL_PREVIEW_VIEWPORT,
8 } from "@t3tools/contracts";
9 import { useAtomValue } from "@effect/atom-react";
10 import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
11 import { type ComponentProps, useState } from "react";
12
13 import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
14
15 import { isElectron } from "~/env";
16 import { useClientSettingsHydrated } from "~/hooks/useSettings";
17 import { useDesktopHostedPreviewSessions } from "~/components/preview/usePreviewSession";
18 import {
19 readActivePreviewSessions,
20 type ThreadPreviewState,
21 useActivePreviewSessions,
22 } from "~/previewStateStore";
23 import { appAtomRegistry } from "~/rpc/atomRegistry";
24 import { previewEnvironment } from "~/state/preview";
25 import { readPreviewTunnelUrl } from "~/state/previewTunnel";
26 import { useEnvironmentScope } from "~/state/session";
27
28 import { readPreviewAnnotationTheme } from "./annotationTheme";
29 import { useBrowserDefaults } from "./browserDefaults";
30 import { useBrowserPointerStore } from "./browserPointerStore";
31 import { HostedBrowserWebview } from "./HostedBrowserWebview";
32 import { openUrlInPreview } from "./openFileInPreview";
33 import { rendersServerTabNatively } from "./previewRuntime";
34 import { previewRuntimeTabId } from "./previewRuntimeTabId";
35
36 /** Every session this window renders as a hosted webview, in a fixed (non-display) order. */
37 function hostedBrowserSessions(
38 previewByThreadKey: Record<string, ThreadPreviewState>,
39 primaryEnvironmentId: EnvironmentId | null,
40 ) {
41 const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
42 const threadRef = parseScopedThreadKey(threadKey);
43 return threadRef
44 ? Object.values(previewState.sessions)
45 .filter(
46 (snapshot) =>
47 snapshot.runtime !== "server" ||
48 rendersServerTabNatively(threadRef.environmentId, primaryEnvironmentId, snapshot),
49 )
50 .map((snapshot) => ({
51 threadRef,
52 snapshot,
53 runtimeTabId: previewRuntimeTabId(threadRef, previewState.serverEpoch, snapshot.tabId),
54 pictureInPicture:
55 previewState.desktopByTabId[snapshot.tabId]?.pictureInPicture ?? false,
56 zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
57 }))
58 : [];
59 });
60 // Electron destroys a moved webview's guest, so the render order must not follow the server's
61 // updatedAt order. Any fixed order works; this one is not a display order.
62 return activeSessions.toSorted((left, right) =>
63 left.runtimeTabId < right.runtimeTabId ? -1 : left.runtimeTabId > right.runtimeTabId ? 1 : 0,
64 );
65 }
66
67 function startAnnotationThemeSync(preview: DesktopPreviewBridge): () => void {
68 let lastSerializedTheme = "";
69 const syncTheme = () => {
70 const theme = readPreviewAnnotationTheme();
71 const serializedTheme = JSON.stringify(theme);
72 if (serializedTheme === lastSerializedTheme) return;
73 lastSerializedTheme = serializedTheme;
74 void preview.setAnnotationTheme(theme).catch(() => {
75 lastSerializedTheme = "";
76 });
77 };
78 // App services start before the first paint, when the theme styles may not be applied yet.
79 const frameId = window.requestAnimationFrame(syncTheme);
80 const observer = new MutationObserver(syncTheme);
81 observer.observe(document.documentElement, {
82 attributes: true,
83 attributeFilter: ["class", "style"],
84 });
85 const headObserver = new MutationObserver(syncTheme);
86 headObserver.observe(document.head, {
87 childList: true,
88 subtree: true,
89 characterData: true,
90 });
91 return () => {
92 window.cancelAnimationFrame(frameId);
93 observer.disconnect();
94 headObserver.disconnect();
95 };
96 }
97
98 function openLinkInPreview({ tabId, url, background }: DesktopPreviewOpenLinkEvent): void {
99 const source = hostedBrowserSessions(
100 readActivePreviewSessions(),
101 appAtomRegistry.get(primaryEnvironmentIdAtom),
102 ).find((session) => session.runtimeTabId === tabId);
103 if (!source) return;
104 void openUrlInPreview({
105 threadRef: source.threadRef,
106 url,
107 openPreview: (input) => runAtomCommand(appAtomRegistry, previewEnvironment.open, input),
108 profileId: source.snapshot.profileId,
109 background,
110 });
111 }
112
113 /** App-lifetime listeners for the desktop preview bridge: annotation theme, agent pointer, links. */
114 export function startElectronBrowserHost(): () => void {
115 const preview = window.desktopBridge?.preview;
116 if (!preview) return () => {};
117 const disposers = [
118 startAnnotationThemeSync(preview),
119 preview.onPointerEvent((event) => {
120 useBrowserPointerStore.getState().apply(event);
121 }),
122 preview.onOpenLink(openLinkInPreview),
123 preview.onTunnelAccessRequest(({ requestId, environmentId }) => {
124 void readPreviewTunnelUrl(environmentId).then((url) =>
125 preview.resolveTunnelAccess(requestId, url),
126 );
127 }),
128 ];
129 return () => {
130 for (const dispose of disposers) dispose();
131 };
132 }
133
134 export function ElectronBrowserHost() {
135 const previewByThreadKey = useActivePreviewSessions();
136 const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
137 useDesktopHostedPreviewSessions(primaryEnvironmentId);
138 const sessions = hostedBrowserSessions(previewByThreadKey, primaryEnvironmentId);
139
140 if (!isElectron) return null;
141 return (
142 <div className="contents" data-electron-browser-host>
143 {sessions.map(({ threadRef, snapshot, runtimeTabId, pictureInPicture, zoomFactor }) => {
144 const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
145 return (
146 <AuthorizedBrowserWebview
147 key={runtimeTabId}
148 threadRef={threadRef}
149 tabId={snapshot.tabId}
150 runtimeTabId={runtimeTabId}
151 initialUrl={url}
152 viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
153 pictureInPicture={pictureInPicture}
154 profileId={snapshot.profileId}
155 zoomFactor={zoomFactor}
156 serverDriven={snapshot.runtime === "server"}
157 {...(snapshot.runtime === "server"
158 ? {
159 serverRendering: {
160 colorScheme: snapshot.colorScheme ?? "system",
161 zoomFactor: snapshot.zoomFactor ?? 1,
162 },
163 }
164 : {})}
165 />
166 );
167 })}
168 </div>
169 );
170 }
171
172 function AuthorizedBrowserWebview(props: ComponentProps<typeof HostedBrowserWebview>) {
173 const canOperatePreview = useEnvironmentScope(
174 props.threadRef.environmentId,
175 AuthPreviewOperateScope,
176 );
177 const profileId = useTabProfileId(props.profileId);
178 return canOperatePreview ? <HostedBrowserWebview {...props} profileId={profileId} /> : null;
179 }
180
181 // Latch after hydration: Electron fixes the partition when the guest attaches.
182 function useTabProfileId(profileId: string | undefined): string | undefined {
183 const hydrated = useClientSettingsHydrated();
184 const defaultProfileId = useBrowserDefaults().profileId;
185 const [fallback, setFallback] = useState<string | undefined>(undefined);
186 if (profileId === undefined && hydrated && fallback === undefined) {
187 setFallback(defaultProfileId);
188 }
189 return profileId ?? fallback;
190 }