Skip to content

Commit a661e43

Browse files
authored
feat(limrun): serve iOS alert get/wait/accept/dismiss from tree capture (#3699)
* feat(limrun): serve iOS alert get/wait/accept/dismiss from tree capture Limrun iOS direct sessions refused all four alert legs with unsupported-provider-mode even though the session's element-tree capture already shows the system alert and its touch seam can press its buttons. Issue #3349. Detect the alert from the capture: a system alert arrives as its own blank-label AXApplication root hosting text and pressable buttons, while the app's own UIAlertController rides the app's named root, so app-owned dialogs stay app UI. Accept and dismiss press exactly the button whose label states the asked-for choice and confirm the alert is gone; an ambiguous choice is reported, never guessed, and dismiss never authorizes tracking. The four legs bind through the same catalog and facts the Android tree-based legs already use. * fix(limrun): harden iOS alert detection against ambiguous sheets Review follow-up on the alert legs: a sheet must offer at least two pressable choices, launch-icon buttons never qualify, a capture whose host sheets disagree is refused instead of shadowing one with the other, and an action fires only when exactly one button states its choice. The legs' poll/confirm budgets now spend through an injected sleep seam so their tests drive the clock, a malformed timeout fails as a bounded default instead of an unbound loop, and the grant vocabulary covers the iOS variants (Allow Once / While Using App / All the Time) and Close App. User docs and CHANGELOG updated. * refactor(alert): drive every tree-based alert backend through one shared driver PR #3699 review: the Limrun iOS alert legs duplicated the Android tree-alert driver (poll, confirm, same-alert, response building) and its label vocabulary. Both backends now reach those steps through one backend-neutral driver, runTreeAlertAction in platform-android (exported via the mechanics facet provider-limrun already depends on), and classify button roles through one English vocabulary that lives in contracts/alert-contract with the alert budgets and typed reasons (contracts owns vocabulary only; the driver loop owns the AppError/timer mechanics R18 keeps out of contracts). Each backend supplies only its own seams: Android wraps its dump reader and keeps its platform-id roles, neutral/Back fallbacks, and tap/Back presses; Limrun supplies the blank-root process-exclusive host reader, the label-strict chooser, and client.tap. The confirm-on-ambiguous-capture and duplicate-label threads settle once in the shared code: the three-way alert|none|undecided observation gates confirmation in the driver, and selectUniqueAlertButtonByRole refuses duplicated roles at the shared choice boundary. The deadline order resolves to read-first: over a positive window both predecessor loops already observed before waiting. The alert-not-found and undecided refusals now carry the same typed details.reason and dispatched: 'no' on both backends. * refactor(alert): ride main's deadline primitive with no sleep seam origin/main migrated the Android alert loops to pollUntilSettled/Deadline and moved timing into fake timers at the test edge. The shared driver adopts the same shape: poll/confirm run on the deadline primitive, so the driver-owned sleep seam is dead weight and goes — Limrun's tests now drive the clock the way the migrated Android tests do. * test(limrun): pin the accept-once/second-get-none timeline and satisfy catch-name lint Adds the maintainer's live-validated sequence at the unit seam: accept taps exactly once, and a following get on the same seam reports no alert. Renames catch params to satisfy oxlint's catch-error-name (three findings the affected gate reported). * fix(alerts): resolve multi-grant sheets by a declared preference table The unique-role choice boundary refused exactly the sheets the fix is for: Android 11+'s permission_allow_foreground_only_button and permission_allow_one_time_button both classify accept, and iOS's 'Allow Once'/'Allow While Using App' sheet refused the same way. The shared vocabulary is now a per-role preference table: distinct grants resolve by declared rank (a lasting grant before a one-time grant), and the acting legs refuse only when the capture names no single physical button — the same label at two points, or vocabulary-free multiplicity. Android keeps its neutral-button/Back fallback, Limrun keeps none. * fix(alerts): type the undecided state and bound the seams each budget owns Three review findings on the shared tree-alert driver, plus the test that masked a polling loop: - alert get on a tree backend answered undecided exactly like absence (alert: null, message-only difference). The result now carries a typed status (visible/none/undecided) so clients switch on states, not text. - The budgets bounded only the poll sleeps: a capture or press that hung could outrun the leg. Each leg now builds a window (deadline clock plus the joined window/caller signal) that reaches the capture and press seams; the Android legs hand it to the snapshot capture and the adb input sends, which kill their child on abort. A capture that lands once its window closed is refused on a typed alert-window-expired reason and never consumed or pressed; a press cut off mid-flight says dispatched: unknown, one refused before dispatch says no. - Limrun's WebSocket transport exposes no abort on elementTree/tap (checked against the shipped typings), so the consumption rule is what keeps it honest, and the SDK gap is stated rather than papered over. - The awaitAlert first-capture test now asserts the capture count; its same-alert fixture had made it vacuous. * fix(alerts): close the window holes the review found and cap the budget The shared tree-alert driver consumed an answer from a poll that started after its window closed (the loop tests settled before remaining, and an expired-at-start probe rode unguarded), and its first probe paid the Android helper cold start inside the action budget, aborting the very read that leg was about to press on — the executed smoke failure. The first observation is now read-first, unarmed, consumed once, and arms the window behind it; a later probe starting past the deadline never captures at all, and the press rides the armed window. - contracts: a mix of ranked and unranked role candidates refuses instead of letting the one known label win (selectRankedAlertButton- ByRole); MAX_ALERT_WINDOW_MS names the timer ceiling the daemon refuses above (INVALID_ARGS) and the driver defaults above. - android: same-label dedup keys on the physical center, so nested nodes collapse and two distinct OKs reach the shared refusal; the input dispatch option type owns cancellation only, and the tap forward picks fields so allowFailure cannot reach the transport. - docs: alert-window-expired/none/undecided reasons stated exactly per phase, Limrun's non-abortable transport described as post-capture and pre-press guards with the hung-request limit named. Prose at the driver trims to invariants. * fix(alerts): scope alert captures to the warm helper and split the unconfirmed press The executed Android smoke failure at 5b1e1c1: the session's alert probes ran without the app-backed helper session scope, so each probe cold-started the snapshot helper inside the window that bounds it — the request log shows the post-press confirm capture aborted at 2.3s ("operation was aborted due to timeout") while the canary proves the dialog was in fact dismissed. Alert reads now carry the same helperSessionScope as every other app-backed read. The failure also proved the wording lied: with no confirm capture ever answering, "did not dismiss the visible alert"/"dialog is still visible" accused a dialog that was already gone. Only a re-read naming the same alert earns the still-visible failure; an unconfirmed press now says exactly that, on both the cut-off and the spent-budget exits, with a hint to run alert get before retrying. The same-alert stuck-alert failure keeps its message. Pinned: interactor scoping regression (fail-before against 5b1e1c1) and the three Limrun confirm-phase tests moved to the truthful split; the Android still-visible pin keeps its message via the same-alert path. * fix(alerts): let only the latest answered capture claim a visible dialog Two review findings on the confirm split, one batch: - The spent-budget exits of confirmTreeAlertDismissed omitted details.reason, while commands.md promises every post-press failure branches on alert-window-expired. Both unconfirmed and still-visible failures now carry the typed reason, pinned in the Android and Limrun suites. - The same-alert flag latched on the first matching capture, so a later undecided re-read still reported the dialog as currently visible. Each probe now replaces the verdict with its own observation: the still-visible failure requires the latest capture that answered to name the same alert, and a fresher undecided read exits as an unconfirmed press. A probe whose capture never answered is not a completed observation, so the thrown cutoff keeps saying only that the press went unconfirmed, at any earlier match. Pinned fail-before at the pre-fix alert.ts: same-alert then undecided to budget-end, and same-alert then a hung capture, both expect the unconfirmed message and the typed reason. The helper-scope comment is trimmed to the non-obvious constraint per AGENTS. * fix(alerts): a deadline-straddling confirm capture cannot erase an answered sighting The Coverage run at f584e8a (38924441176) failed the maintainer-owned provider-integration scenario 'Android alert accept fails when the dialog stays visible' — a suite the affected gate's related-test selection does not reach, so the local exact-head receipt never ran it. The driver, not the oracle, was wrong: f584's confirm catch downgraded every thrown cutoff to unconfirmed, discarding the captures that had answered before it. On CI the final confirm capture starts inside the 2s window and lands past it (the thrown path); locally it starts after the deadline (the sentinel path), which is why the same commit passed one and failed the other. The dialog had been re-named by answered reads; the error claimed the check never answered. The latest-completed-observation rule from review thread r4296070770 and from commands.md is: the latest capture that ANSWERED carries the claim. A hung probe is not an observation, so the cutoff now reports still-visible when an answered capture named the alert, and unconfirmed only when none did — the 2482e24 smoke case, with no answer at all. The undecided-overrules-match case is unchanged: undecided is an answered observation. Pin flipped to the CI timeline (fail-before at f584's catch); all 128 alert-family tests and the 197-test provider-integration project pass at this working tree. * test(alerts): pin the press cutoff's dispatched disclosure; review nits The independent review of f584e8a returned merge-ready with three follow-up-scale findings, batched here: - The documented `dispatched: 'unknown'` press-cutoff failure had no test. Pinned in the Android suite with the real transport shape: the adb fake hangs the tap until the 2s action window closes and dies with the signal; the failure must disclose unknown, never 'no'. Mutation-checked: flipping the disclosure to 'no' fails the pin. - The `[timeout]` positional is honored by `alert wait` only — the Apple acting legs pass fixed runner budgets and the tree legs run their own lookup/confirm windows; commands.md now says the argument is wait-only per backend instead of leaving the silence to surprise callers. - `void device;` in limrunAlertOperationFacts follows the `_device` convention; the two byte-identical visible-after-press exits collapse into one helper, keeping the two hints that genuinely differ (latest read hung vs budget ended unresolved). No behavior change for any message, reason, or tap. * fix(alerts): let started probes finish, rank Android grants by id The maintainer review at be48a28 named two defects and a design simplification; this applies all three. Budget rule (whole): the alert budget now bounds only how long a leg polls. pollUntilSettled awaits every probe it starts, the deadline ends the loop, and only the caller's cancellation stops a capture or press in flight. A quiet screen answers alert-not-found with dispatched:no on every backend, never a reason that depends on which capture crossed the deadline; the late positive that used to be refused is consumed and pressed, per the rule the maintainer asked for and this supersedes the earlier late-answer-refusal contract. Grant ranking: the shared choice boundary takes a backend rank first and the label vocabulary only where the backend declares nothing. Android declares the permissioncontroller grant ids (foreground-only, always, one-time), so a Spanish Android 11+ sheet and the Android 10 foreground copy resolve to the lasting grant instead of refusing; equal ranks and candidates no rank reaches keep refusing. Design: the driver moved to capture-kit/alert-tree-driver (Limrun no longer depends on platform-android), treeAlertWindow/arm/start, the delegating clock, the window-closed sentinel, lastCaptureNamesAlert, and the exception paths are gone; net production diff vs be48a28 is -161 lines. Docs and CHANGELOG state the chosen behavior. * fix(alerts): keep the mechanics façade lazy, honor cancel at every post-press seam, rank only on one scale Follow-up to the review at 5cfe029: - platform-android: load the shared tree-alert driver behind the alert entry's function-scoped import (types stay static), so mechanics.ts keeps its merge-base eager closure (177->176, the gate's owning-edge rule). - capture-kit driver: a caller cancel is typed dispatched:'unknown' from the press onward even when a non-abortable transport RESOLVES after the cancel or the cancel lands in the confirm window, and a cancel that rode a straddling lookup probe refuses cleanly (dispatched:'no', no press). - contracts: selectRankedAlertButtonByRole refuses pairs mixing backend id-ranks with label-table positions — different scales are not comparable; same-source conflicts still let the owning backend win. - tests: deterministic started-gated cancel pins (no unreachable mock branches), Limrun no-abort capability pins, backend-rank-override and mixed-scale pins at the contract seam, faithful vendor-id fixture. - docs: correct the CHANGELOG/commands/driver claims about Limrun cancellation (started calls run to their answer; the leg ends at the next seam cancel can reach), scope the quiet-screen guarantee to accept/dismiss, and limit the details.reason promise to driver refusals; fix the stale platform-android module comment. * docs(alerts): state the real lazy-load constraint, cancel truth, and confirm-never-started pin - platform-android/alert.ts: drop the false comparison to how the Limrun provider loads its own alert file; the comment now states only the real constraint — a static driver import would grow the mechanics facade past its merge-base eager-closure budget (ADR-0019). - commands.md: replace 'the next seam cancellation can reach' with what the reader observes: a Limrun request already sent is not stoppable; cancellation lands once that request answers; restarting the instance session clears a stall. Human-rule facts unchanged. - alert.test.ts: the resolves-after-cancel pin also asserts the leg ended before any confirm read started (elementTree exactly once). * fix(alerts): type the transport-death cancel as pre-press, and make the stall docs exhaustive R6-review P3 follow-ups (report /tmp/3349-r6-review-report-3e1e.md): - capture-kit driver: a capture whose transport died with the caller's cancellation exits through observeTreeAlert, which is always pre-press (acting legs never press before the lookup returns) — it now carries the clean dispatched:'no' like the other pre-press exit instead of omitting the key; both backend pins assert it. Pins fail without the key. - capture-kit driver: correct the seam comment's attribution — the caller learns of its cancellation from its own client transport; the daemon's answer lands once the leg settles on the started probe's answer. - commands.md: the Limrun stall sentence enumerates the SDK's own ~30 s request timeout (verified against @limrun/[email protected] sendRequest) as a route the unanswered request resolves on, instead of reading exhaustive. * docs(capture-kit): scope the transport-death cancel comment to the routes that end here R7 P3 / inline r4300817984: 'always a pre-press exit' overstated the catch's reach — confirmTreeAlertGone polls through the same observeTreeAlert, so a cancel mid-confirm-probe reaches it post-press (harmless: the actOnTreeAlert press/confirm catch re-types it to dispatched:'unknown', which owns that invariant). The comment now states where each typed answer is owned instead of asserting a false reachability fact. No behavior change. * fix(alerts): state each permissioncontroller grant's role and rank in one table The maintainer's rule for the Android media sheet: every id the Android classifier maps to a role must carry a rank in the same declaration, so an accept-by-id with no rank cannot exist. The partial-media sheet's permission_allow_all_button and permission_allow_selected_button both classified accept by id with no backend rank, and on the English sheet the mixed-source pair refused where main pressed "Allow all". - PERMISSION_GRANT_ID_SLOTS is now the one declaration: one slot per rank, role and rank read together. Full access, then foreground-only, then plain/always, then the picker-limited selection, then one-time; the deny ids rank on the same scale (plain deny before its don't-ask-again variants). An unknown controller id keeps the prefix-only role with no rank, so it can only ever refuse. - Tests pin the AOSP media-sheet ids at the choice boundary and at the tap seam, a cohesion sweep over every declared id, and the two-deny scale. - commands.md names the media-sheet order; the limrun test's stale platform-android driver comment and the driver header's narration are corrected to the invariants. * fix(alerts): refuse every undeclared permission grant instead of pressing it The maintainer's rule admits no exception: an id the Android classifier maps to a role must carry its rank in the same declaration. A grant-shaped id outside PERMISSION_GRANT_ID_SLOTS no longer earns a role from its prefix, so no path can accept-by-id without a rank: not the single candidate at the shared boundary, not the single-button or neutral fallbacks (the sheet-level refusal stops both actions), and not the label vocabulary. An undeclared grant keeps the sheet represented and makes it unactionable; dismiss answers with Back, the cancel that grants nothing.
1 parent 56618ac commit a661e43

29 files changed

Lines changed: 3539 additions & 244 deletions

‎packages/capture-kit/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
"types": "./src/snapshot/android-replacement-surface-occlusion.ts",
1919
"default": "./src/snapshot/android-replacement-surface-occlusion.ts"
2020
},
21+
"./alert-tree-driver": {
22+
"types": "./src/alert-tree-driver.ts",
23+
"default": "./src/alert-tree-driver.ts"
24+
},
2125
"./app-log-durable-resource": {
2226
"types": "./src/capture-admission/app-log-durable-resource.ts",
2327
"default": "./src/capture-admission/app-log-durable-resource.ts"

‎packages/capture-kit/src/alert-tree-driver.ts‎

Lines changed: 443 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { classifyAlertButtonRole, selectRankedAlertButtonByRole } from './alert-contract.ts';
3+
4+
type Button = { label: string; role: ReturnType<typeof classifyAlertButtonRole> };
5+
const button = (label: string): Button => ({ label, role: classifyAlertButtonRole(label) });
6+
7+
describe('selectRankedAlertButtonByRole', () => {
8+
it('resolves distinct grants by the declared preference order', () => {
9+
const buttons = [button("Don't Allow"), button('Allow Once'), button('Allow While Using App')];
10+
expect(selectRankedAlertButtonByRole(buttons, 'accept')?.label).toBe('Allow While Using App');
11+
expect(selectRankedAlertButtonByRole(buttons, 'dismiss')?.label).toBe("Don't Allow");
12+
});
13+
14+
it('resolves the Android grant pair by the same table', () => {
15+
const buttons = [button('While using the app'), button('Only this time'), button('Deny')];
16+
expect(selectRankedAlertButtonByRole(buttons, 'accept')?.label).toBe('While using the app');
17+
});
18+
19+
it('refuses on equal-rank duplicates: the capture names no single physical button', () => {
20+
const buttons = [button('OK'), button('OK'), button('Cancel')];
21+
expect(selectRankedAlertButtonByRole(buttons, 'accept')).toBeNull();
22+
});
23+
24+
it('refuses when multiple candidates share a role the vocabulary cannot rank', () => {
25+
// Roles can arrive from a platform id classifier; labels outside the vocabulary then tie.
26+
const buttons: Button[] = [
27+
{ label: 'While on the go', role: 'accept' },
28+
{ label: 'Just this run', role: 'accept' },
29+
];
30+
expect(selectRankedAlertButtonByRole(buttons, 'accept')).toBeNull();
31+
});
32+
33+
it('refuses a mix of ranked and unranked candidates rather than preferring the known label', () => {
34+
// The unranked one's role came from a platform id classifier, so it is a real grant the
35+
// table cannot order. Letting the one known English label win would press an arbitrary
36+
// grant of an unordered pair.
37+
const buttons: Button[] = [
38+
{ label: 'OK', role: 'accept' },
39+
{ label: 'Unrecognized grant', role: 'accept' },
40+
];
41+
expect(selectRankedAlertButtonByRole(buttons, 'accept')).toBeNull();
42+
});
43+
44+
it('keeps the declared order over mixed English variants of distinct grants', () => {
45+
// The closest positive: both candidates are ranked, so this is a preference, not ambiguity.
46+
const buttons = [button('Allow Once'), button('Allow')];
47+
expect(selectRankedAlertButtonByRole(buttons, 'accept')?.label).toBe('Allow');
48+
});
49+
50+
it('returns null when no button carries the role', () => {
51+
expect(selectRankedAlertButtonByRole([button('Settings')], 'accept')).toBeNull();
52+
});
53+
54+
it('orders candidates the label table cannot read by the backend rank it supplies', () => {
55+
// The localized-sheet shape at the shared boundary: both labels are outside the vocabulary,
56+
// and the backend's own fact (here, a grant-id rank) is the only order the pair has. The
57+
// boundary must use it instead of refusing a pair the owning backend can order.
58+
type RankedButton = Button & { id: string };
59+
const idRanks: Record<string, number> = { 'id/fg': 0, 'id/once': 1 };
60+
const rankById = (button: RankedButton): number | null => idRanks[button.id] ?? null;
61+
const buttons: RankedButton[] = [
62+
{ label: 'Solo esta vez', role: 'accept', id: 'id/once' },
63+
{ label: 'Mientras la app est\u00e1 en uso', role: 'accept', id: 'id/fg' },
64+
];
65+
expect(selectRankedAlertButtonByRole(buttons, 'accept', rankById)?.id).toBe('id/fg');
66+
});
67+
68+
it('still refuses when the backend rank reaches neither of a multi-candidate pair', () => {
69+
// The closest negative: the ranker exists but names nothing for these buttons, so the
70+
// label fallback leaves an unranked candidate and the refusal stands.
71+
type RankedButton = Button & { id: string };
72+
const buttons: RankedButton[] = [
73+
{ label: 'Mientras la app est\u00e1 en uso', role: 'accept', id: 'vendor/a' },
74+
{ label: 'Solo esta vez', role: 'accept', id: 'vendor/b' },
75+
];
76+
expect(selectRankedAlertButtonByRole(buttons, 'accept', () => null)).toBeNull();
77+
});
78+
79+
it('lets the backend rank decide a pair the label table would order the other way', () => {
80+
// Both sources know these labels, and they conflict: the label table prefers
81+
// "While using the app" (position 1) over "Only this time" (position 15), while the
82+
// backend ranks them 2 and 0. The owning backend's fact is the authority — the label
83+
// table ranks only where the backend declares nothing.
84+
type RankedButton = Button & { id: string };
85+
const idRanks: Record<string, number> = { 'id/once': 0, 'id/fg': 2 };
86+
const rankById = (button: RankedButton): number | null => idRanks[button.id] ?? null;
87+
const buttons: RankedButton[] = [
88+
{ label: 'While using the app', role: 'accept', id: 'id/fg' },
89+
{ label: 'Only this time', role: 'accept', id: 'id/once' },
90+
];
91+
expect(selectRankedAlertButtonByRole(buttons, 'accept', rankById)?.id).toBe('id/once');
92+
});
93+
94+
it('refuses a pair whose ranks come from different sources rather than comparing scales', () => {
95+
// A backend id-rank and a label-table position are numbers on unrelated scales: id-rank 2
96+
// (a one-time grant) says nothing against label position 3 ("Always allow"). The pair is
97+
// not orderable by any table, so it is refused, never resolved by whichever number is
98+
// smaller.
99+
type RankedButton = Button & { id: string };
100+
const rankById = (button: RankedButton): number | null => (button.id === 'id/once' ? 2 : null);
101+
const buttons: RankedButton[] = [
102+
{ label: 'Only this time', role: 'accept', id: 'id/once' },
103+
{ label: 'Always allow', role: 'accept', id: 'no/rank' },
104+
];
105+
expect(selectRankedAlertButtonByRole(buttons, 'accept', rankById)).toBeNull();
106+
});
107+
});

‎packages/contracts/src/alert-contract.ts‎

Lines changed: 159 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,23 @@ export const ALERT_POLL_INTERVAL_MS = 300;
22
export const DEFAULT_ALERT_TIMEOUT_MS = 10_000;
33
export const ALERT_ACTION_RETRY_MS = 2_000;
44

5+
/**
6+
* The largest alert budget the legs accept. The window signal rides `AbortSignal.timeout`, whose
7+
* Node ceiling is 2^31-1 ms: larger values are rejected outright there, and its underlying timer
8+
* overflows to a 1 ms firing when merely exceeded. The daemon refuses a larger `alert wait`
9+
* budget as `INVALID_ARGS`, and a tree driver reads one as the bounded default — never a
10+
* silently shortened window.
11+
*/
12+
export const MAX_ALERT_WINDOW_MS = 2_147_483_647;
13+
514
/**
615
* The one alert failure the family retries on: the backend looked and there was no alert *yet*.
716
* Both Apple backends state it in typed form — the XCTest runner as this `ErrorPayload.code`
817
* (surfacing as `details.runnerErrorCode`, like `RUNNER_BUSY`, without changing the wire error
9-
* code), the macOS helper as `details.reason`. Retry and the fallback hint key on these, never on
10-
* the message text: a transport, runner or helper failure must never read as an absent alert.
18+
* code), the macOS helper as details.reason — and so do the tree-based acting legs (Android and
19+
* Limrun iOS, through the shared driver), as this `details.reason` paired with `dispatched:
20+
* 'no'`. Retry and the fallback hint key on these, never on the message text: a transport,
21+
* runner or helper failure must never read as an absent alert.
1122
*/
1223
export const ALERT_NOT_FOUND_RUNNER_CODE = 'ALERT_NOT_FOUND';
1324
export const ALERT_NOT_FOUND_REASON = 'alert-not-found';
@@ -20,6 +31,152 @@ export const ALERT_NOT_FOUND_REASON = 'alert-not-found';
2031
*/
2132
export const ALERT_BUTTON_NOT_FOUND_RUNNER_CODE = 'ALERT_BUTTON_NOT_FOUND';
2233

34+
/**
35+
* The acting leg's confirm budget ran out after a press landed without settling whether the
36+
* alert is gone: the dialog was seen standing again after the press ("did not dismiss"), or no
37+
* post-press read ever resolved to an answer ("could not be confirmed"). Typed so a caller can
38+
* tell "a press went out and the screen never proved it worked" from absence or an
39+
* unresolvable capture. The lookup never answers with it — a budget ends its loop, it does not
40+
* cancel a started capture — so a quiet screen is always `alert-not-found`.
41+
*/
42+
export const ALERT_WINDOW_EXPIRED_REASON = 'alert-window-expired';
43+
44+
/** What an `alert get` capture resolved to, typed so clients switch on states, not messages. */
45+
export type AlertStatusKind = 'visible' | 'none' | 'undecided';
46+
47+
export type AlertButtonRole = 'accept' | 'dismiss' | 'neutral';
48+
49+
/**
50+
* What one capture from a tree-based alert backend says about alerts. `none` states absence;
51+
* `undecided` states the capture is alert-shaped yet unresolvable (a degraded or shared root,
52+
* competing sheets) and proves nothing — confirming a dismissal may accept `none`, never
53+
* `undecided`. Backends whose capture cannot reach `undecided` report a quiet capture as `none`.
54+
*/
55+
export type AlertCapture<TCandidate> =
56+
| { kind: 'alert'; candidate: TCandidate }
57+
| { kind: 'none' }
58+
| { kind: 'undecided' };
59+
60+
/**
61+
* The one alert button label vocabulary every tree-based alert backend classifies with,
62+
* declared as a per-role preference table: each entry names one English label (regex only for
63+
* spelling variants of the *same* label), earlier entries outrank later ones, so a sheet
64+
* offering several grants resolves by declared preference ("while using the app" over "only
65+
* this time") instead of tree order. The table ranks labels, not buttons it cannot read: a
66+
* backend owning a fact no label carries — Android's permission-grant ids — supplies its own
67+
* rank per candidate, and the label table ranks only where the backend declares nothing.
68+
* Buttons neither the vocabulary nor a backend rank reaches stay neutral, and acting legs
69+
* refuse on the button-undecided reason rather than guessing at a translation.
70+
*/
71+
const ACCEPT_LABEL_PREFERENCES: readonly RegExp[] = [
72+
/^allow while using (?:the )?app$/i,
73+
/^while using the app$/i,
74+
/^allow all$/i,
75+
/^always allow$/i,
76+
/^allow all the time$/i,
77+
/^allow notifications$/i,
78+
/^allow$/i,
79+
/^ok$/i,
80+
/^yes$/i,
81+
/^continue$/i,
82+
/^save$/i,
83+
/^confirm$/i,
84+
/^turn on$/i,
85+
/^open settings$/i,
86+
// One-time grants last: a sheet offering a lasting grant should not spend the tap here.
87+
/^allow once$/i,
88+
/^only this time$/i,
89+
];
90+
// `don.?t allow` covers the straight, missing, and typographic apostrophe in one alternate.
91+
const DISMISS_LABEL_PREFERENCES: readonly RegExp[] = [
92+
/^cancel$/i,
93+
/^deny$/i,
94+
/^don.?t allow$/i,
95+
/^not now$/i,
96+
/^no$/i,
97+
/^dismiss$/i,
98+
/^close$/i,
99+
/^close app$/i,
100+
/^later$/i,
101+
/^skip$/i,
102+
/^ask app not to track$/i,
103+
];
104+
105+
const LABEL_PREFERENCES: Record<'accept' | 'dismiss', readonly RegExp[]> = {
106+
accept: ACCEPT_LABEL_PREFERENCES,
107+
dismiss: DISMISS_LABEL_PREFERENCES,
108+
};
109+
110+
/** One button's action role under the shared vocabulary; anything unnamed is neutral. */
111+
export function classifyAlertButtonRole(label: string): AlertButtonRole {
112+
const trimmed = label.trim();
113+
if (ACCEPT_LABEL_PREFERENCES.some((pattern) => pattern.test(trimmed))) return 'accept';
114+
if (DISMISS_LABEL_PREFERENCES.some((pattern) => pattern.test(trimmed))) return 'dismiss';
115+
return 'neutral';
116+
}
117+
118+
/**
119+
* A role-named button's place in the declared preference table, or null when its label carries
120+
* no vocabulary entry (localized grants, unnamed choices).
121+
*/
122+
function alertButtonPreferenceRank(label: string, role: 'accept' | 'dismiss'): number | null {
123+
const index = LABEL_PREFERENCES[role].findIndex((pattern) => pattern.test(label.trim()));
124+
return index === -1 ? null : index;
125+
}
126+
127+
/**
128+
* The one choice boundary for a shared choice: pick the action's role candidates by declared
129+
* preference. Each candidate's rank comes from the owning backend first — a backend may own
130+
* facts a label cannot carry, like Android's permission-grant ids — and from the label
131+
* vocabulary only where the backend declares nothing. A single candidate wins outright.
132+
* Several resolve only when every one of them carries a rank AND all ranks come from the same
133+
* source: backend ids and label positions are different scales, and an id-rank 2 (a one-time
134+
* grant) says nothing against a label-position 3 ("Always allow"). A mix of sources cannot be
135+
* ordered by any table, so it names no single physical button and is refused rather than
136+
* resolved by tree order or by one side's number happening to be smaller.
137+
*/
138+
export function selectRankedAlertButtonByRole<
139+
TButton extends Readonly<{ role: AlertButtonRole; label: string }>,
140+
>(
141+
buttons: readonly TButton[],
142+
role: 'accept' | 'dismiss',
143+
backendRank?: (button: TButton) => number | null,
144+
): TButton | null {
145+
const matching = buttons.filter((button) => button.role === role);
146+
if (matching.length === 1) return matching[0] ?? null;
147+
if (matching.length === 0) return null;
148+
const ranked = matching.map((button) => {
149+
const fromBackend = backendRank?.(button) ?? null;
150+
return {
151+
button,
152+
rank: fromBackend ?? alertButtonPreferenceRank(button.label, role),
153+
source: fromBackend !== null ? ('backend' as const) : ('label' as const),
154+
};
155+
});
156+
if (ranked.some((entry) => entry.rank === null)) return null;
157+
if (ranked.some((entry) => entry.source !== ranked[0]?.source)) return null;
158+
ranked.sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0));
159+
const [first, second] = ranked;
160+
if (!first || (second && second.rank === first.rank)) return null;
161+
return first.button;
162+
}
163+
164+
/**
165+
* The reason a tree-based acting leg (`alert accept|dismiss`) refuses after seeing an alert: the
166+
* visible buttons name no single choice for the asked-for action. Callers branch on
167+
* `error.details.reason` instead of the prose; `dispatched: 'no'` states the refusal ran before
168+
* any press.
169+
*/
170+
export const ALERT_BUTTON_UNDECIDED_REASON = 'alert_button_undecided';
171+
172+
/**
173+
* The reason a tree-based acting leg refuses before it has a candidate at all: the capture was
174+
* alert-shaped but unresolvable (degraded buttons, competing sheets, an unverifiable owner).
175+
* This is not absence — reporting `alert-not-found` over it would state more than the capture
176+
* supports — and confirming a dismissal must never accept such a capture as proof of absence.
177+
*/
178+
export const ALERT_CAPTURE_UNDECIDED_REASON = 'alert_capture_undecided';
179+
23180
export const ALERT_ACTIONS = ['get', 'accept', 'dismiss', 'wait'] as const;
24181
export type AlertAction = (typeof ALERT_ACTIONS)[number];
25182

