Skip to content

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

Merged
thymikee merged 10 commits into
0.22from
t3/implicit-virtual-device-shutdown
Nov 20, 2026
Merged

thymikee merged 10 commits into
0.22from
t3/implicit-virtual-device-shutdown

Conversation

@thymikee

@thymikee thymikee commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Refs #4162 and #4585. Plain agent-device close stops a local simulator or emulator that this session's own open booted, while the session's device claim is current. A device that was already running stays running. Explicit close --shutdown, daemon policy, lost claims and provider release keep their existing paths.

For an Android emulator, close stops only the process that open launched. Close reads that process once, right before it asks for the stop. A reopen of the same device keeps the recorded launch identity, and a serial change clears it.

Scope is 62 files against 0.22 9440141767.

Ownership rule for an Android emulator

Plain close stops the emulator process this session's open launched. Open records { pid, startTime } from the spawn. Close reads that process once, after platform close and hint cleanup and right before the stop:

  • no recorded identity: the device stays running, with a warning;
  • the process is gone, a zombie, or has another start time (a Quick Boot restart or a foreign boot owns the serial): the device stays running, with the "process has changed" warning;
  • the read fails: the device stays running, with the "could not verify" warning;
  • the process is alive with the recorded start time: adb emu kill, then close confirms that the pid exits, and falls back to a pid stop that checks the start time.

There is no lsof probe, so the rule does not depend on lsof on the host.

Validation

Current head 696e453f33ca5872fdc52ca9c8f941ca67d1e7e3 on 0.22 9440141767. Exact pnpm check:affected --run --base origin/0.22 --head 696e453f33 passed: 42 passed, 28 skipped, exact commit, unchanged checkout.

Live Android evidence is required at this head, on a dedicated AVD: cold open then close (stops); a prebooted emulator (kept); an external restart with the same serial (warning, replacement kept); a policy denial (kept, warning); close --shutdown (stops); and an emulator that ignores adb emu kill (pid stop). The earlier live runs covered the removed lsof design.

@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.17 MB 6.18 MB +8.3 kB
Package (unpacked) 6.17 MB 6.18 MB +8.3 kB
Package (download) 1.88 MB 1.88 MB +2.4 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 31.5 ms 32.6 ms +1.0 ms
CLI --help 79.9 ms 56.7 ms -23.2 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

This comment has been minimized.

@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.

@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.

@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.

@thymikee

Copy link
Copy Markdown
Member Author

This branch now conflicts with main at 93b40d7. Please rebase onto main and push, together with the live Android runs from the earlier review, and I will re-check the new head.

@thymikee

Copy link
Copy Markdown
Member Author

