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