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(artifacts): right-click menu with delete on gallery cards
rubenluetke10-beepd6c3ef9e3699
diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.test.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.test.tsxnew file mode 100644index 0000000000..2902ace744--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.test.tsx@@ -0,0 +1,187 @@+/**+ * The Artifacts card's right-click menu.+ *+ * Contracts worth pinning:+ * - a right-click on a card opens the card's own menu, never the app-wide+ * Cut/Copy/Paste one (the event stops at the card),+ * - an artifact offers open / open in browser / save a copy / delete; a run+ * without one offers open / delete; "Show in folder" appears only where+ * native file actions exist,+ * - delete asks first, then sends DELETE for that file (an artifact) or for+ * the whole run (a run card), and the list is read again,+ * - a run that is still working cannot be deleted from its card.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import { VisualizationView } from "@/views/VisualizationView";+import type { ArtifactSummary, OutputSummary } from "@/hooks/useOutputs";++vi.mock("@/hooks/useWebSocket", () => ({+ getWSClient: () => null,+}));++afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.clearAllMocks();+});++const PAGE_PATH = "tasks/t1/artifacts/files/dashboard.html";++function file(path: string, over: Partial<ArtifactSummary> = {}): ArtifactSummary {+ return { path, size: 2048, mtime: 1_700_000_000, is_text: false, preview: null, ...over };+}++function installFetchMock(+ runs: OutputSummary[],+ artifactsBySlug: Record<string, ArtifactSummary[]>,+ { native = false }: { native?: boolean } = {},+) {+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ if (init?.method === "DELETE") {+ return { ok: true, status: 200, json: async () => ({ deleted: "run" }) };+ }+ if (url.includes("/capabilities")) {+ return {+ ok: true,+ status: 200,+ json: async () => ({ native_file_actions: native, platform: "linux" }),+ };+ }+ const artifacts = /\/api\/outputs\/([^/]+)\/artifacts/.exec(url);+ if (artifacts) {+ const slug = decodeURIComponent(artifacts[1]);+ return { ok: true, status: 200, json: async () => ({ files: artifactsBySlug[slug] ?? [] }) };+ }+ if (url.includes("/api/outputs")) {+ return { ok: true, status: 200, json: async () => ({ sessions: runs }) };+ }+ return { ok: true, status: 200, json: async () => ({}) };+ });+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+}++function renderView() {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },+ });+ return render(+ <QueryClientProvider client={client}>+ <VisualizationView />+ </QueryClientProvider>,+ );+}++function deleteCalls(fetchMock: ReturnType<typeof installFetchMock>): string[] {+ return fetchMock.mock.calls+ .filter(([, init]) => init?.method === "DELETE")+ .map(([input]) => String(input));+}++describe("Artifact card menu", () => {+ it("opens on right-click and keeps the click away from the app-wide menu", async () => {+ installFetchMock([{ slug: "mission_dash", status: "success" }], {+ mission_dash: [file(PAGE_PATH)],+ });+ const documentMenu = vi.fn();+ document.addEventListener("contextmenu", documentMenu);+ renderView();++ const card = await screen.findByTestId("visualization-artifact-row");+ fireEvent.contextMenu(card, { clientX: 120, clientY: 80 });++ expect(screen.getByTestId("artifact-card-menu")).toBeTruthy();+ expect(screen.getByTestId("artifact-menu-open")).toBeTruthy();+ expect(screen.getByTestId("artifact-menu-open-external")).toBeTruthy();+ expect(screen.getByTestId("artifact-menu-download")).toBeTruthy();+ expect(screen.queryByTestId("artifact-menu-reveal")).toBeNull();+ expect(documentMenu).not.toHaveBeenCalled();+ document.removeEventListener("contextmenu", documentMenu);+ });++ it("offers Show in folder only where native file actions exist", async () => {+ installFetchMock(+ [{ slug: "mission_dash", status: "success" }],+ { mission_dash: [file(PAGE_PATH)] },+ { native: true },+ );+ renderView();++ const card = await screen.findByTestId("visualization-artifact-row");+ // The capability answer may land after the card does.+ await waitFor(() => {+ fireEvent.contextMenu(card, { clientX: 10, clientY: 10 });+ expect(screen.getByTestId("artifact-menu-reveal")).toBeTruthy();+ });+ });++ it("deletes one artifact file after asking", async () => {+ const fetchMock = installFetchMock([{ slug: "mission_dash", status: "success" }], {+ mission_dash: [file(PAGE_PATH)],+ });+ renderView();++ const card = await screen.findByTestId("visualization-artifact-row");+ fireEvent.contextMenu(card, { clientX: 10, clientY: 10 });+ fireEvent.click(screen.getByTestId("artifact-menu-delete"));++ // Nothing is deleted before the question is answered.+ expect(screen.getByTestId("artifact-confirm-delete")).toBeTruthy();+ expect(deleteCalls(fetchMock)).toEqual([]);++ fireEvent.click(screen.getByTestId("artifact-confirm-delete-confirm"));+ await waitFor(() =>+ expect(deleteCalls(fetchMock)).toEqual([`/api/outputs/mission_dash/files/${PAGE_PATH}`]),+ );+ await waitFor(() => expect(screen.queryByTestId("artifact-confirm-delete")).toBeNull());+ });++ it("deletes a whole run from a run card", async () => {+ const fetchMock = installFetchMock(+ [{ slug: "run-text", utterance: "Write notes", status: "success" }],+ { "run-text": [file("tasks/t1/artifacts/files/notes.md", { is_text: true })] },+ );+ renderView();++ const card = await screen.findByTestId("visualization-run-row");+ fireEvent.contextMenu(card, { clientX: 10, clientY: 10 });+ expect(screen.queryByTestId("artifact-menu-download")).toBeNull();+ fireEvent.click(screen.getByTestId("artifact-menu-delete"));+ fireEvent.click(screen.getByTestId("artifact-confirm-delete-confirm"));++ await waitFor(() => expect(deleteCalls(fetchMock)).toEqual(["/api/outputs/run-text"]));+ });++ it("does not delete a run that is still working", async () => {+ const fetchMock = installFetchMock(+ [{ slug: "run-busy", utterance: "Crunch numbers", status: "running" }],+ {},+ );+ renderView();++ const card = await screen.findByTestId("visualization-run-row");+ fireEvent.contextMenu(card, { clientX: 10, clientY: 10 });+ const item = screen.getByTestId("artifact-menu-delete") as HTMLButtonElement;+ expect(item.disabled).toBe(true);++ fireEvent.keyDown(card, { key: "Delete" });+ expect(screen.queryByTestId("artifact-confirm-delete")).toBeNull();+ expect(deleteCalls(fetchMock)).toEqual([]);+ });++ it("asks before deleting when the Delete key is pressed on a card", async () => {+ installFetchMock([{ slug: "mission_dash", status: "success" }], {+ mission_dash: [file(PAGE_PATH)],+ });+ renderView();++ const card = await screen.findByTestId("visualization-artifact-row");+ fireEvent.keyDown(card, { key: "Delete" });++ expect(screen.getByTestId("artifact-confirm-delete")).toBeTruthy();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsxnew file mode 100644index 0000000000..4fa084367b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactCardMenu.tsx@@ -0,0 +1,265 @@+import {+ useEffect,+ useLayoutEffect,+ useRef,+ type KeyboardEvent as ReactKeyboardEvent,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import { Download, Eye, ExternalLink, FolderOpen, Trash2 } from "lucide-react";++import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { rowTitle, type RailRow } from "@/components/visualization/galleryModel";++/**+ * The right-click menu on an Artifacts card, and the question it asks before+ * anything is deleted.+ *+ * The desktop WebView has no native context menu, and the app-wide+ * Cut/Copy/Paste menu lives on `document`, so the card stops its own+ * right-click and opens this one instead. What it offers follows the card:+ * an artifact can be opened, opened in the browser, saved and shown in its+ * folder; a run without one can be opened and shown in its folder; anything+ * finished can be deleted. A card whose run is still working cannot be+ * deleted — its worker may be writing into that very folder — so the item is+ * there but disabled, with the reason on hover.+ */++const MENU_WIDTH = 220;+const VIEWPORT_MARGIN = 8;++export interface ArtifactMenuState {+ row: RailRow;+ x: number;+ y: number;+}++/** True while the card's run may still write into its folder. */+export function rowIsWorking(row: RailRow): boolean {+ if (row.kind === "build") return true;+ return row.run?.status === "running";+}++export function ArtifactCardMenu({+ row,+ x,+ y,+ canReveal,+ onDismiss,+ onOpen,+ onOpenExternal,+ onDownload,+ onReveal,+ onDelete,+}: {+ row: RailRow;+ x: number;+ y: number;+ /** Desktop only — a headless host has no file manager to open. */+ canReveal: boolean;+ onDismiss: () => void;+ onOpen: () => void;+ onOpenExternal: () => void;+ onDownload: () => void;+ onReveal: () => void;+ onDelete: () => void;+}) {+ const t = useT();+ const menuRef = useRef<HTMLDivElement | null>(null);+ const isVisual = row.kind === "visual";+ const working = rowIsWorking(row);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ onDismiss();+ }+ };+ const onPointerDown = (event: PointerEvent) => {+ if (!menuRef.current?.contains(event.target as Node)) onDismiss();+ };+ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("pointerdown", onPointerDown, true);+ window.addEventListener("resize", onDismiss);+ window.addEventListener("blur", onDismiss);+ document.addEventListener("scroll", onDismiss, true);+ return () => {+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("pointerdown", onPointerDown, true);+ window.removeEventListener("resize", onDismiss);+ window.removeEventListener("blur", onDismiss);+ document.removeEventListener("scroll", onDismiss, true);+ };+ }, [onDismiss]);++ useLayoutEffect(() => {+ const node = menuRef.current;+ if (!node) return;+ const { width, height } = node.getBoundingClientRect();+ const maxX = window.innerWidth - width - VIEWPORT_MARGIN;+ const maxY = window.innerHeight - height - VIEWPORT_MARGIN;+ node.style.left = `${Math.max(VIEWPORT_MARGIN, Math.min(x, maxX))}px`;+ node.style.top = `${Math.max(VIEWPORT_MARGIN, Math.min(y, maxY))}px`;+ node.style.visibility = "visible";+ node.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus();+ }, [x, y]);++ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ event.preventDefault();+ const items = Array.from(+ menuRef.current?.querySelectorAll<HTMLButtonElement>("button:not([disabled])") ?? [],+ );+ if (!items.length) return;+ const current = items.indexOf(document.activeElement as HTMLButtonElement);+ const step = event.key === "ArrowDown" ? 1 : -1;+ items[(current + step + items.length) % items.length]?.focus();+ };++ return createPortal(+ <div+ ref={menuRef}+ role="menu"+ aria-label={t("visualization.menu_aria")}+ data-testid="artifact-card-menu"+ onKeyDown={onMenuKeyDown}+ onContextMenu={(event) => event.preventDefault()}+ style={{ width: MENU_WIDTH, visibility: "hidden" }}+ className="fixed z-[100] overflow-hidden rounded-lg border border-border bg-popover py-1 shadow-float"+ >+ <MenuItem icon={<Eye />} testId="artifact-menu-open" onClick={onOpen}>+ {t("visualization.menu_open")}+ </MenuItem>+ {isVisual && (+ <MenuItem icon={<ExternalLink />} testId="artifact-menu-open-external" onClick={onOpenExternal}>+ {t("visualization.open_external")}+ </MenuItem>+ )}+ {isVisual && (+ <MenuItem icon={<Download />} testId="artifact-menu-download" onClick={onDownload}>+ {t("visualization.download")}+ </MenuItem>+ )}+ {canReveal && row.kind !== "build" && (+ <MenuItem icon={<FolderOpen />} testId="artifact-menu-reveal" onClick={onReveal}>+ {t("visualization.reveal")}+ </MenuItem>+ )}+ <div role="separator" className="my-1 h-px bg-border" />+ <MenuItem+ icon={<Trash2 />}+ testId="artifact-menu-delete"+ onClick={onDelete}+ disabled={working}+ title={working ? t("visualization.delete_running") : undefined}+ destructive+ >+ {t("visualization.delete")}+ </MenuItem>+ </div>,+ document.body,+ );+}++function MenuItem({+ icon,+ testId,+ onClick,+ disabled = false,+ title,+ destructive = false,+ children,+}: {+ icon: ReactNode;+ testId: string;+ onClick: () => void;+ disabled?: boolean;+ title?: string;+ destructive?: boolean;+ children: ReactNode;+}) {+ return (+ <button+ type="button"+ role="menuitem"+ data-testid={testId}+ onClick={onClick}+ disabled={disabled}+ title={title}+ className={cn(+ "flex w-full items-center gap-2.5 px-3 py-1.5 text-left text-sm transition-colors",+ "focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",+ "[&_svg]:h-4 [&_svg]:w-4 [&_svg]:shrink-0",+ destructive+ ? "text-destructive hover:bg-destructive/10 focus-visible:bg-destructive/10"+ : "text-foreground hover:bg-secondary focus-visible:bg-secondary [&_svg]:text-muted-foreground",+ )}+ >+ <span aria-hidden className="contents">+ {icon}+ </span>+ {children}+ </button>+ );+}++/** "Delete this?" — the one step between a right-click and a gone folder. */+export function ConfirmDeleteArtifact({+ row,+ busy,+ onCancel,+ onConfirm,+}: {+ row: RailRow;+ busy: boolean;+ onCancel: () => void;+ onConfirm: () => void;+}) {+ const t = useT();+ const title = fill(t("visualization.delete_title"), { name: rowTitle(row) });+ return createPortal(+ <div+ role="dialog"+ aria-modal="true"+ aria-label={title}+ data-testid="artifact-confirm-delete"+ className="fixed inset-0 z-[100] flex items-center justify-center bg-background/80 p-6 backdrop-blur-sm"+ onClick={(event) => {+ if (event.target === event.currentTarget && !busy) onCancel();+ }}+ onKeyDown={(event) => {+ if (event.key === "Escape" && !busy) onCancel();+ }}+ >+ <div className="w-full max-w-sm rounded-lg bg-popover p-5 shadow-float">+ <h3 className="font-display text-base font-semibold [overflow-wrap:anywhere]">{title}</h3>+ <p className="mt-2 text-sm text-muted-foreground">+ {t(row.kind === "visual" ? "visualization.delete_body_file" : "visualization.delete_body_run")}+ </p>+ <div className="mt-5 flex items-center justify-end gap-2">+ <button+ type="button"+ className="rounded-lg px-3 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ autoFocus+ disabled={busy}+ onClick={onCancel}+ >+ {t("visualization.delete_cancel")}+ </button>+ <button+ type="button"+ data-testid="artifact-confirm-delete-confirm"+ className="rounded-lg bg-destructive px-3 py-2 text-sm font-medium text-destructive-foreground transition-opacity hover:opacity-90 disabled:opacity-50"+ disabled={busy}+ onClick={onConfirm}+ >+ {t("visualization.delete_confirm")}+ </button>+ </div>+ </div>+ </div>,+ document.body,+ );+}diff --git a/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx b/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsxindex 69d3981056..31aa42e096 100644--- a/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx+++ b/jarvis/ui/web/frontend/src/components/visualization/ArtifactGallery.tsx@@ -1,4 +1,14 @@-import { useEffect, useRef, useState, type DragEvent, type ReactNode, type RefObject } from "react";+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type DragEvent,+ type MouseEvent as ReactMouseEvent,+ type ReactNode,+ type RefObject,+} from "react";+import { useQueryClient } from "@tanstack/react-query";import {FileImage,FileText,@@ -19,7 +29,17 @@ import { useT, useUiLanguage } from "@/i18n";import { useThemeValue } from "@/hooks/useTheme";import { cn } from "@/lib/utils";import { endMissionDrag, startMissionDrag } from "@/lib/missionDnd";-import type { OutputStatus } from "@/hooks/useOutputs";+import { openExternalUrl } from "@/lib/openExternal";+import { useEventStore } from "@/store/events";+import {+ DeleteOutputError,+ artifactDownloadUrl,+ deleteOutput,+ revealArtifact,+ revealOutput,+ useOutputsCapabilities,+ type OutputStatus,+} from "@/hooks/useOutputs";import { artifactPageUrl, type VisualArtifact, type VisualKind } from "@/hooks/useVisualArtifacts";import {RAIL_FILTERS,@@ -32,6 +52,12 @@ import {type RailFilter,type RailRow,} from "@/components/visualization/galleryModel";+import {+ ArtifactCardMenu,+ ConfirmDeleteArtifact,+ rowIsWorking,+ type ArtifactMenuState,+} from "@/components/visualization/ArtifactCardMenu";/*** The Artifacts library — every artifact as a card with the artifact itself@@ -196,6 +222,7 @@ export function ArtifactGallery({}) {const t = useT();const empty = groups.every((group) => group.rows.length === 0);+ const actions = useCardActions();return (<ScrollArea className="min-h-0 flex-1">@@ -224,7 +251,13 @@ export function ArtifactGallery({</h2><CardGrid>{group.rows.map((row) => (- <ArtifactCard key={row.key} row={row} onOpen={onOpen} />+ <ArtifactCard+ key={row.key}+ row={row}+ onOpen={onOpen}+ onMenu={actions.openMenu}+ onDeleteKey={actions.askDelete}+ />))}</CardGrid></section>@@ -232,10 +265,134 @@ export function ArtifactGallery({)}{footer}</div>+ {actions.menu && (+ <ArtifactCardMenu+ row={actions.menu.row}+ x={actions.menu.x}+ y={actions.menu.y}+ canReveal={actions.canReveal}+ onDismiss={actions.closeMenu}+ onOpen={() => actions.run(onOpen)}+ onOpenExternal={() => actions.run(actions.openExternal)}+ onDownload={() => actions.run(actions.download)}+ onReveal={() => actions.run(actions.reveal)}+ onDelete={() => actions.run(actions.askDelete)}+ />+ )}+ {actions.pendingDelete && (+ <ConfirmDeleteArtifact+ row={actions.pendingDelete}+ busy={actions.deleting}+ onCancel={actions.cancelDelete}+ onConfirm={() => void actions.confirmDelete()}+ />+ )}</ScrollArea>);}+/**+ * What a card's right-click menu does. One menu and one pending delete for+ * the whole gallery — the card only reports where it was clicked.+ */+function useCardActions() {+ const t = useT();+ const theme = useThemeValue();+ const queryClient = useQueryClient();+ const pushToast = useEventStore((s) => s.pushToast);+ const capabilities = useOutputsCapabilities();+ const [menu, setMenu] = useState<ArtifactMenuState | null>(null);+ const [pendingDelete, setPendingDelete] = useState<RailRow | null>(null);+ const [deleting, setDeleting] = useState(false);++ const openMenu = useCallback((row: RailRow, x: number, y: number) => setMenu({ row, x, y }), []);+ const closeMenu = useCallback(() => setMenu(null), []);++ /** Close the menu, then act on the row it was opened for. */+ const run = useCallback(+ (action: (row: RailRow) => void) => {+ if (!menu) return;+ setMenu(null);+ action(menu.row);+ },+ [menu],+ );++ const openExternal = useCallback(+ (row: RailRow) => {+ if (row.kind !== "visual") return;+ const { visual } = row;+ const url =+ visual.kind === "page" ? `${artifactPageUrl(visual.slug, visual.path)}?theme=${theme}` : visual.url;+ void openExternalUrl(`${window.location.origin}${url}`);+ },+ [theme],+ );++ const download = useCallback((row: RailRow) => {+ if (row.kind !== "visual") return;+ const link = document.createElement("a");+ link.href = artifactDownloadUrl(row.visual.slug, row.visual.path);+ link.download = row.visual.name;+ document.body.appendChild(link);+ link.click();+ link.remove();+ }, []);++ const reveal = useCallback(+ (row: RailRow) => {+ const request =+ row.kind === "visual"+ ? revealArtifact(row.visual.slug, row.visual.path)+ : revealOutput(row.run.slug);+ request.catch(() => pushToast("error", t("visualization.reveal_failed")));+ },+ [pushToast, t],+ );++ const askDelete = useCallback((row: RailRow) => {+ if (!rowIsWorking(row)) setPendingDelete(row);+ }, []);+ const cancelDelete = useCallback(() => {+ if (!deleting) setPendingDelete(null);+ }, [deleting]);++ const confirmDelete = useCallback(async () => {+ const row = pendingDelete;+ if (!row || row.kind === "build") return;+ const slug = row.kind === "visual" ? row.visual.slug : row.run.slug;+ setDeleting(true);+ try {+ await deleteOutput(slug, row.kind === "visual" ? row.visual.path : null);+ setPendingDelete(null);+ pushToast("success", t("visualization.deleted"));+ } catch (error) {+ const running = error instanceof DeleteOutputError && error.status === 409;+ pushToast("error", t(running ? "visualization.delete_running" : "visualization.delete_failed"));+ } finally {+ setDeleting(false);+ void queryClient.invalidateQueries({ queryKey: ["outputs"] });+ void queryClient.invalidateQueries({ queryKey: ["output-artifacts", slug] });+ }+ }, [pendingDelete, pushToast, queryClient, t]);++ return {+ menu,+ openMenu,+ closeMenu,+ run,+ canReveal: capabilities.data?.native_file_actions === true,+ openExternal,+ download,+ reveal,+ pendingDelete,+ deleting,+ askDelete,+ cancelDelete,+ confirmDelete,+ };+}+function CardGrid({ children }: { children: ReactNode }) {return (<div className="grid grid-cols-[repeat(auto-fill,minmax(20rem,1fr))] gap-5">{children}</div>@@ -272,7 +429,17 @@ const ROW_TESTID: Record<RailRow["kind"], string> = {run: "visualization-run-row",};-function ArtifactCard({ row, onOpen }: { row: RailRow; onOpen: (row: RailRow) => void }) {+function ArtifactCard({+ row,+ onOpen,+ onMenu,+ onDeleteKey,+}: {+ row: RailRow;+ onOpen: (row: RailRow) => void;+ onMenu: (row: RailRow, x: number, y: number) => void;+ onDeleteKey: (row: RailRow) => void;+}) {const t = useT();const language = useUiLanguage();const title = rowTitle(row);@@ -292,10 +459,31 @@ function ArtifactCard({ row, onOpen }: { row: RailRow; onOpen: (row: RailRow) =>}: {};+ const onContextMenu = (event: ReactMouseEvent<HTMLButtonElement>) => {+ // The app-wide Cut/Copy/Paste menu lives on document; a card offers its+ // own actions instead. The menu key reports no pointer, so the menu then+ // opens at the card's corner.+ event.preventDefault();+ event.stopPropagation();+ if (event.clientX === 0 && event.clientY === 0) {+ const box = event.currentTarget.getBoundingClientRect();+ onMenu(row, box.left + 16, box.top + 16);+ } else {+ onMenu(row, event.clientX, event.clientY);+ }+ };+return (<buttontype="button"onClick={() => onOpen(row)}+ onContextMenu={onContextMenu}+ onKeyDown={(event) => {+ if (event.key === "Delete" && !event.altKey && !event.ctrlKey && !event.metaKey) {+ event.preventDefault();+ onDeleteKey(row);+ }+ }}data-testid={ROW_TESTID[row.kind]}data-kind={row.kind === "visual" ? row.visual.kind : undefined}data-status={row.kind === "run" ? status : undefined}diff --git a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.tsindex 6377b89644..dbdd5c5c46 100644--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts@@ -359,6 +359,40 @@ export async function revealArtifact(slug: string, path: string): Promise<void>if (!r.ok) throw new Error(`HTTP ${r.status}`);}+/** Open a run's folder in the OS file manager (desktop only). */+export async function revealOutput(slug: string): Promise<void> {+ const r = await fetch(`/api/outputs/${encodeURIComponent(slug)}/open`, { method: "POST" });+ if (!r.ok) throw new Error(`HTTP ${r.status}`);+}++// --- Delete -----------------------------------------------------------------++/** A delete the server refused; `status` 409 means the run is still working. */+export class DeleteOutputError extends Error {+ constructor(readonly status: number) {+ super(`HTTP ${status}`);+ }+}++/**+ * What a delete removed. Deleting a run's last artifact takes the run with+ * it (`"run"`), so the card does not come back as an empty output.+ */+export interface DeleteOutputResult {+ deleted: "file" | "run";+}++/** Delete a whole run — `path` null — or one of its artifact files. */+export async function deleteOutput(slug: string, path: string | null): Promise<DeleteOutputResult> {+ const url =+ path === null+ ? `/api/outputs/${encodeURIComponent(slug)}`+ : `/api/outputs/${encodeURIComponent(slug)}/files/${encodeArtifactPath(path)}`;+ const r = await fetch(url, { method: "DELETE" });+ if (!r.ok) throw new DeleteOutputError(r.status);+ return (await r.json()) as DeleteOutputResult;+}+// --- "Open with" chooser --------------------------------------------------/** One launchable app in the "open with" chooser. `id` is "default",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 7d35769d36..b5f0bee118 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4588,6 +4588,17 @@"download": "Kopie speichern","reveal": "Im Ordner zeigen","reveal_failed": "Die Datei konnte nicht im Ordner gezeigt werden.",+ "menu_aria": "Aktionen für dieses Artefakt",+ "menu_open": "Öffnen",+ "delete": "Löschen",+ "delete_title": "„{name}“ löschen?",+ "delete_body_file": "Dieses Artefakt wird endgültig von deinem Computer gelöscht. Das lässt sich nicht rückgängig machen.",+ "delete_body_run": "Dieser Lauf und alles, was er erstellt hat, werden endgültig von deinem Computer gelöscht. Das lässt sich nicht rückgängig machen.",+ "delete_cancel": "Behalten",+ "delete_confirm": "Löschen",+ "deleted": "Gelöscht.",+ "delete_failed": "Das konnte nicht gelöscht werden.",+ "delete_running": "Dieser Lauf arbeitet noch. Stopp ihn zuerst, dann kannst du ihn löschen.","open_from_agent": "Artefakte","open_from_agent_hint": "Zeigt die Seiten und Bilder, die die letzten Durchläufe erzeugt haben."},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex bfe1ababbf..7dfd6f5673 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4621,6 +4621,17 @@"download": "Save a copy","reveal": "Show in folder","reveal_failed": "That file could not be shown in the folder.",+ "menu_aria": "Artifact actions",+ "menu_open": "Open",+ "delete": "Delete",+ "delete_title": "Delete “{name}”?",+ "delete_body_file": "This artifact is removed from your computer for good. This cannot be undone.",+ "delete_body_run": "This run and everything it produced are removed from your computer for good. This cannot be undone.",+ "delete_cancel": "Keep it",+ "delete_confirm": "Delete",+ "deleted": "Deleted.",+ "delete_failed": "That could not be deleted.",+ "delete_running": "This run is still working. Stop it first, then delete it.","open_from_agent": "Artifacts","open_from_agent_hint": "Show the pages and pictures the latest runs produced."},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 3ffca4e705..a766aa5094 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4588,6 +4588,17 @@"download": "Guardar una copia","reveal": "Mostrar en la carpeta","reveal_failed": "No se pudo mostrar el archivo en la carpeta.",+ "menu_aria": "Acciones del artefacto",+ "menu_open": "Abrir",+ "delete": "Eliminar",+ "delete_title": "¿Eliminar «{name}»?",+ "delete_body_file": "Este artefacto se elimina de tu ordenador para siempre. No se puede deshacer.",+ "delete_body_run": "Esta ejecución y todo lo que produjo se eliminan de tu ordenador para siempre. No se puede deshacer.",+ "delete_cancel": "Conservar",+ "delete_confirm": "Eliminar",+ "deleted": "Eliminado.",+ "delete_failed": "No se pudo eliminar.",+ "delete_running": "Esta ejecución sigue en marcha. Detenla primero y luego elimínala.","open_from_agent": "Artefactos","open_from_agent_hint": "Muestra las páginas e imágenes que produjeron las últimas ejecuciones."},diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex dc2b83ed4d..56e54c7cff 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -1400,3 +1400,135 @@ async def open_output(slug: str, request: Request) -> dict[str, Any]:if not opened:return {"opened": False, "path": str(target), "reason": "open failed"}return {"opened": True, "path": str(target)}+++# --- Delete -----------------------------------------------------------------+# The Artifacts library's right-click "Delete". A card is either one artifact+# file or a whole run, so there are two routes. Both refuse a run that is still+# working (its worker may be writing into the very folder) and both stay inside+# the same sandbox as every other route here: a slug resolves inside an outputs+# root, a file path must be a genuine deliverable.+++async def _run_is_live(request: Request, slug: str) -> bool:+ """True while the mission behind ``slug`` has not reached a terminal state.++ Only ``mission_<short>`` dirs map to a mission row; any other run (a+ standalone visualisation) finished the moment its folder existed. Without+ a mission manager nothing can be running. A failing lookup raises 503: we+ cannot prove the worker is done, so we do not pull the folder from under it.+ """+ prefix = _mission_id_prefix_for_dir(slug)+ mgr = getattr(request.app.state, "mission_manager", None)+ if prefix is None or mgr is None:+ return False+ try:+ cur = await mgr.store.conn.execute(+ "SELECT state FROM missions WHERE id LIKE ? ORDER BY updated_ms DESC LIMIT 1",+ (f"{prefix}%",),+ )+ row = await cur.fetchone()+ await cur.close()+ except Exception as exc: # noqa: BLE001 - any DB failure means "cannot confirm"+ logger.warning("outputs: liveness lookup failed for %s: %s", slug, exc)+ raise HTTPException(+ status_code=503, detail="could not confirm the run has finished"+ ) from exc+ return row is not None and str(row[0]) not in _TERMINAL_STATE_VALUES+++def _force_rmtree(path: Path) -> None:+ """``shutil.rmtree`` that also removes read-only files.++ Workers leave read-only files behind (git objects, copied installers); on+ Windows a plain rmtree stops at the first one with "Access is denied".+ Clearing the read-only bit and retrying is the documented recipe.+ """+ import shutil+ import stat+ import sys++ def _retry(func: Any, target: str, _exc: object) -> None:+ os.chmod(target, stat.S_IWRITE)+ func(target)++ if sys.version_info >= (3, 12):+ shutil.rmtree(path, onexc=_retry)+ else:+ shutil.rmtree(path, onerror=_retry)+++def _delete_run_dirs(request: Request, slug: str) -> int:+ """Remove ``slug`` from every readable outputs root; return how many went.++ Every root, not only the canonical one: a retained legacy copy of the same+ slug would otherwise surface again on the next listing.+ """+ removed = 0+ for candidate_root in _outputs_roots(request):+ root = candidate_root.resolve()+ target = (root / slug).resolve()+ if target == root or not target.is_relative_to(root) or not target.is_dir():+ continue+ _force_rmtree(target)+ removed += 1+ return removed+++def _prune_empty_parents(start: Path, stop: Path) -> None:+ """Remove now-empty folders from ``start`` up to (not including) ``stop``."""+ current = start+ while current != stop and current.is_relative_to(stop):+ try:+ current.rmdir()+ except OSError:+ return+ current = current.parent++[email protected]("/{slug}")+async def delete_output(slug: str, request: Request) -> dict[str, Any]:+ """Delete a whole run: its folder and everything it produced."""+ _resolve_output_dir(request, slug)+ if await _run_is_live(request, slug):+ raise HTTPException(status_code=409, detail="run is still working")+ try:+ removed = await asyncio.to_thread(_delete_run_dirs, request, slug)+ except OSError as exc:+ logger.warning("outputs: deleting run %s failed: %s", slug, exc)+ raise HTTPException(status_code=500, detail=f"delete failed: {exc}") from exc+ logger.info("outputs: deleted run %s (%d folder(s))", slug, removed)+ return {"deleted": "run", "slug": slug}++[email protected]("/{slug}/files/{path:path}")+async def delete_output_artifact(slug: str, path: str, request: Request) -> dict[str, Any]:+ """Delete one artifact file.++ When that was the run's last deliverable the whole run goes with it: a run+ with nothing left to show would come back as an empty "Output" card, which+ is not what deleting the card the user right-clicked means.+ """+ target = _resolve_artifact_target(request, slug, path)+ if await _run_is_live(request, slug):+ raise HTTPException(status_code=409, detail="run is still working")+ base = _resolve_output_dir(request, slug)+ rel_parts = target.relative_to(base).parts+ # tasks/<id>/artifacts/files — the deliverable root this file sits under.+ files_root = base.joinpath(*rel_parts[:4])++ def _delete() -> str:+ target.unlink()+ _prune_empty_parents(target.parent, files_root)+ if _count_deliverables(base) == 0:+ _delete_run_dirs(request, slug)+ return "run"+ return "file"++ try:+ deleted = await asyncio.to_thread(_delete)+ except OSError as exc:+ logger.warning("outputs: deleting %s/%s failed: %s", slug, path, exc)+ raise HTTPException(status_code=500, detail=f"delete failed: {exc}") from exc+ logger.info("outputs: deleted %s/%s (%s)", slug, path, deleted)+ return {"deleted": deleted, "slug": slug, "path": path}diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex 2ed9ab6610..a7284d6008 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -1661,3 +1661,133 @@ def test_graph_page_traversal_slug_is_rejected(app):with TestClient(app) as client:r = client.get("/api/outputs/..%2F..%2Fetc/graph")assert r.status_code in (400, 404)+++# --- DELETE routes (Artifacts right-click "Delete") ---------------------------+++def test_delete_artifact_keeps_run_with_other_deliverables(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ page = _make_deliverable(root, "019ed2dfd0fab1234", "page.html", "<p>x</p>")+ _make_deliverable(root, "019ed2dfd0fab1234", "notes.md", "# notes")+ client = TestClient(app)++ r = client.delete(f"/api/outputs/{slug}/files/{page}")++ assert r.status_code == 200+ assert r.json()["deleted"] == "file"+ assert not (root / slug / page).exists()+ assert (root / slug / "tasks/019edeadbeef/artifacts/files/notes.md").is_file()+++def test_delete_last_artifact_removes_the_whole_run(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ page = _make_deliverable(root, "019ed2dfd0fab1234", "page.html", "<p>x</p>")+ _seed(root / slug / "reflections.md", "scaffolding")+ client = TestClient(app)++ r = client.delete(f"/api/outputs/{slug}/files/{page}")++ assert r.status_code == 200+ assert r.json()["deleted"] == "run"+ assert not (root / slug).exists()+++def test_delete_artifact_refuses_scaffolding_and_traversal(app):+ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ _seed(root / slug / "reflections.md", "secret")+ outside = _seed(root / "keep.txt", "keep")+ client = TestClient(app)++ assert client.delete(f"/api/outputs/{slug}/files/reflections.md").status_code == 404+ assert (+ client.delete(+ f"/api/outputs/{slug}/files/tasks/x/artifacts/files/..%2f..%2f..%2f..%2fkeep.txt"+ ).status_code+ == 404+ )+ assert (root / slug / "reflections.md").is_file()+ assert outside.is_file()+++def test_delete_run_removes_folder_from_every_root(app, tmp_path: Path):+ canonical = tmp_path / "jarvis-agent-outputs"+ legacy = tmp_path / "sub-agents-outputs"+ mission_id = "019e3600-a84e-7000-8000-000000000097"+ for root in (canonical, legacy):+ _seed(_make_mission_dir(root, mission_id) / "tasks/t/artifacts/files/a.md", "a")+ app.state.outputs_root = canonical+ app.state.outputs_roots = (canonical, legacy)+ slug = f"mission_{mission_id[:13]}"+ client = TestClient(app)++ r = client.delete(f"/api/outputs/{slug}")++ assert r.status_code == 200+ assert not (canonical / slug).exists()+ assert not (legacy / slug).exists()+++def test_delete_run_removes_read_only_files(app):+ import os+ import stat++ root = Path(app.state.outputs_root)+ slug = "mission_019ed2dfd0fab"+ rel = _make_deliverable(root, "019ed2dfd0fab1234", "locked.md", "x")+ os.chmod(root / slug / rel, stat.S_IREAD)+ client = TestClient(app)++ r = client.delete(f"/api/outputs/{slug}")++ assert r.status_code == 200+ assert not (root / slug).exists()+++def test_delete_unknown_or_escaping_slug_is_refused(app):+ root = Path(app.state.outputs_root)+ client = TestClient(app)++ assert client.delete("/api/outputs/mission_0000000000000").status_code == 404+ assert client.delete("/api/outputs/..").status_code in (400, 404, 405)+ assert root.is_dir()+++async def test_delete_refuses_a_running_mission(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ mission_id = "019e3600-b000-7000-8000-000000000042"+ session = _make_mission_dir(tmp_path, mission_id)+ rel = "tasks/t/artifacts/files/page.html"+ _seed(session / rel, "<p>x</p>")+ await _insert_mission(db_conn, mission_id=mission_id, state="RUNNING")++ with TestClient(app) as client:+ run = client.delete(f"/api/outputs/{session.name}")+ file = client.delete(f"/api/outputs/{session.name}/files/{rel}")++ assert run.status_code == 409+ assert file.status_code == 409+ assert (session / rel).is_file()+++async def test_delete_allows_a_finished_mission(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ mission_id = "019e3600-b000-7000-8000-000000000043"+ session = _make_mission_dir(tmp_path, mission_id)+ _seed(session / "tasks/t/artifacts/files/page.html", "<p>x</p>")+ await _insert_mission(db_conn, mission_id=mission_id, state="APPROVED")++ with TestClient(app) as client:+ r = client.delete(f"/api/outputs/{session.name}")+ listing = client.get("/api/outputs")++ assert r.status_code == 200+ assert not session.exists()+ assert listing.json()["sessions"] == []