Skip to content

feat(close): stop a simulator or emulator the session's own open booted - #4539

Open
thymikee wants to merge 20 commits into
0.22from
t3/implicit-virtual-device-shutdown
Open

thymikee wants to merge 20 commits into
0.22from
t3/implicit-virtual-device-shutdown

Conversation

@thymikee

@thymikee thymikee commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Summary

For #4162, plain close stops only a local virtual device booted by this session's open, while its claim remains current. Prebooted, physical and provider-owned targets remain running. Policy denial keeps the device running with a warning; explicit denial remains a typed refusal. Successful native-close warnings survive outer replay and attempt projection.

Published head 93b40d7c4c82cc5460c3b02db4aa5d02eff51d90 is rebased on 0.22 root 9f6435f0: 50 files/1,412 gross lines; default-main scope 209 files/5,527 gross including integration.

Validation

Independent Apex/medium written source/prose recheck found no issues after the 20c2d716 requested changes. The report was checked against committed blobs; inconsistent delivery-summary claims are excluded.

At this head, pinned pnpm11.17/Node26.8.1 install/build passed. One focused/closure run passed 947 tests across five files. One canonical affected run passed 42 checks, skipped 25 with owners retained, and left none unrun: exactCommit=true, checkoutChanged=false. Receipt SHA256: b09a1482dc347043b6806424c34c2f344eaba927757d6613a3308881abbe3814.

Tracked bytes, logical index entries and clean fingerprints match. Raw index-file bytes changed; cause remains unproven. Complete evidence and all receipt-copy pairs were independently verified. The earlier d59576d5 closure-budget failure remains recorded; the fix changed neither limits, tests nor baselines.

Size passed: +3,702 B installed/unpacked, +1,203 B download. Sentinel raises stale reopen ownership; a scoped iOS source trace was posted. The finding remains open and its check unwaived. Other hosted checks remain unverified. Android cold ownership and current-client warning rendering remain live blockers; Pixel7/Pixel9 stopped-route constraints remain. No merge or release clearance.

Named receipts and retained failures.

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.29 MB 6.29 MB +3.7 kB
Package (unpacked) 6.29 MB 6.29 MB +3.7 kB
Package (download) 1.91 MB 1.91 MB +1.2 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 27.4 ms 24.0 ms -3.4 ms
CLI --help 52.9 ms 48.9 ms -4.1 ms

@thymikee
thymikee marked this pull request as draft November 14, 2026 02:24

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

All reported issues were addressed across 32 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread website/docs/docs/commands.md Resolved
Comment thread skills/agent-device/SKILL.md Resolved
Comment thread docs/agents/device-verification.md Resolved
Comment thread skills/ios-simulator/SKILL.md Resolved
Comment thread docs/adr/0029-daemon-policy.md Resolved
Comment thread website/docs/docs/sessions.md Resolved
@apex-sentinel-staging

apex-sentinel-staging Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Apex Sentinel · 🟠 Request changes

Since the last review: 1 new · 0 still open · 0 no longer raised

1 finding(s): 1 major.

Required fixes

  • Session reopen forges boot ownership from a stale booted: false snapshot

🟠 Major (1)

Where Finding
packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts:270 🆕 Session reopen forges boot ownership from a stale booted: false snapshot

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (7848a1a9283f).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

Earlier reviews

Review of 8c241431 · 14.11.2026 17:38 UTC

Apex Sentinel · ✅ Approve

Since the last review: 0 new · 0 still open · 1 no longer raised (1 marked fixed)

No open findings.

Reviewed with this repository's own Sentinel configuration (d78be6c88715).

Review of ebce87fa · 14.11.2026 10:01 UTC

Apex Sentinel · ✅ Approve

Since the last review: 0 new · 0 still open · 0 no longer raised

No open findings.

Reviewed with this repository's own Sentinel configuration (d38e35e61193).

Review of fcd2ec89 · 14.11.2026 08:24 UTC

Apex Sentinel · ✅ Approve

Since the last review: 1 new · 0 still open · 2 no longer raised (1 deferred)

