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
| 1 | import { useAtomValue } from "@effect/atom-react"; |
| 2 | import { |
| 3 | parseScopedThreadKey, |
| 4 | scopeThreadRef, |
| 5 | scopedThreadKey, |
| 6 | } from "@t3tools/client-runtime/environment"; |
| 7 | import { type EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import { AsyncResult, Atom } from "effect/reactivity"; |
| 10 | |
| 11 | import { |
| 12 | applyPreviewServerEvent, |
| 13 | previewStateAtom, |
| 14 | readThreadPreviewState, |
| 15 | reconcilePreviewServerSessions, |
| 16 | } from "~/previewStateStore"; |
| 17 | import { isElectron } from "~/env"; |
| 18 | import { previewEnvironment } from "~/state/preview"; |
| 19 | |
| 20 | class PreviewSessionThreadKeyParseError extends Schema.TaggedError<PreviewSessionThreadKeyParseError>()( |
| 21 | "PreviewSessionThreadKeyParseError", |
| 22 | { threadKey: Schema.String }, |
| 23 | ) { |
| 24 | override get message(): string { |
| 25 | return `Invalid scoped preview thread key: ${this.threadKey}`; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | const previewSessionSyncAtom = Atom.family((threadKey: string) => { |
| 30 | const threadRef = parseScopedThreadKey(threadKey); |
| 31 | if (threadRef === null) { |
| 32 | throw new PreviewSessionThreadKeyParseError({ threadKey }); |
| 33 | } |
| 34 | |
| 35 | const sessionsAtom = previewEnvironment.list({ |
| 36 | environmentId: threadRef.environmentId, |
| 37 | input: { threadId: threadRef.threadId }, |
| 38 | }); |
| 39 | const eventsAtom = previewEnvironment.events({ |
| 40 | environmentId: threadRef.environmentId, |
| 41 | input: {}, |
| 42 | }); |
| 43 | |
| 44 | return Atom.make((get) => { |
| 45 | let disposed = false; |
| 46 | let eventsVersion = 0; |
| 47 | |
| 48 | const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => { |
| 49 | if (result.waiting || !AsyncResult.isSuccess(result)) return; |
| 50 | reconcilePreviewServerSessions(threadRef, result.value); |
| 51 | if (!readThreadPreviewState(threadRef).listLoaded) { |
| 52 | // An event overtook the initial list; retry before using the partial index for surface cleanup. |
| 53 | queueMicrotask(() => { |
| 54 | if (!disposed) get.refresh(sessionsAtom); |
| 55 | }); |
| 56 | } |
| 57 | }; |
| 58 | |
| 59 | const applyLatestEvent = (result: Atom.Type<typeof eventsAtom>) => { |
| 60 | if (!AsyncResult.isSuccess(result) || result.value.threadId !== threadRef.threadId) return; |
| 61 | const currentEpoch = readThreadPreviewState(threadRef).serverEpoch; |
| 62 | if (currentEpoch !== null && currentEpoch !== result.value.serverEpoch) { |
| 63 | get.refresh(sessionsAtom); |
| 64 | return; |
| 65 | } |
| 66 | applyPreviewServerEvent(threadRef, result.value); |
| 67 | }; |
| 68 | |
| 69 | get.addFinalizer(() => { |
| 70 | disposed = true; |
| 71 | }); |
| 72 | const initialEvent = get.once(eventsAtom); |
| 73 | // Evaluate the lazy list, then reconcile only new responses because cached results can be stale. |
| 74 | get.once(sessionsAtom); |
| 75 | get.subscribe(sessionsAtom, (result) => { |
| 76 | reconcileSessions(result); |
| 77 | }); |
| 78 | get.subscribe(eventsAtom, (result) => { |
| 79 | eventsVersion += 1; |
| 80 | applyLatestEvent(result); |
| 81 | }); |
| 82 | get.mount(sessionsAtom); |
| 83 | get.mount(eventsAtom); |
| 84 | queueMicrotask(() => { |
| 85 | if (disposed) return; |
| 86 | // Keep local tabs until authoritative refresh; stale cached emptiness could remove automation-created |
| 87 | // tabs. |
| 88 | const current = get.once(sessionsAtom); |
| 89 | if (!AsyncResult.isInitial(current) && !current.waiting) get.refresh(sessionsAtom); |
| 90 | if (eventsVersion === 0) applyLatestEvent(initialEvent); |
| 91 | }); |
| 92 | }).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`)); |
| 93 | }); |
| 94 | |
| 95 | export function usePreviewSession(threadRef: ScopedThreadRef): void { |
| 96 | useAtomValue(previewSessionSyncAtom(scopedThreadKey(threadRef))); |
| 97 | } |
| 98 | |
| 99 | const inactiveAtom = Atom.make(() => undefined); |
| 100 | |
| 101 | // Discover background tabs without listing every thread at startup. Keep each |
| 102 | // sync while the thread has tabs so later events still arrive while chat is |
| 103 | // absent, then release it so closed previews stop costing a list and a fan-out. |
| 104 | const desktopHostedPreviewSyncAtom = Atom.family((environmentId: EnvironmentId) => { |
| 105 | const eventsAtom = previewEnvironment.events({ environmentId, input: {} }); |
| 106 | return Atom.make((get) => { |
| 107 | const releaseByThreadId = new Map<string, () => void>(); |
| 108 | get.addFinalizer(() => { |
| 109 | for (const release of releaseByThreadId.values()) release(); |
| 110 | }); |
| 111 | get.subscribe( |
| 112 | eventsAtom, |
| 113 | (result) => { |
| 114 | if (!AsyncResult.isSuccess(result) || result.value.type === "closed") return; |
| 115 | const threadId = result.value.threadId; |
| 116 | if (releaseByThreadId.has(threadId)) return; |
| 117 | const threadKey = scopedThreadKey(scopeThreadRef(environmentId, ThreadId.make(threadId))); |
| 118 | const unmount = get.registry.mount(previewSessionSyncAtom(threadKey)); |
| 119 | // The opening event may not be applied yet, so wait until a tab has |
| 120 | // been seen. A pending local close can still be cancelled and restored. |
| 121 | let hadSessions = false; |
| 122 | const unwatch = get.registry.subscribe( |
| 123 | previewStateAtom(threadKey), |
| 124 | (state) => { |
| 125 | if (Object.keys(state.sessions).length > 0) hadSessions = true; |
| 126 | else if (hadSessions && state.suppressedTabIds.size === 0) release(); |
| 127 | }, |
| 128 | { immediate: true }, |
| 129 | ); |
| 130 | function release() { |
| 131 | unwatch(); |
| 132 | unmount(); |
| 133 | releaseByThreadId.delete(threadId); |
| 134 | } |
| 135 | releaseByThreadId.set(threadId, release); |
| 136 | }, |
| 137 | { immediate: true }, |
| 138 | ); |
| 139 | }).pipe(Atom.withLabel(`preview:desktop-hosted-sync:${environmentId}`)); |
| 140 | }); |
| 141 | |
| 142 | export function useDesktopHostedPreviewSessions(environmentId: EnvironmentId | null): void { |
| 143 | useAtomValue( |
| 144 | isElectron && environmentId !== null |
| 145 | ? desktopHostedPreviewSyncAtom(environmentId) |
| 146 | : inactiveAtom, |
| 147 | ); |
| 148 | } |