Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/desktop/src/ipc/DesktopIpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
openRemoteZed,
pickFolder,
setTheme,
showContextMenu,
Expand Down Expand Up @@ -82,6 +83,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openRemoteZed);
yield* ipc.handle(openExternal);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/ipc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_REMOTE_ZED_CHANNEL = "desktop:open-remote-zed";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
Expand Down
12 changes: 12 additions & 0 deletions apps/desktop/src/ipc/methods/window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ContextMenuItemSchema,
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopOpenRemoteZedInputSchema,
DesktopThemeSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
Expand All @@ -17,6 +18,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as DesktopZedLauncher from "../../shell/DesktopZedLauncher.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
Expand Down Expand Up @@ -268,3 +270,13 @@ export const openExternal = DesktopIpc.makeIpcMethod({
return yield* shell.openExternal(url);
}),
});

export const openRemoteZed = DesktopIpc.makeIpcMethod({
channel: IpcChannels.OPEN_REMOTE_ZED_CHANNEL,
payload: DesktopOpenRemoteZedInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.window.openRemoteZed")(function* (input) {
const launcher = yield* DesktopZedLauncher.DesktopZedLauncher;
yield* launcher.openRemoteWorkspace(input);
}),
});
2 changes: 2 additions & 0 deletions apps/desktop/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopZedLauncher from "./shell/DesktopZedLauncher.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
Expand Down Expand Up @@ -184,6 +185,7 @@ const desktopApplicationLayer = Layer.mergeAll(
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
DesktopZedLauncher.layer,
desktopSshLayer,
).pipe(
Layer.provideMerge(DesktopUpdates.layer),
Expand Down
1 change: 1 addition & 0 deletions apps/desktop/src/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
items,
...(position === undefined ? {} : { position }),
}),
openRemoteZed: (input) => ipcRenderer.invoke(IpcChannels.OPEN_REMOTE_ZED_CHANNEL, input),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
Expand Down
186 changes: 186 additions & 0 deletions apps/desktop/src/shell/DesktopZedLauncher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";

import * as DesktopZedLauncher from "./DesktopZedLauncher.ts";

function makeDetachedHandle(onUnref: () => void): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(true),
kill: () => Effect.void,
unref: Effect.sync(() => {
onUnref();
return Effect.void;
}),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}

describe("DesktopZedLauncher", () => {
it("builds Zed's encoded SSH URI from the connection target", () => {
assert.equal(
DesktopZedLauncher.remoteZedSshUri({
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: "declan",
port: 2222,
},
path: "~/code/project alpha",
}),
"ssh://declan@devbox:2222/~/code/project%20alpha",
);
assert.equal(
DesktopZedLauncher.remoteZedSshUri({
target: {
alias: "",
hostname: "devbox.example.com",
username: null,
port: null,
},
path: "/srv/project",
}),
"ssh://devbox.example.com/srv/project",
);
assert.equal(
DesktopZedLauncher.remoteZedSshUri({
target: {
alias: "",
hostname: "2001:db8::1",
username: "declan",
port: 2222,
},
path: "/srv/project",
}),
"ssh://declan@[2001:db8::1]:2222/srv/project",
);
});

it.effect.each<{
availableCommands: ReadonlyArray<"zed" | "zeditor">;
expectedCommand: "zed" | "zeditor";
}>([
{ availableCommands: ["zed", "zeditor"], expectedCommand: "zed" },
{ availableCommands: ["zeditor"], expectedCommand: "zeditor" },
])(
"launches and detaches $expectedCommand when available",
({ availableCommands, expectedCommand }) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-zed-" });
for (const command of availableCommands) {
const commandPath = path.join(binDir, command);
yield* fileSystem.writeFileString(commandPath, "#!/bin/sh\n");
yield* fileSystem.chmod(commandPath, 0o755);
}

let spawned: ChildProcess.StandardCommand | undefined;
let didUnref = false;
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) =>
Effect.sync(() => {
assert.equal(ChildProcess.isStandardCommand(command), true);
if (!ChildProcess.isStandardCommand(command)) {
throw new Error("Expected a standard command");
}
spawned = command;
return makeDetachedHandle(() => {
didUnref = true;
});
}),
),
);
const previousPath = process.env.PATH;
process.env.PATH = binDir;

yield* Effect.gen(function* () {
const launcher = yield* DesktopZedLauncher.DesktopZedLauncher;
yield* launcher.openRemoteWorkspace({
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: null,
port: null,
},
path: "/srv/project",
});
}).pipe(
Effect.ensuring(
Effect.sync(() => {
process.env.PATH = previousPath;
}),
),
Effect.provide(
DesktopZedLauncher.layer.pipe(
Layer.provide(Layer.merge(NodeServices.layer, spawnerLayer)),
),
),
);

