Skip to content

feat(cli): replace cloud connection profiles with hosted session leases - #5085

Merged
thymikee merged 27 commits into
0.22from
feat/0.22-hosted-session-lifecycle
Nov 25, 2026
Merged

thymikee merged 27 commits into
0.22from
feat/0.22-hosted-session-lifecycle

Conversation

@thymikee

@thymikee thymikee commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Replace hosted connection profiles with session create and teardown. Persist the attempt key and keep observed lease IDs until the API confirms teardown. Fence owned sessions when sending probes or device commands and before pulling artifacts. Delete the superseded profile module and hosted-profile tests. Direct provider cases remain.

Before / after

  • connect cloud --platform ios --session example --json creates a hosted lease and reports the ID and deadline.
  • snapshot -i --session example uses the lease's scoped credential.
  • disconnect --session example --json ends the lease. Retry after an inconclusive teardown.

Validation

Head 9bb90e4608306b4ff3d35ece0542619faf32af87. Coverage timed out twice in the SOCKS/TLS fixture. A controlled delay reproduced the timeout before the ordering fix and passed afterward. The fixture now acknowledges CONNECT after the upstream relay is ready. All 25 focused SOCKS and artifact tests, lint, and type checking passed. Fresh CI is pending.

Previous head 6b4c4933de6aa523493709e4af9a2aa18b153656. Refused artifact admission destroys the unsent request and preserves existing output. Cleanup still runs after an admitted send starts. The regression reproduced deletion at 0a0baf4 and passed on this head. All 23 focused tests, lint, type checking, and the protocol v3 wire check passed. Fresh CI is pending.

Earlier hosted iOS and Android connect, open, snapshot, and release passed on aaad938870b91029cbe988474f543b178d07b29a, with each session settling at $0.10 under a $0.50 cap.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 5.07 MB 5.10 MB +33.0 kB
Package (unpacked) 5.07 MB 5.10 MB +33.0 kB
Package (download) 1.55 MB 1.56 MB +10.8 kB

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 16.2 ms 15.4 ms -0.8 ms
CLI --help 26.9 ms 26.7 ms -0.3 ms

@thymikee
thymikee changed the base branch from fix/0.22-hosted-auth-origin to refactor/0.22-daemon-request-cancellation November 24, 2026 20:01
@thymikee
thymikee added this pull request to stack #5087 November 24, 2026 20:01
@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 b2e2c8f. The verdict and the full list are in the summary comment.

Comment thread src/commands/schema/cli-help.ts Resolved
Comment thread src/cli/commands/connection.ts Resolved
@thymikee

Copy link
Copy Markdown
Member Author

Reviewed b2e2c8f. This needs changes before merge: disconnect can stall for about 3 minutes on direct connections, and every local command now creates a lock directory that fails three integration tests.

src/cli/connection/ended-lease.ts:34: disconnectCommand holds withConnectionLock while disconnectProvider calls client.sessions.close through the CLI transport. When the close reply carries endedLeases, forgetEndedConnectionLease takes the same lock again. The process lock is not re-entrant, so the call waits the full 180 s, the timeout is swallowed, and providerData is lost. connect --remote-config --force nests the same way through cleanupForcedPreviousConnection. Before this PR, disconnect of a leased remote-config or proxy connection returned at once. The rule: no daemon request sent while the connection lock is held may re-take that lock. createCliDaemonTransport is the place that enumerates this, so skip the forget wrapper for connect and disconnect, which own the state they run under. Please add a runCliCapture test that disconnects a leased connection whose close reply carries endedLeases and finishes without a lock wait.

src/cli/connection/active-connection.ts:50: resolveCloudAdmission returns an admission for every session command, even when the session has no cloud binding and no record. MCP createClient does the same. Each local command now takes the connection lock twice and creates connection-locks/ in the state dir. That is why Integration Tests fail in daemon-replace-exit-flush, smoke-daemon-clean and smoke-daemon-http with "stray state-dir entries: connection-locks/". Local and direct users who never use the cloud pay for a fence they do not need. Please fence only sessions that a cloud connection owns: when neither the binding nor record.json exists, return no admission (and skip admit in MCP). An lstat of the record is enough. A command that races a concurrent connect cloud still runs on the local daemon without cloud credentials, so it needs no lock.

