Skip to content

fix(daemon): write the default screenshot to the session's stable path - #4865

Draft
strzhao wants to merge 6 commits into
callstack:mainfrom
strzhao:community-screenshot-stable-path
Draft

strzhao wants to merge 6 commits into
callstack:mainfrom
strzhao:community-screenshot-stable-path

Conversation

@strzhao

@strzhao strzhao commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A screenshot that names no destination on the ordinary local route now publishes to one stable session file, <session>/screenshots/screenshot.png, so a caller reads the latest capture from the path the help promises. A remote request (publicNetworkOnly) or a caller-owned destination keeps the adapter's per-capture reservation, so independent owners never share a file. The earlier session staging and per-capture minting are gone: crops stage under os.tmpdir(), the sparse-snapshot fallback keeps its per-capture path and snapshot-fallback.png download name, and the CLI text and JSON summary are unchanged.

Before / after

local, two captures without a destination:
before: each reports its own temp path
after:  both report <session>/screenshots/screenshot.png; the latest capture is read there

remote Maestro flow, two takeScreenshot steps:
before: both steps share the dropped flow path and the daemon's temp default
after:  each step keeps its own reserved capture, reported through artifactPaths

failed crop with no destination:
before: an uncropped frame replaces the last good capture
after:  the staged crop never publishes; the earlier file keeps its bytes

Validation

Tested at 03e6068.

  • Session-doctor, screenshot router, remote Maestro capture, Maestro daemon-port and session-artifact-path suites pass; typecheck, oxlint and oxfmt clean.
  • New controls: two local destination-less captures report the same stable path; a remote destination-less capture keeps its own reservation; a failing crop leaves the earlier stable capture byte-identical; a remote Maestro flow's two steps report distinct, intact captures.

🤖 Generated with Claude Code

A screenshot that names no destination minted a fresh temp dir per
capture (mkdtemp agent-device-screenshot-*), so a caller had to parse
the path out of the output and copy the file before temp cleanup raced
the read. The artifact adapter now reserves the session's stable
artifact path when the request names no destination, and the crop
publish stages inside the session dir instead of os.tmpdir(). An
explicit positional or --out destination still wins, and the
sparse-snapshot fallback gets its own stable name so it never
overwrites a capture the caller asked for earlier in the session.

The CLI renders the destination path alone on the final line; capture
metadata (dimensions, density, annotated-ref count) moves above it.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@thymikee

Copy link
Copy Markdown
Member

Thanks for working on the stable screenshot path.

At 0abde34 the change has two regressions that lose or delete screenshots, so it needs fixes before merge.

With publicNetworkOnly (remote Maestro), invokeMaestroPublicOperation drops the screenshot path. The daemon then resolves every takeScreenshot and every comparison capture to the one screenshots/screenshot.png. A flow with N takeScreenshot steps now reports N identical artifactPaths entries, and each step overwrites the previous frame. Also, captureMaestroComparisonScreenshot removes data.path and its parent directory after reading it, so tap-retry and animation comparisons delete the session's default screenshot, including one an agent captured earlier. The docs at website/docs/docs/run-maestro-flows.md:40 still promise a separate daemon-generated path per takeScreenshot. The rule: a capture path that a caller lists as its own artifact, or deletes after reading, must belong to that request alone. Please add a remote-Maestro test with two takeScreenshot steps that asserts two distinct, intact files.

The staged atomic publish in screenshot-artifact-adapter.ts only runs when ref.kind === 'path'. So screenshot --crop-on <selector> with no destination writes the uncropped frame straight onto the stable default path, and a missing, ambiguous or canceled selector fails with no cleanup. Any capture or scale failure after the platform write does the same. At base, a failed capture wrote into a temp directory that cleanup removed, so the earlier screenshot stayed intact. Here a failed request replaces the last good capture with an uncropped or partial frame, which #4423 rules out. The rule: a failed capture never changes the bytes at the stable session path. Please send the default path through the same staging and publish step, and add a router test with a pre-existing stable file and a failing crop that asserts the bytes are unchanged.

Not blocking, and fine to take or leave: the CLI text summary change in src/cli/commands/screenshot.ts:163 rides along, and its "path on the final line" goal does not hold because warning lines are appended after it; the stated race with temp cleanup does not exist at base, since cleanup runs only on failure, and screenshot <path> already gives a predictable destination; the fixed screenshots/crop-staging directory is not needed by the rule above and relies on the session request lock, while the optional sessionDir keeps two code paths for one concept; and no route-level test covers the sparse fallback's snapshot-fallback.png destination.

