Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex b96a27717d fix(vcs): extend worktree cleanup deadline (#3593)
Allow filesystem-bound worktree removal enough time for large dependency trees while retaining a bounded five-minute deadline.

Co-authored-by: codex <[email protected]>
2026-07-20 18:49:55 +02:00
5 changed files with 181 additions and 141 deletions

No files matched your search

+103 -1
View File
@@ -1,5 +1,6 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, describe } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -8,11 +9,16 @@ import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../config.ts";
import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";
import {
makeGitVcsDriverCore,
splitNullSeparatedGitStdoutPaths,
WORKTREE_REMOVE_TIMEOUT_MS,
} from "./GitVcsDriverCore.ts";
import * as GitVcsDriver from "./GitVcsDriver.ts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
@@ -38,6 +44,55 @@ const makeNonRepositoryHandle = () =>
getOutputFd: () => Stream.empty,
});
const makeWorktreeRemovalLayer = (input: {
readonly exitCode: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly commands: Array<ReadonlyArray<string>>;
readonly timeoutMs?: number;
}) => {
const spawner = ChildProcessSpawner.make((command) =>
Effect.sync(() => {
if (!ChildProcess.isStandardCommand(command)) {
return assert.fail("expected a standard Git command");
}
input.commands.push(command.args);
let running = true;
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: input.exitCode.pipe(
Effect.tap(() =>
Effect.sync(() => {
running = false;
}),
),
),
isRunning: Effect.sync(() => running),
kill: () =>
Effect.sync(() => {
running = false;
}),
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}),
);
const nodeServicesLayer = Layer.merge(
NodeServices.layer,
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return Layer.effect(
GitVcsDriver.GitVcsDriver,
makeGitVcsDriverCore(
input.timeoutMs === undefined ? {} : { worktreeRemoveTimeoutMs: input.timeoutMs },
),
).pipe(Layer.provide(ServerConfigLayer), Layer.provideMerge(nodeServicesLayer));
};
const makeTmpDir = (
prefix = "git-vcs-driver-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> =>
@@ -641,6 +696,53 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
});
describe("worktree operations", () => {
it.effect("uses the extended deadline while allowing a slow worktree removal", () => {
const commands: Array<ReadonlyArray<string>> = [];
const layer = makeWorktreeRemovalLayer({
commands,
exitCode: Effect.sleep(Duration.millis(50)).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
timeoutMs: 100,
});
return TestClock.withLive(
Effect.gen(function* () {
assert.equal(WORKTREE_REMOVE_TIMEOUT_MS, 300_000);
const driver = yield* GitVcsDriver.GitVcsDriver;
yield* driver.removeWorktree({ cwd: "/repo", path: "/repo-worktrees/feature" });
assert.deepStrictEqual(commands, [["worktree", "remove", "/repo-worktrees/feature"]]);
}).pipe(Effect.provide(layer)),
);
});
it.effect("still fails a worktree removal that exceeds its cleanup deadline", () => {
const commands: Array<ReadonlyArray<string>> = [];
const layer = makeWorktreeRemovalLayer({
commands,
exitCode: Effect.never,
timeoutMs: 25,
});
return TestClock.withLive(
Effect.gen(function* () {
const driver = yield* GitVcsDriver.GitVcsDriver;
const error = yield* driver
.removeWorktree({ cwd: "/repo", path: "/repo-worktrees/stuck" })
.pipe(Effect.flip);
assert.deepInclude(error, {
_tag: "GitCommandError",
operation: "GitVcsDriver.removeWorktree",
detail: "Git command timed out.",
cwd: "/repo",
});
assert.deepStrictEqual(commands, [["worktree", "remove", "/repo-worktrees/stuck"]]);
}).pipe(Effect.provide(layer)),
);
});
it.effect("creates and removes a worktree for a new refName", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+12 -2
View File
@@ -38,6 +38,7 @@ import {
import { ServerConfig } from "../config.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
export const WORKTREE_REMOVE_TIMEOUT_MS = Duration.toMillis(Duration.minutes(5));
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
@@ -642,7 +643,13 @@ const collectOutput = Effect.fnUntraced(function* (
};
});
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* () {
export interface GitVcsDriverCoreOptions {
readonly worktreeRemoveTimeoutMs?: number;
}
export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* (
options: GitVcsDriverCoreOptions = {},
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -2395,7 +2402,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
}
args.push(input.path);
yield* executeGit("GitVcsDriver.removeWorktree", input.cwd, args, {
timeoutMs: 15_000,
// Removing untracked dependency trees is filesystem-bound and can take
// minutes on Windows. Keep the operation supervised, but give it a
// cleanup-specific ceiling instead of the short interactive deadline.
timeoutMs: options.worktreeRemoveTimeoutMs ?? WORKTREE_REMOVE_TIMEOUT_MS,
fallbackErrorDetail: "git worktree remove failed",
});
});
+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 {