src/commands/schema/cli-help.ts:485: the new provider sentence reads "--max-minutes to request a duration to cap the charge for the session in USD (for example 0.50) to start the session with a hosted app archive". These are fragments of removed flags. connect has no charge cap and no app archive URL. Agents read help as the contract and may assume a session is cost-capped when it is not. Please remove the two fragments so the sentence lists only --needs, --vendor, --device, --os, --max-minutes and --show-viewer, then regenerate the docs guard. A second independent pass found the same help text also fails in practice at src/commands/schema/cli-help.ts:551: with AGENT_DEVICE_SESSION set and no ambient platform, bare connect stops because src/cli/connection/cloud-session-api.ts:56 requires a platform. Please replace the walkthrough with an explicit connect cloud --platform ios command.

A second independent pass found these further problems. Each is phrased as the rule the code must satisfy.

src/cli/connection/cloud-access.ts:40: after a lease is created on a custom issuer, unsetting AGENT_DEVICE_CLOUD_BASE_URL and setting AGENT_DEVICE_DAEMON_AUTH_TOKEN pairs that ambient credential with the saved custom origin on connect retry, disconnect and forced replacement. The mismatch check at line 35 runs only when an override is present. The POST, GET or DELETE then sends an unrelated token to the old broker. Please resolve the issuer of explicit and ambient keys from current configuration before choosing any lease endpoint, and require it to equal the saved origin before using a key. A stored login can use the pinned origin after its issuer check.

src/cli/connection/cloud-session-api.ts:442: a create response can return the bearer it received in the POST as daemonAuthToken or a Limrun token with a different attachment origin. Lines 470–481 accept any nonempty token, and cloud-attachment.ts then applies it to device requests at the response-selected endpoint. Please reject attachments that reuse the create bearer before publication. The hosted API contract should give a session credential distinct from the broker's, bound to the allocation and attachment audience.

packages/provider-limrun/src/device-session.ts:188: stopping a recording on a hosted Limrun attachment feeds downloadUrl from the stop response to the downloader, which adds the instance bearer without checking origin or TLS. download-file.ts also follows redirects by default, and the iOS file helpers in ios-files.ts do the same. Those helpers predate this PR, but the hosted route now gives them leased attachment credentials. Please bind authenticated downloads to the instance origin, require HTTPS or loopback HTTP before the first request, and set redirect: 'error' when sending an attachment credential. If this cannot land here, please leave Limrun out of hosted accepts until it does.

packages/daemon-client/src/daemon-client-rpc.ts:155: a device daemon can return an RPC error with the scoped token in its message. registerDiagnosticSensitiveValue covers local diagnostic events, but the RPC message becomes an AppError whose message is kept outside diagnostic redaction, and cli.ts prints it in human and JSON errors. Please scrub the exact scoped bearer from peer-controlled result, error and diagnostic text at the hosted attachment response boundary, so generic private-daemon behavior stays unchanged.

src/cli/commands/connection-presentation.ts:204: the create response can echo a key or attachment token in id, vendor or a fallbackFrom entry. The parser accepts any nonempty value and JSON emits it verbatim. With --show-viewer, lines 167 and 209 print the complete bearer link including its query credential, and cli-cloud-session.test.ts exercises a token-bearing link in JSON. Please validate narrow public identifiers, drop display values that contain known credentials before persistence or output, and keep viewer bearer URLs out of stdout and JSON.

src/cli/connection/cloud-connect.ts:82: after allocation_in_progress returns an ID, a retry that gets a generic HTTP 429 is treated as definitive at cloud-session-api.ts lines 222–231, and the pending record is deleted even though it holds the ID. Separately, disconnect with a known ID that gets a bare 404 from lookup (lines 169–175) skips DELETE, reports success and removes the record. A lookup miss does not show that an observed allocation ended. Please keep the ID across inconclusive POST responses and attempt an exact-ID DELETE unless the broker confirms the ID is terminal. When only the attempt key is known, require a broker-defined definitive no-allocation response, not any 404.

src/cli/connection/cloud-session-api.ts:234: an ID with an unpaired UTF-16 surrogate passes isSessionId and can commit a lease. encodeURIComponent at line 391 then throws before DELETE, and every later disconnect fails the same way. Please validate IDs against the broker's bounded path-segment grammar before storing them, and keep the attempt key for recovery when the ID is invalid.