‎packages/contracts/src/alert-runtime.test.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ test('each local leg forwards the window and the session target to its own owner
5858
timeoutMs: 37,
5959
appBundleId: 'com.example.app',
6060
surface: 'app',
61+
// The request's cancellation rides along: owners whose transport cannot abort a call (the
62+
// Limrun tree legs) still refuse to consume a capture once the request is canceled.
63+
signal,
6164
};
6265
expect(legs.readAlert).toHaveBeenCalledWith(expectedOptions);
6366
expect(legs.awaitAlert).toHaveBeenCalledWith(expectedOptions);
@@ -76,12 +79,13 @@ test('an absent target field never reaches the owner as an explicit undefined',
7679
const readAlert = vi.fn(async (_options?: AlertInteractorOptions) => ({}));
7780
const resolveInteractor = async () => ({ readAlert }) as unknown as Interactor;
7881
const source = localInteractorSource({ device, resolveInteractor });
79-
const operations = bindAlertLeg('readAlert', new AbortController().signal, source);
82+
const signal = new AbortController().signal;
83+
const operations = bindAlertLeg('readAlert', signal, source);
8084

8185
await operations.readAlert({ surface: 'frontmost-app' });
8286

83-
expect(readAlert).toHaveBeenCalledWith({ surface: 'frontmost-app' });
84-
expect(Object.keys(readAlert.mock.calls[0]?.[0] ?? {})).toEqual(['surface']);
87+
expect(readAlert).toHaveBeenCalledWith({ surface: 'frontmost-app', signal });
88+
expect(Object.keys(readAlert.mock.calls[0]?.[0] ?? {})).toEqual(['surface', 'signal']);
8589
});
8690