Would a smaller design work? The adapter could keep minting a default path, but under the session directory with a request-unique name such as screenshots/<requestId>.png. That needs no temp directory, never overwrites Maestro artifacts or earlier captures, and needs no staging move or CLI reformat. If a single predictable latest file is really needed, it could be published through the existing staged publish so failures never touch it. Which caller needs a fixed path, given that the response already returns the path?

The Coverage check fails on this head. The diff adds branches in the adapter, screenshot-runtime.ts and sparse-fallback-screenshot.ts that no route test reaches, so the failure is likely related. Not verified here: the exact coverage metric, the Maestro remote path by running it, and any external consumers that parse the old CLI text line. The two Body rules runs were canceled by newer runs and are not failures. There are no conflicts. Before merge, both regressions need fixes, each with a route-level regression test.

strzhao and others added 3 commits November 21, 2026 10:16
…taging root

The provider-scenario android-screenshot-crop lane pins the contract that a
crop request acquires staging through mkdtemp, and the staged atomic publish
had stopped minting one once the session owns a staging root, so all 12 lane
cases failed. Each request now mints its own agent-device-crop-* dir inside
the staging root (the session's screenshots/crop-staging when one is owned,
os.tmpdir() otherwise), so concurrent crop publishes in one session no longer
share one staging path and no longer rely on the session request lock for
exclusivity. The staging root stays for the session's lifetime; cleanup
removes only the request dir.

Co-Authored-By: Claude Code <noreply@anthropic.com>
The CLI screenshot summary moved capture metadata above the destination
path, but this pinned case still expected the old "path (width x height)"
line and failed the Coverage run at the previous head. Pin the current
two-line contract with the warning still last.

Co-Authored-By: Claude Code <noreply@anthropic.com>
…ed file

A capture without a destination previously landed on one stable
`screenshots/screenshot.png`, so a remote Maestro flow's N takeScreenshot
steps all reported and overwrote the same file, and a comparison capture
that releases its capture after reading deleted that shared file. The
default is now minted per capture under the session's screenshots dir as
`<request id>-<suffix>.png`: every step reports its own intact file, and
nothing a caller lists as its artifact or deletes after reading is shared
with another request.

A crop capture without a destination now sends its default through the
same staged publish an explicit destination uses, and a minted capture
removes its own file when the capture fails. A missing, ambiguous, or
canceled selector — or any capture or scale failure after the platform
write — leaves every earlier capture untouched and leaves no bytes behind.

Co-Authored-By: Claude Code <noreply@anthropic.com>
@strzhao

strzhao commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review — I adopted your smaller design, with one addition your question uncovers.

The default is now minted per capture as screenshots/<request id>-<suffix>.png under the session dir. No caller needs the fixed path: the response returns the path, and the request log already established the convention that a request's artifacts carry its own name, so the file name now does too. A capture that names no destination keeps landing inside the session dir (no temp-dir lottery); it just mints its own file instead of sharing one.

One finding forced a deviation from the literal screenshots/<requestId>.png: every operation of one flow dispatches under the flow's single request id. The replay dispatch envelope re-sends the originating request's wire shape for each nested step, and nested dispatches keep meta.requestId unchanged — so a flow's takeScreenshot steps and its comparison captures all share one id. A bare <requestId>.png would still collapse N steps onto one file. The adapter therefore appends a per-capture suffix (resolveSessionTrackingId-style nonce in screenshot-artifact-adapter.ts), keeping the request-id prefix for attributability and making the name unique per capture.

Blocking #2: the staged publish now runs for every real destination (atomic && tempRoot === undefined), so a crop capture without a destination stages like one with an explicit path, and a minted capture also removes its own file when the capture fails — a missing, ambiguous, or canceled selector, or any capture or scale failure after the platform write, leaves no bytes anywhere. The one shared file that remains (snapshot-fallback.png) is the sparse fallback's own stable destination and never passes through the crop path.

