From 3e4dc94d27f4838a5f0b8481a1664d6c23afdf9c Mon Sep 17 00:00:00 2001 From: Dotta Date: Mon, 8 Jun 2026 21:19:34 +0000 Subject: [PATCH] Support workspace folder file-browser links Co-Authored-By: Paperclip --- .../src/types/workspace-file-resource.ts | 5 +- .../src/validators/workspace-file-resource.ts | 12 +- server/src/__tests__/file-resources.test.ts | 78 +++++++++++- server/src/routes/file-resources.ts | 4 +- .../src/services/workspace-file-resources.ts | 117 ++++++++++++++++-- ui/src/api/file-resources.ts | 3 +- ui/src/components/FileViewerSheet.tsx | 1 + .../components/WorkspaceFileBrowser.test.tsx | 45 +++++++ ui/src/components/WorkspaceFileBrowser.tsx | 28 ++++- ui/src/components/WorkspaceFileLink.tsx | 41 +++--- .../WorkspaceFileMarkdownBody.test.tsx | 12 ++ ui/src/context/FileViewerContext.test.ts | 21 ++++ ui/src/context/FileViewerContext.tsx | 54 +++++++- ui/src/lib/queryKeys.ts | 1 + ui/src/lib/remark-workspace-file-refs.test.ts | 38 ++++++ ui/src/lib/remark-workspace-file-refs.ts | 3 + ui/src/lib/workspace-file-parser.test.ts | 26 +++- ui/src/lib/workspace-file-parser.ts | 34 +++-- 18 files changed, 476 insertions(+), 47 deletions(-) diff --git a/packages/shared/src/types/workspace-file-resource.ts b/packages/shared/src/types/workspace-file-resource.ts index 7ae4e49b034..dcbe144a470 100644 --- a/packages/shared/src/types/workspace-file-resource.ts +++ b/packages/shared/src/types/workspace-file-resource.ts @@ -2,7 +2,7 @@ export type WorkspaceFileWorkspaceKind = "execution_workspace" | "project_worksp export type WorkspaceFileSelector = "auto" | "execution" | "project"; export type WorkspaceFileListMode = "all" | "recent" | "changed"; export type WorkspaceFilePreviewKind = "text" | "image" | "video" | "pdf" | "unsupported"; -export type WorkspaceFileResourceKind = "file" | "remote_resource"; +export type WorkspaceFileResourceKind = "file" | "directory" | "remote_resource"; export type WorkspaceFileContentEncoding = "utf8" | "base64"; export interface WorkspaceFileRef { @@ -35,7 +35,7 @@ export interface ResolvedWorkspaceResource { capabilities: { preview: boolean; download: false; - listChildren: false; + listChildren: boolean; }; } @@ -84,6 +84,7 @@ export interface WorkspaceFileListResponse { query: { workspace: WorkspaceFileSelector; mode: WorkspaceFileListMode; + path?: string | null; q: string | null; limit: number; }; diff --git a/packages/shared/src/validators/workspace-file-resource.ts b/packages/shared/src/validators/workspace-file-resource.ts index 9bc1080953d..37de50b0ee2 100644 --- a/packages/shared/src/validators/workspace-file-resource.ts +++ b/packages/shared/src/validators/workspace-file-resource.ts @@ -10,7 +10,7 @@ export const workspaceFileWorkspaceKindSchema = z.enum(["execution_workspace", " export const workspaceFileSelectorSchema = z.enum(["auto", "execution", "project"]).default("auto"); export const workspaceFileListModeSchema = z.enum(["all", "recent", "changed"]).default("all"); export const workspaceFilePreviewKindSchema = z.enum(["text", "image", "video", "pdf", "unsupported"]); -export const workspaceFileResourceKindSchema = z.enum(["file", "remote_resource"]); +export const workspaceFileResourceKindSchema = z.enum(["file", "directory", "remote_resource"]); export const workspaceFileRefSchema = z.object({ kind: z.literal("workspace_file"), @@ -46,6 +46,14 @@ export const workspaceFileListQuerySchema = z.object({ projectId: z.string().uuid().optional(), workspaceId: z.string().uuid().optional(), workspace: workspaceFileSelectorSchema.optional(), + path: z + .string() + .min(1) + .refine((value) => !/[\x00-\x1f\x7f]/.test(value), { + message: "Workspace folder path contains an invalid character", + params: { code: "invalid_path" }, + }) + .optional(), mode: workspaceFileListModeSchema.optional(), q: z .string() @@ -82,7 +90,7 @@ export const resolvedWorkspaceResourceSchema = z.object({ capabilities: z.object({ preview: z.boolean(), download: z.literal(false), - listChildren: z.literal(false), + listChildren: z.boolean(), }), }); diff --git a/server/src/__tests__/file-resources.test.ts b/server/src/__tests__/file-resources.test.ts index 2823abf0574..072eccb1052 100644 --- a/server/src/__tests__/file-resources.test.ts +++ b/server/src/__tests__/file-resources.test.ts @@ -329,6 +329,63 @@ describeEmbeddedPostgres("workspace file resources", () => { expect(JSON.stringify(res.body)).not.toContain(root); }); + it("resolves and lists explicit same-company cross-project workspace folders", async () => { + const { root, projectRoot, targetProjectRoot, executionRoot } = await makeWorkspace(); + const graph = await seedGraph(db, { projectRoot, targetProjectRoot, executionRoot }); + const folderPath = "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/"; + await fs.mkdir(path.join(targetProjectRoot, folderPath), { recursive: true }); + await fs.writeFile(path.join(targetProjectRoot, folderPath, "README.md"), "# Bundled skills\n", "utf8"); + await fs.writeFile(path.join(targetProjectRoot, folderPath, "notes.txt"), "notes\n", "utf8"); + await fs.writeFile(path.join(targetProjectRoot, "outside.txt"), "not in focused folder\n", "utf8"); + + const app = createApp(db, { + type: "board", + userId: "board-user", + companyIds: [graph.companyId], + source: "session", + isInstanceAdmin: false, + }); + + const resolved = await request(app) + .get(`/api/issues/${graph.issueId}/file-resources/resolve`) + .query({ + projectId: graph.targetProjectId, + workspaceId: graph.targetProjectWorkspaceId, + path: folderPath, + }); + + expect(resolved.status).toBe(200); + expect(resolved.body).toMatchObject({ + kind: "directory", + workspaceKind: "project_workspace", + workspaceId: graph.targetProjectWorkspaceId, + projectId: graph.targetProjectId, + projectName: "Target project", + displayPath: `Target project / ${folderPath}`, + capabilities: { preview: false, download: false, listChildren: true }, + }); + expect(JSON.stringify(resolved.body)).not.toContain(root); + + const listed = await request(app) + .get(`/api/issues/${graph.issueId}/file-resources/list`) + .query({ + projectId: graph.targetProjectId, + workspaceId: graph.targetProjectWorkspaceId, + path: folderPath, + mode: "all", + }); + + expect(listed.status).toBe(200); + expect(listed.body.state).toBe("available"); + expect(listed.body.query).toMatchObject({ path: folderPath.slice(0, -1), mode: "all" }); + expect(new Set(listed.body.items.map((item: { relativePath: string }) => item.relativePath))).toEqual(new Set([ + `${folderPath}README.md`, + `${folderPath}notes.txt`, + ])); + expect(JSON.stringify(listed.body)).not.toContain(root); + expect(JSON.stringify(listed.body)).not.toContain("outside.txt"); + }); + it("denies explicit cross-company project workspaces", async () => { const { projectRoot, targetProjectRoot, executionRoot } = await makeWorkspace(); const graph = await seedGraph(db, { projectRoot, targetProjectRoot, executionRoot }); @@ -399,6 +456,24 @@ describeEmbeddedPostgres("workspace file resources", () => { }); }); + it("blocks symlink directory escapes from explicit cross-project workspaces", async () => { + const { root, projectRoot, targetProjectRoot, executionRoot } = await makeWorkspace(); + const graph = await seedGraph(db, { projectRoot, targetProjectRoot, executionRoot }); + const outsideDir = path.join(root, "outside-dir"); + await fs.mkdir(outsideDir, { recursive: true }); + await fs.writeFile(path.join(outsideDir, "secret.txt"), "secret\n", "utf8"); + await fs.symlink(outsideDir, path.join(targetProjectRoot, "escape-dir")); + + await expect(workspaceFileResourceService(db).resolve(graph.issueId, { + projectId: graph.targetProjectId, + workspaceId: graph.targetProjectWorkspaceId, + path: "escape-dir/", + })).rejects.toMatchObject({ + status: 403, + details: { code: "outside_workspace" }, + }); + }); + it("resolves and reads video workspace files as base64 previews", async () => { const { projectRoot, executionRoot } = await makeWorkspace(); const graph = await seedGraph(db, { projectRoot, executionRoot }); @@ -596,7 +671,7 @@ describeEmbeddedPostgres("workspace file resources", () => { expect(otherControl.body?.details?.code).toBe("invalid_path"); }); - it("rejects traversal, encoded traversal, backslash traversal, and double-encoding without double-decoding", async () => { + it("rejects traversal, encoded traversal, home-relative paths, backslash traversal, and double-encoding without double-decoding", async () => { const { projectRoot, executionRoot } = await makeWorkspace(); const graph = await seedGraph(db, { projectRoot, executionRoot }); await fs.writeFile(path.join(projectRoot, "safe.txt"), "safe\n", "utf8"); @@ -611,6 +686,7 @@ describeEmbeddedPostgres("workspace file resources", () => { expect((await request(app).get(`/api/issues/${graph.issueId}/file-resources/content?workspace=project&path=..%2Fsecret.txt`)).status).toBe(403); expect((await request(app).get(`/api/issues/${graph.issueId}/file-resources/content?workspace=project&path=%2e%2e%2Fsecret.txt`)).status).toBe(403); + expect((await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: "~/secret.txt" })).status).toBe(422); expect((await request(app).get(`/api/issues/${graph.issueId}/file-resources/content`).query({ workspace: "project", path: "..\\secret.txt" })).status).toBe(422); const doubleEncoded = await request(app) .get(`/api/issues/${graph.issueId}/file-resources/content?workspace=project&path=%252e%252e%252Fsecret.txt`); diff --git a/server/src/routes/file-resources.ts b/server/src/routes/file-resources.ts index 59bddb1a9c5..342e63cc652 100644 --- a/server/src/routes/file-resources.ts +++ b/server/src/routes/file-resources.ts @@ -19,6 +19,7 @@ export type WorkspaceFileResourceService = { workspace?: "auto" | "execution" | "project" | null; projectId?: string | null; workspaceId?: string | null; + path?: string | null; mode?: "all" | "recent" | "changed" | null; q?: string | null; limit?: number | null; @@ -133,7 +134,7 @@ function readListQuery(query: unknown) { if (error instanceof ZodError) { const refinement = error.errors.find((issue) => { const code = (issue as { params?: { code?: string } }).params?.code; - return code === "invalid_query" || code === "invalid_target"; + return code === "invalid_query" || code === "invalid_target" || code === "invalid_path"; }); const code = (refinement as { params?: { code?: string } } | undefined)?.params?.code; if (refinement) throw unprocessable(refinement.message, { code: code ?? "invalid_query" }); @@ -145,6 +146,7 @@ function readListQuery(query: unknown) { workspace: parsed.workspace ?? "auto", projectId: parsed.projectId ?? null, workspaceId: parsed.workspaceId ?? null, + path: parsed.path ?? null, mode: parsed.mode ?? "all", q: parsed.q?.trim() || null, limit: parsed.limit, diff --git a/server/src/services/workspace-file-resources.ts b/server/src/services/workspace-file-resources.ts index a2c1590768a..d5c27c2f74e 100644 --- a/server/src/services/workspace-file-resources.ts +++ b/server/src/services/workspace-file-resources.ts @@ -120,10 +120,17 @@ type LocalResolvedFile = { realPath: string; }; +type LocalResolvedDirectory = { + resource: ResolvedWorkspaceResource; + realPath: string; + rootReal: string; +}; + type WorkspaceFileListQueryInput = { workspace?: WorkspaceFileSelector | null; projectId?: string | null; workspaceId?: string | null; + path?: string | null; mode?: WorkspaceFileListMode | null; q?: string | null; limit?: number | null; @@ -158,10 +165,12 @@ function normalizeWorkspaceRelativePath(input: string): NormalizedPath { if (trimmed.includes("\0")) throw unprocessable("Workspace file path contains an invalid character", { code: "invalid_path" }); if (/^file:\/\//i.test(trimmed)) throw unprocessable("File URLs are not supported", { code: "invalid_path" }); if (/^[a-zA-Z]:/.test(trimmed)) throw unprocessable("Windows drive paths are not supported", { code: "invalid_path" }); + if (trimmed.startsWith("~")) throw unprocessable("Home-relative paths are not supported", { code: "invalid_path" }); if (trimmed.includes("\\")) throw unprocessable("Workspace file paths must use forward slashes", { code: "invalid_path" }); if (path.posix.isAbsolute(trimmed)) throw unprocessable("Workspace file path must be relative", { code: "invalid_path" }); - const normalized = path.posix.normalize(trimmed); + const normalizedRaw = path.posix.normalize(trimmed); + const normalized = normalizedRaw.endsWith("/") ? normalizedRaw.replace(/\/+$/, "") : normalizedRaw; if (normalized === "." || normalized === ".." || normalized.startsWith("../")) { throw new HttpError(403, "Workspace file path is outside the workspace", { code: "outside_workspace" }); } @@ -331,6 +340,34 @@ function candidateFromProjectWorkspace( }; } +function directoryResource(input: { + candidate: WorkspaceCandidate; + relativePath: string; +}): ResolvedWorkspaceResource { + return { + kind: "directory", + provider: input.candidate.provider, + title: path.posix.basename(input.relativePath), + displayPath: input.candidate.projectName + ? `${input.candidate.projectName} / ${input.relativePath}/` + : `${input.relativePath}/`, + workspaceLabel: input.candidate.label, + workspaceKind: input.candidate.workspaceKind, + workspaceId: input.candidate.workspaceId, + projectId: input.candidate.projectId ?? null, + projectName: input.candidate.projectName ?? null, + contentType: null, + byteSize: null, + previewKind: "unsupported", + denialReason: null, + capabilities: { + preview: false, + download: false, + listChildren: true, + }, + }; +} + async function statLocalCandidate(candidate: WorkspaceCandidate, normalized: NormalizedPath): Promise { if (!candidate.rootPath) { throw unprocessable("Workspace is not locally readable", { code: "remote_workspace" }); @@ -399,6 +436,44 @@ async function statLocalCandidate(candidate: WorkspaceCandidate, normalized: Nor }; } +async function statLocalDirectory(candidate: WorkspaceCandidate, normalized: NormalizedPath): Promise { + if (!candidate.rootPath) { + throw unprocessable("Workspace is not locally readable", { code: "remote_workspace" }); + } + throwIfDenied(normalized.segments); + + let rootReal: string; + try { + rootReal = await fs.realpath(candidate.rootPath); + } catch { + throw unprocessable("Workspace is not available on this host", { code: "workspace_unavailable" }); + } + + const targetLexical = path.resolve(rootReal, ...normalized.segments); + let targetReal: string; + try { + targetReal = await fs.realpath(targetLexical); + } catch { + throw notFound("Workspace folder not found"); + } + + if (!isInsideRoot(rootReal, targetReal)) { + throw new HttpError(403, "Workspace folder path is outside the workspace", { code: "outside_workspace" }); + } + throwIfDenied(relativePathFromReal(rootReal, targetReal).split("/").filter(Boolean)); + + const stat = await fs.stat(targetReal); + if (!stat.isDirectory()) { + throw unprocessable("Workspace path is not a directory", { code: "not_directory" }); + } + + return { + realPath: targetReal, + rootReal, + resource: directoryResource({ candidate, relativePath: normalized.relativePath }), + }; +} + async function readStableFile(realPath: string, maxBytes: number) { const handle = await fs.open(realPath, "r"); try { @@ -419,6 +494,7 @@ async function readStableFile(realPath: string, maxBytes: number) { function unavailableFileList(input: { selector: WorkspaceFileSelector; mode: WorkspaceFileListMode; + path?: string | null; q: string | null; limit: number; candidate?: WorkspaceCandidate | null; @@ -441,6 +517,7 @@ function unavailableFileList(input: { query: { workspace: input.selector, mode: input.mode, + path: input.path ?? null, q: input.q, limit: input.limit, }, @@ -453,6 +530,7 @@ function unavailableFileList(input: { function availableFileList(input: { selector: WorkspaceFileSelector; mode: WorkspaceFileListMode; + path?: string | null; q: string | null; limit: number; candidate: WorkspaceCandidate; @@ -474,6 +552,7 @@ function availableFileList(input: { query: { workspace: input.selector, mode: input.mode, + path: input.path ?? null, q: input.q, limit: input.limit, }, @@ -521,12 +600,14 @@ async function listLocalFileCandidate(input: { async function enumerateWorkspaceFiles(input: { candidate: WorkspaceCandidate; rootReal: string; + startReal?: string; + startRelativePath?: string; mode: WorkspaceFileListMode; normalizedQuery: string | null; limit: number; }) { const dirs: Array<{ realPath: string; relativePath: string; depth: number }> = [ - { realPath: input.rootReal, relativePath: "", depth: 0 }, + { realPath: input.startReal ?? input.rootReal, relativePath: input.startRelativePath ?? "", depth: 0 }, ]; const items: WorkspaceFileListItem[] = []; let scannedCount = 0; @@ -762,6 +843,7 @@ export function workspaceFileResourceService(db: Db) { const issue = opts.issue ?? await getIssue(issueId); const selector = input.workspace ?? "auto"; const explicitTarget = Boolean(input.projectId || input.workspaceId); + const isDirectoryRequest = input.path.trim().endsWith("/"); const normalized = normalizeWorkspaceRelativePath(input.path); const candidates = await listCandidates(issue, selector, input); if (candidates.length === 0) { @@ -775,7 +857,9 @@ export function workspaceFileResourceService(db: Db) { continue; } try { - return (await statLocalCandidate(candidate, normalized)).resource; + return isDirectoryRequest + ? (await statLocalDirectory(candidate, normalized)).resource + : (await statLocalCandidate(candidate, normalized)).resource; } catch (error) { if ( !explicitTarget && @@ -803,7 +887,8 @@ export function workspaceFileResourceService(db: Db) { const issue = opts.issue ?? await getIssue(issueId); const selector = input.workspace ?? "auto"; const explicitTarget = Boolean(input.projectId || input.workspaceId); - const mode = input.mode ?? "all"; + const normalizedPath = input.path?.trim() ? normalizeWorkspaceRelativePath(input.path) : null; + const mode = normalizedPath ? "all" : input.mode ?? "all"; const limit = Math.min( WORKSPACE_FILE_LIST_MAX_LIMIT, Math.max(1, Math.floor(input.limit ?? WORKSPACE_FILE_LIST_DEFAULT_LIMIT)), @@ -812,7 +897,7 @@ export function workspaceFileResourceService(db: Db) { const normalizedQuery = q?.toLowerCase() ?? null; const candidates = await listCandidates(issue, selector, input); if (candidates.length === 0) { - return unavailableFileList({ selector, mode, q, limit, reason: "no_workspace" }); + return unavailableFileList({ selector, mode, path: normalizedPath?.relativePath ?? null, q, limit, reason: "no_workspace" }); } let firstUnavailable: { candidate: WorkspaceCandidate; reason: string } | null = null; @@ -820,18 +905,27 @@ export function workspaceFileResourceService(db: Db) { if (candidate.remote) { firstUnavailable ??= { candidate, reason: "remote_workspace" }; if (explicitTarget || selector !== "auto") { - return unavailableFileList({ selector, mode, q, limit, candidate, reason: "remote_workspace" }); + return unavailableFileList({ selector, mode, path: normalizedPath?.relativePath ?? null, q, limit, candidate, reason: "remote_workspace" }); } continue; } let rootReal: string; + let startReal: string | undefined; + let startRelativePath: string | undefined; try { rootReal = await fs.realpath(candidate.rootPath!); - } catch { + if (normalizedPath) { + const resolvedDirectory = await statLocalDirectory(candidate, normalizedPath); + rootReal = resolvedDirectory.rootReal; + startReal = resolvedDirectory.realPath; + startRelativePath = normalizedPath.relativePath; + } + } catch (error) { + if (normalizedPath) throw error; firstUnavailable ??= { candidate, reason: "workspace_unavailable" }; if (explicitTarget || selector !== "auto") { - return unavailableFileList({ selector, mode, q, limit, candidate, reason: "workspace_unavailable" }); + return unavailableFileList({ selector, mode, path: null, q, limit, candidate, reason: "workspace_unavailable" }); } continue; } @@ -842,13 +936,14 @@ export function workspaceFileResourceService(db: Db) { const reason = changed.unavailableReason ?? "changed_unavailable"; firstUnavailable ??= { candidate, reason }; if (explicitTarget || selector !== "auto") { - return unavailableFileList({ selector, mode, q, limit, candidate, reason }); + return unavailableFileList({ selector, mode, path: normalizedPath?.relativePath ?? null, q, limit, candidate, reason }); } continue; } return availableFileList({ selector, mode, + path: normalizedPath?.relativePath ?? null, q, limit, candidate, @@ -861,6 +956,8 @@ export function workspaceFileResourceService(db: Db) { const listed = await enumerateWorkspaceFiles({ candidate, rootReal, + startReal, + startRelativePath, mode, normalizedQuery, limit, @@ -868,6 +965,7 @@ export function workspaceFileResourceService(db: Db) { return availableFileList({ selector, mode, + path: normalizedPath?.relativePath ?? null, q, limit, candidate, @@ -880,6 +978,7 @@ export function workspaceFileResourceService(db: Db) { return unavailableFileList({ selector, mode, + path: normalizedPath?.relativePath ?? null, q, limit, candidate: firstUnavailable?.candidate ?? null, diff --git a/ui/src/api/file-resources.ts b/ui/src/api/file-resources.ts index 537e845d936..f96b5d51c70 100644 --- a/ui/src/api/file-resources.ts +++ b/ui/src/api/file-resources.ts @@ -18,6 +18,7 @@ export interface FileResourceListQuery { workspace?: WorkspaceFileSelector; projectId?: string | null; workspaceId?: string | null; + path?: string | null; mode?: WorkspaceFileListMode; q?: string | null; limit?: number; @@ -29,7 +30,7 @@ function buildQuery(query: FileResourceQuery | FileResourceListQuery): string { params.set("projectId", query.projectId); params.set("workspaceId", query.workspaceId); } - if ("path" in query) params.set("path", query.path); + if ("path" in query && query.path) params.set("path", query.path); if (query.workspace && query.workspace !== "auto") { params.set("workspace", query.workspace); } diff --git a/ui/src/components/FileViewerSheet.tsx b/ui/src/components/FileViewerSheet.tsx index 3a050b8a409..6035801dddc 100644 --- a/ui/src/components/FileViewerSheet.tsx +++ b/ui/src/components/FileViewerSheet.tsx @@ -654,6 +654,7 @@ export function FileViewerSheet({ companyId={companyId} onOpen={handleBrowseOpen} initialQuery={viewer.query} + initialFolderPath={viewer.folderPath} initialProjectId={viewer.browseProjectId} initialWorkspaceId={viewer.browseWorkspaceId} className="min-h-0 flex-1 p-4" diff --git a/ui/src/components/WorkspaceFileBrowser.test.tsx b/ui/src/components/WorkspaceFileBrowser.test.tsx index a0f0c406e16..d70b68f7244 100644 --- a/ui/src/components/WorkspaceFileBrowser.test.tsx +++ b/ui/src/components/WorkspaceFileBrowser.test.tsx @@ -278,6 +278,51 @@ describe("WorkspaceFileBrowser", () => { workspaceId: "workspace-content", }); }); + + it("focuses an initial folder in a selected other project workspace", () => { + const folderPath = "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/"; + const contentItem = createItem({ + relativePath: `${folderPath}README.md`, + displayPath: `Paperclip Content / ${folderPath}README.md`, + workspaceLabel: "Paperclip Content", + workspaceKind: "project_workspace", + workspaceId: "workspace-content", + projectId: "project-content", + projectName: "Paperclip Content", + }); + useQueryMock.mockImplementation((options: { queryKey: readonly unknown[] }) => { + if (options.queryKey[0] === "projects") return ok([createProject()]); + return ok(availableResponse([contentItem])); + }); + + const { onOpen } = renderBrowser(vi.fn(), { + companyId: "company-1", + initialProjectId: "project-content", + initialWorkspaceId: "workspace-content", + initialFolderPath: folderPath, + }); + + expect(container.textContent).toContain(folderPath); + expect(container.textContent).toContain("Files in folder"); + const listCall = useQueryMock.mock.calls.find(([options]) => options.queryKey?.[3] === "list"); + expect(listCall?.[0].queryKey[4]).toMatchObject({ + workspace: "project", + projectId: "project-content", + workspaceId: "workspace-content", + path: folderPath, + }); + + const option = container.querySelector('[role="option"]')!; + act(() => { + option.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true })); + }); + expect(onOpen).toHaveBeenCalledWith({ + path: `${folderPath}README.md`, + workspace: "project", + projectId: "project-content", + workspaceId: "workspace-content", + }); + }); }); describe("describeUnavailable", () => { diff --git a/ui/src/components/WorkspaceFileBrowser.tsx b/ui/src/components/WorkspaceFileBrowser.tsx index f5bb495279b..4c20957410e 100644 --- a/ui/src/components/WorkspaceFileBrowser.tsx +++ b/ui/src/components/WorkspaceFileBrowser.tsx @@ -216,6 +216,7 @@ export interface WorkspaceFileBrowserProps { }) => void; /** Seed the search field (e.g. from a URL-backed deep link). */ initialQuery?: string | null; + initialFolderPath?: string | null; initialProjectId?: string | null; initialWorkspaceId?: string | null; className?: string; @@ -226,6 +227,7 @@ export function WorkspaceFileBrowser({ companyId, onOpen, initialQuery, + initialFolderPath, initialProjectId, initialWorkspaceId, className, @@ -236,6 +238,7 @@ export function WorkspaceFileBrowser({ const [workspace, setWorkspace] = useState("auto"); const [selectedProjectId, setSelectedProjectId] = useState(initialProjectId ?? null); const [selectedWorkspaceId, setSelectedWorkspaceId] = useState(initialWorkspaceId ?? null); + const [folderPath, setFolderPath] = useState(initialFolderPath ?? null); const [searchInput, setSearchInput] = useState(initialQuery ?? ""); const [debouncedQuery, setDebouncedQuery] = useState(initialQuery?.trim() ?? ""); // When the workspace has no git change-tracking we silently fall back to a full @@ -297,11 +300,11 @@ export function WorkspaceFileBrowser({ // A new search or workspace should re-attempt recent-change tracking. useEffect(() => { setRecentUnavailable(false); - }, [workspace, source, selectedProjectId, selectedWorkspaceId]); + }, [workspace, source, selectedProjectId, selectedWorkspaceId, folderPath]); const q = debouncedQuery || null; const isSearch = q !== null; - const mode: WorkspaceFileListMode = isSearch ? "all" : recentUnavailable ? "all" : "changed"; + const mode: WorkspaceFileListMode = folderPath || isSearch ? "all" : recentUnavailable ? "all" : "changed"; const targetProjectId = source === "other" ? selectedProjectId : null; const targetWorkspaceId = source === "other" ? selectedWorkspaceId : null; const effectiveWorkspace: WorkspaceFileSelector = source === "other" ? "project" : workspace; @@ -318,6 +321,7 @@ export function WorkspaceFileBrowser({ mode, q, limit: LIST_LIMIT, + path: folderPath, }), queryFn: () => fileResourcesApi.list(issueId, { workspace: effectiveWorkspace, @@ -326,6 +330,7 @@ export function WorkspaceFileBrowser({ mode, q, limit: LIST_LIMIT, + path: folderPath, }), enabled: canListFiles, retry: false, @@ -346,7 +351,7 @@ export function WorkspaceFileBrowser({ // Keep the highlighted option valid as results change. useEffect(() => { setHighlightedIndex(items.length > 0 ? 0 : -1); - }, [items, q, workspace, source, selectedProjectId, selectedWorkspaceId]); + }, [items, q, workspace, source, selectedProjectId, selectedWorkspaceId, folderPath]); const announcement = useMemo(() => { if (listQuery.isFetching) return "Loading workspace files…"; @@ -361,7 +366,11 @@ export function WorkspaceFileBrowser({ if (!value) return; const parsed = parseWorkspaceFileRef(value); const target = { workspace: effectiveWorkspace, ...targetRef }; - if (parsed) onOpen({ path: parsed.path, ...target, line: parsed.line, column: parsed.column }); + if (parsed?.resourceKind === "directory") { + setFolderPath(parsed.path); + setSearchInput(""); + setDebouncedQuery(""); + } else if (parsed) onOpen({ path: parsed.path, ...target, line: parsed.line, column: parsed.column }); else onOpen({ path: value, ...target }); } @@ -567,9 +576,18 @@ export function WorkspaceFileBrowser({ ) : null} + {folderPath ? ( +
+
+ ) : null} +
- {isSearch ? <>Files matching “{q}” : "Recently changed"} + {folderPath ? ( + isSearch ? <>Files in folder matching “{q}” : "Files in folder" + ) : isSearch ? <>Files matching “{q}” : "Recently changed"} {listQuery.isFetching ?