Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(chat): open explicit directory links in the file manager

SeanLiu326ef6e07fbf4da
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 35627a0e4..823316577 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -1078,7 +1078,7 @@ handleWithEvent(
handle(
IPC.invoke.fsResolveRef,
async (
- input: { ref?: string; sessionId?: string } = {},
+ input: { ref?: string; sessionId?: string; allowDirectory?: boolean } = {},
): Promise<FsChatRefResolveResult> => {
const rawRef = String(input.ref ?? "").trim();
if (!rawRef) return { match: null };
@@ -1114,10 +1114,16 @@ handleWithEvent(
};
if (await isChatRefOutsideRoots(ref, roots)) {
// An exact absolute path outside the managed roots opens when it names
- // an existing regular file (ADR 0339).
+ // an existing regular file (ADR 0339). Directories outside the roots
+ // stay unreachable: the remote transport has no allowDirectory flag
+ // either, so local and remote keep the same file-only contract there.
return resolveExternalChatRef(ref);
}
- return { match: await resolveChatFileRef(ref, roots) };
+ return {
+ match: await resolveChatFileRef(ref, roots, {
+ allowDirectory: input.allowDirectory === true,
+ }),
+ };
},
);
diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.ts
index 9af9e25a7..97a7f781a 100644
--- a/apps/desktop/src/hooks/use-preview-target.ts
+++ b/apps/desktop/src/hooks/use-preview-target.ts
@@ -38,6 +38,10 @@ export function useOpenPreviewTarget() {
return openFileRef(target.path, undefined, undefined, {
line: target.line,
column: target.column,
+ // A tool names its paths deliberately, the way a Markdown link does,
+ // so a directory argument opens in the file manager instead of
+ // reporting a missing file (issue #2113).
+ allowDirectory: true,
});
}
if (target.kind === "session") {
@@ -86,6 +90,8 @@ export type ResolvedChatFileRef = {
primary: boolean;
/** Session-owned generated artifacts, rather than imported attachments. */
scratch: boolean;
+ /** Present when the reference names a directory, not a regular file. */
+ target?: "file" | "directory";
};
export type ChatFileOpenDestination =
@@ -97,6 +103,8 @@ export type ChatFileOpenOptions = {
line?: number;
column?: number;
destination?: ChatFileOpenDestination;
+ /** Let an exact path resolve to a directory; the open flow browses it. */
+ allowDirectory?: boolean;
};
/**
@@ -170,6 +178,7 @@ function useResolveChatFileRef() {
async (
path: string,
baseDir?: string,
+ options?: { allowDirectory?: boolean },
): Promise<ResolvedChatFileRef | null> => {
const state = useAppStore.getState();
const ownerId = paneSessionId || state.activeSessionId;
@@ -185,7 +194,7 @@ function useResolveChatFileRef() {
: null;
let result;
try {
- result = await api.fsResolveRef(anchored ?? raw, ownerId);
+ result = await api.fsResolveRef(anchored ?? raw, ownerId, options);
} catch {
showToast(t("chat.fileRefLookupFailed"), { variant: "error" });
return null;
@@ -210,6 +219,7 @@ function useResolveChatFileRef() {
inProject: false,
primary: false,
scratch: match.sessionScratch === true,
+ ...(match.target ? { target: match.target } : {}),
};
}
// A project group can hold several folders, and a relative path always
@@ -223,6 +233,7 @@ function useResolveChatFileRef() {
inProject: true,
primary,
scratch: false,
+ ...(match.target ? { target: match.target } : {}),
};
},
[paneSessionId, sessionId, showToast, t, workspacePath],
@@ -263,7 +274,7 @@ export function useOpenChatFileRef() {
const column = options?.column;
const destination = options?.destination;
void (async () => {
- const resolved = await resolveRef(path, baseDir);
+ const resolved = await resolveRef(path, baseDir, options);
if (!resolved) return;
const current = useAppStore.getState();
if (
@@ -272,6 +283,33 @@ export function useOpenChatFileRef() {
) {
return;
}
+ if (resolved.target === "directory" && !destination) {
+ // A directory cannot open in the file view: browse it in the file
+ // manager instead (issue #2113). An explicit destination keeps its
+ // own contract below ("file-manager" already browses); the resolver
+ // only reports directories when the reference itself was explicit.
+ if (current.workspace?.remote) {
+ showToast(t("chat.fileManagerOpenFailed"), { variant: "error" });
+ return;
+ }
+ if (await ensureFileManagerView(workspacePath)) {
+ const latest = useAppStore.getState();
+ if (
+ (latest.workspace?.path ?? null) !== workspacePath ||
+ latest.activeSessionId !== sessionId
+ ) {
+ return;
+ }
+ openTab(
+ fileManagerPluginTab(
+ resolved.inProject ? resolved.path : resolved.absolutePath,
+ ),
+ );
+ return;
+ }
+ showToast(t("chat.fileManagerUnavailable"), { variant: "error" });
+ return;
+ }
if (destination === "file-manager") {
if (current.workspace?.remote) {
showToast(t("chat.fileManagerOpenFailed"), { variant: "error" });
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index b641325f9..a7c0459f5 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1743,12 +1743,19 @@ export const api = {
/**
* Complete a file reference from chat text to a real file (D320 follow-up).
* The main process owns the root order — project, session scratch,
- * attachments — because only it can see the scratch store.
+ * attachments — because only it can see the scratch store. `allowDirectory`
+ * lets an exact reference name a real directory (issue #2113); shorthand
+ * resolution keeps answering files only.
*/
- fsResolveRef: (ref: string, sessionId?: string) =>
+ fsResolveRef: (
+ ref: string,
+ sessionId?: string,
+ options?: { allowDirectory?: boolean },
+ ) =>
invoke<FsChatRefResolveResult>(IPC.invoke.fsResolveRef, {
ref,
...(sessionId ? { sessionId } : {}),
+ ...(options?.allowDirectory ? { allowDirectory: true } : {}),
}),
composerCommands: () =>
invoke<{ commands: ComposerCommand[] }>(IPC.invoke.composerCommands),
diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.ts
index 59fc399c5..34d837c8d 100644
--- a/apps/desktop/src/lib/chat-links.ts
+++ b/apps/desktop/src/lib/chat-links.ts
@@ -124,7 +124,16 @@ function normalizeMarkdownFilePath(url: string): string {
const decoded = safeDecodeUri(url);
if (parseFileRef(decoded) && parseFileRefPosition(decoded)) return encodeURIComponent(decoded);
if (!/^[A-Za-z]:[\\/]/.test(decoded)) return url;
- if (!parseFileRef(decoded)) return url;
+ if (!parseFileRef(decoded)) {
+ // A link destination is an explicit reference (the same rule
+ // markdownLinkFileTarget applies): keep a drive-anchored path even when it
+ // carries no file extension — a directory, a Makefile — or the sanitizer
+ // drops the href as an unknown `c:` scheme and the link dies before the
+ // click handler can resolve it (issue #2113).
+ const path = stripLineRef(decoded);
+ if (!path || /[\n\0]/.test(path) || /[\\/]$/.test(path)) return url;
+ return encodeWindowsPathForHref(decoded);
+ }
return encodeWindowsPathForHref(decoded);
}
@@ -287,15 +296,21 @@ export function handleMarkdownFileLinkClick(
root: string | null | undefined,
baseDir: string | undefined,
openFileRef: (path: string, baseDir?: string, mimeType?: string,
- position?: { line?: number; column?: number }) => void,
+ options?: { line?: number; column?: number; allowDirectory?: boolean }) => void,
): boolean {
const target = markdownLinkFileTarget(href, root, baseDir);
if (!target) return false;
event.preventDefault();
+ // The link names its target deliberately, so an extension-less directory
+ // destination opens in the file manager instead of missing (issue #2113).
if (target.line !== undefined) {
- openFileRef(target.path, baseDir, undefined, { line: target.line, column: target.column });
+ openFileRef(target.path, baseDir, undefined, {
+ line: target.line,
+ column: target.column,
+ allowDirectory: true,
+ });
} else {
- openFileRef(target.path, baseDir);
+ openFileRef(target.path, baseDir, undefined, { allowDirectory: true });
}
return true;
}
diff --git a/apps/desktop/test/chat-file-open-with-menu.test.mjs b/apps/desktop/test/chat-file-open-with-menu.test.mjs
index d0740136d..6b1078c0d 100644
--- a/apps/desktop/test/chat-file-open-with-menu.test.mjs
+++ b/apps/desktop/test/chat-file-open-with-menu.test.mjs
@@ -109,6 +109,7 @@ const previewTarget = loadModule("../src/hooks/use-preview-target.ts", {
"../lib/api": {
api: {
listPluginViews: async () => state.pluginViews,
+ listPlugins: async () => ({ plugins: [] }),
fsOpen: async (path, mimeType, sessionId) =>
calls.defaultBrowsers.push([path, mimeType, sessionId]),
fsResolveRef: async (ref) => {
@@ -442,3 +443,58 @@ test("remote workspace references retain copy actions but never offer local open
assert.deepEqual(items.map(item => item.id), ["copy-full-path", "copy-relative-path"]);
state.sessions = before;
});
+
+test("a directory reference browses the file manager instead of the file view (issue #2113)", async () => {
+ reset({
+ root: "workspace",
+ relativePath: "examples",
+ absolutePath: "C:/project/examples",
+ matchedBy: "exact-relative",
+ target: "directory",
+ projectRoot: { primary: true },
+ });
+ await openWithDestination("examples", undefined);
+ assert.deepEqual(calls.tabs, [{
+ id: "plugin:pi.file-manager/manager",
+ kind: "plugin",
+ resource: "pi.file-manager/manager",
+ location: "examples",
+ }]);
+ assert.deepEqual(calls.files, []);
+ assert.deepEqual(calls.toasts, []);
+
+ // A directory outside the project's primary folder travels by its absolute
+ // path, exactly like a file from a sibling folder does.
+ reset({
+ root: "scratch",
+ relativePath: "run",
+ absolutePath: "C:/data/scratch/session-1/run",
+ matchedBy: "exact-relative",
+ target: "directory",
+ sessionScratch: true,
+ });
+ await openWithDestination("run", undefined);
+ assert.deepEqual(calls.tabs.map((tab) => tab.location), ["C:/data/scratch/session-1/run"]);
+ assert.deepEqual(calls.files, []);
+});
+
+test("a directory reference without a loadable file manager reports and never opens the file view", async () => {
+ const viewsBefore = state.pluginViews;
+ state.pluginViews = [];
+ try {
+ reset({
+ root: "workspace",
+ relativePath: "examples",
+ absolutePath: "C:/project/examples",
+ matchedBy: "exact-relative",
+ target: "directory",
+ projectRoot: { primary: true },
+ });
+ await openWithDestination("examples", undefined);
+ assert.deepEqual(calls.tabs, []);
+ assert.deepEqual(calls.files, []);
+ assert.deepEqual(calls.toasts.map(([message]) => message), ["chat.fileManagerUnavailable:"]);
+ } finally {
+ state.pluginViews = viewsBefore;
+ }
+});
diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjs
index 2f5b0299b..80d80148f 100644
--- a/apps/desktop/test/chat-links.test.mjs
+++ b/apps/desktop/test/chat-links.test.mjs
@@ -46,7 +46,9 @@ function assertMarkdownLinkClick(markup, expectedPath) {
);
assert.equal(handled, true);
assert.equal(prevented, true);
- assert.deepEqual(calls, [[expectedPath, undefined]]);
+ // An explicit link destination may name a directory (issue #2113): the
+ // opener is always told the reference is deliberate.
+ assert.deepEqual(calls, [[expectedPath, undefined, undefined, { allowDirectory: true }]]);
}
test("Windows Markdown file links survive parsing and sanitization without changing their paths", () => {
@@ -97,6 +99,36 @@ test("Windows Markdown file links survive parsing and sanitization without chang
assertMarkdownLinkClick(encodedSlashMarkup, "D:/person/dir name/报告.js");
});
+test("explicit Markdown destinations keep their href without a file extension (issue #2113)", () => {
+ // A link destination is a deliberate reference: a drive-anchored directory
+ // (or extension-less file) keeps its href instead of being sanitized away
+ // as an unknown `c:` scheme, and the click routes through the file opener.
+ for (const destination of [String.raw`C:\link-demo\输出目录`, "C:/link-demo/输出目录"]) {
+ const markup = renderSanitizedMarkdown(`[目录](<${destination}>)`);
+ assertMarkdownLinkClick(markup, destination);
+ }
+
+ const plainMarkup = renderSanitizedMarkdown(String.raw`[目录](C:\link-demo\输出目录)`);
+ assertMarkdownLinkClick(plainMarkup, String.raw`C:\link-demo\输出目录`);
+
+ assertMarkdownLinkClick(renderSanitizedMarkdown("[build](<C:/repo/Makefile>)"), "C:/repo/Makefile");
+
+ // A relative directory destination keeps its href and routes through the
+ // opener against the workspace root.
+ const relMarkup = renderSanitizedMarkdown("[相对目录](examples/)");
+ const relHref = relMarkup.match(/<a href="([^"]+)"/)?.[1];
+ assert.ok(relHref, relMarkup);
+ const calls = [];
+ assert.equal(handleMarkdownFileLinkClick({ preventDefault() {} }, relHref, "/Users/dev/project", undefined,
+ (...args) => calls.push(args)), true);
+ assert.deepEqual(calls, [["examples", undefined, undefined, { allowDirectory: true }]]);
+
+ // A trailing separator keeps today's inert rendering: the click path's own
+ // acceptance still rejects it, so normalization stays in parity.
+ const trailingMarkup = renderSanitizedMarkdown(String.raw`[目录](<C:\link-demo\输出目录\>)`);
+ assert.ok(!/<a href=/i.test(trailingMarkup), trailingMarkup);
+});
+
test("positioned HTML references preserve source navigation through Markdown sanitization", () => {
for (const source of [
"Source: animation.html:12:3",
@@ -111,7 +143,7 @@ test("positioned HTML references preserve source navigation through Markdown san
handleMarkdownFileLinkClick({ preventDefault() {} }, href, "D:/person", undefined,
(...args) => calls.push(args));
assert.deepEqual(calls, [[source.includes("D:/person") ? "D:/person/animation.html" : "animation.html",
- undefined, undefined, { line: 12, column: 3 }]], source);
+ undefined, undefined, { line: 12, column: 3, allowDirectory: true }]], source);
}
});
@@ -960,13 +992,15 @@ test("session links segment as their own target", () => {
test("an absolute Markdown link to an extensionless file still reaches the file opener", () => {
// The link destination is explicit, so the extension heuristic that keeps
- // prose from turning into chips does not apply. The main process decides
- // whether the file exists and may open (ADR 0339).
+ // prose from turning into chips does not apply — for files and, since
+ // #2113, for directories too: the opener is told the reference is
+ // deliberate so an extension-less directory can resolve. The main process
+ // decides whether the path exists and may open (ADR 0339).
for (const [source, root, expected] of [
- ["[config](</Users/me/.ssh/config>)", null, ["/Users/me/.ssh/config", undefined]],
- ["[Makefile](</tmp/build dir/Makefile>)", "/Users/me/project", ["/tmp/build dir/Makefile", undefined]],
- ["[LICENSE](<D:/vendor/LICENSE>)", "D:/person", ["D:/vendor/LICENSE", undefined]],
- ["[notes](</tmp/notes:4>)", null, ["/tmp/notes", undefined, undefined, { line: 4, column: undefined }]],
+ ["[config](</Users/me/.ssh/config>)", null, ["/Users/me/.ssh/config", undefined, undefined, { allowDirectory: true }]],
+ ["[Makefile](</tmp/build dir/Makefile>)", "/Users/me/project", ["/tmp/build dir/Makefile", undefined, undefined, { allowDirectory: true }]],
+ ["[LICENSE](<D:/vendor/LICENSE>)", "D:/person", ["D:/vendor/LICENSE", undefined, undefined, { allowDirectory: true }]],
+ ["[notes](</tmp/notes:4>)", null, ["/tmp/notes", undefined, undefined, { line: 4, column: undefined, allowDirectory: true }]],
]) {
const markup = renderSanitizedMarkdown(source);
const href = markup.match(/<a href="([^"]+)"/)?.[1];
diff --git a/apps/desktop/test/chat-ref-external.test.mjs b/apps/desktop/test/chat-ref-external.test.mjs
index 3f692adaa..0c9364779 100644
--- a/apps/desktop/test/chat-ref-external.test.mjs
+++ b/apps/desktop/test/chat-ref-external.test.mjs
@@ -65,6 +65,18 @@ test("a missing external file is a miss, not an access limit", async () => {
assert.deepEqual(await resolveExternalChatRef(join(outside)), { match: null });
});
+test("an external directory stays outside the ADR 0339 file contract (issue #2113)", async () => {
+ // Directories inside the managed roots resolve with allowDirectory; outside
+ // them the external rule keeps naming that exact regular file or nothing,
+ // so the managed-root containment is not widened to directory browsing.
+ const workspace = tempTree("ws-dir-ext", ["src/a.ts"]);
+ const outside = tempTree("outside-dir", ["docs/manual.txt"]);
+ const roots = projectRoots(workspace);
+ assert.equal(await isChatRefOutsideRoots(outside, roots), true);
+ assert.equal(await resolveChatFileRef(outside, roots, { allowDirectory: true }), null);
+ assert.equal((await resolveExternalChatRef(outside)).match, null);
+});
+
test("a shorthand never resolves outside the managed roots", async () => {
const workspace = tempTree("ws-short", ["src/a.ts"]);
const roots = projectRoots(workspace);
diff --git a/apps/desktop/test/chat-ref-resolve.test.mjs b/apps/desktop/test/chat-ref-resolve.test.mjs
index 33044757a..3d71456fd 100644
--- a/apps/desktop/test/chat-ref-resolve.test.mjs
+++ b/apps/desktop/test/chat-ref-resolve.test.mjs
@@ -28,7 +28,8 @@ function roots(options) {
return { ...rest, project: workspace ? [folder(workspace)] : [] };
}
-const resolve = (ref, options) => resolveChatFileRef(ref, roots(options));
+const resolve = (ref, options, resolveOptions) =>
+ resolveChatFileRef(ref, roots(options), resolveOptions);
/**
* Partial-path completion for chat file references.
@@ -276,6 +277,62 @@ test("a directory with a matching name never matches", async () => {
assert.equal(await resolve("openimage.js", { workspace }), null);
});
+test("an explicit directory reference resolves only with allowDirectory (issue #2113)", async () => {
+ const workspace = tempTree("ws-dir", ["examples/child.txt"]);
+
+ // Shorthand and default resolution keep answering nothing for a directory.
+ assert.equal(await resolve("examples", { workspace }), null);
+ assert.equal(await resolve("examples", { workspace }, { allowDirectory: false }), null);
+
+ // The exact reference names a real directory: it resolves as one.
+ const match = await resolve("examples", { workspace }, { allowDirectory: true });
+ assert.equal(match?.matchedBy, "exact-relative");
+ assert.equal(match?.target, "directory");
+ assert.equal(match?.relativePath, "examples");
+ assert.equal(match?.absolutePath, join(workspace, "examples"));
+
+ const absolute = join(workspace, "examples");
+ const absoluteMatch = await resolve(absolute, { workspace }, { allowDirectory: true });
+ assert.equal(absoluteMatch?.matchedBy, "exact-absolute");
+ assert.equal(absoluteMatch?.target, "directory");
+ assert.equal(absoluteMatch?.absolutePath, absolute);
+
+ // The existing pin keeps its contract on both sides: without the flag a
+ // directory named like the ref answers nothing; with it the exact reference
+ // names the directory honestly.
+ const named = tempTree("ws-named", ["openimage.js/placeholder.txt"]);
+ assert.equal(await resolve("openimage.js", { workspace: named }), null);
+ const namedMatch = await resolve("openimage.js", { workspace: named }, { allowDirectory: true });
+ assert.equal(namedMatch?.target, "directory");
+ assert.equal(namedMatch?.matchedBy, "exact-relative");
+
+ // A shorthand that suffix-matches a file still resolves to that file, never
+ // to a directory: directories cannot hijack fuzzy completion.
+ const fileMatch = await resolve("child.txt", { workspace }, { allowDirectory: true });
+ assert.equal(fileMatch?.matchedBy, "basename");
+ assert.equal(fileMatch?.target, undefined);
+});
+
+test("a dangling or escaping directory link never resolves, flag or not", async () => {
+ const workspace = tempTree("ws-dangling-dir", ["other/real.txt"]);
+ symlinkSync(join(workspace, "missing"), join(workspace, "linked"), process.platform === "win32" ? "junction" : "dir");
+ assert.equal(await resolve("linked", { workspace }, { allowDirectory: true }), null);
+
+ // A directory link that points outside the roots stays unreachable.
+ const outsideDir = tempTree("outside-dir", ["secret.txt"]);
+ symlinkSync(outsideDir, join(workspace, "escape"), process.platform === "win32" ? "junction" : "dir");
+ assert.equal(await resolve(join(workspace, "escape"), { workspace }, { allowDirectory: true }), null);
+});
+
+test("the scratch store answers an explicit directory reference when the project has nothing", async () => {
+ const workspace = tempTree("ws-files", ["src/index.ts"]);
+ const scratch = tempTree("scratch-dirs", ["run/artifact.txt"]);
+ const match = await resolve("run", { workspace, scratch }, { allowDirectory: true });
+ assert.equal(match?.root, "scratch");
+ assert.equal(match?.target, "directory");
+ assert.equal(match?.relativePath, "run");
+});
+
test("a content-addressed attachment blob resolves against the attachment store", async () => {
const digest = "a".repeat(64);
const attachments = tempTree("attachments", [digest]);
diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjs
index f49837574..74d18c084 100644
--- a/apps/desktop/test/transcript-file-chips.test.mjs
+++ b/apps/desktop/test/transcript-file-chips.test.mjs
@@ -63,7 +63,9 @@ test("a file chip is routed by where the reference resolved, never optimisticall
// Plain project files prefer the bundled file view. A path:line reference
// uses the host file tab because the bundled view has no line-navigation API.
assert.match(hook, /FILE_MANAGER_PLUGIN_TAB/);
- const resolvedRefIndex = hook.indexOf("const resolved = await resolveRef(path, baseDir)");
+ // The resolver may now be handed the caller's options (issue #2113 adds
+ // allowDirectory), but resolution still precedes any file-manager load.
+ const resolvedRefIndex = hook.indexOf("const resolved = await resolveRef(path, baseDir, options)");
const livePluginViewIndex = hook.indexOf("ensureFileManagerView(workspacePath)", resolvedRefIndex);
assert.ok(
livePluginViewIndex > resolvedRefIndex,
diff --git a/packages/host-runtime/src/chat-ref-resolve.ts b/packages/host-runtime/src/chat-ref-resolve.ts
index 03fd1854d..fb6aa4d1e 100644
--- a/packages/host-runtime/src/chat-ref-resolve.ts
+++ b/packages/host-runtime/src/chat-ref-resolve.ts
@@ -30,7 +30,9 @@ import { getWorkspaceFileIndex } from "./fs-index.js";
* searched to exhaustion before the scratch store is considered;
* 4. inside one root an exact path wins; a shorthand resolves only when the
* complete supplied suffix matches one safe file. Ambiguous or shortened
- * suffixes remain unresolved.
+ * suffixes remain unresolved. An exact reference may additionally name a
+ * real directory when the caller passes `allowDirectory` (issue #2113);
+ * a shorthand never resolves to a directory.
*/
export type ChatRefRoots = {
@@ -189,6 +191,14 @@ async function isRegularFile(target: string): Promise<boolean> {
}
}
+async function isDirectory(target: string): Promise<boolean> {
+ try {
+ return (await stat(target)).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
/** Root-relative POSIX path, or null when `absolute` is outside `rootPath`. */
function relativeInside(rootPath: string, absolute: string): string | null {
const rel = relative(rootPath, absolute);
@@ -306,6 +316,21 @@ async function isContainedRegularFile(root: string, relativePath: string): Promi
return realPath !== null && isRegularFile(realPath);
}
+/**
+ * The same containment contract as `isContainedRegularFile` for an exact
+ * directory reference: the real path must stay inside the root, so a symlinked
+ * or dangling directory never matches (issue #2113).
+ */
+async function isContainedDirectory(root: string, relativePath: string): Promise<boolean> {
+ const realPath = await resolveRealPathWithinRoot(root, relativePath);
+ if (realPath === null) return false;
+ try {
+ return (await stat(realPath)).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
async function hasInvalidLinkAncestor(root: string, segments: readonly string[]): Promise<boolean> {
for (let length = 1; length <= segments.length; length += 1) {
const prefixSegments = segments.slice(0, length);
@@ -371,10 +396,24 @@ async function listRootFiles(
/**
* Resolve one chat file reference to the best existing file, or null when
* nothing matches. Never throws: an unreadable root is simply not a match.
+ * With `allowDirectory` an exact reference may name a real directory inside
+ * the roots instead; the match then carries `target: "directory"`.
*/
+export type ChatRefResolveOptions = {
+ /**
+ * Let an exact reference name a real directory (issue #2113). Explicit
+ * Markdown links carry this flag; shorthand and fuzzy completion never do,
+ * so a directory named like the file a shorthand asks for keeps answering
+ * nothing. The absolute branch still stays inside the managed roots — an
+ * exact absolute path outside them keeps the ADR 0339 file-only contract.
+ */
+ allowDirectory?: boolean;
+};
+
export async function resolveChatFileRef(
ref: string,
roots: ChatRefRoots,
+ options: ChatRefResolveOptions = {},
): Promise<FsChatRefMatch | null> {
const parsed = parseChatRef(ref);
if (!parsed) return null;
@@ -402,7 +441,13 @@ export async function resolveChatFileRef(
} catch {
return null;
}
- if (!(await isRegularFile(targetPath))) return null;
+ const regular = await isRegularFile(targetPath);
+ if (!regular) {
+ // An exact absolute directory inside a managed root resolves only when
+ // the caller asked for directories (issue #2113); realpath has already
+ // collapsed any link, so the root attribution below cannot escape.
+ if (!options.allowDirectory || !(await isDirectory(targetPath))) return null;
+ }
for (const root of canonicalRootList) {
const relativePath = root.realPath ? relativeInside(root.realPath, targetPath) : null;
if (!relativePath) continue;
@@ -411,6 +456,7 @@ export async function resolveChatFileRef(
relativePath,
absolutePath,
matchedBy: "exact-absolute",
+ ...(regular ? {} : { target: "directory" as const }),
...(root.sessionScratch ? { sessionScratch: true } : {}),
...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
};
@@ -459,6 +505,24 @@ export async function resolveChatFileRef(
...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
};
}
+ // An exact directory reference answers before the fuzzy walk, and only
+ // when the caller asked for directories (issue #2113). The containment
+ // check doubles as the dangling-link guard: a junction pointing outside
+ // the root (or at nothing) resolves to null, never to the link path.
+ if (
+ options.allowDirectory
+ && (await isContainedDirectory(root.path, parsed.segments.join("/")))
+ ) {
+ return {
+ root: root.kind,
+ relativePath: parsed.segments.join("/"),
+ absolutePath,
+ matchedBy: "exact-relative",
+ target: "directory",
+ ...(root.sessionScratch ? { sessionScratch: true } : {}),
+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
+ };
+ }
if (await hasInvalidLinkAncestor(root.path, parsed.segments)) return null;
const candidates = fuzzyCandidates(
await listRootFiles(root.kind, root.path),
diff --git a/packages/shared/src/types/filesystem.ts b/packages/shared/src/types/filesystem.ts
index b4c3867fc..b88cad335 100644
--- a/packages/shared/src/types/filesystem.ts
+++ b/packages/shared/src/types/filesystem.ts
@@ -124,6 +124,13 @@ export type FsChatRefMatch = {
/** Native absolute path of the matched regular file. */
absolutePath: string;
matchedBy: FsChatRefMatchKind;
+ /**
+ * What the match names. Absent means a regular file. `"directory"` is
+ * produced only for an exact reference resolved with `allowDirectory` —
+ * never by a shorthand or fuzzy match — and the chat open flow routes it to
+ * the file manager instead of the file view.
+ */
+ target?: "file" | "directory";
/**
* Which folder of the project answered, for `root: "workspace"`. The caller
* needs it to decide how to address the file: relative for the primary