assert.ok(spawned);
assert.equal(spawned.command, expectedCommand);
assert.deepEqual(spawned.args, ["-r", "ssh://devbox/srv/project"]);
assert.equal(spawned.options.detached, true);
assert.equal(didUnref, true);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);

it("keeps launch errors free of SSH connection details", () => {
const error = new DesktopZedLauncher.DesktopZedLaunchError({
argumentCount: 2,
cause: new Error("spawn failed"),
});

assert.equal(error.message, "Failed to open remote workspace in Zed.");
assert.equal(error.argumentCount, 2);
});

it.effect("fails clearly when no local Zed CLI is available", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const binDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-no-zed-" });
const previousPath = process.env.PATH;
process.env.PATH = binDir;

const error = yield* Effect.gen(function* () {
const launcher = yield* DesktopZedLauncher.DesktopZedLauncher;
return yield* launcher.openRemoteWorkspace({
target: {
alias: "devbox",
hostname: "devbox.example.com",
username: null,
port: null,
},
path: "/srv/project",
});
}).pipe(
Effect.flip,
Effect.ensuring(
Effect.sync(() => {
process.env.PATH = previousPath;
}),
),
Effect.provide(DesktopZedLauncher.layer.pipe(Layer.provide(NodeServices.layer))),
);

assert.equal(error._tag, "DesktopZedCommandNotFoundError");
assert.equal(error.message, "Zed CLI not found.");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
122 changes: 122 additions & 0 deletions apps/desktop/src/shell/DesktopZedLauncher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import {
type DesktopOpenRemoteZedInput,
type DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";

const ZED_COMMANDS = ["zed", "zeditor"] as const;

export class DesktopZedCommandNotFoundError extends Schema.TaggedErrorClass<DesktopZedCommandNotFoundError>()(
"DesktopZedCommandNotFoundError",
{},
) {
override get message(): string {
return "Zed CLI not found.";
}
}

export class DesktopZedLaunchError extends Schema.TaggedErrorClass<DesktopZedLaunchError>()(
"DesktopZedLaunchError",
{
argumentCount: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to open remote workspace in Zed.";
}
}
Comment thread
macroscopeapp[bot] marked this conversation as resolved.

function remoteAuthority(target: DesktopSshEnvironmentTarget): string {
const rawHost = target.alias.trim() || target.hostname.trim();
const host = rawHost.includes(":") && !rawHost.startsWith("[") ? `[${rawHost}]` : rawHost;
const username = target.username?.trim();
const port = target.port === null ? "" : `:${target.port}`;
return `${username ? `${username}@` : ""}${host}${port}`;
Comment thread
macroscopeapp[bot] marked this conversation as resolved.
}
Comment thread
cursor[bot] marked this conversation as resolved.

function remoteUriPath(path: string): string {
const normalized = path === "~" ? "/~" : path.startsWith("~/") ? `/~/${path.slice(2)}` : path;
const absolute = normalized.startsWith("/") ? normalized : `/${normalized}`;
return absolute
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
}

export function remoteZedSshUri(input: DesktopOpenRemoteZedInput): string {
return `ssh://${remoteAuthority(input.target)}${remoteUriPath(input.path)}`;
}

export class DesktopZedLauncher extends Context.Service<
DesktopZedLauncher,
{
readonly openRemoteWorkspace: (
input: DesktopOpenRemoteZedInput,
) => Effect.Effect<void, DesktopZedCommandNotFoundError | DesktopZedLaunchError>;
}
>()("@t3tools/desktop/shell/DesktopZedLauncher") {}

export const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;

const openRemoteWorkspace = Effect.fn("desktop.zed.openRemoteWorkspace")(function* (
input: DesktopOpenRemoteZedInput,
) {
let command = Option.none<string>();
for (const candidate of ZED_COMMANDS) {
if (
yield* isCommandAvailable(candidate).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
)
) {
command = Option.some(candidate);
break;
}
}
if (Option.isNone(command)) {
return yield* new DesktopZedCommandNotFoundError();
}

const args = ["-r", remoteZedSshUri(input)];
const resolved = yield* resolveSpawnCommand(command.value, args).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const process = ChildProcess.make(resolved.command, resolved.args, {
detached: true,
shell: resolved.shell,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
yield* spawner.spawn(process).pipe(
Effect.flatMap((handle) => handle.unref),
Effect.asVoid,
Effect.scoped,
Effect.mapError(
(cause) =>
new DesktopZedLaunchError({
argumentCount: resolved.args.length,
cause,
}),
),
);
});

return DesktopZedLauncher.of({ openRemoteWorkspace });
});

export const layer = Layer.effect(DesktopZedLauncher, make);
Loading
Loading