This follows up on the earlier review at 93b40d7 (#4539 (comment)). The rebase to 0e19c8d keeps the same logical patch, so the earlier trace of the open and close route still holds. One gap remains: the Android cold-open route has no live run.

The route boots by AVD name, swaps the AVD name for an ADB serial, and records bootedByOpen in session-open-execution.ts:443. Close then needs the claim renewal at session-close-lifecycle-teardown.ts:105 to return 'renewed' for a claim written before that swap. Only unit fakes cover this. The PR body still lists Android cold-open, claim, implicit-stop and the current-client warning as live gaps, and the earlier Pixel 7 DEVICE_NOT_FOUND failure is still not explained. If the swap drops bootedByOpen, or the renewal reports 'lost', plain close leaves the emulator running with no data.shutdown and no warning. That is the #4162 failure on Android, and it would ship silently.

Please run pnpm build at 0e19c8d and use that CLI with a fresh --state-dir. Attach the output of three runs. First, 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. Second, start with the emulator prebooted. Show that close --json has no data.shutdown and that adb devices still lists the emulator. Third, set AGENT_DEVICE_DAEMON_POLICY to deny device-shutdown and start cold. Show the kept-running text in data.warnings of close --json, with the emulator still booted. If the cold open fails, attach error.details and the same run on base 0.22.

Of the other open threads, the Darwin iOS reopen thread does not apply. The device is refreshed before reopen on iOS, and the Android re-mark is idempotent (session-open-execution.ts:273-284, session-store.ts:423), so a source==='local' guard would drop real reopen boots. The client-app.ts thread also does not apply. A skipped stop already shows as absent data.shutdown plus the kept-running warning (session-close-lifecycle-teardown.ts:100-105). Please resolve both.

The checks show 18 passing at 0e19c8d and none failing. There are no conflicts. The device lanes do not run the Android cold-open lifecycle with a live boot-owned close, so green CI does not replace the runs above. Before merge, the three live Android runs must be attached.

Not blocking: if an older @agent-device/replay plugin can run against this daemon, cleanup warnings returned through ReplayTestCleanupSession would be dropped by that older runtime.

@thymikee

Copy link
Copy Markdown
Member Author

The code at 16f77f9 has one open gap: the Android cold-open close route still has no live run. The duplicate warning plumbing is gone, and nothing in that change looks wrong. The live evidence I asked for at 0e19c8d is still missing.

The Android cold-open route boots by AVD name and stamps bootOccurred through markSelectionBootOccurred (session-open-execution.ts:274-288). It then swaps the AVD name for an ADB serial and records bootedByOpen through updateOpenDevice (session-store.ts:423-430). At close, renewDeviceClaim must return 'renewed' for the claim written before the swap. Only unit fakes cover this route, and the PR body and your 12:01Z comment both say the device runs are outstanding. If the identity swap drops bootedByOpen, or the renewal reports 'lost', plain close leaves a cold-booted emulator running and returns no data.shutdown and no warning. That is the #4162 failure on Android, and it would ship silently. Could you run pnpm build at 16f77f9, use that checkout's node bin with a fresh --state-dir, and attach the output of three runs? (1) Start with the AVD shut down and an empty adb devices. open <app> --platform android --device <AVD name> --json should show selection.bootOccurred:true. Then close --json should show data.shutdown.success:true, and the emulator should be gone from adb devices. (2) Start with the emulator prebooted. close --json should have no data.shutdown, and adb devices should still list the emulator. (3) Set AGENT_DEVICE_DAEMON_POLICY to deny device-shutdown and start cold. data.warnings in close --json should carry the 'still running' text, and the emulator should stay booted. Read the warnings through the current SDK/CLI reader, because 16f77f9 moved warning delivery to readScriptDeliveryDisclosure. If the cold open fails, please attach error.details and the same run on base 0.22.

The two open inline threads on the cold-open boot stamp do not apply, so you can resolve them. The first (thread) is the external-reboot case: your 12:01Z reply moves it to #4585, and the exclusive claim still protects #4162. The second (thread) asks for a source==='local' guard: that code is unchanged, and the guard would drop legitimate cold-reopen boots. No other review threads still apply.

CI is unclear at 16f77f9. One check failed and seven are still running. 'Smoke Tests' failed in run 43953240485, but three workflows use that job name (android.yml, linux.yml, apple.yml), so which one failed is not attributed yet. The Android smoke job overlaps this PR, since it replays steps on a prebooted emulator, so please check it first. All checks were green at 0e19c8d. There are no conflicts.

Before merge, please post the three live Android runs at 16f77f9 and get the failed Smoke Tests job explained or green.

… deadline

Cover the retried 5 s launch start time read and the zombie case. The ps read after lsof now gets only what the shared deadline still has, so one slow attempt stays inside the 10 s pair budget.
Plain close now owns the emulator process its own `open` launched, instead
of probing which emulator generation owns the console. `open` records
`{ pid, startTime }`; close reads the host facts for that pid once, keeps
the device when the process is gone, changed, or unverifiable, and stops
the recorded process when the emulator console kill does not take.

Removes the `lsof` console-listener generation probe, the
`DeviceShutdownGenerationService` wiring, and the `generation` field that
platform runtimes no longer answer for.
`check:layering` rejects the previous shape: R65 keeps the daemon's close
orchestration from selecting a concrete platform, and the launched-emulator
check did exactly that. The rule moves to where R65 points — a published
`LaunchedDeviceProcessService` composed at the root, answered by the Android
family and `not-applicable` for every device that launches no host process.

The process reads themselves (one `ps`, liveness, and the pid escalation with
the recorded start time) now live in `@agent-device/platform-android/device-boot`
beside the launch that records the identity, which is where the timeout and
escalation budgets belong.
@thymikee
thymikee force-pushed the t3/implicit-virtual-device-shutdown branch from 9ac325a to 00f70c2 Compare November 20, 2026 07:34
@thymikee

Copy link
Copy Markdown
Member Author

Pushed 00f70c241d, on 0.22 9440141767. This replaces the lsof ownership check with the simpler rule the maintainer chose: close stops the emulator process this session's open launched.

  • Open records { pid, startTime } from the spawn. Close reads that process once, right before the stop. Gone, zombie or another start time: retain with the "process has changed" warning. Read failure: retain with "could not verify". No identity: retain. Alive and matching: adb emu kill, confirm the pid exits, then fall back to a pid stop that checks the start time.
  • Removed: the lsof console probe, the agreeing reads, retries and deadlines, the miss types, DeviceShutdownGenerationService and the verification callback. The rule is one typed capability (LaunchedDeviceProcessService) composed in src/platform-runtime-device-boot.ts; the close path names no platform.
  • Delta against 9ac325a1a6: production +309 / -353, total +732 / -995. No lsof remains in the docs or help.
  • Unchanged: policy denial, the lost-claim path, close --shutdown, iOS, and data.shutdown.

Exact affected validation passed (42 passed, 28 skipped). The ready-for-human review covered the previous head. This head needs a review and one live run of the five cases, plus one run of the pid fallback. This also covers #4743, which I will close when this merges.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

The launched-process rule is simpler than the old console probe, but at 00f70c2 close can still stop an emulator this session did not boot, and the new rule has no live run yet. CI is green: 16 checks pass. No hosted job boots an emulator, so CI does not exercise the changed stop route. No conflicts.

The earlier review at 9ac325a was clean. That head re-checked ownership inside shutdownAndroidTarget, right before adb emu kill. This head dropped that check and keeps only the one at the top of the teardown. Between that read and the kill, close stops session resources, waits for the platform close (up to 2 s foreground plus 10 s process exit), clears runtime hints and waits out the IME flush. If the #4585 actor restarts the emulator in that window, Quick Boot keeps the serial. The check already said 'same', so adb emu kill stops the replacement. Then confirmLaunchedProcessStopped sees the recorded pid gone and reports 'stopped'. That is the #4585 outcome, and the claims 'right before the stop' and 'covers #4743' no longer hold. The rule to keep: the launched-process check is the last host read before the stop is requested. The smallest change is to move the single checkLaunchedProcess call to just before finalizeApplicationClose, and pass shutdownTarget only on 'same' or 'not-applicable'. Report 'changed' and 'unverified' with the existing warnings. Alternatively, pass the identity as opaque data on the shutdown request and check inside shutdownAndroidTarget after the IME flush. Either way, please add a routed test where the owner answers 'same' at decide time and 'changed' at stop time, and assert that no shutdownTarget is sent. If you were told decide-time placement is acceptable, this becomes a documented trade-off; please say so in the PR.

The ownership rule in device-boot.ts changed from the lsof console probe to pid plus start-time identity, with a new pid-stop fallback after adb emu kill. The earlier live Android runs exercised the lsof design, so this head has only mocked host-kit coverage. Please run it at the final head on a local emulator and post the close JSON with ps -p <pid> before and after for each case. (1) A stopped AVD, open then close: data.shutdown is present and the process is gone. (2) A pre-booted emulator, open then close: still running, no shutdown. (3) Open cold, then kill and restart the same AVD externally (same serial), then close: a process-changed warning appears and the replacement keeps running. (4) A daemon policy denying device shutdown, then close: a policy warning and the emulator keeps running. (5) close --shutdown on an emulator this open did not boot: it stops. Add one more run where the emulator ignores adb emu kill, showing no launch_process_identity_miss diagnostic and the pid gone through the start-time-checked stop.

Not blocking, take or leave: when confirmLaunchedProcessStopped returns 'unconfirmed', close only emits a diagnostic and still reports data.shutdown from the adb result, so either add a response warning or drop the 'confirm' wording from the PR body; also the LaunchedDeviceProcessService doc in device-boot.ts says it names no pid while both members take AndroidEmulatorLaunchIdentity, and the PR Summary still describes the removed readiness-timestamp design.

Before merge, move the launched-process check to the last read before the stop, then post the live Android runs above at that head.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
The ownership read ran when close decided the stop, up to about 12 s before adb emu kill, so a replacement that took the serial during platform close or hint cleanup could be stopped. The single read now runs just before finalizeApplicationClose, and shutdownTarget is passed only when the launched process still matches. Close also warns when it could not confirm that the process exited.
@thymikee

Copy link
Copy Markdown
Member Author

Pushed 76b0043980. It answers the review at 00f70c2.

  1. Ownership check: the single checkLaunchedProcess read now runs right before finalizeApplicationClose, after resource stops, platform close and hint cleanup. shutdownTarget is passed only on same or not-applicable; changed and unverified give the existing warnings. The decide step only settles whether a stop is owed (claim renewed, policy allows). New routed test: a replacement that takes the serial during platform close is not stopped. It asserts that no ownership read happened before platform close, then flips the process to changed and expects no shutdownTarget, no stop and the warning. The IME flush runs inside the stop, so a short window after the read remains; say if you want the check inside shutdownAndroidTarget instead.
  2. Live run: not done yet. The PR body lists the six scenarios for this head.
  3. Optional items: close now warns when confirmLaunchedProcessStopped is unconfirmed; the LaunchedDeviceProcessService doc and the PR Summary are corrected.

Exact affected validation passed (42 passed, 28 skipped).

@apex-sentinel-staging

This comment has been minimized.

@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 76b0043. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At 76b0043 the race from the earlier review is fixed: the ownership check now runs just before finalizeApplicationClose, and the routed regression covers it. One item remains, and it needs a live Android run. All 16 checks pass, but no hosted job boots an emulator, so CI does not exercise the changed stop route.

The Android ownership rule at device-boot.ts:77 now uses a pid plus start-time launch identity, with a start-time-checked pid stop after adb emu kill. Only mocked host-kit and routed fake-owner tests cover it. This is a device-facing stop path. A wrong start-time parse or pid read on a real host would either stop an emulator this session did not boot or leave a session-booted one running. Please run these on a dedicated AVD at the final head, and post the close JSON plus ps -o pid,lstart -p <pid> before and after for each: (1) stopped AVD, open then close: data.shutdown is present and the pid is gone; (2) pre-booted emulator, open then close: no data.shutdown, pid still alive; (3) open cold, then kill and restart the same AVD externally on the same serial, then close: the 'process has changed' warning appears, no data.shutdown, and the replacement pid is alive; (4) daemon policy denying device-shutdown, then close: the policy warning appears and the emulator is alive; (5) close --shutdown on an emulator this open did not boot: it stops; (6) an emulator that ignores adb emu kill (for example SIGSTOP the guest console, or a stubbed adb): no launch_process_identity_miss diagnostic, no unconfirmed warning, and the pid is gone through the start-time-checked stop. The pid and start-time parsing did not change in this delta, and only the live run can confirm it on a real host.

Please also close the remaining window while you are there: lifecycle.ts:88 still runs restoreTestIme after the ownership read, and shutdownAndroidTarget then waits up to 2.5 s in awaitTestImeFlushWindow before adb emu kill, so the window shrank from about 14 s but is not closed, and a Quick Boot replacement taking the serial inside it would be killed and reported as stopped (passing the launch identity on the shutdown request and checking it after that wait would close it, otherwise the teardown comment could state the residual window instead of 'right before the stop'); and in session-close-lifecycle-teardown.ts:110 decideDeviceStopOnClose now always returns false for implicitShutdownLaunchedProcessGone and implicitShutdownLaunchedProcessUnverified, which runSessionCloseTeardown then overwrites, so those two fields could live only on SessionCloseTeardownResult.

The open inline thread on markSelectionBootOccurred (discussion) does not apply to this PR. The race is narrow, pre-existing, outside this delta and tracked in #4791, so you can resolve it here.

There are no known conflicts. Before merge, the live Android runs above need to be posted at the final head.

The decide step no longer reads the launched process, so the two outcomes live only on the teardown result. The teardown comment states the residual window inside the Android stop's IME flush wait.
@thymikee

Copy link
Copy Markdown
Member Author

Pushed 696e453f33.

  • Residual window: stated in the teardown comment. The Android stop restores the test IME and waits up to 2.5 s for its flush before adb emu kill, so a replacement that takes the serial inside that wait is not seen. A check after that wait needs a verification callback back in the Android shutdown runtime, which the simpler design removed on purpose, so I documented the window instead.
  • implicitShutdownLaunchedProcessGone and implicitShutdownLaunchedProcessUnverified now live only on SessionCloseTeardownResult.
  • The markSelectionBootOccurred thread is resolved; close: require proof that open booted an Apple simulator before the implicit stop #4791 tracks it.
  • Exact affected validation passed (42 passed, 28 skipped).

Live runs: not done by me. This host has only AVDs that are under the standing stop conditions, and the dedicated AVD is not on it. The six scenarios in the PR body need a run at 696e453f33 on the host that has the dedicated AVD.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 696e453

Since the review of 76b0043: 0 new · 0 still open · 1 no longer raised

No open findings.

1 new finding away from what changed since 76b0043 not shown. Comment @apex-sentinel-staging review for a full review.

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

💬 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.

@thymikee

Copy link
Copy Markdown
Member Author

At 696e453 the teardown comment now states the residual 2.5 s IME-flush window before adb emu kill, and the two always-false decision fields are gone, which settles the remaining code notes. The one open item is still the live Android run of the six close cases from the earlier review, with the close JSON and ps -o pid,lstart -p <pid> before and after each, at the final head.

@thymikee

Copy link
Copy Markdown
Member Author

Live Android runs for the six close cases from the earlier review, at the current head 696e453. All six behaved as expected, each run once with no retries.

One thing to note outside the six: close --shutdown returns when adb emu kill answers and does not wait for the emulator process to exit (case 5), while the implicit stop does wait (case 1). The pid was gone about 6 s later. That does not block this PR, but the two stop paths could wait the same way.

Full transcript

All six scenarios behaved as expected.

# Scenario Result
1 Stopped AVD, open then close pass
2 Prebooted emulator, open then close pass
3 Cold open, external restart on the same serial, close pass
4 Policy denies device-shutdown, cold open then close pass
5 close --shutdown on an emulator this open did not boot pass
6 Emulator that ignores adb emu kill pass

Environment

  • Tested SHA: 696e453f33ca5872fdc52ca9c8f941ca67d1e7e3 (the PR head at the time of the run), built with pnpm install --frozen-lockfile && pnpm build, driven with node bin/agent-device.mjs.
  • Host: macOS 27.0 (26A428), Apple silicon.
  • Node: v26.11.1.
  • Android Emulator 37.2.13.0. Dedicated AVD agent-device-pr4539-api37, API level 37 (ro.build.version.sdk=37, release 17), arm64.
  • Serial: emulator-5560 in every scenario. Three other emulators (5554, 5556, 5558) ran on the host the whole time and were not touched.
  • Daemon state: STATE=$(mktemp -d), and --state-dir "$STATE" on every command.

How the emulator pid was found: pgrep -f "qemu-system.*-avd agent-device-pr4539-api37( |$)", cross-checked with adb -s emulator-5560 emu avd name.

"External boot" below means:

emulator -avd agent-device-pr4539-api37 -port 5560 -no-window -no-audio -no-boot-anim -no-metrics &
# then wait for: adb -s emulator-5560 shell getprop sys.boot_completed == 1

1. Stopped AVD, open then close — pass

agent-device open Settings --platform android --device agent-device-pr4539-api37 --session s1 --state-dir "$STATE" --json
agent-device close --session s1 --state-dir "$STATE" --json

open reported selection.bootOccurred: true, serial emulator-5560.

Before close:

  PID STARTED
20336 Fri Nov 20 13:19:20 2026

Close output:

{
  "success": true,
  "data": {
    "session": "s1",
    "shutdown": {
      "success": true,
      "exitCode": 0,
      "stdout": "OK: killing emulator, bye bye\r\nOK\r\n",
      "stderr": ""
    },
    "message": "Closed: s1"
  }
}

After close (ps exit 1, no row; emulator-5560 gone from adb devices):

  PID STARTED

2. Prebooted emulator, open then close — pass

External boot first, then:

agent-device open Settings --platform android --device agent-device-pr4539-api37 --session s2 --state-dir "$STATE" --json
agent-device close --session s2 --state-dir "$STATE" --json

open reported selection.bootOccurred: false.

Before close:

  PID STARTED
26672 Fri Nov 20 13:19:57 2026

Close output (no data.shutdown, no warnings):

{
  "success": true,
  "data": {
    "session": "s2",
    "message": "Closed: s2"
  }
}

After close (same pid, same start time; emulator-5560 device in adb devices):

  PID STARTED
26672 Fri Nov 20 13:19:57 2026

3. Cold open, external restart on the same serial, close — pass

agent-device open Settings --platform android --device agent-device-pr4539-api37 --session s3 --state-dir "$STATE" --json
adb -s emulator-5560 emu kill        # external kill; waited until the pid left
# external boot again on port 5560
agent-device close --session s3 --state-dir "$STATE" --json

open reported selection.bootOccurred: true.

Process that open launched, before the external kill:

  PID STARTED
30706 Fri Nov 20 13:20:21 2026

Replacement process, before close:

  PID STARTED
31944 Fri Nov 20 13:20:29 2026

Close output (warning present, no data.shutdown):

{
  "success": true,
  "data": {
    "session": "s3",
    "warnings": [
      "This session's open booted this device, but its emulator process has changed, so close did not request a stop. The device is still running."
    ],
    "message": "Closed: s3"
  }
}

After close, the original pid has no row (ps exit 1) and the replacement is alive (emulator-5560 device in adb devices):

  PID STARTED
31944 Fri Nov 20 13:20:29 2026

4. Policy denies device-shutdown, cold open then close — pass

The isolated daemon was stopped and restarted with a policy file, set through AGENT_DEVICE_DAEMON_POLICY (ADR 0029):

echo '{"version":1,"capabilities":{"deny":["device-shutdown"]}}' > "$STATE/policy.json"
export AGENT_DEVICE_DAEMON_POLICY="$STATE/policy.json"
agent-device open Settings --platform android --device agent-device-pr4539-api37 --session s4 --state-dir "$STATE" --json
agent-device close --session s4 --verbose --state-dir "$STATE" --json

daemon.json showed a policyDigest. open reported selection.bootOccurred: true.

Before close:

  PID STARTED
35819 Fri Nov 20 13:20:57 2026

Close output:

{
  "success": true,
  "data": {
    "session": "s4",
    "warnings": [
      "This session's open booted this device and close would stop it, but this daemon's policy denies device-shutdown. The device is still running."
    ],
    "message": "Closed: s4"
  }
}

After close (same pid, same start time; emulator-5560 device in adb devices):

  PID STARTED
35819 Fri Nov 20 13:20:57 2026

5. close --shutdown on an emulator this open did not boot — pass

Same externally booted emulator as scenario 2 (still running), no policy:

agent-device open Settings --platform android --device agent-device-pr4539-api37 --session s5 --state-dir "$STATE" --json
agent-device close --session s5 --shutdown --state-dir "$STATE" --json

open reported selection.bootOccurred: false.

Before close:

  PID STARTED
26672 Fri Nov 20 13:19:57 2026

Close output:

{
  "success": true,
  "data": {
    "session": "s5",
    "shutdown": {
      "success": true,
      "exitCode": 0,
      "stdout": "OK: killing emulator, bye bye\r\nOK\r\n",
      "stderr": ""
    },
    "message": "Closed: s5"
  }
}

After close:

  PID STARTED

Note: ps run in the same instant as close returned still showed pid 26672, and adb devices still listed the serial. A second ps about 6 seconds later showed no row (ps exit 1) and the serial was gone. The explicit --shutdown path returns when adb emu kill answers and does not wait for the process to exit; the implicit path in scenario 1 does wait. This is not a failure of the scenario.

6. Emulator that ignores adb emu kill — pass

Staging. A wrapper adb first on PATH does not work, because the daemon puts the SDK tool directories in front of PATH. So the daemon for this scenario got a shadow SDK root: a directory whose entries are symlinks to the real SDK, except platform-tools/adb, which is this wrapper:

#!/bin/sh
# Swallow only "emu kill"; pass everything else to the real adb.
case " $* " in
  *" emu kill "*) echo "$(date -u +%FT%TZ) swallowed: adb $*" >> "$STATE/adb-swallowed.log"
                  printf 'OK: killing emulator, bye bye\r\nOK\r\n'; exit 0;;