src/cli.ts:405: a session-aware command without a session flag, run while the active connection is a non-leased private profile under a non-default name, gets that name from remote-connection-state.ts. If a cloud connect takes that name while the command prepares, the admission closure at active-connection.ts lines 46–50 still checks default from the pre-merge flags. The stale command can then dispatch to the previous daemon. Please fence the effective request session in the resolved state directory and verify the expected generation for that location at the transport handoff.

src/cli/connection/active-connection.ts:44: under umask 002 a direct connection can leave remote-connections at mode 0775 inside a private state root. The expiry sweep inspects that shared parent even when no cloud directory exists, and cloud-connection-record.ts lines 254–259 reject it before any direct command. The per-session read applies the same check on connect, disconnect and MCP admission. Please keep cloud credentials in a dedicated private sibling directory, or check for the cloud subtree before enforcing its permissions, and keep expiry failures local to the cloud store.

src/cli/connection/connect-provider-adapters.ts:174: bare connect with a named session, a configured daemon URL that does not end in /agent-device, and working cloud profile credentials used the builtin cloud adapter at f6ab008. At this head usesCloudSessionApi returns false for the explicit daemon URL, the resolver still defaults to cloud, and it tries to load a cloud plugin that is not registered. Please route an implicit connect with an explicit supported daemon endpoint to a configured daemon adapter that keeps its token and scope. Keep explicit connect cloud on the lease API.

src/cli/connection/cloud-access.ts:42: with AGENT_DEVICE_DAEMON_AUTH_TOKEN set to a private-daemon token and a usable stored login, connect list worked at f6ab008 because cloud-catalog-access.ts rejected the environment value as a cloud credential and used the login. At this head the merged resolver throws cloud_api_key_required before reading the login, for both static and live listings. Please restore the distinction between an explicitly supplied key and an ambient daemon token, and ignore an incompatible ambient token for the hosted catalog.

src/cli.ts:516: a state directory with a saved cloud profile from the base's built-in cloud route holds a remoteConfigPath and no cloudSession field. remote-connection-state.ts still supplies that profile's daemon URL, admission sees no cloud record and allows the generic route, and the CLI can send the account login token to the old daemon on each device command. Please recognize generated legacy cloud connection records at admission and require a new hosted connect before device dispatch. Scope this to legacy generated cloud state so explicit private and direct-provider profiles still work.

Not blocking, and fine to take or leave: replace the 'cloud' fallback in resolveConnectProviderProfile with an INVALID_ARGS refusal that names connect cloud, --remote-config and connect proxy, and drop the dead provider === 'cloud' branch at provider-policy.ts:191 if nothing reaches it; treat a 404 on DELETE of a recorded ID as ended in deleteCloudSession (or give disconnect --force a way to drop the record), since any other 404 body currently leaves the record in closing with no way out; use the contracts/kernel record guard instead of the new asRecord, un-export the local helpers, and split resolveHostedCloudAccess to clear the Fallow findings; delete the four blank lines after the --show-viewer paragraph in commands.md; and consider that the admit/dispatch seam in daemon-client-ensuring.ts and the cloud binding stored in both record.json and RemoteConnectionState.cloudSession add cross-checks for a single consumer.

Would a smaller design deliver the same lease ownership? One option is three PRs. (1) Lease lifecycle only: cloud-session-api (create, lookup, delete) plus record.json as the single source of the binding, with connect cloud and disconnect under the connection lock. That removes the four cross-checks. (2) Fencing: one pre-dispatch check in cli.ts (record committed, generation matches, deadline not passed) for sessions that have a record and no lock for sessions without one, relying on the cloud revoking the attachment token on DELETE instead of threading admit/dispatch through daemon-client, both senders and MCP (about 150 lines). (3) The Limrun attachment transport with its dedicated per-session daemon, which stays optional. This would be roughly half the production lines with no daemon-client or packages/remote changes. It first needs confirmation from the cloud API owner that DELETE /v1/sessions/{id} revokes the daemonAuthToken and the Limrun token synchronously. If it does not, would the client-side fence fit better in the CLI command dispatcher than in daemon-client?

