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(appshot): give the editor CleanShot X's window and a drag-out handle
rubenluetke10-beep0b8e32b75983
diff --git a/docs/appshots.md b/docs/appshots.mdindex eccd5cf3b1..c0247c852e 100644--- a/docs/appshots.md+++ b/docs/appshots.md@@ -77,9 +77,17 @@ the card only opens the editor and shares nothing.## The editorThe editor follows CleanShot X's annotate tool — same tools, same one-letter-keys — in this app's own look. It opens from the corner card or from-**Edit** on the last appshot (Settings → Appshots), as a full-window layer-over the current view.+keys, the same window shape — in this app's own look. It opens from the+corner card or from **Edit** on the last appshot (Settings → Appshots), as a+floating rounded window over the dimmed app; nothing navigates away.++- **Top bar:** close, crop and background, the tools as pills, the colour+ menu (presets + any colour) and the size slider, then **Save** and+ **Done**.+- **Options capsule:** under the top bar, only for tools that have options+ (text style, pixelate or blur, crop ratio, background) or a hint.+- **Bottom bar:** zoom (Fit, 50 %, 100 %, 200 %), undo and redo; a **Drag me**+ handle in the middle; delete (with a selection), save and copy on the right.| Key | Tool | What it does ||---|---|---|@@ -96,17 +104,21 @@ over the current view.| B | Background | Frames the picture on a backdrop (eight presets, padding, corner radius, shadow); applied on copy, save and use. |Colours: eight presets plus any colour from the system picker; the last one-is remembered. Sizes: 1 / 2 / 3. History: Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y-(⌘ on macOS).+is remembered. Sizes: the slider or keys 1–5. History: Ctrl+Z, Ctrl+Shift+Z+or Ctrl+Y (⌘ on macOS).Results: **Copy** (Ctrl+C) puts the PNG on the clipboard — natively through`POST /api/appshot/clipboard` on the desktop, the browser clipboardelsewhere. **Save** (Ctrl+S) writes it to Downloads through the backend(the desktop WebView drops browser downloads) and the toast offers "Show in-folder". **Use this version** (Ctrl+Enter) replaces the held appshot so the-next message carries the edit (a picture already sent into a voice call stays-as it was). Escape cancels a stroke, then a selection, then closes; with-unsaved edits it asks first.+folder". **Done** (Ctrl+Enter) replaces the held appshot so the next+message carries the edit (a picture already sent into a voice call stays+as it was). **Drag me** writes the finished picture to+`<temp>/jarvis-appshots/` the moment it is pressed and hands it to the native+drag bridge while the button is held, so it drops into any app as a real+file (Windows and macOS; Linux has no drag bridge yet, the handle is hidden+there and Save + "Show in folder" stand in). Escape closes a menu, cancels a+stroke, clears a selection, then closes; with unsaved edits it asks first.### Compared with CleanShot X@@ -127,6 +139,7 @@ reason.| Combine images, editable project file | Not done || Capture area / window / fullscreen, freeze, magnifier, crosshair | Elsewhere: the area picker and the window shortcut ([Selecting an area](#selecting-an-area)); no fullscreen mode || Quick Access Overlay (copy / save / annotate / drag after capture) | Elsewhere: the corner card (click = editor, drag = file) |+| Editor window: drag handle, zoom, Save / Done | Done: "Drag me" (Windows, macOS), zoom Fit/50/100/200 %, Save to Downloads, Done = use in the next message || Scrolling capture, self-timer | Not done (the page's "in 3 s" button is the only timer) || Screen recording, video editor, GIF | Not done || Cloud upload and sharing | Not done — appshots stay on this machine by design |diff --git a/jarvis/appshot/dragfile.py b/jarvis/appshot/dragfile.pynew file mode 100644index 0000000000..69c6748d6f--- /dev/null+++ b/jarvis/appshot/dragfile.py@@ -0,0 +1,52 @@+"""The one place an appshot touches disk: a file for a drag into another app.++A WebView cannot drag a real file out, so the native drag bridge+(``jarvis/ui/native_drag.py``) needs a path. The corner card writes its+picture here when it is dragged, and the editor's "Drag me" handle writes the+edited picture here the moment the user presses it. Nothing is written+otherwise; files older than an hour are removed on the next write, so the+folder never grows (see ``docs/appshots.md``).+"""++from __future__ import annotations++import logging+import tempfile+import time+from contextlib import suppress+from pathlib import Path++log = logging.getLogger(__name__)++#: Files older than this are removed before the next one is written.+MAX_AGE_S = 3600.0+++def drag_folder() -> Path:+ return Path(tempfile.gettempdir()) / "jarvis-appshots"+++def write_drag_file(png: bytes, *, now: float | None = None) -> Path | None:+ """Write ``png`` for one drag and return its path, or None on failure."""+ folder = drag_folder()+ moment = time.time() if now is None else now+ try:+ folder.mkdir(parents=True, exist_ok=True)+ for old in folder.glob("appshot-*.png"):+ with suppress(OSError): # a file still open elsewhere stays+ if old.stat().st_mtime < moment - MAX_AGE_S:+ old.unlink()+ stem = time.strftime("appshot-%Y%m%d-%H%M%S", time.localtime(moment))+ path = folder / f"{stem}.png"+ counter = 1+ while path.exists():+ counter += 1+ path = folder / f"{stem}-{counter}.png"+ path.write_bytes(png)+ return path+ except OSError as exc:+ log.warning("appshot: could not write the drag file (%s)", exc)+ return None+++__all__ = ["MAX_AGE_S", "drag_folder", "write_drag_file"]diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 4ea0ed82ea..ce5863368e 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -5868,9 +5868,12 @@ class DesktopApp:try:from pathlib import Path as _Path+ from jarvis.appshot.dragfile import drag_folderfrom jarvis.ui.native_drag import install_native_drag- install_native_drag(allowed_base_dirs=[_Path.home() / "Downloads"])+ # Downloads for saved files; the appshot drag folder for the+ # editor's "Drag me" handle (jarvis/appshot/dragfile.py).+ install_native_drag(allowed_base_dirs=[_Path.home() / "Downloads", drag_folder()])except Exception: # noqa: BLE001, S110 - the drag bridge is never load-bearingpassdiff --git a/jarvis/ui/web/appshot_routes.py b/jarvis/ui/web/appshot_routes.pyindex a87c6e8d46..f04a9c1651 100644--- a/jarvis/ui/web/appshot_routes.py+++ b/jarvis/ui/web/appshot_routes.py@@ -9,13 +9,15 @@ Endpoints (mounted by the WebServer in ``_build_app()``):GET /api/appshot/latest/image → its picture (never cached).PUT /api/appshot/latest/image → replace it with the editor's version.POST /api/appshot/clipboard → copy the editor's PNG natively (desktop only).+ POST /api/appshot/drag-file → write it for a native drag out (desktop only).GET /api/appshot/pending → the appshot waiting for the next message.POST /api/appshot/pending/claim → hand that one to the chat composer.DELETE /api/appshot → forget every held appshot now.Under the CLI-first contract every action here is also a``jarvis api appshot <op>`` command. Pixels stay in memory-(``jarvis.appshot.store``); nothing here writes an image to disk.+(``jarvis.appshot.store``); the only image written to disk is the one a+user drags out of the editor (``/drag-file``, see ``jarvis.appshot.dragfile``)."""from __future__ import annotations@@ -269,6 +271,30 @@ async def copy_to_clipboard(request: Request) -> dict[str, Any]:return {"copied": True}[email protected]("/drag-file")+async def drag_file(request: Request) -> dict[str, Any]:+ """Write the editor's PNG for a native drag and return its path.++ Called the moment the user presses the editor's "Drag me" handle — the+ only time an edited appshot touches disk (``jarvis.appshot.dragfile``).+ Desktop only: the path must be on the machine the drag starts from.+ """+ if not bool(getattr(request.app.state, "native_file_actions", False)):+ raise HTTPException(status_code=404, detail="native-drag-disabled")+ body = await request.body()+ if not body or len(body) > _MAX_EDIT_BYTES:+ raise HTTPException(status_code=413, detail="The picture is empty or too large.")+ from jarvis.appshot.dragfile import write_drag_file # noqa: PLC0415+ from jarvis.platform.clipboard_image import is_png # noqa: PLC0415++ if not is_png(body):+ raise HTTPException(status_code=400, detail="The picture is not a PNG.")+ path = await asyncio.to_thread(write_drag_file, body)+ if path is None:+ raise HTTPException(status_code=503, detail="The drag file could not be written.")+ return {"path": str(path)}++@router.get("/pending")async def pending() -> dict[str, Any]:from jarvis.appshot.store import get_store # noqa: PLC0415diff --git a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorDrag.test.tsx b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorDrag.test.tsxnew file mode 100644index 0000000000..b077b48dc7--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorDrag.test.tsx@@ -0,0 +1,103 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { AppshotEditorHost } from "@/components/appshot/AppshotEditorHost";+import { useAppshotEditor } from "@/store/appshotEditor";+import { useEventStore } from "@/store/events";++/**+ * The "Drag me" handle: pressing it writes the finished picture once+ * (POST /api/appshot/drag-file) and hands that path to the native drag bridge+ * while the button is still held. Its own file, because the desktop+ * capability is cached per module and the other editor tests run as a browser.+ */++class LoadedImage {+ naturalWidth = 400;+ naturalHeight = 300;+ onload: (() => void) | null = null;+ set src(_value: string) {+ queueMicrotask(() => this.onload?.());+ }+}++class TestPointerEvent extends MouseEvent {+ pointerId: number;+ constructor(type: string, init: PointerEventInit = {}) {+ super(type, init);+ this.pointerId = init.pointerId ?? 1;+ }+}++/** A 2D context that accepts every call, so the export can run in jsdom. */+function fakeContext(): unknown {+ const handler: ProxyHandler<object> = {+ get: (_target, key) => {+ if (key === "measureText") return () => ({ width: 10 });+ return new Proxy(() => undefined, { ...handler, apply: () => new Proxy({}, handler) });+ },+ set: () => true,+ };+ return new Proxy({}, handler);+}++function json(body: unknown, status = 200): Response {+ return { ok: status < 400, status, json: async () => body } as Response;+}++describe("the editor's drag handle", () => {+ const posted: unknown[] = [];++ beforeEach(() => {+ posted.length = 0;+ useEventStore.setState({ events: [], toasts: [], assistantName: "Jarvis" });+ useAppshotEditor.setState({ openId: null, revision: 0 });+ vi.stubGlobal("Image", LoadedImage);+ vi.stubGlobal("PointerEvent", TestPointerEvent);+ vi.stubGlobal("chrome", { webview: { postMessage: (message: unknown) => posted.push(message) } });+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => fakeContext() as never);+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((done: BlobCallback) =>+ done(new Blob(["png"], { type: "image/png" })),+ );+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string) => {+ if (url === "/api/downloads/capabilities") return json({ native_file_actions: true, platform: "win32" });+ if (url === "/api/appshot/drag-file") return json({ path: "C:/tmp/jarvis-appshots/appshot-1.png" });+ return json({}, 404);+ }),+ );+ });++ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ it("hands a written file to the native drag while the handle is held", { timeout: 10_000 }, async () => {+ render(<AppshotEditorHost />);+ act(() => useAppshotEditor.getState().open("shot-1"));+ // The capability check waits out the boot stagger (4 s) first.+ const handle = await screen.findByTestId("appshot-editor-drag", undefined, { timeout: 6000 });++ fireEvent.pointerDown(handle, { button: 0, pointerId: 3 });++ await waitFor(() =>+ expect(posted).toEqual([["jarvis-file-drag", { files: ["C:/tmp/jarvis-appshots/appshot-1.png"] }]]),+ );+ });++ it("does not start a drag the user already let go of", { timeout: 10_000 }, async () => {+ render(<AppshotEditorHost />);+ act(() => useAppshotEditor.getState().open("shot-1"));+ // The capability check waits out the boot stagger (4 s) first.+ const handle = await screen.findByTestId("appshot-editor-drag", undefined, { timeout: 6000 });++ fireEvent.pointerDown(handle, { button: 0, pointerId: 3 });+ fireEvent.pointerUp(window, { pointerId: 3 });++ await waitFor(() => expect(useEventStore.getState().toasts.length).toBe(1));+ expect(posted).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsxindex 59c675a42c..7507542caf 100644--- a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx+++ b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.test.tsx@@ -154,6 +154,26 @@ describe("AppshotEditorHost", () => {);});+ it("opens the colour menu and zooms from the bottom bar", async () => {+ render(<AppshotEditorHost />);+ act(() => useAppshotEditor.getState().open("shot-1"));+ await screen.findByTestId("appshot-editor-canvas");++ fireEvent.click(screen.getByTestId("appshot-editor-style"));+ expect(screen.getByTestId("appshot-editor-style-menu")).toBeDefined();+ // Escape closes the menu first, not the editor.+ fireEvent.keyDown(window, { key: "Escape" });+ await waitFor(() => expect(screen.queryByTestId("appshot-editor-style-menu")).toBeNull());+ expect(screen.getByTestId("appshot-editor")).toBeDefined();++ fireEvent.click(screen.getByTestId("appshot-editor-zoom"));+ fireEvent.click(screen.getByRole("menuitemradio", { name: "100%" }));+ expect(screen.getByTestId("appshot-editor-zoom").textContent).toContain("100%");++ fireEvent.keyDown(window, { key: "5" });+ expect((screen.getByTestId("appshot-editor-size") as HTMLInputElement).value).toBe("4");+ });+it("says when the appshot is gone instead of showing an empty editor", async () => {vi.stubGlobal("Image", BrokenImage);render(<AppshotEditorHost />);diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.jsonindex f7d6596306..d102314284 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/de.json@@ -23,16 +23,11 @@"color": "Farbe","custom_color": "Beliebige Farbe wählen","size": "Größe",- "size_small": "Klein",- "size_medium": "Mittel",- "size_large": "Groß","undo": "Rückgängig","redo": "Wiederholen","delete": "Auswahl löschen","copy": "Kopieren","save": "Speichern",- "apply": "Diese Version nutzen",- "apply_hint": "Ersetzt den Appshot, sodass deine nächste Nachricht an {name} das bearbeitete Bild mitschickt.","copied": "In die Zwischenablage kopiert.","copy_failed": "Kopieren hat nicht geklappt: {0}","copy_timeout": "die Zwischenablage hat nicht geantwortet",@@ -56,13 +51,20 @@"background_radius": "Ecken","background_shadow": "Schatten","hint_move": "Klick auf eine Markierung wählt sie aus. Ziehen verschiebt sie, Pfeiltasten schieben sie, Entf löscht sie. Doppelklick auf Text ändert ihn.",- "hint_crop": "Zieh über den Teil, der bleiben soll. Rückgängig holt den Rest zurück.","hint_counter": "Jeder Klick setzt die nächste Zahl.","hint_spotlight": "Zieh über das Wichtige; alles andere wird abgedunkelt.",- "hint_background": "Der Rahmen kommt beim Kopieren, Speichern oder Nutzen dazu.","discard_title": "Änderungen verwerfen?","discard_body": "Bisher wurde nichts kopiert, gespeichert oder übernommen.","discard_keep": "Weiter bearbeiten",- "discard_confirm": "Verwerfen"+ "discard_confirm": "Verwerfen",+ "save_hint": "In Downloads speichern",+ "done": "Fertig",+ "done_hint": "Diese Version nutzen: Deine nächste Nachricht an {name} schickt das bearbeitete Bild mit",+ "drag_me": "Zieh mich",+ "drag_hint": "Gedrückt halten und das Bild in eine beliebige App ziehen",+ "drag_release": "Halte den Griff gedrückt, während du ziehst.",+ "drag_failed": "Ziehen hat nicht geklappt: {0}",+ "zoom": "Zoom",+ "zoom_fit": "Einpassen"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.jsonindex 033a7d3a33..7c9ddd1911 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/en.json@@ -23,16 +23,11 @@"color": "Colour","custom_color": "Pick any colour","size": "Size",- "size_small": "Small",- "size_medium": "Medium",- "size_large": "Large","undo": "Undo","redo": "Redo","delete": "Delete selection","copy": "Copy","save": "Save",- "apply": "Use this version",- "apply_hint": "Replaces the appshot, so your next message to {name} carries the edited picture.","copied": "Copied to the clipboard.","copy_failed": "Copying did not work: {0}","copy_timeout": "the clipboard did not answer",@@ -56,13 +51,20 @@"background_radius": "Corners","background_shadow": "Shadow","hint_move": "Click an annotation to select it. Drag to move it, arrow keys nudge it, Delete removes it. Double-click text to change it.",- "hint_crop": "Drag over the part to keep. Undo brings the rest back.","hint_counter": "Each click adds the next number.","hint_spotlight": "Drag over what matters; everything else dims.",- "hint_background": "The frame is added when you copy, save or use the picture.","discard_title": "Discard your edits?","discard_body": "Nothing has been copied, saved or used yet.","discard_keep": "Keep editing",- "discard_confirm": "Discard"+ "discard_confirm": "Discard",+ "save_hint": "Save to Downloads",+ "done": "Done",+ "done_hint": "Use this version: your next message to {name} carries the edited picture",+ "drag_me": "Drag me",+ "drag_hint": "Hold and drag the picture into any app",+ "drag_release": "Keep the handle pressed while you drag.",+ "drag_failed": "Dragging did not work: {0}",+ "zoom": "Zoom",+ "zoom_fit": "Fit"}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.jsonindex fc2d70c212..c5643bed9a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/appshot_editor/es.json@@ -23,16 +23,11 @@"color": "Color","custom_color": "Elegir cualquier color","size": "Tamaño",- "size_small": "Pequeño",- "size_medium": "Mediano",- "size_large": "Grande","undo": "Deshacer","redo": "Rehacer","delete": "Eliminar selección","copy": "Copiar","save": "Guardar",- "apply": "Usar esta versión",- "apply_hint": "Sustituye el appshot, así tu próximo mensaje a {name} lleva la imagen editada.","copied": "Copiado al portapapeles.","copy_failed": "No se pudo copiar: {0}","copy_timeout": "el portapapeles no respondió",@@ -56,13 +51,20 @@"background_radius": "Esquinas","background_shadow": "Sombra","hint_move": "Haz clic en una anotación para seleccionarla. Arrástrala para moverla, las flechas la desplazan y Supr la elimina. Doble clic en un texto para cambiarlo.",- "hint_crop": "Arrastra sobre la parte que quieres conservar. Deshacer recupera el resto.","hint_counter": "Cada clic añade el siguiente número.","hint_spotlight": "Arrastra sobre lo importante; el resto se oscurece.",- "hint_background": "El marco se añade al copiar, guardar o usar la imagen.","discard_title": "¿Descartar los cambios?","discard_body": "Todavía no se ha copiado, guardado ni usado nada.","discard_keep": "Seguir editando",- "discard_confirm": "Descartar"+ "discard_confirm": "Descartar",+ "save_hint": "Guardar en Descargas",+ "done": "Listo",+ "done_hint": "Usar esta versión: tu próximo mensaje a {name} lleva la imagen editada",+ "drag_me": "Arrástrame",+ "drag_hint": "Mantén pulsado y arrastra la imagen a cualquier app",+ "drag_release": "Mantén pulsada el asa mientras arrastras.",+ "drag_failed": "No se pudo arrastrar: {0}",+ "zoom": "Zoom",+ "zoom_fit": "Ajustar"}}diff --git a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.tsindex 45c4e0aaac..c688dbc307 100644--- a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts+++ b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.test.ts@@ -46,10 +46,9 @@ describe("appshot editor model", () => {});it("scales stroke and text sizes with the picture", () => {- const [small, , large] = strokeWidths(1400, 800);- expect(small).toBe(3);- expect(large).toBe(11);- expect(strokeWidths(2800, 1600)[0]).toBe(6);+ expect(strokeWidths(1400, 800)).toEqual([2, 4, 6, 9, 13]);+ expect(strokeWidths(2800, 1600)[0]).toBe(4);+ expect(strokeWidths(300, 200)[0]).toBe(2);expect(textSize(6)).toBe(30);});});diff --git a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.tsindex d08e59c40e..00c4c80eb9 100644--- a/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts+++ b/jarvis/ui/web/frontend/src/lib/appshotEditorModel.ts@@ -101,10 +101,13 @@ export function withId<T extends Draft>(shape: T): T & { id: number } {return { ...shape, id: nextId };}-/** Stroke widths (S / M / L) for a picture of this size, in its own pixels. */-export function strokeWidths(width: number, height: number): [number, number, number] {+/** The five stroke sizes (keys 1–5, the size slider), for a 1400 px picture. */+export const STROKE_LEVELS = [2, 4, 6, 9, 13] as const;++/** The stroke sizes for a picture of this size, in its own pixels. */+export function strokeWidths(width: number, height: number): number[] {const unit = Math.max(1, Math.max(width, height) / 1400);- return [Math.round(3 * unit), Math.round(6 * unit), Math.round(11 * unit)];+ return STROKE_LEVELS.map((level) => Math.round(level * unit));}export function textSize(stroke: number): number {diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsxindex 56a4b9372e..d4f1029441 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx@@ -1,14 +1,15 @@import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import {- Check,+ ChevronDown,Circle,Copy,Crop,Download,Focus,- Image as ImageIcon,+ GripVertical,Grid3x3,Highlighter,+ Image as ImageIcon,Loader2,Minus,MousePointer2,@@ -34,6 +35,7 @@ import {COLORS,CROP_RATIOS,DEFAULT_BACKGROUND,+ STROKE_LEVELS,TOOL_KEYS,bounds,canvasMeasure,@@ -69,6 +71,7 @@ import {type Tool,} from "@/lib/appshotEditorModel";import { saveOrDownload } from "@/lib/clipboard";+import { canNativeDrag, startNativeFileDrag } from "@/lib/nativeDrag";import { cn } from "@/lib/utils";import { useEventStore } from "@/store/events";@@ -84,8 +87,35 @@ import { useEventStore } from "@/store/events";* because the WebView cannot be trusted with images; Save writes into* Downloads through the backend because the desktop WebView drops browser* downloads. In a plain browser both fall back to the browser's own paths.+ *+ * The layout follows CleanShot X's editor window: a floating rounded window+ * over a dimmed app, the tools as pills along the top with colour and size+ * beside them, "Save" and "Done" at the top right, and a bottom bar with the+ * zoom, a "Drag me" handle (a real file drag into any app, where the desktop+ * shell has the native drag bridge) and the copy action.*/+/** Toolbar order, as in CleanShot X: selection, shapes, text, effects, ink. */+const TOOL_ORDER: readonly Tool[] = [+ "move",+ "rect",+ "filled",+ "ellipse",+ "line",+ "arrow",+ "text",+ "redact",+ "spotlight",+ "counter",+ "pen",+ "highlight",+];++const KEY_OF: Record<Tool, string> = Object.fromEntries(TOOL_KEYS.map(({ tool, key }) => [tool, key])) as Record<Tool, string>;++/** Zoom steps after "fit". */+const ZOOMS = [0.5, 1, 2] as const;+const TOOL_ICONS: Record<Tool, typeof Square | null> = {move: MousePointer2,arrow: MoveUpRight,@@ -103,8 +133,6 @@ const TOOL_ICONS: Record<Tool, typeof Square | null> = {background: ImageIcon,};-/** Tools whose colour and stroke size matter. */-const INKED: ReadonlySet<Tool> = new Set(["arrow", "line", "rect", "filled", "ellipse", "pen", "highlight", "text", "counter"]);const COLOR_KEY = "jarvis.appshotEditor.color";const BACKGROUND_KEY = "jarvis.appshotEditor.background";@@ -171,7 +199,11 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPrconst ops = history.present;const [tool, setTool] = useState<Tool>("arrow");const [color, setColorState] = useState(() => readStored(COLOR_KEY, COLORS[0], isColor));- const [widthIndex, setWidthIndex] = useState(1);+ const [widthIndex, setWidthIndex] = useState(2);+ const [zoom, setZoom] = useState<"fit" | number>("fit");+ const [menu, setMenu] = useState<"" | "style" | "zoom">("");+ const [dragging, setDragging] = useState(false);+ const holdingRef = useRef(false);const [textStyle, setTextStyle] = useState<TextStyle>("plain");const [redactMode, setRedactMode] = useState<RedactMode>("pixelate");const [cropRatio, setCropRatio] = useState<string>("free");@@ -262,10 +294,11 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPrconst shown = tool === "crop" ? { x: 0, y: 0, w: iw, h: ih } : view;const framing = tool === "crop" ? { ...background, enabled: false } : background;const layout = frameLayout(shown.w || 1, shown.h || 1, framing);- const scale =+ const fitScale =shown.w > 0 && stage.w > 0? Math.min((stage.w - 48) / layout.width, (stage.h - 48) / layout.height, 1): 1;+ const scale = zoom === "fit" ? fitScale : zoom;const cw = Math.max(1, Math.round(shown.w * scale));const ch = Math.max(1, Math.round(shown.h * scale));const ratio = CROP_RATIOS.find((entry) => entry.id === cropRatio)?.ratio ?? null;@@ -565,7 +598,8 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPrconst key = event.key.toLowerCase();if (event.key === "Escape") {event.preventDefault();- if (confirmDiscard) setConfirmDiscard(false);+ if (menu) setMenu("");+ else if (confirmDiscard) setConfirmDiscard(false);else if (gestureRef.current) setGesture(null);else if (selectedId !== null) setSelectedId(null);else requestClose();@@ -596,7 +630,7 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPrconst dx = event.key === "ArrowLeft" ? -step : event.key === "ArrowRight" ? step : 0;const dy = event.key === "ArrowUp" ? -step : event.key === "ArrowDown" ? step : 0;nudgeSelected(dx, dy);- } else if (!mod && !event.altKey && ["1", "2", "3"].includes(event.key)) {+ } else if (!mod && !event.altKey && /^[1-5]$/.test(event.key)) {setWidthIndex(Number(event.key) - 1);} else if (!mod && !event.altKey) {const next = toolForKey(event.key);@@ -605,7 +639,56 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPr};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);- }, [chooseTool, confirmDiscard, copy, nudgeSelected, redo, removeSelected, requestClose, save, scale, selectedId, setGesture, typing, undo, use]);+ }, [chooseTool, confirmDiscard, copy, menu, nudgeSelected, redo, removeSelected, requestClose, save, scale, selectedId, setGesture, typing, undo, use]);++ // -- drag out --------------------------------------------------------------+ // The handle writes the finished picture to a file only when pressed, then+ // hands it to the native drag bridge if the button is still held.+ const canDragOut = native && canNativeDrag();+ useEffect(() => {+ const release = () => {+ holdingRef.current = false;+ };+ window.addEventListener("pointerup", release);+ window.addEventListener("blur", release);+ return () => {+ window.removeEventListener("pointerup", release);+ window.removeEventListener("blur", release);+ };+ }, []);++ const dragOut = async (event: React.PointerEvent) => {+ if (event.button !== 0 || !image || dragging) return;+ event.preventDefault();+ holdingRef.current = true;+ setDragging(true);+ try {+ const blob = await render();+ const response = await fetch("/api/appshot/drag-file", {+ method: "POST",+ headers: { "content-type": "image/png" },+ body: blob,+ });+ if (!response.ok) throw new Error(`HTTP ${response.status}`);+ const { path } = (await response.json()) as { path: string };+ if (holdingRef.current) startNativeFileDrag(path);+ else pushToast("info", t("appshot_editor.drag_release"));+ } catch (error) {+ pushToast("error", fill(t("appshot_editor.drag_failed"), { 0: (error as Error).message }));+ } finally {+ setDragging(false);+ }+ };++ // Close an open menu on a press anywhere else.+ useEffect(() => {+ if (!menu) return;+ const close = (event: PointerEvent) => {+ if (!(event.target as Element | null)?.closest?.("[data-editor-menu]")) setMenu("");+ };+ window.addEventListener("pointerdown", close, true);+ return () => window.removeEventListener("pointerdown", close, true);+ }, [menu]);const label = (key: string) => (ready ? t(`appshot_editor.${key}`) : "");const toolLabel = (name: Tool) => label(`tool_${name}`);@@ -616,321 +699,434 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPrtool === "text" ? "text" : tool === "move" ? (gesture?.kind === "move" ? "grabbing" : "default") : tool === "background" ? "default" : "crosshair";const frameOn = framing.enabled;const preset = presetById(background.preset);+ const zoomLabel = zoom === "fit" ? label("zoom_fit") : `${Math.round(zoom * 100)}%`;const hint =tool === "move"? label("hint_move")- : tool === "crop"- ? label("hint_crop")- : tool === "counter"- ? label("hint_counter")- : tool === "spotlight"- ? label("hint_spotlight")- : tool === "background"- ? label("hint_background")- : "";+ : tool === "counter"+ ? label("hint_counter")+ : tool === "spotlight"+ ? label("hint_spotlight")+ : "";+ const showCapsule = tool === "text" || tool === "redact" || tool === "crop" || tool === "background" || hint !== "";++ const toolButton = (name: Tool) => {+ const Icon = TOOL_ICONS[name];+ return (+ <QuickTooltip key={name} content={`${toolLabel(name)} (${KEY_OF[name].toUpperCase()})`} side="bottom">+ <button+ type="button"+ aria-label={toolLabel(name)}+ aria-pressed={tool === name}+ onClick={() => chooseTool(name)}+ data-testid={`appshot-editor-tool-${name}`}+ className={cn(+ "flex h-7 w-8 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors",+ "hover:bg-foreground/10 hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",+ (name === "crop" || name === "background") && "bg-foreground/10",+ tool === name && "bg-foreground/20 text-foreground",+ )}+ >+ {name === "filled" ? (+ <Square className="h-[15px] w-[15px]" fill="currentColor" aria-hidden />+ ) : name === "counter" ? (+ <span className="flex h-[15px] w-[15px] items-center justify-center rounded-full bg-current text-[9px] font-bold leading-none">+ <span className="text-popover">1</span>+ </span>+ ) : Icon ? (+ <Icon className="h-[15px] w-[15px]" aria-hidden />+ ) : null}+ </button>+ </QuickTooltip>+ );+ };return (- <div className="flex h-full w-full flex-col bg-background text-foreground" data-testid="appshot-editor">- {/* Top bar: close + title · tools · history and results. */}- <div className="flex shrink-0 items-center gap-3 border-b border-border px-3 py-2">- <div className="flex min-w-0 items-center gap-2">+ <div className="flex h-full w-full items-center justify-center bg-black/45 p-2 backdrop-blur-[2px] sm:p-5">+ <div+ className="relative flex h-full w-full max-w-[1800px] flex-col overflow-hidden rounded-2xl border border-border bg-popover text-popover-foreground shadow-2xl"+ data-testid="appshot-editor"+ >+ {/* Top bar: close · crop and background · tools · colour and size · Save, Done. */}+ <div className="flex h-12 shrink-0 items-center gap-2 border-b border-border px-3"><QuickTooltip content={`${label("close")} (Esc)`} side="bottom">- <Button type="button" variant="ghost" size="sm" onClick={requestClose} aria-label={label("close")} data-testid="appshot-editor-close">- <X aria-hidden />- </Button>+ <button+ type="button"+ onClick={requestClose}+ aria-label={label("close")}+ data-testid="appshot-editor-close"+ className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-foreground/10 text-muted-foreground transition-colors hover:bg-destructive hover:text-destructive-foreground"+ >+ <X className="h-3.5 w-3.5" aria-hidden />+ </button></QuickTooltip>- <p className="hidden truncate text-sm font-medium text-foreground xl:block">{label("title")}</p>- </div>+ <div className="flex shrink-0 items-center gap-1">+ {toolButton("crop")}+ {toolButton("background")}+ </div>+ <div className="h-5 w-px shrink-0 bg-border" aria-hidden />+ <div className="flex min-w-0 items-center gap-0.5 overflow-x-auto" role="toolbar" aria-label={label("tools")}>+ {TOOL_ORDER.map(toolButton)}+ </div>+ <div className="h-5 w-px shrink-0 bg-border" aria-hidden />- <div className="flex min-w-0 flex-1 justify-center overflow-x-auto">- <div className="flex items-center gap-0.5 rounded-xl bg-secondary/70 p-1" role="toolbar" aria-label={label("tools")}>- {TOOL_KEYS.map(({ tool: name, key }) => {- const Icon = TOOL_ICONS[name];- return (- <QuickTooltip key={name} content={`${toolLabel(name)} (${key.toUpperCase()})`} side="bottom">- <button- type="button"- aria-label={toolLabel(name)}- aria-pressed={tool === name}- onClick={() => chooseTool(name)}- data-testid={`appshot-editor-tool-${name}`}+ {/* Colour (a menu) and size (a slider), like CleanShot's style controls. */}+ <div className="relative shrink-0" data-editor-menu>+ <QuickTooltip content={label("color")} side="bottom">+ <button+ type="button"+ aria-label={label("color")}+ aria-expanded={menu === "style"}+ onClick={() => setMenu(menu === "style" ? "" : "style")}+ data-testid="appshot-editor-style"+ className="flex h-7 items-center gap-1 rounded-full bg-foreground/10 pl-1.5 pr-1 transition-colors hover:bg-foreground/15"+ >+ <span className="h-4 w-4 rounded-full border border-border-strong" style={{ backgroundColor: color }} />+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />+ </button>+ </QuickTooltip>+ {menu === "style" && (+ <div+ className="absolute left-0 top-full z-10 mt-2 w-[208px] rounded-xl border border-border bg-popover p-2.5 shadow-2xl"+ role="group"+ aria-label={label("color")}+ data-testid="appshot-editor-style-menu"+ >+ <div className="grid grid-cols-5 gap-2">+ {COLORS.map((swatch) => (+ <button+ key={swatch}+ type="button"+ aria-label={swatch}+ aria-pressed={color === swatch}+ onClick={() => {+ setColor(swatch);+ setMenu("");+ }}+ className={cn(+ "h-7 w-7 rounded-full border border-border-strong transition-transform hover:scale-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",+ color === swatch && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-popover",+ )}+ style={{ backgroundColor: swatch }}+ />+ ))}+ <labelclassName={cn(- "flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors",- "hover:bg-popover hover:text-foreground focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",- tool === name && "bg-popover text-foreground shadow-sm",- (name === "redact" || name === "move" || name === "background") && "ml-1",+ "relative h-7 w-7 cursor-pointer overflow-hidden rounded-full border border-border-strong",+ !COLORS.includes(color) && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-popover",)}+ style={{ background: "conic-gradient(#ff3b30, #ffcc00, #34c759, #0a84ff, #af52de, #ff3b30)" }}+ title={label("custom_color")}>- {name === "filled" ? (- <Square className="h-4 w-4" fill="currentColor" aria-hidden />- ) : name === "counter" ? (- <span className="flex h-4 w-4 items-center justify-center rounded-full bg-current text-[10px] font-bold leading-none">- <span className="text-popover">1</span>- </span>- ) : Icon ? (- <Icon className="h-4 w-4" aria-hidden />- ) : null}- </button>- </QuickTooltip>- );- })}+ <input+ type="color"+ value={color}+ onChange={(event) => setColor(event.target.value)}+ aria-label={label("custom_color")}+ className="absolute inset-0 cursor-pointer opacity-0"+ data-testid="appshot-editor-custom-color"+ />+ </label>+ </div>+ </div>+ )}</div>- </div>-- <div className="flex shrink-0 items-center gap-1.5">- <QuickTooltip content={`${label("undo")} (Ctrl+Z)`} side="bottom">- <Button type="button" variant="ghost" size="sm" onClick={undo} disabled={history.past.length === 0} aria-label={label("undo")} data-testid="appshot-editor-undo">- <Undo2 aria-hidden />- </Button>- </QuickTooltip>- <QuickTooltip content={`${label("redo")} (Ctrl+Shift+Z)`} side="bottom">- <Button type="button" variant="ghost" size="sm" onClick={redo} disabled={history.future.length === 0} aria-label={label("redo")} data-testid="appshot-editor-redo">- <Redo2 aria-hidden />- </Button>- </QuickTooltip>- <div className="mx-1 h-5 w-px bg-border" aria-hidden />- <QuickTooltip content={`${label("copy")} (Ctrl+C)`} side="bottom">- <Button type="button" variant="secondary" size="sm" onClick={() => void copy()} disabled={!image || busy !== ""} data-testid="appshot-editor-copy">- {busy === "copy" ? <Loader2 className="animate-spin" aria-hidden /> : <Copy aria-hidden />}- <span className="hidden lg:inline">{label("copy")}</span>- </Button>- </QuickTooltip>- <QuickTooltip content={`${label("save")} (Ctrl+S)`} side="bottom">- <Button type="button" variant="secondary" size="sm" onClick={() => void save()} disabled={!image || busy !== ""} data-testid="appshot-editor-save">- {busy === "save" ? <Loader2 className="animate-spin" aria-hidden /> : <Download aria-hidden />}- <span className="hidden lg:inline">{label("save")}</span>- </Button>- </QuickTooltip>- <QuickTooltip content={`${fill(label("apply_hint"), { name: assistantName })} (Ctrl+Enter)`} side="bottom">- <Button type="button" size="sm" onClick={() => void use()} disabled={!image || busy !== ""} data-testid="appshot-editor-apply">- {busy === "apply" ? <Loader2 className="animate-spin" aria-hidden /> : <Check aria-hidden />}- <span className="hidden md:inline">{label("apply")}</span>- </Button>+ <QuickTooltip content={`${label("size")} (1–5)`} side="bottom">+ <label className="flex shrink-0 items-center">+ <span className="sr-only">{label("size")}</span>+ <input+ type="range"+ min={0}+ max={STROKE_LEVELS.length - 1}+ step={1}+ value={widthIndex}+ onChange={(event) => setWidthIndex(Number(event.currentTarget.value))}+ aria-label={label("size")}+ data-testid="appshot-editor-size"+ className="h-1 w-24 cursor-pointer accent-primary"+ />+ </label></QuickTooltip>++ <div className="ml-auto flex shrink-0 items-center gap-1.5">+ <QuickTooltip content={`${label("save_hint")} (Ctrl+S)`} side="bottom">+ <button+ type="button"+ onClick={() => void save()}+ disabled={!image || busy !== ""}+ data-testid="appshot-editor-save"+ className="flex h-7 items-center gap-1.5 rounded-full bg-foreground/10 px-3 text-[13px] font-medium text-foreground transition-colors hover:bg-foreground/15 disabled:opacity-50"+ >+ {busy === "save" && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />}+ {label("save")}+ </button>+ </QuickTooltip>+ <QuickTooltip content={`${fill(label("done_hint"), { name: assistantName })} (Ctrl+Enter)`} side="bottom">+ <button+ type="button"+ onClick={() => void use()}+ disabled={!image || busy !== ""}+ data-testid="appshot-editor-apply"+ className="flex h-7 items-center gap-1.5 rounded-full bg-primary px-3.5 text-[13px] font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50"+ >+ {busy === "apply" && <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />}+ {label("done")}+ </button>+ </QuickTooltip>+ </div></div>- </div>- {/* Options for the active tool. */}- <div className="flex min-h-11 shrink-0 flex-wrap items-center justify-center gap-x-4 gap-y-1.5 border-b border-border px-3 py-1.5 text-sm" data-testid="appshot-editor-options">- {INKED.has(tool) && (- <>- <div className="flex items-center gap-1.5" role="group" aria-label={label("color")}>- {COLORS.map((swatch) => (- <button- key={swatch}- type="button"- aria-label={swatch}- aria-pressed={color === swatch}- onClick={() => setColor(swatch)}- className={cn(- "h-5 w-5 rounded-full border border-border-strong transition-transform focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",- color === swatch && "scale-110 ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",- )}- style={{ backgroundColor: swatch }}- />- ))}- <QuickTooltip content={label("custom_color")} side="bottom">- <label- className={cn(- "relative h-5 w-5 cursor-pointer overflow-hidden rounded-full border border-border-strong",- !COLORS.includes(color) && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",- )}- style={{ background: "conic-gradient(#ff3b30, #ffcc00, #34c759, #0a84ff, #af52de, #ff3b30)" }}- >- <input- type="color"- value={color}- onChange={(event) => setColor(event.target.value)}- aria-label={label("custom_color")}- className="absolute inset-0 cursor-pointer opacity-0"- data-testid="appshot-editor-custom-color"+ {/* The picture. */}+ <div className="relative min-h-0 flex-1 bg-background/70">+ {/* Floats over the picture, so it never changes the space the picture fits into. */}+ {showCapsule && (+ <div className="pointer-events-none absolute inset-x-0 top-0 z-10 flex justify-center px-3 pt-3">+ <div+ className="pointer-events-auto flex max-w-full flex-wrap items-center justify-center gap-x-3 gap-y-1.5 rounded-2xl border border-border bg-popover/95 px-3 py-1.5 text-[13px] shadow-lg backdrop-blur"+ data-testid="appshot-editor-options"+ >+ {tool === "text" && (+ <Segmented+ label={label("text_style")}+ value={textStyle}+ onChange={(value) => setTextStyle(value as TextStyle)}+ options={[+ { value: "plain", label: label("text_plain") },+ { value: "label", label: label("text_label") },+ { value: "outline", label: label("text_outline") },+ ]}+ testId="appshot-editor-text-style"/>- </label>- </QuickTooltip>- </div>- <div className="flex items-center gap-0.5 rounded-lg bg-secondary/70 p-0.5" role="group" aria-label={label("size")}>- {(["size_small", "size_medium", "size_large"] as const).map((name, index) => (- <QuickTooltip key={name} content={`${label(name)} (${index + 1})`} side="bottom">- <button- type="button"- aria-label={label(name)}- aria-pressed={widthIndex === index}- onClick={() => setWidthIndex(index)}- className={cn(- "flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-popover",- widthIndex === index && "bg-popover shadow-sm",- )}- >- <span className="rounded-full bg-foreground" style={{ width: 3 + index * 3, height: 3 + index * 3 }} />- </button>- </QuickTooltip>- ))}+ )}+ {tool === "redact" && (+ <Segmented+ label={label("redact_mode")}+ value={redactMode}+ onChange={(value) => setRedactMode(value as RedactMode)}+ options={[+ { value: "pixelate", label: label("redact_pixelate") },+ { value: "blur", label: label("redact_blur") },+ ]}+ testId="appshot-editor-redact-mode"+ />+ )}+ {tool === "crop" && (+ <Segmented+ label={label("crop_ratio")}+ value={cropRatio}+ onChange={setCropRatio}+ options={CROP_RATIOS.map((entry) => ({ value: entry.id, label: entry.id === "free" ? label("crop_free") : entry.id }))}+ testId="appshot-editor-crop-ratio"+ />+ )}+ {tool === "background" && (+ <>+ <label className="flex items-center gap-2 text-muted-foreground">+ <Switch+ checked={background.enabled}+ onCheckedChange={(enabled) => setBackground({ enabled })}+ aria-label={label("background_enabled")}+ data-testid="appshot-editor-background-enabled"+ />+ {label("background_enabled")}+ </label>+ <div className="flex items-center gap-1.5" role="group" aria-label={label("background_preset")}>+ {BACKGROUND_PRESETS.map((entry) => (+ <button+ key={entry.id}+ type="button"+ aria-label={entry.id}+ aria-pressed={background.preset === entry.id}+ onClick={() => setBackground({ preset: entry.id, enabled: true })}+ className={cn(+ "h-6 w-6 rounded-md border border-border-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",+ background.preset === entry.id && background.enabled && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-popover",+ )}+ style={{ background: presetCss(entry) }}+ />+ ))}+ </div>+ <Slider label={label("background_padding")} min={0} max={0.2} step={0.01} value={background.padding} onChange={(padding) => setBackground({ padding, enabled: true })} />+ <Slider label={label("background_radius")} min={0} max={40} step={1} value={background.radius} onChange={(radius) => setBackground({ radius, enabled: true })} />+ <label className="flex items-center gap-2 text-muted-foreground">+ <Switch checked={background.shadow} onCheckedChange={(shadow) => setBackground({ shadow })} aria-label={label("background_shadow")} />+ {label("background_shadow")}+ </label>+ </>+ )}+ {hint && <p className="text-muted-foreground">{hint}</p>}+ </div></div>- </>- )}-- {tool === "text" && (- <Segmented- label={label("text_style")}- value={textStyle}- onChange={(value) => setTextStyle(value as TextStyle)}- options={[- { value: "plain", label: label("text_plain") },- { value: "label", label: label("text_label") },- { value: "outline", label: label("text_outline") },- ]}- testId="appshot-editor-text-style"- />- )}-- {tool === "redact" && (- <Segmented- label={label("redact_mode")}- value={redactMode}- onChange={(value) => setRedactMode(value as RedactMode)}- options={[- { value: "pixelate", label: label("redact_pixelate") },- { value: "blur", label: label("redact_blur") },- ]}- testId="appshot-editor-redact-mode"- />- )}-- {tool === "crop" && (- <Segmented- label={label("crop_ratio")}- value={cropRatio}- onChange={setCropRatio}- options={CROP_RATIOS.map((entry) => ({ value: entry.id, label: entry.id === "free" ? label("crop_free") : entry.id }))}- testId="appshot-editor-crop-ratio"- />- )}+ )}- {tool === "background" && (- <>- <label className="flex items-center gap-2 text-muted-foreground">- <Switch- checked={background.enabled}- onCheckedChange={(enabled) => setBackground({ enabled })}- aria-label={label("background_enabled")}- data-testid="appshot-editor-background-enabled"- />- {label("background_enabled")}- </label>- <div className="flex items-center gap-1.5" role="group" aria-label={label("background_preset")}>- {BACKGROUND_PRESETS.map((entry) => (- <button- key={entry.id}- type="button"- aria-label={entry.id}- aria-pressed={background.preset === entry.id}- onClick={() => setBackground({ preset: entry.id, enabled: true })}- className={cn(- "h-6 w-6 rounded-md border border-border-strong focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",- background.preset === entry.id && background.enabled && "ring-2 ring-foreground/70 ring-offset-2 ring-offset-background",+ <div ref={stageRef} className="h-full w-full overflow-auto" data-testid="appshot-editor-stage">+ <div className="flex min-h-full min-w-full items-center justify-center p-6" style={{ width: "max-content" }}>+ {load === "failed" ? (+ <div className="flex max-w-sm flex-col items-center gap-3 text-center" data-testid="appshot-editor-failed">+ <p className="text-base text-muted-foreground">{label("gone")}</p>+ <Button type="button" variant="secondary" size="sm" onClick={onClose}>+ {label("close")}+ </Button>+ </div>+ ) : !image ? (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />+ {label("loading")}+ </div>+ ) : (+ <div+ className={cn(frameOn ? "" : "shadow-2xl ring-1 ring-border")}+ style={frameOn ? { padding: layout.image.x * scale, background: presetCss(preset), borderRadius: 6 } : undefined}+ data-testid="appshot-editor-frame"+ >+ <div+ className="relative overflow-hidden"+ style={{+ width: cw,+ height: ch,+ borderRadius: frameOn ? layout.radius * scale : 0,+ boxShadow: frameOn && background.shadow ? "0 12px 40px rgba(0,0,0,0.35)" : undefined,+ }}+ >+ <canvas+ ref={canvasRef}+ style={{ width: cw, height: ch, cursor, touchAction: "none", display: "block" }}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={onPointerUp}+ onPointerCancel={() => setGesture(null)}+ onDoubleClick={onDoubleClick}+ data-testid="appshot-editor-canvas"+ />+ {typing && textScreen && (+ <textarea+ autoFocus+ value={typing.text}+ placeholder={label("text_placeholder")}+ onChange={(event) => setTyping({ ...typing, text: event.target.value })}+ onBlur={commitText}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault();+ commitText();+ } else if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ setTyping(null);+ }+ }}+ rows={Math.max(1, typing.text.split("\n").length)}+ data-testid="appshot-editor-text-input"+ className="absolute resize-none border border-dashed border-white/70 bg-black/25 p-0 font-semibold leading-tight outline-none placeholder:text-white/60"+ style={{+ left: textScreen.left,+ top: textScreen.top,+ color,+ fontSize: textSize(width) * scale,+ minWidth: 140,+ }}+ />)}- style={{ background: presetCss(entry) }}- />- ))}- </div>- <Slider label={label("background_padding")} min={0} max={0.2} step={0.01} value={background.padding} onChange={(padding) => setBackground({ padding, enabled: true })} />- <Slider label={label("background_radius")} min={0} max={40} step={1} value={background.radius} onChange={(radius) => setBackground({ radius, enabled: true })} />- <label className="flex items-center gap-2 text-muted-foreground">- <Switch checked={background.shadow} onCheckedChange={(shadow) => setBackground({ shadow })} aria-label={label("background_shadow")} />- {label("background_shadow")}- </label>- </>- )}-- {tool === "move" && selected && (- <Button type="button" variant="ghost" size="sm" onClick={removeSelected} data-testid="appshot-editor-delete">- <Trash2 aria-hidden />- {label("delete")}- </Button>- )}-- {hint && <p className="text-muted-foreground">{hint}</p>}- </div>-- {/* The picture. */}- <div ref={stageRef} className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-muted/40">- {load === "failed" ? (- <div className="flex max-w-sm flex-col items-center gap-3 text-center" data-testid="appshot-editor-failed">- <p className="text-base text-muted-foreground">{label("gone")}</p>- <Button type="button" variant="secondary" size="sm" onClick={onClose}>- {label("close")}- </Button>+ </div>+ </div>+ )}</div>- ) : !image ? (- <div className="flex items-center gap-2 text-sm text-muted-foreground">- <Loader2 className="h-4 w-4 animate-spin" aria-hidden />- {label("loading")}</div>- ) : (- <div- className={cn(frameOn ? "" : "shadow-2xl ring-1 ring-border")}- style={- frameOn- ? { padding: layout.image.x * scale, background: presetCss(preset), borderRadius: 4 }- : undefined- }- data-testid="appshot-editor-frame"- >- <div- className="relative overflow-hidden"- style={{- width: cw,- height: ch,- borderRadius: frameOn ? layout.radius * scale : 0,- boxShadow: frameOn && background.shadow ? "0 12px 40px rgba(0,0,0,0.35)" : undefined,- }}- >- <canvas- ref={canvasRef}- style={{ width: cw, height: ch, cursor, touchAction: "none", display: "block" }}- onPointerDown={onPointerDown}- onPointerMove={onPointerMove}- onPointerUp={onPointerUp}- onPointerCancel={() => setGesture(null)}- onDoubleClick={onDoubleClick}- data-testid="appshot-editor-canvas"- />- {typing && textScreen && (- <textarea- autoFocus- value={typing.text}- placeholder={label("text_placeholder")}- onChange={(event) => setTyping({ ...typing, text: event.target.value })}- onBlur={commitText}- onKeyDown={(event) => {- if (event.key === "Enter" && !event.shiftKey) {- event.preventDefault();- commitText();- } else if (event.key === "Escape") {- event.preventDefault();- event.stopPropagation();- setTyping(null);- }- }}- rows={Math.max(1, typing.text.split("\n").length)}- data-testid="appshot-editor-text-input"- className="absolute resize-none border border-dashed border-white/70 bg-black/25 p-0 font-semibold leading-tight outline-none placeholder:text-white/60"- style={{- left: textScreen.left,- top: textScreen.top,- color,- fontSize: textSize(width) * scale,- minWidth: 140,- }}- />+ </div>++ {/* Bottom bar: zoom and history · drag handle · selection, save and copy. */}+ <div className="grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center gap-2 border-t border-border px-3">+ <div className="flex items-center gap-1">+ <div className="relative" data-editor-menu>+ <button+ type="button"+ aria-label={label("zoom")}+ aria-expanded={menu === "zoom"}+ onClick={() => setMenu(menu === "zoom" ? "" : "zoom")}+ data-testid="appshot-editor-zoom"+ className="flex h-7 items-center gap-1 rounded-full bg-foreground/10 px-2.5 text-[13px] font-medium tabular-nums transition-colors hover:bg-foreground/15"+ >+ {zoomLabel}+ <ChevronDown className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />+ </button>+ {menu === "zoom" && (+ <div className="absolute bottom-full left-0 z-10 mb-2 min-w-[96px] rounded-xl border border-border bg-popover p-1 shadow-2xl" role="menu">+ {(["fit", ...ZOOMS] as const).map((entry) => (+ <button+ key={String(entry)}+ type="button"+ role="menuitemradio"+ aria-checked={zoom === entry}+ onClick={() => {+ setZoom(entry);+ setMenu("");+ }}+ className={cn(+ "flex w-full rounded-lg px-2.5 py-1.5 text-left text-[13px] tabular-nums hover:bg-foreground/10",+ zoom === entry && "bg-foreground/10 font-medium",+ )}+ >+ {entry === "fit" ? label("zoom_fit") : `${Math.round(entry * 100)}%`}+ </button>+ ))}+ </div>)}</div>+ <QuickTooltip content={`${label("undo")} (Ctrl+Z)`} side="top">+ <button type="button" onClick={undo} disabled={history.past.length === 0} aria-label={label("undo")} data-testid="appshot-editor-undo" className={ROUND_ICON}>+ <Undo2 className="h-[15px] w-[15px]" aria-hidden />+ </button>+ </QuickTooltip>+ <QuickTooltip content={`${label("redo")} (Ctrl+Shift+Z)`} side="top">+ <button type="button" onClick={redo} disabled={history.future.length === 0} aria-label={label("redo")} data-testid="appshot-editor-redo" className={ROUND_ICON}>+ <Redo2 className="h-[15px] w-[15px]" aria-hidden />+ </button>+ </QuickTooltip></div>- )}++ <div className="flex justify-center">+ {canDragOut && (+ <QuickTooltip content={label("drag_hint")} side="top">+ <button+ type="button"+ onPointerDown={(event) => void dragOut(event)}+ onDragStart={(event) => event.preventDefault()}+ disabled={!image}+ data-testid="appshot-editor-drag"+ className="flex h-7 cursor-grab select-none items-center gap-1.5 rounded-full bg-foreground/10 px-3 text-[13px] font-medium text-foreground transition-colors hover:bg-foreground/15 active:cursor-grabbing disabled:opacity-50"+ >+ {dragging ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <GripVertical className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />}+ {label("drag_me")}+ <GripVertical className="h-3.5 w-3.5 text-muted-foreground" aria-hidden />+ </button>+ </QuickTooltip>+ )}+ </div>++ <div className="flex items-center justify-end gap-1">+ {selected && (+ <QuickTooltip content={`${label("delete")} (Del)`} side="top">+ <button type="button" onClick={removeSelected} aria-label={label("delete")} data-testid="appshot-editor-delete" className={ROUND_ICON}>+ <Trash2 className="h-[15px] w-[15px]" aria-hidden />+ </button>+ </QuickTooltip>+ )}+ <QuickTooltip content={`${label("save_hint")} (Ctrl+S)`} side="top">+ <button type="button" onClick={() => void save()} disabled={!image || busy !== ""} aria-label={label("save")} className={ROUND_ICON}>+ <Download className="h-[15px] w-[15px]" aria-hidden />+ </button>+ </QuickTooltip>+ <QuickTooltip content={`${label("copy")} (Ctrl+C)`} side="top">+ <button type="button" onClick={() => void copy()} disabled={!image || busy !== ""} aria-label={label("copy")} data-testid="appshot-editor-copy" className={ROUND_ICON}>+ {busy === "copy" ? <Loader2 className="h-[15px] w-[15px] animate-spin" aria-hidden /> : <Copy className="h-[15px] w-[15px]" aria-hidden />}+ </button>+ </QuickTooltip>+ </div>+ </div>{confirmDiscard && (- <div className="absolute inset-0 flex items-center justify-center bg-background/60 backdrop-blur-[2px]" data-testid="appshot-editor-discard">+ <div className="absolute inset-0 z-20 flex items-center justify-center bg-background/60 backdrop-blur-[2px]" data-testid="appshot-editor-discard"><div className="w-[min(360px,calc(100%-2rem))] rounded-2xl border border-border bg-popover p-5 text-popover-foreground shadow-2xl" role="alertdialog" aria-label={label("discard_title")}><p className="text-base font-semibold">{label("discard_title")}</p><p className="mt-1.5 text-sm text-muted-foreground">{label("discard_body")}</p>@@ -950,6 +1146,9 @@ export function AppshotEditor({ appshotId, onClose, onApplied }: AppshotEditorPr);}+const ROUND_ICON =+ "flex h-7 w-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-foreground/10 hover:text-foreground disabled:pointer-events-none disabled:opacity-40";+function Segmented({label,value,@@ -966,7 +1165,7 @@ function Segmented({return (<div className="flex items-center gap-2" data-testid={testId}><span className="text-muted-foreground">{label}</span>- <div className="flex items-center gap-0.5 rounded-lg bg-secondary/70 p-0.5" role="group" aria-label={label}>+ <div className="flex items-center gap-0.5 rounded-lg bg-foreground/10 p-0.5" role="group" aria-label={label}>{options.map((option) => (<buttonkey={option.value}diff --git a/tests/unit/appshot/test_appshot_editor.py b/tests/unit/appshot/test_appshot_editor.pyindex 587bb717bb..936bc47158 100644--- a/tests/unit/appshot/test_appshot_editor.py+++ b/tests/unit/appshot/test_appshot_editor.py@@ -196,3 +196,50 @@ def test_clipboard_image_picks_the_linux_tool(assert ok is (expected is not None)assert [command[0] for command in ran] == ([f"/usr/bin/{expected}"] if expected else [])+++# -- drag out: a file for the native drag bridge -------------------------------+++def test_drag_file_is_written_once_and_old_ones_are_swept(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ import os++ from jarvis.appshot import dragfile++ monkeypatch.setattr(dragfile.tempfile, "gettempdir", lambda: str(tmp_path))+ folder = dragfile.drag_folder()+ folder.mkdir()+ stale = folder / "appshot-old.png"+ stale.write_bytes(b"x")+ os.utime(stale, (1_000.0, 1_000.0))++ first = dragfile.write_drag_file(_png(), now=1_000.0 + dragfile.MAX_AGE_S + 5)+ second = dragfile.write_drag_file(_png(), now=1_000.0 + dragfile.MAX_AGE_S + 5)++ assert first is not None and second is not None and first != second+ assert first.read_bytes() == _png()+ assert not stale.exists()+++def test_drag_route_returns_a_path_on_the_desktop_only(+ monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ from jarvis.appshot import dragfile+ from jarvis.ui.web.appshot_routes import router++ monkeypatch.setattr(dragfile.tempfile, "gettempdir", lambda: str(tmp_path))+ app = FastAPI()+ app.include_router(router)+ app.state.native_file_actions = True+ client = TestClient(app)++ response = client.post("/api/appshot/drag-file", content=_png())+ assert response.status_code == 200, response.text+ path = response.json()["path"]+ assert path.startswith(str(tmp_path)) and path.endswith(".png")+ assert client.post("/api/appshot/drag-file", content=b"nope").status_code == 400++ app.state.native_file_actions = False+ assert client.post("/api/appshot/drag-file", content=_png()).status_code == 404