Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): preview artifacts written into the attached folder
Akarshan Biswas8644bb6c9642
diff --git a/web-app/src/containers/CoworkArtifactCard.tsx b/web-app/src/containers/CoworkArtifactCard.tsxindex e3c41be61..d1df92367 100644--- a/web-app/src/containers/CoworkArtifactCard.tsx+++ b/web-app/src/containers/CoworkArtifactCard.tsx@@ -9,7 +9,7 @@ import {import { Card } from '@/components/ui/card'import { useServiceHub } from '@/hooks/useServiceHub'import { useTranslation } from '@/i18n/react-i18next-compat'-import { previewKindFor, resolveInRoot } from '@/lib/coworkPreview'+import { previewKindFor, resolveInRoots } from '@/lib/coworkPreview'import { ARTIFACT_ICON, type CoworkArtifact } from '@/lib/coworkArtifacts'import { cn } from '@/lib/utils'@@ -35,13 +35,15 @@ const GROUP_TINT: Record<CoworkArtifact['group'], string> = {*/export function CoworkArtifactCard({artifact,- root,+ roots,onPreview,showPath = false,className,}: {artifact: CoworkArtifact- root: string | null+ /** Every place a session may have written the file: its sandbox and, when+ * attached, the writable project folder. Resolved in order. */+ roots: Array<string | null>onPreview: (path: string) => void/** The library sets this: many sessions' files need the disambiguating path. */showPath?: boolean@@ -50,7 +52,7 @@ export function CoworkArtifactCard({const { t } = useTranslation()const serviceHub = useServiceHub()const Icon = ARTIFACT_ICON[artifact.group]- const abs = root ? resolveInRoot(root, artifact.path) : null+ const abs = resolveInRoots(roots, artifact.path)?.abs ?? nullconst kind = previewKindFor(artifact.path)// A real thumbnail only where the browser renders the file on its own; HTML// would need executing the page.diff --git a/web-app/src/containers/CoworkPreviewPanel.tsx b/web-app/src/containers/CoworkPreviewPanel.tsxindex 298a95d41..c86d3e908 100644--- a/web-app/src/containers/CoworkPreviewPanel.tsx+++ b/web-app/src/containers/CoworkPreviewPanel.tsx@@ -30,7 +30,7 @@ import {externalRefs,isAssetKind,previewKindFor,- resolveInRoot,+ resolveInRoots,unresolvedRefs,type PreviewState,} from '@/lib/coworkPreview'@@ -40,8 +40,9 @@ import {const TOO_LARGE = 'common:preview.tooLarge'type Props = {- /** The session sandbox. Every previewed path must resolve inside it. */- root: string | null+ /** Every place the session may have written the file: its sandbox and, when+ * attached, the writable project folder. The path must resolve inside one. */+ roots: Array<string | null>path: stringonClose: () => void}@@ -54,7 +55,7 @@ type Props = {* footer, which is right for a model and wrong for a preview, and it hands back* a description of an image rather than its bytes.*/-export function CoworkPreviewPanel({ root, path, onClose }: Props) {+export function CoworkPreviewPanel({ roots, path, onClose }: Props) {const { t } = useTranslation()const serviceHub = useServiceHub()const [state, setState] = useState<PreviewState>({ status: 'idle' })@@ -66,10 +67,19 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {// from `preview://` with an origin of its own (see previewProtocol.ts).const [unsandboxed, setUnsandboxed] = useState(false)- const abs = useMemo(- () => (root ? resolveInRoot(root, path) : null),- [root, path]+ // Keyed on the values, not the array identity, which the parent rebuilds each+ // render.+ const rootsKey = roots.join('\n')+ // Both the absolute path and the root that contained it: the unsandboxed+ // `preview://` mode registers the matched directory, which may be the attached+ // folder rather than the sandbox.+ const resolved = useMemo(+ () => resolveInRoots(roots, path),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [rootsKey, path])+ const abs = resolved?.abs ?? null+ const matchedRoot = resolved?.root ?? nullconst kind = useMemo(() => previewKindFor(path), [path])useEffect(() => {@@ -127,16 +137,17 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {// The scheme serves nothing until the root is registered, and the network// flag rides on the registration, so a toggle re-registers. Closing the- // panel or leaving the mode withdraws the root.- const live = unsandboxed && kind === 'html' && !!root+ // panel or leaving the mode withdraws the root. The registered root is the+ // one the file resolved inside -- sandbox or attached folder.+ const live = unsandboxed && kind === 'html' && !!matchedRootuseEffect(() => {- if (!live || !root) return- void registerPreviewRoot(root, allowNetwork).catch(() => {+ if (!live || !matchedRoot) return+ void registerPreviewRoot(matchedRoot, allowNetwork).catch(() => {// A failed registration leaves the frame 404ing; the reload button// retries it by re-running this effect.})- return () => void unregisterPreviewRoot(root).catch(() => {})- }, [live, root, allowNetwork, nonce])+ return () => void unregisterPreviewRoot(matchedRoot).catch(() => {})+ }, [live, matchedRoot, allowNetwork, nonce])const iconButton = (label: string,@@ -178,7 +189,7 @@ export function CoworkPreviewPanel({ root, path, onClose }: Props) {() => setAllowNetwork((v) => !v),allowNetwork)}- {root &&+ {matchedRoot &&iconButton(t('common:preview.unsandboxed'),ShieldOff,diff --git a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsxindex e073eb9b8..674617085 100644--- a/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx+++ b/web-app/src/containers/__tests__/CoworkPreviewPanel.test.tsx@@ -50,8 +50,8 @@ const respondWith = (body: string) => {)}-const view = (path: string) =>- render(<CoworkPreviewPanel root={ROOT} path={path} onClose={vi.fn()} />)+const view = (path: string, roots: Array<string | null> = [ROOT]) =>+ render(<CoworkPreviewPanel roots={roots} path={path} onClose={vi.fn()} />)describe('CoworkPreviewPanel', () => {beforeEach(() => {@@ -212,6 +212,34 @@ describe('CoworkPreviewPanel', () => {expect(previewUnregisterRoot).toHaveBeenCalledWith(ROOT)})+ // Regression for #8875: the writable shared folder is a second root, so a+ // slide the agent wrote there previews instead of reporting "outside".+ it('previews a file that lives in the attached folder, not the sandbox', async () => {+ const folder = '/home/me/My Slides'+ respondWith('<h1>Deck</h1>')+ view(`${folder}/deck.html`, [ROOT, folder])++ const frame = (await screen.findByTitle(+ `${folder}/deck.html`+ )) as HTMLIFrameElement+ expect(frame.srcdoc).toContain('<h1>Deck</h1>')+ expect(screen.queryByText('common:preview.outside')).toBeNull()+ })++ // The unsandboxed mode must register the directory the file actually lives+ // in, which is the folder here, not the sandbox.+ it('registers the attached folder for a file served from it', async () => {+ const folder = '/home/me/My Slides'+ respondWith('<canvas></canvas><script>run()</script>')+ view(`${folder}/game.html`, [ROOT, folder])+ await screen.findByTitle(`${folder}/game.html`)++ fireEvent.click(screen.getByLabelText('common:preview.unsandboxed'))+ await waitFor(() =>+ expect(previewRegisterRoot).toHaveBeenLastCalledWith(folder, false)+ )+ })+it('registers nothing while the sandbox is in use', async () => {respondWith('<p>ok</p>')view('page.html')diff --git a/web-app/src/lib/__tests__/coworkPreview.test.ts b/web-app/src/lib/__tests__/coworkPreview.test.tsindex 45b4f0c83..4bccb4766 100644--- a/web-app/src/lib/__tests__/coworkPreview.test.ts+++ b/web-app/src/lib/__tests__/coworkPreview.test.ts@@ -8,6 +8,7 @@ import {externalRefs,previewUrlFor,resolveInRoot,+ resolveInRoots,} from '@/lib/coworkPreview'describe('previewKindFor', () => {@@ -163,3 +164,27 @@ describe('resolveInRoot', () => {expect(resolveInRoot('', 'a.md')).toBeNull()})})++describe('resolveInRoots', () => {+ const sandbox = '/data/agent-workspace/sessions/s1'+ const folder = '/home/me/My Slides'++ it('resolves against the sandbox and returns the matching root', () => {+ expect(resolveInRoots([sandbox, folder], 'deck.html')).toEqual({+ abs: `${sandbox}/deck.html`,+ root: sandbox,+ })+ })++ it('resolves a file that lives in the attached folder (#8875)', () => {+ expect(resolveInRoots([sandbox, folder], `${folder}/deck.html`)).toEqual({+ abs: `${folder}/deck.html`,+ root: folder,+ })+ })++ it('skips null roots and returns null when nothing contains the path', () => {+ expect(resolveInRoots([null, sandbox], '/etc/passwd')).toBeNull()+ expect(resolveInRoots([null, null], 'a.md')).toBeNull()+ })+})diff --git a/web-app/src/lib/coworkPreview.ts b/web-app/src/lib/coworkPreview.tsindex 28bbdf019..22cd6b930 100644--- a/web-app/src/lib/coworkPreview.ts+++ b/web-app/src/lib/coworkPreview.ts@@ -148,6 +148,30 @@ export function resolveInRoot(root: string, path: string): string | null {return inRoot ? abs : null}+/**+ * Resolve `path` against the first of `roots` that contains it, returning both+ * the absolute path and the root that matched.+ *+ * A Cowork session writes into two places at once: its own sandbox and, since+ * the shared folder became writable, the attached project folder. An artifact+ * can therefore land in either, so the preview and the artifact card resolve+ * against both roots instead of the sandbox alone -- resolving against only the+ * sandbox reported a slide written into the folder as "outside the workspace".+ * The matched root is returned so the unsandboxed `preview://` mode can register+ * the directory the file actually lives in.+ */+export function resolveInRoots(+ roots: Array<string | null | undefined>,+ path: string+): { abs: string; root: string } | null {+ for (const root of roots) {+ if (!root) continue+ const abs = resolveInRoot(root, path)+ if (abs) return { abs, root }+ }+ return null+}+/*** The `preview://` URL for `abs`. `sampleUrl` is what `convertFileSrc` produced* for any path under that scheme, which is how the platform's spelling of thediff --git a/web-app/src/routes/artifacts.tsx b/web-app/src/routes/artifacts.tsxindex fd0be510b..fdc29e8e3 100644--- a/web-app/src/routes/artifacts.tsx+++ b/web-app/src/routes/artifacts.tsx@@ -30,16 +30,17 @@ export const Route = createFileRoute(route.artifacts as any)({const PAGE = 24-type Row = CoworkArtifact & { sessionId: string; root: string | null }+type Row = CoworkArtifact & {+ sessionId: string+ roots: Array<string | null>+}/*** Each session's sandbox, keyed by id.*- * Artifacts only ever live there: an attached folder is mounted read-only, so- * every write the agent lands is inside the sandbox. Resolving against- * `session.folder` pointed at a path that does not exist -- and at nothing at- * all for a session with no folder attached, which hid Open and the thumbnails- * entirely.+ * A session writes into two places: its own sandbox and, since the shared+ * folder became writable, the attached project folder. Both are resolution+ * roots, so an artifact the agent wrote into the folder is still openable here.*/function useSessionWorkspaces(sessionIds: string[]): Record<string, string> {const [paths, setPaths] = useState<Record<string, string>>({})@@ -100,7 +101,7 @@ function ArtifactsPage() {return artifactsFromTurns(session.turns, root).map((artifact) => ({...artifact,sessionId: session.id,- root,+ roots: [root, session.folder],}))}),[sessions, workspaces]@@ -179,7 +180,7 @@ function ArtifactsPage() {<CoworkArtifactCardkey={`${row.sessionId}:${row.path}`}artifact={row}- root={row.root}+ roots={row.roots}onPreview={() => open(row)}showPath/>diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex fe395c31c..34ea297bc 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -1268,7 +1268,7 @@ function CoworkPage() {<CoworkArtifactCardkey={artifact.path}artifact={artifact}- root={workspacePath}+ roots={[workspacePath, folder]}onPreview={showPreview}className="my-3"/>@@ -1439,7 +1439,7 @@ function CoworkPage() {{rail?.kind === 'preview' && (<CoworkPreviewPanel- root={workspacePath}+ roots={[workspacePath, folder]}path={rail.path}onClose={() => setRail(null)}/>