@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
ts 115 lines 3.97 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3 import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
4 import * as Schema from "effect/Schema";
5 import { msg } from "gt-react";
6
7 import { toastManager } from "~/components/ui/toast";
8 import { m } from "~/i18n/messages";
9 import { updatePreviewServerSnapshot } from "~/previewStateStore";
10 import { appAtomRegistry } from "~/rpc/atomRegistry";
11 import { previewEnvironment } from "~/state/preview";
12
13 /** One browser tab as both the server (thread + tab id) and this window's runtime know it. */
14 export interface BrowserViewportTarget {
15 readonly threadRef: ScopedThreadRef;
16 readonly tabId: string;
17 readonly runtimeTabId: string;
18 }
19
20 const BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS = 15_000;
21
22 class BrowserViewportCommitTimeoutError extends Schema.TaggedError<BrowserViewportCommitTimeoutError>()(
23 "BrowserViewportCommitTimeoutError",
24 { tabId: Schema.String },
25 ) {
26 override get message(): string {
27 return `Timed out committing the browser viewport for tab ${this.tabId}`;
28 }
29 }
30
31 const commitTails = new Map<string, Promise<void>>();
32
33 /** Serializes UI and automation mutations per tab so rollback cannot overtake a newer resize. */
34 const queueBrowserViewportMutation = <A>(
35 tabId: string,
36 start: () => Promise<A>,
37 ): {
38 readonly started: Promise<{ readonly operation: Promise<A> }>;
39 readonly execution: Promise<A>;
40 } => {
41 const previous = commitTails.get(tabId) ?? Promise.resolve();
42 const started = previous
43 .catch(() => undefined)
44 .then(() => ({
45 operation: Promise.resolve().then(start),
46 }));
47 const execution = started.then(({ operation }) => operation);
48 const tail = execution.then(() => undefined);
49 commitTails.set(tabId, tail);
50 const clear = () => {
51 if (commitTails.get(tabId) === tail) commitTails.delete(tabId);
52 };
53 void tail.then(clear, clear);
54 return { started, execution };
55 };
56
57 const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
58 let timeoutId: ReturnType<typeof setTimeout> | undefined;
59 const timeout = new Promise<never>((_resolve, reject) => {
60 timeoutId = setTimeout(
61 () => reject(new BrowserViewportCommitTimeoutError({ tabId })),
62 BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
63 );
64 });
65 return Promise.race([operation, timeout]).finally(() => {
66 if (timeoutId !== undefined) clearTimeout(timeoutId);
67 });
68 };
69
70 async function resizeBrowserViewport(
71 target: BrowserViewportTarget,
72 viewport: PreviewViewportSetting,
73 ): Promise<void> {
74 const result = await runAtomCommand(
75 appAtomRegistry,
76 previewEnvironment.resize,
77 {
78 environmentId: target.threadRef.environmentId,
79 input: { threadId: target.threadRef.threadId, tabId: target.tabId, viewport },
80 },
81 { label: "preview viewport resize" },
82 );
83 if (result._tag === "Failure") {
84 const error = squashAtomCommandFailure(result);
85 toastManager.add({
86 type: "error",
87 title: m(msg("Unable to resize browser viewport")),
88 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
89 });
90 throw error;
91 }
92 updatePreviewServerSnapshot(target.threadRef, result.value);
93 }
94
95 /**
96 * Runs `operation` after every earlier commit for the runtime tab. The
97 * caller-facing timeout starts only once it reaches the front of the queue,
98 * while the queue itself waits for the real operation.
99 */
100 export function queueBrowserViewportCommit(
101 runtimeTabId: string,
102 operation: () => Promise<void>,
103 ): Promise<void> {
104 const { started } = queueBrowserViewportMutation(runtimeTabId, operation);
105 return started.then(({ operation: running }) => runHandlerWithTimeout(runtimeTabId, running));
106 }
107
108 export function commitBrowserViewportChange(
109 target: BrowserViewportTarget,
110 setting: PreviewViewportSetting,
111 ): Promise<void> {
112 return queueBrowserViewportCommit(target.runtimeTabId, () =>
113 resizeBrowserViewport(target, setting),
114 );
115 }