Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

feat(web): open remote environments in your local editor over SSH (#6572)

Theo Browne57a299a7852b
diff --git a/apps/desktop/src/electron/ElectronShell.ts b/apps/desktop/src/electron/ElectronShell.ts
index 316d3138b..126be71b6 100644
--- a/apps/desktop/src/electron/ElectronShell.ts
+++ b/apps/desktop/src/electron/ElectronShell.ts
@@ -1,3 +1,4 @@
+import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -5,7 +6,16 @@ import * as Option from "effect/Option";
import * as Electron from "electron";
-const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
+// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
+// must reach the OS handler; every other non-web scheme stays blocked.
+const SAFE_EXTERNAL_PROTOCOLS = new Set([
+ "http:",
+ "https:",
+ ...REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
+ const scheme = remoteSchemeForEditor(id);
+ return scheme === undefined ? [] : [`${scheme}:`];
+ }),
+]);
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
if (typeof rawUrl !== "string") {
diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
index cb35ad19a..3d9ff022c 100644
--- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts
+++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts
@@ -36,6 +36,7 @@ import {
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
+ probeRemoteEditors,
pickFolder,
pickThemeFiles,
setTheme,
@@ -83,6 +84,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
+ yield* ipc.handle(probeRemoteEditors);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts
index 4a1213e4e..0e31082af 100644
--- a/apps/desktop/src/ipc/channels.ts
+++ b/apps/desktop/src/ipc/channels.ts
@@ -3,6 +3,7 @@ export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
+export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts
index 7a39eb429..16f7a4694 100644
--- a/apps/desktop/src/ipc/methods/window.ts
+++ b/apps/desktop/src/ipc/methods/window.ts
@@ -3,12 +3,16 @@ import {
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
+ EDITORS,
+ EditorId,
PickedThemeFileSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
+ REMOTE_CAPABLE_EDITOR_IDS,
type DesktopEnvironmentBootstrap,
type PickedThemeFile,
} from "@t3tools/contracts";
+import { isCommandAvailable } from "@t3tools/shared/shell";
import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -261,6 +265,30 @@ export const openExternal = DesktopIpc.makeIpcMethod({
}),
});
+export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
+ channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
+ payload: Schema.Undefined,
+ result: Schema.Array(EditorId),
+ // Probes THIS machine (where the renderer runs) for remote-capable editor
+ // CLIs, unlike the server's probe which walks the environment host's PATH.
+ // A Finder-launched app can miss PATH entries; an empty result makes the
+ // renderer fall back to VS Code only, so that fails soft.
+ handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
+ const available: Array<EditorId> = [];
+ for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
+ const commands = EDITORS.find((editor) => editor.id === editorId)?.commands;
+ if (!commands) continue;
+ for (const command of commands) {
+ if (yield* isCommandAvailable(command, { env: process.env })) {
+ available.push(editorId);
+ break;
+ }
+ }
+ }
+ return available;
+ }),
+});
+
/** Theme files are a few KB; anything larger returns empty text and lets the
* renderer reject it by size without the contents ever crossing the bridge. */
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts
index 2aa345ee5..61e345b90 100644
--- a/apps/desktop/src/preload.ts
+++ b/apps/desktop/src/preload.ts
@@ -105,6 +105,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
+ probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
diff --git a/apps/desktop/src/wsl/DesktopWslBackend.test.ts b/apps/desktop/src/wsl/DesktopWslBackend.test.ts
index 2f58c6adc..ed8911d40 100644
--- a/apps/desktop/src/wsl/DesktopWslBackend.test.ts
+++ b/apps/desktop/src/wsl/DesktopWslBackend.test.ts
@@ -77,6 +77,7 @@ const backendConfigurationLayer = Layer.succeed(
const netLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
+ hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(41773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
} satisfies NetService.NetService["Service"]);
diff --git a/apps/server/src/environment/RemoteOpenTargets.test.ts b/apps/server/src/environment/RemoteOpenTargets.test.ts
new file mode 100644
index 000000000..2f876b995
--- /dev/null
+++ b/apps/server/src/environment/RemoteOpenTargets.test.ts
@@ -0,0 +1,126 @@
+import { it } from "@effect/vitest";
+import { HostProcessHostname } from "@t3tools/shared/hostProcess";
+import * as NetService from "@t3tools/shared/Net";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Sink from "effect/Sink";
+import * as Stream from "effect/Stream";
+import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
+import { describe, expect } from "vite-plus/test";
+
+import * as RemoteOpenTargets from "./RemoteOpenTargets.ts";
+
+const encoder = new TextEncoder();
+
+const TAILSCALE_STATUS_JSON = JSON.stringify({
+ Self: { DNSName: "bb-1.tail1234.ts.net.", TailscaleIPs: ["100.64.1.2"] },
+});
+
+/** Spawner whose `tailscale status --json` exits with the given output. */
+const spawnerLayer = (input: { readonly exitCode: number; readonly stdout: string }) =>
+ Layer.succeed(
+ ChildProcessSpawner.ChildProcessSpawner,
+ ChildProcessSpawner.make(() =>
+ Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(input.exitCode)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.make(encoder.encode(input.stdout)),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ }),
+ ),
+ ),
+ );
+
+const netLayer = (input: { readonly ipv4: boolean; readonly ipv6: boolean }) =>
+ Layer.succeed(NetService.NetService, {
+ canListenOnHost: () => Effect.succeed(true),
+ isPortAvailableOnLoopback: () => Effect.succeed(true),
+ hasListenerOnHost: (_port, host) => Effect.succeed(host === "::1" ? input.ipv6 : input.ipv4),
+ reserveLoopbackPort: () => Effect.succeed(40_000),
+ findAvailablePort: (preferred) => Effect.succeed(preferred),
+ });
+
+const resolveTargets = (input: {
+ readonly sshd: { readonly ipv4: boolean; readonly ipv6: boolean };
+ readonly tailscale: { readonly exitCode: number; readonly stdout: string };
+ readonly hostname: string;
+}) =>
+ Effect.flatMap(RemoteOpenTargets.RemoteOpenTargets, (service) => service.resolveTargets()).pipe(
+ Effect.provideService(HostProcessHostname, input.hostname),
+ Effect.provide(
+ RemoteOpenTargets.layer.pipe(
+ Layer.provide(Layer.mergeAll(netLayer(input.sshd), spawnerLayer(input.tailscale))),
+ ),
+ ),
+ );
+
+const TAILSCALE_UP = { exitCode: 0, stdout: TAILSCALE_STATUS_JSON };
+const TAILSCALE_DOWN = { exitCode: 1, stdout: "" };
+
+describe("RemoteOpenTargets", () => {
+ it.effect("advertises nothing when no sshd accepts on either loopback", () =>
+ Effect.gen(function* () {
+ const targets = yield* resolveTargets({
+ sshd: { ipv4: false, ipv6: false },
+ tailscale: TAILSCALE_UP,
+ hostname: "bb-1",
+ });
+ expect(targets).toEqual([]);
+ }),
+ );
+
+ it.effect("orders the tailnet name before the mDNS name", () =>
+ Effect.gen(function* () {
+ const targets = yield* resolveTargets({
+ sshd: { ipv4: true, ipv6: true },
+ tailscale: TAILSCALE_UP,
+ hostname: "bb-1",
+ });
+ expect(targets).toEqual([
+ { kind: "tailscale", host: "bb-1.tail1234.ts.net" },
+ { kind: "mdns", host: "bb-1.local" },
+ ]);
+ }),
+ );
+
+ it.effect("accepts an sshd bound to IPv6 loopback only", () =>
+ Effect.gen(function* () {
+ const targets = yield* resolveTargets({
+ sshd: { ipv4: false, ipv6: true },
+ tailscale: TAILSCALE_DOWN,
+ hostname: "bb-1",
+ });
+ expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);
+ }),
+ );
+
+ it.effect("falls back to mDNS alone when tailscale is unavailable", () =>
+ Effect.gen(function* () {
+ const targets = yield* resolveTargets({
+ sshd: { ipv4: true, ipv6: false },
+ tailscale: TAILSCALE_DOWN,
+ hostname: "bb-1",
+ });
+ expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);
+ }),
+ );
+
+ it.effect("shortens an FQDN hostname to its first label for mDNS", () =>
+ Effect.gen(function* () {
+ const targets = yield* resolveTargets({
+ sshd: { ipv4: true, ipv6: true },
+ tailscale: TAILSCALE_DOWN,
+ hostname: "bb-1.example.com",
+ });
+ expect(targets).toEqual([{ kind: "mdns", host: "bb-1.local" }]);
+ }),
+ );
+});
diff --git a/apps/server/src/environment/RemoteOpenTargets.ts b/apps/server/src/environment/RemoteOpenTargets.ts
new file mode 100644
index 000000000..f70dfa68a
--- /dev/null
+++ b/apps/server/src/environment/RemoteOpenTargets.ts
@@ -0,0 +1,72 @@
+/**
+ * RemoteOpenTargets - resolves the SSH hostnames this environment advertises
+ * for remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`).
+ *
+ * The server can only check itself: sshd listening locally, tailscaled
+ * reporting a MagicDNS name, and the machine hostname for mDNS. Whether a
+ * given name resolves from the viewer's machine is inherently client-side.
+ * Targets are ordered most-reachable first (tailnet name works from anywhere
+ * on the tailnet; `<hostname>.local` only on the same LAN).
+ */
+import { type RemoteOpenTarget } from "@t3tools/contracts";
+import { HostProcessHostname } from "@t3tools/shared/hostProcess";
+import * as NetService from "@t3tools/shared/Net";
+import { readTailscaleStatus } from "@t3tools/tailscale";
+import * as Context from "effect/Context";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
+
+const SSH_PORT = 22;
+
+export class RemoteOpenTargets extends Context.Service<
+ RemoteOpenTargets,
+ {
+ readonly resolveTargets: () => Effect.Effect<ReadonlyArray<RemoteOpenTarget>>;
+ }
+>()("t3/environment/RemoteOpenTargets") {}
+
+export const make = Effect.gen(function* () {
+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
+ const net = yield* NetService.NetService;
+
+ const resolveTargets = Effect.gen(function* () {
+ // No local sshd means no name can work; advertise nothing so clients
+ // render a clear "no SSH route" state instead of links that hang.
+ // Check both loopback families: sshd can be bound IPv6-only.
+ const sshdListening = yield* Effect.zipWith(
+ net.hasListenerOnHost(SSH_PORT, "127.0.0.1"),
+ net.hasListenerOnHost(SSH_PORT, "::1"),
+ (ipv4, ipv6) => ipv4 || ipv6,
+ );
+ if (!sshdListening) {
+ return [];
+ }
+
+ const targets: Array<RemoteOpenTarget> = [];
+
+ // Tailscale absent or down is the common case, not an error.
+ const magicDnsName = yield* readTailscaleStatus.pipe(
+ Effect.map((status) => status.magicDnsName),
+ Effect.orElseSucceed(() => null),
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
+ );
+ if (magicDnsName !== null) {
+ targets.push({ kind: "tailscale", host: magicDnsName });
+ }
+
+ // os.hostname() may already be an FQDN (macOS often reports
+ // "Name.local"); mDNS names are always `<first-label>.local`.
+ const hostname = yield* HostProcessHostname;
+ const shortHostname = hostname.split(".")[0]?.trim();
+ if (shortHostname !== undefined && shortHostname.length > 0) {
+ targets.push({ kind: "mdns", host: `${shortHostname}.local` });
+ }
+
+ return targets;
+ });
+
+ return RemoteOpenTargets.of({ resolveTargets: () => resolveTargets });
+});
+
+export const layer = Layer.effect(RemoteOpenTargets, make);
diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts
index 944cbd85a..7fa15defe 100644
--- a/apps/server/src/preview/PortScanner.test.ts
+++ b/apps/server/src/preview/PortScanner.test.ts
@@ -47,6 +47,7 @@ let integrationListeningPort: number | null = null;
const TestIntegrationNet = Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: (port) => Effect.sync(() => port !== integrationListeningPort),
+ hasListenerOnHost: (port) => Effect.sync(() => port === integrationListeningPort),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
});
@@ -62,6 +63,7 @@ const makeProbeFailureLayer = (
Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
+ hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
}),
@@ -107,6 +109,7 @@ const makeLsofScannerLayer = (input: {
Layer.succeed(Net.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
+ hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(40_000),
findAvailablePort: (preferred) => Effect.succeed(preferred),
}),
diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts
index 3f63eb4db..89f903c4f 100644
--- a/apps/server/src/server.test.ts
+++ b/apps/server/src/server.test.ts
@@ -107,6 +107,7 @@ import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as GitManager from "./git/GitManager.ts";
import * as Keybindings from "./keybindings.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
+import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
@@ -650,10 +651,15 @@ const buildAppUnderTest = (options?: {
}),
),
Layer.provide(
- Layer.mock(ExternalLauncher.ExternalLauncher)({
- resolveAvailableEditors: () => Effect.succeed([]),
- ...options?.layers?.externalLauncher,
- }),
+ Layer.mergeAll(
+ Layer.mock(ExternalLauncher.ExternalLauncher)({
+ resolveAvailableEditors: () => Effect.succeed([]),
+ ...options?.layers?.externalLauncher,
+ }),
+ Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({
+ resolveTargets: () => Effect.succeed([]),
+ }),
+ ),
),
Layer.provide(
Layer.mock(ProcessDiagnostics.ProcessDiagnostics)({
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 32bcaaa8b..2226449ee 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -81,6 +81,7 @@ import * as SourceControlRepositoryService from "./sourceControl/SourceControlRe
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
+import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
@@ -420,6 +421,7 @@ const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(AnalyticsService.layer),
Layer.provideMerge(ExternalLauncher.layer),
+ Layer.provideMerge(RemoteOpenTargets.layer),
Layer.provideMerge(ServerLifecycleEvents.layer),
Layer.provide(NetService.layer),
);
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 6436a5e44..56ea24a4a 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -99,6 +99,7 @@ import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as ReviewService from "./review/ReviewService.ts";
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
+import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { requiredScopeForRpcMethod } from "./auth/RpcAuthorization.ts";
@@ -361,6 +362,7 @@ const makeWsRpcLayer = (
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
+ const remoteOpenTargets = yield* RemoteOpenTargets.RemoteOpenTargets;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const review = yield* ReviewService.ReviewService;
const vcsProvisioning = yield* VcsProvisioningService.VcsProvisioningService;
@@ -1010,6 +1012,11 @@ const makeWsRpcLayer = (
availableEditors: yield* resolveAvailableEditorsForConfig(
externalLauncher.resolveAvailableEditors(),
),
+ // Same discovery-with-timeout treatment as editors: a slow probe
+ // must not stall server.getConfig, so it degrades to no targets.
+ remoteOpenTargets: yield* resolveAvailableEditorsForConfig(
+ remoteOpenTargets.resolveTargets(),
+ ),
observability: {
logsDirectoryPath: config.logsDir,
localTracingEnabled: true,
diff --git a/apps/web/src/components/chat/ChatHeader.test.ts b/apps/web/src/components/chat/ChatHeader.test.ts
index 94fe070ee..a200a2069 100644
--- a/apps/web/src/components/chat/ChatHeader.test.ts
+++ b/apps/web/src/components/chat/ChatHeader.test.ts
@@ -12,26 +12,40 @@ describe("shouldShowOpenInPicker", () => {
activeProjectName: "codething-mvp",
activeThreadEnvironmentId: primaryEnvironmentId,
primaryEnvironmentId,
+ remoteOpenMode: "local-exec",
}),
).toBe(true);
});
- it("hides the picker when hosted static mode has no primary environment", () => {
+ it("shows the picker for remote environments in deep-link mode", () => {
+ expect(
+ shouldShowOpenInPicker({
+ activeProjectName: "codething-mvp",
+ activeThreadEnvironmentId: EnvironmentId.make("environment-remote"),
+ primaryEnvironmentId,
+ remoteOpenMode: "remote-links",
+ }),
+ ).toBe(true);
+ });
+
+ it("shows the picker's unavailable state for remote environments without an SSH route", () => {
expect(
shouldShowOpenInPicker({
activeProjectName: "codething-mvp",
activeThreadEnvironmentId: EnvironmentId.make("environment-remote"),
primaryEnvironmentId: null,
+ remoteOpenMode: "remote-unavailable",
}),
- ).toBe(false);
+ ).toBe(true);
});
- it("hides the picker for remote environments", () => {
+ it("hides the picker for non-primary local backends", () => {
expect(
shouldShowOpenInPicker({
activeProjectName: "codething-mvp",
activeThreadEnvironmentId: EnvironmentId.make("environment-remote"),
primaryEnvironmentId,
+ remoteOpenMode: "local-exec",
}),
).toBe(false);
});
@@ -42,6 +56,7 @@ describe("shouldShowOpenInPicker", () => {
activeProjectName: undefined,
activeThreadEnvironmentId: primaryEnvironmentId,
primaryEnvironmentId,
+ remoteOpenMode: "remote-links",
}),
).toBe(false);
});
diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx
index 643cf95ee..08e0422dd 100644
--- a/apps/web/src/components/chat/ChatHeader.tsx
+++ b/apps/web/src/components/chat/ChatHeader.tsx
@@ -30,6 +30,7 @@ import ProjectScriptsControl, {
type ProjectScriptActionResult,
} from "../ProjectScriptsControl";
import { OpenInPicker } from "./OpenInPicker";
+import { useRemoteOpenState, type RemoteOpenMode } from "../../remoteOpen";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";
import { useThreadActionMenu } from "~/hooks/useThreadActionMenu";
@@ -91,12 +92,19 @@ export function shouldShowOpenInPicker(input: {
readonly activeProjectName: string | undefined;
readonly activeThreadEnvironmentId: EnvironmentId;
readonly primaryEnvironmentId: EnvironmentId | null;
+ readonly remoteOpenMode: RemoteOpenMode;
}): boolean {
- return (
- Boolean(input.activeProjectName) &&
+ if (!input.activeProjectName) return false;
+ if (
input.primaryEnvironmentId !== null &&
input.activeThreadEnvironmentId === input.primaryEnvironmentId
- );
+ ) {
+ return true;
+ }
+ // Remote environments get the picker in deep-link mode (or its explicit
+ // "no SSH route" state). Non-primary local backends (e.g. WSL) keep it
+ // hidden, matching pre-remote behavior.
+ return input.remoteOpenMode !== "local-exec";
}
export const ChatHeader = memo(function ChatHeader({
@@ -128,10 +136,12 @@ export const ChatHeader = memo(function ChatHeader({
activeThreadEnvironmentId,
activeProjectScripts ? activeProjectCwd : null,
);
+ const remoteOpenState = useRemoteOpenState(activeThreadEnvironmentId);
const showOpenInPicker = shouldShowOpenInPicker({
activeProjectName,
activeThreadEnvironmentId,
primaryEnvironmentId,
+ remoteOpenMode: remoteOpenState.mode,
});
const activeThreadRef = useMemo(
() => scopeThreadRef(activeThreadEnvironmentId, activeThreadId),
diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx
index 8b7a96880..afe35e185 100644
--- a/apps/web/src/components/chat/OpenInPicker.tsx
+++ b/apps/web/src/components/chat/OpenInPicker.tsx
@@ -1,7 +1,19 @@
-import { EditorId, type EnvironmentId, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
+import {
+ buildRemoteOpenUrl,
+ EditorId,
+ type EnvironmentId,
+ type ResolvedKeybindingsConfig,
+} from "@t3tools/contracts";
import { memo, useCallback, useEffect, useMemo } from "react";
import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
import { usePreferredEditor } from "../../editorPreferences";
+import {
+ openRemoteEditorUrl,
+ useRemoteCapableEditors,
+ useRemoteOpenHint,
+ useRemoteOpenState,
+} from "../../remoteOpen";
+import { useEnvironment } from "../../state/environments";
import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
import { Button } from "../ui/button";
import { Group, GroupSeparator } from "../ui/group";
@@ -199,10 +211,17 @@ export const OpenInPicker = memo(function OpenInPicker({
enableShortcut?: boolean;
}) {
const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
- const [preferredEditor, setPreferredEditor] = usePreferredEditor(availableEditors);
+ const remote = useRemoteOpenState(environmentId);
+ const remoteCapableEditors = useRemoteCapableEditors();
+ const [remoteHintSeen, markRemoteHintSeen] = useRemoteOpenHint();
+ const environmentLabel = useEnvironment(environmentId)?.label ?? "this machine";
+ // Remote mode ignores the server's PATH probe: what matters is what runs on
+ // the viewing machine, which only the desktop app can probe.
+ const effectiveEditors = remote.mode === "local-exec" ? availableEditors : remoteCapableEditors;
+ const [preferredEditor, setPreferredEditor] = usePreferredEditor(effectiveEditors);
const options = useMemo(
- () => resolveOptions(navigator.platform, availableEditors),
- [availableEditors],
+ () => resolveOptions(navigator.platform, effectiveEditors),
+ [effectiveEditors],
);
const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
@@ -211,6 +230,23 @@ export const OpenInPicker = memo(function OpenInPicker({
if (!openInCwd) return;
const editor = editorId ?? preferredEditor;
if (!editor) return;
+ if (remote.mode === "remote-unavailable") return;
+ if (remote.mode === "remote-links") {
+ const url = buildRemoteOpenUrl({
+ editor,
+ host: remote.host.host,
+ absolutePath: openInCwd,
+ });
+ if (url === undefined) return;
+ // Only record hint-seen/preferred when the shell actually accepted
+ // the URL (an older desktop build can refuse the editor scheme).
+ void openRemoteEditorUrl(url).then((opened) => {
+ if (!opened) return;
+ markRemoteHintSeen();
+ setPreferredEditor(editor);
+ });
+ return;
+ }
const result = openInEditorMutation({
environmentId,
input: {
@@ -221,7 +257,15 @@ export const OpenInPicker = memo(function OpenInPicker({
setPreferredEditor(editor);
return result;
},
- [environmentId, openInCwd, openInEditorMutation, preferredEditor, setPreferredEditor],
+ [
+ environmentId,
+ markRemoteHintSeen,
+ openInCwd,
+ openInEditorMutation,
+ preferredEditor,
+ remote,
+ setPreferredEditor,
+ ],
);
const openFavoriteEditorShortcutLabel = useMemo(
@@ -237,24 +281,11 @@ export const OpenInPicker = memo(function OpenInPicker({
if (!preferredEditor) return;
e.preventDefault();
- void openInEditorMutation({
- environmentId,
- input: {
- cwd: openInCwd,
- editor: preferredEditor,
- },
- });
+ void openInEditor(preferredEditor);
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
- }, [
- enableShortcut,
- environmentId,
- keybindings,
- openInCwd,
- openInEditorMutation,
- preferredEditor,
- ]);
+ }, [enableShortcut, keybindings, openInCwd, openInEditor, preferredEditor]);
return (
<Group aria-label="Open in editor">
@@ -263,7 +294,7 @@ export const OpenInPicker = memo(function OpenInPicker({
className="ps-[8.5px]"
size="xs"
variant="outline"
- disabled={!preferredEditor || !openInCwd}
+ disabled={!preferredEditor || !openInCwd || remote.mode === "remote-unavailable"}
onClick={() => openInEditor(preferredEditor)}
>
{primaryOption?.Icon && (
@@ -296,16 +327,25 @@ export const OpenInPicker = memo(function OpenInPicker({
<ChevronDownIcon aria-hidden="true" className="size-4" />
</MenuTrigger>
<MenuPopup align="end">
- {options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
- {options.map(({ label, Icon, value, kind }) => (
- <MenuItem key={value} onClick={() => openInEditor(value)}>
- <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
- {label}
- {value === preferredEditor && openFavoriteEditorShortcutLabel && (
- <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
+ {remote.mode === "remote-unavailable" ? (
+ <MenuItem disabled>No SSH route to {environmentLabel}</MenuItem>
+ ) : (
+ <>
+ {options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
+ {options.map(({ label, Icon, value, kind }) => (
+ <MenuItem key={value} onClick={() => openInEditor(value)}>
+ <Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
+ {label}
+ {value === preferredEditor && openFavoriteEditorShortcutLabel && (
+ <MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
+ )}
+ </MenuItem>
+ ))}
+ {remote.mode === "remote-links" && !remoteHintSeen && (
+ <MenuItem disabled>Opens over SSH. Needs your key on {environmentLabel}</MenuItem>
)}
- </MenuItem>
- ))}
+ </>
+ )}
</MenuPopup>
</Menu>
</Group>
diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx
index c4ca57b80..19bf2d5ad 100644
--- a/apps/web/src/components/files/FilePreviewPanel.tsx
+++ b/apps/web/src/components/files/FilePreviewPanel.tsx
@@ -20,6 +20,7 @@ import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPre
import { useAssetUrlState } from "~/assets/assetUrls";
import ChatMarkdown from "~/components/ChatMarkdown";
import { OpenInPicker } from "~/components/chat/OpenInPicker";
+import { useRemoteOpenState } from "~/remoteOpen";
import { useClientSettings } from "~/hooks/useSettings";
import { useTheme } from "~/hooks/useTheme";
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
@@ -771,6 +772,7 @@ export default function FilePreviewPanel({
const { resolvedTheme } = useTheme();
const wordWrap = useClientSettings((settings) => settings.wordWrap);
const primaryEnvironmentId = usePrimaryEnvironmentId();
+ const remoteOpenState = useRemoteOpenState(environmentId);
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(environmentId);
const createAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
reportFailure: false,
@@ -893,7 +895,8 @@ export default function FilePreviewPanel({
))}
</div>
</ScrollArea>
- {absolutePath && environmentId === primaryEnvironmentId ? (
+ {absolutePath &&
+ (environmentId === primaryEnvironmentId || remoteOpenState.mode !== "local-exec") ? (
<OpenInPicker
environmentId={environmentId}
keybindings={keybindings}
diff --git a/apps/web/src/remoteOpen.test.ts b/apps/web/src/remoteOpen.test.ts
new file mode 100644
index 000000000..ff78967aa
--- /dev/null
+++ b/apps/web/src/remoteOpen.test.ts
@@ -0,0 +1,149 @@
+import {
+ BearerConnectionTarget,
+ PrimaryConnectionTarget,
+ RelayConnectionTarget,
+ SshConnectionTarget,
+} from "@t3tools/client-runtime/connection";
+import { buildRemoteOpenUrl, EnvironmentId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import { resolveRemoteOpenState } from "./remoteOpen";
+
+const environmentId = EnvironmentId.make("environment-1");
+
+const primaryTarget = (httpBaseUrl: string) =>
+ new PrimaryConnectionTarget({
+ environmentId,
+ label: "sol",
+ httpBaseUrl,
+ wsBaseUrl: httpBaseUrl.replace("http", "ws"),
+ });
+
+const TAILSCALE_TARGETS = [
+ { kind: "tailscale", host: "sol.tail1234.ts.net" },
+ { kind: "mdns", host: "sol.local" },
+] as const;
+
+describe("resolveRemoteOpenState", () => {
+ it("keeps exec behavior for a loopback primary target", () => {
+ expect(
+ resolveRemoteOpenState({
+ target: primaryTarget("http://127.0.0.1:8000"),
+ sshAlias: null,
+ isDesktopRenderer: false,
+ remoteOpenTargets: TAILSCALE_TARGETS,
+ }),
+ ).toEqual({ mode: "local-exec" });
+ });
+
+ it("uses deep links for a primary target reached over the network", () => {
+ expect(
+ resolveRemoteOpenState({
+ target: primaryTarget("https://sol.tail1234.ts.net"),
+ sshAlias: null,
+ isDesktopRenderer: false,
+ remoteOpenTargets: TAILSCALE_TARGETS,
+ }),
+ ).toEqual({
+ mode: "remote-links",
+ host: { kind: "tailscale", host: "sol.tail1234.ts.net" },
+ });
+ });
+
+ it("keeps exec behavior for the desktop app's own primary even on a NAT URL", () => {
+ // wsl-only mode binds the primary to the WSL2 NAT address; it is still
+ // this machine because the desktop app manages its own primary backend.
+ expect(
+ resolveRemoteOpenState({
+ target: primaryTarget("http://172.29.112.1:14369"),
+ sshAlias: null,
+ isDesktopRenderer: true,
+ remoteOpenTargets: TAILSCALE_TARGETS,
+ }),
+ ).toEqual({ mode: "local-exec" });
+ });
+
+ it("keeps exec behavior for desktop-local secondary backends", () => {
+ expect(
+ resolveRemoteOpenState({
+ target: new BearerConnectionTarget({
+ environmentId,
+ label: "WSL (Ubuntu)",
+ connectionId: "local:wsl-1",
+ }),
+ sshAlias: null,
+ isDesktopRenderer: false,
+ remoteOpenTargets: TAILSCALE_TARGETS,
+ }),
+ ).toEqual({ mode: "local-exec" });
+ });
+
+ it("prefers the desktop SSH alias over server-advertised hosts", () => {
+ expect(
+ resolveRemoteOpenState({
+ target: new SshConnectionTarget({
+ environmentId,
+ label: "sol",
+ connectionId: "ssh-1",
+ }),
+ sshAlias: "sol",
+ isDesktopRenderer: true,
+ remoteOpenTargets: TAILSCALE_TARGETS,
+ }),
+ ).toEqual({ mode: "remote-links", host: { kind: "ssh-alias", host: "sol" } });
+ });
+
+ it("reports unavailable when a remote environment advertises no hosts", () => {
+ for (const remoteOpenTargets of [[], undefined] as const) {
+ expect(
+ resolveRemoteOpenState({
+ target: new RelayConnectionTarget({ environmentId, label: "sol" }),
+ sshAlias: null,
+ isDesktopRenderer: false,
+ remoteOpenTargets,
+ }),
+ ).toEqual({ mode: "remote-unavailable" });
+ }
+ });
+
+ it("falls back to exec when the environment has no catalog entry", () => {
+ expect(
+ resolveRemoteOpenState({
+ target: null,
+ sshAlias: null,
+ isDesktopRenderer: false,
+ remoteOpenTargets: undefined,
+ }),
+ ).toEqual({ mode: "local-exec" });
+ });
+});
+
+describe("buildRemoteOpenUrl", () => {
+ it("builds a vscode-remote deep link", () => {
+ expect(
+ buildRemoteOpenUrl({
+ editor: "vscode",
+ host: "sol.tail1234.ts.net",
+ absolutePath: "/home/theo/code/my repo",
+ }),
+ ).toBe("vscode://vscode-remote/ssh-remote+sol.tail1234.ts.net/home/theo/code/my%20repo");
+ });
+
+ it("uses the fork's scheme", () => {
+ expect(buildRemoteOpenUrl({ editor: "cursor", host: "sol", absolutePath: "/tmp/x" })).toBe(
+ "cursor://vscode-remote/ssh-remote+sol/tmp/x",
+ );
+ });
+
+ it("roots Windows paths", () => {
+ expect(
+ buildRemoteOpenUrl({ editor: "vscode", host: "sol", absolutePath: "C:\\Users\\theo" }),
+ ).toBe("vscode://vscode-remote/ssh-remote+sol/C%3A/Users/theo");
+ });
+
+ it("returns undefined for editors without remote support", () => {
+ expect(buildRemoteOpenUrl({ editor: "zed", host: "sol", absolutePath: "/tmp/x" })).toBe(
+ undefined,
+ );
+ });
+});
diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.ts
new file mode 100644
index 000000000..dff8e9afa
--- /dev/null
+++ b/apps/web/src/remoteOpen.ts
@@ -0,0 +1,189 @@
+/**
+ * Remote open-in-editor: when this client is not on the environment's
+ * machine, "Open" must hand the OS a `vscode://vscode-remote/ssh-remote+…`
+ * deep link (local editor connects over SSH) instead of exec'ing an editor
+ * on the environment host.
+ *
+ * Host precedence: a desktop-SSH environment's real `~/.ssh/config` alias
+ * beats server-advertised names; among advertised names the tailnet MagicDNS
+ * name beats mDNS `<hostname>.local` (server sends them in that order).
+ */
+import type { ConnectionTarget } from "@t3tools/client-runtime/connection";
+import {
+ REMOTE_CAPABLE_EDITOR_IDS,
+ type EditorId,
+ type EnvironmentId,
+ type RemoteOpenTarget,
+} from "@t3tools/contracts";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import { useEffect, useMemo, useState } from "react";
+
+import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
+import { isLoopbackHostname } from "~/environments/primary/target";
+import { useLocalStorage } from "~/hooks/useLocalStorage";
+import { useEnvironmentPresentation } from "~/state/presentation";
+
+export interface RemoteOpenHost {
+ readonly kind: "ssh-alias" | RemoteOpenTarget["kind"];
+ readonly host: string;
+}
+
+export type RemoteOpenState =
+ | { readonly mode: "local-exec" }
+ | { readonly mode: "remote-links"; readonly host: RemoteOpenHost }
+ | { readonly mode: "remote-unavailable" };
+
+export type RemoteOpenMode = RemoteOpenState["mode"];
+
+const LOCAL_EXEC: RemoteOpenState = { mode: "local-exec" };
+const REMOTE_UNAVAILABLE: RemoteOpenState = { mode: "remote-unavailable" };
+
+function parseHostname(url: string): string | null {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return null;
+ }
+}
+
+export function resolveRemoteOpenState(input: {
+ readonly target: ConnectionTarget | null;
+ /** Real ssh alias for desktop-SSH environments; null elsewhere. */
+ readonly sshAlias: string | null;
+ /** Server-advertised hosts; undefined on servers that predate the feature. */
+ readonly remoteOpenTargets: ReadonlyArray<RemoteOpenTarget> | undefined;
+ /** True when running inside the desktop app's renderer. */
+ readonly isDesktopRenderer: boolean;
+}): RemoteOpenState {
+ const { target } = input;
+ // No catalog entry: keep today's exec behavior rather than guessing.
+ if (target === null) {
+ return LOCAL_EXEC;
+ }
+ if (target._tag === "PrimaryConnectionTarget") {
+ // The desktop app manages its own primary backend, so it is always on
+ // this machine even when its URL is not loopback (wsl-only mode binds
+ // the WSL2 NAT address). In a browser, a loopback primary means the
+ // browser runs on the serving machine; a tailnet/LAN URL means remote.
+ if (input.isDesktopRenderer) {
+ return LOCAL_EXEC;
+ }
+ const hostname = parseHostname(target.httpBaseUrl);
+ if (hostname !== null && isLoopbackHostname(hostname)) {
+ return LOCAL_EXEC;
+ }
+ } else if (isDesktopLocalConnectionTarget(target)) {
+ return LOCAL_EXEC;
+ }
+
+ if (input.sshAlias !== null && input.sshAlias.length > 0) {
+ return { mode: "remote-links", host: { kind: "ssh-alias", host: input.sshAlias } };
+ }
+ const advertised = input.remoteOpenTargets?.[0];
+ if (advertised !== undefined) {
+ return { mode: "remote-links", host: advertised };
+ }
+ return REMOTE_UNAVAILABLE;
+}
+
+export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteOpenState {
+ const { presentation } = useEnvironmentPresentation(environmentId);
+
+ return useMemo(() => {
+ if (presentation === null) {
+ return LOCAL_EXEC;
+ }
+ const profile = Option.getOrNull(presentation.entry.profile);
+ const sshAlias =
+ profile !== null && profile._tag === "SshConnectionProfile" ? profile.target.alias : null;
+ return resolveRemoteOpenState({
+ target: presentation.entry.target,
+ sshAlias,
+ remoteOpenTargets: presentation.serverConfig?.remoteOpenTargets,
+ isDesktopRenderer: window.desktopBridge !== undefined,
+ });
+ }, [presentation]);
+}
+
+/**
+ * Editors offered in remote-link mode. The desktop app probes the machine the
+ * renderer runs on; a browser cannot, so it offers VS Code only.
+ */
+const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];
+
+let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;
+
+export function __resetRemoteEditorProbeForTests(): void {
+ cachedProbedEditors = null;
+}
+
+export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {
+ const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(
+ () => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,
+ );
+
+ useEffect(() => {
+ if (cachedProbedEditors !== null) {
+ return;
+ }
+ const probe = window.desktopBridge?.probeRemoteEditors;
+ if (probe === undefined) {
+ cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
+ return;
+ }
+ let cancelled = false;
+ probe().then(
+ (ids) => {
+ const remoteCapable = ids.filter((id) => REMOTE_CAPABLE_EDITOR_IDS.includes(id));
+ cachedProbedEditors = remoteCapable.length > 0 ? remoteCapable : REMOTE_FALLBACK_EDITORS;
+ if (!cancelled) {
+ setEditors(cachedProbedEditors);
+ }
+ },
+ () => {
+ cachedProbedEditors = REMOTE_FALLBACK_EDITORS;
+ },
+ );
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ return editors;
+}
+
+/**
+ * Fire a remote editor deep link. In desktop, route through the Electron
+ * shell so the OS handler opens without navigating the renderer; in a
+ * browser, assign the location — unlike window.open this does not leave a
+ * blank tab behind.
+ *
+ * Resolves false when the desktop shell refused the URL (e.g. an older
+ * build whose protocol allowlist predates editor schemes) so callers do not
+ * record a successful open that never happened.
+ */
+export async function openRemoteEditorUrl(url: string): Promise<boolean> {
+ const bridge = window.desktopBridge;
+ if (bridge !== undefined) {
+ try {
+ return await bridge.openExternal(url);
+ } catch {
+ return false;
+ }
+ }
+ window.location.assign(url);
+ return true;
+}
+
+/**
+ * One-time "you need SSH keys on that machine" hint, shown in the picker menu
+ * until the first remote open fires (we cannot observe SSH success from here,
+ * so first click is the dismiss signal).
+ */
+const REMOTE_OPEN_HINT_KEY = "t3code:remote-open-hint-seen";
+
+export function useRemoteOpenHint(): readonly [seen: boolean, markSeen: () => void] {
+ const [seen, setSeen] = useLocalStorage(REMOTE_OPEN_HINT_KEY, false, Schema.Boolean);
+ return [seen, () => setSeen(true)] as const;
+}
diff --git a/packages/contracts/src/editor.ts b/packages/contracts/src/editor.ts
index 5948d87e1..d714a0e02 100644
--- a/packages/contracts/src/editor.ts
+++ b/packages/contracts/src/editor.ts
@@ -10,20 +10,45 @@ type EditorDefinition = {
readonly commands: readonly [string, ...string[]] | null;
readonly baseArgs?: readonly string[];
readonly launchStyle: EditorLaunchStyle;
+ /**
+ * URL scheme for editors that support VS Code's remote deep links
+ * (`<scheme>://vscode-remote/ssh-remote+<host><path>`). Only set for VS Code
+ * and forks that ship the Remote-SSH machinery.
+ */
+ readonly remoteScheme?: string;
};
export const EDITORS = [
- { id: "cursor", label: "Cursor", commands: ["cursor"], launchStyle: "goto" },
+ {
+ id: "cursor",
+ label: "Cursor",
+ commands: ["cursor"],
+ launchStyle: "goto",
+ remoteScheme: "cursor",
+ },
{ id: "trae", label: "Trae", commands: ["trae"], launchStyle: "goto" },
{ id: "kiro", label: "Kiro", commands: ["kiro"], baseArgs: ["ide"], launchStyle: "goto" },
- { id: "vscode", label: "VS Code", commands: ["code"], launchStyle: "goto" },
+ {
+ id: "vscode",
+ label: "VS Code",
+ commands: ["code"],
+ launchStyle: "goto",
+ remoteScheme: "vscode",
+ },
{
id: "vscode-insiders",
label: "VS Code Insiders",
commands: ["code-insiders"],
launchStyle: "goto",
+ remoteScheme: "vscode-insiders",
+ },
+ {
+ id: "vscodium",
+ label: "VSCodium",
+ commands: ["codium"],
+ launchStyle: "goto",
+ remoteScheme: "vscodium",
},
- { id: "vscodium", label: "VSCodium", commands: ["codium"], launchStyle: "goto" },
{ id: "zed", label: "Zed", commands: ["zed", "zeditor"], launchStyle: "direct-path" },
{ id: "antigravity", label: "Antigravity", commands: ["agy"], launchStyle: "goto" },
{ id: "idea", label: "IntelliJ IDEA", commands: ["idea"], launchStyle: "line-column" },
@@ -50,6 +75,54 @@ export const LaunchEditorInput = Schema.Struct({
});
export type LaunchEditorInput = typeof LaunchEditorInput.Type;
+const remoteSchemeOf = (editor: EditorDefinition): string | undefined => editor.remoteScheme;
+
+/** Editors that can open a remote workspace via `vscode-remote` deep links. */
+export const REMOTE_CAPABLE_EDITOR_IDS: ReadonlyArray<EditorId> = EDITORS.flatMap((editor) =>
+ remoteSchemeOf(editor) !== undefined ? [editor.id] : [],
+);
+
+export const remoteSchemeForEditor = (id: EditorId): string | undefined => {
+ const editor = EDITORS.find((candidate) => candidate.id === id);
+ return editor === undefined ? undefined : remoteSchemeOf(editor);
+};
+
+/**
+ * Builds a `<scheme>://vscode-remote/ssh-remote+<host><path>` deep link that
+ * opens `absolutePath` on `host` in the local editor over SSH. Returns
+ * undefined for editors without remote deep-link support.
+ */
+export const buildRemoteOpenUrl = (input: {
+ readonly editor: EditorId;
+ readonly host: string;
+ readonly absolutePath: string;
+}): string | undefined => {
+ const scheme = remoteSchemeForEditor(input.editor);
+ if (scheme === undefined) {
+ return undefined;
+ }
+ // Windows server paths (`C:\...`) appear as `/C:/...` in vscode-remote URIs.
+ const posixPath = input.absolutePath.replaceAll("\\", "/");
+ const rootedPath = posixPath.startsWith("/") ? posixPath : `/${posixPath}`;
+ const encodedPath = rootedPath.split("/").map(encodeURIComponent).join("/");
+ return `${scheme}://vscode-remote/ssh-remote+${encodeURIComponent(input.host)}${encodedPath}`;
+};
+
+/**
+ * SSH hostnames an environment advertises for remote open links. Reachability
+ * is client-side; the server only advertises names that resolve to itself and
+ * gates them on a local sshd listen check. Ordered most-reachable first
+ * (tailnet MagicDNS name, then mDNS `<hostname>.local`).
+ */
+export const RemoteOpenTargetKind = Schema.Literals(["tailscale", "mdns"]);
+export type RemoteOpenTargetKind = typeof RemoteOpenTargetKind.Type;
+
+export const RemoteOpenTarget = Schema.Struct({
+ kind: RemoteOpenTargetKind,
+ host: TrimmedNonEmptyString,
+});
+export type RemoteOpenTarget = typeof RemoteOpenTarget.Type;
+
export class ExternalLauncherUnknownEditorError extends Schema.TaggedErrorClass<ExternalLauncherUnknownEditorError>()(
"ExternalLauncherUnknownEditorError",
{
diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts
index f99d4d34b..09d7d7a46 100644
--- a/packages/contracts/src/ipc.ts
+++ b/packages/contracts/src/ipc.ts
@@ -92,6 +92,7 @@ import { AuthAccessTokenResult, AuthSessionState, AuthWebSocketTicketResult } fr
import { AdvertisedEndpoint } from "./remoteAccess.ts";
import { ExecutionEnvironmentDescriptor } from "./environment.ts";
import type { ClientSettings } from "./settings.ts";
+import type { EditorId } from "./editor.ts";
import type {
SourceControlCloneRepositoryInput,
SourceControlCloneRepositoryResult,
@@ -1072,6 +1073,12 @@ export interface DesktopBridge {
position?: { x: number; y: number },
) => Promise<T | null>;
openExternal: (url: string) => Promise<boolean>;
+ /**
+ * Probe this desktop machine for installed remote-capable editor CLIs
+ * (used for remote open-in-editor deep links). Optional: older desktop
+ * builds lack it; callers fall back to VS Code only.
+ */
+ probeRemoteEditors?: () => Promise<readonly EditorId[]>;
onMenuAction: (listener: (action: string) => void) => () => void;
getWindowFullscreenState: () => boolean;
onWindowFullscreenStateChange: (listener: (fullscreen: boolean) => void) => () => void;
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index d7bc4c5c1..9791a4f62 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -17,7 +17,7 @@ import {
KeybindingWhen,
ResolvedKeybindingsConfig,
} from "./keybindings.ts";
-import { EditorId } from "./editor.ts";
+import { EditorId, RemoteOpenTarget } from "./editor.ts";
import { ModelCapabilities } from "./model.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
import { ServerSettings } from "./settings.ts";
@@ -428,6 +428,12 @@ export const ServerConfig = Schema.Struct({
// Editor ids grow over time; drop ones this build does not know rather than
// failing the whole config decode.
availableEditors: ForwardCompatibleArray(EditorId),
+ /**
+ * SSH hosts this environment advertises for remote open-in-editor links.
+ * Absent on servers that predate the feature; empty when the machine has no
+ * sshd or no advertisable name.
+ */
+ remoteOpenTargets: Schema.optionalKey(ForwardCompatibleArray(RemoteOpenTarget)),
observability: ServerObservability,
settings: ServerSettings,
/** Whether shell subscriptions can emit an opt-in catch-up completion marker. */
diff --git a/packages/shared/src/Net.ts b/packages/shared/src/Net.ts
index d7713a726..464457629 100644
--- a/packages/shared/src/Net.ts
+++ b/packages/shared/src/Net.ts
@@ -39,6 +39,12 @@ export interface NetServiceShape {
*/
readonly isPortAvailableOnLoopback: (port: number) => Effect.Effect<boolean>;
+ /**
+ * Returns true when something accepts TCP connections on {host, port}.
+ * Unlike the bind-side checks this works for privileged ports (<1024).
+ */
+ readonly hasListenerOnHost: (port: number, host: string) => Effect.Effect<boolean>;
+
/**
* Reserve an ephemeral loopback port and release it immediately.
*/
@@ -183,6 +189,7 @@ export const make = () => {
return {
canListenOnHost,
isPortAvailableOnLoopback,
+ hasListenerOnHost,
reserveLoopbackPort,
findAvailablePort: (preferred) =>
Effect.gen(function* () {
diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts
index 4c2ecb331..76b8ecccb 100644
--- a/packages/ssh/src/tunnel.test.ts
+++ b/packages/ssh/src/tunnel.test.ts
@@ -80,6 +80,7 @@ const hangingHttpClient = HttpClient.make(() => Effect.never);
const testNetService = NetService.NetService.of({
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
+ hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(41_773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
});
diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts
index 6914ebb69..9b4f44475 100644
--- a/scripts/dev-runner.test.ts
+++ b/scripts/dev-runner.test.ts
@@ -35,6 +35,7 @@ const emptyConfigLayer = ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} }
const netServiceLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
+ hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(49_152),
findAvailablePort: (port) => Effect.succeed(port),
});