Skip to content

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.

feat(agentic-ide): readable permission picker and real attachment previews

rubenluetke10-beep079fe2d925ce
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index fecea0f429..04fe171244 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -1201,6 +1201,50 @@ async def attach_files(
return {"attachments": [item.to_dict() for item in found], "cwd": folder}
+ "/attachments/file",
+ summary="Show one attached picture or video in the composer",
+ openapi_extra={"x-jarvis-readonly": True},
+)
+async def attachment_file(cwd: str, reference: str) -> Any:
+ """Stream an attached image or video back for the composer's thumbnail.
+
+ A file dragged in by path (the Appshots gallery, Explorer inside the
+ desktop shell) never passes its bytes through the window, so the composer
+ has nothing to draw. ``reference`` is the attachment's own reference from
+ :func:`attach_files`, ``cwd`` the folder that call answered with. Only a
+ picture or video that resolves INSIDE that folder is served — symlinks
+ included — and never SVG, which can carry script.
+ """
+ from fastapi.responses import FileResponse
+
+ from jarvis.agent_chat.media import MEDIA_TYPES
+ from jarvis.agentic_ide import drops
+
+ folder = _validate_cwd(cwd)
+ relative = drops.dereference(reference)
+ if not folder or not relative:
+ raise HTTPException(status_code=404, detail="attachment not found")
+
+ def _resolve() -> Path | None:
+ inside = drops.within_workspace(str(Path(folder) / relative), folder)
+ if inside is None:
+ return None
+ target = Path(folder) / inside
+ return target if target.is_file() else None
+
+ target = await asyncio.to_thread(_resolve)
+ mime = MEDIA_TYPES.get(target.suffix.lower(), "") if target else ""
+ if target is None or not mime.startswith(("image/", "video/")) or mime == "image/svg+xml":
+ raise HTTPException(status_code=404, detail="attachment not found")
+ return FileResponse(
+ target,
+ media_type=mime,
+ content_disposition_type="inline",
+ headers={"Cache-Control": "private, max-age=300", "X-Content-Type-Options": "nosniff"},
+ )
+
+
# ------------------------------------------------------------------ folders
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
index 2861763e44..b9b5a712c1 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatAttachmentStrip.tsx
@@ -1,5 +1,7 @@
-import { FileText, ImageIcon, Loader2, X } from "lucide-react";
+import { useState } from "react";
+import { FileText, Film, ImageIcon, Loader2, Play, X } from "lucide-react";
+import { attachmentMedia } from "@/components/agentchat/useChatAttachments";
import type { ChatAttachment } from "@/lib/agentChatApi";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -7,12 +9,14 @@ import { cn } from "@/lib/utils";
/**
* The files waiting to go in with the next message.
*
- * Each card shows the picture itself when its bytes passed through this
- * window, and says what was actually LEARNED from the file, not merely that
- * one is attached. That distinction is the whole feature: "screenshot.png"
- * tells the person nothing about whether the model will be able to see it,
- * while "described" and "not described" are the two outcomes they need to
- * tell apart BEFORE pressing Send — and the second happens for real, on any
+ * Each card shows the picture itself — a video's first frame under a play
+ * mark — whenever it can be drawn: from the bytes that passed through this
+ * window, or from the backend's copy of a file that arrived by path. And it
+ * says what was actually LEARNED from the file, not merely that one is
+ * attached. That distinction is the whole feature: "screenshot.png" tells the
+ * person nothing about whether the model will be able to see it, while
+ * "described" and "not described" are the two outcomes they need to tell
+ * apart BEFORE pressing Send — and the second happens for real, on any
* install whose providers cannot see images.
*
* A near-twin of the Agentic IDE's terminal strip
@@ -30,34 +34,64 @@ export function ChatAttachmentStrip({
attachments: ChatAttachment[];
analyzing: number;
onRemove: (name: string) => void;
- /** A local picture per image attachment, keyed by its name. */
+ /** A picture per image or video attachment, keyed by its name. */
previews?: Record<string, string>;
}) {
const t = useT();
+ // A picture that failed to load (an older backend, a file swept since)
+ // falls back to the file's icon instead of an empty frame.
+ const [broken, setBroken] = useState<Record<string, boolean>>({});
if (attachments.length === 0 && analyzing === 0) return null;
return (
<div
data-testid="chat-attachments"
- className="flex max-h-32 shrink-0 flex-wrap items-center gap-2 overflow-y-auto px-1 scrollbar-jarvis"
+ className="flex max-h-40 shrink-0 flex-wrap items-center gap-2 overflow-y-auto px-1 scrollbar-jarvis"
>
{attachments.map((item) => {
const read = item.described_by !== "none" && item.detail.length > 0;
- const preview = previews[item.name];
- const Icon = item.kind === "image" ? ImageIcon : FileText;
+ const media = attachmentMedia(item);
+ const preview = media && !broken[item.name] ? previews[item.name] : undefined;
+ const Icon = media === "video" ? Film : item.kind === "image" ? ImageIcon : FileText;
+ const markBroken = () => setBroken((prev) => ({ ...prev, [item.name]: true }));
return (
<span
key={item.name}
data-testid={`chat-attachment-${item.name}`}
+ data-media={preview ? media : undefined}
title={
read
? `${item.detail.slice(0, 400)}${item.detail.length > 400 ? "…" : ""}`
: item.note || item.name
}
- className="group/attachment relative flex h-12 max-w-[15rem] items-center gap-2.5 rounded-xl border border-border bg-background/40 py-1 pl-1 pr-2"
+ className={cn(
+ "group/attachment relative flex max-w-[16rem] items-center gap-2.5 rounded-xl border border-border bg-background/40 py-1 pl-1 pr-2",
+ preview ? "h-16" : "h-12",
+ )}
>
- <span className="flex h-10 w-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-secondary text-muted-foreground">
- {preview ? (
- <img src={preview} alt="" className="h-full w-full object-cover" />
+ <span
+ className={cn(
+ "relative flex shrink-0 items-center justify-center overflow-hidden rounded-lg bg-secondary text-muted-foreground",
+ preview ? "h-14 w-14" : "h-10 w-10",
+ )}
+ >
+ {preview && media === "video" ? (
+ <>
+ <video
+ src={preview}
+ muted
+ playsInline
+ preload="metadata"
+ onError={markBroken}
+ className="h-full w-full object-cover"
+ />
+ <span aria-hidden className="pointer-events-none absolute inset-0 flex items-center justify-center">
+ <span className="flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white">
+ <Play className="ml-0.5 h-3 w-3 fill-current" />
+ </span>
+ </span>
+ </>
+ ) : preview ? (
+ <img src={preview} alt="" onError={markBroken} className="h-full w-full object-cover" />
) : (
<Icon className="h-4 w-4" aria-hidden />
)}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
index f67d858417..9c8a4f5034 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatAttachments.test.tsx
@@ -177,6 +177,26 @@ describe("chat composer attachments", () => {
expect(screen.queryByTestId("composer-drop-overlay")).toBeNull();
});
+ it("draws a picture dropped by path from the backend's copy", async () => {
+ composer();
+ const card = screen.getByTestId("agent-composer");
+ // The Appshots gallery drags a path, never the bytes.
+ const byPath = {
+ ...transfer([]),
+ types: ["text/uri-list"],
+ getData: (type: string) => (type === "text/uri-list" ? "file:///C:/shots/shot.png" : ""),
+ };
+
+ await act(async () => {
+ fireEvent.drop(card, { dataTransfer: byPath });
+ });
+
+ await waitFor(() => expect(screen.getByTestId("chat-attachment-shot.png").dataset.media).toBe("image"));
+ const src = screen.getByTestId("chat-attachment-shot.png").querySelector("img")?.getAttribute("src") ?? "";
+ expect(src).toContain("/api/agent-chat/attachments/file?");
+ expect(new URLSearchParams(src.split("?")[1]).get("reference")).toBe(ATTACHMENT.reference);
+ });
+
it("sends the attachments with the sentence and then holds none", async () => {
const send = vi.fn(async () => {});
seed({ send });
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.test.ts
index 3912d76f46..f46fecf10d 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.test.ts
@@ -1,45 +1,50 @@
import {
Eye,
- FilePen,
+ FilePenLine,
+ Hand,
NotebookPen,
- ShieldCheck,
- ShieldOff,
- ShieldQuestion,
- ShieldX,
- Sparkles,
+ Shield,
+ ShieldAlert,
+ ShieldBan,
+ WandSparkles,
} from "lucide-react";
import { describe, expect, it } from "vitest";
-import { permissionModeIcon } from "./permissionIcons";
+import { isUnguardedPermissionMode, permissionModeIcon } from "./permissionIcons";
describe("permissionModeIcon", () => {
it("maps every vendor spelling of a stance onto the stance's one glyph", () => {
// Ask before acting — the unified ladder, Claude Code, and agy.
- expect(permissionModeIcon("ask")).toBe(ShieldQuestion);
- expect(permissionModeIcon("default")).toBe(ShieldQuestion);
- expect(permissionModeIcon("approve-for-me")).toBe(ShieldQuestion);
+ expect(permissionModeIcon("ask")).toBe(Hand);
+ expect(permissionModeIcon("default")).toBe(Hand);
+ expect(permissionModeIcon("approve-for-me")).toBe(Hand);
// Edits go through.
- expect(permissionModeIcon("accept-edits")).toBe(FilePen);
- expect(permissionModeIcon("acceptEdits")).toBe(FilePen);
+ expect(permissionModeIcon("accept-edits")).toBe(FilePenLine);
+ expect(permissionModeIcon("acceptEdits")).toBe(FilePenLine);
// Nothing asks.
- expect(permissionModeIcon("bypass")).toBe(ShieldOff);
- expect(permissionModeIcon("bypassPermissions")).toBe(ShieldOff);
- expect(permissionModeIcon("full-access")).toBe(ShieldOff);
- expect(permissionModeIcon("skip-permissions")).toBe(ShieldOff);
+ expect(permissionModeIcon("bypass")).toBe(ShieldAlert);
+ expect(permissionModeIcon("bypassPermissions")).toBe(ShieldAlert);
+ expect(permissionModeIcon("full-access")).toBe(ShieldAlert);
+ expect(permissionModeIcon("skip-permissions")).toBe(ShieldAlert);
// The reading stances and the runner's own judgement.
expect(permissionModeIcon("plan")).toBe(NotebookPen);
expect(permissionModeIcon("read-only")).toBe(Eye);
- expect(permissionModeIcon("auto")).toBe(Sparkles);
- expect(permissionModeIcon("dontAsk")).toBe(ShieldX);
+ expect(permissionModeIcon("auto")).toBe(WandSparkles);
+ expect(permissionModeIcon("dontAsk")).toBe(ShieldBan);
});
- it("gives an id it has never seen the column's shield, never nothing", () => {
- expect(permissionModeIcon("something-new")).toBe(ShieldCheck);
- expect(permissionModeIcon("")).toBe(ShieldCheck);
+ it("gives an id it has never seen a plain shield, never nothing", () => {
+ expect(permissionModeIcon("something-new")).toBe(Shield);
+ expect(permissionModeIcon("")).toBe(Shield);
});
it("keeps the four stances of the unified ladder visually distinct", () => {
const glyphs = ["ask", "accept-edits", "plan", "bypass"].map(permissionModeIcon);
expect(new Set(glyphs).size).toBe(glyphs.length);
});
+
+ it("flags only the stances in which nothing asks", () => {
+ expect(["bypass", "bypassPermissions", "full-access", "skip-permissions"].every(isUnguardedPermissionMode)).toBe(true);
+ expect(["ask", "default", "acceptEdits", "plan", "auto", "dontAsk"].some(isUnguardedPermissionMode)).toBe(false);
+ });
});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.ts b/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.ts
index 0c1090b502..9557db5890 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/permissionIcons.ts
@@ -1,12 +1,12 @@
import {
Eye,
- FilePen,
+ FilePenLine,
+ Hand,
NotebookPen,
- ShieldCheck,
- ShieldOff,
- ShieldQuestion,
- ShieldX,
- Sparkles,
+ Shield,
+ ShieldAlert,
+ ShieldBan,
+ WandSparkles,
type LucideIcon,
} from "lucide-react";
@@ -20,30 +20,38 @@ import {
* `read-only`, `full-access`, …). Several of those mean the same thing, so
* they wear the same glyph — a person who learned "the pen means edits go
* through" recognises it on every provider. Anything unknown falls back to
- * the column's shield so a new ladder entry is never blank.
+ * a plain shield so a new ladder entry is never blank.
*/
const GLYPHS: Record<string, LucideIcon> = {
- // Ask before acting.
- ask: ShieldQuestion,
- default: ShieldQuestion,
- "approve-for-me": ShieldQuestion,
+ // Stops and asks before acting.
+ ask: Hand,
+ default: Hand,
+ "approve-for-me": Hand,
// Edits go through, everything else asks.
- "accept-edits": FilePen,
- acceptEdits: FilePen,
- // Nothing asks.
- bypass: ShieldOff,
- bypassPermissions: ShieldOff,
- "full-access": ShieldOff,
- "skip-permissions": ShieldOff,
+ "accept-edits": FilePenLine,
+ acceptEdits: FilePenLine,
+ // Nothing asks — the one stance that deserves a warning sign.
+ bypass: ShieldAlert,
+ bypassPermissions: ShieldAlert,
+ "full-access": ShieldAlert,
+ "skip-permissions": ShieldAlert,
// Reads and plans, changes nothing.
plan: NotebookPen,
"read-only": Eye,
// The runner decides on its own.
- auto: Sparkles,
+ auto: WandSparkles,
// Never asks — and refuses what it would have asked about.
- dontAsk: ShieldX,
+ dontAsk: ShieldBan,
};
+/** Stances in which nothing stops to ask: the agent may change anything. */
+const UNGUARDED = new Set(["bypass", "bypassPermissions", "full-access", "skip-permissions"]);
+
export function permissionModeIcon(id: string): LucideIcon {
- return GLYPHS[id] ?? ShieldCheck;
+ return GLYPHS[id] ?? Shield;
+}
+
+/** True for a mode that lets the agent act with no approval at all. */
+export function isUnguardedPermissionMode(id: string): boolean {
+ return UNGUARDED.has(id);
}
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
index 0cd442c016..97acf123c5 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/useChatAttachments.ts
@@ -28,16 +28,21 @@ import {
} from "@/components/agentic/paneDrop";
import { usePaneFileDrag } from "@/components/agentic/paneFileDrag";
import { waitForNativeDrop } from "@/lib/nativeDrop";
-import { attachChatFiles, type AgentChatSurface, type ChatAttachment } from "@/lib/agentChatApi";
+import {
+ attachChatFilesIn,
+ attachmentFileUrl,
+ type AgentChatSurface,
+ type ChatAttachment,
+} from "@/lib/agentChatApi";
export interface ChatAttachments {
/** What will travel with the next message. */
attachments: ChatAttachment[];
/**
- * A local picture for each held image whose bytes passed through this
- * window (a paste, the file picker, a claimed appshot), keyed by the
- * attachment's name. A file the desktop shell handed over by path has no
- * bytes here and simply has no entry.
+ * A picture for each held image or video, keyed by the attachment's name:
+ * a local `blob:` URL when its bytes passed through this window (a paste,
+ * the file picker, a claimed appshot), else the backend's copy of the file
+ * (a drag from the Appshots gallery or Explorer arrives by path only).
*/
previews: Record<string, string>;
/** How many files are being read right now — 0 when nothing is in flight. */
@@ -81,17 +86,14 @@ export function useChatAttachments(
// Object URLs hold the picture in memory until revoked; let them go with
// the composer.
- useEffect(
- () => () => Object.values(previewsRef.current).forEach((url) => URL.revokeObjectURL(url)),
- [],
- );
+ useEffect(() => () => Object.values(previewsRef.current).forEach(revokePreview), []);
const attach = useCallback(
async (payload: PaneDropPayload) => {
if (isEmptyPayload(payload)) return;
setAnalyzing((n) => n + 1);
try {
- const found = await attachChatFiles({
+ const { attachments: found, cwd: folder } = await attachChatFilesIn({
files: payload.files,
paths: payload.paths,
sessionId,
@@ -110,11 +112,18 @@ export function useChatAttachments(
...found.filter((item) => !prev.some((held) => held.name === item.name)),
]);
const pictures = matchPreviews(found, payload.files);
+ if (folder) {
+ for (const item of found) {
+ if (!pictures[item.name] && attachmentMedia(item)) {
+ pictures[item.name] = attachmentFileUrl(folder, item.reference);
+ }
+ }
+ }
if (Object.keys(pictures).length > 0) {
setPreviews((prev) => {
const next = { ...prev };
for (const [name, url] of Object.entries(pictures)) {
- if (next[name]) URL.revokeObjectURL(next[name]);
+ if (next[name]) revokePreview(next[name]);
next[name] = url;
}
return next;
@@ -179,7 +188,7 @@ export function useChatAttachments(
setAttachments((prev) => prev.filter((a) => a.name !== name));
setPreviews((prev) => {
if (!prev[name]) return prev;
- URL.revokeObjectURL(prev[name]);
+ revokePreview(prev[name]);
const rest = { ...prev };
delete rest[name];
return rest;
@@ -189,7 +198,7 @@ export function useChatAttachments(
const clear = useCallback(() => {
setAttachments([]);
setPreviews((prev) => {
- Object.values(prev).forEach((url) => URL.revokeObjectURL(url));
+ Object.values(prev).forEach(revokePreview);
return {};
});
}, []);
@@ -207,17 +216,32 @@ export function useChatAttachments(
};
}
+const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif|bmp|ico|heic|heif|tiff?)$/i;
+const VIDEO_EXT = /\.(mp4|m4v|webm|mov)$/i;
+
+/** Whether a held file can be drawn as a picture or a video, from its name. */
+export function attachmentMedia(item: Pick<ChatAttachment, "name" | "kind">): "image" | "video" | null {
+ if (VIDEO_EXT.test(item.name)) return "video";
+ if (item.kind === "image" || IMAGE_EXT.test(item.name)) return "image";
+ return null;
+}
+
+/** Only a local object URL holds memory; a backend URL has nothing to free. */
+function revokePreview(url: string): void {
+ if (url.startsWith("blob:")) URL.revokeObjectURL(url);
+}
+
/**
- * Pair the images the backend read with the bytes that went up, for a
- * picture in the composer. The backend may store a file under another name
+ * Pair the images and videos the backend read with the bytes that went up,
+ * for a picture in the composer. The backend may store a file under another name
* (a clipboard image gets one, a clash gets a suffix), so an exact name match
* comes first and a lone image on both sides pairs by being alone. Anything
* still unpaired gets no picture rather than the wrong one.
*/
export function matchPreviews(found: ChatAttachment[], files: File[]): Record<string, string> {
if (typeof URL.createObjectURL !== "function") return {};
- const images = files.filter((f) => f.type.startsWith("image/"));
- const read = found.filter((item) => item.kind === "image");
+ const images = files.filter((f) => f.type.startsWith("image/") || f.type.startsWith("video/"));
+ const read = found.filter((item) => attachmentMedia(item) !== null);
const out: Record<string, string> = {};
const used = new Set<File>();
for (const item of read) {
diff --git a/jarvis/ui/web/frontend/src/components/ui/combobox.tsx b/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
index 098297265e..62d3589e22 100644
--- a/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
+++ b/jarvis/ui/web/frontend/src/components/ui/combobox.tsx
@@ -726,7 +726,9 @@ export function Combobox({
)}
</span>
{option.description && (
- <span className="mt-0.5 line-clamp-2 text-xs font-normal text-muted-foreground">
+ // Under the label, not under the icon: a 16 px glyph
+ // plus the row's 8 px gap.
+ <span className={cn("mt-0.5 line-clamp-2 text-xs font-normal leading-4 text-muted-foreground", option.icon && "pl-6")}>
{option.description}
</span>
)}
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 409423e3bf..368ecb57b8 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -506,6 +506,15 @@ export async function attachChatFiles(payload: {
provider?: string;
surface?: AgentChatSurface;
}): Promise<ChatAttachment[]> {
+ return (await attachChatFilesIn(payload)).attachments;
+}
+
+/** {@link attachChatFiles}, plus the folder the files landed in. */
+export async function attachChatFilesIn(payload: Parameters<typeof attachChatFiles>[0]): Promise<{
+ attachments: ChatAttachment[];
+ /** Where the copies live; "" from a backend that does not say. */
+ cwd: string;
+}> {
const form = new FormData();
for (const file of payload.files ?? []) form.append("files", file, file.name);
if (payload.paths?.length) form.append("paths", payload.paths.join("\n"));
@@ -514,11 +523,20 @@ export async function attachChatFiles(payload: {
if (payload.provider) form.append("provider", payload.provider);
if (payload.surface) form.append("surface", payload.surface);
- const data = await json<{ attachments?: ChatAttachment[] }>(
+ const data = await json<{ attachments?: ChatAttachment[]; cwd?: string }>(
await fetch("/api/agent-chat/attachments", { method: "POST", body: form }),
"attach-failed",
);
- return Array.isArray(data.attachments) ? data.attachments : [];
+ return {
+ attachments: Array.isArray(data.attachments) ? data.attachments : [],
+ cwd: typeof data.cwd === "string" ? data.cwd : "",
+ };
+}
+
+/** The attached picture or video itself, for a thumbnail (images and videos only). */
+export function attachmentFileUrl(cwd: string, reference: string): string {
+ const query = new URLSearchParams({ cwd, reference });
+ return `/api/agent-chat/attachments/file?${query.toString()}`;
}
export async function cancelAgentChatTurn(sessionId: string): Promise<void> {
diff --git a/tests/unit/agent_chat/test_chat_attachments.py b/tests/unit/agent_chat/test_chat_attachments.py
index a910f5a59b..2a4ba1c078 100644
--- a/tests/unit/agent_chat/test_chat_attachments.py
+++ b/tests/unit/agent_chat/test_chat_attachments.py
@@ -126,6 +126,55 @@ def test_a_path_inside_the_folder_is_referenced_where_it_lies(
assert not (tmp_path / ".jarvis" / "drops").exists()
+def test_an_attached_picture_is_served_back_for_its_thumbnail(
+ tmp_path: Path, described
+) -> None:
+ """A file attached by path has no bytes in the window; the route draws it."""
+ outside = tmp_path / "gallery"
+ outside.mkdir()
+ shot = outside / "appshot.png"
+ shot.write_bytes(PNG)
+ folder = tmp_path / "project"
+ folder.mkdir()
+
+ with TestClient(_app(tmp_path)) as client:
+ attached = client.post(
+ "/api/agent-chat/attachments",
+ data={"cwd": str(folder), "paths": str(shot)},
+ ).json()
+ (row,) = attached["attachments"]
+ res = client.get(
+ "/api/agent-chat/attachments/file",
+ params={"cwd": attached["cwd"], "reference": row["reference"]},
+ )
+ assert res.status_code == 200, res.text
+ assert res.headers["content-type"] == "image/png"
+ assert res.content == PNG
+
+
+def test_the_thumbnail_route_serves_nothing_outside_the_folder(tmp_path: Path) -> None:
+ folder = tmp_path / "project"
+ folder.mkdir()
+ (tmp_path / "secret.png").write_bytes(PNG)
+ (folder / "notes.txt").write_text("not a picture", encoding="utf-8")
+ (folder / "logo.svg").write_text("<svg/>", encoding="utf-8")
+
+ with TestClient(_app(tmp_path)) as client:
+ refused = [
+ '"../secret.png"',
+ f'"{tmp_path / "secret.png"}"',
+ '"notes.txt"',
+ '"logo.svg"',
+ '""',
+ ]
+ for reference in refused:
+ res = client.get(
+ "/api/agent-chat/attachments/file",
+ params={"cwd": str(folder), "reference": reference},
+ )
+ assert res.status_code == 404, reference
+
+
# ------------------------------------------------------------- composition