The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 23:30 UTC
fix(chat): keep scratch file links usable (#30768)
Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Lakshmi Tanmay committed
Nov 12, 2026 at 01:24 UTC
1843c93e3911a3453dfce00034b750a8b36b0418
7 files changed
+178
-5
apps/mobile/src/lib/markdownDocument.ts
+23
-1
@@ -3,6 +3,7 @@ import { unified, type Processor } from "unified";
3
import remarkParse from "remark-parse";
4
import remarkGfm from "remark-gfm";
5
import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths";
6
+import { absoluteFilePathMatches, parseMarkdownFileLink } from "@t3tools/shared/markdownLinks";
7
import { isWindowsAbsolutePath } from "@t3tools/shared/path";
8
9
const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
@@ -304,7 +305,8 @@ function transformNativeMarkdown(
305
}
306
}
307
}
307
- if (!linkFiles && !breakTables) return markdown;
308
+ const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
309
+ if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
310
const edits: MarkdownEdit[] = [];
311
const fileEdits: MarkdownEdit[] = [];
312
let rewritesPipe = false;
@@ -317,6 +319,7 @@ function transformNativeMarkdown(
319
start !== undefined &&
320
end !== undefined &&
321
fileLink?.test(node.value) &&
322
+ parseMarkdownFileLink(node.value) !== null &&
323
!/[<>]/.test(node.value)
324
) {
325
const edit = {
@@ -328,6 +331,25 @@ function transformNativeMarkdown(
331
fileEdits.push(edit);
332
if (node.value.includes("|")) rewritesPipe = true;
333
}
334
+ } else if (
335
+ linkProseFiles &&
336
+ node.type === "text" &&
337
+ node.position?.start.offset !== undefined
338
+ ) {
339
+ const start = node.position.start.offset;
340
+ const raw = markdown.slice(start, node.position.end.offset);
341
+ for (const { index, path } of absoluteFilePathMatches(raw)) {
342
+ // Source offsets stay valid for paths whose own text needs no Markdown decoding.
343
+ if (raw !== node.value && /[\\&]/.test(path)) continue;
344
+ const escaped = path.replace(/[\\[\]&]/g, "\\$&");
345
+ const edit = {
346
+ start: start + index,
347
+ end: start + index + path.length,
348
+ content: `[${escaped}](<${escaped}>)`,
349
+ };
350
+ edits.push(edit);
351
+ fileEdits.push(edit);
352
+ }
353
} else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
354
node.children.forEach((child, index) => {
355
const previous = node.children[index - 1];
apps/mobile/src/lib/markdownInlineFileLinks.test.ts
+21
@@ -13,6 +13,25 @@ import {
13
const rewrite = (markdown: string) =>
14
markdownWithInlineFileLinks(markdown, ENRICHED_INLINE_FILE_LINK_REGEX);
15
16
+describe("absolute paths in prose", () => {
17
+ it("become links without corrupting the source around them", () => {
18
+ const path =
19
+ "/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
20
+ expect(rewrite(`Saved to ${path}.`)).toBe(`Saved to [${path}](<${path}>).`);
21
+ expect(
22
+ markdownForNativeRendering(
23
+ "Intro /tmp/notes.md\n| a | c |\n|---|---|\n| `./a\\|b.ts` | b |",
24
+ ENRICHED_INLINE_FILE_LINK_REGEX,
25
+ ),
26
+ ).toContain("[/tmp/notes.md](</tmp/notes.md>)");
27
+ expect(rewrite(String.raw`See \* and /tmp/notes.md.`)).toBe(
28
+ String.raw`See \* and [/tmp/notes.md](</tmp/notes.md>).`,
29
+ );
30
+ for (const decoded of [String.raw`See /tmp/a\_b.md.`, "See /tmp/a©.md."])
31
+ expect(rewrite(decoded)).toBe(decoded);
32
+ });
33
+});
34
+
35
describe("inline code that names a file", () => {
36
it.each([
37
[
@@ -69,6 +88,8 @@ describe("inline code that names a file", () => {
88
});
89
90
it("becomes a link to the same path", () => {
91
+ expect(rewrite("See `/tmp/claude-1000/...`.")).toBe("See `/tmp/claude-1000/...`.");
92
+ expect(rewrite("See `bin/python3.12`.")).toBe("See [bin/python3.12](<bin/python3.12>).");
93
expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(
94
"See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).",
95
);
evals/mcp-tool-use/cases/file-links.ndjson
+1
@@ -2,3 +2,4 @@
2
{"id":"file-links-ambiguous-basename","area":"file-links","kind":"bad","pattern":"file references by bare basename that several packages share","experience":"Claude cited `index.ts:42`-style basenames. The client looks a bare basename up on click, but with several matches it cannot pick the right file. 272 such pills in the audit.","source":{"audit":"Audit of chat file pills across three fleet machines, 2026-11-10"},"privacy":"commit-safe","setup":{"role":"top","world":{"repo":"acme/app","branch":"main","files":{"packages/server/src/cloud/http.ts":"import { nextDelay } from './retry';\n\nexport async function relayFetch(url: string, init: RequestInit, attempt = 0): Promise<Response> {\n const res = await fetch(url, init);\n if (res.status >= 500 && attempt < 8) {\n await new Promise((r) => setTimeout(r, nextDelay(attempt)));\n return relayFetch(url, init, attempt + 1);\n }\n return res;\n}\n","packages/server/src/cloud/retry.ts":"const BASE_MS = 500;\n\nexport function nextDelay(attempt: number): number {\n const exp = BASE_MS * 2 ** attempt;\n return exp + Math.floor(Math.random() * BASE_MS);\n}\n","packages/server/src/cloud/retry.test.ts":"import { nextDelay } from './retry';\n\ntest('grows', () => expect(nextDelay(3)).toBeGreaterThan(nextDelay(1)));\n","packages/web/src/cloud/http.ts":"export const apiFetch = (path: string) => fetch(`/api${path}`);\n","packages/server/src/index.ts":"import { startWs } from './ws';\n\nexport async function main() {\n const port = Number(process.env.PORT ?? 3773);\n await startWs(port);\n}\n\nmain();\n","packages/web/src/index.ts":"import { createRoot } from 'react-dom/client';\nimport { App } from './App';\n\ncreateRoot(document.getElementById('root')!).render(<App />);\n","packages/server/src/ws.ts":"import { WebSocketServer } from 'ws';\n\nexport function startWs(port: number) {\n const wss = new WebSocketServer({ port });\n wss.on('connection', (socket) => socket.send('hello'));\n return wss;\n}\n","package.json":"{ \"name\": \"acme\", \"private\": true, \"workspaces\": [\"packages/*\"] }\n","packages/server/package.json":"{ \"name\": \"@acme/server\", \"main\": \"src/index.ts\", \"scripts\": { \"start\": \"node src/index.ts\" } }\n","packages/web/package.json":"{ \"name\": \"@acme/web\" }\n"}}},"prompt":"How does the server process boot and start the WebSocket server? Walk me through it with file references.","expect":{"fileLinks":{"minWorking":2}},"maxSteps":8}
3
{"id":"file-links-other-checkout","area":"file-links","kind":"bad","pattern":"relative file references to a checkout outside the thread cwd","experience":"In a scratch thread the agent cloned a repo elsewhere and then cited `src/worker.ts` and `src/api.ts`. Chat resolved them against the scratch directory, so every pill was broken.","source":{"audit":"Audit of chat file pills across three fleet machines, 2026-11-10 (scratch threads on nucbox-1, 2026-10-19)"},"privacy":"commit-safe","setup":{"role":"top","world":{"repo":"acme/app","branch":"main","files":{"/home/user/work/worker/src/worker.ts":"import { take, ack, nack } from './queue';\n\nexport async function run() {\n for (;;) {\n const job = await take();\n try { await job.handle(); await ack(job); }\n catch { await nack(job, { delaySeconds: 30 * job.attempts }); }\n }\n}\n","/home/user/work/worker/src/queue.ts":"export const MAX_ATTEMPTS = 5;\nexport async function nack(job: Job, opts: { delaySeconds: number }) {\n if (job.attempts >= MAX_ATTEMPTS) return deadLetter(job);\n return requeue(job, opts.delaySeconds);\n}\n","/home/user/work/worker/src/api.ts":"export function enqueue(body: unknown) { return requeue({ body, attempts: 0 }, 0); }\n","/home/user/work/worker/package.json":"{ \"name\": \"@acme/worker\" }\n"}},"priorTurns":[{"role":"user","text":"Clone acme/worker into ~/work/worker so we can look at it."},{"role":"assistant","text":"Cloning it.","toolCalls":[{"tool":"Bash","input":{"command":"git clone git@github.com:acme/worker.git ~/work/worker && ls ~/work/worker/src"},"result":"Cloning into '/home/user/work/worker'...\napi.ts\nqueue.ts\nworker.ts"}]},{"role":"assistant","text":"Cloned acme/worker into /home/user/work/worker. Its source is in src/: api.ts, queue.ts and worker.ts."}]},"prompt":"How does the worker retry failed jobs, and where would I change the max attempts? Point me at the files.","expect":{"fileLinks":{"minWorking":2}},"maxSteps":8}
4
{"id":"file-links-no-files-control","area":"file-links","kind":"control","pattern":"a general question that needs no file references","experience":"Guards against an instruction change that makes agents attach file links to answers that are not about files.","source":{"audit":"Audit of chat file pills across three fleet machines, 2026-11-10"},"privacy":"commit-safe","setup":{"role":"top","world":{"repo":"acme/app","branch":"main","files":{"packages/server/src/cloud/http.ts":"import { nextDelay } from './retry';\n\nexport async function relayFetch(url: string, init: RequestInit, attempt = 0): Promise<Response> {\n const res = await fetch(url, init);\n if (res.status >= 500 && attempt < 8) {\n await new Promise((r) => setTimeout(r, nextDelay(attempt)));\n return relayFetch(url, init, attempt + 1);\n }\n return res;\n}\n","packages/server/src/cloud/retry.ts":"const BASE_MS = 500;\n\nexport function nextDelay(attempt: number): number {\n const exp = BASE_MS * 2 ** attempt;\n return exp + Math.floor(Math.random() * BASE_MS);\n}\n","packages/server/src/cloud/retry.test.ts":"import { nextDelay } from './retry';\n\ntest('grows', () => expect(nextDelay(3)).toBeGreaterThan(nextDelay(1)));\n","packages/web/src/cloud/http.ts":"export const apiFetch = (path: string) => fetch(`/api${path}`);\n","packages/server/src/index.ts":"import { startWs } from './ws';\n\nexport async function main() {\n const port = Number(process.env.PORT ?? 3773);\n await startWs(port);\n}\n\nmain();\n","packages/web/src/index.ts":"import { createRoot } from 'react-dom/client';\nimport { App } from './App';\n\ncreateRoot(document.getElementById('root')!).render(<App />);\n","packages/server/src/ws.ts":"import { WebSocketServer } from 'ws';\n\nexport function startWs(port: number) {\n const wss = new WebSocketServer({ port });\n wss.on('connection', (socket) => socket.send('hello'));\n return wss;\n}\n","package.json":"{ \"name\": \"acme\", \"private\": true, \"workspaces\": [\"packages/*\"] }\n","packages/server/package.json":"{ \"name\": \"@acme/server\", \"main\": \"src/index.ts\", \"scripts\": { \"start\": \"node src/index.ts\" } }\n","packages/web/package.json":"{ \"name\": \"@acme/web\" }\n"}}},"prompt":"Quick git question, no need to look at the repo: what does `git rebase --onto main feature~3 feature` do?","expect":{"fileLinks":{"minWorking":0},"notCalls":["Bash"]},"maxSteps":4}
5
+{"id":"scratch-file-markdown-link","area":"file-links","kind":"bad","pattern":"scratch file path shortened instead of written in full","experience":"A Claude scratch file was mentioned as shortened inline code such as `/tmp/claude-1000/...`, which no client can open.","privacy":"commit-safe","setup":{"role":"top","context":"You have just saved notes.md at /tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/12345678-1234-1234-1234-123456789abc/scratchpad/notes.md. The write succeeded. No more tools are needed."},"prompt":"The notes are ready? Tell me where you saved them. Keep it brief.","expect":{"finalTextMust":["/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/12345678-1234-1234-1234-123456789abc/scratchpad/notes\\.md"],"textMustNot":["/tmp/claude-1000/[^\\s<>`)]*(?:\\.{3,}|…)","`\\[[^\\]`\\n]*\\]\\(/tmp/claude-1000/[^)`\\n]*\\)`"]},"maxSteps":2,"source":{"issue":"https://github.com/pingdotgg/t3code/issues/30757"}}
packages/shared/src/markdownLinks.test.ts
+3
@@ -87,6 +87,9 @@ describe("parseMarkdownFileLink", () => {
87
"me@example.com",
88
"foo(bar)",
89
"$HOME",
90
+ "/tmp/claude-1000/...",
91
+ "/tmp/claude-1000/....:12",
92
+ "/tmp/claude-1000/%2E%2E%2E",
93
"\\foo.ts",
94
])("does not treat %s as a file", (href) => {
95
expect(parseMarkdownFileLink(href)).toBeNull();
packages/shared/src/markdownLinks.ts
+47
-1
@@ -335,7 +335,9 @@ export function parseMarkdownFileLink(href: string): FilePathPosition | null {
335
336
function parseFilePathLink(path: string, hash: string): FilePathPosition | null {
337
const position = splitFilePathPosition(path, hash);
338
- return looksLikeFilePath(position.path, path) ? position : null;
338
+ return !ELIDED_PATH_SEGMENT_PATTERN.test(position.path) && looksLikeFilePath(position.path, path)
339
+ ? position
340
+ : null;
341
}
342
343
const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
@@ -450,3 +452,47 @@ export function resolveMarkdownFileLinkTarget(
452
export function isWindowsDrivePathHref(href: string): boolean {
453
return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
454
}
455
+
456
+// Bare prose paths need a filesystem root or a position, so `/api/users.json` stays a route,
457
+// and a file-shaped last segment.
458
+export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
459
+ const paths: Array<{ index: number; path: string }> = [];
460
+ for (const match of text.matchAll(/(^|[\s(["'])(\/[^\s<>"'`]+)/g)) {
461
+ const source = match[2]!;
462
+ let parentheses = 0;
463
+ let brackets = 0;
464
+ for (const character of source) {
465
+ if (character === "(") parentheses += 1;
466
+ if (character === ")") parentheses -= 1;
467
+ if (character === "[") brackets += 1;
468
+ if (character === "]") brackets -= 1;
469
+ }
470
+ let end = source.length;
471
+ while (end > 0) {
472
+ const character = source[end - 1]!;
473
+ if (character === ")" && parentheses < 0) parentheses += 1;
474
+ else if (character === "]" && brackets < 0) brackets += 1;
475
+ else if (!".,;!?:".includes(character)) break;
476
+ end -= 1;
477
+ }
478
+ const path = source.slice(0, end);
479
+ // Trimming `/tmp/a/....` to `/tmp/a/` would hide its elided segment.
480
+ if (path.endsWith("/") && source.startsWith("...", end)) continue;
481
+ if (
482
+ !POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix)) &&
483
+ !POSITION_SUFFIX_PATTERN.test(path)
484
+ )
485
+ continue;
486
+ // Prose ends a path at whitespace, so `/Users/me/Library/Application Support/...` must not link.
487
+ const basename = path.slice(path.lastIndexOf("/") + 1);
488
+ if (
489
+ !POSITION_SUFFIX_PATTERN.test(path) &&
490
+ !FILE_EXTENSION_PATTERN.test(basename) &&
491
+ !EXTENSIONLESS_FILE_NAMES.has(basename)
492
+ )
493
+ continue;
494
+ if (!parseMarkdownFileLink(path)) continue;
495
+ paths.push({ index: match.index + match[1]!.length, path });
496
+ }
497
+ return paths;
498
+}
packages/shared/src/markdownPipeline.test.ts
+38
@@ -497,3 +497,41 @@ it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer
497
{ dataLocalSrc: String.raw`C:\shots\light.png`, dataDarkSrc: "file:///C:/shots/dark.png" },
498
]);
499
});
500
+
501
+it("links complete absolute paths in prose and skips shortened ones", () => {
502
+ const path =
503
+ "/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
504
+ const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS);
505
+ const links = (markdown: string) => {
506
+ const urls: string[] = [];
507
+ const visit = (node: Root | RootContent) => {
508
+ if (node.type === "link") urls.push(node.url);
509
+ if ("children" in node) node.children.forEach(visit);
510
+ };
511
+ visit(processor.runSync(processor.parse(markdown), markdown) as Root);
512
+ return urls;
513
+ };
514
+ expect(links(`Saved to ${path} and /tmp/other.txt.`)).toEqual([path, "/tmp/other.txt"]);
515
+ expect(links(`See (${path}:12).`)).toEqual([`${path}:12`]);
516
+ expect(links("See /tmp/report(1).txt. and /tmp/app/[id]/page.tsx.")).toEqual([
517
+ "/tmp/report(1).txt",
518
+ "/tmp/app/[id]/page.tsx",
519
+ ]);
520
+ expect(links("(see /tmp/claude-1000/...). and /tmp/claude-1000/….")).toEqual([]);
521
+ expect(links("Served at /index.html; GET /api/users.json; see /tmp/x.md:3.")).toEqual([
522
+ "/tmp/x.md:3",
523
+ ]);
524
+ expect(
525
+ links(
526
+ '<a title="</a>" href="https://example.com">/tmp/notes.md</a> and **<a href="x">/tmp/a.md</a>**',
527
+ ),
528
+ ).toEqual([]);
529
+ expect(
530
+ links("Config lives in /Users/me/Library/Application Support/T3 Code/settings.json now."),
531
+ ).toEqual([]);
532
+ expect(links(`/chat/settings and https://example.com${path}`)).toEqual([
533
+ `https://example.com${path}`,
534
+ ]);
535
+ expect(links(`[notes](${path}) and \`${path}\``)).toEqual([path]);
536
+ expect(links(`\`\`\`\n${path}\n\`\`\``)).toEqual([]);
537
+});
packages/shared/src/markdownPipeline.ts
+45
-3
@@ -16,7 +16,11 @@ import {
16
CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
17
remarkCodexDirectives,
18
} from "./codexMarkdownDirectives.ts";
19
-import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";
19
+import {
20
+ absoluteFilePathMatches,
21
+ isWindowsDrivePathHref,
22
+ normalizeMarkdownLinkDestination,
23
+} from "./markdownLinks.ts";
24
import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
25
26
export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
@@ -67,14 +71,16 @@ function markStandaloneImages(node: MarkdownImageHastNode) {
71
});
72
}
73
74
+// Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag.
75
+const RAW_HTML_TAG_PATTERN = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
76
+
77
function rehypePreserveBareAnchorPlaceholders() {
78
return (tree: MarkdownImageHastNode) => {
79
const anchors: Array<MarkdownImageHastNode | null> = [];
80
let rawTextTag: string | undefined;
81
const visit = (node: MarkdownImageHastNode) => {
82
if (node.type === "raw" && typeof node.value === "string") {
76
- // Scan whole tags, attributes, and comments so embedded closing-anchor text cannot match a placeholder.
77
- const tags = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
83
+ const tags = new RegExp(RAW_HTML_TAG_PATTERN);
84
let offset = 0;
85
while (rawTextTag !== "plaintext") {
86
// Raw text ends at its closing tag even inside comment-looking text.
@@ -231,6 +237,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
237
export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
238
remarkGfm,
239
remarkKeepAutolinkSuffixes,
240
+ remarkLinkAbsoluteFilePaths,
241
remarkKeepWindowsPaths,
242
remarkGithubAlerts,
243
remarkKeepOrderedListNumbers,
@@ -244,6 +251,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
251
export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
252
remarkGfm,
253
remarkKeepAutolinkSuffixes,
254
+ remarkLinkAbsoluteFilePaths,
255
remarkKeepWindowsPaths,
256
remarkGithubAlerts,
257
remarkKeepOrderedListNumbers,
@@ -445,6 +453,40 @@ function remarkKeepAutolinkSuffixes(): Transformer<Root> {
453
};
454
}
455
456
+function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
457
+ return (tree) => {
458
+ // Raw `<a>` tags are sibling html nodes, so text inside one is not under a link node.
459
+ let rawAnchorDepth = 0;
460
+ const visit = (node: Root | RootContent) => {
461
+ if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
462
+ node.children = node.children.flatMap((child): typeof node.children => {
463
+ if (child.type === "html") {
464
+ for (const [tag] of child.value.matchAll(RAW_HTML_TAG_PATTERN)) {
465
+ if (/^<a[\s/>]/i.test(tag)) rawAnchorDepth += 1;
466
+ else if (/^<\/a[\s>]/i.test(tag)) rawAnchorDepth = Math.max(0, rawAnchorDepth - 1);
467
+ }
468
+ }
469
+ if (child.type !== "text" || rawAnchorDepth > 0) {
470
+ visit(child);
471
+ return [child];
472
+ }
473
+ const parts: PhrasingContent[] = [];
474
+ let offset = 0;
475
+ for (const { index, path } of absoluteFilePathMatches(child.value)) {
476
+ if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
477
+ parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
478
+ offset = index + path.length;
479
+ }
480
+ if (offset === 0) return [child];
481
+ if (offset < child.value.length)
482
+ parts.push({ type: "text", value: child.value.slice(offset) });
483
+ return parts;
484
+ });
485
+ };
486
+ visit(tree);
487
+ };
488
+}
489
+
490
function remarkPreserveCodeMeta() {
491
return (tree: MarkdownAstNode) => {
492
const visit = (node: MarkdownAstNode) => {