mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
Support workspace folder file-browser links
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
50feeb312a
commit
3e4dc94d27
18 files changed
+476
-47
No files matched your search
@@ -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;
|
||||
};
|
||||
|
||||
@@ -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(),
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -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`);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<LocalResolvedFile> {
|
||||
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<LocalResolvedDirectory> {
|
||||
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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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<WorkspaceFileSelector>("auto");
|
||||
const [selectedProjectId, setSelectedProjectId] = useState<string | null>(initialProjectId ?? null);
|
||||
const [selectedWorkspaceId, setSelectedWorkspaceId] = useState<string | null>(initialWorkspaceId ?? null);
|
||||
const [folderPath, setFolderPath] = useState<string | null>(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({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{folderPath ? (
|
||||
<div className="flex min-w-0 items-center gap-1.5 text-[11px] text-muted-foreground" title={folderPath}>
|
||||
<FolderOpen aria-hidden="true" className="h-3 w-3 shrink-0" />
|
||||
<span className="min-w-0 truncate font-mono">{folderPath}</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex items-baseline justify-between gap-2 pt-1">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{isSearch ? <>Files matching “{q}”</> : "Recently changed"}
|
||||
{folderPath ? (
|
||||
isSearch ? <>Files in folder matching “{q}”</> : "Files in folder"
|
||||
) : isSearch ? <>Files matching “{q}”</> : "Recently changed"}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
|
||||
{listQuery.isFetching ? <Loader2 aria-hidden="true" className="h-3 w-3 animate-spin" /> : null}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { MouseEvent, ReactNode } from "react";
|
||||
import { FileCode2 } from "lucide-react";
|
||||
import { FileCode2, FolderOpen } from "lucide-react";
|
||||
import { useLocation } from "@/lib/router";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ParsedWorkspaceFileRef } from "@/lib/workspace-file-parser";
|
||||
import { formatWorkspaceFileRefDisplay } from "@/lib/workspace-file-parser";
|
||||
import {
|
||||
useFileViewer,
|
||||
writeFolderViewerStateToSearch,
|
||||
writeFileViewerStateToSearch,
|
||||
} from "@/context/FileViewerContext";
|
||||
|
||||
@@ -32,24 +33,31 @@ export function WorkspaceFileLink({
|
||||
const location = useLocation();
|
||||
const display = typeof label !== "undefined" ? label : formatWorkspaceFileRefDisplay(workspaceFileRef);
|
||||
const canOpen = !!(onOpen || viewer);
|
||||
const isDirectory = workspaceFileRef.resourceKind === "directory" || workspaceFileRef.path.endsWith("/");
|
||||
const lineSuffix = workspaceFileRef.line
|
||||
? ` line ${workspaceFileRef.line}${workspaceFileRef.column ? ` column ${workspaceFileRef.column}` : ""}`
|
||||
: "";
|
||||
const ariaLabel = canOpen
|
||||
? `Open ${workspaceFileRef.path}${lineSuffix} in the file viewer`
|
||||
: `Workspace file ${workspaceFileRef.path}${lineSuffix}`;
|
||||
? `Open ${workspaceFileRef.path}${lineSuffix} in the ${isDirectory ? "workspace browser" : "file viewer"}`
|
||||
: `Workspace ${isDirectory ? "folder" : "file"} ${workspaceFileRef.path}${lineSuffix}`;
|
||||
const tooltip = title ?? (canOpen
|
||||
? `Open ${workspaceFileRef.path}${lineSuffix} in the file viewer`
|
||||
: `Workspace file ${workspaceFileRef.path}${lineSuffix}`);
|
||||
? `Open ${workspaceFileRef.path}${lineSuffix} in the ${isDirectory ? "workspace browser" : "file viewer"}`
|
||||
: `Workspace ${isDirectory ? "folder" : "file"} ${workspaceFileRef.path}${lineSuffix}`);
|
||||
|
||||
const deepLinkSearch = writeFileViewerStateToSearch(location.search, {
|
||||
path: workspaceFileRef.path,
|
||||
line: workspaceFileRef.line ?? null,
|
||||
column: workspaceFileRef.column ?? null,
|
||||
workspace: "auto",
|
||||
projectId: workspaceFileRef.projectId ?? null,
|
||||
workspaceId: workspaceFileRef.workspaceId ?? null,
|
||||
});
|
||||
const deepLinkSearch = isDirectory
|
||||
? writeFolderViewerStateToSearch(location.search, {
|
||||
path: workspaceFileRef.path,
|
||||
projectId: workspaceFileRef.projectId ?? null,
|
||||
workspaceId: workspaceFileRef.workspaceId ?? null,
|
||||
})
|
||||
: writeFileViewerStateToSearch(location.search, {
|
||||
path: workspaceFileRef.path,
|
||||
line: workspaceFileRef.line ?? null,
|
||||
column: workspaceFileRef.column ?? null,
|
||||
workspace: "auto",
|
||||
projectId: workspaceFileRef.projectId ?? null,
|
||||
workspaceId: workspaceFileRef.workspaceId ?? null,
|
||||
});
|
||||
const href = canOpen
|
||||
? `${location.pathname}${deepLinkSearch}${location.hash}`
|
||||
: "#";
|
||||
@@ -62,6 +70,7 @@ export function WorkspaceFileLink({
|
||||
event.preventDefault();
|
||||
if (!canOpen) return;
|
||||
if (onOpen) onOpen(workspaceFileRef);
|
||||
else if (isDirectory) viewer?.openFolder(workspaceFileRef);
|
||||
else viewer?.open(workspaceFileRef);
|
||||
};
|
||||
|
||||
@@ -79,7 +88,11 @@ export function WorkspaceFileLink({
|
||||
)}
|
||||
onClick={handleClick}
|
||||
>
|
||||
{showIcon ? <FileCode2 aria-hidden="true" className="h-3 w-3 shrink-0 opacity-70" /> : null}
|
||||
{showIcon ? (
|
||||
isDirectory
|
||||
? <FolderOpen aria-hidden="true" className="h-3 w-3 shrink-0 opacity-70" />
|
||||
: <FileCode2 aria-hidden="true" className="h-3 w-3 shrink-0 opacity-70" />
|
||||
) : null}
|
||||
<span className="truncate max-w-[38ch]">{display}</span>
|
||||
</a>
|
||||
);
|
||||
|
||||
@@ -19,4 +19,16 @@ describe("linkWorkspaceFileInlineCode", () => {
|
||||
it("leaves non-file inline code unchanged", () => {
|
||||
expect(linkWorkspaceFileInlineCode("Run `pnpm test`.", "/issues/PAP-1", "", "")).toBe("Run `pnpm test`.");
|
||||
});
|
||||
|
||||
it("links trailing-slash folder refs to the workspace browser", () => {
|
||||
const markdown = linkWorkspaceFileInlineCode(
|
||||
"Open `content-os/cases/active/2026-06-06-pap-10199-bundled-skills/`.",
|
||||
"/issues/PAP-1",
|
||||
"",
|
||||
"",
|
||||
);
|
||||
|
||||
expect(markdown).toContain("kind=directory");
|
||||
expect(markdown).toContain("path=content-os%2Fcases%2Factive%2F2026-06-06-pap-10199-bundled-skills%2F");
|
||||
});
|
||||
});
|
||||
@@ -3,7 +3,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
FILE_VIEWER_NAVIGATE_OPTIONS,
|
||||
readBrowseStateFromSearch,
|
||||
readFileViewerStateFromSearch,
|
||||
writeFolderViewerStateToSearch,
|
||||
writeFileViewerStateToSearch,
|
||||
} from "./FileViewerContext";
|
||||
|
||||
@@ -122,3 +124,22 @@ describe("writeFileViewerStateToSearch", () => {
|
||||
expect(next).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("folder browse search state", () => {
|
||||
it("round-trips explicit target folder browse params", () => {
|
||||
const targetPath = "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/";
|
||||
const next = writeFolderViewerStateToSearch("?tab=thread", {
|
||||
path: targetPath,
|
||||
projectId: "17acae7d-9d0c-46bf-9c82-be9694ac3461",
|
||||
workspaceId: "0de5f74f-a7d4-4f73-a9a0-455a2b968cf2",
|
||||
});
|
||||
|
||||
expect(readFileViewerStateFromSearch(next)).toBeNull();
|
||||
expect(readBrowseStateFromSearch(next)).toEqual({
|
||||
q: null,
|
||||
folderPath: targetPath,
|
||||
projectId: "17acae7d-9d0c-46bf-9c82-be9694ac3461",
|
||||
workspaceId: "0de5f74f-a7d4-4f73-a9a0-455a2b968cf2",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -22,6 +22,7 @@ export interface FileViewerContextValue {
|
||||
query: string | null;
|
||||
browseProjectId: string | null;
|
||||
browseWorkspaceId: string | null;
|
||||
folderPath: string | null;
|
||||
open(
|
||||
ref: Pick<ParsedWorkspaceFileRef, "path" | "line" | "column" | "projectId" | "workspaceId"> & {
|
||||
workspace?: WorkspaceFileSelector;
|
||||
@@ -30,6 +31,11 @@ export interface FileViewerContextValue {
|
||||
): void;
|
||||
/** Open (or stay in) browse mode, optionally seeding the search query. */
|
||||
openBrowse(opts?: { q?: string }): void;
|
||||
openFolder(
|
||||
ref: Pick<ParsedWorkspaceFileRef, "path" | "projectId" | "workspaceId"> & {
|
||||
workspace?: WorkspaceFileSelector;
|
||||
},
|
||||
): void;
|
||||
/** From a file opened via browse, return to the browse list. */
|
||||
backToFiles(): void;
|
||||
close(): void;
|
||||
@@ -72,6 +78,7 @@ export function writeFileViewerStateToSearch(current: string, next: FileViewerUr
|
||||
// A direct file open/close is never a browse origin — clear browse params too.
|
||||
params.delete("browse");
|
||||
params.delete("q");
|
||||
params.delete("folder");
|
||||
if (!next) {
|
||||
params.delete("file");
|
||||
params.delete("line");
|
||||
@@ -98,6 +105,7 @@ export function writeFileViewerStateToSearch(current: string, next: FileViewerUr
|
||||
|
||||
export interface FileViewerBrowseState {
|
||||
q: string | null;
|
||||
folderPath: string | null;
|
||||
projectId: string | null;
|
||||
workspaceId: string | null;
|
||||
}
|
||||
@@ -106,15 +114,41 @@ export function readBrowseStateFromSearch(search: string): FileViewerBrowseState
|
||||
const params = new URLSearchParams(search);
|
||||
if (params.get("browse") !== "1") return null;
|
||||
const q = params.get("q");
|
||||
const folder = params.get("folder");
|
||||
const projectId = params.get("projectId");
|
||||
const workspaceId = params.get("workspaceId");
|
||||
return {
|
||||
q: q && q.length > 0 ? q : null,
|
||||
folderPath: folder && folder.length > 0 ? folder : null,
|
||||
projectId: projectId || null,
|
||||
workspaceId: workspaceId || null,
|
||||
};
|
||||
}
|
||||
|
||||
export function writeFolderViewerStateToSearch(
|
||||
current: string,
|
||||
next: {
|
||||
path: string;
|
||||
projectId: string | null;
|
||||
workspaceId: string | null;
|
||||
},
|
||||
): string {
|
||||
const params = new URLSearchParams(current);
|
||||
params.delete("file");
|
||||
params.delete("line");
|
||||
params.delete("column");
|
||||
params.delete("workspace");
|
||||
params.delete("q");
|
||||
params.set("browse", "1");
|
||||
params.set("folder", next.path);
|
||||
if (next.projectId) params.set("projectId", next.projectId);
|
||||
else params.delete("projectId");
|
||||
if (next.workspaceId) params.set("workspaceId", next.workspaceId);
|
||||
else params.delete("workspaceId");
|
||||
const str = params.toString();
|
||||
return str ? `?${str}` : "";
|
||||
}
|
||||
|
||||
interface FileViewerProviderProps {
|
||||
issueId: string;
|
||||
children: ReactNode;
|
||||
@@ -156,7 +190,9 @@ function EnabledFileViewerProvider({ issueId, children }: Omit<FileViewerProvide
|
||||
const params = new URLSearchParams(nextSearch);
|
||||
params.set("browse", "1");
|
||||
const prevQ = new URLSearchParams(location.search).get("q");
|
||||
const prevFolder = new URLSearchParams(location.search).get("folder");
|
||||
if (prevQ) params.set("q", prevQ);
|
||||
if (prevFolder) params.set("folder", prevFolder);
|
||||
nextSearch = params.toString() ? `?${params.toString()}` : "";
|
||||
}
|
||||
navigateSearch(nextSearch);
|
||||
@@ -170,6 +206,7 @@ function EnabledFileViewerProvider({ issueId, children }: Omit<FileViewerProvide
|
||||
params.delete("file");
|
||||
params.delete("line");
|
||||
params.delete("column");
|
||||
params.delete("folder");
|
||||
params.set("browse", "1");
|
||||
if (typeof opts?.q === "string" && opts.q.length > 0) params.set("q", opts.q);
|
||||
else params.delete("q");
|
||||
@@ -178,6 +215,18 @@ function EnabledFileViewerProvider({ issueId, children }: Omit<FileViewerProvide
|
||||
[location.search, navigateSearch],
|
||||
);
|
||||
|
||||
const openFolder = useCallback<FileViewerContextValue["openFolder"]>(
|
||||
(ref) => {
|
||||
const nextSearch = writeFolderViewerStateToSearch(location.search, {
|
||||
path: ref.path,
|
||||
projectId: ref.projectId ?? null,
|
||||
workspaceId: ref.workspaceId ?? null,
|
||||
});
|
||||
navigateSearch(nextSearch);
|
||||
},
|
||||
[location.search, navigateSearch],
|
||||
);
|
||||
|
||||
const backToFiles = useCallback(() => {
|
||||
const params = new URLSearchParams(location.search);
|
||||
params.delete("file");
|
||||
@@ -192,6 +241,7 @@ function EnabledFileViewerProvider({ issueId, children }: Omit<FileViewerProvide
|
||||
const params = new URLSearchParams(writeFileViewerStateToSearch(location.search, null).replace(/^\?/, ""));
|
||||
params.delete("browse");
|
||||
params.delete("q");
|
||||
params.delete("folder");
|
||||
navigateSearch(params.toString() ? `?${params.toString()}` : "");
|
||||
}, [location.search, navigateSearch]);
|
||||
|
||||
@@ -203,12 +253,14 @@ function EnabledFileViewerProvider({ issueId, children }: Omit<FileViewerProvide
|
||||
query: browseState?.q ?? null,
|
||||
browseProjectId: browseState?.projectId ?? null,
|
||||
browseWorkspaceId: browseState?.workspaceId ?? null,
|
||||
folderPath: browseState?.folderPath ?? null,
|
||||
open,
|
||||
openBrowse,
|
||||
openFolder,
|
||||
backToFiles,
|
||||
close,
|
||||
}),
|
||||
[issueId, state, browseState, open, openBrowse, backToFiles, close],
|
||||
[issueId, state, browseState, open, openBrowse, openFolder, backToFiles, close],
|
||||
);
|
||||
|
||||
return <FileViewerContext.Provider value={value}>{children}</FileViewerContext.Provider>;
|
||||
|
||||
@@ -93,6 +93,7 @@ export const queryKeys = {
|
||||
workspace?: string;
|
||||
projectId?: string | null;
|
||||
workspaceId?: string | null;
|
||||
path?: string | null;
|
||||
mode?: string;
|
||||
q?: string | null;
|
||||
limit?: number;
|
||||
|
||||
@@ -44,6 +44,7 @@ describe("remarkWorkspaceFileRefs", () => {
|
||||
expect(link.url?.startsWith("workspace-file:")).toBe(true);
|
||||
const parsed = parseWorkspaceFileHref(link.url);
|
||||
expect(parsed?.path).toBe("ui/src/pages/IssueDetail.tsx");
|
||||
expect(parsed?.resourceKind).toBe("file");
|
||||
expect(parsed?.line).toBe(42);
|
||||
});
|
||||
|
||||
@@ -68,6 +69,43 @@ describe("remarkWorkspaceFileRefs", () => {
|
||||
expect(parsed?.column).toBe(2);
|
||||
});
|
||||
|
||||
it("round-trips workspace folder hrefs", () => {
|
||||
const targetPath = "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/";
|
||||
const href = buildWorkspaceFileHref({
|
||||
path: targetPath,
|
||||
resourceKind: "directory",
|
||||
line: null,
|
||||
column: null,
|
||||
raw: targetPath,
|
||||
projectId: "17acae7d-9d0c-46bf-9c82-be9694ac3461",
|
||||
workspaceId: "0de5f74f-a7d4-4f73-a9a0-455a2b968cf2",
|
||||
});
|
||||
const parsed = parseWorkspaceFileHref(href);
|
||||
expect(parsed).toMatchObject({
|
||||
path: targetPath,
|
||||
resourceKind: "directory",
|
||||
line: null,
|
||||
column: null,
|
||||
projectId: "17acae7d-9d0c-46bf-9c82-be9694ac3461",
|
||||
workspaceId: "0de5f74f-a7d4-4f73-a9a0-455a2b968cf2",
|
||||
});
|
||||
});
|
||||
|
||||
it("converts trailing-slash inline code into workspace folder links", () => {
|
||||
const tree = paragraph([
|
||||
textNode("Open "),
|
||||
inlineCode("content-os/cases/active/2026-06-06-pap-10199-bundled-skills/"),
|
||||
textNode("."),
|
||||
]);
|
||||
runPlugin(tree);
|
||||
const link = tree.children![1];
|
||||
expect(link.type).toBe("link");
|
||||
expect(parseWorkspaceFileHref(link.url)).toMatchObject({
|
||||
path: "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/",
|
||||
resourceKind: "directory",
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips explicit project workspace identity", () => {
|
||||
const targetPath = "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/README.md";
|
||||
const href = buildWorkspaceFileHref({
|
||||
|
||||
@@ -13,6 +13,7 @@ export function buildWorkspaceFileHref(ref: ParsedWorkspaceFileRef): string {
|
||||
const params = new URLSearchParams();
|
||||
if (ref.projectId) params.set("projectId", ref.projectId);
|
||||
if (ref.workspaceId) params.set("workspaceId", ref.workspaceId);
|
||||
if (ref.resourceKind === "directory") params.set("kind", "directory");
|
||||
params.set("path", ref.path);
|
||||
if (ref.line !== null) params.set("line", String(ref.line));
|
||||
if (ref.column !== null) params.set("column", String(ref.column));
|
||||
@@ -32,12 +33,14 @@ export function parseWorkspaceFileHref(href: string | null | undefined): ParsedW
|
||||
const workspaceIdRaw = params.get("workspaceId");
|
||||
const hasExplicitTarget = Boolean(projectIdRaw && workspaceIdRaw);
|
||||
const projectName = params.get("projectName");
|
||||
const kindRaw = params.get("kind");
|
||||
const lineRaw = params.get("line");
|
||||
const columnRaw = params.get("column");
|
||||
const line = lineRaw ? Number.parseInt(lineRaw, 10) : NaN;
|
||||
const column = columnRaw ? Number.parseInt(columnRaw, 10) : NaN;
|
||||
return {
|
||||
path,
|
||||
resourceKind: kindRaw === "directory" || path.endsWith("/") ? "directory" : "file",
|
||||
line: Number.isFinite(line) && line > 0 ? line : null,
|
||||
column: Number.isFinite(column) && column > 0 ? column : null,
|
||||
projectId: hasExplicitTarget ? projectIdRaw : null,
|
||||
|
||||
@@ -6,6 +6,7 @@ describe("parseWorkspaceFileRef", () => {
|
||||
const ref = parseWorkspaceFileRef("ui/src/pages/IssueDetail.tsx");
|
||||
expect(ref).toEqual({
|
||||
path: "ui/src/pages/IssueDetail.tsx",
|
||||
resourceKind: "file",
|
||||
line: null,
|
||||
column: null,
|
||||
raw: "ui/src/pages/IssueDetail.tsx",
|
||||
@@ -68,10 +69,29 @@ describe("parseWorkspaceFileRef", () => {
|
||||
expect(ref?.path).toBe("scripts/setup/install");
|
||||
});
|
||||
|
||||
it("parses trailing-slash directory refs", () => {
|
||||
const ref = parseWorkspaceFileRef("content-os/cases/active/2026-06-06-pap-10199-bundled-skills/");
|
||||
expect(ref).toEqual({
|
||||
path: "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/",
|
||||
resourceKind: "directory",
|
||||
line: null,
|
||||
column: null,
|
||||
raw: "content-os/cases/active/2026-06-06-pap-10199-bundled-skills/",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects unsafe directory refs", () => {
|
||||
expect(parseWorkspaceFileRef("../secrets/")).toBeNull();
|
||||
expect(parseWorkspaceFileRef("foo/../secrets/")).toBeNull();
|
||||
expect(parseWorkspaceFileRef("~/secrets/")).toBeNull();
|
||||
expect(parseWorkspaceFileRef("C:/Users/foo/")).toBeNull();
|
||||
expect(parseWorkspaceFileRef("foo\\bar/")).toBeNull();
|
||||
});
|
||||
|
||||
it("formats the display string with line and column", () => {
|
||||
expect(formatWorkspaceFileRefDisplay({ path: "a/b.ts", line: 5, column: 10, raw: "a/b.ts:5:10" })).toBe("a/b.ts:5:10");
|
||||
expect(formatWorkspaceFileRefDisplay({ path: "a/b.ts", line: 5, column: null, raw: "a/b.ts:5" })).toBe("a/b.ts:5");
|
||||
expect(formatWorkspaceFileRefDisplay({ path: "a/b.ts", line: null, column: null, raw: "a/b.ts" })).toBe("a/b.ts");
|
||||
expect(formatWorkspaceFileRefDisplay({ path: "a/b.ts", resourceKind: "file", line: 5, column: 10, raw: "a/b.ts:5:10" })).toBe("a/b.ts:5:10");
|
||||
expect(formatWorkspaceFileRefDisplay({ path: "a/b.ts", resourceKind: "file", line: 5, column: null, raw: "a/b.ts:5" })).toBe("a/b.ts:5");
|
||||
expect(formatWorkspaceFileRefDisplay({ path: "a/b.ts", resourceKind: "file", line: null, column: null, raw: "a/b.ts" })).toBe("a/b.ts");
|
||||
});
|
||||
|
||||
it("rejects line numbers that are zero or negative", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export interface ParsedWorkspaceFileRef {
|
||||
path: string;
|
||||
resourceKind?: "file" | "directory";
|
||||
line: number | null;
|
||||
column: number | null;
|
||||
projectId?: string | null;
|
||||
@@ -26,6 +27,8 @@ const WORKSPACE_FILE_REF_RE =
|
||||
|
||||
const BARE_NO_EXT_RE = /^([A-Za-z0-9_.\-+][A-Za-z0-9_./\-+]+\/[A-Za-z0-9_.\-+]+)(?::([1-9]\d*)(?::([1-9]\d*))?|#L([1-9]\d*)(?:C([1-9]\d*))?)?$/;
|
||||
|
||||
const WORKSPACE_DIRECTORY_REF_RE = /^([A-Za-z0-9_.\-+][A-Za-z0-9_./\-+]*\/)$/;
|
||||
|
||||
const INVALID_PREFIXES = ["/", "./", "../", "~/"];
|
||||
|
||||
function toPositiveInt(value: string | undefined): number | null {
|
||||
@@ -35,13 +38,14 @@ function toPositiveInt(value: string | undefined): number | null {
|
||||
return n;
|
||||
}
|
||||
|
||||
function looksLikeWorkspaceFilePath(path: string): boolean {
|
||||
if (!path || path.length > 512) return false;
|
||||
if (path.includes("\\") || path.includes("\0")) return false;
|
||||
if (path.startsWith("/") || path.startsWith("~") || /^[A-Za-z]:/.test(path)) return false;
|
||||
if (path.includes("//")) return false;
|
||||
if (INVALID_PREFIXES.some((prefix) => path === prefix.slice(0, -1))) return false;
|
||||
if (/^\.+$/.test(path)) return false;
|
||||
function looksLikeWorkspacePath(input: string, opts: { allowTrailingSlash: boolean }): boolean {
|
||||
if (!input || input.length > 512) return false;
|
||||
if (input.includes("\\") || input.includes("\0")) return false;
|
||||
if (input.startsWith("/") || input.startsWith("~") || /^[A-Za-z]:/.test(input)) return false;
|
||||
if (input.includes("//")) return false;
|
||||
if (INVALID_PREFIXES.some((prefix) => input === prefix.slice(0, -1))) return false;
|
||||
const path = opts.allowTrailingSlash && input.endsWith("/") ? input.slice(0, -1) : input;
|
||||
if (!path || /^\.+$/.test(path)) return false;
|
||||
const segments = path.split("/");
|
||||
for (const segment of segments) {
|
||||
if (segment === "" || segment === "." || segment === "..") return false;
|
||||
@@ -58,11 +62,24 @@ export function parseWorkspaceFileRef(input: string): ParsedWorkspaceFileRef | n
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
const directoryMatch = trimmed.match(WORKSPACE_DIRECTORY_REF_RE);
|
||||
if (directoryMatch) {
|
||||
const [, rawPath] = directoryMatch;
|
||||
if (!rawPath || !looksLikeWorkspacePath(rawPath, { allowTrailingSlash: true })) return null;
|
||||
return {
|
||||
path: rawPath,
|
||||
resourceKind: "directory",
|
||||
line: null,
|
||||
column: null,
|
||||
raw: trimmed,
|
||||
};
|
||||
}
|
||||
|
||||
const match = trimmed.match(WORKSPACE_FILE_REF_RE) ?? trimmed.match(BARE_NO_EXT_RE);
|
||||
if (!match) return null;
|
||||
const [, rawPath, colonLine, colonCol, hashLine, hashCol] = match;
|
||||
if (!rawPath) return null;
|
||||
if (!looksLikeWorkspaceFilePath(rawPath)) return null;
|
||||
if (!looksLikeWorkspacePath(rawPath, { allowTrailingSlash: false })) return null;
|
||||
|
||||
const line = toPositiveInt(colonLine) ?? toPositiveInt(hashLine);
|
||||
const column = toPositiveInt(colonCol) ?? toPositiveInt(hashCol);
|
||||
@@ -73,6 +90,7 @@ export function parseWorkspaceFileRef(input: string): ParsedWorkspaceFileRef | n
|
||||
|
||||
return {
|
||||
path: rawPath,
|
||||
resourceKind: "file",
|
||||
line,
|
||||
column,
|
||||
raw: trimmed,
|
||||
|
||||
Reference in new issue
Block a user