The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; |
| 2 | import type { |
| 3 | EnvironmentId, |
| 4 | PreviewCloseInput, |
| 5 | PreviewSessionSnapshot, |
| 6 | ScopedThreadRef, |
| 7 | } from "@t3tools/contracts"; |
| 8 | |
| 9 | import { rendersServerTabNatively } from "~/browser/previewRuntime"; |
| 10 | import { useClosedViewStore } from "~/closedViewStore"; |
| 11 | import { beginPreviewSessionClose, cancelPreviewSessionClose } from "~/previewStateStore"; |
| 12 | import { appAtomRegistry } from "~/rpc/atomRegistry"; |
| 13 | import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment"; |
| 14 | |
| 15 | interface ClosePreviewSessionInput<E> { |
| 16 | readonly closePreview: (input: { |
| 17 | readonly environmentId: EnvironmentId; |
| 18 | readonly input: PreviewCloseInput; |
| 19 | }) => Promise<AtomCommandResult<void, E>>; |
| 20 | readonly snapshot: PreviewSessionSnapshot | null; |
| 21 | readonly tabId: string; |
| 22 | readonly threadRef: ScopedThreadRef; |
| 23 | } |
| 24 | |
| 25 | export async function closePreviewSession<E>( |
| 26 | input: ClosePreviewSessionInput<E>, |
| 27 | ): Promise<AtomCommandResult<void, E>> { |
| 28 | // Unmounting a webview destroys its page, so a tab this window renders stays mounted until the |
| 29 | // server has unloaded it. |
| 30 | const keepMounted = rendersServerTabNatively( |
| 31 | input.threadRef.environmentId, |
| 32 | appAtomRegistry.get(primaryEnvironmentIdAtom), |
| 33 | input.snapshot, |
| 34 | ); |
| 35 | if (!keepMounted) beginPreviewSessionClose(input.threadRef, input.tabId); |
| 36 | const result = await input.closePreview({ |
| 37 | environmentId: input.threadRef.environmentId, |
| 38 | input: { threadId: input.threadRef.threadId, tabId: input.tabId }, |
| 39 | }); |
| 40 | if (result._tag === "Failure") { |
| 41 | cancelPreviewSessionClose(input.threadRef, input.snapshot, input.tabId); |
| 42 | return result; |
| 43 | } |
| 44 | if (keepMounted) beginPreviewSessionClose(input.threadRef, input.tabId); |
| 45 | if (input.snapshot) { |
| 46 | useClosedViewStore.getState().remember({ |
| 47 | kind: "browser", |
| 48 | threadRef: input.threadRef, |
| 49 | snapshot: input.snapshot, |
| 50 | }); |
| 51 | } |
| 52 | return result; |
| 53 | } |