1 finding(s): 1 minor.

🟡 Minor (1)

Where Finding
packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts:270 🆕 Reopen on a stopped simulator is recorded as a boot and close then shuts down a pre-running device

1 finding below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (d38e35e61193).

Review of 7dd1ac93 · 14.11.2026 02:28 UTC

Apex Sentinel · ✅ Approve

2 finding(s): 2 minor.

🟡 Minor (2)

Where Finding
packages/daemon/src/sessions/session-lifecycle/internal/session-open-state.ts:76 markOpenBootedDevice is called after store.publish rather than setting bootedByOpen on the draft, so the sessio…
packages/contracts/src/client-app.ts:158 warnings?: string[] forces SDK callers to match daemon message text

Reviewed with this repository's own Sentinel configuration (ddbfc855661f).

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 2 new findings on 7dd1ac9. The verdict and the full list are in the summary comment.

Comment thread packages/contracts/src/client-app.ts Resolved
@thymikee

thymikee commented Nov 14, 2026 •

Copy link
Copy Markdown
Member Author

CI is green at e5f7ab7 (16 checks, none failing), but the PR is a draft, so the device lanes were skipped and do not cover the Android or iOS lifecycle path. No conflicts. The code has two problems to fix before merge.

The new sentence at website/docs/docs/sessions.md:130 says provider-owned devices are not stopped through --shutdown. On a provider session, close --shutdown calls the runtime's shutdownTarget (session-close.ts:144-163). The Limrun runtime releases the lease there (app-log-runtime.ts:197-200), which deletes an instance agent-device created, and limrun.md:34 tells users to do exactly that. A user who trusts sessions.md could delete its instance, apps and data. The user docs should describe close --shutdown per owner as the code does: a local simulator or emulator stops, a provider session ends through the provider, and physical devices are not stopped. For example, replace the line with "Physical devices are not stopped; on a provider such as Limrun, --shutdown ends the provider instance or attachment (see Limrun)", or drop the provider clause.

The Android cold-open route has no live run. The route is bootStoppedLocalAndroidDevice, then markSelectionBootOccurred on the AVD selection, then the serial swap, then plain close with bootedByOpen. The PR body reports that Android cold open failed with DEVICE_NOT_FOUND for emulator-5554 and Pixel_7_CI, and the cause is not diagnosed. Whether the serial device reaches close with bootedByOpen and the emulator really stops is unproven. The iOS run used T3 client 0.21.31, so the head client and CLI warning delivery are not shown either, and the report paths in the PR body are not readable here. Please run the head-built CLI (pnpm build, then the node bin from this checkout with a fresh --state-dir): (1) with the AVD shut down and adb devices empty, open <app> --platform android --device <AVD name> --json shows selection.bootOccurred:true, then close --json shows data.shutdown.success:true, and adb devices no longer lists the emulator; (2) with the emulator already booted, close --json has no data.shutdown and adb devices still lists it; (3) with AGENT_DEVICE_DAEMON_POLICY denying device-shutdown, on a cold iOS simulator or AVD, close --json shows warnings[] with the kept-running text and the device is still booted. If the Android cold open still fails with DEVICE_NOT_FOUND, please attach the error details and confirm the same command fails on base 0.22, so the failure is attributed.

Not blocking, take or leave: the policy fact is carried per request in req.internal.shutdownCapabilityDenied and hand-copied into the replay cleanup request, while the close handler could read it from its daemon dependencies; the new client warnings pass-through (index.ts:270, index.ts:380, and serializeCloseResult) has no test, since deleting either line keeps every test green, so one client test with a fake transport would cover it; the doc comment at device-selection-resolver.ts:101 still says the boot event holds "once it succeeds", but it is now predicted before dispatch and session selections can claim it; and the cli-help.ts:132 rewrite drops "runners/daemons self-idle after 5 minutes; stale leases self-reclaim", which are unrelated to this change, so please keep them and shorten the new close sentence instead.

