Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex d2de125352 fix(ssh): disable tunnel multiplexing (#3533)
Issue #3533 requires the supervised port-forward process to own its lifecycle even when the user's SSH config enables ControlMaster or ControlPersist.

Co-authored-by: codex <[email protected]>
2026-07-20 18:23:30 +02:00
5 changed files with 131 additions and 245 deletions

No files matched your search

+37 -24
View File
@@ -42,10 +42,6 @@ import remarkGfm from "remark-gfm";
import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";
import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
import {
resolveExternalWebLinkHost,
showExternalLinkContextMenu,
} from "./chat/externalLinkContextMenu";
import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { Button } from "./ui/button";
@@ -80,7 +76,6 @@ import { usePreparedConnection } from "../state/session";
import { previewEnvironment } from "../state/preview";
import { useAtomCommand } from "../state/use-atom-command";
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
import { isPreviewSupportedInRuntime } from "../previewStateStore";
import {
isBrowserPreviewFile,
@@ -836,6 +831,17 @@ const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
/** Hosts whose favicon request already failed this session — skip straight to the globe. */
const failedFaviconHosts = new Set<string>();
function resolveExternalLinkHost(href: string | undefined): string | null {
if (!href) return null;
try {
const url = new URL(href);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
return url.hostname || null;
} catch {
return null;
}
}
const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) {
const [failedHost, setFailedHost] = useState<string | null>(null);
return (
@@ -1387,7 +1393,7 @@ function ChatMarkdown({
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
const faviconHost = resolveExternalWebLinkHost(href);
const faviconHost = resolveExternalLinkHost(href);
const isSameDocumentLink = href?.startsWith("#") ?? false;
const onClick = props.onClick;
const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime();
@@ -1404,30 +1410,37 @@ function ChatMarkdown({
}
}}
onContextMenu={(event) => {
if (!canOpenInPreview || !href || !faviconHost) return;
if (!canOpenInPreview || !href) return;
event.preventDefault();
event.stopPropagation();
const api = readLocalApi();
if (!api) return;
void showExternalLinkContextMenu({
href,
position: { x: event.clientX, y: event.clientY },
showContextMenu: (items, position) => api.contextMenu.show(items, position),
openInPreview: async (target) => {
const result = await openExternalLinkInPreview(target);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
reportMarkdownActionFailure(
{ operation: "open-link-in-preview", target },
result.cause,
);
void (async () => {
let operation = "show-link-context-menu";
try {
const clicked = await api.contextMenu.show(
[
{ id: "open-in-browser", label: "Open in integrated browser" },
{ id: "open-external", label: "Open in system browser" },
] as const,
{ x: event.clientX, y: event.clientY },
);
if (clicked === "open-in-browser") {
operation = "open-link-in-preview";
const result = await openExternalLinkInPreview(href);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
reportMarkdownActionFailure({ operation, target: href }, result.cause);
}
return;
}
},
openExternal: (target) => api.shell.openExternal(target),
copyLink: (target) => writeTextToClipboard(target, "link"),
reportFailure: (operation, cause) => {
if (clicked === "open-external") {
operation = "open-link-external";
await api.shell.openExternal(href);
}
} catch (cause) {
reportMarkdownActionFailure({ operation, target: href }, cause);
},
});
}
})();
}}
>
{faviconHost ? (
@@ -1,128 +0,0 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { resolveExternalWebLinkHost, showExternalLinkContextMenu } from "./externalLinkContextMenu";
function createHarness(selection: "open-in-preview" | "open-external" | "copy-link" | null) {
const showContextMenu = vi.fn().mockResolvedValue(selection);
const openInPreview = vi.fn().mockResolvedValue(undefined);
const openExternal = vi.fn().mockResolvedValue(undefined);
const copyLink = vi.fn().mockResolvedValue(undefined);
const reportFailure = vi.fn();
return {
showContextMenu,
openInPreview,
openExternal,
copyLink,
reportFailure,
};
}
describe("external chat link context menu", () => {
it("offers both open actions and Copy Link", async () => {
const harness = createHarness(null);
await showExternalLinkContextMenu({
href: "https://example.com/docs?topic=menus#copy",
position: { x: 12, y: 24 },
...harness,
});
expect(harness.showContextMenu).toHaveBeenCalledWith(
[
{ id: "open-in-preview", label: "Open in integrated browser" },
{ id: "open-external", label: "Open in system browser" },
{ id: "copy-link", label: "Copy Link" },
],
{ x: 12, y: 24 },
);
expect(harness.openInPreview).not.toHaveBeenCalled();
expect(harness.openExternal).not.toHaveBeenCalled();
expect(harness.copyLink).not.toHaveBeenCalled();
});
it("copies the exact destination without opening it", async () => {
const harness = createHarness("copy-link");
const href = "https://example.com/docs?topic=menus#copy";
await showExternalLinkContextMenu({ href, position: { x: 1, y: 2 }, ...harness });
expect(harness.copyLink).toHaveBeenCalledWith(href);
expect(harness.openInPreview).not.toHaveBeenCalled();
expect(harness.openExternal).not.toHaveBeenCalled();
});
it.each([
["open-in-preview" as const, "openInPreview" as const],
["open-external" as const, "openExternal" as const],
])("preserves the %s action", async (selection, expectedCallback) => {
const harness = createHarness(selection);
const href = "https://example.com/docs";
await showExternalLinkContextMenu({ href, position: { x: 1, y: 2 }, ...harness });
expect(harness[expectedCallback]).toHaveBeenCalledWith(href);
expect(harness.copyLink).not.toHaveBeenCalled();
});
it("reports the selected action when it fails", async () => {
const harness = createHarness("copy-link");
const cause = new Error("clipboard denied");
harness.copyLink.mockRejectedValue(cause);
await showExternalLinkContextMenu({
href: "https://example.com/docs",
position: { x: 1, y: 2 },
...harness,
});
expect(harness.reportFailure).toHaveBeenCalledWith("copy-link", cause);
});
it("reports the menu operation when the native menu cannot be shown", async () => {
const harness = createHarness(null);
const cause = new Error("menu unavailable");
harness.showContextMenu.mockRejectedValue(cause);
await showExternalLinkContextMenu({
href: "https://example.com/docs",
position: { x: 1, y: 2 },
...harness,
});
expect(harness.reportFailure).toHaveBeenCalledWith("show-link-context-menu", cause);
expect(harness.openInPreview).not.toHaveBeenCalled();
expect(harness.openExternal).not.toHaveBeenCalled();
expect(harness.copyLink).not.toHaveBeenCalled();
});
it.each([
["open-in-preview" as const, "openInPreview" as const, "open-link-in-preview"],
["open-external" as const, "openExternal" as const, "open-link-external"],
])("reports a failed %s action", async (selection, callback, operation) => {
const harness = createHarness(selection);
const cause = new Error("open failed");
harness[callback].mockRejectedValue(cause);
await showExternalLinkContextMenu({
href: "https://example.com/docs",
position: { x: 1, y: 2 },
...harness,
});
expect(harness.reportFailure).toHaveBeenCalledWith(operation, cause);
});
it.each([
["https://example.com", "example.com"],
["http://localhost:3000/path", "localhost"],
["#details", null],
["mailto:[email protected]", null],
["file:///tmp/example.txt", null],
["javascript:void(0)", null],
["not a URL", null],
[undefined, null],
])("resolves the external web-link host for %s as %s", (href, expected) => {
expect(resolveExternalWebLinkHost(href)).toBe(expected);
});
});
@@ -1,78 +0,0 @@
import type { ContextMenuItem } from "@t3tools/contracts";
export type ExternalLinkContextMenuAction = "open-in-preview" | "open-external" | "copy-link";
export type ExternalLinkContextMenuFailureOperation =
| "show-link-context-menu"
| "open-link-in-preview"
| "open-link-external"
| "copy-link";
const FAILURE_OPERATION_BY_ACTION = {
"open-in-preview": "open-link-in-preview",
"open-external": "open-link-external",
"copy-link": "copy-link",
} as const satisfies Record<ExternalLinkContextMenuAction, ExternalLinkContextMenuFailureOperation>;
const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [
{ id: "open-in-preview", label: "Open in integrated browser" },
{ id: "open-external", label: "Open in system browser" },
{ id: "copy-link", label: "Copy Link" },
] as const satisfies readonly ContextMenuItem<ExternalLinkContextMenuAction>[];
interface ShowExternalLinkContextMenuOptions {
readonly href: string;
readonly position: { readonly x: number; readonly y: number };
readonly showContextMenu: (
items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
position: { readonly x: number; readonly y: number },
) => Promise<ExternalLinkContextMenuAction | null>;
readonly openInPreview: (href: string) => Promise<void>;
readonly openExternal: (href: string) => Promise<void>;
readonly copyLink: (href: string) => Promise<unknown>;
readonly reportFailure: (
operation: ExternalLinkContextMenuFailureOperation,
cause: unknown,
) => void;
}
export function resolveExternalWebLinkHost(href: string | undefined): string | null {
if (!href) return null;
try {
const url = new URL(href);
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
return url.hostname || null;
} catch {
return null;
}
}
export async function showExternalLinkContextMenu({
href,
position,
showContextMenu,
openInPreview,
openExternal,
copyLink,
reportFailure,
}: ShowExternalLinkContextMenuOptions): Promise<void> {
let action: ExternalLinkContextMenuAction | null;
try {
action = await showContextMenu(EXTERNAL_LINK_CONTEXT_MENU_ITEMS, position);
} catch (cause) {
reportFailure("show-link-context-menu", cause);
return;
}
try {
if (action === "open-in-preview") {
await openInPreview(href);
} else if (action === "open-external") {
await openExternal(href);
} else if (action === "copy-link") {
await copyLink(href);
}
} catch (cause) {
if (action) reportFailure(FAILURE_OPERATION_BY_ACTION[action], cause);
}
}
+56
View File
@@ -14,6 +14,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { SshPasswordPrompt } from "./auth.ts";
import {
buildSupervisedSshTunnelArgs,
buildRemoteLaunchScript,
buildRemotePairingScript,
buildRemoteStopScript,
@@ -89,6 +90,50 @@ function commandArgs(command: ChildProcess.Command): ReadonlyArray<string> {
}
describe("ssh tunnel scripts", () => {
it("disables connection multiplexing for the supervised port-forward command", () => {
const target = {
alias: "devbox",
hostname: "devbox.example.com",
username: "julius",
port: 2222,
} as const;
assert.deepEqual(
buildSupervisedSshTunnelArgs({
target,
batchMode: "no",
localPort: 41_773,
remotePort: 3_773,
hostSpec: "julius@devbox",
}),
[
"-o",
"BatchMode=no",
"-o",
"ConnectTimeout=10",
"-p",
"2222",
"-o",
"ControlMaster=no",
"-o",
"ControlPath=none",
"-o",
"ControlPersist=no",
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
"41773:127.0.0.1:3773",
"julius@devbox",
],
);
});
it("builds the remote t3 runner with npx and npm fallbacks", () => {
const script = buildRemoteT3RunnerScript({ nodeEngineRange: TEST_NODE_ENGINE_RANGE });
@@ -382,6 +427,17 @@ describe("ssh tunnel scripts", () => {
const first = yield* manager.ensureEnvironment(target);
assert.equal(first.httpBaseUrl, "http://127.0.0.1:41773/");
const firstTunnelArgs = spawnedCommands.find((args) => args.includes("-N"));
assert.isDefined(firstTunnelArgs);
assert.include(firstTunnelArgs, "ControlMaster=no");
assert.include(firstTunnelArgs, "ControlPath=none");
assert.include(firstTunnelArgs, "ControlPersist=no");
for (const args of spawnedCommands.filter((entry) => !entry.includes("-N"))) {
assert.notInclude(args, "ControlMaster=no");
assert.notInclude(args, "ControlPath=none");
assert.notInclude(args, "ControlPersist=no");
}
yield* manager.disconnectEnvironment(target);
assert.equal(tunnelKillCount, 1);
assert.equal(stopCommandCount, 1);
+38 -15
View File
@@ -917,6 +917,38 @@ const reserveLocalTunnelPort = Effect.fn("ssh/tunnel.reserveLocalTunnelPort")(fu
return yield* net.reserveLoopbackPort();
});
export function buildSupervisedSshTunnelArgs(input: {
readonly target: DesktopSshEnvironmentTarget;
readonly batchMode: "yes" | "no";
readonly localPort: number;
readonly remotePort: number;
readonly hostSpec: string;
}): ReadonlyArray<string> {
return [
...baseSshArgs(input.target, { batchMode: input.batchMode }),
// This process owns the tunnel lifecycle. Inherited ControlMaster settings
// can otherwise hand the forward to an existing master and let `ssh -N`
// exit while the manager believes it still supervises the connection.
"-o",
"ControlMaster=no",
"-o",
"ControlPath=none",
"-o",
"ControlPersist=no",
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
`${input.localPort}:127.0.0.1:${input.remotePort}`,
input.hostSpec,
];
}
const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input: {
readonly key: string;
readonly resolvedTarget: DesktopSshEnvironmentTarget;
@@ -956,22 +988,13 @@ const startSshTunnel = Effect.fn("ssh/tunnel.startSshTunnel")(function* (input:
}),
),
);
const args = [
...baseSshArgs(input.resolvedTarget, {
batchMode: input.authOptions.batchMode ?? "no",
}),
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-n",
"-N",
"-L",
`${input.localPort}:127.0.0.1:${input.remotePort}`,
const args = buildSupervisedSshTunnelArgs({
target: input.resolvedTarget,
batchMode: input.authOptions.batchMode ?? "no",
localPort: input.localPort,
remotePort: input.remotePort,
hostSpec,
];
});
const sshCommand = yield* resolveSshCommand;
const tunnelCommand = [sshCommand, ...args];
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;