CI: the three Integration Tests failures all report "daemon leak oracle: LEAK (after-shutdown) … stray state-dir entries: connection-locks/", and this diff creates that directory (the active-connection.ts:50 finding above). Repo Guards & Compatibility fails on four unused exports in cloud-session-api.ts and on resolveHostedCloudAccess above the complexity threshold in cloud-access.ts, also from this diff. The Coverage job failed too, but its visible log shows only fuzz-envelope noise, so the cause is not confirmed; it may be the same oracle. The Body rules run was cancelled by a newer run, and Lint, Typecheck & Package passed.

The PR also has merge conflicts with main, and it sits on 6e0c761 while #5084 was amended to f6ab008, so a rebase is needed. The review above covers b2e2c8f against its parent 6e0c761, and the conflict with the amended base was not re-reviewed.

Live validation is required before merge, because this change re-routes dispatch and credentials for device commands and the PR body lists live transport verification as pending. Against the hosted session API (staging is fine) at the final head, please attach the output of: agent-device connect cloud --platform ios --session <s> --json showing cloudSessionId, vendor and deadlineAt; agent-device snapshot -i --session <s> --json succeeding through the agent-device-daemon attachment with non-empty nodes; and agent-device disconnect --session <s> --json with released: true, plus the dashboard or a GET showing the session settled. Please repeat the flow on Android, or on a Limrun-transport session if Limrun acceptance stays in this PR. For the lock stall, please show a direct leased connection (proxy or remote-config) whose disconnect returns in seconds, with timing. Not verified here: the stall timing (it follows from the non-re-entrant lock and the nested withConnectionLock in the code), the attachment-token revocation on DELETE, the loopback-fixture create/teardown and cross-origin DELETE refusal described in the PR body (no artifact is attached), and whether the +11 ms startup delta in the size report is runner noise.

Before merge, the lock stall on direct disconnect and connect --force must be fixed, local sessions must stop creating connection-locks/ (which also turns Integration Tests green), and the false cost-cap and archive text must leave connect help. After that, the Fallow findings need fixing, the branch needs a rebase onto the amended #5084, and the live hosted-session evidence needs attaching.

@thymikee
thymikee force-pushed the feat/0.22-hosted-session-lifecycle branch from b2e2c8f to ff503e0 Compare November 24, 2026 20:34
@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 ff503e0. The verdict and the full list are in the summary comment.

@thymikee
thymikee force-pushed the feat/0.22-hosted-session-lifecycle branch from ff503e0 to 93dac30 Compare November 24, 2026 20:57
@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 93dac30. The verdict and the full list are in the summary comment.

@thymikee
thymikee force-pushed the feat/0.22-hosted-session-lifecycle branch from 93dac30 to 46baced Compare November 24, 2026 21:22
@thymikee
thymikee force-pushed the feat/0.22-hosted-session-lifecycle branch 2 times, most recently from 51ce884 to 3471fb2 Compare November 24, 2026 21:35
@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 3471fb2. The verdict and the full list are in the summary comment.

Comment thread src/cli/commands/connection.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

Base automatically changed from refactor/0.22-daemon-request-cancellation to 0.22 November 24, 2026 22:36
@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 4d90c49. The verdict and the full list are in the summary comment.

@thymikee

Copy link
Copy Markdown
Member Author

At 4d90c49, one problem needs a fix: the diagnostics deadline can leave an incomplete record behind. The earlier review of 5efa384 found no required fixes. The thread fixes made by this head are listed below.

In remote-request-diagnostics.ts, a second independent pass found that the 10-second deadline now only aborts the HTTP request and returns timeout. If the diagnostics GET has finished at the HTTP layer but a slow filesystem still holds the final write, the closed request emits no error on abort. The file sink can stay open and the file is never removed, so a caller that archives remote-diagnostics can pick up an incomplete record. A loopback Node check with a delayed writable stream showed the request closing before the sink finished, with no abort error in that interval. faf8224 and 5efa384 both settled and removed the output on the deadline. The rule: before timeout is reported, every download that has started must be failed, its sink destroyed and its partial file removed, even if the socket is already closed. A request admitted after the deadline must still send nothing. To validate, let the response end while the final write stays pending past the deadline, then show a timeout result and no file at the destination.

