Skip to content
Python

Fix artifact previews across granted roots

kudala-bharani3739653ca679
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index ad76e996..91e6c731 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -1225,15 +1225,51 @@ class SessionManager:
def browser_close(self) -> dict[str, Any]:
return browser_close_session()
+ def _artifact_roots(self, session_id: str) -> list[tuple[Path, bool]]:
+ """Return the session's granted directories in resolution order.
+
+ The live engine is authoritative because ``request_directory`` mutates its shared
+ roots list immediately. Without a live engine, reconstruct the same list from the
+ persisted conversation. Unknown sessions retain the historical standalone-server
+ behaviour of using ``default_workspace``.
+ """
+ engine = self._engines.get(session_id)
+ if engine is not None and getattr(engine, "roots", None):
+ raw = [(Path(r.path), bool(r.writable)) for r in engine.roots]
+ else:
+ record = self.session_store.load(session_id)
+ if record and record.workspace:
+ raw = [(Path(record.workspace), True)]
+ raw.extend(
+ (Path(str(r.get("path", ""))), bool(r.get("writable", False)))
+ for r in (record.extra_roots or [])
+ if str(r.get("path", "")).strip()
+ )
+ elif self.default_workspace:
+ raw = [(Path(self.default_workspace), True)]
+ else:
+ raw = []
+
+ out: list[tuple[Path, bool]] = []
+ seen: set[Path] = set()
+ for path, writable in raw:
+ root = path.expanduser().resolve()
+ if root in seen:
+ continue
+ seen.add(root)
+ out.append((root, writable))
+ return out
+
def list_artifacts(self, session_id: str) -> list[dict[str, Any]]:
- record = self.session_store.load(session_id)
- workspace = record.workspace if record else self.default_workspace
- if not workspace:
- return []
- root = Path(workspace).expanduser().resolve()
- if not root.is_dir():
+ roots = [
+ root
+ for root, writable in self._artifact_roots(session_id)
+ if writable and root.is_dir()
+ ]
+ if not roots:
return []
out: list[dict[str, Any]] = []
+ seen_files: set[Path] = set()
suffixes = {
".md",
".markdown",
@@ -1270,33 +1306,40 @@ class SessionManager:
from ..tools.search import OS_DATA_DIRS
skip = {"node_modules", "target", "dist", "__pycache__"} | OS_DATA_DIRS
- for dirpath, dirs, files in os.walk(root):
- dirs[:] = [d for d in dirs if not d.startswith(".") and d not in skip]
- for name in files:
- if name.startswith("."):
- continue
- path = Path(dirpath) / name
- if path.suffix.lower() not in suffixes:
- continue
- try:
- st = path.stat()
- if not path.is_file():
+ for index, root in enumerate(roots):
+ for dirpath, dirs, files in os.walk(root):
+ dirs[:] = [d for d in dirs if not d.startswith(".") and d not in skip]
+ for name in files:
+ if name.startswith("."):
+ continue
+ path = Path(dirpath) / name
+ if path.suffix.lower() not in suffixes:
+ continue
+ try:
+ resolved = path.resolve()
+ if not resolved.is_file() or not _path_is_under(resolved, root):
+ continue
+ if resolved in seen_files:
+ continue
+ seen_files.add(resolved)
+ st = resolved.stat()
+ rel = path.relative_to(root)
+ out.append(
+ {
+ # Preserve workspace-relative identifiers for the primary root.
+ # Extra-root artifacts use their absolute path so duplicate
+ # relative names remain unambiguous when the viewer calls
+ # read/reveal.
+ "path": str(rel) if index == 0 else str(resolved),
+ "abs_path": str(resolved),
+ "name": resolved.name,
+ "kind": _artifact_kind(resolved),
+ "size": st.st_size,
+ "modified_at": st.st_mtime,
+ }
+ )
+ except (OSError, ValueError):
continue
- out.append(
- {
- "path": str(path.relative_to(root)),
- # Absolute path for "Copy path" — the relative one is useless
- # outside the app (tester catch 2026-07-12: it copied just the
- # filename).
- "abs_path": str(path),
- "name": path.name,
- "kind": _artifact_kind(path),
- "size": st.st_size,
- "modified_at": st.st_mtime,
- }
- )
- except OSError:
- continue
out.sort(key=lambda a: a["modified_at"], reverse=True)
return out[:80]
@@ -1305,25 +1348,32 @@ class SessionManager:
def _artifact_target(
self, session_id: str, path: str, *, allow_dir: bool = False
) -> tuple[Optional[Path], Optional[str]]:
- """Resolve an artifact path under the session's workspace, or (None, error)."""
- record = self.session_store.load(session_id)
- workspace = record.workspace if record else self.default_workspace
- if not workspace:
+ """Resolve an artifact inside any directory granted to this session."""
+ roots = [root for root, _writable in self._artifact_roots(session_id)]
+ if not roots:
return None, "no workspace"
- root = Path(workspace).expanduser().resolve()
- target = (root / path).expanduser().resolve()
- try:
- target.relative_to(root)
- except ValueError:
- return None, "path escapes workspace"
- if allow_dir and target.is_dir():
- return target, None
- if not target.is_file():
- return None, (
+ requested = Path(path).expanduser()
+ candidates = (
+ [requested.resolve()]
+ if requested.is_absolute()
+ else [(root / requested).resolve() for root in roots]
+ )
+ confined = False
+ for target in candidates:
+ if not any(_path_is_under(target, root) for root in roots):
+ continue
+ confined = True
+ if target.is_file() or (allow_dir and target.is_dir()):
+ return target, None
+ return (
+ (
+ None,
"This isn't in the conversation's folder anymore — it may have been "
- "moved or deleted."
+ "moved or deleted.",
)
- return target, None
+ if confined
+ else (None, "path escapes session directories")
+ )
def read_artifact(self, session_id: str, path: str) -> dict[str, Any]:
# Folders are readable too (a model sometimes links a whole package, e.g. a skill
@@ -4041,6 +4091,14 @@ def _recent_files(workspace: str, *, since: float, limit: int = 20) -> list[str]
return out
+def _path_is_under(path: Path, root: Path) -> bool:
+ try:
+ path.relative_to(root)
+ return True
+ except ValueError:
+ return False
+
+
def _artifact_kind(path: Path) -> str:
suffix = path.suffix.lower()
if suffix in {".md", ".markdown"}:
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index ad9debd5..90898e0a 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -179,7 +179,7 @@ export async function deleteSession(sessionId: string): Promise<{ ok: boolean; e
}
export interface ArtifactInfo {
- path: string; // workspace-relative (the display/API identifier)
+ path: string; // primary-root relative or absolute for an additional granted root
abs_path?: string; // absolute — what "Copy path" copies
name: string;
kind: "markdown" | "html" | "image" | "code" | "text" | string;
diff --git a/surfaces/gui/src/artifactPaths.test.ts b/surfaces/gui/src/artifactPaths.test.ts
new file mode 100644
index 00000000..a6b908e3
--- /dev/null
+++ b/surfaces/gui/src/artifactPaths.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import { artifactBaseName, decodeArtifactPath, findArtifact } from "./artifactPaths";
+
+const external = {
+ path: "/Users/example/Documents/新闻摘要_2026-07-27.md",
+ abs_path: "/Users/example/Documents/新闻摘要_2026-07-27.md",
+ name: "新闻摘要_2026-07-27.md",
+};
+
+describe("artifact paths", () => {
+ it("decodes URL-encoded Unicode paths but preserves malformed literal percent names", () => {
+ expect(decodeArtifactPath("%E6%96%B0%E9%97%BB%E6%91%98%E8%A6%81.md")).toBe("新闻摘要.md");
+ expect(decodeArtifactPath("progress-100%.md")).toBe("progress-100%.md");
+ });
+
+ it("extracts names with POSIX or Windows separators", () => {
+ expect(artifactBaseName("reports/summary.md")).toBe("summary.md");
+ expect(artifactBaseName("C:\\Reports\\summary.md")).toBe("summary.md");
+ });
+
+ it("matches encoded bare names and relative paths against external artifacts", () => {
+ expect(
+ findArtifact([external], "%E6%96%B0%E9%97%BB%E6%91%98%E8%A6%81_2026-07-27.md"),
+ ).toBe(external);
+ expect(findArtifact([external], "Documents/新闻摘要_2026-07-27.md")).toBe(external);
+ expect(findArtifact([external], external.path)).toBe(external);
+ });
+});
diff --git a/surfaces/gui/src/artifactPaths.ts b/surfaces/gui/src/artifactPaths.ts
new file mode 100644
index 00000000..19310bed
--- /dev/null
+++ b/surfaces/gui/src/artifactPaths.ts
@@ -0,0 +1,36 @@
+type ArtifactPath = { path: string; abs_path?: string; name: string };
+
+export function decodeArtifactPath(path: string): string {
+ try {
+ return decodeURIComponent(path);
+ } catch {
+ // A literal percent in a filename is valid even when it is not URL encoding.
+ return path;
+ }
+}
+
+export function normalizeArtifactPath(path: string): string {
+ return decodeArtifactPath(path).replace(/\\/g, "/").replace(/^\.\/+/, "");
+}
+
+export function artifactBaseName(path: string): string {
+ const normalized = normalizeArtifactPath(path);
+ return normalized.split("/").pop() || normalized;
+}
+
+export function findArtifact<T extends ArtifactPath>(list: T[], path: string): T | undefined {
+ const requested = normalizeArtifactPath(path);
+ const bareName = !requested.includes("/");
+ return list.find((artifact) => {
+ const candidates = [artifact.path, artifact.abs_path].filter(Boolean) as string[];
+ if (
+ candidates.some((candidate) => {
+ const normalized = normalizeArtifactPath(candidate);
+ return normalized === requested || normalized.endsWith("/" + requested);
+ })
+ ) {
+ return true;
+ }
+ return bareName && normalizeArtifactPath(artifact.name) === requested;
+ });
+}
diff --git a/surfaces/gui/src/components/Markdown.test.tsx b/surfaces/gui/src/components/Markdown.test.tsx
index b2d4fee0..171c7417 100644
--- a/surfaces/gui/src/components/Markdown.test.tsx
+++ b/surfaces/gui/src/components/Markdown.test.tsx
@@ -35,4 +35,16 @@ describe("Markdown artifact links", () => {
render(<Markdown text="[](artifact:out/report.pdf)" />);
expect(screen.getByTestId("artifact-chip").textContent).toContain("report.pdf");
});
+
+ it("dispatches a decoded Unicode filename", () => {
+ const seen: string[] = [];
+ const listener = (e: Event) => seen.push((e as CustomEvent).detail.path);
+ window.addEventListener(OPEN_ARTIFACT_EVENT, listener);
+
+ render(<Markdown text="[News](artifact:%E6%96%B0%E9%97%BB%E6%91%98%E8%A6%81.md)" />);
+ fireEvent.click(screen.getByTestId("artifact-chip"));
+ expect(seen).toEqual(["新闻摘要.md"]);
+
+ window.removeEventListener(OPEN_ARTIFACT_EVENT, listener);
+ });
});
diff --git a/surfaces/gui/src/components/Markdown.tsx b/surfaces/gui/src/components/Markdown.tsx
index 33670427..a8bb22a9 100644
--- a/surfaces/gui/src/components/Markdown.tsx
+++ b/surfaces/gui/src/components/Markdown.tsx
@@ -1,5 +1,6 @@
import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
import remarkGfm from "remark-gfm";
+import { artifactBaseName, decodeArtifactPath } from "../artifactPaths";
import { Icon } from "./Icon";
// §34 (UX-016): the agent ends a deliverable turn with plain markdown —
@@ -10,14 +11,17 @@ import { Icon } from "./Icon";
export const OPEN_ARTIFACT_EVENT = "ocw-open-artifact";
function ArtifactChip({ path, title }: { path: string; title: string }) {
- const file = path.split("/").pop() || path;
+ const decodedPath = decodeArtifactPath(path);
+ const file = artifactBaseName(decodedPath);
return (
<button
className="art-chip"
data-testid="artifact-chip"
- title={path}
+ title={decodedPath}
onClick={() =>
- window.dispatchEvent(new CustomEvent(OPEN_ARTIFACT_EVENT, { detail: { path } }))
+ window.dispatchEvent(
+ new CustomEvent(OPEN_ARTIFACT_EVENT, { detail: { path: decodedPath } }),
+ )
}
>
<span className="art-chip-ico">
diff --git a/surfaces/gui/src/components/RightRail.tsx b/surfaces/gui/src/components/RightRail.tsx
index ac3ea669..9cb92c80 100644
--- a/surfaces/gui/src/components/RightRail.tsx
+++ b/surfaces/gui/src/components/RightRail.tsx
@@ -8,6 +8,7 @@ import {
type ArtifactContent,
type ArtifactInfo,
} from "../api";
+import { artifactBaseName, findArtifact } from "../artifactPaths";
import type { TodoItem } from "../types";
import { AccessSection } from "./AccessSection";
import { Icon } from "./Icon";
@@ -122,17 +123,15 @@ export function RightRail({
if (!active) return;
const minimal = (path: string): ArtifactInfo => ({
path,
- name: path.split("/").pop() || path,
+ name: artifactBaseName(path),
kind: kindFromPath(path),
size: 0,
modified_at: 0,
});
- const match = (list: ArtifactInfo[], path: string) =>
- list.find((a) => a.path === path || a.path.endsWith("/" + path) || a.name === path);
const onOpen = (e: Event) => {
const path = String((e as CustomEvent).detail?.path || "");
if (!path) return;
- const found = match(artifacts, path);
+ const found = findArtifact(artifacts, path);
if (found) {
setSelected(found);
return;
@@ -140,7 +139,7 @@ export function RightRail({
getArtifacts(sessionId)
.then((list) => {
setArtifacts(list);
- setSelected(match(list, path) ?? minimal(path));
+ setSelected(findArtifact(list, path) ?? minimal(path));
})
.catch(() => setSelected(minimal(path)));
};
diff --git a/tests/test_multiroot.py b/tests/test_multiroot.py
index d24aa0ef..5dcdd23e 100644
--- a/tests/test_multiroot.py
+++ b/tests/test_multiroot.py
@@ -239,6 +239,25 @@ def test_add_and_remove_roots_live_and_persisted(tmp_path):
assert str(ro.resolve()) not in persisted
+def test_artifacts_follow_live_root_grants(tmp_path):
+ mgr = _cowork_manager(tmp_path)
+ shared = tmp_path / "shared_artifacts"
+ shared.mkdir()
+ artifact = shared / "实时摘要.md"
+ artifact.write_text("live", encoding="utf-8")
+ sid = "live-artifacts"
+ mgr.get_engine(sid, agent="cowork")
+
+ assert not mgr.list_artifacts(sid)
+
+ mgr.add_root(sid, str(shared), writable=True)
+ listed = mgr.list_artifacts(sid)
+ assert [item["path"] for item in listed] == [str(artifact.resolve())]
+
+ mgr.remove_root(sid, str(shared))
+ assert not mgr.list_artifacts(sid)
+
+
def test_add_root_before_first_turn_persists(tmp_path):
"""Adding a folder on a brand-new conversation (no record, no engine yet) must survive:
the manager creates a minimal cowork record so the grant isn't lost (GUI start panel).
diff --git a/tests/test_server.py b/tests/test_server.py
index 495de260..f21790dd 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -211,6 +211,69 @@ def test_artifact_read_rejects_path_escape(tmp_path):
assert "escapes" in escaped["error"]
+def test_artifacts_include_and_read_granted_external_directories(tmp_path):
+ workspace = tmp_path / "workspace"
+ external = tmp_path / "external"
+ read_only = tmp_path / "read_only"
+ workspace.mkdir()
+ external.mkdir()
+ read_only.mkdir()
+ (workspace / "primary.md").write_text("primary", encoding="utf-8")
+ (external / "外部摘要.md").write_text("external", encoding="utf-8")
+ (read_only / "reference.md").write_text("reference", encoding="utf-8")
+
+ manager = SessionManager(
+ workspace=workspace,
+ data_dir=tmp_path / "data",
+ provider=ScriptedProvider([]),
+ )
+ manager.session_store.save(
+ SessionRecord(
+ session_id="multi-root",
+ workspace=str(workspace),
+ model="gpt-5.5",
+ mode="interactive",
+ messages=[],
+ agent="cowork",
+ extra_roots=[
+ {"path": str(external), "writable": True},
+ {"path": str(read_only), "writable": False},
+ ],
+ )
+ )
+ client = TestClient(create_app(manager))
+
+ artifacts = client.get("/v1/sessions/multi-root/artifacts").json()["artifacts"]
+ by_name = {artifact["name"]: artifact for artifact in artifacts}
+ assert by_name["primary.md"]["path"] == "primary.md"
+ assert by_name["外部摘要.md"]["path"] == str((external / "外部摘要.md").resolve())
+ assert "reference.md" not in by_name
+
+ # A bare artifact: link can resolve against an additional root even before the
+ # frontend's artifact list has refreshed.
+ preview = client.get(
+ "/v1/sessions/multi-root/artifacts/read", params={"path": "外部摘要.md"}
+ ).json()
+ assert preview["ok"] is True
+ assert preview["content"] == "external"
+
+ # Read-only roots stay out of the produced-artifact list, but remain readable because
+ # the user explicitly granted the session read access to them.
+ reference = client.get(
+ "/v1/sessions/multi-root/artifacts/read",
+ params={"path": str(read_only / "reference.md")},
+ ).json()
+ assert reference["ok"] is True
+ assert reference["content"] == "reference"
+
+ escaped = client.get(
+ "/v1/sessions/multi-root/artifacts/read",
+ params={"path": str(tmp_path / "not-granted.md")},
+ ).json()
+ assert escaped["ok"] is False
+ assert "escapes" in escaped["error"]
+
+
def test_sessions_hide_scheduled_internal_runs(tmp_path):
manager = SessionManager(workspace=tmp_path, provider=ScriptedProvider([]))
manager.session_store.save(