Open History to see the last commit
1// @effect-diagnostics globalTimers:off -- The Node socket client owns its response deadline and clears it on every completion path.
2// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect stat follows symlinks; IPC ownership validation requires lstat.
3import * as NodeFSP from "node:fs/promises";
4import * as NodeNet from "node:net";
5import * as NodeOS from "node:os";
6
7import {
8 DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
9 DesktopAppActivationErrorCode,
10 DesktopAppActivationResponse,
11 type DesktopAppActivationPlatform,
12 type DesktopAppActivationRequest,
13} from "@t3tools/contracts";
14import {
15 resolveDesktopAppControlAddress,
16 type DesktopAppControlAddress,
17} from "@t3tools/shared/desktopAppControl";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19import * as Config from "effect/Config";
20import * as Console from "effect/Console";
21import * as SecureRandom from "effect/crypto/SecureRandom";
22import * as Effect from "effect/Effect";
23import * as Option from "effect/Option";
24import * as Path from "effect/Path";
25import * as Schema from "effect/Schema";
26import { Argument, Command } from "effect/cli";
27
28import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
29import { baseDirFlag } from "./config.ts";
30
31const CLI_RESPONSE_TIMEOUT_MS = 17_000;
32const MAX_RESPONSE_BYTES = 64 * 1024;
33const isDesktopAppActivationResponse = Schema.is(DesktopAppActivationResponse);
34
35export class DesktopAppSshUnsupportedError extends Schema.TaggedError<DesktopAppSshUnsupportedError>()(
36 "DesktopAppSshUnsupportedError",
37 {},
38) {
39 override get message(): string {
40 return "`t3 app` only controls a desktop app on the same machine. It cannot run over SSH.";
41 }
42}
43
44export class DesktopAppPlatformUnsupportedError extends Schema.TaggedError<DesktopAppPlatformUnsupportedError>()(
45 "DesktopAppPlatformUnsupportedError",
46 { platform: Schema.String },
47) {
48 override get message(): string {
49 return `\`t3 app\` is not supported on ${this.platform}.`;
50 }
51}
52
53export class DesktopAppUnreachableError extends Schema.TaggedError<DesktopAppUnreachableError>()(
54 "DesktopAppUnreachableError",
55 {
56 candidateAddresses: Schema.Array(Schema.String),
57 requestId: Schema.String,
58 workspaceRoot: Schema.String,
59 cause: Schema.Defect(),
60 },
61) {
62 override get message(): string {
63 return "Could not reach the T3 Code desktop app. Start or update the desktop app on this machine, then run `t3 app` again. A running T3 Code server is not enough.";
64 }
65}
66
67export class DesktopAppRequestFailedError extends Schema.TaggedError<DesktopAppRequestFailedError>()(
68 "DesktopAppRequestFailedError",
69 {
70 code: DesktopAppActivationErrorCode,
71 requestId: Schema.String,
72 workspaceRoot: Schema.String,
73 cause: Schema.Defect(),
74 },
75) {
76 override get message(): string {
77 return `T3 Code could not open ${this.workspaceRoot} (${this.code}).`;
78 }
79}
80
81function isDesktopPlatform(platform: NodeJS.Platform): platform is DesktopAppActivationPlatform {
82 return platform === "darwin" || platform === "linux" || platform === "win32";
83}
84
85async function sendDesktopAppActivationRequest(input: {
86 readonly address: DesktopAppControlAddress;
87 readonly fallbackAddress?: DesktopAppControlAddress;
88 readonly userId: number | undefined;
89 readonly request: DesktopAppActivationRequest;
90 readonly timeoutMs?: number;
91}): Promise<DesktopAppActivationResponse> {
92 if (input.address.directory !== null) {
93 const stat = await NodeFSP.lstat(input.address.directory);
94 if (
95 !stat.isDirectory() ||
96 input.userId === undefined ||
97 stat.uid !== input.userId ||
98 (stat.mode & 0o077) !== 0
99 ) {
100 throw new Error("The desktop app socket directory is not private or owned by this user.");
101 }
102 }
103 return new Promise((resolve, reject) => {
104 const socket = NodeNet.createConnection(input.address.address);
105 socket.setEncoding("utf8");
106 let buffer = "";
107 let settled = false;
108 let connected = false;
109
110 const finish = (
111 result:
112 | { readonly type: "success"; readonly response: DesktopAppActivationResponse }
113 | { readonly type: "failure"; readonly error: Error },
114 ) => {
115 if (settled) return;
116 settled = true;
117 clearTimeout(timeout);
118 socket.destroy();
119 if (result.type === "success") resolve(result.response);
120 else reject(result.error);
121 };
122
123 const timeout = setTimeout(() => {
124 finish({
125 type: "failure",
126 error: new Error("The desktop app did not respond in time."),
127 });
128 }, input.timeoutMs ?? CLI_RESPONSE_TIMEOUT_MS);
129
130 socket.once("connect", () => {
131 connected = true;
132 socket.write(`${JSON.stringify(input.request)}\n`);
133 });
134 socket.on("data", (chunk) => {
135 buffer += chunk;
136 if (Buffer.byteLength(buffer, "utf8") > MAX_RESPONSE_BYTES) {
137 finish({ type: "failure", error: new Error("The desktop app response is too large.") });
138 return;
139 }
140 const newline = buffer.indexOf("\n");
141 if (newline === -1) return;
142
143 let parsed: unknown;
144 try {
145 parsed = JSON.parse(buffer.slice(0, newline));
146 } catch {
147 finish({
148 type: "failure",
149 error: new Error("The desktop app response is not valid JSON."),
150 });
151 return;
152 }
153 if (!isDesktopAppActivationResponse(parsed)) {
154 finish({ type: "failure", error: new Error("The desktop app response is invalid.") });
155 return;
156 }
157 if (parsed.requestId !== input.request.requestId) {
158 finish({
159 type: "failure",
160 error: new Error("The desktop app response did not match this request."),
161 });
162 return;
163 }
164 finish({ type: "success", response: parsed });
165 });
166 socket.once("error", (error: NodeJS.ErrnoException) => {
167 if (
168 !settled &&
169 !connected &&
170 input.fallbackAddress !== undefined &&
171 (error.code === "ENOENT" || error.code === "ECONNREFUSED")
172 ) {
173 settled = true;
174 clearTimeout(timeout);
175 socket.destroy();
176 resolve(
177 sendDesktopAppActivationRequest({
178 address: input.fallbackAddress,
179 userId: input.userId,
180 request: input.request,
181 ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
182 }),
183 );
184 return;
185 }
186 finish({ type: "failure", error });
187 });
188 socket.once("end", () => {
189 finish({ type: "failure", error: new Error("The desktop app closed the connection.") });
190 });
191 });
192}
193
194const appEnvironment = Config.all({
195 t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
196 sshConnection: Config.String("SSH_CONNECTION").pipe(Config.option),
197 sshTty: Config.String("SSH_TTY").pipe(Config.option),
198});
199
200const runAppCommand = Effect.fn("cli.app")(function* (flags: {
201 readonly baseDir: Option.Option<string>;
202 readonly workspaceRoot: Option.Option<string>;
203}) {
204 const environment = yield* appEnvironment;
205 const hostPlatform = yield* HostProcess.Platform;
206 if (Option.isSome(environment.sshConnection) || Option.isSome(environment.sshTty)) {
207 return yield* new DesktopAppSshUnsupportedError({});
208 }
209 if (!isDesktopPlatform(hostPlatform)) {
210 return yield* new DesktopAppPlatformUnsupportedError({ platform: hostPlatform });
211 }
212
213 const path = yield* Path.Path;
214 const configuredBaseDir = Option.getOrUndefined(flags.baseDir) ?? environment.t3Home;
215 const baseDir = yield* resolveBaseDir(configuredBaseDir);
216 const allowDevFallback = Option.isNone(flags.baseDir) && !environment.t3Home?.trim();
217 const rawWorkspaceRoot =
218 Option.getOrUndefined(flags.workspaceRoot) ?? (yield* HostProcess.WorkingDirectory);
219 const workspaceRoot = path.resolve(yield* expandHomePath(rawWorkspaceRoot));
220 const userId = yield* HostProcess.UserId;
221 const resolveAddress = (stateSubdirectory: "userdata" | "dev") =>
222 resolveDesktopAppControlAddress({
223 stateDir: path.join(baseDir, stateSubdirectory),
224 platform: hostPlatform,
225 tempDir: NodeOS.tmpdir(),
226 userId,
227 joinPath: path.join,
228 });
229 const random = yield* SecureRandom.SecureRandom;
230 const requestId = yield* random.uuidV4();
231 const request: DesktopAppActivationRequest = {
232 version: DESKTOP_APP_ACTIVATION_PROTOCOL_VERSION,
233 requestId,
234 type: "open-workspace",
235 workspaceRoot,
236 platform: hostPlatform,
237 };
238 const address = resolveAddress("userdata");
239 const fallbackAddress = allowDevFallback ? resolveAddress("dev") : undefined;
240
241 const response = yield* Effect.tryPromise({
242 try: () =>
243 sendDesktopAppActivationRequest({
244 address,
245 userId,
246 ...(fallbackAddress === undefined ? {} : { fallbackAddress }),
247 request,
248 }),
249 catch: (cause) =>
250 new DesktopAppUnreachableError({
251 candidateAddresses:
252 fallbackAddress === undefined
253 ? [address.address]
254 : [address.address, fallbackAddress.address],
255 requestId: request.requestId,
256 workspaceRoot,
257 cause,
258 }),
259 });
260 if (!response.ok) {
261 return yield* new DesktopAppRequestFailedError({
262 code: response.code,
263 requestId: response.requestId,
264 workspaceRoot,
265 cause: response,
266 });
267 }
268
269 yield* Console.log(`Opened ${workspaceRoot} in T3 Code.`);
270});
271
272export const appCommand = Command.make("app", {
273 baseDir: baseDirFlag,
274 workspaceRoot: Argument.String("path").pipe(
275 Argument.withDescription("Project directory. Default: current directory."),
276 Argument.optional,
277 ),
278}).pipe(
279 Command.withDescription("Open a project in the running T3 Code desktop app."),
280 Command.withHandler(runAppCommand),
281);