Skip to content

Commit 04ba72e

Browse files
committed
fix(chat): keep scratch file links usable
1 parent 8b44f42 commit 04ba72e

10 files changed

Lines changed: 130 additions & 7 deletions

File tree

‎apps/mobile/src/lib/markdownDocument.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { unified, type Processor } from "unified";
33
import remarkParse from "remark-parse";
44
import remarkGfm from "remark-gfm";
55
import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths";
6+
import {
7+
absoluteFilePathMatches,
8+
inlineCodeFilePathCandidate,
9+
} from "@t3tools/shared/markdownLinks";
610
import { isWindowsAbsolutePath } from "@t3tools/shared/path";
711

812
const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
@@ -306,7 +310,8 @@ function transformNativeMarkdown(
306310
}
307311
}
308312
}
309-
if (!linkFiles && !breakTables) return markdown;
313+
const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
314+
if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
310315
const edits: MarkdownEdit[] = [];
311316
const fileEdits: MarkdownEdit[] = [];
312317
let rewritesPipe = false;
@@ -319,6 +324,7 @@ function transformNativeMarkdown(
319324
start !== undefined &&
320325
end !== undefined &&
321326
fileLink?.test(node.value) &&
327+
inlineCodeFilePathCandidate(node.value) !== null &&
322328
!/[<>]/.test(node.value)
323329
) {
324330
const edit = {
@@ -330,6 +336,22 @@ function transformNativeMarkdown(
330336
fileEdits.push(edit);
331337
if (node.value.includes("|")) rewritesPipe = true;
332338
}
339+
} else if (
340+
linkProseFiles &&
341+
node.type === "text" &&
342+
node.position?.start.offset !== undefined
343+
) {
344+
const start = node.position.start.offset;
345+
const raw = markdown.slice(start, node.position.end.offset);
346+
if (raw !== node.value) return;
347+
for (const { index, path } of absoluteFilePathMatches(raw)) {
348+
const escaped = path.replace(/[\\[\]&]/g, "\\$&");
349+
edits.push({
350+
start: start + index,
351+
end: start + index + path.length,
352+
content: `[${escaped}](<${escaped}>)`,
353+
});
354+
}
333355
} else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
334356
node.children.forEach((child, index) => {
335357
const previous = node.children[index - 1];

‎apps/mobile/src/lib/markdownInlineFileLinks.test.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,12 @@ describe("inline code that names a file", () => {
6969
});
7070

7171
it("becomes a link to the same path", () => {
72+
const path =
73+
"/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
74+
expect(rewrite(`Saved to ${path}.`)).toBe(`Saved to [${path}](<${path}>).`);
75+
const escaped = String.raw`See /tmp/a\_b.md.`;
76+
expect(rewrite(escaped)).toBe(escaped);
77+
expect(rewrite("See `/tmp/claude-1000/...`.")).toBe("See `/tmp/claude-1000/...`.");
7278
expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe(
7379
"See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).",
7480
);

‎apps/server/src/provider/CodexDeveloperInstructions.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ describe("Codex runtime context", () => {
4040
});
4141
NodeAssert.match(
4242
instructions,
43-
/<runtime_info>.*embed images, video, and audio.*Markdown image syntax with absolute file paths.*Link any other file.*absolute path.*files viewer.*<\/runtime_info>/,
43+
/<runtime_info>.*embed images, video, and audio.*Markdown image syntax with absolute file paths.*Link files as Markdown.*full absolute path.*never ellipses.*<\/runtime_info>/,
4444
);
4545
}
4646
});
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"claudeSystemAppendBytes": 5153,
3-
"codexAdditionalContextBytes": 6883,
2+
"claudeSystemAppendBytes": 5140,
3+
"codexAdditionalContextBytes": 6870,
44
"mcpToolListJsonBytes": 47538
55
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"id": "scratch-file-markdown-link", "area": "file-links", "kind": "bad", "pattern": "scratch file path shortened or emitted without a Markdown link", "experience": "A Claude scratch file was mentioned as a bare path or shortened inline code; only its full Markdown link reliably opened the viewer.", "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": {"textMust": ["\\[[^\\]\\n]+\\]\\(/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/12345678-1234-1234-1234-123456789abc/scratchpad/notes\\.md\\)"], "textMustNot": ["/tmp/claude-1000/(?:\\.\\.\\.|…)"]}, "maxSteps": 2, "source": {"issue": "https://github.com/pingdotgg/t3code/issues/30757"}}

‎packages/provider-core/src/server/runtimeInstructions.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ export function buildRuntimeInstructions(runtime: {
2020
modelName && modelName !== model ? `${modelName} (model slug: ${model})` : model;
2121
const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : "";
2222
const effortInfo = effort ? ` with ${effort} reasoning effort` : "";
23-
const runtimeInfo = `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio in your response using Markdown image syntax with absolute file paths. Link any other file you produce using its absolute path so the user can open it in T3 Code's files viewer.</runtime_info>`;
23+
const runtimeInfo = `<runtime_info>In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio in your response using Markdown image syntax with absolute file paths. Link files as Markdown: [name](/absolute/path), using the full absolute path, never ellipses.</runtime_info>`;
2424
return runtime.pullRequestLinking === false
2525
? runtimeInfo
2626
: `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`;

‎packages/shared/src/markdownLinks.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,16 @@ describe("inlineCodeFilePathCandidate", () => {
2929
["share/man/ls.1", "share/man/ls.1"],
3030
["src/main.ts/", null],
3131
["./patches/", "./patches/"],
32+
["/tmp/claude-1000/...", null],
33+
["/tmp/claude-1000/....", null],
34+
["/tmp/claude-1000/.../notes.md", null],
35+
["/tmp/claude-1000/…", null],
36+
["/tmp/claude-1000/.hidden.md", "/tmp/claude-1000/.hidden.md"],
37+
["../notes.md", "../notes.md"],
38+
[
39+
"/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md",
40+
"/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md",
41+
],
3242
])("distinguishes file paths from code and hostnames in %s", (source, candidate) => {
3343
expect(inlineCodeFilePathCandidate(source)).toBe(candidate);
3444
});
@@ -68,6 +78,11 @@ describe("parseMarkdownFileLink", () => {
6878
6979
"foo(bar)",
7080
"$HOME",
81+
"/tmp/claude-1000/...",
82+
"/tmp/claude-1000/....:12",
83+
"/tmp/claude-1000/.../notes.md",
84+
"/tmp/claude-1000/%2E%2E%2E",
85+
"/tmp/claude-1000/…",
7186
])("does not treat %s as a file", (href) => {
7287
expect(parseMarkdownFileLink(href)).toBeNull();
7388
});

‎packages/shared/src/markdownLinks.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ const POSITION_ONLY_PATTERN = /^\d+(?::\d+)?$/;
3232

3333
const INLINE_CODE_DISQUALIFIER_PATTERN = /[\s`]/;
3434

35+
const ABBREVIATED_PATH_SEGMENT_PATTERN = /(?:^|[\\/])(?:\.{3,}|…)(?:[\\/]|$)/;
36+
3537
const PATH_SEPARATOR_PATTERN = /[\\/]/;
3638

3739
const FILE_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/;
@@ -176,6 +178,7 @@ export function inlineCodeFilePathCandidate(codeText: string): string | null {
176178
if (trimmed.length === 0 || INLINE_CODE_DISQUALIFIER_PATTERN.test(trimmed)) return null;
177179

178180
const candidate = isWindowsAbsolutePath(trimmed) ? trimmed : trimmed.replaceAll("\\", "/");
181+
if (ABBREVIATED_PATH_SEGMENT_PATTERN.test(splitFilePathPosition(candidate).path)) return null;
179182
const hasPosition = POSITION_SUFFIX_PATTERN.test(candidate);
180183
if (!hasPosition && !PATH_SEPARATOR_PATTERN.test(candidate)) return null;
181184

@@ -311,7 +314,10 @@ export function parseMarkdownFileLink(href: string): FilePathPosition | null {
311314
if (path.length === 0 || hasExternalScheme(path)) return null;
312315

313316
const position = splitFilePathPosition(path, hash);
314-
return looksLikeFilePath(position.path, path) ? position : null;
317+
return !ABBREVIATED_PATH_SEGMENT_PATTERN.test(position.path) &&
318+
looksLikeFilePath(position.path, path)
319+
? position
320+
: null;
315321
}
316322

317323
const FENCED_CODE_SEGMENT_PATTERN = /(```[\s\S]*?(?:```|$))/;
@@ -426,3 +432,14 @@ export function resolveMarkdownFileLinkTarget(
426432
export function isWindowsDrivePathHref(href: string): boolean {
427433
return /^[A-Za-z]:[\\/]/.test(safeDecodeURIComponent(href));
428434
}
435+
436+
export function absoluteFilePathMatches(text: string): Array<{ index: number; path: string }> {
437+
const paths: Array<{ index: number; path: string }> = [];
438+
for (const match of text.matchAll(/(^|[\s("'])(\/[^\s<>"'`[\]]+)/g)) {
439+
if (/(?:^|\/)(?:\.{3,}|…)(?:\/|[.,;!?:)]*$)/.test(match[2]!)) continue;
440+
const path = match[2]!.replace(/[.,;!?:)]+$/, "");
441+
if (!parseMarkdownFileLink(path)) continue;
442+
paths.push({ index: match.index + match[1]!.length, path });
443+
}
444+
return paths;
445+
}

