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

app.ts

261 lines8.7 KB

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