8791
// Facts admitted the leg, so an interactor without it is an ownership bug the caller must see

‎packages/contracts/src/alert-runtime.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,11 +94,15 @@ async function resolveAlertInteractor(
9494
});
9595
}
9696

97-
function alertInteractorOptions(input: AlertRuntimeInput): AlertInteractorOptions {
97+
function alertInteractorOptions(
98+
input: AlertRuntimeInput,
99+
signal: AbortSignal | undefined,
100+
): AlertInteractorOptions {
98101
return {
99102
...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }),
100103
...(input.appBundleId === undefined ? {} : { appBundleId: input.appBundleId }),
101104
...(input.surface === undefined ? {} : { surface: input.surface }),
105+
...(signal ? { signal } : {}),
102106
};
103107
}
104108

@@ -124,7 +128,7 @@ export function bindAlertLeg<Leg extends AlertLeg>(
124128
// held at its merge-base size (`eager-closure-budgets`); a static edge would grow it.
125129
const { requireInteractorMethod } = await import('./interactor-operation-binding.ts');
126130
const method = requireInteractorMethod(interactor[leg], ALERT_LEG_LABELS[leg]);
127-
return await method.call(interactor, alertInteractorOptions(input));
131+
return await method.call(interactor, alertInteractorOptions(input, signal));
128132
},
129133
}) as Readonly<Record<Leg, (input: AlertRuntimeInput) => Promise<Record<string, unknown>>>>;
130134
}