esac
exec "$REAL_SDK/platform-tools/adb" "$@"

The daemon was restarted without a policy and with the shadow root:

export ANDROID_SDK_ROOT="$STATE/fake-sdk" ANDROID_HOME="$STATE/fake-sdk"
agent-device open Settings --platform android --device agent-device-pr4539-api37 --session s6 --state-dir "$STATE" --json
agent-device close --session s6 --verbose --state-dir "$STATE" --json

open reported selection.bootOccurred: true. The emulator is real and was never told to exit by adb; the wrapper log proves the daemon's kill was swallowed:

2026-11-20T12:21:40Z swallowed: adb -s emulator-5560 emu kill

Before close:

  PID STARTED
41324 Fri Nov 20 13:21:36 2026

Close output (no warnings):

{
  "success": true,
  "data": {
    "session": "s6",
    "shutdown": {
      "success": true,
      "exitCode": 0,
      "stdout": "OK: killing emulator, bye bye\r\nOK\r\n",
      "stderr": ""
    },
    "message": "Closed: s6"
  }
}

After close (ps exit 1, no row):

  PID STARTED

Request diagnostics for this close (--verbose request log, UTC):

12:21:40.188 request_start
12:21:40.193 ps            (ownership read: pid alive, start time matches)
12:21:40.201 adb           (emu kill, swallowed by the wrapper)
12:21:43.228 ps            (after the 3 s exit wait: start-time check before the pid stop)
12:21:44.735 ps            (exit confirmed)
12:21:44.849 request_success
  • launch_process_identity_miss diagnostics in the request log and in the --verbose stderr: 0.
  • Diagnostics at level warn: 0.
  • Close took about 4.6 s: the 3 s wait for a graceful exit, then the pid stop inside its 1.5 s terminate budget.
  • adb devices showed emulator-5560 offline for a moment after the hard stop, then the entry cleared.

