Skip to content

feat(desktop): capture a Linux desktop application in use - #8874

Closed
earakely-scale wants to merge 15 commits into
morluto:mainfrom
earakely-scale:feat/capture-desktop-application
Closed

earakely-scale wants to merge 15 commits into
morluto:mainfrom
earakely-scale:feat/capture-desktop-application

Conversation

@earakely-scale

@earakely-scale earakely-scale commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds rea capture-desktop-application, the first step toward turning an application installed on someone's Linux desktop into an agent environment computer application. It launches the application on the user's X11 display, watches it while a person or a driver uses it, and writes a capture folder: Evidence in capture.json and the bytes of retained files in content/<sha256>. Later steps (state view, export, verification, tasks) read this folder; this PR builds no environment.

The overall plan is in docs/specs/desktop-app-environments/README.md; this step's spec, plan and verification are in docs/specs/desktop-app-environments/capture/.

Problem and expected behavior

Building a computer application environment for a real desktop application today means writing its class by hand: how to install it, how to launch it and recognise its window, and which files hold its state. REA can observe all of that. Native UI capture is macOS only and process capture is built for terminal programs, so nothing in REA could watch a Linux GUI application and the files it changes.

After this change, a capture records:

  • Application: desktop entry, launch command, executable, package (dpkg owner with version, the apt sources listing it and apt's archive origin for each; snap, flatpak and AppImage from paths), Electron markers, and candidate state directories.
  • Session: the launched process tree, client windows from xprop with titles, owner pid and type, the time the first application window appeared, a window match (class and instance), and files the application held open.
  • State: a stat walk of the home directory before launch, at each checkpoint read from stdin, at stop and after exit; created, modified, deleted and retyped paths between checkpoints; and the content of every changed file plus everything under the state directories at baseline.

Change and scope

  • CLI only. A capture is a long interactive session (stdin lines mark checkpoints; stop or end of input ends it; empty, duplicate and reserved checkpoint names are refused), like environment-serve. No MCP tool or catalog change.
  • Linux and X11 only: other hosts, a missing DISPLAY or xprop, a window manager without EWMH _NET_CLIENT_LIST support, a non-empty output folder, and an application that already has a window open are refused before anything is launched or written.
  • Walks stay on each root's device (mount points under the home are named, not entered). / or a directory containing the home is never walked or retained as an argument. A capture that fails before capture.json is written removes the content it retained.
  • Pure parsers live in src/domain/desktop/, host adapters in a new src/desktop/ root (added to the adapters test project), and orchestration and Evidence in src/application/desktop/. It reuses readLinuxProcessStat/readLinuxChildren, execFileOutput and readElectronFuseImage.
  • The application starts in its own process group. On stop, end of input, the time limit or an error, REA sends SIGTERM to that group and to every process carrying the run token, then SIGKILL after five seconds. Incomplete cleanup is reported with its facts. A process found only as the owner of a matching window is never signalled.
  • Not included: state view and format readers, export, writer attribution, click or keystroke recording, Wayland-native windows, redaction of the user's files.

Contract and boundary impact

  • Semantic owner and earliest changed stage: new producer capture_desktop_application; no existing producer or consumer changes.
  • Contribution scope fit and linked maintainer decision: this launches a target application, so it needs a maintainer scope decision. morluto approved this line of work with the author directly; it is not yet recorded on GitHub, so this stays a draft until that is confirmed here.
  • CLI and MCP/tool-catalog contract: one new CLI command; MCP catalog unchanged (mcp-catalog:check passes).
  • Provider, bridge, target-format, or platform compatibility: Linux with X11 and xprop (x11-utils) only; REA_XPROP_COMMAND overrides the binary.
  • Evidence, artifact, provenance, or reconstruction contract: new Evidence with provider rea-desktop v1, operation capture_desktop_application, predicate rea.desktop-application-capture, confidence: observed, authority: controlled-replay; parameters carry only counts and the launch kind.
  • Target selection, authority, upstream behavior, and cleanup details: the caller names the application; it runs with the user's permissions against their real files. REA writes only the output folder and signals only processes it started.
  • Generated metadata: the product catalog gains capture-desktop-application (ignored, regenerated by CI).

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration. (REA writes the output folder and terminates the processes it launched; the launched application changes the user's files as it is used.)
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: parser tests for desktop entries, Exec lines, xprop, dpkg and apt-cache output, package paths and walk diffs; adapter tests for the home walk, content store and inventory; service tests for every refusal; and three Linux captures of a fake application with a stub xprop (checkpoint with before and after content, application exiting on its own, refusal while already open).
  • Base reproduction or other evidence: Mousepad end to end in an Ubuntu 24.04 container under Xvfb and xfwm4, driven by xdotool (details in verification.md). The saved ~/Documents/groceries.txt was recorded as created with retained content Groceries: milk, eggs, coffee; the first window appeared after 527 ms; the window match is Mousepad/mousepad; ~/.config/Mousepad/accels.scm is marked as a state directory. A second run with Mousepad already open was refused and wrote nothing.
  • User-visible CLI output:
$ rea capture-desktop-application --desktop-entry org.xfce.mousepad --output ./mousepad-capture < control.fifo
{"rea_progress":{"phase":"desktop_capture","message":"Recording the starting state."}}
{"rea_progress":{"phase":"desktop_capture","message":"Launching mousepad."}}
{"rea_progress":{"phase":"desktop_capture","message":"The application window is open. Send an empty line or `checkpoint <name>` to record its state, or `stop` to finish."}}
{"rea_progress":{"phase":"desktop_capture","message":"Recording checkpoint typed."}}
{"rea_progress":{"phase":"desktop_capture","message":"Recording checkpoint saved."}}
{"rea_progress":{"phase":"desktop_capture","message":"Recording checkpoint stop."}}
{"rea_progress":{"phase":"desktop_capture","message":"Recording checkpoint exit."}}
$ rea capture-desktop-application --executable mousepad --output ./again --format json   # Mousepad already open
{"error":"Desktop capture failed","code":"invalid_request","category":"invalid_input","message":"The application is already open: \"Untitled 1 - Mousepad\" (pid 35).","retryable":false,"remediation":{"action":"Close the application, then run the capture again so it launches the application and records its starting state."}, ...}
  • Remaining proof gaps: only Mousepad on arm64 in a container; no real snap, flatpak or AppImage application captured (parser tests only); the time limit and cancellation paths are reviewed, not tested.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run typecheck, lint, lint:typed, format:check, knip, knip:production, jscpd, docs:check, mcp-catalog:check, verify:test-discovery, verify:architecture-guards, scan:todos: passed; no lint diagnostics in the new files.
  • npx vitest run --project domain --project services --project adapters (macOS): 21,581 passed, 29 skipped, 5 failed. The same 5 fail on main d7df9df33 here (zstd, Inspector cancellation, setupEnvironment).
  • npx vitest run --project cli-boundary (macOS): 1,499 passed, 5 skipped, 39 failed. 38 fail identically on main here (client profiles, setup, doctor, version report); closedStdout passed 3 of 3 when rerun alone.
  • New desktop tests on Linux (Ubuntu 24.04, Node 24.22.1): 83 passed.
  • Mousepad rerun after the review round (b79c71084, 9612ef91f): Mousepad exits with code 0 on SIGTERM, and the exit checkpoint now records its 3 shutdown writes; the package records origin Ubuntu.
  • Mousepad end to end and the already-open refusal: as above.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: Ubuntu 24.04 with Xvfb, xfwm4 and Mousepad 0.6.1.
  • Package or release metadata impact: one new CLI command in the product catalog.
  • Security, privacy, process, or containment review: the capture copies real files from the home directory into the output folder (directory 0700, files 0600); the docs say to treat it as private data and keep it local. The application is not sandboxed. REA terminates only the processes it launched.

Author readiness

Human owner: @earakely-scale

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

🤖 Generated with Claude Code

Add `capture-desktop-application`, a CLI-only, Linux and X11 capture that
launches an installed desktop application, watches it while it is used and
writes capture Evidence plus SHA-256 addressed content:

- inventory: desktop entry, launch command, executable, package and its
  apt sources (or snap, flatpak, AppImage), Electron markers and candidate
  state directories;
- session: the launched process tree, client windows from xprop with the
  first application window time and a window match, and files held open;
- state: a stat walk of the home directory before launch, at checkpoints
  read from stdin, at stop and after exit, with created, modified, deleted
  and retyped paths and the content of changed files and state directories.

It refuses non-Linux hosts, missing DISPLAY or xprop, a non-empty output
folder and an application whose window is already open, and signals only
processes it started.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@greptile-apps

greptile-apps Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: apex

[Critical impact] The command reads existing home-directory data and saves selected file contents into a capture folder.

Hold the merge until DesktopContentStore removes only partial files it created.

Findings

  1. P1 Cleanup deletes unowned files ▶
Fix with agent prompt
### Issue 1
src/application/desktop/DesktopCaptureOutput.ts:64-65
If another process running as the same user creates `capture.json.partial` during the session, the exclusive write correctly fails with `EEXIST`. Failed-run cleanup then deletes that existing file without checking whether this run created it. Cleanup also removes this path after failures that happen before publication begins.

`DesktopContentStore` has the same problem: it sets `#writing` before exclusive creation succeeds, then removes that path on failure. This violates the lifecycle guide's directive to release only owned resources. Keep proof of ownership from the exclusive open and remove only the file this run created.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds capture-desktop-application for Linux/X11. It records application details, windows, processes, filesystem checkpoints, and retained file content.

  • Linux users can start a desktop application capture from the command line.
  • The capture follows the launched app's windows and processes until the session ends.
  • The capture records checkpointed file changes and saves them with Evidence.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A["CLI request and stdin"] --> B["Check host, app, windows, and output"]
  B --> C["Record baseline and retain starting files"]
  C --> D["Launch owned app"]
  D --> E["Sample processes, windows, and open files"]
  E -->|Checkpoint| F["Walk, compare, and retain changed files"]
  F --> E
  E -->|Session ends| G["Release owned processes"]
  G --> H["Publish capture.json and check cleanup"]
  H --> I["Return Evidence or cleanup failure"]
Loading

Reviews (14) · Last reviewed commit: "fix(desktop): look programs up in the la..." · Reviewed by Greptile

Comment thread src/desktop/DesktopContentStore.ts Resolved
…cancelled captures

- Launch through the owned provider path with a run token; release with
  SIGTERM, then the token-verified group cleanup, after every session.
  Processes without the token are never signalled; each records whether it
  carries it, and the session records whether cleanup was verified.
- Report creations and deletions only where a walk listed the nearest
  existing directory; count the rest as unconfirmed.
- Retain a file only when it is still the walked version, through owned
  no-follow reads; charge the budget only for new content; create files
  exclusively in a private output folder owned by the caller.
- Walk content roots outside the home directory, compare paths in their
  physical spelling, and run executables from the caller's directory.
- Refuse when the window list cannot be read, re-evaluate window ownership
  each sample, handle one queued request per sample with a bounded stdin
  queue, and write the capture with end reason `cancelled` on interruption.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/domain/desktop/desktopCapture.ts Resolved
Comment thread src/desktop/DesktopContentStore.ts Resolved
Comment thread src/domain/desktop/desktopStateDiff.ts Resolved
earakely-scale and others added 2 commits November 3, 2026 23:29
- Allow a capture cancelled before any requested checkpoint to hold only the
  baseline.
- Retry an incomplete stop once; if cleanup is still unverified, write the
  capture and fail with the run token and process group as cleanup
  resources.
- Classify path changes after a walk (ENOTDIR and other selected-file
  errors) as changed_since_walk instead of failing the capture.
- Treat a non-directory ancestor as proof that nothing existed beneath it.
- Report a before digest only for the file version it was read from.
- Derive stderr_truncated from stderr's own byte counts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Content reads pass retainFailedClose, so a handle whose close fails stays
owned by the content store; the capture retries those closes after it is
written and fails with the output folder as the cleanup resource if one
still cannot be closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
When both the launched processes and a retained file's handle remain
unresolved after the capture is written, one cleanup error now lists both
reasons and both resource sets.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@earakely-scale
earakely-scale marked this pull request as ready for review November 4, 2026 15:52
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-04T15:52:13.175285Z
We couldn’t complete this review. Comment @codex review to try again.
11bf4c7 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

- Ask the launch process group and token carriers to exit before
  killing them, on errors too; report incomplete cleanup with its facts.
- Count descendants of the launch as started by the capture even when
  their environment cannot be read; treat a reused pid as a new process.
- Follow symlinked desktop entries; name a flatpak's state after its
  application id; match flatpak windows by name only.
- Stop on end of input; refuse empty, duplicate and reserved checkpoint
  names; require whitespace after the checkpoint keyword.
- Stay on each walk root's device, and never walk or retain `/` or a
  directory containing the home; say so in the limitations.
- Refuse a window manager that does not publish _NET_CLIENT_LIST.
- Remove retained content when a capture fails before it is written.
- Skip reading a file larger than the remaining content budget.
- Record apt's archive origin for each package source.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +64 to +65
const partial = capturePartial(output);
return rm(partial, { force: true }).then(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Cleanup deletes unowned files

If another process running as the same user creates capture.json.partial during the session, the exclusive write correctly fails with EEXIST. Failed-run cleanup then deletes that existing file without checking whether this run created it. Cleanup also removes this path after failures that happen before publication begins.

DesktopContentStore has the same problem: it sets #writing before exclusive creation succeeds, then removes that path on failure. This violates the lifecycle guide's directive to release only owned resources. Keep proof of ownership from the exclusive open and remove only the file this run created.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/application/desktop/DesktopCaptureOutput.ts
Line: 64-65

Comment:
**Cleanup deletes unowned files**

If another process running as the same user creates `capture.json.partial` during the session, the exclusive write correctly fails with `EEXIST`. Failed-run cleanup then deletes that existing file without checking whether this run created it. Cleanup also removes this path after failures that happen before publication begins.

`DesktopContentStore` has the same problem: it sets `#writing` before exclusive creation succeeds, then removes that path on failure. This violates the lifecycle guide's directive to release only owned resources. Keep proof of ownership from the exclusive open and remove only the file this run created.

**Context Used:** AGENTS.md ([source](https://github.com/morluto/rea/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e087320: a CaptureFile owner marks the partial file as created only after its exclusive open succeeds, and discards only a file this run created and has not published (tests for EEXIST, failed rename, and publish).

xfwm4 leaves _NET_CLIENT_LIST unset while it manages no windows, so the
capture refused an ordinary desktop with nothing open. Read
_NET_SUPPORTED with the list: an unset list means no windows when the
window manager supports it, and the capture is refused only when it
does not. `xprop`'s "no such atom" output now reads as unset too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/domain/desktop/desktopEntry.ts Resolved
Comment thread src/desktop/HomeStateWalker.ts Resolved
- A zombie or dead process no longer keeps the session open.
- Remove only the partial capture file this run created.
- Keep the exact owners of handles and processes whose cleanup failed on
  the returned error, so a retry can release them; test the published
  capture's cleanup-failure branch with mixed outcomes and retries.
- Release the application once even when the exit checkpoint fails.
- A cancellation before the capture is written removes what it retained.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Edgar Arakelyan and others added 2 commits November 4, 2026 19:13
- An unreadable window list is unknown, not zero windows, and is named in
  the limitations.
- Before ending the session, live run-token carriers no parent link reached
  are tracked; an unreadable process table leaves the exit unknown.
- An env prefix's assignments find the program and name its XDG folders.
- flatpak run options that take a value are skipped with it, -- is honoured
  and a /arch/branch suffix is dropped from the id.
- State directories include the entry's full id.
- Path options refuse empty values; roots count toward the entry limit.
- A capture file whose close failed stays owned and is retried on discard.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A program, or an empty or relative PATH entry, is resolved from the folder the
program starts in, as the launch does, so `env PATH=. app` with the entry's
Path still finds the app.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Program paths and PATH entries are joined rather than resolved, so `..` after
a symbolic link means what it means to the launch. The lookup moves to its own
module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/desktop/ProgramLookup.ts Resolved
This was referenced Nov 5, 2026
@morluto morluto added area: runtime Process capture and runtime observation enhancement New feature or request labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants