@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 68 lines 1.79 KB
Raw
1 import { chunkTerminalWrite } from "@t3tools/contracts";
2
3 import { encodeTerminalPaste } from "./terminalInput";
4
5 interface TerminalPasteInput {
6 readonly readText: () => Promise<string>;
7 readonly write: (data: string) => Promise<boolean>;
8 readonly onReadError: (cause: unknown) => void;
9 }
10
11 export interface TerminalPasteSession {
12 readonly reset: (active: boolean) => void;
13 /** True until the terminal's liveness changes (stop, start or restart) after this call. */
14 readonly liveness: () => () => boolean;
15 readonly paste: (input: TerminalPasteInput) => Promise<void>;
16 }
17
18 export function createTerminalPasteSession(): TerminalPasteSession {
19 let liveTarget: object | null = null;
20 let latestRequest = 0;
21 let writeTail: Promise<void> = Promise.resolve();
22
23 return {
24 reset(active) {
25 liveTarget = active ? {} : null;
26 },
27
28 liveness() {
29 const target = liveTarget;
30 return () => liveTarget === target;
31 },
32
33 async paste({ readText, write, onReadError }) {
34 const target = liveTarget;
35 if (target === null) {
36 return;
37 }
38 const request = ++latestRequest;
39 const isCurrent = () => liveTarget === target && latestRequest === request;
40
41 let text: string;
42 try {
43 text = await readText();
44 } catch (cause) {
45 onReadError(cause);
46 return;
47 }
48
49 if (!isCurrent()) {
50 return;
51 }
52
53 const writePaste = async () => {
54 for (const chunk of chunkTerminalWrite(encodeTerminalPaste(text))) {
55 if (!isCurrent() || !(await write(chunk))) {
56 return;
57 }
58 }
59 };
60 const queuedWrite = writeTail.then(writePaste, writePaste);
61 writeTail = queuedWrite.then(
62 () => undefined,
63 () => undefined,
64 );
65 await queuedWrite;
66 },
67 };
68 }