Limits of this run

  • Request diagnostics are written only with --verbose. Scenarios 1, 2, 3 and 5 ran without it, so their evidence is the close JSON and ps, not the diagnostic stream. In particular the launch_process_identity_miss (process-check-changed) diagnostic expected in scenario 3 was not captured.
  • Each scenario ran once. No scenario was retried.
  • The residual window the review describes (a replacement taking the serial between the ownership read and adb emu kill) was not exercised.

Cleanup

  • Isolated daemon stopped with agent-device daemon stop --state-dir "$STATE" ("stopped": true).
  • No qemu process for agent-device-pr4539-api37 remains (pgrep empty).
  • adb devices lists only the three emulators that were running before the test (5554, 5556, 5558).
  • No code changed, nothing pushed, no GitHub comment or label touched. The $STATE directory was left in place.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at 696e453. The live Android runs cover all six close cases on a dedicated AVD at this head. A cold open then close stops the emulator. A pre-booted emulator is kept. After an external restart on the same serial, close warns and keeps the replacement. A policy denial warns and keeps the device. close --shutdown stops it. When adb emu kill is swallowed, the start-time-checked pid stop ends the emulator with no identity-miss diagnostic. The residual 2.5 s IME-flush window is stated in the teardown comment.

Not blocking: close --shutdown returns when adb emu kill answers, while the implicit stop waits for the process to exit, so the two paths could wait the same way in a follow-up. Case 3 ran without --verbose, so its launch_process_identity_miss diagnostic was not captured; the warning and the surviving replacement pid show the outcome.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@thymikee
thymikee merged commit c30537b into 0.22 Nov 20, 2026
16 checks passed
@thymikee
thymikee deleted the t3/implicit-virtual-device-shutdown branch November 20, 2026 12:55
thymikee added a commit that referenced this pull request Nov 20, 2026
…ed (#4539)

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

Squashed rebase of #4539 onto the rewritten 0.22 (91d3628). The content equals 29cb52b except for conflict adaptations: the interaction-contract harness keeps main's single settling read, and two tests pass main's new cache argument before the lifecycle loader.

* fix(close): read the emulator console listener without blocking calls and retry a slow read

Under heavy host load one lsof read took 1.7-4.2 s against a 3 s budget, so the launch identity read as unobserved and close kept an emulator it should stop. Use lsof -b -w -t, give each read 5 s, and retry once when a read times out or fails. A clean no-listener answer is final.

* fix(close): bound the launch identity probe and keep -b off Linux lsof

Open and close each run two agreeing observations, and each observation could take two 5 s reads, so the probe could add 20 s per step. The pair now shares one 10 s deadline that also caps each lsof and ps read. Linux lsof finds sockets through /proc, and -b can stop the port filter matching there, so -b and -w apply only on macOS.

* fix(close): retry the launch start time read and name each identity miss

Open read the launched emulator's start time with the 1 s ps default, so one slow ps left no launch identity and cold stop failed safe under load. The read now uses the listener probe's 5 s budget and one retry. Each observation reports why it produced no identity; open logs android_launch_identity_unbound and close logs android_launch_identity_unobserved with the step and the read that missed. The close warning now says when open recorded no identity.

* refactor(close): drop the identity-only probe export

Every caller now reads the miss reason through inspectAndroidEmulatorGeneration.

* test(close): cover the launch start time retry and keep ps inside the deadline

Cover the retried 5 s launch start time read and the zombie case. The ps read after lsof now gets only what the shared deadline still has, so one slow attempt stays inside the 10 s pair budget.

* refactor(android): verify the launched emulator process on close

Plain close now owns the emulator process its own `open` launched, instead
of probing which emulator generation owns the console. `open` records
`{ pid, startTime }`; close reads the host facts for that pid once, keeps
the device when the process is gone, changed, or unverifiable, and stops
the recorded process when the emulator console kill does not take.

Removes the `lsof` console-listener generation probe, the
`DeviceShutdownGenerationService` wiring, and the `generation` field that
platform runtimes no longer answer for.

* refactor(close): ask the root-composed owner about the launched process

`check:layering` rejects the previous shape: R65 keeps the daemon's close
orchestration from selecting a concrete platform, and the launched-emulator
check did exactly that. The rule moves to where R65 points — a published
`LaunchedDeviceProcessService` composed at the root, answered by the Android
family and `not-applicable` for every device that launches no host process.

The process reads themselves (one `ps`, liveness, and the pid escalation with
the recorded start time) now live in `@agent-device/platform-android/device-boot`
beside the launch that records the identity, which is where the timeout and
escalation budgets belong.

* fix(close): read launched-process ownership right before the stop

The ownership read ran when close decided the stop, up to about 12 s before adb emu kill, so a replacement that took the serial during platform close or hint cleanup could be stopped. The single read now runs just before finalizeApplicationClose, and shutdownTarget is passed only when the launched process still matches. Close also warns when it could not confirm that the process exited.

* refactor(close): keep launched-process outcomes on the teardown result

The decide step no longer reads the launched process, so the two outcomes live only on the teardown result. The teardown comment states the residual window inside the Android stop's IME flush wait.
thymikee added a commit that referenced this pull request Nov 20, 2026
…ed (#4539)

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

Squashed rebase of #4539 onto the rewritten 0.22 (91d3628). The content equals 29cb52b except for conflict adaptations: the interaction-contract harness keeps main's single settling read, and two tests pass main's new cache argument before the lifecycle loader.

* fix(close): read the emulator console listener without blocking calls and retry a slow read

Under heavy host load one lsof read took 1.7-4.2 s against a 3 s budget, so the launch identity read as unobserved and close kept an emulator it should stop. Use lsof -b -w -t, give each read 5 s, and retry once when a read times out or fails. A clean no-listener answer is final.

* fix(close): bound the launch identity probe and keep -b off Linux lsof

Open and close each run two agreeing observations, and each observation could take two 5 s reads, so the probe could add 20 s per step. The pair now shares one 10 s deadline that also caps each lsof and ps read. Linux lsof finds sockets through /proc, and -b can stop the port filter matching there, so -b and -w apply only on macOS.

* fix(close): retry the launch start time read and name each identity miss

Open read the launched emulator's start time with the 1 s ps default, so one slow ps left no launch identity and cold stop failed safe under load. The read now uses the listener probe's 5 s budget and one retry. Each observation reports why it produced no identity; open logs android_launch_identity_unbound and close logs android_launch_identity_unobserved with the step and the read that missed. The close warning now says when open recorded no identity.

* refactor(close): drop the identity-only probe export

Every caller now reads the miss reason through inspectAndroidEmulatorGeneration.

* test(close): cover the launch start time retry and keep ps inside the deadline

Cover the retried 5 s launch start time read and the zombie case. The ps read after lsof now gets only what the shared deadline still has, so one slow attempt stays inside the 10 s pair budget.

* refactor(android): verify the launched emulator process on close

Plain close now owns the emulator process its own `open` launched, instead
of probing which emulator generation owns the console. `open` records
`{ pid, startTime }`; close reads the host facts for that pid once, keeps
the device when the process is gone, changed, or unverifiable, and stops
the recorded process when the emulator console kill does not take.

Removes the `lsof` console-listener generation probe, the
`DeviceShutdownGenerationService` wiring, and the `generation` field that
platform runtimes no longer answer for.

* refactor(close): ask the root-composed owner about the launched process

`check:layering` rejects the previous shape: R65 keeps the daemon's close
orchestration from selecting a concrete platform, and the launched-emulator
check did exactly that. The rule moves to where R65 points — a published
`LaunchedDeviceProcessService` composed at the root, answered by the Android
family and `not-applicable` for every device that launches no host process.

The process reads themselves (one `ps`, liveness, and the pid escalation with
the recorded start time) now live in `@agent-device/platform-android/device-boot`
beside the launch that records the identity, which is where the timeout and
escalation budgets belong.

* fix(close): read launched-process ownership right before the stop

The ownership read ran when close decided the stop, up to about 12 s before adb emu kill, so a replacement that took the serial during platform close or hint cleanup could be stopped. The single read now runs just before finalizeApplicationClose, and shutdownTarget is passed only when the launched process still matches. Close also warns when it could not confirm that the process exited.

* refactor(close): keep launched-process outcomes on the teardown result

The decide step no longer reads the launched process, so the two outcomes live only on the teardown result. The teardown comment states the residual window inside the Android stop's IME flush wait.
thymikee added a commit that referenced this pull request Nov 21, 2026
…ed (#4539)

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

Squashed rebase of #4539 onto the rewritten 0.22 (91d3628). The content equals 29cb52b except for conflict adaptations: the interaction-contract harness keeps main's single settling read, and two tests pass main's new cache argument before the lifecycle loader.

* fix(close): read the emulator console listener without blocking calls and retry a slow read

Under heavy host load one lsof read took 1.7-4.2 s against a 3 s budget, so the launch identity read as unobserved and close kept an emulator it should stop. Use lsof -b -w -t, give each read 5 s, and retry once when a read times out or fails. A clean no-listener answer is final.

* fix(close): bound the launch identity probe and keep -b off Linux lsof

Open and close each run two agreeing observations, and each observation could take two 5 s reads, so the probe could add 20 s per step. The pair now shares one 10 s deadline that also caps each lsof and ps read. Linux lsof finds sockets through /proc, and -b can stop the port filter matching there, so -b and -w apply only on macOS.

* fix(close): retry the launch start time read and name each identity miss

Open read the launched emulator's start time with the 1 s ps default, so one slow ps left no launch identity and cold stop failed safe under load. The read now uses the listener probe's 5 s budget and one retry. Each observation reports why it produced no identity; open logs android_launch_identity_unbound and close logs android_launch_identity_unobserved with the step and the read that missed. The close warning now says when open recorded no identity.

* refactor(close): drop the identity-only probe export

Every caller now reads the miss reason through inspectAndroidEmulatorGeneration.

* test(close): cover the launch start time retry and keep ps inside the deadline

Cover the retried 5 s launch start time read and the zombie case. The ps read after lsof now gets only what the shared deadline still has, so one slow attempt stays inside the 10 s pair budget.

* refactor(android): verify the launched emulator process on close

Plain close now owns the emulator process its own `open` launched, instead
of probing which emulator generation owns the console. `open` records
`{ pid, startTime }`; close reads the host facts for that pid once, keeps
the device when the process is gone, changed, or unverifiable, and stops
the recorded process when the emulator console kill does not take.

Removes the `lsof` console-listener generation probe, the
`DeviceShutdownGenerationService` wiring, and the `generation` field that
platform runtimes no longer answer for.

* refactor(close): ask the root-composed owner about the launched process

`check:layering` rejects the previous shape: R65 keeps the daemon's close
orchestration from selecting a concrete platform, and the launched-emulator
check did exactly that. The rule moves to where R65 points — a published
`LaunchedDeviceProcessService` composed at the root, answered by the Android
family and `not-applicable` for every device that launches no host process.

The process reads themselves (one `ps`, liveness, and the pid escalation with
the recorded start time) now live in `@agent-device/platform-android/device-boot`
beside the launch that records the identity, which is where the timeout and
escalation budgets belong.

* fix(close): read launched-process ownership right before the stop

The ownership read ran when close decided the stop, up to about 12 s before adb emu kill, so a replacement that took the serial during platform close or hint cleanup could be stopped. The single read now runs just before finalizeApplicationClose, and shutdownTarget is passed only when the launched process still matches. Close also warns when it could not confirm that the process exited.

* refactor(close): keep launched-process outcomes on the teardown result

The decide step no longer reads the launched process, so the two outcomes live only on the teardown result. The teardown comment states the residual window inside the Android stop's IME flush wait.
thymikee added a commit that referenced this pull request Nov 21, 2026
…ed (#4539)

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

Squashed rebase of #4539 onto the rewritten 0.22 (91d3628). The content equals 29cb52b except for conflict adaptations: the interaction-contract harness keeps main's single settling read, and two tests pass main's new cache argument before the lifecycle loader.

* fix(close): read the emulator console listener without blocking calls and retry a slow read

Under heavy host load one lsof read took 1.7-4.2 s against a 3 s budget, so the launch identity read as unobserved and close kept an emulator it should stop. Use lsof -b -w -t, give each read 5 s, and retry once when a read times out or fails. A clean no-listener answer is final.

* fix(close): bound the launch identity probe and keep -b off Linux lsof

Open and close each run two agreeing observations, and each observation could take two 5 s reads, so the probe could add 20 s per step. The pair now shares one 10 s deadline that also caps each lsof and ps read. Linux lsof finds sockets through /proc, and -b can stop the port filter matching there, so -b and -w apply only on macOS.

* fix(close): retry the launch start time read and name each identity miss

Open read the launched emulator's start time with the 1 s ps default, so one slow ps left no launch identity and cold stop failed safe under load. The read now uses the listener probe's 5 s budget and one retry. Each observation reports why it produced no identity; open logs android_launch_identity_unbound and close logs android_launch_identity_unobserved with the step and the read that missed. The close warning now says when open recorded no identity.

* refactor(close): drop the identity-only probe export

Every caller now reads the miss reason through inspectAndroidEmulatorGeneration.

* test(close): cover the launch start time retry and keep ps inside the deadline

Cover the retried 5 s launch start time read and the zombie case. The ps read after lsof now gets only what the shared deadline still has, so one slow attempt stays inside the 10 s pair budget.

* refactor(android): verify the launched emulator process on close

Plain close now owns the emulator process its own `open` launched, instead
of probing which emulator generation owns the console. `open` records
`{ pid, startTime }`; close reads the host facts for that pid once, keeps
the device when the process is gone, changed, or unverifiable, and stops
the recorded process when the emulator console kill does not take.

Removes the `lsof` console-listener generation probe, the
`DeviceShutdownGenerationService` wiring, and the `generation` field that
platform runtimes no longer answer for.

* refactor(close): ask the root-composed owner about the launched process

`check:layering` rejects the previous shape: R65 keeps the daemon's close
orchestration from selecting a concrete platform, and the launched-emulator
check did exactly that. The rule moves to where R65 points — a published
`LaunchedDeviceProcessService` composed at the root, answered by the Android
family and `not-applicable` for every device that launches no host process.

The process reads themselves (one `ps`, liveness, and the pid escalation with
the recorded start time) now live in `@agent-device/platform-android/device-boot`
beside the launch that records the identity, which is where the timeout and
escalation budgets belong.

* fix(close): read launched-process ownership right before the stop

The ownership read ran when close decided the stop, up to about 12 s before adb emu kill, so a replacement that took the serial during platform close or hint cleanup could be stopped. The single read now runs just before finalizeApplicationClose, and shutdownTarget is passed only when the launched process still matches. Close also warns when it could not confirm that the process exited.

* refactor(close): keep launched-process outcomes on the teardown result

The decide step no longer reads the launched process, so the two outcomes live only on the teardown result. The teardown comment states the residual window inside the Android stop's IME flush wait.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant