Skip to content

Commit 638c9f2

Browse files
committed
feat(desktop): open projects in external terminal apps
1 parent f8b4c46 commit 638c9f2

25 files changed

Lines changed: 848 additions & 30 deletions

‎apps/desktop/scripts/electron-launcher.mjs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
2020
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
2121
: "com.t3tools.t3code";
2222
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
23-
const LAUNCHER_VERSION = 15;
23+
const LAUNCHER_VERSION = 16;
2424
const developmentMacIconPngPath = NodePath.join(
2525
repoRoot,
2626
"assets",
@@ -232,6 +232,11 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
232232
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
233233
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
234234
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
235+
setPlistString(
236+
infoPlistPath,
237+
"NSAppleEventsUsageDescription",
238+
"T3 Code uses your terminal app to open project directories and SSH sessions.",
239+
);
235240
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
236241
{
237242
CFBundleURLName: APP_BUNDLE_ID,

‎apps/desktop/src/ipc/DesktopIpcHandlers.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { openTerminal, requestTerminalPermission } from "./methods/terminal.ts";
12
import * as Effect from "effect/Effect";
23

34
import * as DesktopIpc from "./DesktopIpc.ts";
@@ -95,6 +96,8 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
9596
yield* ipc.handle(setTheme);
9697
yield* ipc.handle(showContextMenu);
9798
yield* ipc.handle(openExternal);
99+
yield* ipc.handle(openTerminal);
100+
yield* ipc.handle(requestTerminalPermission);
98101
yield* ipc.handle(openSystemSettings);
99102
yield* ipc.handle(probeRemoteEditors);
100103
yield* ipc.handle(getUpdateState);

‎apps/desktop/src/ipc/channels.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,3 +90,7 @@ export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
9090
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
9191
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
9292
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
93+
94+
export const OPEN_TERMINAL_CHANNEL = "desktop:open-terminal";
95+
96+
export const REQUEST_TERMINAL_PERMISSION_CHANNEL = "desktop:request-terminal-permission";
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { requestTerminalPermission as requestPermission } from "../../terminal/terminalPermissions.ts";
2+
import { ExternalTerminalId, OpenExternalTerminalInput } from "@t3tools/contracts";
3+
import * as Effect from "effect/Effect";
4+
import * as Schema from "effect/Schema";
5+
import { DesktopEnvironment } from "../../app/DesktopEnvironment.ts";
6+
import { launchExternalTerminal } from "../../terminal/externalTerminal.ts";
7+
import * as DesktopIpc from "../DesktopIpc.ts";
8+
import * as IpcChannels from "../channels.ts";
9+
10+
export const openTerminal = DesktopIpc.makeIpcMethod({
11+
channel: IpcChannels.OPEN_TERMINAL_CHANNEL,
12+
payload: OpenExternalTerminalInput,
13+
result: Schema.Void,
14+
handler: Effect.fn("desktop.ipc.openTerminal")(function* (input) {
15+
const { platform } = yield* DesktopEnvironment;
16+
yield* launchExternalTerminal(input, platform);
17+
}),
18+
});
19+
20+
export const requestTerminalPermission = DesktopIpc.makeIpcMethod({
21+
channel: IpcChannels.REQUEST_TERMINAL_PERMISSION_CHANNEL,
22+
payload: ExternalTerminalId,
23+
result: Schema.Void,
24+
handler: Effect.fn("desktop.ipc.requestTerminalPermission")(function* (terminal) {
25+
const { platform } = yield* DesktopEnvironment;
26+
yield* requestPermission(terminal, platform);
27+
}),
28+
});

‎apps/desktop/src/preload.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,9 @@ contextBridge.exposeInMainWorld("desktopBridge", {
115115
items,
116116
...(position === undefined ? {} : { position }),
117117
}),
118+
requestTerminalPermission: (terminal) =>
119+
ipcRenderer.invoke(IpcChannels.REQUEST_TERMINAL_PERMISSION_CHANNEL, terminal),
120+
openTerminal: (input) => ipcRenderer.invoke(IpcChannels.OPEN_TERMINAL_CHANNEL, input),
118121
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
119122
openSystemSettings: (pane: string) =>
120123
ipcRenderer.invoke(IpcChannels.OPEN_SYSTEM_SETTINGS_CHANNEL, pane),

‎apps/desktop/src/settings/DesktopClientSettings.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
1313
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
1414

1515
const clientSettings: ClientSettings = {
16+
externalTerminal: "ghostty",
1617
appearanceContrast: 100,
1718
browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },
1819
browserDefaultZoomFactor: 1.25,
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// @effect-diagnostics nodeBuiltinImport:off - Tests execute generated commands through a real POSIX shell in temporary directories.
2+
import { describe, expect, it } from "vite-plus/test";
3+
import { it as effectIt } from "@effect/vitest";
4+
import * as NodeServices from "@effect/platform-node/NodeServices";
5+
import * as NodeChildProcess from "node:child_process";
6+
import * as NodeFS from "node:fs";
7+
import * as NodeOS from "node:os";
8+
import * as NodePath from "node:path";
9+
import * as Effect from "effect/Effect";
10+
import * as Sink from "effect/Sink";
11+
import * as Stream from "effect/Stream";
12+
import { ChildProcessSpawner } from "effect/unstable/process";
13+
import { launchExternalTerminal, terminalLaunch } from "./externalTerminal.ts";
14+
15+
describe("external terminal launch", () => {
16+
it("opens the exact local directory without evaluating shell syntax in its name", () => {
17+
const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-terminal-"));
18+
try {
19+
const cwd = NodePath.join(root, "a 'quoted' $(touch INJECTED) ; folder");
20+
NodeFS.mkdirSync(cwd);
21+
const shell = NodePath.join(root, "login-shell");
22+
NodeFS.writeFileSync(shell, '#!/bin/sh\nprintf "%s" "$PWD"\n', { mode: 0o700 });
23+
const launch = terminalLaunch({ terminal: "gnome-terminal", cwd }, "linux");
24+
const result = NodeChildProcess.execFileSync(launch.args[1]!, launch.args.slice(2), {
25+
env: { ...process.env, SHELL: shell },
26+
encoding: "utf8",
27+
});
28+
expect(result).toBe(cwd);
29+
} finally {
30+
NodeFS.rmSync(root, { recursive: true, force: true });
31+
}
32+
});
33+
34+
it("preserves a remote directory across the SSH shell boundary", () => {
35+
const cwd = "/srv/user's repo $(id); `whoami`";
36+
const launch = terminalLaunch(
37+
{ terminal: "gnome-terminal", cwd, sshHost: "my-ssh-alias" },
38+
"linux",
39+
);
40+
expect(launch.args.slice(0, 5)).toEqual(["--", "ssh", "-t", "--", "my-ssh-alias"]);
41+
// Substitute shell builtins to observe cd's argument without requiring that remote path locally.
42+
const inner = NodeChildProcess.execFileSync(
43+
"/bin/sh",
44+
["-c", `capture() { printf '%s' "$2"; }; ${launch.args[5]!.replace("/bin/sh", "capture")}`],
45+
{ encoding: "utf8" },
46+
);
47+
const command = `cd() { printf '%s' "$1"; }; exec() { :; }; ${inner}`;
48+
expect(NodeChildProcess.execFileSync("/bin/sh", ["-c", command], { encoding: "utf8" })).toBe(
49+
cwd,
50+
);
51+
});
52+
53+
it.each(["terminal", "iterm2"] as const)("quotes commands through %s AppleScript", (terminal) => {
54+
const launch = terminalLaunch(
55+
{ terminal, cwd: '/srv/a "quote" and \\ slash', sshHost: "dev" },
56+
"darwin",
57+
);
58+
const literal = launch.args[1]!.split("\n")[2]!.replace(
59+
/^(do script |create window with default profile command )/,
60+
"",
61+
);
62+
const command = JSON.parse(literal) as string;
63+
// Resolve the /bin/sh invocation once, then examine the command delivered to that shell.
64+
const args = NodeChildProcess.execFileSync(
65+
"/bin/sh",
66+
["-c", `capture() { printf '%s' "$2"; }; ${command.replace("/bin/sh", "capture")}`],
67+
{ encoding: "utf8" },
68+
);
69+
expect(args).toContain("'ssh' '-t' '--' 'dev'");
70+
expect(launch.file).toBe("/usr/bin/osascript");
71+
});
72+
73+
it("passes Windows paths as encoded PowerShell data, including WT's semicolon separator", () => {
74+
const launch = terminalLaunch(
75+
{ terminal: "system", cwd: "C:\\users\\O'Brien; $(whoami)" },
76+
"win32",
77+
);
78+
expect(launch.file).toBe("wt.exe");
79+
expect(Buffer.from(launch.args.at(-1)!, "base64").toString("utf16le")).toBe(
80+
"Set-Location -LiteralPath 'C:\\users\\O''Brien; $(whoami)'",
81+
);
82+
});
83+
84+
it("opens WSL in the selected running distribution", () => {
85+
const launch = terminalLaunch(
86+
{ terminal: "system", cwd: "/home/me/repo", wslDistro: "Ubuntu" },
87+
"win32",
88+
);
89+
expect(Buffer.from(launch.args.at(-1)!, "base64").toString("utf16le")).toBe(
90+
`Start-Process -FilePath 'wsl.exe' -ArgumentList '"--distribution" "Ubuntu" "--cd" "/home/me/repo"' -NoNewWindow -Wait`,
91+
);
92+
});
93+
94+
it.each(["-oProxyCommand=evil", "host;id", "host\ncommand"])(
95+
"rejects an unsafe SSH host %s",
96+
(sshHost) => {
97+
expect(() =>
98+
terminalLaunch({ terminal: "system", cwd: "/repo", sshHost }, "darwin"),
99+
).toThrow();
100+
},
101+
);
102+
103+
it("rejects an unsupported terminal rather than silently changing the preference", () => {
104+
expect(() => terminalLaunch({ terminal: "iterm2", cwd: "/repo" }, "linux")).toThrow();
105+
});
106+
});
107+
108+
describe("external terminal process lifecycle", () => {
109+
function processSpawner(exitCode: number | null, onUnref: () => void) {
110+
return ChildProcessSpawner.make(() =>
111+
Effect.succeed(
112+
ChildProcessSpawner.makeHandle({
113+
pid: ChildProcessSpawner.ProcessId(1),
114+
exitCode:
115+
exitCode === null
116+
? Effect.never
117+
: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
118+
isRunning: Effect.succeed(exitCode === null),
119+
kill: () => Effect.void,
120+
unref: Effect.sync(() => {
121+
onUnref();
122+
return Effect.void;
123+
}),
124+
stdin: Sink.drain,
125+
stdout: Stream.empty,
126+
stderr: Stream.empty,
127+
all: Stream.empty,
128+
getInputFd: () => Sink.drain,
129+
getOutputFd: () => Stream.empty,
130+
}),
131+
),
132+
);
133+
}
134+
135+
effectIt.effect("reports launcher failures instead of claiming the terminal opened", () =>
136+
Effect.gen(function* () {
137+
const error = yield* launchExternalTerminal(
138+
{ terminal: "terminal", cwd: "/repo" },
139+
"darwin",
140+
).pipe(
141+
Effect.provideService(
142+
ChildProcessSpawner.ChildProcessSpawner,
143+
processSpawner(1, () => {}),
144+
),
145+
Effect.flip,
146+
);
147+
expect(error.message).toContain("Could not open the terminal");
148+
}).pipe(Effect.provide(NodeServices.layer)),
149+
);
150+
151+
effectIt.effect(
152+
"releases a long-running native terminal without waiting for its window to close",
153+
() =>
154+
Effect.gen(function* () {
155+
let unreferenced = false;
156+
yield* launchExternalTerminal({ terminal: "konsole", cwd: "/repo" }, "linux").pipe(
157+
Effect.provideService(
158+
ChildProcessSpawner.ChildProcessSpawner,
159+
processSpawner(null, () => {
160+
unreferenced = true;
161+
}),
162+
),
163+
);
164+
expect(unreferenced).toBe(true);
165+
}).pipe(Effect.provide(NodeServices.layer)),
166+
);
167+
});

0 commit comments

Comments
 (0)