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 160 additions and 153 deletions

No files matched your search

+45 -73
View File
@@ -64,7 +64,6 @@ import { remarkNormalizeListItemIndentation } from "../markdown-list-indentation
import {
normalizeMarkdownLinkDestination,
resolveMarkdownFileLinkMeta,
resolveMarkdownFileLinkTarget,
rewriteMarkdownFileUriHref,
} from "../markdown-links";
import { readLocalApi } from "../localApi";
@@ -123,8 +122,6 @@ const EMPTY_MARKDOWN_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "d
const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/;
const MAX_HIGHLIGHT_CACHE_ENTRIES = 500;
const MAX_HIGHLIGHT_CACHE_MEMORY_BYTES = 50 * 1024 * 1024;
const FILE_LINK_PARENT_SUFFIX_DATA_ATTRIBUTE = "data-file-link-parent-suffix";
const FILE_LINK_PARENT_SUFFIX_PROPERTY = "dataFileLinkParentSuffix";
interface MarkdownActionFailureContext {
readonly operation: string;
@@ -159,10 +156,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
...defaultSchema,
attributes: {
...defaultSchema.attributes,
"*": [
...(defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
FILE_LINK_PARENT_SUFFIX_PROPERTY,
],
"*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
code: [...(defaultSchema.attributes?.code ?? []), "dataCodeMeta"],
},
protocols: {
@@ -228,7 +222,6 @@ function extractPreCodeMeta(node: unknown): string | undefined {
type MarkdownAstNode = {
type?: string;
url?: string;
meta?: unknown;
data?: {
hProperties?: Record<string, unknown>;
@@ -754,6 +747,7 @@ interface MarkdownFileLinkProps {
className?: string | undefined;
}
const MARKDOWN_LINK_HREF_PATTERN = /\[[^\]]*]\(([^)\s]+)(?:\s+["'][^"']*["'])?\)/g;
const MARKDOWN_FILE_LINK_CLASS_NAME =
"chat-markdown-file-link cursor-pointer transition-colors hover:bg-accent/70";
@@ -817,42 +811,19 @@ function buildFileLinkParentSuffixByPath(filePaths: ReadonlyArray<string>): Map<
return suffixByPath;
}
function createFileLinkDisambiguationPlugin(cwd: string | undefined) {
return () => (tree: MarkdownAstNode) => {
const fileLinks: Array<{
node: MarkdownAstNode;
meta: NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>;
}> = [];
function extractMarkdownLinkHrefs(text: string): string[] {
const hrefs: string[] = [];
for (const match of text.matchAll(MARKDOWN_LINK_HREF_PATTERN)) {
const href = match[1]?.trim();
if (!href) continue;
hrefs.push(href);
}
return hrefs;
}
const visit = (node: MarkdownAstNode) => {
if (node.type === "link" && typeof node.url === "string") {
const meta = resolveMarkdownFileLinkMeta(node.url, cwd);
if (meta) {
fileLinks.push({ node, meta });
}
}
for (const child of node.children ?? []) {
visit(child);
}
};
visit(tree);
const suffixByPath = buildFileLinkParentSuffixByPath(
fileLinks.map((fileLink) => fileLink.meta.filePath),
);
for (const { node, meta } of fileLinks) {
const parentSuffix = suffixByPath.get(meta.filePath);
if (!parentSuffix) continue;
node.data = {
...node.data,
hProperties: {
...node.data?.hProperties,
[FILE_LINK_PARENT_SUFFIX_PROPERTY]: parentSuffix,
},
};
}
};
function normalizeMarkdownLinkHrefKey(href: string): string {
const normalizedHref = normalizeMarkdownLinkDestination(href);
return rewriteMarkdownFileUriHref(normalizedHref) ?? normalizedHref;
}
const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none";
@@ -1301,22 +1272,28 @@ function ChatMarkdown({
serverConfig?.availableEditors ?? [],
);
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const remarkPlugins = useMemo(
() => [
...(lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS),
createFileLinkDisambiguationPlugin(cwd),
],
[cwd, lineBreaks],
);
const markdownUrlTransform = useCallback(
(href: string) => {
return (
rewriteMarkdownFileUriHref(href) ??
(resolveMarkdownFileLinkTarget(href, cwd) ? href : defaultUrlTransform(href))
);
},
[cwd],
);
const markdownFileLinkMetaByHref = useMemo(() => {
const metaByHref = new Map<
string,
NonNullable<ReturnType<typeof resolveMarkdownFileLinkMeta>>
>();
for (const href of extractMarkdownLinkHrefs(text)) {
const normalizedHref = normalizeMarkdownLinkHrefKey(href);
if (metaByHref.has(normalizedHref)) continue;
const meta = resolveMarkdownFileLinkMeta(normalizedHref, cwd);
if (meta) {
metaByHref.set(normalizedHref, meta);
}
}
return metaByHref;
}, [cwd, text]);
const fileLinkParentSuffixByPath = useMemo(() => {
const filePaths = [...markdownFileLinkMetaByHref.values()].map((meta) => meta.filePath);
return buildFileLinkParentSuffixByPath(filePaths);
}, [markdownFileLinkMetaByHref]);
const markdownUrlTransform = useCallback((href: string) => {
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []);
// Re-emit highlighted content as markdown so copying out of the rendered
// view keeps links, emphasis, lists, and code fences intact.
const handleCopy = useCallback((event: ReactClipboardEvent<HTMLDivElement>) => {
@@ -1413,12 +1390,8 @@ function ChatMarkdown({
);
},
a({ node, href, children, ...props }) {
const normalizedHref = href
? (rewriteMarkdownFileUriHref(href) ?? normalizeMarkdownLinkDestination(href))
: "";
const fileLinkMeta = normalizedHref
? resolveMarkdownFileLinkMeta(normalizedHref, cwd)
: null;
const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : "";
const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null;
if (!fileLinkMeta) {
const faviconHost = resolveExternalLinkHost(href);
const isSameDocumentLink = href?.startsWith("#") ?? false;
@@ -1495,13 +1468,9 @@ function ChatMarkdown({
);
}
const anchorProps = props as typeof props & Record<string, unknown>;
const parentSuffix =
typeof anchorProps[FILE_LINK_PARENT_SUFFIX_DATA_ATTRIBUTE] === "string"
? anchorProps[FILE_LINK_PARENT_SUFFIX_DATA_ATTRIBUTE]
: undefined;
const parentSuffix = fileLinkParentSuffixByPath.get(fileLinkMeta.filePath);
const labelParts = [fileLinkMeta.basename];
if (parentSuffix) {
if (typeof parentSuffix === "string" && parentSuffix.length > 0) {
labelParts.push(parentSuffix);
}
if (fileLinkMeta.line) {
@@ -1570,9 +1539,10 @@ function ChatMarkdown({
},
}),
[
cwd,
diffThemeName,
fileLinkParentSuffixByPath,
isStreaming,
markdownFileLinkMetaByHref,
onTaskListChange,
openInPreferredEditor,
openExternalLinkInPreview,
@@ -1593,7 +1563,9 @@ function ChatMarkdown({
onCopy={handleCopy}
>
<ReactMarkdown
remarkPlugins={remarkPlugins}
remarkPlugins={
lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS
}
rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
components={markdownComponents}
urlTransform={markdownUrlTransform}
+14 -39
View File
@@ -6,20 +6,6 @@ import {
rewriteMarkdownFileUriHref,
} from "./markdown-links";
describe("normalizeMarkdownLinkDestination", () => {
it("unescapes markdown punctuation when normalizing destinations", () => {
expect(
resolveMarkdownFileLinkTarget("apps/web/src/routes/\\(chat\\)/\\[id\\].tsx", "/repo"),
).toBe("/repo/apps/web/src/routes/(chat)/[id].tsx");
});
it("preserves windows path separators before punctuation", () => {
expect(resolveMarkdownFileLinkTarget(String.raw`C:\src\(group)\page.tsx`)).toBe(
String.raw`C:\src\(group)\page.tsx`,
);
});
});
describe("rewriteMarkdownFileUriHref", () => {
it("rewrites file uri hrefs into direct path hrefs", () => {
expect(rewriteMarkdownFileUriHref("file:///Users/julius/project/src/main.ts#L42")).toBe(
@@ -40,6 +26,12 @@ describe("rewriteMarkdownFileUriHref", () => {
),
).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx#L69");
});
it("unwraps angle-bracketed file uri hrefs", () => {
expect(
rewriteMarkdownFileUriHref(" <file:///D:/Programme/t3code/apps/web/src/markdown-links.ts> "),
).toBe("D:/Programme/t3code/apps/web/src/markdown-links.ts");
});
});
describe("resolveMarkdownFileLinkTarget", () => {
@@ -67,31 +59,6 @@ describe("resolveMarkdownFileLinkTarget", () => {
);
});
it("resolves relative paths with route group and dynamic segment characters", () => {
expect(
resolveMarkdownFileLinkTarget("apps/web/src/routes/(chat)/[threadId].tsx", "/repo/project"),
).toBe("/repo/project/apps/web/src/routes/(chat)/[threadId].tsx");
});
it("resolves encoded route group and dynamic segment characters", () => {
expect(
resolveMarkdownFileLinkTarget(
"apps/web/src/routes/%28chat%29/%5BthreadId%5D.tsx",
"/repo/project",
),
).toBe("/repo/project/apps/web/src/routes/(chat)/[threadId].tsx");
});
it("preserves support for conservative extensionless relative file paths", () => {
expect(resolveMarkdownFileLinkTarget("scripts/release", "/repo/project")).toBe(
"/repo/project/scripts/release",
);
});
it("does not treat ambiguous encoded relative web links as file paths", () => {
expect(resolveMarkdownFileLinkTarget("docs/user%20guide", "/repo/project")).toBeNull();
});
it("maps #L line anchors to editor line suffixes", () => {
expect(resolveMarkdownFileLinkTarget("/Users/julius/project/src/main.ts#L42C7")).toBe(
"/Users/julius/project/src/main.ts:42:7",
@@ -148,6 +115,14 @@ describe("resolveMarkdownFileLinkTarget", () => {
).toBe("D:/Programme/t3code/apps/web/src/components/chat/OpenInPicker.tsx:69");
});
it("resolves angle-bracketed windows drive paths", () => {
expect(
resolveMarkdownFileLinkTarget(
"</D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1>",
),
).toBe("D:/Programme/t3code/apps/web/src/components/ChatMarkdown.tsx:1");
});
it("does not treat app routes as file links", () => {
expect(resolveMarkdownFileLinkTarget("/chat/settings")).toBeNull();
});
+7 -26
View File
@@ -3,10 +3,10 @@ import { resolvePathLinkTarget, splitPathAndPosition } from "./terminal-links";
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/;
const WINDOWS_BACKSLASH_PATH_PATTERN = /^(?:[A-Za-z]:\\|\\\\)/;
const EXTERNAL_SCHEME_PATTERN = /^([A-Za-z][A-Za-z0-9+.-]*):(.*)$/;
const RELATIVE_PATH_PREFIX_PATTERN = /^(~\/|\.{1,2}\/)/;
const CONSERVATIVE_RELATIVE_PATH_SEGMENT_PATTERN = /^[A-Za-z0-9._-]+$/;
const RELATIVE_FILE_PATH_PATTERN = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}$/;
const RELATIVE_FILE_NAME_PATTERN = /^[A-Za-z0-9._-]+\.[A-Za-z0-9_-]+(?::\d+){0,2}$/;
const POSITION_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
const POSIX_FILE_ROOT_PREFIXES = [
@@ -40,14 +40,12 @@ function safeDecode(value: string): string {
}
}
const MARKDOWN_ESCAPE_PATTERN = /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g;
function unwrapMarkdownLinkDestination(value: string): string {
return value.startsWith("<") && value.endsWith(">") ? value.slice(1, -1) : value;
}
export function normalizeMarkdownLinkDestination(value: string): string {
const trimmedValue = value.trim();
if (WINDOWS_BACKSLASH_PATH_PATTERN.test(trimmedValue)) {
return trimmedValue;
}
return trimmedValue.replace(MARKDOWN_ESCAPE_PATTERN, "$1");
return unwrapMarkdownLinkDestination(value.trim());
}
function stripSearchAndHash(value: string): { path: string; hash: string } {
@@ -115,24 +113,7 @@ function isLikelyPathCandidate(path: string): boolean {
if (WINDOWS_DRIVE_PATH_PATTERN.test(path) || WINDOWS_UNC_PATH_PATTERN.test(path)) return true;
if (RELATIVE_PATH_PREFIX_PATTERN.test(path)) return true;
if (path.startsWith("/")) return looksLikePosixFilesystemPath(path);
const { path: actualPath } = splitPathAndPosition(path);
if (actualPath.length === 0) return false;
if (["\0", "\r", "\n", '"', "'", "`", "<", ">"].some((char) => actualPath.includes(char))) {
return false;
}
const normalizedPath = actualPath.replaceAll("\\", "/");
const segments = normalizedPath.split("/");
if (segments.length > 1) {
if (segments.some((segment) => segment.length === 0)) return false;
const basename = segments.at(-1) ?? "";
return (
/\.[A-Za-z0-9_-]+$/.test(basename) ||
segments.every((segment) => CONSERVATIVE_RELATIVE_PATH_SEGMENT_PATTERN.test(segment))
);
}
return /\.[A-Za-z0-9_-]+$/.test(actualPath);
return RELATIVE_FILE_PATH_PATTERN.test(path) || RELATIVE_FILE_NAME_PATTERN.test(path);
}
function isRelativePath(path: string): boolean {
+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;