‎packages/shared/src/markdownPipeline.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,3 +290,33 @@ it("moves a <picture>'s color-scheme sources onto its <img>, which the renderer
290290
{ dataLocalSrc: String.raw`C:\shots\light.png`, dataDarkSrc: "file:///C:/shots/dark.png" },
291291
]);
292292
});
293+
294+
it.each([
295+
["default", CHAT_MARKDOWN_REMARK_PLUGINS],
296+
["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS],
297+
] as const)("links complete scratch paths in prose (%s)", (_, plugins) => {
298+
const path =
299+
"/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md";
300+
const processor = unified().use(remarkParse).use(plugins);
301+
const links = (markdown: string) => {
302+
const urls: string[] = [];
303+
const visit = (node: Root | RootContent) => {
304+
if (node.type === "link") urls.push(node.url);
305+
if ("children" in node) node.children.forEach(visit);
306+
};
307+
visit(processor.runSync(processor.parse(markdown), markdown) as Root);
308+
return urls;
309+
};
310+
expect(links(`Saved to ${path}.`)).toEqual([path]);
311+
expect(links(`See (${path}:12).`)).toEqual([`${path}:12`]);
312+
expect(links(`**${path}**`)).toEqual([path]);
313+
expect(links(`Saved to ${path} and /tmp/other.txt.`)).toEqual([path, "/tmp/other.txt"]);
314+
expect(links("/tmp/claude-1000/... and /tmp/claude-1000/....")).toEqual([]);
315+
expect(links("see /tmp/claude-1000/..., ok")).toEqual([]);
316+
expect(links("(see /tmp/claude-1000/...).")).toEqual([]);
317+
expect(links(`/chat/settings and https://example.com${path}`)).toEqual([
318+
`https://example.com${path}`,
319+
]);
320+
expect(links(`[notes](${path}) and \`${path}\``)).toEqual([path]);
321+
expect(links(`\`\`\`\n${path}\n\`\`\``)).toEqual([]);
322+
});

‎packages/shared/src/markdownPipeline.ts‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,11 @@ import {
1414
CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES,
1515
remarkCodexDirectives,
1616
} from "./codexMarkdownDirectives.ts";
17-
import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts";
17+
import {
18+
absoluteFilePathMatches,
19+
isWindowsDrivePathHref,
20+
normalizeMarkdownLinkDestination,
21+
} from "./markdownLinks.ts";
1822
import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
1923

2024
type MarkdownImageHastNode = {
@@ -205,6 +209,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
205209
export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
206210
remarkGfm,
207211
remarkKeepAutolinkSuffixes,
212+
remarkLinkAbsoluteFilePaths,
208213
remarkKeepWindowsPaths,
209214
remarkGithubAlerts,
210215
remarkNormalizeListItemIndentation,
@@ -217,6 +222,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
217222
export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
218223
remarkGfm,
219224
remarkKeepAutolinkSuffixes,
225+
remarkLinkAbsoluteFilePaths,
220226
remarkKeepWindowsPaths,
221227
remarkGithubAlerts,
222228
remarkNormalizeListItemIndentation,
@@ -416,6 +422,32 @@ function remarkKeepAutolinkSuffixes(): Transformer<Root> {
416422
};
417423
}
418424

425+
function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
426+
return (tree) => {
427+
const visit = (node: Root | RootContent) => {
428+
if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
429+
node.children = node.children.flatMap((child): typeof node.children => {
430+
if (child.type !== "text") {
431+
visit(child);
432+
return [child];
433+
}
434+
const parts: PhrasingContent[] = [];
435+
let offset = 0;
436+
for (const { index, path } of absoluteFilePathMatches(child.value)) {
437+
if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
438+
parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
439+
offset = index + path.length;
440+
}
441+
if (offset === 0) return [child];
442+
if (offset < child.value.length)
443+
parts.push({ type: "text", value: child.value.slice(offset) });
444+
return parts;
445+
});
446+
};
447+
visit(tree);
448+
};
449+
}
450+
419451
function remarkPreserveCodeMeta() {
420452
return (tree: MarkdownAstNode) => {
421453
const visit = (node: MarkdownAstNode) => {

0 commit comments

Comments
 (0)