Could the request-stamped policy flag become a daemon dependency instead? handleSessionCloseCommands would receive deviceShutdownDenied, derived once from the loaded DaemonPolicy where daemon-runtime.ts:218 already derives assertShutdownAllowed, and pass it to runSessionCloseTeardown, the way platformResourceCleanup is threaded. That would delete withShutdownPolicyDeniedFlag, the new isDaemonPolicyCapabilityDenied export path, DaemonRequestInternal.shutdownCapabilityDenied, the router stamp and the replay-cleanup copy, about 25 production lines, with no propagation invariant to keep. bootedByOpen and updateOpenDevice can stay as they are, and setting bootedByOpen on the publish draft would be a small extra simplification. No ADR change looks needed.

On the other threads: the threads on boot ownership for reopens and on replay close scope are fixed at this head and can be resolved. These do not apply and can be resolved: skills/agent-device/SKILL.md:16 already limits --shutdown to a local simulator or emulator, and provider shutdown goes through session-close.ts:144-163; skills/android-emulator/SKILL.md:24 states the policy-denied case and scoping to a local emulator is correct; the publish-then-update thread has no reader between the two synchronous calls, so the draft change is only a simplification. The typed-reason thread on warnings still holds but is not blocking, because warnings: string[] is the existing contract convention.

@thymikee

Copy link
Copy Markdown
Member Author

Addressed the source and documentation feedback in fcd2ec8.

  • sessions.md now distinguishes local/physical targets from provider shutdown and warns, before the command, that Limrun can end an attachment or delete a created instance.
  • The loaded policy is evaluated once at request-handler composition. Ordinary close and suite cleanup receive the resulting dependency directly; DaemonRequestInternal.shutdownCapabilityDenied and its routing/copy machinery are removed. Explicit shutdown still uses the existing policy gate.
  • Restored the five-minute runner/daemon idle and stale-lease recovery facts. The compact workflow routes ownership/policy details to help close without changing byte limits.
  • Added warning projection coverage for actual SDK apps.close, sessions.close, and CLI serialization, plus a router-level loaded-policy test. Corrected policy regression: 2 failed / 13 passed before the fix; final focused run: 141 passed. Format, lint/typecheck, build, layering and doc-prose also passed. Fresh independent review and exact-head admission are pending.

I retained the existing display-warning convention; no consumer branches on warning prose. The nonblocking structured-warning suggestion remains deferred rather than being presented as fixed.

Live evidence remains limited: the e5 T3-bound iOS daemon cases passed, but its old bound client omitted the warning; Android cold selection failed twice and that route stopped. The new fake-response tests prove current client/serializer projection, not fresh end-to-end device delivery. I have not used an unbound head CLI to bypass the required T3 route. This PR remains draft.

@thymikee
thymikee marked this pull request as ready for review November 14, 2026 08:08

@cubic-dev-ai cubic-dev-ai Bot left a comment •

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.