Regression tests (each fails at the previous head for the recorded reason):

  • request-router-maestro-screenshot.test.ts — a remote flow (publicNetworkOnly) with two takeScreenshot steps through the real replay backend and request handler: the flow-authored paths never reach the daemon, and the run reports two distinct, intact files.
  • request-router-screenshot.test.ts — two captures under one shared request id mint distinct files; a failing crop with no destination leaves the earlier minted capture byte-identical and removes its staging dir.
  • screenshot-artifact-adapter.test.ts — minted destinations: publish success keeps the file, failure cleanup removes it, and the crop path stages into the session staging root before publishing to the minted name.
  • daemon-runtime-port.test.ts — with publicNetworkOnly, a screenshot step asks the daemon for a path-less capture; without it, the flow-authored path is still sent.

Converted to draft while the revision runs; the body's Validation section records the lanes at 867f23f.

🤖 Generated with Claude Code

@strzhao
strzhao marked this pull request as draft November 21, 2026 05:07
@thymikee

Copy link
Copy Markdown
Member

Thanks for the update. At 867f23f, the earlier findings from the first review (#4865 (comment)) are addressed. One docs problem remains.

The path help still describes the old behavior: "Omit it to write the session's stable screenshot file" (screenshot.ts:37). The code now mints a new screenshots/<request id>-<suffix>.png for each capture (screenshot-runtime.ts:254, screenshot-artifact-adapter.ts:166). Agents read this help, so they will look for or reuse a fixed file that does not exist. Please make the help say that an omitted path saves a new file in the session's screenshots directory and that the response returns its path. Every help, docs and skill sentence about the default destination should name the minted file, so a search for "stable" across the command-surface help, website docs and skills should find them all.

Not blocking, and fine to take or leave: captureScreenshotArtifact takes two mutually exclusive optional defaults (mintedDefaultDir, defaultOutputPath), which one discriminated default would replace; generic-runtime-execution.ts:40 still calls sessionDir "the stable base"; mintCaptureDestination is async with no await; each destination-less screenshot now leaves a permanent file in the session dir with no pruning, which may deserve a follow-up issue if session dirs live long; and the PR title and sessions.md ("each request owns its file") could say "mint" and "each capture", since a flow request owns several files.

No conflicts were reported. The failing Smoke Tests job is only the aggregate gate: its iOS, macOS and Android jobs were cancelled and never ran, so no smoke test failed. This diff touches the destination-less screenshot route that smoke exercises, so a completed smoke run is still needed. Not verified here: tests, a live remote flow, whether every flow step shares one request id, and the Coverage job at this head. Before merge, fix the help text and rerun Smoke Tests to green.

@thymikee

Copy link
Copy Markdown
Member

867f23f now conflicts with main. Please rebase onto main and include the open findings from the last review in the same push.

@thymikee

Copy link
Copy Markdown
Member

ADR 0040 alignment (ADR)

Decision: screenshot ownership: Rebase the screenshot path work on the #4945 screenshot lane, then reduce the diff to any remaining default or crop regression, including the Maestro route where needed. Use one producer reservation for each remote screenshot through #4970 and keep explicit client destinations client-local. Keep the failed-crop earlier-file control and the two-distinct-captures control. Use the common adapter and reconcile the router file with #4965.

@strzhao

strzhao commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

One routing question before I take the ADR 0040 direction. The #4945 lane lives on 0.22; this PR is based on main, and abec0d04f2 is not in main (main and 0.22 have diverged). Should I retarget this PR to 0.22 and bring the branch to that base by merging 0.22 in (no force-push), then reduce the diff to the remaining default/crop regression, keep the failed-crop earlier-file and two-distinct-captures controls, and add the per-remote-screenshot producer reservation from #4970 only where the lane still lacks it? Or do you want this held until the lane reaches main?

@thymikee

thymikee commented Dec 4, 2026

Copy link
Copy Markdown
Member

The base question (retarget to 0.22 and merge it in, or hold until the lane reaches main) is a maintainer decision and has been passed on. The branch still needs a conflict-free base either way before the next review.

…t-stable-path-merge

# Conflicts:
#	packages/daemon/src/execution/screenshot-artifact-adapter.ts
@strzhao

strzhao commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged current main into the branch without force-pushing: head is now 6f20bbc, which makes the branch conflict-free against main while the retarget decision is pending. Locally I also prepared the reduced version on the 0.22 #4945 lane (minted local default + failure cleanup; remote/client-path captures keep the lane's producer reservation; both controls kept). I'll publish that once you confirm whether this PR moves to 0.22 or waits for the lane to reach main.

@thymikee

thymikee commented Dec 4, 2026

Copy link
Copy Markdown
Member

Thanks for the update.

This review covers 6f20bbc and builds on the earlier review at 867f23f. The earlier request for a completed Smoke Tests run is now met, because the checks at this head show 16 total and 0 not passing. Not verified here: individual smoke job results were not opened, and the PR's test files were not run locally. The code still has six problems, listed below.

The PR still has merge conflicts with main. Before merge, the problems below must be fixed and the conflicts resolved.

The first problem is that two successful screenshots with no destination in the same session return different filenames (screenshot.ts:37). The router supplies a stable directory, but screenshot-runtime.ts:254-256 selects a per-capture mint and screenshot-artifact-adapter.ts:175-177 picks a new filename. The stated invariant and the added help both promise one stable file, so a caller cannot read the latest capture from the first returned path. The shared-request test at request-router-screenshot.test.ts:179-201 requires two different paths, and only the sparse snapshot fallback selects the fixed-path option. Please make the ordinary omitted-path route resolve and publish to the session's stable default file, and keep per-capture reservations only where independent artifact ownership is required. If a stable directory with distinct files is the intended design, please update the invariant and the help text to say so.

The second problem is that two sparse snapshots in one session publish different captures to the same snapshot-fallback.png (sparse-fallback-screenshot.ts:100). The artifact tracker reuses the pending ID for the same path and tenant (artifact-tracking.ts:126-128, 157-167). A later fallback can replace bytes the earlier response already advertised, or overwrite a caller's screenshot at that explicit path, and download cleanup can remove the shared file. Please keep the per-capture reservation and the existing snapshot-fallback.png download filename. Please also remove the fixed-path claim in sessions.md and the unused fixed-default adapter option.

The third problem is that session staging now applies to explicit crops (screenshot-artifact-adapter.ts:136). If the caller's destination equals the crop-staging path, mkdir creates a directory at the requested output and the final rename fails. If a file occupies the new staging-root path, an unrelated explicit crop fails at mkdir. The base staged under os.tmpdir() and handled both cases. Please keep the existing staging parent for explicit output paths, and apply session placement only to daemon-owned default destinations.

The fourth problem is that a long request ID can break a destination-less screenshot (session-artifact-paths.ts:28). safeSessionName replaces characters but does not shorten the ID, so a valid long ASCII ID can exceed a 255-byte filename component once the suffix and .png are added (screenshot-artifact-adapter.ts:176-177). The base's fixed screenshot.png did not depend on the ID. Please bound the sanitized name so the suffix and extension always fit, using a short digest if the name must stay tied to a long ID.

The fifth problem is that mintCaptureDestination computes a candidate but does not reserve it (screenshot-artifact-adapter.ts:175). If two captures get the same prefix, clock and random suffix, or the file already exists, both use it. A later capture can overwrite it, failure cleanup at line 94 can unlink it, and a staged crop can replace it at line 158. This breaks the guarantee in sessions.md:35, and the base's mkdtemp did not have this gap. If per-capture filenames stay, please reserve each destination atomically, retry occupied names, and clean up only the reservation this capture acquired.

The sixth problem is that the text summary changes even for an explicit output path (screenshot.ts:49). A caller that read the path from the previous summary line now reads dimensions or an annotation heading. The new final-line claim at line 155 also fails for a clipped crop, because screenshot-crop.ts:31 produces a warning that line 52 appends after the path, and the test at line 64 pins that output. Please keep the previous text format and drop the final-line claim. The JSON path field already gives the destination.

The earlier clean assessment also rested on the claim that a screenshot with no caller-supplied path writes to one stable default file in the session. The code does not do that on the ordinary route. Please make the claim true or explain it. The new Maestro test drives the real router and adapter, but it does not cover the public HTTP or same-session replay envelope.

The next change needed before merge is the first problem above: a caller must be able to use one session default file to read the latest destination-less capture.

…t-stable-path-merge

# Conflicts:
#	packages/command-surface/src/capture/screenshot.ts
@strzhao

strzhao commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Redesigned at 03e6068 and merged current main (no force-push), so the branch is conflict-free. Point by point:

  1. The ordinary omitted-path route now resolves and publishes to one stable file, <session>/screenshots/screenshot.png. Per-capture reservations remain only where ownership is independent: publicNetworkOnly requests and caller-owned destinations. Router tests assert two local destination-less captures report the same path, and two remote captures stay distinct.
  2. The sparse-snapshot fallback is back on its per-capture adapter path with the existing snapshot-fallback.png download name; the fixed-path claim is removed from sessions.md, and the fixed-default adapter option is gone.
  3. Session staging is removed; crops stage under os.tmpdir() again for explicit destinations and daemon defaults alike.
  4. No request-id filenames remain: the default is the fixed screenshot.png, so a long request id cannot overflow a filename component.
  5. Per-capture minting is gone entirely, so there is no unreserved candidate; remote/client captures keep the adapter's mkdtemp reservation.
  6. The CLI text summary and annotation heading are reverted to the previous format; the JSON path field remains the destination contract.

Coverage: the new remote control drives the same router envelope the HTTP surface uses (internal.publicNetworkOnly) plus the Maestro replay route; the failed-crop control asserts the earlier stable capture stays byte-identical. Validation at 03e6068: screenshot router, remote Maestro capture, Maestro daemon-port, session-artifact-path and daemon execution suites pass; typecheck, oxlint and oxfmt clean.

@thymikee

thymikee commented Dec 4, 2026

Copy link
Copy Markdown
Member

Thanks for the update.

This follow-up on the earlier review of 6f20bbc covers commit 03e6068. The default screenshot now targets the session's stable path, but two problems remain, and the earlier conclusion that the stable-path behavior holds on the ordinary local route did not hold up.

On a local X11 desktop with scrot installed, the second pathless screenshot passes the existing screenshots/screenshot.png to the backend. screenshot-runtime.ts:227 picks the stable path, and for uncropped captures screenshot-artifact-adapter.ts:30-45 hands that file to the backend as is. Linux prefers scrot on X11 and passes only the output path (tool-provider.ts:272-275, :317-320, :372). When the destination exists and overwrite is off, scrot succeeds by saving to a numbered sibling (scrot.c). The command still returns reserved.path (screenshot.ts:68-73). So the second call reports success but returns the first frame, and the new capture piles up as an unreported sibling. The merge base used an unused temp filename for every pathless capture, so this is a regression on a supported local route. The rule to satisfy is that a daemon-selected stable default gives the backend a fresh staging filename and publishes to the stable path only after capture succeeds. The screenshot adapter already has staged publication, so please reuse it for this case and keep the current policy for caller-supplied paths. The stable-path test at request-router-screenshot.test.ts:178-198 does not catch this because its backend fixture always overwrites the file. Please cover the existing-destination case.

The new help at screenshot.ts:44 tells callers to omit path to write a stable file, and sessions.md:25-34 names screenshots/screenshot.png as the omitted-path result. That holds for local daemon captures only. Public-network requests get a per-capture daemon temp path (screenshot-runtime.ts:74-79). Remote CLI and MCP prepare a timestamped client destination (daemon-artifacts.ts:359-378). A remote caller who follows the new text and opens the named session artifact finds no file. Please qualify both statements for local daemon captures and tell remote callers to use the returned artifact path, or to pass a client destination when they need a fixed filename.

CI is green: 18 checks, none failing at 03e6068, and smoke covers the pathless screenshot route. No conflicts. Not verified here: any live run, individual smoke job logs, and the remote behavior, which was traced from source only. The first finding must be fixed before merge.

@thymikee

thymikee commented Dec 4, 2026

Copy link
Copy Markdown
Member

Thanks for working through the screenshot cases. Could you narrow this PR to the screenshot help on main? When someone omits the path, the command already chooses a filename and returns the path to that capture. Please tell readers to open that path, or to supply a filename when they need a particular destination. That lets someone taking before-and-after screenshots read both frames without knowing where either was saved.

Please drop the runtime and test changes, remove the new session-file entry from the docs, and update the title to describe the help change. This scope can ship on 0.21 without waiting for the 0.22 branch.

@strzhao

strzhao commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Understood — narrowing this PR to the screenshot help change only: the pathless capture keeps returning its per-capture path, and the help will tell readers to open that returned path (or pass a filename when they need a fixed destination). The runtime, test and sessions.md changes come out, and the title will describe the help-only scope. The scrot finding is a fair reason to drop the stable-path direction on this PR — if a stable default path comes back on the 0.22 lane it will need staged publication rather than handing a fixed path to backends that rename on collision.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants