Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopCliShim.ts

190 lines8.1 KB

1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import * as Random from "effect/Random";
6​
7import * as DesktopEnvironment from "./DesktopEnvironment.ts";
8import { makeComponentLogger } from "./DesktopObservability.ts";
9​
10// AppImage mounts change each run; the launcher must mount the image itself.
11const { logInfo, logWarning } = makeComponentLogger("desktop-cli-shim");
12​
13export const MARKER = "Written by T3 Code: runs the desktop app's bundled t3 CLI.";
14​
15const SERVER_ENTRY = "apps/server/dist/bin.mjs";
16​
17const shellWord = (value: string) => `'${value.replaceAll("'", `'"'"'`)}'`;
18/** cmd.exe expands `%` even inside quotes; Windows paths cannot contain `"`. */
19const cmdText = (value: string) => value.replaceAll("%", "%%");
20const cmdWord = (value: string) => `"${cmdText(value)}"`;
21​
22const MOVED = "T3 Code has moved or been removed. Open the app once to update this command.";
23​
24export type CliShimTarget =
25 | { readonly kind: "appimage"; readonly appImage: string; readonly executableName: string }
26 | { readonly kind: "direct"; readonly executable: string; readonly entry: string }
27 | { readonly kind: "windows"; readonly executable: string; readonly entry: string };
28​
29/** Embed this install's home and executable path so `sudo`, which clears the environment, uses the same install. */
30export const renderCliShim = (input: {
31 readonly target: CliShimTarget;
32 readonly shimPath: string;
33 readonly t3Home: string;
34}) => {
35 const { target } = input;
36 if (target.kind === "windows") {
37 const utf8 = [target.executable, target.entry, input.shimPath, input.t3Home].some((value) =>
38 [...value].some((character) => character.codePointAt(0)! > 0x7f),
39 );
40 const restore = utf8 ? ["chcp %t3_codepage% >nul"] : [];
41 return [
42 "@echo off",
43 `rem ${MARKER}`,
44 // Delayed expansion would rewrite `!name!` in paths and arguments.
45 "setlocal EnableExtensions DisableDelayedExpansion",
46 // Ctrl-C skips codepage restoration, so switch to UTF-8 only for non-ASCII install paths.
47 ...(utf8
48 ? [
49 `for /f "tokens=2 delims=:." %%c in ('chcp') do set "t3_codepage=%%c"`,
50 "chcp 65001 >nul",
51 ]
52 : []),
53 `set "T3CODE_CLI_PATH=${cmdText(input.shimPath)}"`,
54 `if not defined T3CODE_HOME set "T3CODE_HOME=${cmdText(input.t3Home)}"`,
55 'set "ELECTRON_RUN_AS_NODE=1"',
56 // Electron's Windows executable starts without stdin; this tells the CLI to reopen the console.
57 'set "T3CODE_DESKTOP_CLI_LAUNCHER=1"',
58 // A goto, not a parenthesized block: "Program Files (x86)" would close the block early.
59 `if exist ${cmdWord(target.executable)} goto run`,
60 ...restore,
61 `echo ${MOVED} 1>&2`,
62 "exit /b 127",
63 ":run",
64 `${cmdWord(target.executable)} ${cmdWord(target.entry)} %*`,
65 'set "t3_exit=%ERRORLEVEL%"',
66 ...restore,
67 "exit /b %t3_exit%",
68 "",
69 ].join("\r\n");
70 }
71 const header = [
72 "#!/bin/sh",
73 `# ${MARKER}`,
74 `export T3CODE_CLI_PATH=${shellWord(input.shimPath)}`,
75 `home=${shellWord(input.t3Home)}`,
76 'export T3CODE_HOME="${T3CODE_HOME:-$home}"',
77 "export ELECTRON_RUN_AS_NODE=1",
78 `app=${shellWord(target.kind === "appimage" ? target.appImage : target.executable)}`,
79 'if [ ! -x "$app" ]; then',
80 ` echo "${MOVED}" >&2`,
81 " exit 127",
82 "fi",
83 ];
84 if (target.kind === "direct") {
85 return [...header, `exec "$app" ${shellWord(target.entry)} "$@"`, ""].join("\n");
86 }
87 const run = (root: string) =>
88 `"${root}/${target.executableName}" "${root}/resources/app.asar/${SERVER_ENTRY}" "$@"`;
89 return [
90 ...header,
91 // Extract-and-run would make the runtime start the app instead of mounting it.
92 "unset APPIMAGE_EXTRACT_AND_RUN",
93 // Its own session keeps a group signal (Ctrl-C, SSH hangup) from unmounting it under the
94 // running server, and ignoring TERM survives a stop sent to every process (systemd's default).
95 // Without setsid the extract fallback runs.
96 "work=$(mktemp -d) || exit 1",
97 "trap '' TERM",
98 'setsid "$app" --appimage-mount >"$work/mount" 2>/dev/null &',
99 "mounter=$!",
100 // It unmounts itself on TERM, which it now ignores, so the trap unmounts it. Lazily, like the
101 // runtime: the server's own children may still be exiting.
102 `trap '[ -z "$mount" ] || fusermount3 -uz "$mount" 2>/dev/null || fusermount -uz "$mount" 2>/dev/null; kill -HUP "$mounter" 2>/dev/null; rm -rf "$work"' EXIT`,
103 "trap 'exit 130' INT TERM HUP",
104 "mount=",
105 'while kill -0 "$mounter" 2>/dev/null; do',
106 ' mount=$(head -n 1 "$work/mount")',
107 ' [ -d "$mount" ] && break',
108 " mount=",
109 " sleep 0.05",
110 "done",
111 // Without FUSE the runtime cannot mount (it prints why and exits); extracting the image still works.
112 'if [ -z "$mount" ]; then',
113 ' (cd "$work" && "$app" --appimage-extract >/dev/null) || { echo "Could not open $app." >&2; exit 1; }',
114 ' mount="$work/squashfs-root"',
115 "fi",
116 // The runtime sets this when it launches the app; the CLI skips its path-keyed compile cache on it.
117 'export APPIMAGE="$app"',
118 // The shell must outlive the CLI to unmount, so it forwards TERM and HUP; the terminal sends
119 // Ctrl-C to the CLI directly. A background child would read /dev/null, so pass stdin on fd 9.
120 // With stdin closed, `exec 9<&0` would end the shell; `command` makes it a normal error.
121 "{ command exec 9<&0; } 2>/dev/null || exec 9</dev/null",
122 `${run("$mount")} <&9 9<&- &`,
123 "cli=$!",
124 "exec 9<&-",
125 `trap 'kill -TERM "$cli" 2>/dev/null' TERM`,
126 `trap 'kill -HUP "$cli" 2>/dev/null' HUP`,
127 "trap '' INT",
128 "status=0",
129 'wait "$cli" || status=$?',
130 // A trapped signal interrupts wait; wait again for the CLI's own exit status.
131 'while kill -0 "$cli" 2>/dev/null; do',
132 " status=0",
133 ' wait "$cli" || status=$?',
134 "done",
135 'exit "$status"',
136 "",
137 ].join("\n");
138};
139​
140export const launcherPath = (environment: DesktopEnvironment.DesktopEnvironment["Service"]) =>
141 environment.path.join(
142 environment.baseDir,
143 "bin",
144 environment.platform === "win32" ? "t3.cmd" : "t3",
145 );
146​
147export const install = Effect.gen(function* () {
148 const environment = yield* DesktopEnvironment.DesktopEnvironment;
149 if (!environment.isPackaged) return Option.none<string>();
150 const fs = yield* FileSystem.FileSystem;
151 const path = environment.path;
152 const windows = environment.platform === "win32";
153 const shimPath = launcherPath(environment);
154 const entry = path.join(environment.serverRoot, SERVER_ENTRY);
155 const target: CliShimTarget = windows
156 ? { kind: "windows", executable: process.execPath, entry }
157 : Option.match(environment.appImagePath, {
158 onSome: (appImage) => ({
159 kind: "appimage" as const,
160 appImage,
161 executableName: path.basename(process.execPath),
162 }),
163 onNone: () => ({ kind: "direct" as const, executable: process.execPath, entry }),
164 });
165 const content = renderCliShim({ target, shimPath, t3Home: environment.baseDir });
166​
167 return yield* Effect.gen(function* () {
168 const existing = yield* fs.readFileString(shimPath).pipe(Effect.option);
169 if (Option.isSome(existing) && !existing.value.includes(MARKER)) {
170 yield* logWarning("leaving a t3 launcher the app did not write", { shimPath });
171 return Option.none<string>();
172 }
173 if (Option.getOrUndefined(existing) !== content) {
174 yield* fs.makeDirectory(path.dirname(shimPath), { recursive: true });
175 // Unique per call: backend startup and the first-launch command install can race here.
176 const staging = `${shimPath}.${process.pid}.${yield* Random.nextIntBetween(0, 0xffffff)}.tmp`;
177 yield* fs.writeFileString(staging, content, { mode: 0o755 });
178 yield* fs.rename(staging, shimPath);
179 yield* logInfo("installed t3 launcher", { shimPath });
180 }
181 return Option.some(shimPath);
182 }).pipe(
183 Effect.catchCause((cause) =>
184 logWarning("could not install t3 launcher", { shimPath, cause: Cause.pretty(cause) }).pipe(
185 Effect.as(Option.none<string>()),
186 ),
187 ),
188 Effect.withSpan("desktop.cliShim.install"),
189 );
190});