@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 254 lines 10.3 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - Executes the generated remote launcher in an isolated shell with fake commands and clock.
2 import * as NodeFS from "node:fs";
3 import * as NodePath from "node:path";
4 import * as NodeURL from "node:url";
5 import * as NodeChildProcess from "node:child_process";
6 import * as NodeSqlite from "node:sqlite";
7 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
8 import * as NodeServices from "@effect/platform-node/NodeServices";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Sink from "effect/Sink";
12 import * as Stream from "effect/Stream";
13 import { ChildProcessSpawner } from "effect/process";
14 import { launchOrReuseRemoteServer, type RemoteT3RunnerOptions } from "./tunnel.ts";
15
16 // Capture exactly the script sent over SSH, then run it with fake remote commands.
17 export const captureLauncherFor = Effect.fn("test.captureLauncher")(function* (
18 runner: RemoteT3RunnerOptions,
19 ) {
20 let script = "";
21 const spawner = ChildProcessSpawner.make((command) =>
22 Effect.gen(function* () {
23 if (command._tag === "StandardCommand") {
24 const stdin = command.options.stdin;
25 if (typeof stdin === "object" && "stream" in stdin && Stream.isStream(stdin.stream)) {
26 script = yield* stdin.stream.pipe(Stream.decodeText(), Stream.mkString);
27 }
28 }
29 return ChildProcessSpawner.makeHandle({
30 pid: ChildProcessSpawner.ProcessId(123),
31 stdout: Stream.make(new TextEncoder().encode('{"remotePort":3773}\n')),
32 stderr: Stream.empty,
33 all: Stream.empty,
34 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
35 isRunning: Effect.succeed(false),
36 kill: () => Effect.void,
37 stdin: Sink.drain,
38 getInputFd: () => Sink.drain,
39 getOutputFd: () => Stream.empty,
40 unref: Effect.succeed(Effect.void),
41 });
42 }),
43 );
44 yield* launchOrReuseRemoteServer(
45 { alias: "test", hostname: "test.invalid", username: null, port: null },
46 undefined,
47 runner,
48 ).pipe(
49 Effect.provide(
50 Layer.mergeAll(
51 NodeServices.layer,
52 NodeCrypto.layer,
53 Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
54 ),
55 ),
56 );
57 return script;
58 });
59
60 export const captureLauncher = captureLauncherFor({ nodeScriptPath: "/fake/server.ts" });
61
62 function holdLock(path: string) {
63 const db = new NodeSqlite.DatabaseSync(path);
64 db.exec("BEGIN EXCLUSIVE;");
65 return { [Symbol.dispose]: () => db.close() };
66 }
67
68 export function runLauncher(
69 script: string,
70 options: {
71 readonly marker?: unknown;
72 readonly archive?: boolean;
73 readonly clearMarkerOnReady?: boolean;
74 readonly recordedKind?: "managed" | "external";
75 readonly clockJump?: number;
76 readonly readyAt?: number;
77 readonly initialPort?: number;
78 // A boot service between two servers holds the home with no runtime record yet.
79 readonly serviceServing?: boolean;
80 readonly allowFailure?: boolean;
81 // The desktop publishes runtime and removes the marker right after the first runtime read.
82 readonly publishAfterFirstRuntimeRead?: boolean;
83 },
84 ) {
85 const root = NodeURL.fileURLToPath(new URL("../../../", import.meta.url));
86 const home = NodeFS.mkdtempSync(NodePath.join(root, "packages/ssh/.ssh-launcher-test-"));
87 try {
88 const bin = NodePath.join(home, "bin");
89 const runtime = NodePath.join(home, ".t3/runtime");
90 NodeFS.mkdirSync(bin);
91 NodeFS.mkdirSync(runtime, { recursive: true });
92 const markerPath = NodePath.join(runtime, "desktop-update-in-progress");
93 if (options.marker)
94 NodeFS.writeFileSync(
95 markerPath,
96 typeof options.marker === "string" ? options.marker : JSON.stringify(options.marker),
97 );
98 NodeFS.writeFileSync(NodePath.join(home, "clock"), "0");
99 NodeFS.writeFileSync(NodePath.join(home, "events"), "");
100 const executable = (name: string, body: string) =>
101 NodeFS.writeFileSync(NodePath.join(bin, name), `#!/bin/sh\nset -eu\n${body}\n`, {
102 mode: 0o755,
103 });
104 NodeFS.writeFileSync(
105 NodePath.join(home, "clock.cjs"),
106 `
107 const fs = require('node:fs');
108 Date.now = () => Number(fs.readFileSync(process.env.HOME + '/clock', 'utf8'));
109 `,
110 );
111 executable(
112 options.archive ? "test-node" : "node",
113 `
114 case "\${2:-}" in
115 */server-runtime.json)
116 # A started server publishes its runtime record, which the launch waits for.
117 # The fake nohup runs in the background, so wait for it instead of racing it.
118 if [ -e "$HOME/picked-port" ]; then
119 while [ ! -e "$HOME/started-server" ]; do /bin/sleep 0.01; done
120 fi
121 if [ -e "$HOME/started-server" ]; then
122 printf 'record %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"
123 printf '%s 5999' "$(cat "$HOME/started-server")"
124 exit 0
125 fi
126 NOW="$(cat "$HOME/clock")"
127 printf 'runtime %s\\n' "$NOW" >> "$HOME/events"
128 if [ "$NOW" -ge "$TEST_READY_AT" ] || [ -e "$2" ]; then printf '%s %s' "$TEST_SERVER_PID" 4888
129 elif [ "$TEST_PUBLISH_AFTER_FIRST_READ" = 1 ]; then
130 mkdir -p "\${2%/*}"
131 printf '{}' > "$2"
132 rm -f "$HOME/.t3/runtime/desktop-update-in-progress"
133 exit 1
134 elif [ -n "$TEST_INITIAL_PORT" ]; then printf '%s %s' "$TEST_SERVER_PID" "$TEST_INITIAL_PORT"
135 else exit 1; fi ;;
136 */port)
137 printf 'start %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"
138 touch "$HOME/picked-port"
139 printf 5999 ;;
140 [0-9]*)
141 NOW="$(cat "$HOME/clock")"
142 printf 'probe %s %s\\n' "$2" "$NOW" >> "$HOME/events"
143 [ "$2" = 5999 ] || { [ "$2" = 4888 ] && { [ "$NOW" -ge "$TEST_READY_AT" ] || [ -e "$HOME/.t3/userdata/server-runtime.json" ]; }; } ;;
144 */desktop-update-in-progress)
145 printf 'marker %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"
146 exec "$TEST_REAL_NODE" --require "$HOME/clock.cjs" "$@" ;;
147 *) exec "$TEST_REAL_NODE" --require "$HOME/clock.cjs" "$@" ;;
148 esac`,
149 );
150 executable(
151 "sleep",
152 `awk -v seconds="$1" '{ printf "%.0f", $1 + seconds * 1000 }' "$HOME/clock" > "$HOME/clock.next"
153 mv "$HOME/clock.next" "$HOME/clock"
154 if [ "$TEST_CLEAR_MARKER" = 1 ] && [ "$(cat "$HOME/clock")" -ge "$TEST_READY_AT" ]; then
155 rm -f "$HOME/.t3/runtime/desktop-update-in-progress"
156 fi
157 if [ -n "$TEST_CLOCK_JUMP" ] && [ ! -e "$HOME/jumped" ]; then
158 printf '%s' "$TEST_CLOCK_JUMP" > "$HOME/clock"
159 touch "$HOME/jumped"
160 fi`,
161 );
162 executable("nohup", 'printf "%s" "$$" > "$HOME/started-server"');
163 // The test process stands in for a recorded server; report the serve command it would run.
164 executable(
165 "ps",
166 `if [ "$*" = "-ww -o args= -p $TEST_SERVER_PID" ]; then
167 printf '/bin/sh %s/.t3/ssh-launch/test-target/run-t3.sh serve --host 127.0.0.1 --port 5999\\n' "$HOME"
168 exit 0
169 fi
170 PATH=/usr/bin:/bin exec ps "$@"`,
171 );
172 if (options.recordedKind) {
173 const state = NodePath.join(home, ".t3/ssh-launch/test-target");
174 NodeFS.mkdirSync(state, { recursive: true });
175 NodeFS.writeFileSync(NodePath.join(state, "pid"), String(process.pid));
176 NodeFS.writeFileSync(NodePath.join(state, "port"), "5999");
177 NodeFS.writeFileSync(NodePath.join(state, "managed"), options.recordedKind);
178 const runner = script.split("cat >\"$RUNNER_NEXT\" <<'SH'\n")[1]?.split("\nSH\n")[0];
179 if (!runner) throw new Error("runner missing");
180 NodeFS.writeFileSync(NodePath.join(state, "run-t3.sh"), runner + "\n");
181 }
182 if (options.archive) {
183 executable("node", 'printf "unexpected host node invocation\\n" >&2; exit 1');
184 const version = NodePath.join(home, ".t3/runtime/versions/1.2.3");
185 NodeFS.mkdirSync(version, { recursive: true });
186 NodeFS.writeFileSync(NodePath.join(version, ".install-complete"), "1.2.3");
187 NodeFS.writeFileSync(
188 NodePath.join(home, "helper.ts"),
189 `
190 import * as Effect from "effect/Effect";
191 import * as NodeServices from "@effect/platform-node/NodeServices";
192 import { Command } from "effect/cli";
193 import { sshHelperCommand } from ${JSON.stringify(NodePath.join(root, "apps/server/src/cli/sshHelper.ts"))};
194 await Effect.runPromise(Command.runWith(sshHelperCommand, { version: "1.2.3" })(process.argv.slice(2)).pipe(Effect.provide(NodeServices.layer)));
195 `,
196 );
197 NodeFS.writeFileSync(
198 NodePath.join(version, "t3"),
199 `#!/bin/sh
200 set -eu
201 if [ "$1" = --version ]; then printf 1.2.3; exit; fi
202 [ "$1" = __ssh-helper ]
203 case "$2" in
204 update-remaining) printf 'marker %s\\n' "$(cat "$HOME/clock")" >> "$HOME/events"; exec "$TEST_REAL_NODE" --require "$HOME/clock.cjs" "$HOME/helper.ts" "$2" "$3" ;;
205 home-owned) exec "$TEST_REAL_NODE" "$HOME/helper.ts" "$2" "$3" ;;
206 runtime-port | pick-port | wait-ready) exec "$HOME/bin/test-node" - "$3" ;;
207 *) exit 1 ;;
208 esac
209 `,
210 { mode: 0o755 },
211 );
212 }
213 using _serving = options.serviceServing
214 ? holdLock(NodePath.join(runtime, "service-serving.lock"))
215 : undefined;
216 const result = NodeChildProcess.spawnSync("/bin/sh", ["-s", "--", "test-target"], {
217 input: `kill() {
218 if [ "$1" = -0 ]; then command kill "$@"; else
219 printf 'kill %s\\n' "$*" >> "$HOME/events"
220 return 1
221 fi
222 }
223 ${script}`,
224 encoding: "utf8",
225 timeout: 30_000,
226 env: {
227 ...process.env,
228 HOME: home,
229 PATH: `${bin}:/usr/bin:/bin`,
230 TEST_REAL_NODE: process.execPath,
231 TEST_CLEAR_MARKER: options.clearMarkerOnReady ? "1" : "0",
232 TEST_CLOCK_JUMP: options.clockJump === undefined ? "" : String(options.clockJump),
233 TEST_SERVER_PID: String(process.pid),
234 TEST_READY_AT: String(options.readyAt ?? 1_000_000),
235 TEST_INITIAL_PORT: options.initialPort === undefined ? "" : String(options.initialPort),
236 TEST_PUBLISH_AFTER_FIRST_READ: options.publishAfterFirstRuntimeRead ? "1" : "0",
237 },
238 });
239 if (result.error || (result.status !== 0 && !options.allowFailure))
240 throw new Error(
241 `launcher failed: ${result.error ?? result.status}\n${result.stderr}\n${result.stdout}\n${NodeFS.readFileSync(NodePath.join(home, "events"), "utf8")}`,
242 );
243 return {
244 status: result.status,
245 stderr: result.stderr,
246 output: result.status === 0 ? JSON.parse(result.stdout.trim()) : undefined,
247 events: NodeFS.readFileSync(NodePath.join(home, "events"), "utf8").trim().split("\n"),
248 now: Number(NodeFS.readFileSync(NodePath.join(home, "clock"), "utf8")),
249 markerExists: NodeFS.existsSync(markerPath),
250 };
251 } finally {
252 NodeFS.rmSync(home, { recursive: true, force: true });
253 }
254 }