@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
ts 547 lines 18.9 KB
Raw
1 import { useAtomValue } from "@effect/atom-react";
2 import { scopedThreadKey } from "@t3tools/client-runtime/environment";
3 import {
4 type DesktopPreviewColorScheme,
5 type DesktopPreviewFavicon,
6 type PreviewEvent,
7 type PreviewListResult,
8 type PreviewSessionSnapshot,
9 type ScopedThreadRef,
10 } from "@t3tools/contracts";
11 import { Atom } from "effect/reactivity";
12
13 import { PREVIEW_RECENT_URL_LIMIT } from "./components/preview/previewConstants";
14 import { appAtomRegistry } from "./rpc/atomRegistry";
15
16 export interface DesktopPreviewOverlay {
17 hasWebContents: boolean;
18 navStatus: PreviewSessionSnapshot["navStatus"];
19 canGoBack: boolean;
20 canGoForward: boolean;
21 loading: boolean;
22 zoomFactor: number;
23 pictureInPicture: boolean;
24 colorScheme: DesktopPreviewColorScheme;
25 audioMuted: boolean;
26 audible: boolean;
27 controller: "human" | "agent" | "none";
28 favicon: DesktopPreviewFavicon | null;
29 }
30
31 export interface ThreadPreviewState {
32 snapshot: PreviewSessionSnapshot | null;
33 sessions: Record<string, PreviewSessionSnapshot>;
34 /** Tabs intentionally closed by this client. Stale list snapshots must not resurrect them. */
35 suppressedTabIds: ReadonlySet<string>;
36 activeTabId: string | null;
37 desktopOverlay: DesktopPreviewOverlay | null;
38 desktopByTabId: Record<string, DesktopPreviewOverlay>;
39 recentlySeenUrls: string[];
40 listLoaded: boolean;
41 serverEpoch: string | null;
42 serverRevision: number;
43 }
44
45 const EMPTY_THREAD_PREVIEW_STATE: ThreadPreviewState = Object.freeze({
46 snapshot: null,
47 sessions: {},
48 suppressedTabIds: new Set<string>(),
49 activeTabId: null,
50 desktopOverlay: null,
51 desktopByTabId: {},
52 recentlySeenUrls: [] as string[],
53 listLoaded: false,
54 serverEpoch: null,
55 serverRevision: 0,
56 });
57
58 const emptyPreviewStateAtom = Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
59 Atom.withLabel("preview:empty-thread"),
60 );
61
62 export const previewStateAtom = Atom.family((threadKey: string) =>
63 Atom.make<ThreadPreviewState>(EMPTY_THREAD_PREVIEW_STATE).pipe(
64 Atom.keepAlive,
65 Atom.withLabel(`preview:thread:${threadKey}`),
66 ),
67 );
68
69 // Only Electron needs this cross-thread index; separate it to avoid unrelated preview subscriptions.
70 interface ActivePreviewThreadIndex {
71 readonly keys: ReadonlySet<string>;
72 }
73
74 const activePreviewThreadKeysAtom = Atom.make<ActivePreviewThreadIndex>({
75 keys: new Set<string>(),
76 }).pipe(Atom.keepAlive, Atom.withLabel("preview:active-thread-keys"));
77
78 const activePreviewSessionsAtom = Atom.make((get) => {
79 const byThreadKey: Record<string, ThreadPreviewState> = {};
80 for (const threadKey of get(activePreviewThreadKeysAtom).keys) {
81 const state = get(previewStateAtom(threadKey));
82 if (Object.keys(state.sessions).length > 0) {
83 byThreadKey[threadKey] = state;
84 }
85 }
86 return byThreadKey;
87 }).pipe(Atom.withLabel("preview:active-sessions"));
88
89 /**
90 * Every thread whose preview state has been written. Panel tabs and the mini
91 * player follow those threads' states from a store this one cannot import
92 * (rightPanelStore -> closedViewStore -> lib/utils -> composerDraftStore ->
93 * previewStateStore is a cycle), so they subscribe through this index.
94 */
95 export const previewThreadRefsAtom = Atom.make<ReadonlyMap<string, ScopedThreadRef>>(
96 new Map(),
97 ).pipe(Atom.keepAlive, Atom.withLabel("preview:thread-refs"));
98
99 function syncActivePreviewThread(threadKey: string, state: ThreadPreviewState): void {
100 const active = Object.keys(state.sessions).length > 0;
101 appAtomRegistry.update(activePreviewThreadKeysAtom, (current) => {
102 if (current.keys.has(threadKey) === active) return current;
103 const next = new Set(current.keys);
104 if (active) next.add(threadKey);
105 else next.delete(threadKey);
106 return { keys: next };
107 });
108 }
109
110 function updateThreadPreviewState(
111 ref: ScopedThreadRef,
112 update: (current: ThreadPreviewState) => ThreadPreviewState,
113 ): void {
114 const threadKey = scopedThreadKey(ref);
115 // Indexed before the write so a new thread's subscribers see this change.
116 appAtomRegistry.update(previewThreadRefsAtom, (refs) =>
117 refs.has(threadKey) ? refs : new Map(refs).set(threadKey, ref),
118 );
119 const atom = previewStateAtom(threadKey);
120 let nextState = appAtomRegistry.get(atom);
121 const changed = appAtomRegistry.modify(atom, (current) => {
122 nextState = update(current);
123 return [nextState !== current, nextState];
124 });
125 if (changed) syncActivePreviewThread(threadKey, nextState);
126 }
127
128 const dedupeRecentUrls = (existing: string[], url: string): string[] => {
129 const next = [url, ...existing.filter((entry) => entry !== url)];
130 return next.slice(0, PREVIEW_RECENT_URL_LIMIT);
131 };
132
133 const rememberSnapshotUrl = (
134 recentlySeenUrls: string[],
135 snapshot: PreviewSessionSnapshot,
136 ): string[] =>
137 snapshot.navStatus._tag === "Idle"
138 ? recentlySeenUrls
139 : dedupeRecentUrls(recentlySeenUrls, snapshot.navStatus.url);
140
141 const latestSnapshot = (
142 sessions: Record<string, PreviewSessionSnapshot>,
143 ): PreviewSessionSnapshot | null =>
144 Object.values(sessions)
145 .toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt))
146 .at(-1) ?? null;
147
148 const removeSession = (current: ThreadPreviewState, tabId: string): ThreadPreviewState => {
149 if (!current.sessions[tabId]) return current;
150 const { [tabId]: _closed, ...sessions } = current.sessions;
151 const { [tabId]: _desktop, ...desktopByTabId } = current.desktopByTabId;
152 const nextSnapshot = latestSnapshot(sessions);
153 const activeTabId =
154 current.activeTabId === tabId ? (nextSnapshot?.tabId ?? null) : current.activeTabId;
155 const snapshot = activeTabId ? (sessions[activeTabId] ?? nextSnapshot) : nextSnapshot;
156 return {
157 ...current,
158 sessions,
159 desktopByTabId,
160 activeTabId: snapshot?.tabId ?? null,
161 snapshot,
162 desktopOverlay: snapshot ? (desktopByTabId[snapshot.tabId] ?? null) : null,
163 };
164 };
165
166 export function useThreadPreviewState(ref: ScopedThreadRef | null | undefined): ThreadPreviewState {
167 const atom = ref ? previewStateAtom(scopedThreadKey(ref)) : emptyPreviewStateAtom;
168 return useAtomValue(atom);
169 }
170
171 export function useActivePreviewSessions(): Record<string, ThreadPreviewState> {
172 return useAtomValue(activePreviewSessionsAtom);
173 }
174
175 export function readActivePreviewSessions(): Record<string, ThreadPreviewState> {
176 return appAtomRegistry.get(activePreviewSessionsAtom);
177 }
178
179 export function readThreadPreviewState(ref: ScopedThreadRef): ThreadPreviewState {
180 return appAtomRegistry.get(previewStateAtom(scopedThreadKey(ref)));
181 }
182
183 export function applyPreviewServerEvent(ref: ScopedThreadRef, event: PreviewEvent): void {
184 updateThreadPreviewState(ref, (current) => {
185 if (current.serverEpoch !== null && event.serverEpoch !== current.serverEpoch) return current;
186 if (event.revision < current.serverRevision) return current;
187 const next = (() => {
188 switch (event.type) {
189 case "opened":
190 case "navigated":
191 case "resized": {
192 const snapshot = event.snapshot;
193 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
194 const recentlySeenUrls =
195 snapshot.navStatus._tag === "Idle"
196 ? current.recentlySeenUrls
197 : dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url);
198 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
199 const activeTabId = event.type === "opened" ? snapshot.tabId : current.activeTabId;
200 const activeSnapshot = sessions[activeTabId ?? snapshot.tabId] ?? snapshot;
201 return {
202 ...current,
203 sessions,
204 activeTabId: activeTabId ?? snapshot.tabId,
205 snapshot: activeSnapshot,
206 desktopOverlay: current.desktopByTabId[activeSnapshot.tabId] ?? null,
207 recentlySeenUrls,
208 };
209 }
210 case "failed": {
211 const existing = current.sessions[event.tabId];
212 if (!existing) return current;
213 const failedSnapshot = {
214 ...existing,
215 navStatus: {
216 _tag: "LoadFailed" as const,
217 url: event.url,
218 title: event.title,
219 code: event.code,
220 description: event.description,
221 ...(event.download === undefined ? {} : { download: event.download }),
222 },
223 updatedAt: event.createdAt,
224 };
225 const sessions = { ...current.sessions, [event.tabId]: failedSnapshot };
226 return {
227 ...current,
228 sessions,
229 snapshot: current.activeTabId === event.tabId ? failedSnapshot : current.snapshot,
230 };
231 }
232 case "closed": {
233 const closed = removeSession(current, event.tabId);
234 if (!closed.suppressedTabIds.has(event.tabId)) return closed;
235 const suppressedTabIds = new Set(closed.suppressedTabIds);
236 suppressedTabIds.delete(event.tabId);
237 return { ...closed, suppressedTabIds };
238 }
239 }
240 })();
241 return next.serverRevision === event.revision && next.serverEpoch === event.serverEpoch
242 ? next
243 : {
244 ...next,
245 serverEpoch: event.serverEpoch,
246 serverRevision: event.revision,
247 };
248 });
249 }
250
251 export function applyPreviewServerSnapshot(
252 ref: ScopedThreadRef,
253 snapshot: PreviewSessionSnapshot | null,
254 ): void {
255 updateThreadPreviewState(ref, (current) => {
256 if (!snapshot && current.snapshot === null) return current;
257 if (!snapshot) {
258 return {
259 ...current,
260 snapshot: null,
261 sessions: {},
262 activeTabId: null,
263 desktopOverlay: null,
264 desktopByTabId: {},
265 };
266 }
267 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
268 const existing = current.sessions[snapshot.tabId];
269 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
270 const recentlySeenUrls = rememberSnapshotUrl(current.recentlySeenUrls, snapshot);
271 return {
272 ...current,
273 snapshot,
274 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
275 activeTabId: snapshot.tabId,
276 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
277 recentlySeenUrls,
278 };
279 });
280 }
281
282 /** Updates background tabs without focusing them. */
283 export function updatePreviewServerSnapshot(
284 ref: ScopedThreadRef,
285 snapshot: PreviewSessionSnapshot,
286 ): void {
287 updateThreadPreviewState(ref, (current) => {
288 if (current.suppressedTabIds.has(snapshot.tabId)) return current;
289 const existing = current.sessions[snapshot.tabId];
290 if (existing && existing.updatedAt > snapshot.updatedAt) return current;
291 const sessions = { ...current.sessions, [snapshot.tabId]: snapshot };
292 const activeTabId =
293 current.activeTabId && sessions[current.activeTabId] ? current.activeTabId : snapshot.tabId;
294 const activeSnapshot = sessions[activeTabId] ?? snapshot;
295 return {
296 ...current,
297 sessions,
298 activeTabId,
299 snapshot: activeSnapshot,
300 desktopOverlay: current.desktopByTabId[activeTabId] ?? null,
301 recentlySeenUrls: rememberSnapshotUrl(current.recentlySeenUrls, snapshot),
302 };
303 });
304 }
305
306 export function reconcilePreviewServerSessions(
307 ref: ScopedThreadRef,
308 result: PreviewListResult,
309 ): void {
310 updateThreadPreviewState(ref, (current) => {
311 const sameServer = current.serverEpoch === result.serverEpoch;
312 if (sameServer && result.revision < current.serverRevision) {
313 return current;
314 }
315 const snapshots = result.sessions;
316 const sessions: Record<string, PreviewSessionSnapshot> = {};
317 const currentSuppressedTabIds = sameServer ? current.suppressedTabIds : new Set<string>();
318 let recentlySeenUrls = current.recentlySeenUrls;
319 for (const snapshot of snapshots) {
320 if (currentSuppressedTabIds.has(snapshot.tabId)) continue;
321 const existing = sameServer ? current.sessions[snapshot.tabId] : undefined;
322 const next = existing && existing.updatedAt > snapshot.updatedAt ? existing : snapshot;
323 sessions[next.tabId] = next;
324 recentlySeenUrls = rememberSnapshotUrl(recentlySeenUrls, next);
325 }
326
327 const fallback = latestSnapshot(sessions);
328 const activeTabId =
329 current.activeTabId && sessions[current.activeTabId]
330 ? current.activeTabId
331 : (fallback?.tabId ?? null);
332 const snapshot = activeTabId ? (sessions[activeTabId] ?? null) : null;
333 const desktopByTabId = sameServer
334 ? Object.fromEntries(
335 Object.entries(current.desktopByTabId).filter(([tabId]) => sessions[tabId] !== undefined),
336 )
337 : {};
338 const suppressedTabIds = new Set(
339 [...currentSuppressedTabIds].filter((tabId) =>
340 snapshots.some((snapshot) => snapshot.tabId === tabId),
341 ),
342 );
343 const desktopOverlay = activeTabId ? (desktopByTabId[activeTabId] ?? null) : null;
344 if (
345 sameServer &&
346 current.listLoaded &&
347 current.serverRevision === result.revision &&
348 current.activeTabId === activeTabId &&
349 current.snapshot === snapshot &&
350 current.desktopOverlay === desktopOverlay &&
351 current.recentlySeenUrls === recentlySeenUrls &&
352 haveSameValues(current.sessions, sessions) &&
353 haveSameValues(current.desktopByTabId, desktopByTabId) &&
354 current.suppressedTabIds.size === suppressedTabIds.size
355 ) {
356 return current;
357 }
358 return {
359 ...current,
360 sessions,
361 suppressedTabIds,
362 activeTabId,
363 snapshot,
364 desktopByTabId,
365 desktopOverlay,
366 recentlySeenUrls,
367 listLoaded: true,
368 serverEpoch: result.serverEpoch,
369 serverRevision: result.revision,
370 };
371 });
372 }
373
374 function haveSameValues<T>(left: Record<string, T>, right: Record<string, T>): boolean {
375 const keys = Object.keys(left);
376 return keys.length === Object.keys(right).length && keys.every((key) => left[key] === right[key]);
377 }
378
379 function sameDesktopNavStatus(
380 previous: DesktopPreviewOverlay["navStatus"],
381 next: DesktopPreviewOverlay["navStatus"],
382 ): boolean {
383 if (previous._tag === "Idle" || next._tag === "Idle") return previous._tag === next._tag;
384 return (
385 previous._tag === next._tag &&
386 previous.url === next.url &&
387 previous.title === next.title &&
388 (previous._tag !== "LoadFailed" ||
389 next._tag !== "LoadFailed" ||
390 (previous.code === next.code && previous.description === next.description))
391 );
392 }
393
394 function isPreviewStateEqual(
395 previous: DesktopPreviewOverlay | null,
396 next: DesktopPreviewOverlay | null,
397 ) {
398 return (
399 previous === next ||
400 (previous !== null &&
401 next !== null &&
402 previous.hasWebContents === next.hasWebContents &&
403 sameDesktopNavStatus(previous.navStatus, next.navStatus) &&
404 previous.canGoBack === next.canGoBack &&
405 previous.canGoForward === next.canGoForward &&
406 previous.loading === next.loading &&
407 previous.zoomFactor === next.zoomFactor &&
408 previous.pictureInPicture === next.pictureInPicture &&
409 previous.colorScheme === next.colorScheme &&
410 previous.audioMuted === next.audioMuted &&
411 previous.audible === next.audible &&
412 previous.controller === next.controller &&
413 previous.favicon?.dataUrl === next.favicon?.dataUrl &&
414 previous.favicon?.pageUrl === next.favicon?.pageUrl &&
415 previous.favicon?.capturedAt === next.favicon?.capturedAt)
416 );
417 }
418
419 export function applyPreviewDesktopState(
420 ref: ScopedThreadRef,
421 tabId: string,
422 overlay: DesktopPreviewOverlay | null,
423 ): void {
424 updateThreadPreviewState(ref, (current) => {
425 if (isPreviewStateEqual(current.desktopByTabId[tabId] ?? null, overlay)) {
426 return current;
427 }
428 const desktopByTabId = { ...current.desktopByTabId };
429 if (overlay) desktopByTabId[tabId] = overlay;
430 else delete desktopByTabId[tabId];
431 return {
432 ...current,
433 desktopByTabId,
434 desktopOverlay: current.activeTabId === tabId ? overlay : current.desktopOverlay,
435 };
436 });
437 }
438
439 export function beginPreviewSessionClose(ref: ScopedThreadRef, tabId: string): void {
440 updateThreadPreviewState(ref, (current) => {
441 const suppressedTabIds = new Set(current.suppressedTabIds);
442 suppressedTabIds.add(tabId);
443 return {
444 ...removeSession(current, tabId),
445 suppressedTabIds,
446 };
447 });
448 }
449
450 export function cancelPreviewSessionClose(
451 ref: ScopedThreadRef,
452 snapshot: PreviewSessionSnapshot | null,
453 tabId: string,
454 ): void {
455 updateThreadPreviewState(ref, (current) => {
456 if (!current.suppressedTabIds.has(tabId)) return current;
457 const suppressedTabIds = new Set(current.suppressedTabIds);
458 suppressedTabIds.delete(tabId);
459 if (!snapshot) {
460 return { ...current, suppressedTabIds };
461 }
462 const recentlySeenUrls =
463 snapshot.navStatus._tag !== "Idle"
464 ? dedupeRecentUrls(current.recentlySeenUrls, snapshot.navStatus.url)
465 : current.recentlySeenUrls;
466 return {
467 ...current,
468 snapshot,
469 sessions: { ...current.sessions, [snapshot.tabId]: snapshot },
470 suppressedTabIds,
471 activeTabId: snapshot.tabId,
472 desktopOverlay: current.desktopByTabId[snapshot.tabId] ?? null,
473 recentlySeenUrls,
474 };
475 });
476 }
477
478 export function setActivePreviewTab(ref: ScopedThreadRef, tabId: string): void {
479 updateThreadPreviewState(ref, (current) => {
480 const snapshot = current.sessions[tabId];
481 if (!snapshot || current.activeTabId === tabId) return current;
482 return {
483 ...current,
484 activeTabId: tabId,
485 snapshot,
486 desktopOverlay: current.desktopByTabId[tabId] ?? null,
487 };
488 });
489 }
490
491 /** Runs once the tab is known; popup opened events can arrive after their announcing stream. */
492 export function whenPreviewTabKnown(
493 ref: ScopedThreadRef,
494 tabId: string,
495 action: () => void,
496 timeoutMs = 5_000,
497 ): () => void {
498 const atom = previewStateAtom(scopedThreadKey(ref));
499 if (appAtomRegistry.get(atom).sessions[tabId]) {
500 action();
501 return () => {};
502 }
503 const stop = () => {
504 clearTimeout(timer);
505 unsubscribe();
506 };
507 const unsubscribe = appAtomRegistry.subscribe(atom, (state) => {
508 if (!state.sessions[tabId]) return;
509 stop();
510 action();
511 });
512 const timer = setTimeout(stop, timeoutMs);
513 return stop;
514 }
515
516 export function rememberPreviewUrl(ref: ScopedThreadRef, url: string): void {
517 if (url.trim().length === 0) return;
518 updateThreadPreviewState(ref, (current) => ({
519 ...current,
520 recentlySeenUrls: dedupeRecentUrls(current.recentlySeenUrls, url),
521 }));
522 }
523
524 export function isPreviewSupportedInRuntime(): boolean {
525 if (typeof window === "undefined") return false;
526 return Boolean(window.desktopBridge?.preview);
527 }
528
529 /** Releases desktop-host pages as well as local session state. */
530 export function clearThreadPreviewState(ref: ScopedThreadRef): void {
531 updateThreadPreviewState(ref, (current) =>
532 Object.keys(current.sessions).length === 0 ? current : EMPTY_THREAD_PREVIEW_STATE,
533 );
534 }
535
536 export function resetPreviewStateForTests(): void {
537 for (const threadKey of appAtomRegistry.get(previewThreadRefsAtom).keys()) {
538 appAtomRegistry.set(previewStateAtom(threadKey), EMPTY_THREAD_PREVIEW_STATE);
539 }
540 appAtomRegistry.set(previewThreadRefsAtom, new Map());
541 appAtomRegistry.set(activePreviewThreadKeysAtom, { keys: new Set<string>() });
542 }
543
544 export const __testing = {
545 EMPTY_THREAD_PREVIEW_STATE,
546 RECENT_URL_LIMIT: PREVIEW_RECENT_URL_LIMIT,
547 };