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