‎packages/contracts/src/interactor-types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -474,6 +474,8 @@ export type Interactor = {
474474
*/
475475
export type AlertInteractorOptions = {
476476
timeoutMs?: number;
477+
/** The daemon request's cancellation; owners whose transport can abort thread it into the legs. */
478+
signal?: AbortSignal;
477479
appBundleId?: string;
478480
surface?: SessionSurface;
479481
};

‎packages/daemon/src/execution/handlers/__tests__/snapshot-alert.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,34 @@ for (const action of ['accept', 'dismiss']) {
140140
expect(successor?.actions).toEqual([]);
141141
});
142142
}
143+
144+
test('alert wait forwards its timeout budget to the runtime leg', async () => {
145+
const sessionStore = makeSessionStore();
146+
const sessionName = 'ios-sim';
147+
sessionStore.publish(sessionName, makeSession(sessionName));
148+
149+
await handleSnapshotCommands(sessionName, sessionStore, ['wait', '1500']);
150+
151+
// The ceiling test below proves the refusal; this proves a legal budget crosses the runtime
152+
// seam whole. (The Apple runner leg reads the state as `get` and waits on its own deadline.)
153+
expect(mockRunnerCommand.mock.calls[0]?.[1]).toMatchObject({
154+
command: 'alert',
155+
timeoutMs: 1_500,
156+
});
157+
});
158+
159+
test('alert wait refuses a budget past the window ceiling instead of arming a misfired timer', async () => {
160+
// Above 2^31-1 ms Node's timer overflows: `AbortSignal.timeout` throws outright and a bare
161+
// setTimeout fires after 1 ms. The refusal must be the typed argument error, never either.
162+
const sessionStore = makeSessionStore();
163+
const sessionName = 'ios-sim';
164+
sessionStore.publish(sessionName, makeSession(sessionName));
165+
166+
await expect(
167+
handleSnapshotCommands(sessionName, sessionStore, ['wait', '4294967296']),
168+
).rejects.toThrow(/exceeds the maximum/);
169+
await expect(
170+
handleSnapshotCommands(sessionName, sessionStore, ['wait', '2147483648']),
171+
).rejects.toThrow(/exceeds the maximum/);
172+
expect(mockRunnerCommand).not.toHaveBeenCalled();
173+
});

0 commit comments

Comments
 (0)