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): a saved edit flies back into the corner card
rubenluetke10-beep251dcafdc629
diff --git a/jarvis/appshot/card_actions.py b/jarvis/appshot/card_actions.pyindex 30d971aa91..1147c4c4fc 100644--- a/jarvis/appshot/card_actions.py+++ b/jarvis/appshot/card_actions.py@@ -130,8 +130,13 @@ async def run_card_action(action: str) -> str:return labels["failed"]-async def return_to_corner() -> bool:- """Slide the held appshot back into the corner card. ``False`` = not shown."""+async def return_to_corner(fly_from: list[float] | None = None) -> bool:+ """Bring the held appshot back into the corner card. ``False`` = not shown.++ ``fly_from`` (``[x, y, w, h]``, global logical pixels) is where the+ editor showed the picture: it then flies from there into the corner,+ like after the shutter. Without it the card slides in from the edge.+ """try:from jarvis.appshot.effect import card_hint, thumbnail_from_image # noqa: PLC0415from jarvis.appshot.store import get_store # noqa: PLC0415@@ -154,6 +159,7 @@ async def return_to_corner() -> bool:hint=card_hint(config),rest_ms=card_rest_ms(config),labels=card_labels(config),+ fly_from=fly_from,))except Exception: # noqa: BLE001 - the card is a convenience, never a failurediff --git a/jarvis/cu/indicator/controller.py b/jarvis/cu/indicator/controller.pyindex 89c539b9c9..28d1ec0110 100644--- a/jarvis/cu/indicator/controller.py+++ b/jarvis/cu/indicator/controller.py@@ -332,6 +332,7 @@ class CUIndicatorController:hint: str = "",rest_ms: int = 6000,labels: dict[str, str] | None = None,+ fly_from: list[float] | None = None,) -> bool:"""Put a picture straight back into the corner card — no flash, no flight.@@ -359,6 +360,7 @@ class CUIndicatorController:hint=hint,rest_ms=int(rest_ms),labels=dict(labels or {}),+ **({"from": list(fly_from)} if fly_from else {}),)if shown and image_b64:await asyncio.to_thread(diff --git a/jarvis/cu/indicator/renderer.py b/jarvis/cu/indicator/renderer.pyindex 86c127f4b7..e0c876d259 100644--- a/jarvis/cu/indicator/renderer.py+++ b/jarvis/cu/indicator/renderer.py@@ -239,6 +239,29 @@ def _lerp(a: float, b: float, t: float) -> float:return a + (b - a) * t+def _flight_origin(raw: object):+ """``(screen, rect as fractions of it)`` for a flight start, or ``None``.++ ``raw`` is ``[x, y, w, h]`` in global logical pixels — where the editor+ showed the picture. Anything unusable means "no flight".+ """+ if not isinstance(raw, list) or len(raw) != 4:+ return None+ try:+ x, y, w, h = (float(v) for v in raw)+ except (TypeError, ValueError):+ return None+ if w < 8 or h < 8:+ return None+ centre = QPointF(x + w / 2.0, y + h / 2.0).toPoint()+ screen = QGuiApplication.screenAt(centre) or QGuiApplication.primaryScreen()+ if screen is None:+ return None+ g = screen.geometry()+ gw, gh = max(1.0, float(g.width())), max(1.0, float(g.height()))+ return screen, [(x - g.x()) / gw, (y - g.y()) / gh, w / gw, h / gh]++def _match_screen(monitor: list[float]):"""The QScreen that best matches a capture-coordinate monitor rect.@@ -286,7 +309,16 @@ def _paint_card(painter: QPainter, rect: QRectF, thumb: QImage, radius: float, rclass _SnapWindow(QWidget):"""One monitor-sized, click-through canvas for the flash and the flight."""- def __init__(self, screen, rect_frac: list[float], thumb: QImage, on_landed, on_done) -> None:+ def __init__(+ self,+ screen,+ rect_frac: list[float],+ thumb: QImage,+ on_landed,+ on_done,+ *,+ flash: bool = True,+ ) -> None:super().__init__(None)self.setWindowFlags(Qt.WindowType.FramelessWindowHint@@ -309,6 +341,9 @@ class _SnapWindow(QWidget):self._thumb = thumbself._on_landed = on_landedself._on_done = on_done+ # No flash when the picture is not a fresh capture (back from the+ # editor): only the flight into the corner.+ self._flash = flashw, h = float(screen.geometry().width()), float(screen.geometry().height())fx, fy, fw, fh = (max(0.0, min(1.0, float(v))) for v in rect_frac)self._src = QRectF(fx * w, fy * h, max(1.0, fw * w), max(1.0, fh * h))@@ -395,7 +430,7 @@ class _SnapWindow(QWidget):_paint_card(painter, rect, self._thumb, _SNAP_RADIUS * fly, fly)flash = 1.0 - _ease_out_cubic(t / _SNAP_FLASH_MS)- if flash > 0.0:+ if self._flash and flash > 0.0:painter.setPen(Qt.PenStyle.NoPen)painter.setBrush(QColor(255, 255, 255, int(225 * flash)))painter.drawRect(self._src)@@ -1060,6 +1095,17 @@ class Renderer(QObject):self.card_image = Noneself._card_hint = str(payload.get("hint", "") or "")self._take_card_options(payload)+ origin = _flight_origin(payload.get("from"))+ if origin is not None:+ # Saved in the editor: the picture flies from the editor into+ # the corner, the same flight as after the shutter.+ fly_screen, frac = origin+ win = _SnapWindow(+ fly_screen, frac, thumb, self._snap_landed, self._snap_done, flash=False+ )+ self._snaps.append(win)+ win.start()+ returnself._new_card(_card_rect(screen, thumb), thumb).start(slide_in=True)def card_action(self, action: str) -> None:diff --git a/jarvis/ui/web/appshot_routes.py b/jarvis/ui/web/appshot_routes.pyindex 46319bca06..8f85509bab 100644--- a/jarvis/ui/web/appshot_routes.py+++ b/jarvis/ui/web/appshot_routes.py@@ -258,16 +258,24 @@ async def open_editor(body: OpenEditorRequest) -> dict[str, Any]:return {"window": await open_editor_window(body.id)}+class ReturnCardRequest(BaseModel):+ #: Where the editor showed the picture, ``[x, y, w, h]`` in global+ #: logical pixels: the saved picture flies from there into the corner.+ fly_from: list[float] | None = Field(default=None, min_length=4, max_length=4)++@router.post("/latest/card")-async def return_card() -> dict[str, Any]:- """Slide the held (edited) appshot back into the corner card.+async def return_card(body: ReturnCardRequest | None = None) -> dict[str, Any]:+ """Bring the held (edited) appshot back into the corner card.- The editor window calls this when it closes, so the picture stays at- hand like after the shutter. ``shown: false`` where no overlay can run.+ The editor calls this when it closes, so the picture stays at hand+ like after the shutter; after a save it flies there from the editor.+ ``shown: false`` where no overlay can run."""from jarvis.appshot.card_actions import return_to_corner # noqa: PLC0415- return {"shown": await return_to_corner()}+ fly_from = body.fly_from if body is not None else None+ return {"shown": await return_to_corner(fly_from)}def _png_size(data: bytes) -> tuple[int, int] | None:diff --git a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsx b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsxindex 274b02c12e..edd19ae50b 100644--- a/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsx+++ b/jarvis/ui/web/frontend/src/components/appshot/AppshotEditorHost.tsx@@ -19,6 +19,14 @@ const AppshotEditor = lazy(() =>* the editor. Escape and outside presses are left to the editor itself, which* cancels a stroke or asks before discarding edits.*/+function returnToCorner(flyFrom: [number, number, number, number]) {+ void fetch("/api/appshot/latest/card", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ fly_from: flyFrom }),+ }).catch(() => undefined);+}+export function AppshotEditorHost() {const openId = useAppshotEditor((s) => s.openId);const close = useAppshotEditor((s) => s.close);@@ -38,7 +46,16 @@ export function AppshotEditorHost() {<Dialog.Title className="sr-only">Appshot editor</Dialog.Title>{openId !== null && (<Suspense fallback={<div className="h-full w-full bg-background" />}>- <AppshotEditor key={openId} appshotId={openId} onClose={close} onApplied={applied} />+ <AppshotEditor+ key={openId}+ appshotId={openId}+ onClose={(exit) => {+ // Saved or used: the picture flies back into the corner card.+ if (exit?.flyFrom) returnToCorner(exit.flyFrom);+ close();+ }}+ onApplied={applied}+ /></Suspense>)}</Dialog.Content>diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsxindex 6494b9bc18..734d0e3fcd 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditor.tsx@@ -178,9 +178,19 @@ interface Typing {replaceId: number | null;}+/**+ * How the editor ended when it ended with a result (Save or Done): where the+ * picture was on screen, ``[x, y, w, h]`` in global logical pixels, so it can+ * fly from there back into the corner card.+ */+export interface EditorExit {+ flyFrom?: [number, number, number, number];+}+export interface AppshotEditorProps {appshotId: string;- onClose: () => void;+ /** Closed; ``exit`` is set when it closed with a saved or used picture. */+ onClose: (exit?: EditorExit) => void;/** The edited picture replaced the held appshot (and went to the assistant). */onApplied?: () => void;/**@@ -551,20 +561,42 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla}}, [native, pushToast, render, t]);+ /** Where the picture is on screen right now, for the flight back to the corner. */+ const flyFrom = useCallback((): EditorExit["flyFrom"] => {+ const canvas = canvasRef.current;+ if (!canvas) return undefined;+ const r = canvas.getBoundingClientRect();+ // A framed window adds its title bar and borders above/around the page.+ const chromeX = Math.max(0, (window.outerWidth - window.innerWidth) / 2);+ const chromeY = Math.max(0, window.outerHeight - window.innerHeight - chromeX);+ return [window.screenX + chromeX + r.left, window.screenY + chromeY + r.top, r.width, r.height];+ }, []);+const save = useCallback(async () => {setBusy("save");+ let saved = false;try {const blob = await render();const filename = `appshot-${stamp()}.png`;const path = await saveOrDownload({ filename, blob, native });setDirty(false);+ saved = true;if (path) pushToast("success", fill(t("appshot_editor.saved_to"), { 0: path }), { filePath: path, filename });+ // The saved state is the appshot from now on: the corner card, a drag+ // and the next message all carry the edit. A gone appshot only skips this.+ await fetch(`/api/appshot/latest/image?id=${encodeURIComponent(appshotId)}`, {+ method: "PUT",+ headers: { "content-type": "image/png" },+ body: blob,+ }).catch(() => undefined);} catch (error) {pushToast("error", fill(t("appshot_editor.save_failed"), { 0: (error as Error).message }));} finally {setBusy("");}- }, [native, pushToast, render, t]);+ // Saved: back into the corner, flying from where the picture is now.+ if (saved) onClose({ flyFrom: flyFrom() });+ }, [appshotId, flyFrom, native, onClose, pushToast, render, t]);const use = useCallback(async () => {setBusy("apply");@@ -591,13 +623,13 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla);setDirty(false);onApplied?.();- onClose();+ onClose({ flyFrom: flyFrom() });} catch (error) {pushToast("error", fill(t("appshot_editor.apply_failed"), { 0: (error as Error).message }));} finally {setBusy("");}- }, [appshotId, assistantName, onApplied, onClose, pushToast, render, t]);+ }, [appshotId, assistantName, flyFrom, onApplied, onClose, pushToast, render, t]);const requestClose = useCallback(() => {if (dirty && ops.length > 0) setConfirmDiscard(true);@@ -992,7 +1024,7 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla{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}>+ <Button type="button" variant="secondary" size="sm" onClick={() => onClose()}>{label("close")}</Button></div>@@ -1161,7 +1193,7 @@ export function AppshotEditor({ appshotId, onClose, onApplied, variant = "overla<Button type="button" variant="secondary" size="sm" autoFocus onClick={() => setConfirmDiscard(false)}>{label("discard_keep")}</Button>- <Button type="button" variant="destructive" size="sm" onClick={onClose} data-testid="appshot-editor-discard-confirm">+ <Button type="button" variant="destructive" size="sm" onClick={() => onClose()} data-testid="appshot-editor-discard-confirm">{label("discard_confirm")}</Button></div>diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsxindex ac7cc2e035..202cac1b5d 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx@@ -68,6 +68,49 @@ describe("the appshot editor window", () => {await waitFor(() => expect(order).toEqual(["card", "close"]));});+ it("after Save the edited picture becomes the appshot and flies back to the corner", async () => {+ const proxy: ProxyHandler<object> = {+ get: (_t, key) =>+ key === "measureText" ? () => ({ width: 10 }) : new Proxy(() => undefined, { ...proxy, apply: () => new Proxy({}, proxy) }),+ set: () => true,+ };+ vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => new Proxy({}, proxy) as never);+ vi.spyOn(HTMLCanvasElement.prototype, "toBlob").mockImplementation((done: BlobCallback) =>+ done(new Blob(["png"], { type: "image/png" })),+ );+ vi.stubGlobal("URL", Object.assign(URL, { createObjectURL: () => "blob:x", revokeObjectURL: () => undefined }));+ const calls: string[] = [];+ vi.stubGlobal(+ "fetch",+ vi.fn(async (url: string, init?: RequestInit) => {+ calls.push(`${init?.method ?? "GET"} ${url}`);+ return json({ native_file_actions: false, platform: "linux" });+ }),+ );+ const flights: unknown[] = [];+ const closeWindow = vi.fn(async () => undefined);+ render(+ <AppshotEditorWindow+ deps={{+ returnCard: async (flyFrom) => {+ flights.push(flyFrom);+ },+ closeWindow,+ }}+ />,+ );+ await screen.findByTestId("appshot-editor-canvas");++ fireEvent.click(screen.getByTestId("appshot-editor-save"));++ await waitFor(() => expect(closeWindow).toHaveBeenCalledTimes(1));+ expect(calls).toContain("PUT /api/appshot/latest/image?id=a1b2c3d4");+ expect(flights).toHaveLength(1);+ const from = flights[0] as number[];+ expect(Array.isArray(from) && from.length === 4).toBe(true);+ vi.restoreAllMocks();+ });+it("still closes when the card cannot come back", async () => {const closeWindow = vi.fn(async () => undefined);render(<AppshotEditorWindow deps={{ returnCard: () => Promise.reject(new Error("no overlay")), closeWindow }} />);diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsxindex 7c5b7bedf6..eefb84bc52 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx@@ -1,16 +1,18 @@import { useCallback, useRef } from "react";import { ToastLayer } from "@/components/ToastLayer";-import { AppshotEditor } from "@/views/AppshotEditor";+import { AppshotEditor, type EditorExit } from "@/views/AppshotEditor";/*** The appshot editor as its own desktop window (`?view=appshot-editor&solo=1* &appshot=<id>`), opened by a click on the corner card — CleanShot X's* editor window. Nothing of the app is loaded around it.*- * When it closes — Done or Close — the appshot slides back into the screen- * corner (`POST /api/appshot/latest/card`), so it stays at hand, and then the- * window closes itself through the shell (`POST /api/window/reattach`).+ * When it closes the appshot goes back into the screen corner+ * (`POST /api/appshot/latest/card`), so it stays at hand — after Save or Done+ * it flies there from where the editor showed it, after Close it slides in —+ * and then the window closes itself through the shell+ * (`POST /api/window/reattach`).*/export const APPSHOT_EDITOR_VIEW = "appshot-editor";@@ -27,12 +29,17 @@ export function isAppshotEditorWindow(search: string): boolean {}export interface EditorWindowDeps {- returnCard: () => Promise<unknown>;+ returnCard: (flyFrom?: EditorExit["flyFrom"]) => Promise<unknown>;closeWindow: () => Promise<unknown>;}const browserDeps: EditorWindowDeps = {- returnCard: () => fetch("/api/appshot/latest/card", { method: "POST" }),+ returnCard: (flyFrom) =>+ fetch("/api/appshot/latest/card", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(flyFrom ? { fly_from: flyFrom } : {}),+ }),closeWindow: () =>fetch("/api/window/reattach", {method: "POST",@@ -45,13 +52,13 @@ export function AppshotEditorWindow({ deps = browserDeps }: { deps?: EditorWindoconst appshotId = appshotIdFromUrl(window.location.search);const closing = useRef(false);- const close = useCallback(() => {+ const close = useCallback((exit?: EditorExit) => {if (closing.current) return;closing.current = true;// Back into the corner first: the window must not take the card's// request down with it.void deps- .returnCard()+ .returnCard(exit?.flyFrom).catch(() => undefined).finally(() => {void deps.closeWindow().catch(() => undefined);diff --git a/tests/unit/appshot/test_appshot_editor.py b/tests/unit/appshot/test_appshot_editor.pyindex 936bc47158..1f2e6c5cd6 100644--- a/tests/unit/appshot/test_appshot_editor.py+++ b/tests/unit/appshot/test_appshot_editor.py@@ -243,3 +243,57 @@ def test_drag_route_returns_a_path_on_the_desktop_only(app.state.native_file_actions = Falseassert client.post("/api/appshot/drag-file", content=_png()).status_code == 404+++# -- saved in the editor: the picture flies back into the corner ---------------+++def test_the_card_route_hands_the_flight_start_through(monkeypatch: pytest.MonkeyPatch) -> None:+ from jarvis.appshot import card_actions+ from jarvis.ui.web.appshot_routes import router++ seen: list = []++ async def fake_return(fly_from=None):+ seen.append(fly_from)+ return True++ monkeypatch.setattr(card_actions, "return_to_corner", fake_return)+ app = FastAPI()+ app.include_router(router)+ client = TestClient(app)++ saved = client.post("/api/appshot/latest/card", json={"fly_from": [100, 80, 640, 400]})+ closed = client.post("/api/appshot/latest/card")++ assert saved.json() == {"shown": True} and closed.json() == {"shown": True}+ assert seen == [[100.0, 80.0, 640.0, 400.0], None]+ assert client.post("/api/appshot/latest/card", json={"fly_from": [1, 2]}).status_code == 422+++async def test_the_card_command_carries_the_flight_start(monkeypatch: pytest.MonkeyPatch) -> None:+ from jarvis.cu.indicator import protocol+ from jarvis.cu.indicator.controller import CUIndicatorController++ class _Proc:+ @staticmethod+ def poll() -> None:+ return None++ controller = CUIndicatorController(bus=None)+ sent: list[tuple[str, dict]] = []+ monkeypatch.setattr(controller, "_border_capability", lambda: (True, ""))+ monkeypatch.setattr(controller, "_spawn_sidecar", lambda: setattr(controller, "_proc", _Proc()))+ monkeypatch.setattr(+ controller,+ "_send_and_wait",+ lambda cmd, _timeout, **fields: sent.append((cmd, fields)) or True,+ )++ flight = [1.0, 2.0, 300.0, 200.0]+ assert await controller.show_card(thumb_b64="t", image_b64="", fly_from=flight)+ assert await controller.show_card(thumb_b64="t", image_b64="")++ cards = [fields for cmd, fields in sent if cmd == protocol.CMD_CARD]+ assert cards[0]["from"] == [1.0, 2.0, 300.0, 200.0]+ assert "from" not in cards[1], "a plain close slides in, it does not fly"