Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agentic-ide): preview workspace files in app
rubenluetke10-beepccaa2b08dcf6
diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 94188fb170..824ca6bab8 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -14,6 +14,8 @@ Endpoints (prefix ``/api/agentic-ide``):* ``POST /terminal-target/open`` → open a path printed by one terminal* ``GET /workspaces`` → every open workspace, in tab order* ``GET /workspaces/{id}/files`` → browse that workspace's file tree+* ``GET /workspaces/{id}/file`` → stream one workspace file in-app+* ``GET /workspaces/{id}/file-preview`` → readable text or a binary preview* ``PUT /workspaces/active`` → bring one to the front (null = wizard)* ``PATCH /workspaces/{workspace_id}`` → rename one workspace tab* ``DELETE /workspaces/{workspace_id}`` → close that one and stop its agents@@ -53,6 +55,7 @@ from __future__ import annotationsimport asyncioimport logging+import mimetypesimport refrom dataclasses import asdictfrom pathlib import Path@@ -68,6 +71,7 @@ from fastapi import (WebSocket,WebSocketDisconnect,)+from fastapi.responses import FileResponsefrom pydantic import BaseModel, Fieldfrom jarvis.agentic_ide import (@@ -649,6 +653,19 @@ class WorkspaceFilesResponse(BaseModel):error: str | None = None+class WorkspaceFilePreviewResponse(BaseModel):+ """A bounded in-app preview without exposing an absolute host path."""++ workspace_id: str+ path: str+ name: str+ size: int+ media_type: str+ text: str | None = None+ truncated: bool = False+ hex_preview: str | None = None++class SearchResponse(BaseModel):query: strentries: list[FolderItem]@@ -1400,6 +1417,106 @@ def _resolve_terminal_target(workspace_folder: str, printed: str) -> Path:return target+_WORKSPACE_PREVIEW_MAX_CHARS = 2 * 1024 * 1024+_WORKSPACE_HEX_PREVIEW_BYTES = 256+_WORKSPACE_FILE_CSP = (+ "default-src 'none'; style-src 'unsafe-inline'; img-src data:; "+ "media-src 'self'; sandbox"+)+++def _resolve_workspace_file(workspace_id: str, path: str) -> Path:+ """Resolve one file inside an open workspace without leaking host paths."""+ session = get_registry().get(workspace_id)+ if session is None:+ raise HTTPException(status_code=404, detail="That workspace is not open.")+ try:+ target = _resolve_terminal_target(session.folder, path)+ except (OSError, RuntimeError, ValueError) as exc:+ raise HTTPException(status_code=404, detail="That workspace file is unavailable.") from exc+ if not target.is_file():+ raise HTTPException(status_code=404, detail="That workspace file is unavailable.")+ return target+++def _read_workspace_file_preview(target: Path) -> dict[str, object]:+ """Extract readable text, with a small hexadecimal fallback for any binary."""+ size = target.stat().st_size+ media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"+ text: str | None = None+ truncated = False++ # Lazy import keeps document parsers off the application boot path (AP-26).+ from jarvis.ultrawiki.extract import MAX_DOCUMENT_BYTES, extract_text++ if size <= MAX_DOCUMENT_BYTES:+ extracted = extract_text(target, filename=target.name, mime=media_type)+ if extracted.ok:+ text = extracted.text[:_WORKSPACE_PREVIEW_MAX_CHARS]+ truncated = len(extracted.text) > _WORKSPACE_PREVIEW_MAX_CHARS++ hex_preview: str | None = None+ if text is None and size > 0:+ with target.open("rb") as handle:+ head = handle.read(_WORKSPACE_HEX_PREVIEW_BYTES)+ hex_preview = " ".join(f"{byte:02X}" for byte in head)++ return {+ "name": target.name,+ "size": size,+ "media_type": media_type,+ "text": text,+ "truncated": truncated,+ "hex_preview": hex_preview,+ }+++ "/workspaces/{workspace_id}/file",+ summary="View one file from an open workspace",+)+async def get_workspace_file(workspace_id: str, path: str) -> FileResponse:+ """Stream any workspace file for an in-app native viewer.++ Active document formats receive a script-blocking CSP. Resolution follows+ symlinks and rejects every target outside the selected workspace.+ """+ target = await asyncio.to_thread(_resolve_workspace_file, workspace_id, path)+ media_type = mimetypes.guess_type(target.name)[0] or "application/octet-stream"+ return FileResponse(+ target,+ media_type=media_type,+ filename=target.name,+ content_disposition_type="inline",+ headers={+ "Cache-Control": "no-store",+ "Content-Security-Policy": _WORKSPACE_FILE_CSP,+ "X-Content-Type-Options": "nosniff",+ },+ )+++ "/workspaces/{workspace_id}/file-preview",+ response_model=WorkspaceFilePreviewResponse,+ summary="Preview one file from an open workspace",+)+async def get_workspace_file_preview(+ workspace_id: str, path: str+) -> WorkspaceFilePreviewResponse:+ """Return bounded readable text or a safe hexadecimal fallback."""+ target = await asyncio.to_thread(_resolve_workspace_file, workspace_id, path)+ try:+ preview = await asyncio.to_thread(_read_workspace_file_preview, target)+ except OSError as exc:+ raise HTTPException(status_code=404, detail="That workspace file is unavailable.") from exc+ return WorkspaceFilePreviewResponse(+ workspace_id=workspace_id,+ path=path.replace("\\", "/"),+ **preview,+ )++@router.post("/terminal-target/open",summary="Open a file or folder linked in an Agentic-IDE terminal",diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsxindex ce491eb8bc..82d5f94588 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.test.tsx@@ -61,6 +61,9 @@ vi.mock("@/lib/agenticIdeApi", () => ({entries: [],truncated: false,})),+ fetchWorkspaceFilePreview: vi.fn(),+ workspaceFileUrl: (workspaceId: string, path: string) =>+ `/api/agentic-ide/workspaces/${workspaceId}/file?path=${encodeURIComponent(path)}`,openTerminalTarget: vi.fn(),promptTerminal: vi.fn(),// Reached from the toolbar's settings panel, which the grid always renders.@@ -2466,6 +2469,48 @@ describe("the workspace header row", () => {expect(screen.getByTestId("pane-Mika")).toBe(pane);});+ it("opens workspace files in-app without remounting a live agent pane", async () => {+ vi.mocked(api.fetchWorkspaceFiles).mockResolvedValueOnce({+ workspace_id: "ide_test",+ root_name: "project",+ path: "",+ entries: [+ {+ name: "README.md",+ path: "README.md",+ is_directory: false,+ is_symlink: false,+ size: 18,+ },+ ],+ truncated: false,+ });+ vi.mocked(api.fetchWorkspaceFilePreview).mockResolvedValueOnce({+ workspace_id: "ide_test",+ path: "README.md",+ name: "README.md",+ size: 18,+ media_type: "text/markdown",+ text: "# Inside the IDE",+ truncated: false,+ hex_preview: null,+ });+ renderGrid();++ const pane = screen.getByTestId("pane-Mika");+ fireEvent.click(screen.getByTestId("workspace-explorer-toggle"));+ const file = await screen.findByRole("treeitem", { name: /README\.md/i });+ fireEvent.click(file);++ expect(await screen.findByRole("heading", { name: "Inside the IDE" })).toBeTruthy();+ expect(screen.getByTestId("workspace-file-viewer")).toBeTruthy();+ expect(screen.getByTestId("pane-Mika")).toBe(pane);+ fireEvent.click(screen.getByRole("button", { name: "Close file preview" }));+ expect(screen.queryByTestId("workspace-file-viewer")).toBeNull();+ expect(screen.getByTestId("pane-Mika")).toBe(pane);+ await waitFor(() => expect(document.activeElement).toBe(file));+ });+it("resizes the right-hand explorer from its left seam", async () => {renderGrid();fireEvent.click(screen.getByTestId("workspace-explorer-toggle"));diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsxindex c89ac283a4..1009356ad0 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticGrid.tsx@@ -80,6 +80,7 @@ import { PromptPreview } from "./PromptPreview";import { PromptEditor } from "./PromptEditor";import { WorkspaceSettings } from "./WorkspaceSettings";import { WorkspaceExplorer } from "./WorkspaceExplorer";+import { WorkspaceFileViewer } from "./WorkspaceFileViewer";import { usePaneFileDrag } from "./paneFileDrag";import {chatTerminalIdentity,@@ -846,6 +847,8 @@ export function AgenticGrid({*/const [viewMode, setViewModeState] = useState<WorkspaceView>(() => storedViewMode() ?? "grid");const [explorerOpen, setExplorerOpen] = useState(false);+ const [openedWorkspaceFile, setOpenedWorkspaceFile] = useState<string | null>(null);+ const openedWorkspaceFileTrigger = useRef<HTMLElement | null>(null);/*** Which agent's terminal is unfolded on the deck, if any.*@@ -871,6 +874,21 @@ export function AgenticGrid({const chatView = viewMode === "chat";const deckView = viewMode === "deck";+ useEffect(() => {+ setOpenedWorkspaceFile(null);+ openedWorkspaceFileTrigger.current = null;+ }, [session.id]);++ const closeWorkspaceFile = useCallback(() => {+ setOpenedWorkspaceFile(null);+ window.requestAnimationFrame(() => openedWorkspaceFileTrigger.current?.focus());+ }, []);++ const openWorkspaceFile = useCallback((path: string, trigger?: HTMLElement) => {+ if (trigger) openedWorkspaceFileTrigger.current = trigger;+ setOpenedWorkspaceFile(path);+ }, []);+/** Which pane the chat stage shows. Kept apart from `target` (the pane the* prompt bar types into) because the two answer different questions: a plain@@ -1355,6 +1373,13 @@ export function AgenticGrid({*/const canvasRef = useRef<HTMLDivElement | null>(null);+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ if (openedWorkspaceFile) canvas.setAttribute("inert", "");+ else canvas.removeAttribute("inert");+ }, [openedWorkspaceFile]);+/** The panes and seams as ELEMENTS, so a drag can move them itself.*@@ -2875,6 +2900,7 @@ export function AgenticGrid({ref={canvasRef}data-testid="agentic-grid-canvas"className="relative h-full w-full"+ aria-hidden={openedWorkspaceFile !== null}>{session.terminals.map((term, index) => {const box = layout.boxes[index];@@ -3166,7 +3192,7 @@ export function AgenticGrid({Folded open, the terminal takes the surface and this layer shrinks tothe strip that carries the way back.*/}- {deckView && deckExpanded !== null && (+ {!openedWorkspaceFile && deckView && deckExpanded !== null && (<divdata-testid="deck-open-pane-header"className="absolute inset-x-0 top-0 z-30 flex items-center gap-2 px-3"@@ -3188,7 +3214,7 @@ export function AgenticGrid({<span className="truncate text-xs text-muted-foreground">{deckExpanded}</span></div>)}- {deckView && deckExpanded === null && (+ {!openedWorkspaceFile && deckView && deckExpanded === null && (<div className="absolute inset-0 z-10"><DeckStageagents={deckAgents}@@ -3208,6 +3234,14 @@ export function AgenticGrid({/></div>)}+ {openedWorkspaceFile && (+ <WorkspaceFileViewer+ workspaceId={session.id}+ path={openedWorkspaceFile}+ onClose={closeWorkspaceFile}+ onOpenFile={openWorkspaceFile}+ />+ )}</div>{/* The explorer owns the right edge. This zero-width host is ALWAYS@@ -3257,6 +3291,7 @@ export function AgenticGrid({workspaceId={session.id}rootName={project.name}onClose={() => setExplorerOpen(false)}+ onOpenFile={openWorkspaceFile}/></div></>diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsxindex 2f9aa764fa..287f8dbc02 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.test.tsx@@ -1,20 +1,6 @@-import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-const pushToast = vi.fn();-let nativeFileActions = true;--vi.mock("@/store/events", () => ({- useEventStore: (selector: (state: { pushToast: typeof pushToast }) => unknown) =>- selector({ pushToast }),-}));--vi.mock("@/hooks/useCapabilities", () => ({- useCapabilities: () => ({- data: { native_file_actions: nativeFileActions, platform: "win32" },- }),-}));-vi.mock("@/i18n", () => ({useT: () => (key: string) =>({@@ -25,14 +11,12 @@ vi.mock("@/i18n", () => ({"agentic_grid.explorer.loading": "Loading…","agentic_grid.explorer.empty": "Empty folder","agentic_grid.explorer.load_failed": "The folder could not be loaded.",- "agentic_grid.explorer.open_failed": "The file could not be opened.",- "agentic_grid.explorer.open_file": "Open file",- "agentic_grid.explorer.open_unavailable": "File opening is available in the desktop app.",+ "agentic_grid.explorer.open_file": "Open in app","agentic_grid.explorer.file": "File","agentic_grid.explorer.folder": "Folder","agentic_grid.explorer.symlink": "Symbolic link","agentic_grid.explorer.open_hint":- "Double-click a file to open it in your system editor.",+ "Click a file to open it here in the workspace.","agentic_grid.explorer.truncated":"This folder has more entries than can be shown at once.",})[key] ?? key,@@ -40,7 +24,6 @@ vi.mock("@/i18n", () => ({vi.mock("@/lib/agenticIdeApi", () => ({fetchWorkspaceFiles: vi.fn(),- openTerminalTarget: vi.fn(),}));import * as api from "@/lib/agenticIdeApi";@@ -49,7 +32,6 @@ import { WorkspaceExplorer } from "./WorkspaceExplorer";describe("WorkspaceExplorer", () => {beforeEach(() => {vi.clearAllMocks();- nativeFileActions = true;vi.mocked(api.fetchWorkspaceFiles).mockImplementation(async (_workspace, path = "") => {if (path === "src") {return {@@ -104,19 +86,16 @@ describe("WorkspaceExplorer", () => {],};});- vi.mocked(api.openTerminalTarget).mockResolvedValue({- opened: true,- kind: "file",- path: "src/main.ts",- });});- it("lazy-loads the complete tree and opens files from their relative paths", async () => {+ it("lazy-loads the complete tree and previews files from their relative paths", async () => {+ const onOpenFile = vi.fn();render(<WorkspaceExplorerworkspaceId="workspace-1"rootName="fallback"onClose={vi.fn()}+ onOpenFile={onOpenFile}/>,);@@ -138,36 +117,25 @@ describe("WorkspaceExplorer", () => {expect(await screen.findByText("main.ts")).toBeTruthy();expect(api.fetchWorkspaceFiles).toHaveBeenCalledWith("workspace-1", "src");- fireEvent.doubleClick(screen.getByRole("treeitem", { name: /main\.ts/i }));- await waitFor(() =>- expect(api.openTerminalTarget).toHaveBeenCalledWith(- "workspace-1",- "src/main.ts",- ),- );+ fireEvent.click(screen.getByRole("treeitem", { name: /main\.ts/i }));+ expect(onOpenFile).toHaveBeenCalledWith("src/main.ts", expect.any(HTMLElement));- fireEvent.click(screen.getByRole("button", { name: "Open file main.ts" }));- await waitFor(() =>- expect(api.openTerminalTarget).toHaveBeenCalledTimes(2),- );+ fireEvent.click(screen.getByRole("button", { name: "Open in app main.ts" }));+ expect(onOpenFile).toHaveBeenCalledTimes(2);});- it("keeps open failures visible and lets the close button collapse the panel", async () => {+ it("lets the close button collapse the panel", async () => {const onClose = vi.fn();- vi.mocked(api.openTerminalTarget).mockRejectedValue(new Error("No editor is available."));render(<WorkspaceExplorerworkspaceId="workspace-1"rootName="project"onClose={onClose}+ onOpenFile={vi.fn()}/>,);- const file = await screen.findByRole("treeitem", { name: /\.gitignore/i });- fireEvent.doubleClick(file);- await waitFor(() =>- expect(pushToast).toHaveBeenCalledWith("error", "No editor is available."),- );+ await screen.findByRole("treeitem", { name: /\.gitignore/i });fireEvent.click(screen.getByRole("button", { name: "Close the explorer" }));expect(onClose).toHaveBeenCalledOnce();@@ -181,6 +149,7 @@ describe("WorkspaceExplorer", () => {workspaceId="workspace-1"rootName="project"onClose={vi.fn()}+ onOpenFile={vi.fn()}/>,);@@ -189,23 +158,4 @@ describe("WorkspaceExplorer", () => {);});- it("disables native file opening outside the desktop app", async () => {- nativeFileActions = false;- render(- <WorkspaceExplorer- workspaceId="workspace-1"- rootName="project"- onClose={vi.fn()}- />,- );-- const file = await screen.findByRole("treeitem", { name: /\.gitignore/i });- const openButton = screen.getByRole("button", {- name: /File opening is available in the desktop app\. \.gitignore/i,- });- expect((openButton as HTMLButtonElement).disabled).toBe(true);-- fireEvent.doubleClick(file);- expect(api.openTerminalTarget).not.toHaveBeenCalled();- });});diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsxindex f939904bd7..d34e5dc729 100644--- a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceExplorer.tsx@@ -8,7 +8,7 @@import { useCallback, useEffect, useRef, useState } from "react";import {ChevronRight,- ExternalLink,+ FileSearch,Link2,Loader2,RefreshCw,@@ -16,15 +16,12 @@ import {} from "lucide-react";import { useThemeValue } from "@/hooks/useTheme";-import { useCapabilities } from "@/hooks/useCapabilities";import { useT } from "@/i18n";import {fetchWorkspaceFiles,- openTerminalTarget,type WorkspaceFileItem,} from "@/lib/agenticIdeApi";import { cn } from "@/lib/utils";-import { useEventStore } from "@/store/events";import { materialFileIcon, useMaterialFileIcons } from "./materialFileIcons";@@ -39,24 +36,23 @@ interface WorkspaceExplorerProps {workspaceId: string;rootName: string;onClose: () => void;+ onOpenFile: (path: string, trigger?: HTMLElement) => void;}export function WorkspaceExplorer({workspaceId,rootName,onClose,+ onOpenFile,}: WorkspaceExplorerProps) {const t = useT();const theme = useThemeValue();- const capabilities = useCapabilities();useMaterialFileIcons();const tRef = useRef(t);tRef.current = t;- const pushToast = useEventStore((state) => state.pushToast);const [directories, setDirectories] = useState<Record<string, DirectoryState>>({});const [openPaths, setOpenPaths] = useState<Set<string>>(() => new Set([""]));const [selectedPath, setSelectedPath] = useState<string | null>(null);- const [openingPath, setOpeningPath] = useState<string | null>(null);const [resolvedRootName, setResolvedRootName] = useState(rootName);const loadDirectory = useCallback(@@ -124,22 +120,11 @@ export function WorkspaceExplorer({);const openFile = useCallback(- async (path: string) => {- if (openingPath === path) return;- setOpeningPath(path);- try {- await openTerminalTarget(workspaceId, path);- } catch (error) {- const detail = error instanceof Error ? error.message : "";- pushToast(- "error",- detail || t("agentic_grid.explorer.open_failed"),- );- } finally {- setOpeningPath((current) => (current === path ? null : current));- }+ (path: string, trigger?: HTMLElement) => {+ setSelectedPath(path);+ onOpenFile(path, trigger);},- [openingPath, pushToast, t, workspaceId],+ [onOpenFile],);const refresh = () => {@@ -150,8 +135,6 @@ export function WorkspaceExplorer({};const rootOpen = openPaths.has("");- const nativeFileActions = capabilities.data?.native_file_actions === true;-return (<asideid="workspace-explorer"@@ -232,23 +215,17 @@ export function WorkspaceExplorer({directories={directories}openPaths={openPaths}selectedPath={selectedPath}- openingPath={openingPath}- nativeFileActions={nativeFileActions}theme={theme}onToggle={toggleDirectory}onSelect={setSelectedPath}- onOpenFile={(path) => void openFile(path)}+ onOpenFile={openFile}/>)}</div></div><footer className="shrink-0 border-t border-border/60 px-3 py-2 text-[10px] leading-relaxed text-muted-foreground">- {t(- nativeFileActions- ? "agentic_grid.explorer.open_hint"- : "agentic_grid.explorer.open_unavailable",- )}+ {t("agentic_grid.explorer.open_hint")}</footer></aside>);@@ -260,8 +237,6 @@ function TreeLevel({directories,openPaths,selectedPath,- openingPath,- nativeFileActions,theme,onToggle,onSelect,@@ -272,12 +247,10 @@ function TreeLevel({directories: Record<string, DirectoryState>;openPaths: Set<string>;selectedPath: string | null;- openingPath: string | null;- nativeFileActions: boolean;theme: "dark" | "light";onToggle: (path: string) => void;onSelect: (path: string) => void;- onOpenFile: (path: string) => void;+ onOpenFile: (path: string, trigger?: HTMLElement) => void;}) {const t = useT();const directory = directories[parentPath];@@ -321,7 +294,7 @@ function TreeLevel({theme,});const isFile = !entry.is_directory && !entry.is_symlink;- const canOpen = isFile && nativeFileActions;+ const canOpen = isFile;const typeName = entry.is_symlink? t("agentic_grid.explorer.symlink"): entry.is_directory@@ -344,17 +317,15 @@ function TreeLevel({aria-selected={selected}aria-label={`${entry.name}, ${typeName}`}title={`${typeName} · ${entry.path}`}- onClick={() => {+ onClick={(event) => {onSelect(entry.path);if (expandable) onToggle(entry.path);- }}- onDoubleClick={() => {- if (canOpen) onOpenFile(entry.path);+ if (canOpen) onOpenFile(entry.path, event.currentTarget);}}onKeyDown={(event) => {if (event.key === "Enter" && canOpen) {event.preventDefault();- onOpenFile(entry.path);+ onOpenFile(entry.path, event.currentTarget);}}}className="flex h-full min-w-0 flex-1 items-center gap-1.5 text-left text-[12px] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring/60"@@ -385,28 +356,15 @@ function TreeLevel({{isFile && (<buttontype="button"- onClick={() => {- if (!canOpen) return;+ onClick={(event) => {onSelect(entry.path);- onOpenFile(entry.path);+ onOpenFile(entry.path, event.currentTarget);}}- disabled={!canOpen || openingPath === entry.path}- aria-label={`${t(canOpen ? "agentic_grid.explorer.open_file" : "agentic_grid.explorer.open_unavailable")} ${entry.name}`}- title={t(- canOpen- ? "agentic_grid.explorer.open_file"- : "agentic_grid.explorer.open_unavailable",- )}- className="mr-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground/70 opacity-70 transition hover:bg-primary/10 hover:text-primary hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring/60 disabled:cursor-not-allowed disabled:opacity-30"+ aria-label={`${t("agentic_grid.explorer.open_file")} ${entry.name}`}+ title={t("agentic_grid.explorer.open_file")}+ className="mr-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-control text-muted-foreground/70 opacity-70 transition hover:bg-primary/10 hover:text-primary hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring/60">- {openingPath === entry.path ? (- <Loader2- className="h-3 w-3 animate-spin motion-reduce:animate-none"- aria-hidden- />- ) : (- <ExternalLink className="h-3 w-3" aria-hidden />- )}+ <FileSearch className="h-3 w-3" aria-hidden /></button>)}</div>@@ -418,8 +376,6 @@ function TreeLevel({directories={directories}openPaths={openPaths}selectedPath={selectedPath}- openingPath={openingPath}- nativeFileActions={nativeFileActions}theme={theme}onToggle={onToggle}onSelect={onSelect}diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceFileViewer.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceFileViewer.test.tsxnew file mode 100644index 0000000000..8b75e9928c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceFileViewer.test.tsx@@ -0,0 +1,146 @@+import { act, fireEvent, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@/i18n", () => ({+ useT: () => (key: string) =>+ ({+ "agentic_grid.viewer.title": "File preview",+ "agentic_grid.viewer.close": "Close file preview",+ "agentic_grid.viewer.loading": "Opening file…",+ "agentic_grid.viewer.failed": "This file could not be displayed.",+ "agentic_grid.viewer.truncated": "The preview is truncated.",+ "agentic_grid.viewer.binary": "Binary preview",+ "agentic_grid.viewer.remote_image": "External image blocked: {0}",+ "agentic_grid.viewer.empty": "This file has no previewable content.",+ "common.retry": "Retry",+ })[key] ?? key,+}));++vi.mock("@/lib/agenticIdeApi", () => ({+ fetchWorkspaceFilePreview: vi.fn(),+ workspaceFileUrl: (workspaceId: string, path: string) =>+ `/api/agentic-ide/workspaces/${workspaceId}/file?path=${encodeURIComponent(path)}`,+}));++import * as api from "@/lib/agenticIdeApi";+import { classifyWorkspaceFile, WorkspaceFileViewer } from "./WorkspaceFileViewer";++describe("WorkspaceFileViewer", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it.each([+ ["README.md", "markdown"],+ ["manual.pdf", "pdf"],+ ["photo.webp", "image"],+ ["voice.mp3", "audio"],+ ["demo.mp4", "video"],+ ["report.docx", "document"],+ ["archive.zip", "binary"],+ ] as const)("classifies %s as %s", (path, kind) => {+ expect(classifyWorkspaceFile(path)).toBe(kind);+ });++ it("renders Markdown safely and opens relative links inside the app", async () => {+ vi.mocked(api.fetchWorkspaceFilePreview).mockResolvedValue({+ workspace_id: "workspace-1",+ path: "docs/README.md",+ name: "README.md",+ size: 24,+ media_type: "text/markdown",+ text: "# Hello\n\n[Guide](guide.md)\n\n",+ truncated: false,+ hex_preview: null,+ });+ const onOpenFile = vi.fn();++ render(+ <WorkspaceFileViewer+ workspaceId="workspace-1"+ path="docs/README.md"+ onClose={vi.fn()}+ onOpenFile={onOpenFile}+ />,+ );++ expect(await screen.findByRole("heading", { name: "Hello" })).toBeTruthy();+ fireEvent.click(screen.getByRole("link", { name: "Guide" }));+ expect(onOpenFile).toHaveBeenCalledWith("docs/guide.md");+ expect(screen.getByText("External image blocked: Spy")).toBeTruthy();+ expect(document.querySelector('img[src^="https://tracker.invalid"]')).toBeNull();+ });++ it("embeds PDFs and closes with Escape", () => {+ const onClose = vi.fn();+ render(+ <WorkspaceFileViewer+ workspaceId="workspace-1"+ path="docs/manual.pdf"+ onClose={onClose}+ onOpenFile={vi.fn()}+ />,+ );++ expect(screen.getByTitle("manual.pdf").getAttribute("src")).toContain(+ "docs%2Fmanual.pdf",+ );+ fireEvent.keyDown(window, { key: "Escape" });+ expect(onClose).toHaveBeenCalledOnce();+ expect(api.fetchWorkspaceFilePreview).not.toHaveBeenCalled();+ });++ it("shows a bounded hexadecimal fallback for unknown binary formats", async () => {+ vi.mocked(api.fetchWorkspaceFilePreview).mockResolvedValue({+ workspace_id: "workspace-1",+ path: "archive.bin",+ name: "archive.bin",+ size: 3,+ media_type: "application/octet-stream",+ text: null,+ truncated: false,+ hex_preview: "00 FF 2A",+ });++ render(+ <WorkspaceFileViewer+ workspaceId="workspace-1"+ path="archive.bin"+ onClose={vi.fn()}+ onOpenFile={vi.fn()}+ />,+ );++ expect(await screen.findByText("00 FF 2A")).toBeTruthy();+ });++ it("ignores an obsolete preview failure after switching to a native viewer", async () => {+ let rejectPreview: ((reason?: unknown) => void) | undefined;+ vi.mocked(api.fetchWorkspaceFilePreview).mockImplementationOnce(+ () => new Promise((_resolve, reject) => {+ rejectPreview = reject;+ }),+ );+ const view = render(+ <WorkspaceFileViewer+ workspaceId="workspace-1"+ path="README.md"+ onClose={vi.fn()}+ onOpenFile={vi.fn()}+ />,+ );++ view.rerender(+ <WorkspaceFileViewer+ workspaceId="workspace-1"+ path="manual.pdf"+ onClose={vi.fn()}+ onOpenFile={vi.fn()}+ />,+ );+ await act(async () => rejectPreview?.(new Error("obsolete")));++ expect(screen.getByTitle("manual.pdf")).toBeTruthy();+ expect(screen.queryByRole("alert")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/WorkspaceFileViewer.tsx b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceFileViewer.tsxnew file mode 100644index 0000000000..3f1fe30059--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/WorkspaceFileViewer.tsx@@ -0,0 +1,287 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { AlertTriangle, FileText, Loader2, X } from "lucide-react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";++import { useT } from "@/i18n";+import {+ fetchWorkspaceFilePreview,+ workspaceFileUrl,+ type WorkspaceFilePreviewResponse,+} from "@/lib/agenticIdeApi";++export type WorkspaceFileKind =+ | "markdown"+ | "text"+ | "pdf"+ | "image"+ | "audio"+ | "video"+ | "html"+ | "document"+ | "binary";++const EXTENSIONS: Record<WorkspaceFileKind, Set<string>> = {+ markdown: new Set(["md", "mdown", "mdx", "mkd", "markdown"]),+ text: new Set([+ "c", "cc", "conf", "cpp", "cs", "css", "csv", "env", "go", "h",+ "hpp", "ini", "java", "js", "json", "jsx", "log", "lua", "mjs",+ "php", "properties", "py", "rb", "rs", "scss", "sh", "sql", "svg",+ "toml", "ts", "tsx", "txt", "xml", "yaml", "yml",+ ]),+ pdf: new Set(["pdf"]),+ image: new Set(["avif", "bmp", "gif", "ico", "jpeg", "jpg", "png", "webp"]),+ audio: new Set(["aac", "flac", "m4a", "mp3", "oga", "ogg", "wav", "weba"]),+ video: new Set(["m4v", "mov", "mp4", "ogv", "webm"]),+ html: new Set(["htm", "html"]),+ document: new Set([+ "doc", "docx", "epub", "odp", "ods", "odt", "ppt", "pptx", "rtf",+ "xls", "xlsx",+ ]),+ binary: new Set(),+};++export function classifyWorkspaceFile(path: string): WorkspaceFileKind {+ const name = path.split("/").at(-1) ?? path;+ const extension = name.includes(".") ? name.split(".").at(-1)?.toLowerCase() ?? "" : "";+ for (const kind of Object.keys(EXTENSIONS) as WorkspaceFileKind[]) {+ if (EXTENSIONS[kind].has(extension)) return kind;+ }+ return "binary";+}++interface WorkspaceFileViewerProps {+ workspaceId: string;+ path: string;+ onClose: () => void;+ onOpenFile: (path: string) => void;+}++export function WorkspaceFileViewer({+ workspaceId,+ path,+ onClose,+ onOpenFile,+}: WorkspaceFileViewerProps) {+ const t = useT();+ const closeRef = useRef<HTMLButtonElement | null>(null);+ const previewRequest = useRef(0);+ const [preview, setPreview] = useState<WorkspaceFilePreviewResponse | null>(null);+ const [error, setError] = useState(false);+ const [nativeFailed, setNativeFailed] = useState(false);+ const kind = classifyWorkspaceFile(path);+ const name = path.split("/").at(-1) ?? path;+ const fileUrl = workspaceFileUrl(workspaceId, path);+ const needsExtractedPreview =+ nativeFailed || ["markdown", "text", "document", "binary"].includes(kind);++ const loadPreview = useCallback(async () => {+ const request = ++previewRequest.current;+ setError(false);+ setPreview(null);+ try {+ const nextPreview = await fetchWorkspaceFilePreview(workspaceId, path);+ if (previewRequest.current === request) setPreview(nextPreview);+ } catch {+ if (previewRequest.current === request) setError(true);+ }+ }, [path, workspaceId]);++ useEffect(() => {+ previewRequest.current += 1;+ setError(false);+ setPreview(null);+ setNativeFailed(false);+ closeRef.current?.focus();+ }, [path, workspaceId]);++ useEffect(+ () => () => {+ previewRequest.current += 1;+ },+ [],+ );++ useEffect(() => {+ if (needsExtractedPreview) void loadPreview();+ }, [loadPreview, needsExtractedPreview]);++ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") onClose();+ };+ window.addEventListener("keydown", handleKeyDown);+ return () => window.removeEventListener("keydown", handleKeyDown);+ }, [onClose]);++ const openRelativeFile = useCallback(+ (href: string) => {+ const base = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";+ let relative = href.split("#", 1)[0];+ try {+ relative = decodeURIComponent(relative);+ } catch {+ return;+ }+ const parts = `${base}${relative}`.split("/");+ const resolved: string[] = [];+ for (const part of parts) {+ if (!part || part === ".") continue;+ if (part === "..") resolved.pop();+ else resolved.push(part);+ }+ if (resolved.length) onOpenFile(resolved.join("/"));+ },+ [onOpenFile, path],+ );++ const markdownComponents = useMemo(+ () => ({+ a: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => {+ const external = !!href && /^(https?:|mailto:)/i.test(href);+ if (external) {+ return <a href={href} target="_blank" rel="noreferrer noopener" {...props}>{children}</a>;+ }+ return (+ <a+ href={href}+ {...props}+ onClick={(event) => {+ event.preventDefault();+ if (href) openRelativeFile(href);+ }}+ >+ {children}+ </a>+ );+ },+ img: ({ src, alt, ...props }: React.ImgHTMLAttributes<HTMLImageElement>) => {+ const external = !!src && (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith("//"));+ if (external) {+ return (+ <span role="img" aria-label={alt ?? ""} className="text-xs text-muted-foreground">+ {t("agentic_grid.viewer.remote_image").replace("{0}", alt || src)}+ </span>+ );+ }+ const base = path.includes("/") ? path.slice(0, path.lastIndexOf("/") + 1) : "";+ const resolvedSrc = src ? workspaceFileUrl(workspaceId, `${base}${src}`) : undefined;+ return <img src={resolvedSrc} alt={alt ?? ""} loading="lazy" {...props} />;+ },+ }),+ [openRelativeFile, path, t, workspaceId],+ );++ return (+ <section+ data-testid="workspace-file-viewer"+ aria-label={`${t("agentic_grid.viewer.title")}: ${name}`}+ className="absolute inset-0 z-40 flex min-h-0 flex-col bg-background/95 backdrop-blur-xl"+ >+ <header className="flex h-11 shrink-0 items-center gap-3 border-b border-border/70 bg-card/50 px-3">+ <FileText className="h-4 w-4 shrink-0 text-primary" aria-hidden />+ <div className="min-w-0 flex-1">+ <div className="truncate text-xs font-medium text-foreground">{name}</div>+ <div className="truncate text-[10px] text-muted-foreground">{path}</div>+ </div>+ <span className="rounded-full border border-border/70 bg-secondary/60 px-2 py-0.5 text-[9px] uppercase tracking-[0.12em] text-muted-foreground">+ {kind}+ </span>+ <button+ ref={closeRef}+ type="button"+ onClick={onClose}+ aria-label={t("agentic_grid.viewer.close")}+ title={t("agentic_grid.viewer.close")}+ className="flex h-8 w-8 items-center justify-center rounded-control text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60"+ >+ <X className="h-4 w-4" aria-hidden />+ </button>+ </header>++ <div className="min-h-0 flex-1 overflow-auto bg-background/35 scrollbar-jarvis">+ {error ? (+ <div role="alert" className="m-auto flex h-full max-w-md flex-col items-center justify-center gap-3 p-8 text-center text-sm text-muted-foreground">+ <AlertTriangle className="h-7 w-7 text-destructive" aria-hidden />+ <p>{t("agentic_grid.viewer.failed")}</p>+ <button type="button" onClick={() => void loadPreview()} className="rounded-control border border-border bg-secondary px-3 py-1.5 text-xs text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60">+ {t("common.retry")}+ </button>+ </div>+ ) : needsExtractedPreview && !preview ? (+ <div role="status" className="flex h-full items-center justify-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" aria-hidden />+ {t("agentic_grid.viewer.loading")}+ </div>+ ) : (+ <ViewerContent+ kind={nativeFailed ? "binary" : kind}+ fileUrl={fileUrl}+ name={name}+ preview={preview}+ markdownComponents={markdownComponents}+ onNativeError={() => setNativeFailed(true)}+ />+ )}+ </div>+ </section>+ );+}++function ViewerContent({+ kind,+ fileUrl,+ name,+ preview,+ markdownComponents,+ onNativeError,+}: {+ kind: WorkspaceFileKind;+ fileUrl: string;+ name: string;+ preview: WorkspaceFilePreviewResponse | null;+ markdownComponents: Record<string, React.ElementType>;+ onNativeError: () => void;+}) {+ const t = useT();+ if (kind === "pdf") {+ return <iframe title={name} src={fileUrl} className="h-full min-h-[28rem] w-full border-0 bg-white" />;+ }+ if (kind === "image") {+ return <div className="flex min-h-full items-center justify-center p-6"><img src={fileUrl} alt={name} onError={onNativeError} className="max-h-full max-w-full object-contain shadow-2xl" /></div>;+ }+ if (kind === "audio") {+ return <div className="flex min-h-full items-center justify-center p-8"><audio src={fileUrl} controls onError={onNativeError} className="w-full max-w-xl" /></div>;+ }+ if (kind === "video") {+ return <div className="flex min-h-full items-center justify-center p-6"><video src={fileUrl} controls onError={onNativeError} className="max-h-full max-w-full bg-black shadow-2xl" /></div>;+ }+ if (kind === "html") {+ return <iframe title={name} src={fileUrl} sandbox="" className="h-full min-h-[28rem] w-full border-0 bg-white" />;+ }++ const text = preview?.text ?? "";+ return (+ <div className="mx-auto w-full max-w-5xl p-5 sm:p-8">+ {preview?.truncated && (+ <div role="note" className="mb-4 border-l-2 border-amber-500 bg-amber-500/5 px-3 py-2 text-xs text-amber-500">+ {t("agentic_grid.viewer.truncated")}+ </div>+ )}+ {kind === "markdown" ? (+ <article className="prose prose-neutral max-w-none text-sm dark:prose-invert prose-a:text-primary prose-code:text-foreground prose-pre:border prose-pre:border-border prose-pre:bg-card/80">+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>{text}</ReactMarkdown>+ </article>+ ) : text ? (+ <pre className="whitespace-pre-wrap break-words font-mono text-xs leading-relaxed text-foreground selection:bg-primary/30">{text}</pre>+ ) : preview?.hex_preview ? (+ <div>+ <p className="mb-3 text-xs text-muted-foreground">{t("agentic_grid.viewer.binary")}</p>+ <pre className="whitespace-pre-wrap break-words rounded-card border border-border bg-card/70 p-4 font-mono text-xs leading-relaxed text-foreground">{preview.hex_preview}</pre>+ </div>+ ) : (+ <p className="text-center text-sm text-muted-foreground">{t("agentic_grid.viewer.empty")}</p>+ )}+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 0fc8eadc71..f472977051 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1792,7 +1792,7 @@"safety_description": "Patterns die ohne Nachfrage ausgeführt werden, auch bei Risk-Tier 'ask'. Vermeidet Confirmation-Fatigue.","appearance": {"title": "Erscheinungsbild",- "description": "Das Farbschema der gesamten App. Dunkel ist die Voreinstellung; Hell ist ein warmer Papier-Look. Wechselt sofort.",+ "description": "Ändert die Farben der Oberfläche, ohne dein Hintergrundbild zu tönen. Dunkel ist die Voreinstellung und der Wechsel erfolgt sofort.","dark": "Dunkel","light": "Hell","system": "System",@@ -3942,14 +3942,24 @@"empty": "Leerer Ordner","load_failed": "Der Ordner konnte nicht geladen werden.","open_failed": "Die Datei konnte nicht geöffnet werden.",- "open_file": "Datei öffnen",+ "open_file": "In der App öffnen","open_unavailable": "Dateien können in der Desktop-App geöffnet werden.","file": "Datei","folder": "Ordner","symlink": "Symbolische Verknüpfung",- "open_hint": "Doppelklick oder die Öffnen-Schaltfläche öffnet eine Datei.",+ "open_hint": "Eine Datei anklicken, um sie direkt im Workspace zu öffnen.","truncated": "Dieser Ordner enthält mehr Einträge, als gleichzeitig angezeigt werden können."},+ "viewer": {+ "title": "Dateivorschau",+ "close": "Dateivorschau schließen",+ "loading": "Datei wird geöffnet…",+ "failed": "Diese Datei konnte nicht dargestellt werden.",+ "empty": "Diese Datei enthält keine darstellbare Vorschau.",+ "binary": "Dieses Format wird als Binärvorschau angezeigt.",+ "remote_image": "Externes Bild blockiert: {0}",+ "truncated": "Die Vorschau ist gekürzt, weil die Datei sehr groß ist."+ },"arrange": {"carrying": "auf ein Terminal ziehen","swap": "Mit {0} tauschen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex d44cedba86..4574deee1f 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1792,7 +1792,7 @@"safety_description": "Patterns executed without confirmation, even at risk-tier 'ask'. Avoids confirmation fatigue.","appearance": {"title": "Appearance",- "description": "The colour theme of the whole app. Dark is the default; light is a warm paper look. Switches instantly.",+ "description": "Changes the interface colours without tinting your wallpaper. Dark is the default and switching is instant.","dark": "Dark","light": "Light","system": "System",@@ -3942,14 +3942,24 @@"empty": "Empty folder","load_failed": "The folder could not be loaded.","open_failed": "The file could not be opened.",- "open_file": "Open file",+ "open_file": "Open in app","open_unavailable": "File opening is available in the desktop app.","file": "File","folder": "Folder","symlink": "Symbolic link",- "open_hint": "Double-click a file or use its open button.",+ "open_hint": "Click a file to open it here in the workspace.","truncated": "This folder has more entries than can be shown at once."},+ "viewer": {+ "title": "File preview",+ "close": "Close file preview",+ "loading": "Opening file…",+ "failed": "This file could not be displayed.",+ "empty": "This file has no previewable content.",+ "binary": "This format is shown as a binary preview.",+ "remote_image": "External image blocked: {0}",+ "truncated": "The preview is truncated because the file is large."+ },"arrange": {"carrying": "drop it on a terminal","swap": "Swap with {0}",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 1aa19bea72..cebd2785f6 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1792,7 +1792,7 @@"safety_description": "Patrones ejecutados sin confirmación, incluso en nivel de riesgo 'preguntar'. Evita la fatiga de confirmaciones.","appearance": {"title": "Apariencia",- "description": "El tema de color de toda la aplicación. Oscuro es el predeterminado; claro es un aspecto de papel cálido. Cambia al instante.",+ "description": "Cambia los colores de la interfaz sin teñir el fondo de pantalla. Oscuro es el predeterminado y el cambio es instantáneo.","dark": "Oscuro","light": "Claro","system": "Sistema",@@ -3942,14 +3942,24 @@"empty": "Carpeta vacía","load_failed": "No se pudo cargar la carpeta.","open_failed": "No se pudo abrir el archivo.",- "open_file": "Abrir archivo",+ "open_file": "Abrir en la aplicación","open_unavailable": "Los archivos se pueden abrir en la aplicación de escritorio.","file": "Archivo","folder": "Carpeta","symlink": "Enlace simbólico",- "open_hint": "Haz doble clic en un archivo o usa su botón para abrirlo.",+ "open_hint": "Haz clic en un archivo para abrirlo aquí en el espacio de trabajo.","truncated": "Esta carpeta tiene más entradas de las que se pueden mostrar a la vez."},+ "viewer": {+ "title": "Vista previa del archivo",+ "close": "Cerrar la vista previa",+ "loading": "Abriendo archivo…",+ "failed": "No se pudo mostrar este archivo.",+ "empty": "Este archivo no tiene contenido que se pueda previsualizar.",+ "binary": "Este formato se muestra como vista previa binaria.",+ "remote_image": "Imagen externa bloqueada: {0}",+ "truncated": "La vista previa está truncada porque el archivo es grande."+ },"arrange": {"carrying": "suéltalo sobre un terminal","swap": "Intercambiar con {0}",diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 401718f084..f69f138cdb 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -59,6 +59,17 @@ export interface WorkspaceFilesResponse {error?: string | null;}+export interface WorkspaceFilePreviewResponse {+ workspace_id: string;+ path: string;+ name: string;+ size: number;+ media_type: string;+ text: string | null;+ truncated: boolean;+ hex_preview: string | null;+}+export interface SearchResponse {query: string;entries: FolderItem[];@@ -729,6 +740,30 @@ export function fetchWorkspaceFiles();}+function workspaceFileUrlFor(+ workspaceId: string,+ path: string,+ endpoint: "file" | "file-preview",+): string {+ const query = new URLSearchParams({ path });+ return `/api/agentic-ide/workspaces/${encodeURIComponent(workspaceId)}/${endpoint}?${query.toString()}`;+}++/** A same-origin URL suitable for an image, media element, or sandboxed frame. */+export function workspaceFileUrl(workspaceId: string, path: string): string {+ return workspaceFileUrlFor(workspaceId, path, "file");+}++/** Extract a bounded, safe text or hexadecimal preview for a workspace file. */+export function fetchWorkspaceFilePreview(+ workspaceId: string,+ path: string,+): Promise<WorkspaceFilePreviewResponse> {+ return getJson<WorkspaceFilePreviewResponse>(+ workspaceFileUrlFor(workspaceId, path, "file-preview"),+ );+}+export function searchFolders(query: string,limit = 40,diff --git a/jarvis/ultrawiki/extract.py b/jarvis/ultrawiki/extract.pyindex e172ae2caa..11048183e0 100644--- a/jarvis/ultrawiki/extract.py+++ b/jarvis/ultrawiki/extract.py@@ -83,6 +83,13 @@ _MAX_TEXT_CHARS = 64 * 1024 * 1024#: into a silent empty item instead of an honest oversized one.MAX_DOCUMENT_BYTES = 64 * 1024 * 1024+# Archive extraction limits. A DOCX can be only a few kilobytes on disk while+# claiming gigabytes of repeated XML after decompression, so the compressed+# file limit above is necessary but not sufficient.+_MAX_ZIP_MEMBERS = 4096+_MAX_ZIP_COMPRESSION_RATIO = 200+_ZIP_RATIO_CHECK_MIN_BYTES = 1024 * 1024+#: Leading magic → kind. Order matters: ZIP-based office formats share the#: `PK` signature and are separated afterwards by their inner layout._MAGIC: tuple[tuple[bytes, str], ...] = (@@ -561,8 +568,27 @@ def _zip_members(data: bytes | Path, predicate: Any) -> list[tuple[str, bytes]]:try:source: Any = data if isinstance(data, Path) else io.BytesIO(data)with zipfile.ZipFile(source) as archive:- names = [n for n in archive.namelist() if predicate(n)]- return [(name, archive.read(name)) for name in names]+ members = archive.infolist()+ if len(members) > _MAX_ZIP_MEMBERS:+ log.warning("extract: refusing archive with too many members")+ return []+ selected = [member for member in members if predicate(member.filename)]+ if sum(member.file_size for member in selected) > MAX_DOCUMENT_BYTES:+ log.warning("extract: refusing archive with oversized extracted content")+ return []+ for member in selected:+ if member.file_size > MAX_DOCUMENT_BYTES:+ log.warning("extract: refusing oversized archive member")+ return []+ if member.file_size < _ZIP_RATIO_CHECK_MIN_BYTES:+ continue+ if member.compress_size == 0:+ log.warning("extract: refusing archive member with invalid compression size")+ return []+ if member.file_size / member.compress_size > _MAX_ZIP_COMPRESSION_RATIO:+ log.warning("extract: refusing archive member with unsafe compression ratio")+ return []+ return [(member.filename, archive.read(member)) for member in selected]except Exception: # noqa: BLE001 — a broken archive yields nothing, never raiseslog.debug("zip member read failed", exc_info=True)return []diff --git a/tests/unit/agentic_ide/test_workspace_explorer.py b/tests/unit/agentic_ide/test_workspace_explorer.pyindex 7e2d2bea71..dd172805fa 100644--- a/tests/unit/agentic_ide/test_workspace_explorer.py+++ b/tests/unit/agentic_ide/test_workspace_explorer.py@@ -3,6 +3,7 @@from __future__ import annotationsimport os+import zipfilefrom pathlib import Pathfrom types import SimpleNamespace@@ -144,3 +145,81 @@ async def test_workspace_route_hides_unknown_and_escaping_paths(workspace: Path)with pytest.raises(HTTPException) as traversal:await routes.get_workspace_files("workspace-1", "..")assert traversal.value.status_code == 404+++async def test_workspace_file_route_streams_inline_without_exposing_host_path(+ workspace: Path,+) -> None:+ document = workspace / "docs" / "guide.pdf"+ document.parent.mkdir()+ document.write_bytes(b"%PDF-1.4\npreview")++ response = await routes.get_workspace_file("workspace-1", "docs/guide.pdf")++ assert Path(response.path) == document+ assert response.media_type == "application/pdf"+ assert response.headers["content-disposition"].startswith("inline;")+ assert response.headers["cache-control"] == "no-store"+ assert "sandbox" in response.headers["content-security-policy"]+ assert response.headers["x-content-type-options"] == "nosniff"+ assert str(workspace) not in repr(response.headers)+++async def test_workspace_file_preview_extracts_text_and_office_documents(+ workspace: Path,+) -> None:+ markdown = workspace / "README.md"+ markdown.write_text("# In-app preview\n", encoding="utf-8")+ docx = workspace / "proposal.docx"+ with zipfile.ZipFile(docx, "w") as archive:+ archive.writestr(+ "word/document.xml",+ '<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'+ "<w:body><w:p><w:r><w:t>Office text</w:t></w:r></w:p></w:body>"+ "</w:document>",+ )++ text_preview = await routes.get_workspace_file_preview("workspace-1", "README.md")+ office_preview = await routes.get_workspace_file_preview("workspace-1", "proposal.docx")++ assert text_preview.text == "# In-app preview"+ assert text_preview.path == "README.md"+ assert str(workspace) not in text_preview.model_dump_json()+ assert office_preview.text is not None+ assert "Office text" in office_preview.text+++async def test_workspace_file_preview_uses_bounded_hex_for_unknown_binary(+ workspace: Path,+) -> None:+ binary = workspace / "archive.bin"+ binary.write_bytes(bytes((0, 255, 42)))++ preview = await routes.get_workspace_file_preview("workspace-1", "archive.bin")++ assert preview.text is None+ assert preview.hex_preview == "00 FF 2A"+ assert preview.size == 3++[email protected]("path", ["..", "missing.txt", "."])+async def test_workspace_file_routes_hide_unavailable_targets(+ workspace: Path, path: str+) -> None:+ with pytest.raises(HTTPException) as unavailable:+ await routes.get_workspace_file_preview("workspace-1", path)+ assert unavailable.value.status_code == 404+++async def test_workspace_file_route_rejects_symlink_escape(workspace: Path) -> None:+ outside = workspace.parent / "outside-secret.txt"+ outside.write_text("not workspace content", encoding="utf-8")+ link = workspace / "linked.txt"+ try:+ os.symlink(outside, link)+ except (NotImplementedError, OSError):+ pytest.skip("File symlinks are unavailable on this host")++ with pytest.raises(HTTPException) as unavailable:+ await routes.get_workspace_file_preview("workspace-1", "linked.txt")+ assert unavailable.value.status_code == 404diff --git a/tests/unit/ultrawiki/test_extract.py b/tests/unit/ultrawiki/test_extract.pyindex ffa3a5b5c5..f731a985d1 100644--- a/tests/unit/ultrawiki/test_extract.py+++ b/tests/unit/ultrawiki/test_extract.py@@ -425,6 +425,17 @@ def test_an_xml_entity_bomb_is_refused_rather_than_expanded():assert len(result.text) < 10_000+def test_a_high_ratio_office_zip_bomb_is_refused_before_decompression():+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ archive.writestr("word/document.xml", b"<w:t>repeat</w:t>" * 250_000)++ result = extract_text(buffer.getvalue(), filename="bomb.docx")++ assert not result.ok+ assert result.text == ""++def test_a_zip_that_is_not_really_a_zip_never_raises():result = extract_text(b"PK\x03\x04garbage-not-an-archive", filename="x.docx")assert isinstance(result, ExtractResult)