Not blocking: the cloud_origin_mismatch table row and the CLOUD_ACCESS_REASONS comment could also cover an API-key origin that differs from the configured base URL with no saved connection, not only a saved-connection pin; take it or leave it.

Of the open threads, artifact download inside dispatch still applies as an advisory maintainer note, and 2 lower-priority threads also still apply. These no longer apply and can be resolved. Contended operations: withdrawn by its author; contended hosted operations are refused. Ended lease lock: it now tries the lock without the 180-second wait. Lock test: the test now asserts that the blocking acquire is never called. Help text: it now names auth login or AGENT_DEVICE_CLOUD_API_KEY. Admission abort: an abort during admission now resolves as unreachable. Login flags: those flags scope the daemon-cloud exchange, and hosted access still honors --no-login. Origin mismatch: the hosted path now raises cloud_origin_mismatch. Connection profiles: their removal is required, and a cloud lease without a daemon URL is refused with guidance. Legacy teardown: the token deliberately goes only to the endpoint declared in the environment. Test title: it now says a second CLI invocation. Contention callback: hosted refusal throws on first contention, and per-poll behavior is documented. Commands doc: it now says the JSON output includes the rental deadline. Expired handoff: the abort listener is registered before handoff, and an expired request is not sent. ADR 0007: fixed; the API owns the rental deadline and the daemon keeps session lifetime. Token assertions: fixed; they now run outside the fake. Session expiry: fixed; expiry is checked before the origin. Ready message: fixed for hosted sessions. Startup admission: fixed; the wait is guarded with the caller signal. Unobserved result: fixed; the start result is observed. Diagnostics timeout: admission and request are now bounded; the pending-write case is the problem above. Disconnect key: fixed; the saved custom origin is used first. Null record: fixed; removal accepts it after the session is deleted. Usage text: fixed; it shows the --platform form. Android test name: fixed. Route assertions: fixed; all routes are asserted. Windows file mode: fixed; the assertion skips Windows. Vendor whitespace: fixed; the value is trimmed. Endpoint protocols: fixed with a typed pair. Fallback grammar: fixed. Viewer flag validation: fixed.

The only check not passing is Body rules, which was cancelled, not failed. It checks the PR description and metadata, so it is likely unrelated to the code change. The other 17 checks pass at this head.

Not verified here: tests were not run locally, and CI at this head was relied on for the new and changed tests. Code covered by the earlier review, such as the cloud connect release path and connection lock callers, was not traced again beyond the points touched since then.

Before merge, the diagnostics deadline needs the fix above and the Body rules check needs a re-run.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 44cd162, the diagnostics deadline problem from the earlier review of 4d90c49 is fixed, and no required code fix remains. On the deadline, each started download is now settled, and the report waits until its sink is closed and the partial file is removed. A request admitted after the deadline still sends nothing.

Of the open threads, artifact download inside dispatch still applies as an advisory maintainer note, and 2 lower-priority threads also still apply. The threads that the earlier review marked as fixed can be resolved, including diagnostics timeout, which now also covers started downloads. These do not apply and can be resolved too. Contended operations: withdrawn by its author; contended hosted operations are refused. Ended lease lock: it tries the lock without waiting. Lock test: the test asserts that the blocking acquire is never called. Help text: it names auth login or AGENT_DEVICE_CLOUD_API_KEY. Admission abort: the probe timeout covers the admission wait. Login flags: the neutral flags are deliberate for the login exchange, and --no-login is still honored. Origin mismatch: hosted access raises cloud_origin_mismatch. Connection profiles: their removal is required, and the refusal points to connect cloud. Legacy teardown: the token deliberately goes only to the endpoint declared in the environment. Test title: it says a second CLI invocation. Contention callback: per-poll behavior is documented, and hosted refusal throws on contention. Expired handoff: withdrawn by its author; admission time counts against the probe budget by design, and nothing is sent after expiry.

All CI jobs pass at this head except Proof, which was skipped. No conflicts are known.

Not verified here: tests were not run locally, and CI at this head was relied on. The new test stalls the response, so it does not exercise an ended response with a pending final write; the abort listener that covers that case was checked by reading the code. Code outside the changes since 4d90c49 was not reviewed again, and the live-device evidence is from aaad938.

