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
ci(appshot): check appshots on real macOS, Linux and Windows desktops
rubenluetke10-beep1f296f99386a
diff --git a/.github/workflows/appshot-cross-os.yml b/.github/workflows/appshot-cross-os.ymlnew file mode 100644index 0000000000..a939f91a38--- /dev/null+++ b/.github/workflows/appshot-cross-os.yml@@ -0,0 +1,171 @@+# Appshots on real desktops: macOS (Apple Silicon + Intel), Linux (X11 under+# Xvfb, Wayland under headless sway, and a bare headless box) and Windows.+#+# Unit tests fake the OS. scripts/ci/appshot_desktop_smoke.py does not: it+# copies pictures and text to the runner's real clipboard and reads them back+# with the OS's own tools, burns markings, keeps a gallery entry, saves a PNG+# and takes a real appshot through the shortcut service. Free on public repos.++name: Appshots cross-OS++on:+ workflow_dispatch:+ push:+ branches: ["test/appshot-**", "claude/appshot-**"]+ pull_request:+ paths:+ - "jarvis/appshot/**"+ - "jarvis/jarvisx/**"+ - "jarvis/platform/clipboard*.py"+ - "jarvis/ui/web/appshot_routes.py"+ - "scripts/ci/appshot_desktop_smoke.py"+ - "tests/unit/appshot/**"+ - ".github/workflows/appshot-cross-os.yml"++permissions:+ contents: read++concurrency:+ group: appshot-cross-os-${{ github.ref }}+ cancel-in-progress: true++env:+ PYTHONUTF8: "1"+ APPSHOT_TESTS: >-+ tests/unit/appshot tests/unit/jarvisx tests/unit/platform/test_clipboard.py+ tests/unit/platform/test_clipboard_image.py tests/unit/platform/test_clipboard_reader.py++jobs:+ linux:+ name: Linux (X11 + Wayland)+ runs-on: ubuntu-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.11"+ cache: pip+ cache-dependency-path: pyproject.toml+ - name: Desktop packages+ run: |+ sudo apt-get update -qq+ sudo apt-get install -y -qq --no-install-recommends xvfb xauth xclip xsel \+ wl-clipboard sway libegl1 libxkbcommon-x11-0 libxcb-cursor0 libxcb-icccm4 \+ libxcb-keysyms1 libxcb-shape0 libxcb-xinerama0 libxcb-randr0 \+ libxcb-render-util0 libxcb-image0 libportaudio2 ffmpeg+ - name: Install+ run: python -m pip install -e ".[dev,desktop]"+ - name: Unit tests (no display, Qt offscreen)+ env:+ QT_QPA_PLATFORM: offscreen+ run: python -m pytest -q -p no:cacheprovider $APPSHOT_TESTS --junitxml=out/junit-linux.xml+ - name: Smoke — no display+ run: env -u DISPLAY -u WAYLAND_DISPLAY python scripts/ci/appshot_desktop_smoke.py --headless --report out/smoke-headless.json+ - name: Smoke — X11 (Xvfb)+ run: xvfb-run -a -s "-screen 0 1920x1080x24" python scripts/ci/appshot_desktop_smoke.py --expect-capture --report out/smoke-x11.json+ # Headless sway, not weston: wlroots offers a seat (and the data-control+ # protocol wl-copy uses) even with no input device; weston's headless+ # backend has no seat, so wl-copy fails there with "Missing a seat".+ - name: Smoke — Wayland (headless sway)+ run: |+ export XDG_RUNTIME_DIR="$RUNNER_TEMP/xdg"+ mkdir -p -m 700 "$XDG_RUNTIME_DIR"+ WLR_BACKENDS=headless WLR_LIBINPUT_NO_DEVICES=1 WLR_RENDERER=pixman \+ sway -c /dev/null > out/sway.log 2>&1 &+ for _ in $(seq 1 100); do ls "$XDG_RUNTIME_DIR"/wayland-* >/dev/null 2>&1 && break; sleep 0.1; done+ SOCKET=$(basename "$(ls "$XDG_RUNTIME_DIR"/wayland-* | grep -v lock | head -1)")+ WAYLAND_DISPLAY="$SOCKET" env -u DISPLAY python scripts/ci/appshot_desktop_smoke.py --report out/smoke-wayland.json+ - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3+ if: always()+ with:+ name: appshot-linux+ path: out/+ retention-days: 14++ linux-base-install:+ name: Linux headless (base install, python:3.11-slim)+ runs-on: ubuntu-latest+ timeout-minutes: 20+ container: python:3.11-slim+ steps:+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false+ - name: Base install only (no desktop extras)+ run: python -m pip install -e .+ - name: Smoke — the appshot code degrades without a display or extras+ run: python scripts/ci/appshot_desktop_smoke.py --headless --report out/smoke-base.json+ - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3+ if: always()+ with:+ name: appshot-linux-base+ path: out/+ retention-days: 14++ macos:+ name: macOS ${{ matrix.name }}+ strategy:+ fail-fast: false+ matrix:+ include:+ - name: Apple Silicon+ runner: macos-15+ - name: Intel+ runner: macos-15-intel+ runs-on: ${{ matrix.runner }}+ timeout-minutes: 40+ steps:+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ cache: pip+ cache-dependency-path: pyproject.toml+ - name: Install+ run: python -m pip install -e ".[dev,desktop,desktop-macos]"+ - name: Unit tests+ env:+ QT_QPA_PLATFORM: offscreen+ run: python -m pytest -q -p no:cacheprovider $APPSHOT_TESTS --junitxml=out/junit-macos.xml+ # Screen Recording is a TCC grant CI cannot give, so a real capture may be+ # refused here; the clipboard, markings, gallery and Save must all work.+ - name: Smoke — real pasteboard+ run: python scripts/ci/appshot_desktop_smoke.py --report out/smoke-macos.json+ - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3+ if: always()+ with:+ name: appshot-macos-${{ matrix.runner }}+ path: out/+ retention-days: 14++ windows:+ name: Windows+ runs-on: windows-latest+ timeout-minutes: 40+ steps:+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2+ with:+ persist-credentials: false+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.11"+ cache: pip+ cache-dependency-path: pyproject.toml+ - name: Install+ run: python -m pip install -e ".[dev,desktop]"+ - name: Unit tests+ shell: bash+ run: python -m pytest -q -p no:cacheprovider $APPSHOT_TESTS --junitxml=out/junit-windows.xml+ - name: Smoke — real clipboard and capture+ run: python scripts/ci/appshot_desktop_smoke.py --expect-capture --report out/smoke-windows.json+ - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3+ if: always()+ with:+ name: appshot-windows+ path: out/+ retention-days: 14diff --git a/scripts/ci/appshot_desktop_smoke.py b/scripts/ci/appshot_desktop_smoke.pynew file mode 100644index 0000000000..aa3d95eda9--- /dev/null+++ b/scripts/ci/appshot_desktop_smoke.py@@ -0,0 +1,401 @@+#!/usr/bin/env python3+"""Exercise the appshot feature on a REAL desktop session and read the results back.++Unit tests fake the OS; this script does not. It copies pictures and text to+the real clipboard and reads them back with the OS's own tools, burns markings+into a picture, keeps an appshot in the gallery, saves one to Downloads, and+takes a real appshot through the same service the shortcuts use.++Run it only where a desktop session exists that may be clobbered (a CI+runner, Xvfb, a headless Wayland compositor, a container): it REPLACES the+clipboard. Data and config go to a temporary folder, never the user's.++ python scripts/ci/appshot_desktop_smoke.py --report out/appshot-smoke.json+ python scripts/ci/appshot_desktop_smoke.py --expect-capture # capture must work+ python scripts/ci/appshot_desktop_smoke.py --headless # no display: degrade++Exit code 1 when a check that must pass on this host failed.+"""++from __future__ import annotations++import argparse+import asyncio+import io+import json+import os+import platform+import shutil+import subprocess+import sys+import tempfile+import time+import traceback+import uuid+from pathlib import Path++# Isolate data + config BEFORE anything imports jarvis.core.config.+_SANDBOX = Path(tempfile.mkdtemp(prefix="appshot-smoke-"))+os.environ.setdefault("JARVIS_DATA_DIR", str(_SANDBOX / "data"))+_CONFIG = _SANDBOX / "jarvis.toml"+_CONFIG.write_text("[screen_context]\nenabled = true\n", encoding="utf-8")+os.environ.setdefault("JARVIS_CONFIG", str(_CONFIG))++REPO_ROOT = Path(__file__).resolve().parents[2]+if str(REPO_ROOT) not in sys.path:+ sys.path.insert(0, str(REPO_ROOT))++_TIMEOUT_S = 10.0+++class Report:+ def __init__(self) -> None:+ self.checks: list[dict] = []++ def add(self, name: str, ok: bool, detail: str = "", *, required: bool = True) -> None:+ self.checks.append({"name": name, "ok": ok, "required": required, "detail": detail})+ mark = "PASS" if ok else ("FAIL" if required else "info")+ print(f"[{mark}] {name}{': ' + detail if detail else ''}", flush=True)++ @property+ def failed(self) -> list[dict]:+ return [c for c in self.checks if c["required"] and not c["ok"]]+++def _png(alpha: bool = True) -> bytes:+ from PIL import Image++ image = Image.new("RGBA", (64, 48), (0, 0, 0, 0) if alpha else (255, 255, 255, 255))+ for x in range(8, 56):+ for y in range(8, 40):+ image.putpixel((x, y), (30, 140, 230, 255))+ out = io.BytesIO()+ image.save(out, "PNG")+ return out.getvalue()+++def _run(command: list[str], data: bytes | None = None) -> tuple[int, bytes]:+ """Run a READER command (it exits on its own); ``(returncode, stdout)``."""+ try:+ done = subprocess.run( # noqa: S603 - fixed OS reader commands+ command, input=data, capture_output=True, timeout=_TIMEOUT_S, check=False+ )+ except (OSError, subprocess.SubprocessError) as exc:+ return -1, str(exc).encode()+ return done.returncode, done.stdout+++def _session() -> str:+ if sys.platform == "win32":+ return "windows"+ if sys.platform == "darwin":+ return "macos"+ if os.environ.get("WAYLAND_DISPLAY"):+ return "wayland"+ if os.environ.get("DISPLAY"):+ return "x11"+ return "headless"+++# -- reading the clipboard back with the OS's own tools ----------------------++_MACOS_READ = """+function run(argv) {+ ObjC.import('AppKit');+ var board = $.NSPasteboard.generalPasteboard;+ var types = ObjC.deepUnwrap(board.types) || [];+ var data = board.dataForType('public.png');+ if (!data.isNil()) { data.writeToFileAtomically(argv[0], true); }+ var tiff = board.dataForType('public.tiff');+ return JSON.stringify({types: types, tiff: tiff.isNil() ? 0 : tiff.length});+}+"""+++def read_back_image() -> tuple[set[str], bytes | None, str]:+ """``(formats offered, png bytes or None, note)`` as another app would see them."""+ session = _session()+ if session == "windows":+ import ctypes+ from ctypes import wintypes++ from PIL import ImageGrab++ user32 = ctypes.WinDLL("user32")+ user32.EnumClipboardFormats.argtypes = [wintypes.UINT]+ user32.EnumClipboardFormats.restype = wintypes.UINT+ user32.GetClipboardFormatNameW.argtypes = [wintypes.UINT, wintypes.LPWSTR, ctypes.c_int]+ names: set[str] = set()+ if user32.OpenClipboard(None):+ try:+ fmt = 0+ while fmt := user32.EnumClipboardFormats(fmt):+ buf = ctypes.create_unicode_buffer(64)+ user32.GetClipboardFormatNameW(fmt, buf, 64)+ names.add(+ buf.value+ or {2: "CF_BITMAP", 8: "CF_DIB", 17: "CF_DIBV5"}.get(fmt, str(fmt))+ )+ finally:+ user32.CloseClipboard()+ grabbed = ImageGrab.grabclipboard()+ out = io.BytesIO()+ if grabbed is not None and hasattr(grabbed, "save"):+ grabbed.save(out, "PNG")+ return names, out.getvalue() or None, f"pillow read {getattr(grabbed, 'size', None)}"+ if session == "macos":+ target = _SANDBOX / "pasteboard.png"+ code, out = _run(["/usr/bin/osascript", "-l", "JavaScript", "-e", _MACOS_READ, str(target)])+ if code != 0:+ return set(), None, f"osascript exit {code}: {out[:200]!r}"+ info = json.loads(out.decode("utf-8", "replace") or "{}")+ png = target.read_bytes() if target.exists() else None+ return set(info.get("types", [])), png, f"tiff bytes {info.get('tiff')}"+ if session == "wayland":+ code, out = _run(["wl-paste", "--list-types"])+ types = set(out.decode("utf-8", "replace").split()) if code == 0 else set()+ code, png = _run(["wl-paste", "--no-newline", "--type", "image/png"])+ return types, png if code == 0 else None, "wl-paste"+ if session == "x11":+ code, out = _run(["xclip", "-selection", "clipboard", "-t", "TARGETS", "-o"])+ types = set(out.decode("utf-8", "replace").split()) if code == 0 else set()+ code, png = _run(["xclip", "-selection", "clipboard", "-t", "image/png", "-o"])+ return types, png if code == 0 else None, "xclip"+ return set(), None, "no display"+++def _same_pixels(a: bytes, b: bytes | None) -> bool:+ if not b:+ return False+ from PIL import Image++ with Image.open(io.BytesIO(a)) as one, Image.open(io.BytesIO(b)) as two:+ return one.convert("RGBA").tobytes() == two.convert("RGBA").tobytes()+++EXPECTED_FORMATS = {+ "windows": {"PNG", "CF_DIB"},+ "macos": {"public.png", "public.tiff"},+ "x11": {"image/png"},+ "wayland": {"image/png"},+}+++# -- checks --------------------------------------------------------------------+++def check_image_clipboard(report: Report) -> None:+ from jarvis.platform.clipboard_image import copy_image++ session = _session()+ png = _png()+ started = time.monotonic()+ result = copy_image(png)+ took = time.monotonic() - started+ if session == "headless":+ report.add(+ "image copy degrades without a display", result.reason == "no_display", result.reason+ )+ return+ report.add(+ "image copy accepted by the OS", result.ok, f"{result.formats} reason={result.reason!r}"+ )+ report.add("image copy returns promptly", took < 3.0, f"{took:.2f}s")+ formats, pasted, note = read_back_image()+ expected = EXPECTED_FORMATS[session]+ report.add(+ "clipboard offers every expected format",+ expected <= formats,+ f"offered={sorted(formats)} expected={sorted(expected)} ({note})",+ )+ report.add("pasted picture equals the copied one", _same_pixels(png, pasted), note)+++def check_text_clipboard(report: Report) -> None:+ from jarvis.platform.clipboard import read_text, write_text++ # i18n-allow: umlauts and symbols prove the non-ASCII clipboard round trip.+ text = f"Appshot text check — Größe ✓ {uuid.uuid4().hex[:6]}" # i18n-allow+ if _session() == "headless":+ report.add("text copy degrades without a display", write_text(text) is False)+ return+ started = time.monotonic()+ ok = write_text(text)+ took = time.monotonic() - started+ report.add("text copy accepted by the OS", ok)+ report.add("text copy returns promptly", took < 3.0, f"{took:.2f}s")+ report.add("text reads back unchanged", read_text() == text)+++def check_jarvisx_copy(report: Report) -> None:+ from jarvis.jarvisx.clipboard import copy_png++ ok, message = copy_png(_png(alpha=False))+ expected = _session() != "headless"+ report.add("Jarvis X copy", ok is expected, message)+++def _appshot(png: bytes):+ from jarvis.appshot.store import Appshot++ return Appshot(+ id=uuid.uuid4().hex,+ image=png,+ mime="image/png",+ width=64,+ height=48,+ label="selected area",+ app_name="Smoke",+ note="APPSHOT: smoke",+ ui_text="smoke text",+ trigger="button",+ taken_at=time.time(),+ )+++def check_markup_burn(report: Report) -> None:+ import base64++ from PIL import Image++ from jarvis.appshot import markup++ overlay = Image.new("RGBA", (64, 48), (0, 0, 0, 0))+ for x in range(40, 60):+ overlay.putpixel((x, 44), (255, 0, 0, 255))+ buffer = io.BytesIO()+ overlay.save(buffer, "PNG")+ payload = {+ "overlay": base64.b64encode(buffer.getvalue()).decode("ascii"),+ "hides": [{"kind": "pixelate", "rect": [0.1, 0.1, 0.5, 0.5]}],+ }+ parsed = markup.parse_markup(payload)+ report.add("markings payload parses", parsed is not None and len(parsed.hides) == 1)+ if parsed is None:+ return+ burnt = markup.apply_to_bytes(_png(alpha=False), "image/png", parsed)+ with Image.open(io.BytesIO(burnt)) as picture:+ red = picture.convert("RGB").getpixel((50, 44))+ report.add("markings burn into the picture", red[0] > 200 and red[1] < 60, f"pixel {red}")+++def check_library_and_downloads(report: Report) -> None:+ from jarvis.appshot import library+ from jarvis.appshot.card_actions import save_shot_to_downloads++ shot = _appshot(_png(alpha=False))+ report.add("gallery keeps the appshot", library.save(shot) is True)+ kept = list((library.library_root()).rglob("*.png"))+ report.add("gallery file is on disk", bool(kept), str(library.library_root()))+ folder = _SANDBOX / "Downloads"+ folder.mkdir(exist_ok=True)+ path = save_shot_to_downloads(shot, folder=folder)+ report.add(+ "Save writes a PNG", path.exists() and path.read_bytes().startswith(b"\x89PNG"), path.name+ )+++def check_real_appshot(report: Report, *, expect_capture: bool) -> None:+ from jarvis.appshot import service++ async def no_library(_shot, _config) -> None:+ return None++ service._keep_in_library = no_library # noqa: SLF001 - keep the sandbox gallery clean+ from jarvis.platform.clipboard import write_text++ write_text("before-appshot")++ async def take():+ result = await service.take_appshot(trigger="button", deliver=False)+ while service._COPIES: # noqa: SLF001+ await asyncio.gather(*service._COPIES) # noqa: SLF001+ return result++ try:+ result = asyncio.run(asyncio.wait_for(take(), timeout=60))+ except Exception as exc: # noqa: BLE001 - the report says what broke+ report.add("real appshot never raises", False, f"{type(exc).__name__}: {exc}")+ return+ report.add("real appshot never raises", True)+ detail = f"status={result.status} reason={result.reason_code!r} message={result.message!r}"+ if result.ok:+ shot = result.shot+ report.add(+ "real appshot captured", True, f"{shot.width}x{shot.height} {shot.label} {detail}"+ )+ formats, pasted, note = read_back_image()+ report.add(+ "real appshot landed on the clipboard",+ bool(pasted) and EXPECTED_FORMATS.get(_session(), set()) <= formats,+ f"offered={sorted(formats)} ({note})",+ )+ else:+ report.add("real appshot captured", False, detail, required=expect_capture)+ report.add("a refusal explains itself", bool(result.message), result.message)+++def check_headless_imports(report: Report) -> None:+ for module in (+ "jarvis.appshot.service",+ "jarvis.appshot.card_actions",+ "jarvis.appshot.library",+ "jarvis.ui.web.appshot_routes",+ "jarvis.jarvisx.service",+ "jarvis.platform.clipboard_image",+ ):+ try:+ __import__(module)+ report.add(f"imports without a display: {module}", True)+ except Exception as exc: # noqa: BLE001+ report.add(+ f"imports without a display: {module}", False, f"{type(exc).__name__}: {exc}"+ )+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--report", type=Path, default=None)+ parser.add_argument("--expect-capture", action="store_true")+ parser.add_argument("--headless", action="store_true", help="assert the no-display path")+ args = parser.parse_args()++ report = Report()+ session = _session()+ host = f"{platform.platform()} / Python {platform.python_version()}"+ print(f"appshot smoke on {host} / session={session}")+ if args.headless and session != "headless":+ report.add("headless run has no display", False, session)+ steps = [+ check_headless_imports,+ check_image_clipboard,+ check_text_clipboard,+ check_jarvisx_copy,+ ]+ steps += [check_markup_burn, check_library_and_downloads]+ for step in steps:+ try:+ step(report)+ except Exception as exc: # noqa: BLE001 - one broken check never hides the rest+ report.add(step.__name__, False, "".join(traceback.format_exception_only(exc)).strip())+ if session != "headless":+ check_real_appshot(report, expect_capture=args.expect_capture)++ if args.report:+ args.report.parent.mkdir(parents=True, exist_ok=True)+ args.report.write_text(+ json.dumps(+ {"session": session, "platform": platform.platform(), "checks": report.checks},+ indent=2,+ ),+ encoding="utf-8",+ )+ shutil.rmtree(_SANDBOX, ignore_errors=True)+ failed = report.failed+ passed = len(report.checks) - len(failed)+ print(f"\n{passed}/{len(report.checks)} checks ok; {len(failed)} required failed")+ return 1 if failed else 0+++if __name__ == "__main__":+ sys.exit(main())