All reported issues were addressed across 43 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread website/docs/docs/commands.md Resolved

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 1 new finding on fcd2ec8. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At fcd2ec8 the per-request policy marker is gone and reopen selections are now classified, so those two earlier findings are fixed. Two problems remain from the earlier review (#4539 (comment)), and one check fails.

The Android cold-open route still has no live run, and the PR says there was no fresh device execution at this head. The route is bootStoppedLocalAndroidDevice, then markSelectionBootOccurred on the AVD selection, then the serial swap and updateOpenDevice with bootedByOpen, then plain close and its implicit shutdown (https://github.com/callstack/agent-device/blob/fcd2ec8/packages/daemon/src/sessions/session-lifecycle/internal/session-open.ts#L422). Android cold binding returned DEVICE_NOT_FOUND twice, the cause is not diagnosed, and nothing ties it to base 0.22. Without a run, we do not know that the AVD-name selection and serial swap carry boot ownership to close. If they do not, the emulator stays running and the core #4162 behavior fails silently. The client/CLI warning delivery is also shown only with fake transports. Please run the CLI built from this head (pnpm build, then the node bin from this checkout, with a fresh --state-dir). (1) Start with the AVD shut down and an empty adb devices. Run open <app> --platform android --device <AVD name> --json and show selection.bootOccurred:true. Then run close --json and show data.shutdown.success:true and that adb devices no longer lists the emulator. (2) With the emulator already booted, show close --json without data.shutdown, and that adb devices still lists it. (3) With AGENT_DEVICE_DAEMON_POLICY denying device-shutdown, on a cold simulator or AVD, show close --json printing warnings[] with the kept-running text, and the device still booted. If the cold open still fails with DEVICE_NOT_FOUND, attach the error details and run the same command on base 0.22 to attribute it.

Close help says plain close stops a device "your session booted", but only open records ownership (updateOpenDevice, session-store.ts:418-424). The session-scoped boot command (session-boot.ts:135) does not. After boot then open, plain close leaves the device running, which contradicts the text at https://github.com/callstack/agent-device/blob/fcd2ec8/src/commands/schema/cli-help-workflows.ts#L32 and line 288. A user who follows workflow help and boots explicitly will expect close to stop the device, and it keeps running. The rule: every close help or doc sentence names the owner exactly as the code does, "this session's open booted". Apply it at those two lines and at app.ts:96, then grep "session booted" across src/commands/schema, packages/command-surface, skills and website/docs to find the rest. sessions.md and commands.md already use "open booted".

The Coverage gate fails because of this delta. application.test.ts:150 ("close routes only its lifecycle input through its owner") asserts the exact key set forwarded to handleSessionCloseCommands, and it now also receives deviceShutdownDenied, added at session.ts:65. Add that key to the expected list.

Open review threads that still apply: #4539 (comment) (close help owner wording, same rule as above) and #4539 (comment) (commands.md provider shutdown). The second one needs a fix: commands.md:107 says provider-owned devices are never stopped this way, but --shutdown releases a Limrun instance (session-close.ts:144-166), so please align it with sessions.md:129-131. #4539 (comment) (replay cleanup warnings) and #4539 (comment) (replay test gap) still apply, plus two lower-priority test threads. These can wait. The replay cleanup one is not a plain user close. These can be resolved: #4539 (comment) (callers can check that data.shutdown is absent, and explicit denial is typed), #4539 (comment) (readers use requireCurrent, so the snapshot is not stale), #4539 (comment) (ownership comes from device.booted at this open, which matches #4162), and #4539 (comment) (the write happens under the open's execution lock, before any reader).

I did not run tests; I judged this from the diff. The new router case in daemon-policy.test.ts would probably also pass on e5f7ab7, so it guards the new wiring, not a past bug. The iOS evidence in the PR comes from the earlier 0.21.31 client, not this head.

The branch now conflicts with its base 0.22, so please rebase. Before merge, fix the Coverage gate, attach the Android cold-open and close run, and align the close wording and the commands.md sentence.

@thymikee
thymikee force-pushed the t3/implicit-virtual-device-shutdown branch from fcd2ec8 to ebce87f Compare November 14, 2026 09:49
@thymikee

Copy link
Copy Markdown
Member Author

The code from the earlier review (fcd2ec8) is mostly fixed at ebce87f, but two items remain. The Coverage failure is repaired and all 18 checks pass. There are no conflicts. The close owner wording is fixed at app.ts:96, and replay warnings now reach the test outcome.

The workflow help still over-states who owns the boot. cli-help-workflows.ts:32 and line 288 say plain close stops a simulator or emulator "your session booted". Only open records boot ownership. The session boot command (session-boot.ts:135) records nothing. So boot, then open, then close leaves the device running, while the help says close stops it. A user who follows the card will leave a device running, which is the #4162 failure. Please make every close sentence in help, docs and skills name the owner as the code does: "your open booted". Then run git grep -i 'session booted' over src/commands/schema, packages/command-surface, skills and website/docs, and expect no close sentence in the output.

The live Android evidence is still missing. The route is session-open.ts:422: cold boot by AVD name, the serial swap, updateOpenDevice with bootedByOpen, then plain close. Only unit tests with fakes cover it. The PR body reports DEVICE_NOT_FOUND twice on Android with no diagnosis, and the iOS evidence comes from an older 0.21.31 client. If the AVD-name to serial swap drops boot ownership, the emulator keeps running after close and the core fix fails silently on Android. Please run pnpm build and use this checkout's node bin with a fresh --state-dir, then attach the output of three runs. (1) Start with the AVD shut down and an empty adb devices. Run open <app> --platform android --device <AVD name> --json and show selection.bootOccurred:true. Then run close --json and show data.shutdown.success:true and an adb devices list without the emulator. (2) Start with the emulator already booted. Show close --json without data.shutdown and adb devices still listing it. (3) Set AGENT_DEVICE_DAEMON_POLICY to deny device-shutdown and start cold. Show close --json with warnings[] containing the kept-running text and the device still booted. If the cold open still fails with DEVICE_NOT_FOUND, attach the error details and the same run on base 0.22.

Not blocking, take or leave: ReplayTestSessionCleanup (command-types.ts:96 and session-test-types.ts:190) is widened to Promise<readonly string[] | void> only so test fakes like async () => {} still type-check, which forces the ?? [] and truthiness guards in session-test-runtime.ts:168,249. The only production producer always returns string[], so typing it as Promise<readonly string[]>, making the fakes return [] and dropping the guards would be simpler.

Of the open inline threads, the help owner wording thread still applies, because app.ts:96 is fixed but the two help lines are not. These threads no longer apply and can be resolved: replay warnings is fixed in session-replay-command.ts:251 and session-test-runtime.ts:167-169; replay test cases now set bootedByOpen:true and assert the warnings; refresh return is fixed in session-open-state.ts:76; commands.md scope now matches sessions.md; warnings serialization asserts the exact payload; runner retention is asserted with retainRunner:true; ownership source is the open's own boot of a stopped device, which is the #4162 rule; boot-ownership race does not apply, because the write happens under the open's execution lock before any close reader; and skipped-stop signal is deferred by the author, since callers can see a skipped stop from the absent data.shutdown and the warnings[] text.

I did not run tests. This review comes from the diff and the code at ebce87f, and the CI result comes from the check summary, not the per-job logs. I did not trace which Limrun lease kinds reach deleteLimrunInstance. The client-side warning delivery is shown only with fake transports.

Before merge, please fix the two help lines and attach the Android cold-open to close runs on this head.

@thymikee

Copy link
Copy Markdown
Member Author

Exact local affected admission passed at ebce87faf5e0684f65df9c1fa8fdb04df9bf2c5d.

Command (one invocation): pnpm check:affected --run --head ebce87faf5e0684f65df9c1fa8fdb04df9bf2c5d.

  • 67 selected: 42 passed, 25 skipped, 0 failed/not-run; raw exit 0. Skips retain their GitHub/manual owners.
  • exactCommit=true, checkoutChanged=false; initial/final source clean at the full head, fingerprint 2a8e365c7ec2613ee23a9d127debb37321d8bcf3a2ff8d715b2592cdf505f884.
  • Fresh pnpm 11.17 frozen install/build exited 0. Command elapsed 470.081s, 11:09:45–11:17:35 UTC; no printed lock waits, exact wait unmeasured.
  • Immutable receipt copy matches original SHA256 452150fd1674f4bdfbe7162701e5e3e32b0a92426ab8b9ee5a1790a4bfbc42b0.
  • Default origin/main selection retained (d78be6c88715ad80fc658497f23f91c86bf9489b, merge base d38e35e61193b2e7e10f46f433f86bbecf52c8d4). Actual 0.22 base 61d027bd3f4c2b19418df2d62ddb514dad6528f8 was assessed separately.

Independent actual-owner source recheck: NO FINDINGS. Hosted at this head: 16 successful / 1 skipped / 1 neutral. These lanes are separate. Current-client warning rendering and supported cold Android lifecycle proof remain open; stopped device paths were not retried. No merge clearance.

@thymikee
thymikee force-pushed the t3/implicit-virtual-device-shutdown branch from ebce87f to 8c24143 Compare November 14, 2026 17:27
@thymikee

Copy link
Copy Markdown
Member Author

Published rebased A5 head8c241431f249ce4040fc0f32e5261bc771d9c4a0 on0.22root0081. Independent rebase preservation/prose recheck found no findings: all14patches equal, binary layer byte-identical, disjoint base/layer changes and automatic merge tree equals candidate. Prior actual-owner semantic review applies to unchanged A5 bytes; inaccurate narrative/device-status statements from the new report are excluded rather than treated as live proof.

New exact affected admission ran ONCE: raw0,42 passed/25 skipped, all67 FAIL-OPEN checks retained, exactCommit=true,checkoutChanged=false. Direct pnpm11.17.0 frozen install/build0. Defaultorigin/mainD78/mergebase d38; actual0.22root0081 separately. Receipt UTC2026-11-14 17:16:43.404–17:24:34.924. Matching clean fingerprint b3d88311b7cc7f25311dd86d230253375dd990b452d6c609da915f813ccdfb71. ReceiptSHA1dc54abc9653d62201579ab383e4e756a46eea02454a13453db6051f07a4347b.

Parent verified all87manifest hashes in evidence directory and archive and all52original/copy evidence files byte-identically, refs/results/pinnedsetup/finalindex. ArchiveSHA d971b2758fe86a9b52f47934ce59b8bbb6dd79323c8f655ced710c9fc5f5c5de, VERIFIED-UNSEALED. Initial read-only shell/controller errors were separate from actual gate execution; no rerun. No printed lock wait; actual wait unmeasured.

New-head hosted checks remain owed. Current-client warning delivery and supported cold Android ownership live proof remain BLOCKED. Pixel7 twice DEVICE_NOT_FOUND and Pixel9 KO shutdown routes remain STOPPED; Pixel9 last known ON/unclaimed, no cleanup claim. No device actions or alternate route occurred. No merge/release clearance.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. The app.ts:96 wording from the earlier review is fixed at 8c24143, but two items from that review still stand. The checks show 18 passing and none failing, and there are no conflicts. Before merge, fix the help text below and attach the live Android runs.

The close help still names the wrong owner. cli-help-workflows.ts:32 and :288, and cli-help.ts:617, say "your session booted" or "its session booted". Only open records boot ownership, because bootedByOpen is written only through updateOpenDevice. If the session boot command starts a device and the caller then runs open and plain close, the device keeps running and no warning appears. That is the #4162 failure this PR closes, and a user who follows the help will expect a stop. Every close sentence in help, docs and skills should name the owner the code reads, which is this session's open. Please change those three sentences to "open booted". Then check that git grep -n -i 'session booted' -- src/commands/schema packages/command-surface skills website/docs prints no close sentence.

The Android cold-open route is still covered only by unit fakes at session-open-execution.ts:443. That route boots by AVD name, swaps the name for an ADB serial, calls updateOpenDevice with bootOccurred, then runs plain close. I did not check whether the retainsBoot check at session-store.ts:423 keeps bootedByOpen across that identity change. If it does not, the emulator keeps running after close, and the core fix fails silently on Android. Only a live run settles this, and none is attached at this head. Please run pnpm build, use this checkout's node bin with a fresh --state-dir, and attach three runs:

  1. Start with the AVD shut down and an empty adb devices. Run open <app> --platform android --device <AVD name> --json and show selection.bootOccurred:true. Then run close --json and show data.shutdown.success:true, with the emulator gone from adb devices.
  2. Start with the emulator already booted. Show that close --json has no data.shutdown and that adb devices still lists the emulator.
  3. Set AGENT_DEVICE_DAEMON_POLICY to deny device-shutdown and start cold. Show that close --json has warnings[] with the kept-running text and that the device is still booted.

If the cold open fails with DEVICE_NOT_FOUND, attach the error details and the same run on base 0.22.

I did not run tests or any device. CI state comes from the check summary, not the per-job logs. The patch is identical to the one in the earlier review, so I did not re-trace the close and open code beyond the owner reads and writes.

On the inline threads: the one on app.ts (discussion) is marked resolved, but the same owner wording remains in the three help lines above. Two threads no longer apply and can be resolved. The deferred skipped-stop thread is covered because the skipped stop shows as an absent data.shutdown and a kept-running entry in warnings[]. The ownership-source thread is covered because ownership comes from the open's own boot of a stopped device, which is the #4162 rule.

Plain close now stops a local simulator or emulator that this session's
open booted. The boot fact selection already computes
(markSelectionBootOccurred) is recorded on the session by the open-state
publisher, and close finalization asks the same shutdown capability
close --shutdown uses.

A policy that denies device-shutdown blocks the implicit stop but the
close still succeeds and reports the kept device through warnings.
A boot-owned iOS close no longer retains a warm runner, because the
device stops.

Closes #4162
R7 classifies bootedByOpen as store-established: publishOpenSession
builds the record and SessionStore.markOpenBootedDevice sets the fact,
matching the markCloseEffectsUnconfirmed shape.
Help, workflow topics, website docs, skills, device verification, and
ADR 0029 now state that plain close stops the device its own open booted,
that --shutdown is for a device the session did not boot, and how a policy
denial reads on each of those paths.
The contract pinned the pre-#4162 wording 'agent-device close --shutdown'.
Plain close now owns the boot-stop, so the contract anchors on the finish
instruction itself, and the mutation fixture still removes exactly that.
Review round 1 on #4162:

- A policy that denies device-shutdown is now a request-scoped fact the
  router marks once. The close lifecycle decides the refusal before it
  finalizes, so the refused stop never consumes the warm-runner
  retention a kept-running device earns, and no error is swallowed.
- The boot-ownership fact is additive across every publish path, so a
  provisional dispatch publish (record-video test opens) cannot lose it.
- SessionCloseResult and AppCloseResult carry the close response's
  warnings, and serializeCloseResult keeps them, so the kept-device
  disclosure reaches the SDK, the CLI text, and close --json.
- remote-proxy.md states the plain-close exception to the denied
  capability, and the layering note names the real writer.
The close lifecycle consumes the derived request flag, not the predicate, so
the export has no consumer outside daemon-policy.ts.
@thymikee
thymikee force-pushed the t3/implicit-virtual-device-shutdown branch from 8c24143 to 93b40d7 Compare November 15, 2026 11:09

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Apex Sentinel: 1 new finding on 93b40d7. The verdict and the full list are in the summary comment.

Comment on lines +270 to +273
const preparedSelection = markSelectionBootOccurred(
selection,
lifecycle.owner.kind === 'local-family',
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🆕 🟠 Major · Session reopen forges boot ownership from a stale booted: false snapshot

On a reopen of an existing session, markSelectionBootOccurred receives a selection whose bootOccurred is derived solely from the stored snapshot (device.booted !== true && kind === 'simulator'|'emulator'), so a session whose snapshot was recorded before boot was confirmed gets bootedByOpen: true from the first reopen onward. SessionStore.updateOpenDevice never clears it for that device identity, so a later plain close shuts down a simulator that was already running before the session opened.

Suggested change
const preparedSelection = markSelectionBootOccurred(
selection,
lifecycle.owner.kind === 'local-family',
);
const preparedSelection = markSelectionBootOccurred(
selection,
lifecycle.owner.kind === 'local-family' && selection?.source === 'local',
);

Suggested change

Keep the boot fact derivable only from a selection that observed this request booting the device (source 'local' or an explicit boot stamp), and never from a source: 'session' snapshot; if reopens must be able to record it, carry an explicit booted-device argument from the boot site instead of re-deriving it from the stored DeviceInfo.

Details

persona: javascript

Useful? Reply @apex-sentinel-staging like, or @apex-sentinel-staging dislike <why> if it is not.

Reply @apex-sentinel-staging note ... to add context, or @apex-sentinel-staging pivot ... if it is wrong — I will re-check the cited code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

At 93b40d7c, the ordinary local iOS-simulator reopen path refreshes the device before creating this selection: session-open.ts:288–293 calls refreshSessionDeviceIfNeeded, then passes its returned device to resolveExistingSessionDeviceSelection. On Darwin, the refresh uses a live attached-runner observation (booted: true) or resolves the current exact UDID/simulator set (session-device-resolution.ts:117–145). Request execution copies platformServices per request (request-execution-scope.ts:392), so the WeakMap pin from an earlier ordinary request cannot supply its old snapshot.

For that path, a simulator already running at reopen reaches this helper with booted: true; the reported stored-false premise is not established. The proposed blanket source === 'local' guard would also remove intentional ownership when an existing-session reopen actually boots a stopped simulator. The existing cold-reopen test checks that prepared-command contract, but it bypasses the full refresh path and is not a reproduction of the reported stale-snapshot case.

This is a source trace for ordinary separate-request local iOS reopen, not Android, composite-request, race, or live proof. I have not applied the suggested guard. A concrete caller/reproduction that retains stale false after current-device selection is still needed before changing that ownership contract. Leaving this finding open and the current check unwaived; Android cold ownership and current-client warning delivery remain separate live blockers.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At 93b40d7 the owner wording in help now says "this session's open booted" at all three sites, so that part of the earlier review (#4539 (comment)) is fixed. One item remains: there is still no live Android run.

The Android cold-open route is covered only by unit fakes. Open boots by AVD name, swaps the name for an ADB serial, then updateOpenDevice records bootedByOpen (https://github.com/callstack/agent-device/blob/93b40d7/packages/daemon/src/sessions/session-lifecycle/internal/session-open-execution.ts#L443). Plain close must now renew the claim and then stop the device. So ownership also depends on the claim deviceKey, written for the pre-boot AVD identity, still matching at close. If it does not match after the swap, the renewal reports 'lost' or bootedByOpen is dropped. Plain close then leaves the emulator running, with no data.shutdown and no warning. That is the #4162 failure on Android. Please run pnpm build at 93b40d7 and use this checkout's bin with a fresh --state-dir. Attach three runs. (1) Start with the AVD shut down and empty adb devices. Run open <app> --platform android --device <AVD name> --json and show selection.bootOccurred:true. Then run close --json and show data.shutdown.success:true, with the emulator gone from adb devices. (2) Start with the emulator prebooted. Show that close --json has no data.shutdown and the emulator is still listed. (3) Set AGENT_DEVICE_DAEMON_POLICY to deny device-shutdown and start cold. Show the kept-running text in data.warnings of close --json and the emulator still booted. If the cold open fails, attach error.details and the same run on base 0.22.

Not blocking, take or leave: the claim-currency condition gates only the permitted branch (https://github.com/callstack/agent-device/blob/93b40d7/packages/daemon/src/sessions/session-lifecycle/internal/session-close-lifecycle-teardown.ts#L100), so a lost claim under a deny policy still warns that close would stop the device, which it would not; deciding claim currency once before both branches and deriving the warning and shutdownRequested from that value would fix it. Also, when renewDeviceClaim returns 'lost' the boot-owned stop is skipped with no data.shutdown, warning or diagnostic, while help lists policy denial as the only exception (https://github.com/callstack/agent-device/blob/93b40d7/src/commands/schema/cli-help-workflows.ts#L32); either add a warning for the lost-claim skip or name the condition in sessions.md, but only one of the two.

On the other open threads: the owner-wording thread (#4539 (comment)) is fixed at this head, and the resolved-benign thread on open-boot ownership (#4539 (comment)) needs nothing more, since this change touches only the close-side claim check. Two other threads do not apply and can be resolved: #4539 (comment) (on Darwin iOS the device is refreshed before reopen, and on Android the reopen re-mark is idempotent, so the proposed source==='local' guard would drop real reopen boots) and #4539 (comment) (the author deferred it, and a skipped stop already shows as absent data.shutdown plus the kept-running warning).

The only check not passing is a review gate that is holding open thread r4578158108. That thread does not apply, so the gate needs a waiver or a reply on that thread, not a code change. The other 17 checks pass. Before merge, please attach the three live Android runs above.

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.

1 participant