Nothing in the changes since 4d90c49 holds up the merge. The three advisory threads that still apply are for the maintainer to weigh.

@thymikee thymikee left a comment

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.

On the artifact materialization advisory, this PR keeps the dispatch guard through the full materialization. A single materialization can make multiple authenticated requests, including fallback and retries. A guard around the initial check alone could let a later request leave after disconnect retires the session. A transfer can delay teardown on the same session. Shortening the lock safely requires admission at each authenticated request handoff.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 0d6af48, one code fix is still needed. Since the earlier review at 44cd162, an artifact transfer no longer holds the connection lock, so connect and disconnect can proceed while a body streams. The new per-download admission can now end too early.

A second independent pass found that admission can release before the queued GET headers are sent, which is likely a defect. A hosted screenshot, recorded action, or successful or failed batch receipt gets its artifact ID after the attachment closes the RPC connection, so the GET needs another connection. If that connection is delayed, request.end() can return with the headers still queued, and dispatch does not wait for the HTTP write inside the lock. A concurrent disconnect can then mark or release the lease, or the lease deadline can pass, before the GET sends the old bearer to the old endpoint. An in-memory Node check confirmed that end() returns while socket assignment is pending and that the Authorization header reaches the socket only later. At every artifact GET, the connection should be prepared before admission, ownership should be checked right before credentials are attached and the request is ended, and admission should be held until the write completes or fails. An unsent request should be destroyed if admission is refused or the lease deadline expires, and the response body and local publication should be awaited after release. Please add a test that delays socket assignment for the artifact GET while disconnect or lease expiry occurs. It should show that disconnect waits for the write, and that a refused or expired request never delivers Authorization to the server.

No high-priority review thread still applies, and 2 lower-priority threads still apply. These do not apply and can be resolved. Download inside dispatch: only the synchronous start of each GET is wrapped now. Contended operations: withdrawn by its author; contended disconnect is refused. Ended lease lock: it tries the lock without waiting. Lock test: the spy is gone, but the test would still time out on a blocking acquire. Help text: unchanged since it was checked to name auth login or AGENT_DEVICE_CLOUD_API_KEY. Admission abort: the probe timeout covers the admission wait. Login flags: hosted access now takes only noLogin, and the neutral login flags are deliberate. Origin mismatch: hosted access raises cloud_origin_mismatch. Connection profiles: their removal is the purpose of this change, and the refusal points to connect cloud. Legacy teardown: the credential deliberately goes only to the environment-declared endpoint that matches the saved one. Test title: it says a second CLI invocation. Contention callback: per-poll behavior is documented, and hosted refusal throws on first contention. Expired handoff: withdrawn by its author; admission time counts against the probe budget by design.

The Body rules check was cancelled, not failed. It checks the PR body and is likely unrelated to the code changes. The other 16 checks pass at this head. No conflicts are known.

Not verified here: tests were not run locally, and CI at this head was relied on, including the eager-closure check for the lazy import. The live hosted-device evidence is from aaad938, and no live run at this head exercised per-download admission. A new live run was not judged necessary for the admission change since 44cd162, because the endpoint, credential and headers are the same. In the failed-batch path, a refused admission now returns the localized error with its logPath; this was checked by reading the code and judged benign. Code outside the changes since 44cd162 was not reviewed again.

Before merge, the admission fix above is needed and Body rules needs a re-run. The lower-priority threads on request retriability and test brittleness are advisory, for the maintainer to weigh.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At 0a0baf4, the admission problem from the earlier review at 0d6af48 is fixed, but one likely defect needs a fix before merge: a refused artifact download can delete an existing output file.

Likely defect: a second independent pass found that, when admission rejects the GET, the download path destroys the unsent request, and fail() then runs cleanupOnError(). For ordinary file artifacts, this unlinks the existing destination (failure handling, reached from these callers). To hit it, run a hosted screenshot with --out set to a previous screenshot, then disconnect or let the lease expire after the RPC returns the artifact ID and before the GET is admitted. At 0d6af48, the rejection happened before the download failure handler. An in-memory check of the download source from both commits kept the prior file at 0d6af48 and removed it at 0a0baf4. The rule: until the admitted send starts, a failure must destroy the unsent request, reject with the admission error and leave the destination untouched, for every artifact download that registers file cleanup. Cleanup should stay for failures after that send starts. Please add a test where admission is refused for an existing destination, and show that the error is returned and the file content is unchanged.

No high-priority open thread still applies, and 2 lower-priority threads still apply. These threads do not apply and can be resolved: withdrawn by its author, a contended hosted disconnect is refused; ended-lease.ts tries the lock without waiting; the CLI help already names auth login and AGENT_DEVICE_CLOUD_API_KEY; the probe timeout covers the admission wait; hosted access takes only noLogin by design; admission covers only header setup, end() and finish, so the body streams outside the lock; hosted access raises cloud_origin_mismatch; removing connection profiles is the purpose of this PR, and the refusal points to connect cloud; requireLegacyTeardownCredential deliberately binds the credential to the env endpoint that matches the saved one; the title says a second CLI invocation; per-poll behavior is documented, and hosted refusal throws on first contention; withdrawn by its author, admission time counts against the probe budget by design.

All 17 checks pass at 0a0baf4.

Not verified here: no tests were run locally, and CI was relied on. No live hosted run exercised per-download admission at this commit; the endpoint, credential and headers are unchanged, so a new live run was not judged necessary. The timing of Node's ClientRequest finish event after the socket write callback was not probed at runtime, although the write-completion test supports it. The new test stands in for admission with a local flag, so the interaction with the real connection lock and a concurrent disconnect was checked only by reading the code. Code unchanged since 0d6af48 was not reviewed again.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of 9bb90e4

Since the review of 6b4c493: 0 new · 0 still open · 0 no longer raised

No open findings.

Not in the reviewers' prompt (8 files)
  • docs/adr/0007-remote-device-leases.md: left out as an asset or for its size; reviewers could still search it
  • src/__tests__/cli-cloud-legacy-admission.test.ts: left out as an asset or for its size; reviewers could still search it
  • src/__tests__/cli-cloud-session.test.ts: left out as an asset or for its size; reviewers could still search it
  • src/cli/connection/cloud-profile.ts: left out as an asset or for its size; reviewers could still search it
  • src/cli/connection/cloud-session-api.test.ts: left out as an asset or for its size; reviewers could still search it
  • test/wire-compat/ledger.json: left out as an asset or for its size; reviewers could still search it
  • website/docs/docs/commands.md: left out as an asset or for its size; reviewers could still search it
  • website/docs/docs/error-reasons.md: left out as an asset or for its size; reviewers could still search it

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

💬 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 9bb90e4, the code has no remaining problem that needs a fix before merge. The defect from the earlier review at 0a0baf4 is fixed: when admission refuses an artifact download, the failure path now returns that error without running destination cleanup, so an existing output file is kept. A new test covers this case and also expects that no request reaches the server.

No high-priority open thread still applies, and 2 lower-priority threads still apply. These threads do not apply and can be resolved: withdrawn by its author, a contended hosted disconnect is refused; ended-lease.ts tries the lock without waiting; the CLI help already names auth login and AGENT_DEVICE_CLOUD_API_KEY; the probe timeout covers the admission wait; hosted access takes only noLogin by design; admission covers only header setup, end() and finish, so the body streams outside the lock; hosted access raises cloud_origin_mismatch; removing connection profiles is the purpose of this PR, and the refusal points to connect cloud; requireLegacyTeardownCredential deliberately binds the credential to the env endpoint that matches the saved one; the title says a second CLI invocation; per-poll behavior is documented, and hosted refusal throws on first contention; withdrawn by its author, admission time counts against the probe budget by design.

The only check that is not passing is Body rules, which was cancelled and did not fail. It checks the PR body text and does not exercise any route this change touches, so it is likely unrelated to the code. No other check fails.

Not verified here: the new test was not run locally. That it fails at 0a0baf4 and passes now is inferred from the code, where every failure at 0a0baf4 ran the destination cleanup, which removes an ordinary output file.

Before merge, the cancelled Body rules check needs a re-run.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 25, 2026
@thymikee
thymikee merged commit 7f37a91 into 0.22 Nov 25, 2026
16 of 17 checks passed
@thymikee
thymikee deleted the feat/0.22-hosted-session-lifecycle branch November 25, 2026 15:03
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