diff --git a/apps/agent/src/plugins/control.ts b/apps/agent/src/plugins/control.ts index 82843d842d..61681e67bc 100644 --- a/apps/agent/src/plugins/control.ts +++ b/apps/agent/src/plugins/control.ts @@ -1,11 +1,50 @@ // spec/agent/index.md, "Story: Run Alpha's agent on the phone"; spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease"; spec/app/control/index.md, "Story: Enforce formal safety guarantees over external app control" import { turnNotes } from "@elizaos/agent-host"; import { Effect, Option } from "effect"; +import { + CONTROL_CONTEXT_MAX_CHARS, + type DiscoveredAppFunction, + type ExecutionMode, + type ObservedUiNode, + type TakeoverReason, + classifyActionTier, + detectTakeoverFromObservation, + formatCompactControlContext, + runPhoneUseLoop, + selectPreferredActionTier, +} from "./control/phone-use.ts"; +import { + type ProfileReceipt, + type ProfileSettingKey, + ReversibleProfileStore, + type ReversibleProfileSpec, + builtInProfileSpec, + isProfileSettingKey, +} from "./control/profiles.ts"; import { type AgentAction, type AgentProvider, type AgentRoute, asRecord, readBoolean, readNumber, readRawString, readString, } from "./types.ts"; +export { + CONTROL_CONTEXT_MAX_CHARS, + ReversibleProfileStore, + builtInProfileSpec, + classifyActionTier, + detectTakeoverFromObservation, + formatCompactControlContext, + runPhoneUseLoop, + selectPreferredActionTier, +}; +export type { + DiscoveredAppFunction, + ExecutionMode, + ObservedUiNode, + ProfileReceipt, + ProfileSettingKey, + TakeoverReason, +}; + /** Action name exposed to the model for bounded external app control. */ export const CONTROL_ACTION_NAME = "DEVICE_CONTROL"; @@ -98,12 +137,12 @@ export const BLOCKED_ACTIVITY_SUBSTRINGS: ReadonlyMap ["com.google.android.gms", ["Auth", "Account", "Credential", "Wallet", "TapAndPay", "Fido", "Security", "Lockscreen"]], ]); -/** Discriminated union of the twelve closed external-app control operations. */ +/** Discriminated union of external-app control, virtual display, and reversible OS profile operations. */ export type ControlOpPayload = - | { readonly type: "app_launch_package"; readonly packageName: string } + | { readonly type: "app_launch_package"; readonly packageName: string; readonly displayId?: number; readonly activityName?: string } | { readonly type: "app_open_url"; readonly url: string; readonly packageName?: string } | { readonly type: "ui_read_tree"; readonly includeNonInteractive?: boolean; readonly maxNodes?: number } - | { readonly type: "ui_capture_screen"; readonly maxWidth?: number; readonly quality?: number } + | { readonly type: "ui_capture_screen"; readonly maxWidth?: number; readonly quality?: number; readonly displayId?: number } | { readonly type: "ui_click"; readonly snapshotId: number; @@ -112,6 +151,7 @@ export type ControlOpPayload = readonly x?: number; readonly y?: number; readonly longClick?: boolean; + readonly displayId?: number; } | { readonly type: "ui_set_text"; @@ -134,6 +174,7 @@ export type ControlOpPayload = readonly snapshotId: number; readonly expectedPackage: string; readonly keyCode: ControlKeyCode; + readonly displayId?: number; } | { readonly type: "ui_gesture"; @@ -159,22 +200,35 @@ export type ControlOpPayload = readonly expectedPackage: string; readonly functionId: string; readonly parameters: Readonly>; - }; - -/** Normalized UI node reported by the native accessibility service. */ -export interface ObservedUiNode { - readonly nodeId: string; - readonly role: string; - readonly resourceId?: string; - readonly text?: string; - readonly contentDescription?: string; - readonly hintText?: string; - readonly bounds: { readonly left: number; readonly top: number; readonly right: number; readonly bottom: number }; - readonly clickable: boolean; - readonly editable: boolean; - readonly scrollable: boolean; - readonly sensitive: boolean; -} + } + | { + readonly type: "virtual_display_create"; + readonly packageName: string; + readonly activityName?: string; + readonly width?: number; + readonly height?: number; + readonly densityDpi?: number; + readonly allowForegroundFallback?: boolean; + } + | { readonly type: "virtual_display_release"; readonly displayId?: number } + | { + readonly type: "virtual_display_launch"; + readonly displayId: number; + readonly packageName: string; + readonly activityName?: string; + } + | { + readonly type: "profile_preview"; + readonly profileId: string; + readonly settings?: Readonly>>; + } + | { + readonly type: "profile_apply"; + readonly profileId: string; + readonly durationMs?: number; + readonly settings?: Readonly>>; + } + | { readonly type: "profile_restore"; readonly receiptId: string }; /** Foreground snapshot held by the control coordinator. */ export interface ForegroundObservation { @@ -192,7 +246,7 @@ export interface ForegroundObservation { readonly observedAtMs: number; } -/** Active or historical owner-approved control lease. */ +/** Active or historical owner-approved control lease (foreground or trusted VirtualDisplay). */ export interface ActiveControlLease { readonly leaseId: number; readonly packageName: string; @@ -200,6 +254,8 @@ export interface ActiveControlLease { readonly usedOps: number; readonly expiresAtMs: number; readonly status: LeaseStatus; + readonly mode: ExecutionMode; + readonly displayId: number; } /** Single in-flight external control operation awaiting native execution. */ @@ -241,15 +297,24 @@ export interface ControlCoordinatorState { readonly pending: PendingControlOp | null; readonly lastResult: ExecutionOutcome; readonly killed: boolean; + readonly needsReconcile: boolean; + readonly takeover: TakeoverReason; + readonly lastReadbackSnapId: number; + readonly appFunctions: readonly DiscoveredAppFunction[]; + readonly activeProfiles: readonly ProfileReceipt[]; readonly recentReceipts: readonly ControlReceiptRecord[]; } const PACKAGE_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*(\.[a-zA-Z][a-zA-Z0-9_]*)+$/; +const ACTIVITY_PATTERN = /^[a-zA-Z0-9_.$]{1,220}$/; const NODE_ID_PATTERN = /^[A-Za-z0-9_.:-]{1,128}$/; const FUNCTION_ID_PATTERN = /^[A-Za-z0-9_.:/-]{1,160}$/; +const PROFILE_ID_PATTERN = /^[A-Za-z0-9._-]{1,64}$/; const CAPABILITY_PATTERN = /^[a-z0-9][a-z0-9._-]{1,63}$/; const TIER_SET: ReadonlySet = new Set(["TierNone", "TierAccessibility", "TierPrivileged"]); +const MODE_SET: ReadonlySet = new Set(["ModeForeground", "ModeVirtualDisplay"]); const PROTECTION_SET: ReadonlySet = new Set(["ScreenClear", "ScreenLocked", "SecureFlag", "PrivateTab", "SensitiveView"]); +const TAKEOVER_SET: ReadonlySet = new Set(["TakeoverAuth", "TakeoverPayment", "TakeoverPermission", "TakeoverAmbiguous"]); const KEY_CODE_SET: ReadonlySet = new Set(ALLOWLISTED_KEY_CODES); const DIRECTION_SET: ReadonlySet = new Set(SCROLL_DIRECTIONS); const GESTURE_SET: ReadonlySet = new Set(GESTURE_KINDS); @@ -273,7 +338,21 @@ export function isBlockedTarget(packageName: string, activityName?: string): boo /** Whether `op` requires a live matching foreground snapshot before dispatch. */ export function opRequiresSnapshot(op: ControlOpPayload): boolean { - return op.type !== "app_launch_package" && op.type !== "app_open_url" && op.type !== "app_functions_discover"; + return op.type !== "app_launch_package" + && op.type !== "app_open_url" + && op.type !== "app_functions_discover" + && op.type !== "virtual_display_create" + && op.type !== "virtual_display_release" + && op.type !== "virtual_display_launch" + && op.type !== "profile_preview" + && op.type !== "profile_apply" + && op.type !== "profile_restore"; +} + +function isLeaseModeValid(tier: ControlTier, mode: ExecutionMode, displayId: number): boolean { + if (!Number.isSafeInteger(displayId)) return false; + if (mode === "ModeForeground") return displayId === 0; + return mode === "ModeVirtualDisplay" && tier === "TierPrivileged" && displayId > 0; } function parsePositiveInt(value: unknown): number | undefined { @@ -284,6 +363,11 @@ function parseIntInRange(value: unknown, min: number, max: number): number | und return typeof value === "number" && Number.isSafeInteger(value) && value >= min && value <= max ? value : undefined; } +function parseOptionalDisplayId(value: unknown): number | undefined | null { + if (value === undefined) return undefined; + return parseIntInRange(value, 0, 10_000) ?? null; +} + function parseHttpsUrl(value: unknown): string | undefined { if (typeof value !== "string") return undefined; const trimmed = value.trim(); @@ -319,7 +403,19 @@ function parsePrimitiveParameters(input: unknown): Readonly>> | undefined { + if (input === undefined) return undefined; + if (typeof input !== "object" || input === null || Array.isArray(input)) return undefined; + const out: Partial> = {}; + for (const [key, value] of Object.entries(input as Record)) { + if (!isProfileSettingKey(key)) return undefined; + if (typeof value !== "string" || value.length === 0 || value.length > 128 || value.includes("\0")) return undefined; + out[key] = value; + } + return Object.keys(out).length === 0 ? undefined : out; +} + +/** Decode and strictly validate any closed external-app, virtual-display, or reversible-profile operation. */ export function parseControlOp(input: unknown): ControlOpPayload | undefined { const rec = asRecord(input); const type = readString(rec, "type"); @@ -327,7 +423,16 @@ export function parseControlOp(input: unknown): ControlOpPayload | undefined { switch (type) { case "app_launch_package": { const packageName = readString(rec, "packageName"); - return packageName !== undefined && isValidPackageName(packageName) ? { type, packageName } : undefined; + const displayId = parseOptionalDisplayId(rec.displayId); + const activityName = readString(rec, "activityName"); + if (packageName === undefined || !isValidPackageName(packageName) || displayId === null) return undefined; + if (rec.activityName !== undefined && (activityName === undefined || !ACTIVITY_PATTERN.test(activityName))) return undefined; + return { + type, + packageName, + ...(displayId === undefined ? {} : { displayId }), + ...(activityName === undefined ? {} : { activityName }), + }; } case "app_open_url": { const url = parseHttpsUrl(rec.url); @@ -352,10 +457,13 @@ export function parseControlOp(input: unknown): ControlOpPayload | undefined { if (rec.maxWidth !== undefined && maxWidth === undefined) return undefined; const quality = rec.quality === undefined ? undefined : parseIntInRange(rec.quality, 40, 85); if (rec.quality !== undefined && quality === undefined) return undefined; + const displayId = parseOptionalDisplayId(rec.displayId); + if (displayId === null) return undefined; return { type, ...(maxWidth === undefined ? {} : { maxWidth }), ...(quality === undefined ? {} : { quality }), + ...(displayId === undefined ? {} : { displayId }), }; } case "ui_click": { @@ -372,11 +480,14 @@ export function parseControlOp(input: unknown): ControlOpPayload | undefined { if (nodeId === undefined && !hasCoords) return undefined; const longClick = readBoolean(rec, "longClick"); if (rec.longClick !== undefined && longClick === undefined) return undefined; + const displayId = parseOptionalDisplayId(rec.displayId); + if (displayId === null) return undefined; return { type, snapshotId, expectedPackage, ...(nodeId === undefined ? {} : { nodeId }), ...(hasCoords ? { x, y } : {}), ...(longClick === undefined ? {} : { longClick }), + ...(displayId === undefined ? {} : { displayId }), }; } case "ui_set_text": { @@ -415,11 +526,15 @@ export function parseControlOp(input: unknown): ControlOpPayload | undefined { const snapshotId = parsePositiveInt(rec.snapshotId); const expectedPackage = readString(rec, "expectedPackage"); const keyCode = readString(rec, "keyCode"); + const displayId = parseOptionalDisplayId(rec.displayId); if ( snapshotId === undefined || expectedPackage === undefined || !isValidPackageName(expectedPackage) - || keyCode === undefined || !KEY_CODE_SET.has(keyCode) + || keyCode === undefined || !KEY_CODE_SET.has(keyCode) || displayId === null ) return undefined; - return { type, snapshotId, expectedPackage, keyCode: keyCode as ControlKeyCode }; + return { + type, snapshotId, expectedPackage, keyCode: keyCode as ControlKeyCode, + ...(displayId === undefined ? {} : { displayId }), + }; } case "ui_gesture": { const snapshotId = parsePositiveInt(rec.snapshotId); @@ -469,6 +584,66 @@ export function parseControlOp(input: unknown): ControlOpPayload | undefined { ) return undefined; return { type, snapshotId, expectedPackage, functionId, parameters }; } + case "virtual_display_create": { + const packageName = readString(rec, "packageName"); + const activityName = readString(rec, "activityName"); + const width = rec.width === undefined ? undefined : parseIntInRange(rec.width, 360, 1440); + const height = rec.height === undefined ? undefined : parseIntInRange(rec.height, 640, 3200); + const densityDpi = rec.densityDpi === undefined ? undefined : parseIntInRange(rec.densityDpi, 120, 640); + const allowForegroundFallback = readBoolean(rec, "allowForegroundFallback"); + if (packageName === undefined || !isValidPackageName(packageName)) return undefined; + if (rec.activityName !== undefined && (activityName === undefined || !ACTIVITY_PATTERN.test(activityName))) return undefined; + if ((rec.width !== undefined && width === undefined) || (rec.height !== undefined && height === undefined) || (rec.densityDpi !== undefined && densityDpi === undefined)) return undefined; + if (rec.allowForegroundFallback !== undefined && allowForegroundFallback === undefined) return undefined; + return { + type, + packageName, + ...(activityName === undefined ? {} : { activityName }), + ...(width === undefined ? {} : { width }), + ...(height === undefined ? {} : { height }), + ...(densityDpi === undefined ? {} : { densityDpi }), + ...(allowForegroundFallback === undefined ? {} : { allowForegroundFallback }), + }; + } + case "virtual_display_release": { + const displayId = parseOptionalDisplayId(rec.displayId); + if (displayId === null) return undefined; + return displayId === undefined ? { type } : { type, displayId }; + } + case "virtual_display_launch": { + const displayId = parsePositiveInt(rec.displayId); + const packageName = readString(rec, "packageName"); + const activityName = readString(rec, "activityName"); + if (displayId === undefined || packageName === undefined || !isValidPackageName(packageName)) return undefined; + if (rec.activityName !== undefined && (activityName === undefined || !ACTIVITY_PATTERN.test(activityName))) return undefined; + return { type, displayId, packageName, ...(activityName === undefined ? {} : { activityName }) }; + } + case "profile_preview": { + const profileId = readString(rec, "profileId"); + if (profileId === undefined || !PROFILE_ID_PATTERN.test(profileId)) return undefined; + const settings = parseProfileSettings(rec.settings); + if (rec.settings !== undefined && settings === undefined) return undefined; + return { type, profileId, ...(settings === undefined ? {} : { settings }) }; + } + case "profile_apply": { + const profileId = readString(rec, "profileId"); + if (profileId === undefined || !PROFILE_ID_PATTERN.test(profileId)) return undefined; + const durationMs = rec.durationMs === undefined ? undefined : parseIntInRange(rec.durationMs, 0, 86_400_000); + if (rec.durationMs !== undefined && durationMs === undefined) return undefined; + const settings = parseProfileSettings(rec.settings); + if (rec.settings !== undefined && settings === undefined) return undefined; + return { + type, + profileId, + ...(durationMs === undefined ? {} : { durationMs }), + ...(settings === undefined ? {} : { settings }), + }; + } + case "profile_restore": { + const receiptId = readString(rec, "receiptId"); + if (receiptId === undefined || !PROFILE_ID_PATTERN.test(receiptId)) return undefined; + return { type, receiptId }; + } default: return undefined; } @@ -508,11 +683,15 @@ function parseObservedNode(input: unknown): ObservedUiNode | undefined { function opTargetPackage(op: ControlOpPayload, foregroundPackage: string, activeLeasePackage: string): string { switch (op.type) { case "app_launch_package": + case "virtual_display_create": + case "virtual_display_launch": return op.packageName; case "app_open_url": return op.packageName ?? (activeLeasePackage !== "" ? activeLeasePackage : foregroundPackage); case "app_functions_discover": return op.packageName ?? (foregroundPackage !== "" ? foregroundPackage : activeLeasePackage); + case "virtual_display_release": + return activeLeasePackage !== "" ? activeLeasePackage : foregroundPackage; case "ui_read_tree": case "ui_capture_screen": return foregroundPackage; @@ -524,6 +703,10 @@ function opTargetPackage(op: ControlOpPayload, foregroundPackage: string, active case "ui_global_action": case "app_function_execute": return op.expectedPackage; + case "profile_preview": + case "profile_apply": + case "profile_restore": + return ""; } } @@ -543,21 +726,57 @@ function opSnapshotId(op: ControlOpPayload, currentSnapId: number): number { case "app_launch_package": case "app_open_url": case "app_functions_discover": + case "virtual_display_create": + case "virtual_display_release": + case "virtual_display_launch": + case "profile_preview": + case "profile_apply": + case "profile_restore": return 0; } } +function parseDiscoveredFunctionsFromResult(result: Record): readonly DiscoveredAppFunction[] { + const rawList = Array.isArray(result.functions) ? result.functions : []; + const fallbackPkg = typeof result.packageName === "string" ? result.packageName.trim() : ""; + const parsed: DiscoveredAppFunction[] = []; + for (const item of rawList.slice(0, 16)) { + const rec = asRecord(item); + const functionId = readString(rec, "functionId"); + const packageName = readString(rec, "packageName") ?? fallbackPkg; + if (functionId === undefined || !FUNCTION_ID_PATTERN.test(functionId) || !isValidPackageName(packageName) || isBlockedTarget(packageName)) { + continue; + } + const displayName = readString(rec, "displayName"); + const description = readString(rec, "description"); + const rawParams = Array.isArray(rec.parameters) ? rec.parameters : []; + const parameters = rawParams.filter((p): p is string => typeof p === "string" && p.trim().length > 0).slice(0, 12); + parsed.push({ + functionId, + packageName, + ...(displayName === undefined ? {} : { displayName }), + ...(description === undefined ? {} : { description: description.slice(0, 120) }), + parameters, + }); + } + return parsed; +} + /** Control effect emitted by coordinator transitions, matching spec/app/control/index.md. */ export type CoordinatorEffect = - | { readonly tag: "DispatchOp"; readonly pending: PendingControlOp } + | { readonly tag: "DispatchOp"; readonly pending: PendingControlOp; readonly mode: ExecutionMode; readonly displayId: number } | { readonly tag: "HaltBridge"; readonly reason: string } - | { readonly tag: "ClearOverlay" }; + | { readonly tag: "ClearOverlay" } + | { readonly tag: "PauseForTakeover"; readonly reason: TakeoverReason; readonly surfaceToForeground: boolean } + | { readonly tag: "ReleaseVirtualDisplay"; readonly displayId: number }; /** - * In-memory coordinator enforcing `spec/app/control/index.md` invariants across the - * resident agent's overlay routes, native control bridge routes, and `DEVICE_CONTROL` action. + * In-memory coordinator enforcing `spec/app/control/index.md` v2 invariants (dual-mode execution, + * observed-readback completion, post-interrupt reconciliation, human takeover pause, and reversible + * OS profile receipts) across overlay routes, native bridge routes, and `DEVICE_CONTROL`. */ export class AlphaControlCoordinator { + readonly profiles: ReversibleProfileStore; private tier: ControlTier = "TierNone"; private capabilities: readonly string[] = []; private foreground: ForegroundObservation = { @@ -581,17 +800,50 @@ export class AlphaControlCoordinator { usedOps: 0, expiresAtMs: 0, status: "LeaseInactive", + mode: "ModeForeground", + displayId: 0, }; private leaseRequest: ControlLeaseRequest | null = null; private pending: PendingControlOp | null = null; private lastResult: ExecutionOutcome = "done"; private lastOpId = 0; private killed = false; + private needsReconcile = false; + private takeover: TakeoverReason = "TakeoverNone"; + private lastReadbackSnapId = 0; + private readonly appFunctionsByPackage = new Map(); private readonly recentReceipts: ControlReceiptRecord[] = []; private readonly waiters = new Map void>(); + constructor(profiles?: ReversibleProfileStore) { + this.profiles = profiles ?? new ReversibleProfileStore({ + dnd_mode: "off", + notification_silence: "disabled", + screen_timeout_seconds: "60", + home_shortcuts: "default_pack", + }); + } + + /** Register discovered Android 16+/17 AppFunctions scoped to a single non-blocked package. */ + registerDiscoveredFunctions(packageName: string, functions: readonly DiscoveredAppFunction[]): void { + const pkg = packageName.trim(); + if (!isValidPackageName(pkg) || isBlockedTarget(pkg)) return; + const scoped = functions + .filter((fn) => fn.packageName === pkg && FUNCTION_ID_PATTERN.test(fn.functionId)) + .slice(0, 16); + this.appFunctionsByPackage.set(pkg, scoped); + } + + /** Return compact AppFunctions scoped exclusively to the active foreground or leased package. */ + scopedAppFunctionsFor(packageName?: string): readonly DiscoveredAppFunction[] { + const target = (packageName ?? this.foreground.packageName) || this.lease.packageName; + if (target === "") return []; + return this.appFunctionsByPackage.get(target) ?? []; + } + /** Read the current control state without advancing clock expiry. */ readState(): ControlCoordinatorState { + const activePkg = this.foreground.packageName || this.lease.packageName; return { tier: this.tier, capabilities: [...this.capabilities], @@ -601,6 +853,11 @@ export class AlphaControlCoordinator { pending: this.pending, lastResult: this.lastResult, killed: this.killed, + needsReconcile: this.needsReconcile, + takeover: this.takeover, + lastReadbackSnapId: this.lastReadbackSnapId, + appFunctions: activePkg === "" ? [] : [...(this.appFunctionsByPackage.get(activePkg) ?? [])], + activeProfiles: this.profiles.activeReceipts(), recentReceipts: [...this.recentReceipts], }; } @@ -615,40 +872,66 @@ export class AlphaControlCoordinator { return this.lease.status === "LeaseActive" || this.pending !== null || !this.killed; } - /** Read the current control state, revoking any expired lease first. */ + /** Read the current control state, revoking any expired lease and expired OS profiles first. */ snapshot(nowMs: number): ControlCoordinatorState { this.expireIfDue(nowMs); + this.profiles.restoreExpired(nowMs); return this.readState(); } - /** Update the native control tier reported by the phone, revoking active work when dropping to TierNone. */ + /** Update the native control tier reported by the phone, revoking incompatible leases and releasing virtual displays. */ setTier(tier: ControlTier, nowMs = 0): | { readonly ok: true; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false; readonly code: string; readonly status: number } { if (!TIER_SET.has(tier) || tier === this.tier) { return { ok: false, code: "TIER_UNCHANGED", status: 409 }; } + const hadPending = this.pending !== null; + const dropVirtual = tier !== "TierPrivileged" + && this.lease.status === "LeaseActive" + && this.lease.mode === "ModeVirtualDisplay"; + const revoke = (tier === "TierNone" && this.lease.status === "LeaseActive") || dropVirtual; + const prevDisplayId = this.lease.displayId; + const releaseEffects: CoordinatorEffect[] = dropVirtual && prevDisplayId > 0 + ? [{ tag: "ReleaseVirtualDisplay", displayId: prevDisplayId }] + : []; + this.tier = tier; if (tier === "TierNone") { - const hadPending = this.pending !== null; - if (this.lease.status === "LeaseActive") { - this.lease = { ...this.lease, status: "LeaseRevoked" }; + if (revoke) { + this.lease = { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }; } if (hadPending) { + this.needsReconcile = true; this.settlePreempted("tier_disabled", nowMs, false); } this.leaseRequest = null; return { ok: true, - effects: hadPending - ? [{ tag: "HaltBridge", reason: "tier_disabled" }, { tag: "ClearOverlay" }] - : [{ tag: "ClearOverlay" }], + effects: [ + ...(hadPending ? [{ tag: "HaltBridge" as const, reason: "tier_disabled" }, { tag: "ClearOverlay" as const }] : [{ tag: "ClearOverlay" as const }]), + ...releaseEffects, + ], }; } - return { ok: true, effects: [] }; + + if (revoke) { + this.lease = { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }; + } + if (dropVirtual && hadPending) { + this.needsReconcile = true; + this.settlePreempted("virtual_display_tier_lost", nowMs, false); + } + return { + ok: true, + effects: [ + ...(dropVirtual && hadPending ? [{ tag: "HaltBridge" as const, reason: "virtual_display_tier_lost" }] : []), + ...releaseEffects, + ], + }; } - /** Revoke an expired active lease and halt any in-flight operation. */ + /** Revoke an expired active lease, release any virtual display, and halt any in-flight operation. */ expireLease(nowMs: number): | { readonly ok: true; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false; readonly code: string; readonly status: number } { @@ -656,25 +939,57 @@ export class AlphaControlCoordinator { return { ok: false, code: "LEASE_NOT_EXPIRED", status: 409 }; } const hadPending = this.pending !== null; - this.lease = { ...this.lease, status: "LeaseRevoked" }; + const releaseVd = this.lease.mode === "ModeVirtualDisplay" && this.lease.displayId > 0; + const prevDisplayId = this.lease.displayId; + this.lease = { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }; if (hadPending) { + this.needsReconcile = true; this.settlePreempted("lease_expired", nowMs, false); } return { ok: true, - effects: hadPending ? [{ tag: "HaltBridge", reason: "lease_expired" }] : [], + effects: [ + ...(hadPending ? [{ tag: "HaltBridge" as const, reason: "lease_expired" }] : []), + ...(releaseVd ? [{ tag: "ReleaseVirtualDisplay" as const, displayId: prevDisplayId }] : []), + ], }; } - /** Apply an owner-approved bounded lease for one non-blocked target package. */ + private checkClearIdleForeground(): { readonly ok: false; readonly code: string; readonly status: number } | undefined { + if (this.pending !== null) return { ok: false, code: "OPERATION_IN_FLIGHT", status: 409 }; + if (this.needsReconcile) return { ok: false, code: "RECONCILIATION_REQUIRED", status: 409 }; + if (this.foreground.protection !== "ScreenClear") return { ok: false, code: "PROTECTED_SCREEN", status: 409 }; + if (this.foreground.targetKind === "BlockedApp") return { ok: false, code: "BLOCKED_FOREGROUND", status: 403 }; + return undefined; + } + + private revokeLeaseAndPreempt(reason: string, nowMs: number, updateLastResult: boolean): void { + if (this.lease.status === "LeaseActive") { + this.lease = { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }; + } + if (this.pending !== null) { + this.needsReconcile = true; + this.settlePreempted(reason, nowMs, updateLastResult); + } + this.leaseRequest = null; + } + + /** Apply an owner-approved bounded foreground or virtual-display lease for one non-blocked package. */ grantLease( - input: { readonly leaseId?: number; readonly packageName: string; readonly requestedAt?: number; readonly maxOps: number; readonly durationMs: number }, + input: { + readonly leaseId?: number; + readonly packageName: string; + readonly requestedAt?: number; + readonly maxOps: number; + readonly durationMs: number; + readonly mode?: ExecutionMode; + readonly displayId?: number; + }, nowMs: number, ): { readonly ok: true; readonly lease: ActiveControlLease } | { readonly ok: false; readonly code: string; readonly status: number } { if (this.tier === "TierNone") return { ok: false, code: "CONTROL_TIER_UNAVAILABLE", status: 409 }; - if (this.pending !== null) return { ok: false, code: "OPERATION_IN_FLIGHT", status: 409 }; - if (this.foreground.protection !== "ScreenClear") return { ok: false, code: "PROTECTED_SCREEN", status: 409 }; - if (this.foreground.targetKind === "BlockedApp") return { ok: false, code: "BLOCKED_FOREGROUND", status: 403 }; + const idleGuard = this.checkClearIdleForeground(); + if (idleGuard !== undefined) return idleGuard; if (!isValidPackageName(input.packageName) || isBlockedTarget(input.packageName)) { return { ok: false, code: "BLOCKED_PACKAGE", status: 403 }; } @@ -684,6 +999,11 @@ export class AlphaControlCoordinator { if (!Number.isSafeInteger(input.durationMs) || input.durationMs < MIN_LEASE_DURATION_MS || input.durationMs > MAX_LEASE_DURATION_MS) { return { ok: false, code: "INVALID_DURATION", status: 400 }; } + const mode: ExecutionMode = input.mode ?? "ModeForeground"; + const displayId = input.displayId ?? 0; + if (!MODE_SET.has(mode) || !isLeaseModeValid(this.tier, mode, displayId)) { + return { ok: false, code: "INVALID_EXECUTION_MODE", status: 409 }; + } if (input.requestedAt !== undefined && (this.leaseRequest?.packageName !== input.packageName || this.leaseRequest.requestedAt !== input.requestedAt)) { return { ok: false, code: "LEASE_REQUEST_CHANGED", status: 409 }; } @@ -697,26 +1017,79 @@ export class AlphaControlCoordinator { usedOps: 0, expiresAtMs: nowMs + input.durationMs, status: "LeaseActive", + mode, + displayId, }; this.leaseRequest = null; this.killed = false; + this.takeover = "TakeoverNone"; + this.needsReconcile = false; return { ok: true, lease: this.lease }; } - /** Engage the kill-switch immediately, revoking any active lease and preempting in-flight work. */ - stop(reason: string, nowMs: number): { readonly state: ControlCoordinatorState; readonly effects: readonly CoordinatorEffect[] } { - if (this.lease.status === "LeaseActive") { - this.lease = { ...this.lease, status: "LeaseRevoked" }; + /** Pause actuation for human takeover, automatically releasing and surfacing any background virtual display. */ + pauseForTakeover(reason: TakeoverReason, nowMs: number): + | { readonly ok: true; readonly surfacedToForeground: boolean; readonly effects: readonly CoordinatorEffect[] } + | { readonly ok: false; readonly code: string; readonly status: number } { + if (!TAKEOVER_SET.has(reason)) { + return { ok: false, code: "INVALID_TAKEOVER_REASON", status: 400 }; + } + if (this.lease.status !== "LeaseActive" && this.pending === null) { + return { ok: false, code: "NO_ACTIVE_CONTROL", status: 409 }; + } + const fromVirtual = this.lease.mode === "ModeVirtualDisplay" && this.lease.displayId > 0; + const prevDisplayId = this.lease.displayId; + if (fromVirtual) { + this.lease = { ...this.lease, mode: "ModeForeground", displayId: 0 }; } + if (this.pending !== null) { + this.settlePreempted("takeover_paused", nowMs, true); + } else { + this.lastResult = "preempted"; + } + this.needsReconcile = true; + this.takeover = reason; + const effects: CoordinatorEffect[] = [ + { tag: "PauseForTakeover", reason, surfaceToForeground: fromVirtual }, + ...(fromVirtual ? [{ tag: "ReleaseVirtualDisplay" as const, displayId: prevDisplayId }] : []), + ]; + return { ok: true, surfacedToForeground: fromVirtual, effects }; + } + + /** Owner resumes after completing human takeover once a fresh clear observation has reconciled state. */ + resumeAfterTakeover(): + | { readonly ok: true; readonly state: ControlCoordinatorState } + | { readonly ok: false; readonly code: string; readonly status: number } { + if (this.takeover === "TakeoverNone") return { ok: false, code: "NOT_PAUSED_FOR_TAKEOVER", status: 409 }; + const idleGuard = this.checkClearIdleForeground(); + if (idleGuard !== undefined) return idleGuard; + this.takeover = "TakeoverNone"; + return { ok: true, state: this.readState() }; + } + + /** Engage the kill-switch immediately, revoking any active lease, releasing any VD, and preempting in-flight work. */ + stop(reason: string, nowMs: number): { readonly state: ControlCoordinatorState; readonly effects: readonly CoordinatorEffect[] } { + const releaseVd = this.lease.mode === "ModeVirtualDisplay" && this.lease.displayId > 0; + const prevDisplayId = this.lease.displayId; + this.lease = this.lease.status === "LeaseActive" + ? { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 } + : { ...this.lease, mode: "ModeForeground", displayId: 0 }; if (this.pending !== null) { this.settlePreempted(reason || "kill_switch", nowMs, false); } this.leaseRequest = null; this.killed = true; - return { state: this.readState(), effects: [{ tag: "HaltBridge", reason: reason || "kill_switch" }, { tag: "ClearOverlay" }] }; + return { + state: this.readState(), + effects: [ + { tag: "HaltBridge", reason: reason || "kill_switch" }, + { tag: "ClearOverlay" }, + ...(releaseVd ? [{ tag: "ReleaseVirtualDisplay" as const, displayId: prevDisplayId }] : []), + ], + }; } - /** Record a fresh native observation from AlphaAccessibilityService. */ + /** Record a fresh native observation from AlphaAccessibilityService, reconciling clear unblocked screens. */ observe(input: Record, nowMs: number): | { readonly ok: true; @@ -762,9 +1135,7 @@ export class AlphaControlCoordinator { this.tier = tier; this.capabilities = capabilities; if (tier === "TierNone") { - if (this.lease.status === "LeaseActive") this.lease = { ...this.lease, status: "LeaseRevoked" }; - if (this.pending !== null) this.settlePreempted("tier_disabled", nowMs, false); - this.leaseRequest = null; + this.revokeLeaseAndPreempt("tier_disabled", nowMs, false); } if (protection !== "ScreenClear" || targetKind === "BlockedApp") { this.leaseRequest = null; @@ -790,17 +1161,26 @@ export class AlphaControlCoordinator { || (opRequiresSnapshot(this.pending.op) && (packageName !== this.pending.expectedPackage || targetKind !== "AllowedApp")) ); if (mustPreempt) { + this.needsReconcile = true; this.settlePreempted("screen_changed", nowMs, true); + } else if (protection === "ScreenClear" && targetKind !== "BlockedApp") { + this.needsReconcile = false; } - if (protection === "ScreenLocked" && this.lease.status === "LeaseActive") { - this.lease = { ...this.lease, status: "LeaseRevoked" }; + const revokeOnLock = protection === "ScreenLocked" && this.lease.status === "LeaseActive"; + const releaseVd = revokeOnLock && this.lease.mode === "ModeVirtualDisplay" && this.lease.displayId > 0; + const prevDisplayId = this.lease.displayId; + if (revokeOnLock) { + this.lease = { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }; } return { ok: true, snapshotId: nextSnapId, lease: this.lease, pendingOp: this.pending, - effects: mustPreempt ? [{ tag: "HaltBridge", reason: "screen_changed" }] : [], + effects: [ + ...(mustPreempt ? [{ tag: "HaltBridge" as const, reason: "screen_changed" }] : []), + ...(releaseVd ? [{ tag: "ReleaseVirtualDisplay" as const, displayId: prevDisplayId }] : []), + ], }; } @@ -814,6 +1194,8 @@ export class AlphaControlCoordinator { | { readonly ok: false; readonly code: string; readonly status: number } { if (this.tier === "TierNone") return { ok: false, code: "CONTROL_TIER_UNAVAILABLE", status: 409 }; if (this.pending !== null) return { ok: false, code: "OPERATION_IN_FLIGHT", status: 409 }; + if (this.needsReconcile) return { ok: false, code: "RECONCILIATION_REQUIRED", status: 409 }; + if (this.takeover !== "TakeoverNone") return { ok: false, code: "TAKEOVER_PAUSED", status: 409 }; if (this.foreground.protection !== "ScreenClear") return { ok: false, code: "PROTECTED_SCREEN", status: 409 }; if (this.foreground.targetKind === "BlockedApp") return { ok: false, code: "BLOCKED_PACKAGE", status: 403 }; if (overrides?.opId !== undefined && (!Number.isSafeInteger(overrides.opId) || overrides.opId <= this.lastOpId)) { @@ -829,6 +1211,9 @@ export class AlphaControlCoordinator { return { ok: false, code: "LEASE_REQUIRED", status: 403 }; } if (this.killed) return { ok: false, code: "KILL_SWITCH_ACTIVE", status: 409 }; + if (!isLeaseModeValid(this.tier, this.lease.mode, this.lease.displayId)) { + return { ok: false, code: "INVALID_EXECUTION_MODE", status: 409 }; + } if (this.lease.usedOps >= this.lease.maxOps || nowMs >= this.lease.expiresAtMs) { return { ok: false, code: "LEASE_EXHAUSTED", status: 403 }; } @@ -863,7 +1248,11 @@ export class AlphaControlCoordinator { createdAtMs: nowMs, }; this.pending = pending; - return { ok: true, pending, effects: [{ tag: "DispatchOp", pending }] }; + return { + ok: true, + pending, + effects: [{ tag: "DispatchOp", pending, mode: this.lease.mode, displayId: this.lease.displayId }], + }; } /** Return the current pending operation for the native executor, or null if idle/expired. */ @@ -872,7 +1261,7 @@ export class AlphaControlCoordinator { return this.pending; } - /** Record a native execution receipt for the currently in-flight operation. */ + /** Record a native execution receipt for the currently in-flight operation, requiring observed readback for UI completion. */ recordReceipt(input: Record, nowMs: number): | { readonly ok: true; readonly receipt: ControlReceiptRecord; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false; readonly code: string; readonly status: number } { @@ -885,43 +1274,73 @@ export class AlphaControlCoordinator { return { ok: false, code: "NO_MATCHING_OPERATION", status: 409 }; } const refusalCode = readString(input, "refusalCode"); - const postSnapshotId = parsePositiveInt(input.postSnapshotId); + const rawPostSnap = input.postSnapshotId; + const postSnapshotId = rawPostSnap === undefined ? undefined : parseIntInRange(rawPostSnap, 0, Number.MAX_SAFE_INTEGER); + if (rawPostSnap !== undefined && postSnapshotId === undefined) { + return { ok: false, code: "INVALID_RECEIPT", status: 400 }; + } + if ( + outcomeRaw === "done" + && opRequiresSnapshot(this.pending.op) + && (postSnapshotId === undefined || postSnapshotId <= this.pending.boundSnapId) + ) { + return { ok: false, code: "READBACK_REQUIRED", status: 409 }; + } const result = typeof input.result === "object" && input.result !== null && !Array.isArray(input.result) ? (input.result as Record) : undefined; + + const completedOp = this.pending.op; + const completedPkg = this.pending.expectedPackage; const record: ControlReceiptRecord = { opId, leaseId: this.pending.leaseId, snapshotId: this.pending.boundSnapId, outcome: outcomeRaw, ...(refusalCode === undefined ? {} : { refusalCode }), - ...(postSnapshotId === undefined ? {} : { postSnapshotId }), + ...(postSnapshotId !== undefined && postSnapshotId > 0 ? { postSnapshotId } : {}), ...(result === undefined ? {} : { result }), receivedAtMs: nowMs, }; this.pending = null; this.lastResult = outcomeRaw; + let releaseVd = false; + const prevDisplayId = this.lease.displayId; if (outcomeRaw === "preempted") { - if (this.lease.status === "LeaseActive") this.lease = { ...this.lease, status: "LeaseRevoked" }; + releaseVd = this.lease.mode === "ModeVirtualDisplay" && prevDisplayId > 0; + if (this.lease.status === "LeaseActive") { + this.lease = { ...this.lease, status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }; + } this.killed = true; + this.needsReconcile = true; + } else if (outcomeRaw === "done") { + if (postSnapshotId !== undefined && postSnapshotId > this.lastReadbackSnapId) { + this.lastReadbackSnapId = postSnapshotId; + } + if (completedOp.type === "app_functions_discover" && result !== undefined) { + const discovered = parseDiscoveredFunctionsFromResult(result); + const pkg = typeof result.packageName === "string" && isValidPackageName(result.packageName) + ? result.packageName + : completedPkg; + if (isValidPackageName(pkg)) { + this.registerDiscoveredFunctions(pkg, discovered); + } + } } this.pushReceipt(record); return { ok: true, receipt: record, - effects: outcomeRaw === "preempted" ? [{ tag: "HaltBridge", reason: "preempted" }] : [], + effects: [ + ...(outcomeRaw === "preempted" ? [{ tag: "HaltBridge" as const, reason: "preempted" }] : []), + ...(releaseVd ? [{ tag: "ReleaseVirtualDisplay" as const, displayId: prevDisplayId }] : []), + ], }; } /** Handle an immediate native interrupt such as physical touch preemption or screen lock. */ interrupt(reason: string, packageName: string | undefined, nowMs: number): ControlCoordinatorState { - if (this.lease.status === "LeaseActive") { - this.lease = { ...this.lease, status: "LeaseRevoked" }; - } - if (this.pending !== null) { - this.settlePreempted(reason, nowMs, true); - } - this.leaseRequest = null; + this.revokeLeaseAndPreempt(reason, nowMs, true); this.killed = true; if (packageName !== undefined && isValidPackageName(packageName) && isBlockedTarget(packageName)) { this.foreground = { @@ -991,42 +1410,17 @@ export class AlphaControlCoordinator { } function formatControlContext(state: ControlCoordinatorState): string { - if (state.tier === "TierNone") { - return ""; - } - if (state.foreground.protection !== "ScreenClear") { - return `External app control: screen protected (${state.foreground.protection}); observation withheld.`; - } - if (state.foreground.targetKind === "BlockedApp") { - return `External app control: foreground package ${state.foreground.packageName} is blocked from automation.`; - } - const remaining = state.lease.status === "LeaseActive" ? state.lease.maxOps - state.lease.usedOps : 0; - const lines: string[] = [ - `External app control: tier=${state.tier}, package=${state.foreground.packageName || "none"}, snapshotId=${state.foreground.snapId}`, - `Lease: status=${state.lease.status}, target=${state.lease.packageName || "none"}, remainingOps=${remaining}, killed=${state.killed}`, - ]; - if (state.foreground.webUri !== null) { - lines.push(`Active web URL: ${state.foreground.webUri}`); - } - const interactive = state.foreground.nodes.filter((node) => node.clickable || node.editable || node.scrollable).slice(0, 20); - if (interactive.length > 0) { - lines.push("Visible interactive elements:"); - for (const node of interactive) { - const label = node.text ?? node.contentDescription ?? node.hintText ?? node.resourceId ?? node.role; - lines.push(`- ${node.nodeId} [${node.role}] "${label}" (${node.bounds.left},${node.bounds.top},${node.bounds.right},${node.bounds.bottom})`); - } - } - return lines.join("\n"); + return formatCompactControlContext(state); } -/** Provider exposing live foreground context and active lease state to the resident agent. */ +/** Provider exposing compact, dynamically-scoped foreground context, active AppFunctions, and lease state. */ export function controlProvider( coordinator: AlphaControlCoordinator, now: () => number = () => Date.now(), ): AgentProvider { return { name: "alpha_device_control", - description: "Foreground Android app summary, active browser URL, snapshot id, and external control lease state.", + description: "Compact foreground Android app summary, scoped AppFunctions, active browser URL, snapshot id, and external control lease state.", get: () => Promise.resolve({ text: formatControlContext(coordinator.snapshot(now())) }), }; } @@ -1041,6 +1435,14 @@ function controlRefusalMessage(code: string, packageName?: string): string { return "External app control is halted by the kill-switch."; case "OPERATION_IN_FLIGHT": return "Another external app control operation is already running."; + case "RECONCILIATION_REQUIRED": + return "External app control must observe fresh screen state to reconcile after an interruption before acting again."; + case "TAKEOVER_PAUSED": + return "External app control is paused for owner takeover."; + case "READBACK_REQUIRED": + return "UI action completion requires observed post-action screen readback."; + case "INVALID_EXECUTION_MODE": + return "Virtual display mode requires TierPrivileged and a valid owned virtual display."; case "PROTECTED_SCREEN": return "External app control is refused on a locked, private, or protected screen."; case "BLOCKED_PACKAGE": @@ -1055,12 +1457,72 @@ function controlRefusalMessage(code: string, packageName?: string): string { return "The target UI snapshot is no longer current; observe the foreground screen again."; case "SENSITIVE_VIEW": return "External app control is refused on a password or sensitive field."; + case "INVALID_PROFILE": + return "Unknown or invalid reversible OS profile specification."; + case "RECEIPT_NOT_FOUND": + return "No reversible OS profile receipt matches that receipt id."; default: return `External app control refused (${code}).`; } } -/** Action allowing the resident agent to execute bounded external-app operations through the control coordinator. */ +function resolveProfileSpecForOp( + profileId: string, + settings?: Readonly>>, +): ReversibleProfileSpec | undefined { + const base = builtInProfileSpec(profileId); + if (settings === undefined) return base; + return { + profileId, + displayName: base?.displayName ?? profileId, + targetValues: { ...(base?.targetValues ?? {}), ...settings }, + }; +} + +function handleProfileOp( + coordinator: AlphaControlCoordinator, + op: Extract, + nowMs: number, +) { + if (op.type === "profile_restore") { + const restored = coordinator.profiles.restore(op.receiptId); + if (!restored.ok) { + const msg = controlRefusalMessage("RECEIPT_NOT_FOUND"); + return { success: false, text: msg, error: msg, data: { code: "RECEIPT_NOT_FOUND" } }; + } + const preservedNote = restored.preservedManualEdits.length > 0 + ? ` Preserved ${restored.preservedManualEdits.length} manual edit(s).` + : ""; + return { + success: true, + text: restored.alreadyRestored + ? `Profile ${restored.profileId} (${restored.receiptId}) was already restored.` + : `Restored ${restored.restoredKeys.length} setting(s) for ${restored.profileId}.${preservedNote}`, + data: { status: "done", tier: "direct_os", restore: restored }, + }; + } + const spec = resolveProfileSpecForOp(op.profileId, op.settings); + if (spec === undefined) { + const msg = controlRefusalMessage("INVALID_PROFILE"); + return { success: false, text: msg, error: msg, data: { code: "INVALID_PROFILE" } }; + } + if (op.type === "profile_preview") { + const preview = coordinator.profiles.preview(spec); + return { + success: true, + text: `Previewed ${preview.displayName}: ${preview.changes.length} setting(s) would change.`, + data: { status: "done", tier: "direct_os", readOnlyOperation: true, preview }, + }; + } + const receipt = coordinator.profiles.apply(spec, nowMs, op.durationMs ?? 0); + return { + success: true, + text: `Applied ${spec.displayName} (${receipt.receiptId}, ${receipt.entries.length} setting(s) recorded for reversible restore).`, + data: { status: "done", tier: "direct_os", receipt }, + }; +} + +/** Action allowing the resident agent to execute bounded external-app, virtual-display, and reversible-profile operations. */ export function controlActions( coordinator: AlphaControlCoordinator, now: () => number = () => Date.now(), @@ -1068,12 +1530,12 @@ export function controlActions( ): readonly AgentAction[] { const action: AgentAction = { name: CONTROL_ACTION_NAME, - description: "Observe or act inside an owner-approved third-party Android app using one of the twelve closed typed control operations.", - similes: ["CONTROL_APP", "OPERATE_APP", "BROWSER_EXTERNAL_CONTROL"], + description: "Observe or act inside an owner-approved third-party Android app (preferring Direct OS -> AppFunctions -> Accessibility tree -> opt-in screenshot) or manage reversible OS profiles.", + similes: ["CONTROL_APP", "OPERATE_APP", "BROWSER_EXTERNAL_CONTROL", "PHONE_USE"], parameters: [ { name: "op", - description: "Typed external control operation payload (app_launch_package, app_open_url, ui_read_tree, ui_capture_screen, ui_click, ui_set_text, ui_scroll, ui_key_event, ui_gesture, ui_global_action, app_functions_discover, app_function_execute).", + description: "Typed control operation (app_launch_package, app_open_url, ui_read_tree, ui_capture_screen, ui_click, ui_set_text, ui_scroll, ui_key_event, ui_gesture, ui_global_action, app_functions_discover, app_function_execute, virtual_display_create, virtual_display_release, virtual_display_launch, profile_preview, profile_apply, profile_restore).", required: true, schema: { type: "object" }, }, @@ -1086,6 +1548,9 @@ export function controlActions( const message = controlRefusalMessage("INVALID_OPERATION"); return { success: false, text: message, error: message, data: { code: "INVALID_OPERATION" } }; } + if (parsed.type === "profile_preview" || parsed.type === "profile_apply" || parsed.type === "profile_restore") { + return handleProfileOp(coordinator, parsed, now()); + } const dispatched = coordinator.dispatch(parsed, now()); if (!dispatched.ok) { const current = dispatched.code === "LEASE_REQUIRED" ? coordinator.snapshot(now()) : undefined; @@ -1107,7 +1572,12 @@ export function controlActions( return { success: true, text: `Queued ${parsed.type} for ${dispatched.pending.expectedPackage}.`, - data: { status: "queued", opId: dispatched.pending.opId, leaseId: dispatched.pending.leaseId }, + data: { + status: "queued", + tier: classifyActionTier(parsed.type), + opId: dispatched.pending.opId, + leaseId: dispatched.pending.leaseId, + }, }; } const succeeded = receipt.outcome === "done"; @@ -1120,6 +1590,7 @@ export function controlActions( ...(succeeded ? {} : { error: message }), data: { status: receipt.outcome, + tier: classifyActionTier(parsed.type), opId: receipt.opId, leaseId: receipt.leaseId, ...(receipt.refusalCode === undefined ? {} : { code: receipt.refusalCode }), @@ -1160,7 +1631,22 @@ export function controlRoutes( if (requestedAt !== undefined && (typeof requestedAt !== "number" || !Number.isSafeInteger(requestedAt))) { return Promise.resolve({ status: 400, body: { error: "INVALID_REQUEST_TIME" } }); } - const result = coordinator.grantLease({ packageName, maxOps, durationMs, ...(requestedAt === undefined ? {} : { requestedAt }) }, now()); + const rawMode = readString(rec, "mode"); + if (rec.mode !== undefined && (rawMode === undefined || !MODE_SET.has(rawMode))) { + return Promise.resolve({ status: 400, body: { error: "INVALID_EXECUTION_MODE" } }); + } + const rawDisplayId = rec.displayId; + if (rawDisplayId !== undefined && (typeof rawDisplayId !== "number" || !Number.isSafeInteger(rawDisplayId) || rawDisplayId < 0)) { + return Promise.resolve({ status: 400, body: { error: "INVALID_DISPLAY_ID" } }); + } + const result = coordinator.grantLease({ + packageName, + maxOps, + durationMs, + ...(requestedAt === undefined ? {} : { requestedAt }), + ...(rawMode === undefined ? {} : { mode: rawMode as ExecutionMode }), + ...(rawDisplayId === undefined ? {} : { displayId: rawDisplayId }), + }, now()); if (!result.ok) return Promise.resolve({ status: result.status, body: { error: result.code } }); return Promise.resolve({ status: 200, body: { lease: result.lease } }); }, diff --git a/apps/agent/src/plugins/control/phone-use.ts b/apps/agent/src/plugins/control/phone-use.ts new file mode 100644 index 0000000000..43c8af2cfd --- /dev/null +++ b/apps/agent/src/plugins/control/phone-use.ts @@ -0,0 +1,607 @@ +// spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease" +import type { ProfileReceipt } from "./profiles.ts"; + +/** Hard character budget for dynamic external-control prompt context (honors Shaw's <10k context discipline). */ +export const CONTROL_CONTEXT_MAX_CHARS = 9_600; + +/** Maximum AppFunctions surfaced per foreground package to avoid prompt bloat. */ +export const MAX_SCOPED_APP_FUNCTIONS = 12; + +/** Maximum interactive UI tree nodes summarized in compact control context. */ +export const MAX_COMPACT_UI_NODES = 20; + +/** Execution mode matching spec/app/control/index.md. */ +export type ExecutionMode = "ModeForeground" | "ModeVirtualDisplay"; + +/** Human takeover trigger classification matching spec/app/control/index.md. */ +export type TakeoverReason = + | "TakeoverNone" + | "TakeoverAuth" + | "TakeoverPayment" + | "TakeoverPermission" + | "TakeoverAmbiguous"; + +/** Four-tier action priority ladder from the OS-level agent control plan. */ +export type ActionTier = + | "direct_os" + | "app_functions" + | "accessibility_tree" + | "screenshot_fallback"; + +/** Compact discovered Android 16+/17 AppFunction schema descriptor scoped to one package. */ +export interface DiscoveredAppFunction { + readonly functionId: string; + readonly packageName: string; + readonly displayName?: string; + readonly description?: string; + readonly parameters: readonly string[]; +} + +/** Normalized UI node reported by the native accessibility service. */ +export interface ObservedUiNode { + readonly nodeId: string; + readonly role: string; + readonly resourceId?: string; + readonly text?: string; + readonly contentDescription?: string; + readonly hintText?: string; + readonly bounds: { readonly left: number; readonly top: number; readonly right: number; readonly bottom: number }; + readonly clickable: boolean; + readonly editable: boolean; + readonly scrollable: boolean; + readonly sensitive: boolean; +} + +/** Minimal observation snapshot needed for compact context and takeover checks. */ +export interface CompactObservationView { + readonly snapId: number; + readonly packageName: string; + readonly activityName: string; + readonly webUri: string | null; + readonly targetKind: "AllowedApp" | "BlockedApp" | "NoTarget"; + readonly protection: "ScreenClear" | "ScreenLocked" | "SecureFlag" | "PrivateTab" | "SensitiveView"; + readonly nodes: readonly ObservedUiNode[]; +} + +/** Input passed to `formatCompactControlContext`. */ +export interface CompactContextInput { + readonly tier: "TierNone" | "TierAccessibility" | "TierPrivileged"; + readonly foreground: CompactObservationView; + readonly lease: { + readonly status: "LeaseInactive" | "LeaseActive" | "LeaseRevoked"; + readonly packageName: string; + readonly maxOps: number; + readonly usedOps: number; + readonly mode: ExecutionMode; + readonly displayId: number; + }; + readonly killed: boolean; + readonly needsReconcile: boolean; + readonly takeover: TakeoverReason; + readonly appFunctions: readonly DiscoveredAppFunction[]; + readonly activeProfiles: readonly ProfileReceipt[]; + readonly maxChars?: number; +} + +const AUTH_MARKERS = [ + "sign in", "log in", "login", "password", "passkey", "two-factor", "2fa", + "verification code", "one-time code", "authenticate", "oauth", "verify identity", +] as const; + +const PAYMENT_MARKERS = [ + "checkout", "pay now", "place order", "confirm purchase", "complete payment", + "credit card", "debit card", "billing", "cvv", "wire transfer", "send money", "subscribe now", +] as const; + +const PERMISSION_MARKERS = [ + "allow this app", "grant permission", "permission request", "allow access to", + "install unknown apps", "accessibility permission", "device admin", +] as const; + +/** Classify a control operation type into the 4-tier action priority ladder. */ +export function classifyActionTier(opType: string): ActionTier { + switch (opType) { + case "app_launch_package": + case "app_open_url": + case "virtual_display_create": + case "virtual_display_release": + case "virtual_display_launch": + case "profile_preview": + case "profile_apply": + case "profile_restore": + return "direct_os"; + case "app_functions_discover": + case "app_function_execute": + return "app_functions"; + case "ui_capture_screen": + return "screenshot_fallback"; + default: + return "accessibility_tree"; + } +} + +/** + * Pick the highest-priority feasible action tier strictly following the 4-tier ladder: + * Direct OS tools -> AppFunctions -> AccessibilityService UI tree -> opt-in screenshot fallback. + */ +export function selectPreferredActionTier(options: { + readonly hasDirectOsTool: boolean; + readonly hasMatchingAppFunction: boolean; + readonly hasAccessibilityTarget: boolean; + readonly allowScreenshotFallback: boolean; +}): ActionTier | null { + if (options.hasDirectOsTool) return "direct_os"; + if (options.hasMatchingAppFunction) return "app_functions"; + if (options.hasAccessibilityTarget) return "accessibility_tree"; + if (options.allowScreenshotFallback) return "screenshot_fallback"; + return null; +} + +/** Inspect foreground metadata, visible node labels, and candidate ambiguity for mandatory human takeover. */ +export function detectTakeoverFromObservation( + observation: Pick, + candidateMatchCount = 1, +): TakeoverReason { + const pkg = observation.packageName.trim().toLowerCase(); + const act = observation.activityName.trim().toLowerCase(); + if (pkg.includes("permissioncontroller") || pkg.includes("packageinstaller") || act.includes("grantpermissions")) { + return "TakeoverPermission"; + } + if (act.includes("billing") || act.includes("purchase") || act.includes("payment") || act.includes("checkout")) { + return "TakeoverPayment"; + } + if (act.includes("login") || act.includes("signin") || act.includes("auth") || act.includes("credential")) { + return "TakeoverAuth"; + } + if (observation.protection === "SensitiveView") { + return "TakeoverAuth"; + } + for (const node of observation.nodes) { + if (node.sensitive) return "TakeoverAuth"; + const text = [node.text, node.contentDescription, node.hintText] + .filter((part): part is string => typeof part === "string" && part.length > 0) + .join(" ") + .toLowerCase(); + if (text === "") continue; + if (PERMISSION_MARKERS.some((marker) => text.includes(marker))) return "TakeoverPermission"; + if (PAYMENT_MARKERS.some((marker) => text.includes(marker))) return "TakeoverPayment"; + if (AUTH_MARKERS.some((marker) => text.includes(marker))) return "TakeoverAuth"; + } + if (candidateMatchCount > 1) { + return "TakeoverAmbiguous"; + } + return "TakeoverNone"; +} + +function clampText(text: string, maxLen: number): string { + const normalized = text.replace(/\s+/g, " ").trim(); + return normalized.length <= maxLen ? normalized : `${normalized.slice(0, maxLen - 1)}…`; +} + +/** + * Format compact, dynamically-scoped control context strictly bounded below `CONTROL_CONTEXT_MAX_CHARS` + * (<10k chars). Includes ONLY the active foreground app's AppFunctions + compact interactive UI tree. + */ +export function formatCompactControlContext(input: CompactContextInput): string { + if (input.tier === "TierNone") { + return ""; + } + if (input.foreground.protection !== "ScreenClear") { + return `External app control: screen protected (${input.foreground.protection}); observation withheld.`; + } + if (input.foreground.targetKind === "BlockedApp") { + return `External app control: foreground package ${input.foreground.packageName} is blocked from automation.`; + } + const budget = Math.min(CONTROL_CONTEXT_MAX_CHARS, Math.max(512, input.maxChars ?? CONTROL_CONTEXT_MAX_CHARS)); + const remaining = input.lease.status === "LeaseActive" ? input.lease.maxOps - input.lease.usedOps : 0; + const activePkg = input.foreground.packageName || input.lease.packageName || ""; + const lines: string[] = [ + `External app control: tier=${input.tier}, package=${input.foreground.packageName || "none"}, snapshotId=${input.foreground.snapId}, mode=${input.lease.mode}, displayId=${input.lease.displayId}`, + `Lease: status=${input.lease.status}, target=${input.lease.packageName || "none"}, remainingOps=${remaining}, killed=${input.killed}, needsReconcile=${input.needsReconcile}, takeover=${input.takeover}`, + ]; + if (input.foreground.webUri !== null) { + lines.push(`Active web URL: ${clampText(input.foreground.webUri, 256)}`); + } + if (input.activeProfiles.length > 0) { + const profileSummary = input.activeProfiles + .slice(0, 4) + .map((receipt) => `${receipt.profileId}(${receipt.receiptId})`) + .join(", "); + lines.push(`Active reversible profiles: ${profileSummary}`); + } + + const scopedFunctions = activePkg === "" + ? [] + : input.appFunctions + .filter((fn) => fn.packageName === activePkg) + .slice(0, MAX_SCOPED_APP_FUNCTIONS); + if (scopedFunctions.length > 0) { + lines.push(`AppFunctions (${activePkg}, Tier 2 preferred over UI scraping):`); + for (const fn of scopedFunctions) { + const params = fn.parameters.slice(0, 8).join(", "); + const desc = fn.description ? ` - ${clampText(fn.description, 80)}` : ""; + lines.push(`- ${fn.functionId}(${params})${desc}`); + } + } + + const interactive = input.foreground.nodes + .filter((node) => node.clickable || node.editable || node.scrollable) + .slice(0, MAX_COMPACT_UI_NODES); + if (interactive.length > 0) { + lines.push("Visible interactive elements:"); + for (const node of interactive) { + const rawLabel = node.text ?? node.contentDescription ?? node.hintText ?? node.resourceId ?? node.role; + const label = clampText(rawLabel, 64); + lines.push(`- ${node.nodeId} [${node.role}] "${label}" (${node.bounds.left},${node.bounds.top},${node.bounds.right},${node.bounds.bottom})`); + } + } + + const assembled: string[] = []; + let usedChars = 0; + for (const line of lines) { + const nextSize = usedChars + (assembled.length > 0 ? 1 : 0) + line.length; + if (nextSize > budget) break; + assembled.push(line); + usedChars = nextSize; + } + return assembled.join("\n"); +} + +/** Planner decision returned on each iteration of the autonomous Phone Use loop. */ +export type PhoneUsePlanStep = + | { readonly kind: "done"; readonly summary: string; readonly verifiedByReadback: boolean } + | { readonly kind: "takeover"; readonly reason: Exclude; readonly detail: string } + | { + readonly kind: "op"; + readonly op: Op; + readonly candidateMatchCount?: number; + readonly verifyReadback?: (after: CompactObservationView) => boolean; + }; + +/** Minimal execution receipt shape consumed by the Phone Use loop. */ +export interface PhoneUseReceiptLike { + readonly opId: number; + readonly outcome: "done" | "refused" | "preempted"; + readonly refusalCode?: string; + readonly postSnapshotId?: number; + readonly result?: Record; +} + +/** Minimal coordinator interface driven by `runPhoneUseLoop` (avoids circular import with control.ts). */ +export interface PhoneUseCoordinatorLike { + snapshot(nowMs: number): CompactContextInput & { + readonly lease: CompactContextInput["lease"] & { readonly leaseId: number; readonly expiresAtMs: number }; + }; + dispatch(op: Op, nowMs: number): + | { readonly ok: true; readonly pending: { readonly opId: number; readonly boundSnapId: number; readonly expectedPackage: string } } + | { readonly ok: false; readonly code: string; readonly status: number }; + waitForReceipt(opId: number, timeoutMs: number): Promise; + pauseForTakeover(reason: Exclude, nowMs: number): + | { readonly ok: true; readonly surfacedToForeground: boolean } + | { readonly ok: false }; + stop(reason: string, nowMs: number): unknown; +} + +/** Final outcome returned by `runPhoneUseLoop`. */ +export interface PhoneUseLoopResult { + readonly status: + | "completed" + | "paused_for_takeover" + | "aborted" + | "needs_reconcile" + | "refused" + | "budget_exhausted"; + readonly summary: string; + readonly stepsExecuted: number; + readonly tiersUsed: readonly ActionTier[]; + readonly receipts: readonly Receipt[]; + readonly takeoverReason?: TakeoverReason; + readonly surfacedToForeground?: boolean; + readonly refusalCode?: string; +} + +function checkLoopPreconditions( + coordinator: PhoneUseCoordinatorLike, + state: CompactContextInput, + targetPackage: string, + stepIndex: number, + nowMs: number, + tiersUsed: readonly ActionTier[], + receipts: readonly Receipt[], +): PhoneUseLoopResult | undefined { + if (state.killed) { + return { + status: "aborted", + summary: "Stopped because the kill-switch is active.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + }; + } + if (state.needsReconcile) { + return { + status: "needs_reconcile", + summary: "Paused until a fresh screen observation reconciles post-interrupt state.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: "RECONCILIATION_REQUIRED", + }; + } + if (state.takeover !== "TakeoverNone") { + return { + status: "paused_for_takeover", + summary: `Paused for human takeover (${state.takeover}).`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + takeoverReason: state.takeover, + }; + } + if (state.foreground.protection !== "ScreenClear" || state.foreground.targetKind === "BlockedApp") { + const reason: Exclude = + state.foreground.packageName.includes("permissioncontroller") + ? "TakeoverPermission" + : "TakeoverAuth"; + const paused = coordinator.pauseForTakeover(reason, nowMs); + return { + status: "paused_for_takeover", + summary: `Paused on protected/blocked screen (${state.foreground.protection}).`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + takeoverReason: reason, + surfacedToForeground: paused.ok ? paused.surfacedToForeground : false, + }; + } + if ( + stepIndex > 0 + && state.foreground.packageName !== "" + && state.foreground.packageName !== targetPackage + ) { + coordinator.stop("app_switched", nowMs); + return { + status: "aborted", + summary: `Stopped immediately after foreground switched to ${state.foreground.packageName}.`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + }; + } + const detectedTakeover = detectTakeoverFromObservation(state.foreground, 1); + if (detectedTakeover !== "TakeoverNone") { + const paused = coordinator.pauseForTakeover(detectedTakeover, nowMs); + return { + status: "paused_for_takeover", + summary: `Paused for human takeover (${detectedTakeover}).`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + takeoverReason: detectedTakeover, + surfacedToForeground: paused.ok ? paused.surfacedToForeground : false, + }; + } + return undefined; +} + +/** + * Bounded autonomous multi-step Phone Use loop enforcing: + * 1. 4-tier priority ladder (with opt-in screenshot fallback gate), + * 2. Compact per-foreground-app dynamic context (<10k chars), + * 3. Instant Stop / AbortSignal / app-switch interruption, + * 4. Automatic human takeover pause & virtual-display foreground surfacing, + * 5. Observed-readback completion verification & post-interrupt reconciliation. + */ +export async function runPhoneUseLoop< + Op extends { readonly type: string }, + Receipt extends PhoneUseReceiptLike, +>(options: { + readonly coordinator: PhoneUseCoordinatorLike; + readonly targetPackage: string; + readonly maxSteps: number; + readonly allowScreenshotFallback?: boolean; + readonly receiptTimeoutMs?: number; + readonly signal?: AbortSignal; + readonly now?: () => number; + readonly planNextStep: (input: { + readonly stepIndex: number; + readonly compactContext: string; + readonly state: CompactContextInput; + readonly preferredTier: ActionTier | null; + readonly receipts: readonly Receipt[]; + }) => Promise> | PhoneUsePlanStep; +}): Promise> { + const now = options.now ?? (() => Date.now()); + const allowScreenshot = options.allowScreenshotFallback ?? false; + const receiptTimeoutMs = options.receiptTimeoutMs ?? 10_000; + const stepCap = Math.max(1, Math.min(12, Math.trunc(options.maxSteps))); + const isAborted = () => options.signal?.aborted === true; + const receipts: Receipt[] = []; + const tiersUsed: ActionTier[] = []; + let readbackObservedCount = 0; + + for (let stepIndex = 0; stepIndex < stepCap; stepIndex += 1) { + if (isAborted()) { + options.coordinator.stop("abort_signal", now()); + return { + status: "aborted", + summary: "Stopped immediately on abort signal.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + }; + } + + const state = options.coordinator.snapshot(now()); + const halted = checkLoopPreconditions( + options.coordinator, + state, + options.targetPackage, + stepIndex, + now(), + tiersUsed, + receipts, + ); + if (halted !== undefined) return halted; + + const compactContext = formatCompactControlContext(state); + const hasScopedFunctions = state.appFunctions.some((fn) => fn.packageName === options.targetPackage); + const hasAxNodes = state.foreground.nodes.some((node) => node.clickable || node.editable || node.scrollable); + const preferredTier = selectPreferredActionTier({ + hasDirectOsTool: state.foreground.packageName !== options.targetPackage, + hasMatchingAppFunction: hasScopedFunctions, + hasAccessibilityTarget: hasAxNodes, + allowScreenshotFallback: allowScreenshot, + }); + + const plan = await options.planNextStep({ + stepIndex, + compactContext, + state, + preferredTier, + receipts, + }); + + if (isAborted()) { + options.coordinator.stop("abort_signal", now()); + return { + status: "aborted", + summary: "Stopped immediately on abort signal.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + }; + } + + if (plan.kind === "done") { + if (!plan.verifiedByReadback && readbackObservedCount === 0 && receipts.length > 0) { + return { + status: "needs_reconcile", + summary: "Cannot mark task complete without observed screen readback.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: "READBACK_REQUIRED", + }; + } + return { + status: "completed", + summary: plan.summary, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + }; + } + + if (plan.kind === "takeover") { + const paused = options.coordinator.pauseForTakeover(plan.reason, now()); + return { + status: "paused_for_takeover", + summary: plan.detail, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + takeoverReason: plan.reason, + surfacedToForeground: paused.ok ? paused.surfacedToForeground : false, + }; + } + + if ((plan.candidateMatchCount ?? 1) > 1) { + const paused = options.coordinator.pauseForTakeover("TakeoverAmbiguous", now()); + return { + status: "paused_for_takeover", + summary: "Multiple ambiguous targets matched; paused for owner disambiguation.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + takeoverReason: "TakeoverAmbiguous", + surfacedToForeground: paused.ok ? paused.surfacedToForeground : false, + }; + } + + const tier = classifyActionTier(plan.op.type); + if (tier === "screenshot_fallback" && !allowScreenshot) { + return { + status: "refused", + summary: "Screenshot fallback is opt-in only and disabled for this session.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: "SCREENSHOT_FALLBACK_DISABLED", + }; + } + + const dispatched = options.coordinator.dispatch(plan.op, now()); + if (!dispatched.ok) { + return { + status: dispatched.code === "RECONCILIATION_REQUIRED" ? "needs_reconcile" : "refused", + summary: `Step refused (${dispatched.code}).`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: dispatched.code, + }; + } + tiersUsed.push(tier); + + const receipt = await options.coordinator.waitForReceipt(dispatched.pending.opId, receiptTimeoutMs); + if (receipt === undefined) { + return { + status: "needs_reconcile", + summary: "Step timed out awaiting execution receipt; reconcile before retrying.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: "RECEIPT_TIMEOUT", + }; + } + receipts.push(receipt); + + if (receipt.outcome === "preempted") { + return { + status: "needs_reconcile", + summary: `Interrupted (${receipt.refusalCode ?? "preempted"}); reconcile observed state before retrying.`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: receipt.refusalCode ?? "PREEMPTED", + }; + } + if (receipt.outcome === "refused") { + return { + status: "refused", + summary: `Operation refused (${receipt.refusalCode ?? "refused"}).`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: receipt.refusalCode ?? "REFUSED", + }; + } + + if (receipt.postSnapshotId !== undefined && receipt.postSnapshotId > dispatched.pending.boundSnapId) { + readbackObservedCount += 1; + } + if (plan.verifyReadback !== undefined) { + const afterState = options.coordinator.snapshot(now()); + if (!plan.verifyReadback(afterState.foreground)) { + return { + status: "needs_reconcile", + summary: "Observed post-action readback did not verify expected state change.", + stepsExecuted: receipts.length, + tiersUsed, + receipts, + refusalCode: "READBACK_MISMATCH", + }; + } + readbackObservedCount += 1; + } + } + + return { + status: "budget_exhausted", + summary: `Reached bounded step limit (${stepCap}).`, + stepsExecuted: receipts.length, + tiersUsed, + receipts, + }; +} diff --git a/apps/agent/src/plugins/control/profiles.ts b/apps/agent/src/plugins/control/profiles.ts new file mode 100644 index 0000000000..0bcc5444aa --- /dev/null +++ b/apps/agent/src/plugins/control/profiles.ts @@ -0,0 +1,267 @@ +// spec/app/control/profile.md, "Story: Apply and restore reversible OS profiles while preserving manual edits" + +/** Typed OS setting keys managed by reversible OS profiles. */ +export const PROFILE_SETTING_KEYS = [ + "dnd_mode", + "notification_silence", + "screen_timeout_seconds", + "home_shortcuts", + "media_volume", + "auto_brightness", +] as const; + +/** Typed OS setting key union. */ +export type ProfileSettingKey = (typeof PROFILE_SETTING_KEYS)[number]; + +const SETTING_KEY_SET: ReadonlySet = new Set(PROFILE_SETTING_KEYS); + +/** Named reversible OS profile target specification. */ +export interface ReversibleProfileSpec { + readonly profileId: string; + readonly displayName: string; + readonly targetValues: Readonly>>; +} + +/** Single setting diff computed during a pure preview. */ +export interface ProfileSettingChange { + readonly key: ProfileSettingKey; + readonly beforeValue: string | undefined; + readonly targetValue: string; +} + +/** Pure dry-run preview of a reversible OS profile. */ +export interface ProfilePreview { + readonly profileId: string; + readonly displayName: string; + readonly changes: readonly ProfileSettingChange[]; + readonly unchangedKeys: readonly ProfileSettingKey[]; +} + +/** Attribution record for one setting written by an applied profile. */ +export interface ProfileReceiptEntry { + readonly key: ProfileSettingKey; + readonly baselineValue: string | undefined; + readonly appliedValue: string; +} + +/** Immutable receipt created when applying a reversible OS profile. */ +export interface ProfileReceipt { + readonly receiptId: string; + readonly profileId: string; + readonly appliedAtMs: number; + readonly expiresAtMs: number; + readonly entries: readonly ProfileReceiptEntry[]; + readonly restored: boolean; +} + +/** Record of a manual user edit preserved untouched during restore. */ +export interface PreservedManualEdit { + readonly key: ProfileSettingKey; + readonly baselineValue: string | undefined; + readonly profileAppliedValue: string; + readonly currentUserValue: string | undefined; +} + +/** Structured outcome returned when restoring a profile receipt. */ +export interface ProfileRestoreResult { + readonly ok: boolean; + readonly receiptId: string; + readonly profileId: string; + readonly alreadyRestored: boolean; + readonly restoredKeys: readonly ProfileSettingKey[]; + readonly preservedManualEdits: readonly PreservedManualEdit[]; +} + +/** Whether `key` is a recognized reversible OS profile setting key. */ +export function isProfileSettingKey(key: string): key is ProfileSettingKey { + return SETTING_KEY_SET.has(key); +} + +/** Resolve a built-in reversible OS profile preset ("focus" or "recording"). */ +export function builtInProfileSpec(profileId: string): ReversibleProfileSpec | undefined { + switch (profileId.trim().toLowerCase()) { + case "focus": + return { + profileId: "focus", + displayName: "Focus Mode", + targetValues: { + dnd_mode: "priority", + notification_silence: "enabled", + }, + }; + case "recording": + return { + profileId: "recording", + displayName: "Recording Mode", + targetValues: { + dnd_mode: "alarms_only", + notification_silence: "enabled", + screen_timeout_seconds: "600", + home_shortcuts: "recording_pack", + }, + }; + default: + return undefined; + } +} + +/** + * In-memory typed read -> preview -> apply -> restore receipt controller for reversible OS + * profiles. Restores ONLY settings whose current live value still matches what the profile wrote, + * idempotently preserving any manual owner edits made mid-profile. + */ +export class ReversibleProfileStore { + private readonly live = new Map(); + private readonly receipts = new Map(); + private readonly restoreHistory = new Map(); + private nextReceiptSeq = 0; + + constructor(initial?: Readonly>>) { + if (initial !== undefined) { + for (const key of PROFILE_SETTING_KEYS) { + const val = initial[key]; + if (val !== undefined) this.live.set(key, val); + } + } + } + + /** Stage 1 (Read): Read current live values without mutating state. */ + readCurrent(keys: readonly ProfileSettingKey[] = PROFILE_SETTING_KEYS): Readonly>> { + const out: Partial> = {}; + for (const key of keys) { + const value = this.live.get(key); + if (value !== undefined) out[key] = value; + } + return out; + } + + /** Record a live manual edit made by the owner or synced from Android settings. */ + manualEdit(key: ProfileSettingKey, value: string | undefined): void { + if (value === undefined) { + this.live.delete(key); + } else { + this.live.set(key, value); + } + } + + /** Stage 2 (Preview): Pure dry-run diff showing exact changes with zero side effects. */ + preview(spec: ReversibleProfileSpec): ProfilePreview { + const changes: ProfileSettingChange[] = []; + const unchangedKeys: ProfileSettingKey[] = []; + for (const key of PROFILE_SETTING_KEYS) { + const target = spec.targetValues[key]; + if (target === undefined) continue; + const before = this.live.get(key); + if (before === target) { + unchangedKeys.push(key); + } else { + changes.push({ key, beforeValue: before, targetValue: target }); + } + } + return { + profileId: spec.profileId, + displayName: spec.displayName, + changes, + unchangedKeys, + }; + } + + /** Stage 3 (Apply): Write only changed settings and emit an immutable attribution receipt. */ + apply(spec: ReversibleProfileSpec, nowMs: number, durationMs = 0): ProfileReceipt { + const entries: ProfileReceiptEntry[] = []; + for (const key of PROFILE_SETTING_KEYS) { + const target = spec.targetValues[key]; + if (target === undefined) continue; + const baseline = this.live.get(key); + if (baseline !== target) { + this.live.set(key, target); + entries.push({ key, baselineValue: baseline, appliedValue: target }); + } + } + this.nextReceiptSeq += 1; + const receipt: ProfileReceipt = { + receiptId: `profile-${this.nextReceiptSeq}`, + profileId: spec.profileId, + appliedAtMs: nowMs, + expiresAtMs: durationMs > 0 ? nowMs + durationMs : 0, + entries, + restored: false, + }; + this.receipts.set(receipt.receiptId, receipt); + return receipt; + } + + /** + * Stage 4 (Restore): Idempotently revert ONLY settings still holding the profile's applied + * value, preserving every manual edit made mid-profile. + */ + restore(receiptId: string): ProfileRestoreResult { + const existing = this.receipts.get(receiptId); + if (existing === undefined) { + return { + ok: false, + receiptId, + profileId: "", + alreadyRestored: false, + restoredKeys: [], + preservedManualEdits: [], + }; + } + const priorRestore = this.restoreHistory.get(receiptId); + if (existing.restored && priorRestore !== undefined) { + return { ...priorRestore, alreadyRestored: true }; + } + const restoredKeys: ProfileSettingKey[] = []; + const preservedManualEdits: PreservedManualEdit[] = []; + for (const entry of existing.entries) { + const currentValue = this.live.get(entry.key); + if (currentValue === entry.appliedValue) { + if (entry.baselineValue === undefined) { + this.live.delete(entry.key); + } else { + this.live.set(entry.key, entry.baselineValue); + } + restoredKeys.push(entry.key); + } else { + preservedManualEdits.push({ + key: entry.key, + baselineValue: entry.baselineValue, + profileAppliedValue: entry.appliedValue, + currentUserValue: currentValue, + }); + } + } + this.receipts.set(receiptId, { ...existing, restored: true }); + const result: ProfileRestoreResult = { + ok: true, + receiptId, + profileId: existing.profileId, + alreadyRestored: false, + restoredKeys, + preservedManualEdits, + }; + this.restoreHistory.set(receiptId, result); + return result; + } + + /** Restore every active receipt whose expiry timestamp is at or before `nowMs`. */ + restoreExpired(nowMs: number): readonly ProfileRestoreResult[] { + const dueIds: string[] = []; + for (const receipt of this.receipts.values()) { + if (!receipt.restored && receipt.expiresAtMs > 0 && nowMs >= receipt.expiresAtMs) { + dueIds.push(receipt.receiptId); + } + } + return dueIds.map((id) => this.restore(id)); + } + + /** List active (unrestored) profile receipts. */ + activeReceipts(): readonly ProfileReceipt[] { + return [...this.receipts.values()].filter((receipt) => !receipt.restored); + } + + /** Return a specific receipt by id, or undefined. */ + getReceipt(receiptId: string): ProfileReceipt | undefined { + return this.receipts.get(receiptId); + } +} diff --git a/apps/agent/test/control-v2.test.ts b/apps/agent/test/control-v2.test.ts new file mode 100644 index 0000000000..28bf61c605 --- /dev/null +++ b/apps/agent/test/control-v2.test.ts @@ -0,0 +1,447 @@ +// spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease"; spec/app/control/profile.md, "Story: Apply and restore reversible OS profiles while preserving manual edits" +import { Effect } from "effect"; +import { describe, expect, it } from "vitest"; +import { + AlphaControlCoordinator, + CONTROL_ACTION_NAME, + CONTROL_CONTEXT_MAX_CHARS, + type ControlOpPayload, + type ControlReceiptRecord, + type DiscoveredAppFunction, + ReversibleProfileStore, + builtInProfileSpec, + classifyActionTier, + controlActions, + controlProvider, + detectTakeoverFromObservation, + formatCompactControlContext, + parseControlOp, + runPhoneUseLoop, + selectPreferredActionTier, +} from "../src/plugins/control.ts"; +import type { AgentAction, AgentRuntimeLike } from "../src/plugins/types.ts"; + +const emptyMessage = (text: string) => ({ content: { text } }) as unknown as Parameters[1]; +const emptyState = {} as unknown as NonNullable[2]>; +const fakeRuntime = {} as unknown as AgentRuntimeLike; + +describe("Full APK Control (Phone Use) v2", () => { + // spec/app/control/index.md, "The control state tracks the active capability tier, latest observation, dual-mode bounded lease, single in-flight operation, reconciliation flag, takeover pause, and kill-switch" + it("scopes AppFunctions dynamically per foreground app and strictly stays under 10k chars", async () => { + const coordinator = new AlphaControlCoordinator(); + for (let i = 0; i < 40; i += 1) { + const pkg = `com.other.app${i}`; + const bloatedFns: DiscoveredAppFunction[] = Array.from({ length: 16 }, (_, idx) => ({ + functionId: `tool_${idx}.runAction`, + packageName: pkg, + displayName: `Action ${idx}`, + description: "Very detailed tool schema description ".repeat(10), + parameters: ["argA", "argB", "argC", "argD"], + })); + coordinator.registerDiscoveredFunctions(pkg, bloatedFns); + } + coordinator.registerDiscoveredFunctions("org.mozilla.firefox", [ + { + functionId: "browser.openTab", + packageName: "org.mozilla.firefox", + displayName: "Open Tab", + description: "Open an HTTPS URL in a new browser tab.", + parameters: ["url", "pinned"], + }, + { + functionId: "browser.toggleAutoplay", + packageName: "org.mozilla.firefox", + displayName: "Toggle Autoplay", + description: "Enable or disable media autoplay.", + parameters: ["enabled"], + }, + ]); + + const hugeNodes = Array.from({ length: 150 }, (_, idx) => ({ + nodeId: `n_${idx}`, + role: "Button", + text: `Interactive Control Element Number ${idx} ${"details ".repeat(30)}`, + bounds: { left: 0, top: idx * 20, right: 400, bottom: idx * 20 + 18 }, + clickable: true, + editable: false, + scrollable: false, + sensitive: false, + })); + + coordinator.observe({ + tier: "TierPrivileged", + capabilities: ["ui.observe.v1", "ui.act.v1", "app.functions.v2", "ui.virtual_display.v1"], + packageName: "org.mozilla.firefox", + activityName: "org.mozilla.fenix.HomeActivity", + webUri: "https://example.org", + protection: "ScreenClear", + windowCount: 1, + nodes: hugeNodes, + }, 1_000); + + const provider = controlProvider(coordinator, () => 1_000); + const context = (await provider.get(fakeRuntime, emptyMessage("context"), emptyState)).text ?? ""; + + expect(context.length).toBeGreaterThan(100); + expect(context.length).toBeLessThan(10_000); + expect(context.length).toBeLessThanOrEqual(CONTROL_CONTEXT_MAX_CHARS); + expect(context).toContain("browser.openTab"); + expect(context).toContain("browser.toggleAutoplay"); + expect(context).not.toContain("com.other.app0"); + expect(context).not.toContain("tool_0.runAction"); + + const tightContext = formatCompactControlContext({ + ...coordinator.snapshot(1_000), + maxChars: 600, + }); + expect(tightContext.length).toBeLessThanOrEqual(600); + }); + + // spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease" + it("enforces the 4-tier action priority ladder and opt-in screenshot gate", () => { + expect(classifyActionTier("app_launch_package")).toBe("direct_os"); + expect(classifyActionTier("profile_apply")).toBe("direct_os"); + expect(classifyActionTier("virtual_display_create")).toBe("direct_os"); + expect(classifyActionTier("app_functions_discover")).toBe("app_functions"); + expect(classifyActionTier("app_function_execute")).toBe("app_functions"); + expect(classifyActionTier("ui_click")).toBe("accessibility_tree"); + expect(classifyActionTier("ui_capture_screen")).toBe("screenshot_fallback"); + + expect(selectPreferredActionTier({ + hasDirectOsTool: true, + hasMatchingAppFunction: true, + hasAccessibilityTarget: true, + allowScreenshotFallback: true, + })).toBe("direct_os"); + + expect(selectPreferredActionTier({ + hasDirectOsTool: false, + hasMatchingAppFunction: true, + hasAccessibilityTarget: true, + allowScreenshotFallback: true, + })).toBe("app_functions"); + + expect(selectPreferredActionTier({ + hasDirectOsTool: false, + hasMatchingAppFunction: false, + hasAccessibilityTarget: true, + allowScreenshotFallback: true, + })).toBe("accessibility_tree"); + + expect(selectPreferredActionTier({ + hasDirectOsTool: false, + hasMatchingAppFunction: false, + hasAccessibilityTarget: false, + allowScreenshotFallback: false, + })).toBeNull(); + + expect(selectPreferredActionTier({ + hasDirectOsTool: false, + hasMatchingAppFunction: false, + hasAccessibilityTarget: false, + allowScreenshotFallback: true, + })).toBe("screenshot_fallback"); + }); + + // spec/app/control/index.md, "The phone finishes an in-flight operation only with observed post-action readback for UI steps, and preemption flags state reconciliation before any retry" + it("runs autonomous multi-step Phone Use loop with AppFunctions -> AX progression, readback verification, and post-interrupt reconciliation", async () => { + let clock = 10_000; + const coordinator = new AlphaControlCoordinator(); + coordinator.observe({ + tier: "TierPrivileged", + capabilities: ["ui.observe.v1", "ui.act.v1", "app.functions.v2", "ui.virtual_display.v1"], + packageName: "org.mozilla.firefox", + activityName: "org.mozilla.fenix.SettingsActivity", + protection: "ScreenClear", + windowCount: 1, + nodes: [ + { + nodeId: "autoplay_toggle", + role: "Switch", + text: "Autoplay: On", + bounds: { left: 20, top: 200, right: 400, bottom: 260 }, + clickable: true, + editable: false, + scrollable: false, + sensitive: false, + }, + ], + }, clock); + + const badVirtualOnAx = new AlphaControlCoordinator(); + badVirtualOnAx.observe({ + tier: "TierAccessibility", + packageName: "org.mozilla.firefox", + protection: "ScreenClear", + nodes: [], + }, clock); + expect(badVirtualOnAx.grantLease({ + packageName: "org.mozilla.firefox", + maxOps: 4, + durationMs: 60_000, + mode: "ModeVirtualDisplay", + displayId: 7, + }, clock)).toMatchObject({ ok: false, code: "INVALID_EXECUTION_MODE" }); + + const granted = coordinator.grantLease({ + packageName: "org.mozilla.firefox", + maxOps: 6, + durationMs: 60_000, + mode: "ModeVirtualDisplay", + displayId: 7, + }, clock); + expect(granted.ok).toBe(true); + + const refusedShot = await runPhoneUseLoop({ + coordinator, + targetPackage: "org.mozilla.firefox", + maxSteps: 3, + allowScreenshotFallback: false, + now: () => clock, + planNextStep: () => ({ kind: "op", op: { type: "ui_capture_screen", maxWidth: 720, quality: 70 } }), + }); + expect(refusedShot).toMatchObject({ status: "refused", refusalCode: "SCREENSHOT_FALLBACK_DISABLED" }); + + let step = 0; + const loopPromise = runPhoneUseLoop({ + coordinator, + targetPackage: "org.mozilla.firefox", + maxSteps: 4, + allowScreenshotFallback: false, + now: () => clock, + planNextStep: ({ compactContext, state }) => { + expect(compactContext.length).toBeLessThan(10_000); + step += 1; + if (step === 1) { + return { kind: "op", op: { type: "app_functions_discover", packageName: "org.mozilla.firefox" } }; + } + if (step === 2) { + return { + kind: "op", + op: { + type: "ui_click", + snapshotId: state.foreground.snapId, + expectedPackage: "org.mozilla.firefox", + nodeId: "autoplay_toggle", + }, + verifyReadback: (after) => after.nodes.some((n) => n.text === "Autoplay: Off"), + }; + } + return { kind: "done", summary: "Turned off autoplay and verified readback.", verifiedByReadback: true }; + }, + }); + + await Promise.resolve(); + const pending1 = coordinator.nextPending(clock); + expect(pending1?.op.type).toBe("app_functions_discover"); + coordinator.recordReceipt({ + opId: pending1!.opId, + outcome: "done", + result: { + packageName: "org.mozilla.firefox", + functions: [ + { functionId: "browser.openTab", packageName: "org.mozilla.firefox", parameters: ["url"] }, + ], + }, + }, clock + 50); + + await Effect.runPromise(Effect.sleep("10 millis")); + const pending2 = coordinator.nextPending(clock); + expect(pending2?.op.type).toBe("ui_click"); + const missingReadback = coordinator.recordReceipt({ + opId: pending2!.opId, + outcome: "done", + }, clock + 100); + expect(missingReadback).toMatchObject({ ok: false, code: "READBACK_REQUIRED" }); + + const obsAfter = coordinator.observe({ + tier: "TierPrivileged", + packageName: "org.mozilla.firefox", + activityName: "org.mozilla.fenix.SettingsActivity", + protection: "ScreenClear", + nodes: [ + { + nodeId: "autoplay_toggle", + role: "Switch", + text: "Autoplay: Off", + bounds: { left: 20, top: 200, right: 400, bottom: 260 }, + clickable: true, + editable: false, + scrollable: false, + sensitive: false, + }, + ], + }, clock + 120); + expect(obsAfter.ok).toBe(true); + if (!obsAfter.ok) throw new Error("expected ok observation"); + coordinator.recordReceipt({ + opId: pending2!.opId, + outcome: "done", + postSnapshotId: obsAfter.snapshotId, + }, clock + 130); + + const loopResult = await loopPromise; + expect(loopResult.status).toBe("completed"); + expect(loopResult.tiersUsed).toEqual(["app_functions", "accessibility_tree"]); + expect(coordinator.scopedAppFunctionsFor("org.mozilla.firefox").map((fn) => fn.functionId)).toEqual(["browser.openTab"]); + + coordinator.observe({ + tier: "TierPrivileged", + packageName: "org.mozilla.firefox", + activityName: "org.mozilla.fenix.HomeActivity", + protection: "ScreenClear", + nodes: [ + { + nodeId: "pay_btn", + role: "Button", + text: "Pay now $19.99", + bounds: { left: 10, top: 100, right: 300, bottom: 160 }, + clickable: true, + editable: false, + scrollable: false, + sensitive: false, + }, + ], + }, clock + 200); + expect(detectTakeoverFromObservation(coordinator.snapshot(clock + 200).foreground, 1)).toBe("TakeoverPayment"); + + const takeoverRun = await runPhoneUseLoop({ + coordinator, + targetPackage: "org.mozilla.firefox", + maxSteps: 2, + now: () => clock + 200, + planNextStep: () => ({ kind: "done", summary: "should never reach", verifiedByReadback: true }), + }); + expect(takeoverRun).toMatchObject({ + status: "paused_for_takeover", + takeoverReason: "TakeoverPayment", + surfacedToForeground: true, + }); + expect(coordinator.snapshot(clock + 200)).toMatchObject({ + takeover: "TakeoverPayment", + needsReconcile: true, + lease: { mode: "ModeForeground", displayId: 0 }, + }); + + expect(coordinator.resumeAfterTakeover()).toMatchObject({ ok: false, code: "RECONCILIATION_REQUIRED" }); + expect(coordinator.dispatch( + { type: "ui_scroll", snapshotId: coordinator.snapshot(clock + 200).foreground.snapId, expectedPackage: "org.mozilla.firefox", direction: "down" }, + clock + 250, + )).toMatchObject({ ok: false, code: "RECONCILIATION_REQUIRED" }); + + coordinator.observe({ + tier: "TierPrivileged", + packageName: "org.mozilla.firefox", + activityName: "org.mozilla.fenix.HomeActivity", + protection: "ScreenClear", + nodes: [], + }, clock + 300); + expect(coordinator.resumeAfterTakeover().ok).toBe(true); + expect(coordinator.snapshot(clock + 300)).toMatchObject({ needsReconcile: false, takeover: "TakeoverNone" }); + clock += 300; + }); + + // spec/app/control/index.md, "The kill-switch immediately revokes any active lease, clears any in-flight operation, releases any virtual display, and signals the native bridge and overlay" + it("aborts Phone Use loop immediately on AbortSignal and app-switch", async () => { + const coordinator = new AlphaControlCoordinator(); + coordinator.observe({ + tier: "TierPrivileged", + packageName: "org.mozilla.firefox", + protection: "ScreenClear", + nodes: [], + }, 1_000); + coordinator.grantLease({ + packageName: "org.mozilla.firefox", + maxOps: 4, + durationMs: 60_000, + mode: "ModeVirtualDisplay", + displayId: 5, + }, 1_000); + + const abortController = new AbortController(); + abortController.abort(); + const aborted = await runPhoneUseLoop({ + coordinator, + targetPackage: "org.mozilla.firefox", + maxSteps: 4, + signal: abortController.signal, + now: () => 1_000, + planNextStep: () => ({ kind: "done", summary: "never", verifiedByReadback: true }), + }); + expect(aborted.status).toBe("aborted"); + expect(coordinator.snapshot(1_000)).toMatchObject({ + killed: true, + lease: { status: "LeaseRevoked", mode: "ModeForeground", displayId: 0 }, + }); + }); + + // spec/app/control/profile.md, "Story: Apply and restore reversible OS profiles while preserving manual edits" + it("supports reversible OS profiles (read -> preview -> apply -> restore preserving manual edits) via store and DEVICE_CONTROL", async () => { + const store = new ReversibleProfileStore({ + dnd_mode: "off", + notification_silence: "disabled", + screen_timeout_seconds: "60", + home_shortcuts: "default_pack", + }); + const coordinator = new AlphaControlCoordinator(store); + coordinator.observe({ + tier: "TierPrivileged", + packageName: "org.mozilla.firefox", + protection: "ScreenClear", + nodes: [], + }, 1_000); + const [action] = controlActions(coordinator, () => 2_000, 0); + expect(action.name).toBe(CONTROL_ACTION_NAME); + + expect(parseControlOp({ type: "virtual_display_create", packageName: "org.mozilla.firefox", width: 1080, height: 2400, densityDpi: 420 })).toBeDefined(); + expect(parseControlOp({ type: "profile_preview", profileId: "recording" })).toBeDefined(); + expect(parseControlOp({ type: "profile_apply", profileId: "recording", durationMs: 2_700_000 })).toBeDefined(); + expect(parseControlOp({ type: "profile_restore", receiptId: "profile-1" })).toBeDefined(); + + const previewRes = await action.handler(fakeRuntime, emptyMessage("preview recording"), emptyState, { + parameters: { op: { type: "profile_preview", profileId: "recording" } }, + }); + expect(previewRes?.success).toBe(true); + expect(store.readCurrent()).toMatchObject({ dnd_mode: "off", screen_timeout_seconds: "60" }); + + const applyRes = await action.handler(fakeRuntime, emptyMessage("apply recording"), emptyState, { + parameters: { op: { type: "profile_apply", profileId: "recording", durationMs: 2_700_000 } }, + }); + expect(applyRes?.success).toBe(true); + const receiptId = (applyRes?.data as { receipt: { receiptId: string } }).receipt.receiptId; + expect(store.readCurrent()).toMatchObject({ + dnd_mode: "alarms_only", + notification_silence: "enabled", + screen_timeout_seconds: "600", + home_shortcuts: "recording_pack", + }); + + store.manualEdit("screen_timeout_seconds", "180"); + + const restoreRes = await action.handler(fakeRuntime, emptyMessage("restore recording"), emptyState, { + parameters: { op: { type: "profile_restore", receiptId } }, + }); + expect(restoreRes?.success).toBe(true); + expect(store.readCurrent()).toEqual({ + dnd_mode: "off", + notification_silence: "disabled", + screen_timeout_seconds: "180", + home_shortcuts: "default_pack", + }); + + store.manualEdit("dnd_mode", "total_silence"); + const repeatRestore = store.restore(receiptId); + expect(repeatRestore).toMatchObject({ ok: true, alreadyRestored: true }); + expect(store.readCurrent().dnd_mode).toBe("total_silence"); + + const focus = builtInProfileSpec("focus")!; + store.apply(focus, 5_000, 1_000); + expect(store.readCurrent().dnd_mode).toBe("priority"); + const expired = store.restoreExpired(6_000); + expect(expired).toHaveLength(1); + expect(store.readCurrent().dnd_mode).toBe("total_silence"); + }); +}); diff --git a/apps/app/android/alpha-control/src/main/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl b/apps/app/android/alpha-control/src/main/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl index f1354d3e5b..bd7be97533 100644 --- a/apps/app/android/alpha-control/src/main/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl +++ b/apps/app/android/alpha-control/src/main/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl @@ -9,4 +9,10 @@ interface IAlphaControlBridge { boolean injectKeyEvent(int keyCode, int metaState, int action); boolean injectMotionEvent(int action, float x, float y, long downTime, long eventTime); boolean setAlphaAccessibilityEnabled(boolean enabled); + int createVirtualDisplay(String name, int width, int height, int densityDpi); + boolean releaseVirtualDisplay(int displayId); + boolean launchPackageOnDisplay(int displayId, String packageName, String activityName); + int[] listVirtualDisplays(); + boolean injectKeyEventOnDisplay(int displayId, int keyCode, int metaState, int action); + boolean injectMotionEventOnDisplay(int displayId, int action, float x, float y, long downTime, long eventTime); } diff --git a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlBridgeClient.java b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlBridgeClient.java index b4ff81df3c..d5cb12242c 100644 --- a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlBridgeClient.java +++ b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlBridgeClient.java @@ -12,6 +12,7 @@ import android.os.Looper; import android.os.ParcelFileDescriptor; import android.os.RemoteException; +import android.view.Display; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -20,7 +21,7 @@ import java.util.concurrent.atomic.AtomicReference; /** - * Verifies and binds the optional platform-signed AOSP AlphaControlBridge service (Tier 2). + * Verifies and binds the optional platform-signed AOSP AlphaControlBridge service (Tier 2, v1/v2). * Falls back cleanly to disconnected state on stock Android (Tier 1). */ public final class AlphaControlBridgeClient { @@ -30,8 +31,11 @@ public final class AlphaControlBridgeClient { /** Component class name of the platform-signed AOSP control bridge service. */ public static final String BRIDGE_CLASS = "ai.alphacompute.control.AlphaControlBridgeService"; - /** Supported AIDL wire protocol version. */ - public static final int EXPECTED_PROTOCOL_VERSION = 1; + /** Minimum supported AIDL wire protocol version (v1 backwards compatibility). */ + public static final int MIN_PROTOCOL_VERSION = 1; + + /** Latest supported AIDL wire protocol version (v2 adds trusted VirtualDisplay & per-display input). */ + public static final int EXPECTED_PROTOCOL_VERSION = 2; /** Capability bitmask for unthrottled display capture with captureSecureLayers=false. */ public static final int CAP_CAPTURE_DISPLAY = 1; @@ -42,11 +46,18 @@ public final class AlphaControlBridgeClient { /** Capability bitmask for owner-initiated AccessibilityService enable/disable toggle. */ public static final int CAP_TOGGLE_ACCESSIBILITY = 4; + /** Capability bitmask for managed trusted VirtualDisplay lifecycle and launch (v2). */ + public static final int CAP_VIRTUAL_DISPLAY = 8; + + /** Capability bitmask for per-display input injection targeting owned virtual displays (v2). */ + public static final int CAP_PER_DISPLAY_INPUT = 16; + private static final int MAX_CAPTURE_BYTES = 1_400_000; private final Context appContext; private final AtomicReference binderRef = new AtomicReference<>(); private final AtomicReference capabilitiesRef = new AtomicReference<>(0); + private final AtomicReference protocolVersionRef = new AtomicReference<>(0); private volatile boolean bound; private volatile CountDownLatch connectLatch = new CountDownLatch(1); @@ -55,16 +66,16 @@ public final class AlphaControlBridgeClient { public void onServiceConnected(ComponentName name, IBinder service) { IAlphaControlBridge proxy = IAlphaControlBridge.Stub.asInterface(service); try { - if (proxy != null && proxy.getProtocolVersion() == EXPECTED_PROTOCOL_VERSION) { + int version = proxy == null ? 0 : proxy.getProtocolVersion(); + if (proxy != null && version >= MIN_PROTOCOL_VERSION && version <= EXPECTED_PROTOCOL_VERSION) { + protocolVersionRef.set(version); capabilitiesRef.set(proxy.getCapabilities()); binderRef.set(proxy); } else { - binderRef.set(null); - capabilitiesRef.set(0); + clearBindingState(); } } catch (RemoteException | SecurityException unavailable) { - binderRef.set(null); - capabilitiesRef.set(0); + clearBindingState(); } finally { connectLatch.countDown(); } @@ -72,21 +83,18 @@ public void onServiceConnected(ComponentName name, IBinder service) { @Override public void onServiceDisconnected(ComponentName name) { - binderRef.set(null); - capabilitiesRef.set(0); + clearBindingState(); } @Override public void onBindingDied(ComponentName name) { - binderRef.set(null); - capabilitiesRef.set(0); + clearBindingState(); connectLatch.countDown(); } @Override public void onNullBinding(ComponentName name) { - binderRef.set(null); - capabilitiesRef.set(0); + clearBindingState(); connectLatch.countDown(); } }; @@ -96,6 +104,12 @@ public AlphaControlBridgeClient(Context context) { this.appContext = context.getApplicationContext(); } + private void clearBindingState() { + binderRef.set(null); + capabilitiesRef.set(0); + protocolVersionRef.set(0); + } + /** Verify that the installed bridge APK is a system package signed with the platform certificate. */ public static boolean isVerifiedPlatformBridgeInstalled(PackageManager pm) { if (pm == null) return false; @@ -152,8 +166,7 @@ public synchronized void disconnect() { } bound = false; } - binderRef.set(null); - capabilitiesRef.set(0); + clearBindingState(); } /** Whether a protocol-verified platform bridge is currently connected. */ @@ -162,6 +175,11 @@ public boolean isConnected() { return proxy != null && proxy.asBinder().isBinderAlive(); } + /** Return the negotiated protocol version (0 if disconnected, 1 or 2 when connected). */ + public int protocolVersion() { + return isConnected() ? protocolVersionRef.get() : 0; + } + /** Return the cached capability bitmask reported by the verified bridge. */ public int capabilities() { return isConnected() ? capabilitiesRef.get() : 0; @@ -177,10 +195,21 @@ public boolean supportsInjectEvents() { return (capabilities() & CAP_INJECT_EVENTS) != 0; } + /** Whether the connected v2 bridge supports managed trusted VirtualDisplays. */ + public boolean supportsVirtualDisplay() { + return protocolVersion() >= 2 && (capabilities() & CAP_VIRTUAL_DISPLAY) != 0; + } + + /** Whether the connected v2 bridge supports per-display key/motion injection. */ + public boolean supportsPerDisplayInput() { + return protocolVersion() >= 2 && (capabilities() & CAP_PER_DISPLAY_INPUT) != 0; + } + /** Capture display image bytes via the platform bridge (always non-secure layers only). */ public byte[] captureDisplayBytes(int displayId, int maxWidth, int jpegQuality) { IAlphaControlBridge proxy = binderRef.get(); if (proxy == null || !supportsCaptureDisplay()) return null; + if (displayId != Display.DEFAULT_DISPLAY && !supportsVirtualDisplay()) return null; try (ParcelFileDescriptor pfd = proxy.captureDisplay(displayId, maxWidth, jpegQuality)) { if (pfd == null) return null; try (InputStream in = new ParcelFileDescriptor.AutoCloseInputStream(pfd); @@ -200,28 +229,93 @@ public byte[] captureDisplayBytes(int displayId, int maxWidth, int jpegQuality) } } - /** Inject an allowlisted key event via the platform bridge. */ + /** Inject an allowlisted key event on the default display via the platform bridge. */ public boolean injectKeyEvent(int keyCode, int metaState, int action) { + return injectKeyEventOnDisplay(Display.DEFAULT_DISPLAY, keyCode, metaState, action); + } + + /** Inject an allowlisted key event on a specific owned display (v2) or default display (v1/v2). */ + public boolean injectKeyEventOnDisplay(int displayId, int keyCode, int metaState, int action) { IAlphaControlBridge proxy = binderRef.get(); if (proxy == null || !supportsInjectEvents()) return false; try { + if (supportsPerDisplayInput()) { + return proxy.injectKeyEventOnDisplay(displayId, keyCode, metaState, action); + } + if (displayId != Display.DEFAULT_DISPLAY) return false; return proxy.injectKeyEvent(keyCode, metaState, action); } catch (RemoteException | SecurityException failed) { return false; } } - /** Inject a raw motion event via the platform bridge. */ + /** Inject a raw motion event on the default display via the platform bridge. */ public boolean injectMotionEvent(int action, float x, float y, long downTime, long eventTime) { + return injectMotionEventOnDisplay(Display.DEFAULT_DISPLAY, action, x, y, downTime, eventTime); + } + + /** Inject a raw motion event on a specific owned display (v2) or default display (v1/v2). */ + public boolean injectMotionEventOnDisplay( + int displayId, int action, float x, float y, long downTime, long eventTime + ) { IAlphaControlBridge proxy = binderRef.get(); if (proxy == null || !supportsInjectEvents()) return false; try { + if (supportsPerDisplayInput()) { + return proxy.injectMotionEventOnDisplay(displayId, action, x, y, downTime, eventTime); + } + if (displayId != Display.DEFAULT_DISPLAY) return false; return proxy.injectMotionEvent(action, x, y, downTime, eventTime); } catch (RemoteException | SecurityException failed) { return false; } } + /** Create a trusted non-secure VirtualDisplay on the v2 platform bridge. */ + public int createVirtualDisplay(String name, int width, int height, int densityDpi) { + IAlphaControlBridge proxy = binderRef.get(); + if (proxy == null || !supportsVirtualDisplay()) return Display.INVALID_DISPLAY; + try { + return proxy.createVirtualDisplay(name, width, height, densityDpi); + } catch (RemoteException | SecurityException failed) { + return Display.INVALID_DISPLAY; + } + } + + /** Release a previously created VirtualDisplay on the v2 platform bridge. */ + public boolean releaseVirtualDisplay(int displayId) { + IAlphaControlBridge proxy = binderRef.get(); + if (proxy == null || !supportsVirtualDisplay() || displayId <= Display.DEFAULT_DISPLAY) return false; + try { + return proxy.releaseVirtualDisplay(displayId); + } catch (RemoteException | SecurityException failed) { + return false; + } + } + + /** Launch an allowlisted package/activity onto {@code displayId} via the v2 platform bridge. */ + public boolean launchPackageOnDisplay(int displayId, String packageName, String activityName) { + IAlphaControlBridge proxy = binderRef.get(); + if (proxy == null || !supportsVirtualDisplay()) return false; + try { + return proxy.launchPackageOnDisplay(displayId, packageName, activityName == null ? "" : activityName); + } catch (RemoteException | SecurityException failed) { + return false; + } + } + + /** Return sorted active VirtualDisplay ids owned by the v2 platform bridge. */ + public int[] listVirtualDisplays() { + IAlphaControlBridge proxy = binderRef.get(); + if (proxy == null || !supportsVirtualDisplay()) return new int[0]; + try { + int[] ids = proxy.listVirtualDisplays(); + return ids == null ? new int[0] : ids; + } catch (RemoteException | SecurityException failed) { + return new int[0]; + } + } + /** Toggle Alpha's own AccessibilityService on or off after explicit owner consent. */ public boolean setAlphaAccessibilityEnabled(boolean enabled) { IAlphaControlBridge proxy = binderRef.get(); diff --git a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlPolicy.java b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlPolicy.java index c51666c61f..d861c5ccec 100644 --- a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlPolicy.java +++ b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaControlPolicy.java @@ -191,6 +191,12 @@ public static boolean requiresSnapshot(String opType) { return opType != null && !"app_launch_package".equals(opType) && !"app_open_url".equals(opType) - && !"app_functions_discover".equals(opType); + && !"app_functions_discover".equals(opType) + && !"virtual_display_create".equals(opType) + && !"virtual_display_release".equals(opType) + && !"virtual_display_launch".equals(opType) + && !"profile_preview".equals(opType) + && !"profile_apply".equals(opType) + && !"profile_restore".equals(opType); } } diff --git a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaUiControlExecutor.java b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaUiControlExecutor.java index 70b35663a8..b6a3b07ea3 100644 --- a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaUiControlExecutor.java +++ b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AlphaUiControlExecutor.java @@ -104,6 +104,9 @@ public static void setOverlayBridge(OverlayBridge bridge) { private final Context appContext; private final NativeAgentTransport transport; private final AlphaControlBridgeClient bridgeClient; + private final AppFunctionsBridge appFunctionsBridge; + private final VirtualDisplaySessionManager sessionManager; + private final ReversibleProfileController profileController; private final OperationDispatcher dispatcher; private final ObservationPusher observationPusher; private final BooleanSupplier accessibilityLiveSupplier; @@ -140,10 +143,47 @@ public AlphaUiControlExecutor(Context context, NativeAgentTransport transport) { ObservationPusher customObservationPusher, BooleanSupplier accessibilityLiveSupplier, long postActuationSettleMs + ) { + this( + context, + transport, + customDispatcher, + customObservationPusher, + accessibilityLiveSupplier, + postActuationSettleMs, + null, + null, + null + ); + } + + AlphaUiControlExecutor( + Context context, + NativeAgentTransport transport, + OperationDispatcher customDispatcher, + ObservationPusher customObservationPusher, + BooleanSupplier accessibilityLiveSupplier, + long postActuationSettleMs, + AppFunctionsBridge customAppFunctionsBridge, + VirtualDisplaySessionManager customSessionManager, + ReversibleProfileController customProfileController ) { this.appContext = context == null ? null : context.getApplicationContext(); this.transport = transport; this.bridgeClient = this.appContext == null ? null : new AlphaControlBridgeClient(this.appContext); + this.appFunctionsBridge = customAppFunctionsBridge != null + ? customAppFunctionsBridge + : new AppFunctionsBridge(this.appContext); + this.sessionManager = customSessionManager != null + ? customSessionManager + : new VirtualDisplaySessionManager(VirtualDisplaySessionManager.fromClient(this.bridgeClient), null); + this.profileController = customProfileController != null + ? customProfileController + : new ReversibleProfileController( + this.appContext != null + ? new ReversibleProfileController.AndroidSettingStore(this.appContext) + : new ReversibleProfileController.InMemorySettingStore(null) + ); this.dispatcher = customDispatcher != null ? customDispatcher : this::executeOperation; this.observationPusher = customObservationPusher != null ? customObservationPusher : this::pushObservation; this.accessibilityLiveSupplier = accessibilityLiveSupplier != null @@ -178,10 +218,11 @@ public void start() { } } - /** Stop polling, disconnect any bound Tier-2 platform bridge, and shut down daemon workers cleanly. */ + /** Stop polling, release any managed VirtualDisplay, disconnect any bound Tier-2 bridge, and shut down workers cleanly. */ public void stop() { if (!running.compareAndSet(true, false)) return; AlphaAccessibilityService.setControlListener(null); + sessionManager.stopSession("executor_stop"); if (bridgeClient != null) { bridgeClient.disconnect(); } @@ -231,12 +272,16 @@ public List currentCapabilities() { if (tier == AlphaControlPolicy.ControlTier.TierPrivileged && bridgeClient != null) { if (bridgeClient.supportsCaptureDisplay()) caps.add("ui.screenshot.v1"); if (bridgeClient.supportsInjectEvents()) caps.add("ui.inject.v1"); + if (bridgeClient.supportsVirtualDisplay()) caps.add("ui.virtual_display.v1"); + if (bridgeClient.supportsPerDisplayInput()) caps.add("ui.per_display_input.v1"); } else { caps.add("ui.screenshot.throttled.v1"); } if (hasAppFunctionsManager()) { caps.add("app.functions.v1"); + caps.add("app.functions.v2"); } + caps.add("os.profile.reversible.v1"); return caps; } @@ -269,6 +314,7 @@ public void onForegroundChanged(String packageName, String activityName) { @Override public void onPhysicalPreemption(String packageName) { + sessionManager.stopSession("user_touch"); submitInterrupt(() -> postInterrupt("user_touch", packageName)); } @@ -399,7 +445,8 @@ && shouldRefreshPostActuation(opType) /** Execute a validated typed control operation against Android APIs with strict safety checks. */ public StepOutcome executeOperation(JSONObject op, int boundSnapId, String expectedPackage) { String type = op.optString("type", ""); - if (AlphaControlPolicy.isBlockedTarget(expectedPackage, null)) { + boolean isProfileOp = "profile_preview".equals(type) || "profile_apply".equals(type) || "profile_restore".equals(type); + if (!isProfileOp && !"virtual_display_release".equals(type) && AlphaControlPolicy.isBlockedTarget(expectedPackage, null)) { return new StepOutcome("refused", "BLOCKED_PACKAGE", null); } if (AlphaControlPolicy.requiresSnapshot(type)) { @@ -415,13 +462,22 @@ public StepOutcome executeOperation(JSONObject op, int boundSnapId, String expec try { switch (type) { case "app_launch_package": - return executeLaunchPackage(op.optString("packageName", ""), expectedPackage); + return executeLaunchPackage( + op.optString("packageName", ""), + expectedPackage, + op.optInt("displayId", Display.DEFAULT_DISPLAY), + op.optString("activityName", "") + ); case "app_open_url": return executeOpenUrl(op.optString("url", ""), op.optString("packageName", ""), expectedPackage); case "ui_read_tree": return executeReadTree(op.optBoolean("includeNonInteractive", false), op.optInt("maxNodes", 120)); case "ui_capture_screen": - return executeCaptureScreen(op.optInt("maxWidth", 720), op.optInt("quality", 70)); + return executeCaptureScreen( + op.optInt("maxWidth", 720), + op.optInt("quality", 70), + op.optInt("displayId", sessionManager.currentSnapshot().displayId) + ); case "ui_click": return executeClick(op); case "ui_set_text": @@ -429,15 +485,30 @@ public StepOutcome executeOperation(JSONObject op, int boundSnapId, String expec case "ui_scroll": return executeScroll(op); case "ui_key_event": - return executeKeyEvent(op.optString("keyCode", "")); + return executeKeyEvent( + op.optString("keyCode", ""), + op.optInt("displayId", sessionManager.currentSnapshot().displayId) + ); case "ui_gesture": return executeGesture(op); case "ui_global_action": return executeGlobalAction(op.optString("action", "")); case "app_functions_discover": - return executeAppFunctionsDiscover(op.optString("packageName", "")); + return executeAppFunctionsDiscover(op.optString("packageName", expectedPackage)); case "app_function_execute": - return executeAppFunction(op); + return executeAppFunction(op, expectedPackage); + case "virtual_display_create": + return executeVirtualDisplayCreate(op, expectedPackage); + case "virtual_display_release": + return executeVirtualDisplayRelease(op); + case "virtual_display_launch": + return executeVirtualDisplayLaunch(op, expectedPackage); + case "profile_preview": + return executeProfilePreview(op); + case "profile_apply": + return executeProfileApply(op); + case "profile_restore": + return executeProfileRestore(op); default: return new StepOutcome("refused", "UNKNOWN_OPERATION", null); } @@ -460,16 +531,25 @@ public void postInterrupt(String reason, String packageName) { } } - private StepOutcome executeLaunchPackage(String packageName, String expectedPackage) { + private StepOutcome executeLaunchPackage(String packageName, String expectedPackage, int displayId, String activityName) { String explicitPkg = packageName == null ? "" : packageName.trim(); String leasedPkg = expectedPackage == null ? "" : expectedPackage.trim(); if (!explicitPkg.isEmpty() && !leasedPkg.isEmpty() && !explicitPkg.equals(leasedPkg)) { return new StepOutcome("refused", "PACKAGE_MISMATCH", null); } String targetPkg = !explicitPkg.isEmpty() ? explicitPkg : leasedPkg; - if (!AlphaControlPolicy.isValidPackageName(targetPkg) || AlphaControlPolicy.isBlockedTarget(targetPkg, null)) { + if (!AlphaControlPolicy.isValidPackageName(targetPkg) || AlphaControlPolicy.isBlockedTarget(targetPkg, activityName)) { return new StepOutcome("refused", "BLOCKED_PACKAGE", null); } + if (displayId > Display.DEFAULT_DISPLAY) { + if (bridgeClient == null || !bridgeClient.supportsVirtualDisplay()) { + return new StepOutcome("refused", "VIRTUAL_DISPLAY_UNAVAILABLE", null); + } + boolean launched = bridgeClient.launchPackageOnDisplay(displayId, targetPkg, activityName); + return launched + ? new StepOutcome("done", null, null) + : new StepOutcome("refused", "VIRTUAL_DISPLAY_LAUNCH_FAILED", null); + } if (appContext == null) return new StepOutcome("refused", "CONTEXT_UNAVAILABLE", null); Intent intent = appContext.getPackageManager().getLaunchIntentForPackage(targetPkg); if (intent == null) return new StepOutcome("refused", "APP_NOT_FOUND", null); @@ -519,9 +599,10 @@ private StepOutcome executeReadTree(boolean includeNonInteractive, int maxNodes) } } - private StepOutcome executeCaptureScreen(int maxWidth, int quality) { + private StepOutcome executeCaptureScreen(int maxWidth, int quality, int displayId) { + int targetDisplay = Math.max(Display.DEFAULT_DISPLAY, displayId); if (bridgeClient != null && bridgeClient.supportsCaptureDisplay()) { - byte[] jpeg = bridgeClient.captureDisplayBytes(Display.DEFAULT_DISPLAY, maxWidth, quality); + byte[] jpeg = bridgeClient.captureDisplayBytes(targetDisplay, maxWidth, quality); if (jpeg != null && jpeg.length > 0) { int[] dims = decodeJpegDimensions(jpeg, maxWidth); String b64 = Base64.encodeToString(jpeg, Base64.NO_WRAP); @@ -531,6 +612,9 @@ private StepOutcome executeCaptureScreen(int maxWidth, int quality) { : new StepOutcome("refused", "OBSERVE_FAILED", null); } } + if (targetDisplay > Display.DEFAULT_DISPLAY) { + return new StepOutcome("refused", "VIRTUAL_DISPLAY_CAPTURE_FAILED", null); + } AlphaAccessibilityService service = AlphaAccessibilityService.live(); if (service == null) return new StepOutcome("refused", "SERVICE_DISCONNECTED", null); AlphaAccessibilityService.ScreenshotCapture shot = service.captureTier1Screenshot(maxWidth, quality); @@ -540,11 +624,12 @@ private StepOutcome executeCaptureScreen(int maxWidth, int quality) { } private StepOutcome executeClick(JSONObject op) { - AlphaAccessibilityService service = AlphaAccessibilityService.live(); - if (service == null) return new StepOutcome("refused", "SERVICE_DISCONNECTED", null); + int targetDisplay = Math.max(Display.DEFAULT_DISPLAY, op.optInt("displayId", sessionManager.currentSnapshot().displayId)); String nodeId = op.optString("nodeId", ""); boolean longClick = op.optBoolean("longClick", false); - if (!nodeId.isEmpty()) { + if (!nodeId.isEmpty() && targetDisplay == Display.DEFAULT_DISPLAY) { + AlphaAccessibilityService service = AlphaAccessibilityService.live(); + if (service == null) return new StepOutcome("refused", "SERVICE_DISCONNECTED", null); return service.clickNode(nodeId, longClick) ? new StepOutcome("done", null, null) : new StepOutcome("refused", "NODE_CLICK_FAILED", null); @@ -552,13 +637,20 @@ private StepOutcome executeClick(JSONObject op) { float x = (float) op.optDouble("x", -1.0); float y = (float) op.optDouble("y", -1.0); if (x < 0f || y < 0f) return new StepOutcome("refused", "INVALID_COORDINATES", null); - dodgeOverlayIfNeeded(x, y, longClick ? 700L : 150L); + if (targetDisplay == Display.DEFAULT_DISPLAY) { + dodgeOverlayIfNeeded(x, y, longClick ? 700L : 150L); + } if (bridgeClient != null && bridgeClient.supportsInjectEvents() && !longClick) { long down = SystemClock.uptimeMillis(); - boolean ok = bridgeClient.injectMotionEvent(MotionEvent.ACTION_DOWN, x, y, down, down) - && bridgeClient.injectMotionEvent(MotionEvent.ACTION_UP, x, y, down, down + 40L); + boolean ok = bridgeClient.injectMotionEventOnDisplay(targetDisplay, MotionEvent.ACTION_DOWN, x, y, down, down) + && bridgeClient.injectMotionEventOnDisplay(targetDisplay, MotionEvent.ACTION_UP, x, y, down, down + 40L); if (ok) return new StepOutcome("done", null, null); } + if (targetDisplay > Display.DEFAULT_DISPLAY) { + return new StepOutcome("refused", "VIRTUAL_DISPLAY_INPUT_FAILED", null); + } + AlphaAccessibilityService service = AlphaAccessibilityService.live(); + if (service == null) return new StepOutcome("refused", "SERVICE_DISCONNECTED", null); return service.dispatchPointGesture(x, y, longClick ? 650L : 80L) ? new StepOutcome("done", null, null) : new StepOutcome("refused", "GESTURE_CLICK_FAILED", null); @@ -591,14 +683,15 @@ private StepOutcome executeScroll(JSONObject op) { return new StepOutcome("refused", "SCROLL_FAILED", null); } - private StepOutcome executeKeyEvent(String keyCodeName) { + private StepOutcome executeKeyEvent(String keyCodeName, int displayId) { int keyCode = AlphaControlPolicy.resolveAllowlistedKeyCode(keyCodeName); if (keyCode < 0) return new StepOutcome("refused", "KEYCODE_NOT_ALLOWED", null); if (bridgeClient == null || !bridgeClient.supportsInjectEvents()) { return new StepOutcome("refused", "TIER_PRIVILEGED_REQUIRED", null); } - boolean ok = bridgeClient.injectKeyEvent(keyCode, 0, KeyEvent.ACTION_DOWN) - && bridgeClient.injectKeyEvent(keyCode, 0, KeyEvent.ACTION_UP); + int targetDisplay = Math.max(Display.DEFAULT_DISPLAY, displayId); + boolean ok = bridgeClient.injectKeyEventOnDisplay(targetDisplay, keyCode, 0, KeyEvent.ACTION_DOWN) + && bridgeClient.injectKeyEventOnDisplay(targetDisplay, keyCode, 0, KeyEvent.ACTION_UP); return ok ? new StepOutcome("done", null, null) : new StepOutcome("refused", "KEY_INJECT_FAILED", null); } @@ -640,37 +733,147 @@ private StepOutcome executeGlobalAction(String action) { } private StepOutcome executeAppFunctionsDiscover(String packageName) { - if (!hasAppFunctionsManager()) { - return new StepOutcome("refused", "APP_FUNCTIONS_UNAVAILABLE", null); + AppFunctionsBridge.DiscoveryOutcome outcome = appFunctionsBridge.discover(packageName); + if (!outcome.ok) { + return new StepOutcome("refused", outcome.refusalCode, null); + } + try { + return new StepOutcome("done", null, outcome.toJson()); + } catch (JSONException failed) { + return new StepOutcome("refused", "APP_FUNCTIONS_FAILED", null); + } + } + + private StepOutcome executeAppFunction(JSONObject op, String expectedPackage) { + String functionId = op.optString("functionId", ""); + String targetPkg = op.optString("expectedPackage", expectedPackage); + if (targetPkg == null || targetPkg.isEmpty()) targetPkg = expectedPackage; + JSONObject parameters = op.optJSONObject("parameters"); + AppFunctionsBridge.ExecutionOutcome outcome = appFunctionsBridge.execute(targetPkg, functionId, parameters); + if (!outcome.ok) { + return new StepOutcome("refused", outcome.refusalCode, null); + } + return new StepOutcome("done", null, outcome.result); + } + + private StepOutcome executeVirtualDisplayCreate(JSONObject op, String expectedPackage) { + String targetPkg = op.optString("packageName", expectedPackage); + if (targetPkg == null || targetPkg.isEmpty()) targetPkg = expectedPackage; + String activityName = op.optString("activityName", ""); + int width = op.optInt("width", VirtualDisplaySessionManager.DEFAULT_VD_WIDTH); + int height = op.optInt("height", VirtualDisplaySessionManager.DEFAULT_VD_HEIGHT); + int densityDpi = op.optInt("densityDpi", VirtualDisplaySessionManager.DEFAULT_VD_DENSITY_DPI); + boolean allowFallback = op.optBoolean("allowForegroundFallback", true); + VirtualDisplaySessionManager.StartResult started = sessionManager.startSession( + targetPkg, + activityName, + VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, + width, + height, + densityDpi, + allowFallback + ); + if (!started.ok) { + return new StepOutcome("refused", started.refusalCode, null); } try { JSONObject result = new JSONObject(); - result.put("apiLevel", Build.VERSION.SDK_INT); - result.put("packageName", packageName == null ? "" : packageName); - result.put("functions", new JSONArray()); + result.put("sessionId", started.snapshot.sessionId); + result.put("displayId", started.snapshot.displayId); + result.put("mode", started.snapshot.mode.name()); + result.put("packageName", started.snapshot.packageName); + result.put("fellBackToForeground", started.snapshot.fellBackToForeground); return new StepOutcome("done", null, result); } catch (JSONException failed) { - return new StepOutcome("refused", "APP_FUNCTIONS_FAILED", null); + return new StepOutcome("refused", "EXECUTION_FAILED", null); } } - private StepOutcome executeAppFunction(JSONObject op) { - if (!hasAppFunctionsManager()) { - return new StepOutcome("refused", "APP_FUNCTIONS_UNAVAILABLE", null); + private StepOutcome executeVirtualDisplayRelease(JSONObject op) { + int displayId = op.optInt("displayId", sessionManager.currentSnapshot().displayId); + VirtualDisplaySessionManager.SessionSnapshot stopped = sessionManager.stopSession("released"); + if (displayId > Display.DEFAULT_DISPLAY && bridgeClient != null && bridgeClient.supportsVirtualDisplay()) { + bridgeClient.releaseVirtualDisplay(displayId); + } + try { + JSONObject result = new JSONObject(); + result.put("releasedDisplayId", displayId); + result.put("state", stopped.state.name()); + return new StepOutcome("done", null, result); + } catch (JSONException failed) { + return new StepOutcome("refused", "EXECUTION_FAILED", null); } - String functionId = op.optString("functionId", ""); - if (functionId.isEmpty()) return new StepOutcome("refused", "INVALID_FUNCTION_ID", null); - return new StepOutcome("refused", "APP_FUNCTION_NOT_REGISTERED", null); } - private boolean hasAppFunctionsManager() { - if (appContext == null || Build.VERSION.SDK_INT < 36) return false; + private StepOutcome executeVirtualDisplayLaunch(JSONObject op, String expectedPackage) { + int displayId = op.optInt("displayId", sessionManager.currentSnapshot().displayId); + String targetPkg = op.optString("packageName", expectedPackage); + if (targetPkg == null || targetPkg.isEmpty()) targetPkg = expectedPackage; + String activityName = op.optString("activityName", ""); + return executeLaunchPackage(targetPkg, expectedPackage, displayId, activityName); + } + + private StepOutcome executeProfilePreview(JSONObject op) { + ReversibleProfileController.ProfileSpec spec = resolveProfileSpec(op); + if (spec == null) return new StepOutcome("refused", "INVALID_PROFILE", null); + try { + return new StepOutcome("done", null, profileController.preview(spec).toJson()); + } catch (JSONException failed) { + return new StepOutcome("refused", "PROFILE_FAILED", null); + } + } + + private StepOutcome executeProfileApply(JSONObject op) { + ReversibleProfileController.ProfileSpec spec = resolveProfileSpec(op); + if (spec == null) return new StepOutcome("refused", "INVALID_PROFILE", null); + long nowMs = System.currentTimeMillis(); + long ttlMs = op.optLong("durationMs", 0L); try { - Class managerClass = Class.forName("android.app.appfunctions.AppFunctionManager"); - return appContext.getSystemService(managerClass) != null; - } catch (ClassNotFoundException | SecurityException unavailable) { - return false; + return new StepOutcome("done", null, profileController.apply(spec, nowMs, ttlMs).toJson()); + } catch (JSONException failed) { + return new StepOutcome("refused", "PROFILE_FAILED", null); + } + } + + private StepOutcome executeProfileRestore(JSONObject op) { + String receiptId = op.optString("receiptId", ""); + ReversibleProfileController.RestoreResult restored = profileController.restore(receiptId); + if (!restored.ok) { + return new StepOutcome("refused", "RECEIPT_NOT_FOUND", null); } + try { + return new StepOutcome("done", null, restored.toJson()); + } catch (JSONException failed) { + return new StepOutcome("refused", "PROFILE_FAILED", null); + } + } + + private static ReversibleProfileController.ProfileSpec resolveProfileSpec(JSONObject op) { + String profileId = op.optString("profileId", ""); + JSONObject overrides = op.optJSONObject("settings"); + if (overrides == null || overrides.length() == 0) { + return ReversibleProfileController.builtInProfile(profileId); + } + Map targets = new java.util.EnumMap<>(ReversibleProfileController.SettingKey.class); + ReversibleProfileController.ProfileSpec base = ReversibleProfileController.builtInProfile(profileId); + if (base != null) { + targets.putAll(base.targetValues); + } + java.util.Iterator keys = overrides.keys(); + while (keys.hasNext()) { + String rawKey = keys.next(); + ReversibleProfileController.SettingKey key = ReversibleProfileController.SettingKey.fromWireName(rawKey); + if (key == null) return null; + Object value = overrides.opt(rawKey); + if (!(value instanceof String str)) return null; + targets.put(key, str); + } + if (profileId.trim().isEmpty() || targets.isEmpty()) return null; + return new ReversibleProfileController.ProfileSpec(profileId, op.optString("displayName", profileId), targets); + } + + private boolean hasAppFunctionsManager() { + return appFunctionsBridge != null && appFunctionsBridge.isAvailable(); } private void postReceipt(int opId, StepOutcome outcome) { @@ -699,6 +902,7 @@ static boolean shouldRefreshPostActuation(String opType) { case "ui_global_action": case "app_open_url": case "app_launch_package": + case "app_function_execute": return true; default: return false; diff --git a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AppFunctionsBridge.java b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AppFunctionsBridge.java new file mode 100644 index 0000000000..5f8125e6e2 --- /dev/null +++ b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/AppFunctionsBridge.java @@ -0,0 +1,726 @@ +// spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease" +package ai.alphacompute.control; + +import android.app.appfunctions.AppFunctionException; +import android.app.appfunctions.AppFunctionManager; +import android.app.appfunctions.ExecuteAppFunctionRequest; +import android.app.appfunctions.ExecuteAppFunctionResponse; +import android.app.appsearch.AppSearchManager; +import android.app.appsearch.AppSearchResult; +import android.app.appsearch.GenericDocument; +import android.app.appsearch.GlobalSearchSession; +import android.app.appsearch.SearchResult; +import android.app.appsearch.SearchResults; +import android.app.appsearch.SearchSpec; +import android.content.Context; +import android.os.Build; +import android.os.CancellationSignal; +import android.os.OutcomeReceiver; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.regex.Pattern; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Typed bridge for Android 16+/17 (API 36/37) {@link AppFunctionManager} and {@link AppSearchManager} + * schema discovery and structured tool execution, with safe API < 36 fallback and strict per-app + * anti-bloat schema scoping. + */ +public final class AppFunctionsBridge { + /** Minimum Android API level that ships AppFunctionManager. */ + public static final int MIN_APP_FUNCTIONS_API = 36; + + /** Maximum functions returned per app to keep prompt schemas compact. */ + public static final int MAX_FUNCTIONS_PER_APP = 16; + + /** Maximum description characters kept per discovered AppFunction. */ + public static final int MAX_DESCRIPTION_CHARS = 120; + + /** Maximum parameter entries accepted or reported for a single AppFunction. */ + public static final int MAX_PARAMETERS_PER_FUNCTION = 16; + + private static final long DEFAULT_TIMEOUT_MS = 10_000L; + private static final Pattern FUNCTION_ID_PATTERN = Pattern.compile("^[A-Za-z0-9_.:/-]{1,160}$"); + private static final String SYSTEM_METADATA_PACKAGE = "android"; + private static final String STATIC_METADATA_SCHEMA = "AppFunctionStaticMetadata"; + + /** Compact schema descriptor for a discovered Android AppFunction. */ + public static final class FunctionSchema { + public final String functionId; + public final String packageName; + public final String displayName; + public final String description; + public final String schemaCategory; + public final String schemaName; + public final boolean enabled; + public final List parameterNames; + + public FunctionSchema( + String functionId, + String packageName, + String displayName, + String description, + String schemaCategory, + String schemaName, + boolean enabled, + List parameterNames + ) { + this.functionId = functionId; + this.packageName = packageName; + this.displayName = displayName; + this.description = description; + this.schemaCategory = schemaCategory; + this.schemaName = schemaName; + this.enabled = enabled; + this.parameterNames = parameterNames == null + ? Collections.emptyList() + : Collections.unmodifiableList(new ArrayList<>(parameterNames)); + } + + /** Serialize into a compact JSON representation suitable for the resident agent. */ + public JSONObject toJson() throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("functionId", functionId); + obj.put("packageName", packageName); + if (!displayName.isEmpty()) obj.put("displayName", displayName); + if (!description.isEmpty()) obj.put("description", description); + if (!schemaCategory.isEmpty()) obj.put("schemaCategory", schemaCategory); + if (!schemaName.isEmpty()) obj.put("schemaName", schemaName); + obj.put("enabled", enabled); + obj.put("parameters", new JSONArray(parameterNames)); + return obj; + } + } + + /** Structured discovery outcome returned to AlphaUiControlExecutor. */ + public static final class DiscoveryOutcome { + public final boolean ok; + public final String refusalCode; + public final int apiLevel; + public final String packageName; + public final List functions; + + private DiscoveryOutcome( + boolean ok, + String refusalCode, + int apiLevel, + String packageName, + List functions + ) { + this.ok = ok; + this.refusalCode = refusalCode; + this.apiLevel = apiLevel; + this.packageName = packageName; + this.functions = functions == null + ? Collections.emptyList() + : Collections.unmodifiableList(new ArrayList<>(functions)); + } + + public static DiscoveryOutcome success(int apiLevel, String packageName, List functions) { + return new DiscoveryOutcome(true, null, apiLevel, packageName, functions); + } + + public static DiscoveryOutcome refused(String refusalCode, int apiLevel, String packageName) { + return new DiscoveryOutcome(false, refusalCode, apiLevel, packageName, Collections.emptyList()); + } + + /** Convert into a compact JSON payload for native receipts. */ + public JSONObject toJson() throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("apiLevel", apiLevel); + obj.put("packageName", packageName); + JSONArray array = new JSONArray(); + for (FunctionSchema fn : functions) { + array.put(fn.toJson()); + } + obj.put("functions", array); + return obj; + } + } + + /** Structured execution outcome returned to AlphaUiControlExecutor. */ + public static final class ExecutionOutcome { + public final boolean ok; + public final String refusalCode; + public final JSONObject result; + + private ExecutionOutcome(boolean ok, String refusalCode, JSONObject result) { + this.ok = ok; + this.refusalCode = refusalCode; + this.result = result; + } + + public static ExecutionOutcome success(JSONObject result) { + return new ExecutionOutcome(true, null, result); + } + + public static ExecutionOutcome refused(String refusalCode) { + return new ExecutionOutcome(false, refusalCode, null); + } + } + + /** Pluggable backend seam so API 36/37 calls work live while remaining unit-testable on JVM. */ + public interface Backend { + int apiLevel(); + boolean isAvailable(); + List> queryMetadataDocuments(String targetPackage) throws Exception; + Boolean checkFunctionEnabled(String targetPackage, String functionId); + ExecutionOutcome executeFunction( + String targetPackage, + String functionId, + Map parameters, + long timeoutMs + ); + } + + private final Backend backend; + private final long timeoutMs; + + /** Construct a live AppFunctionsBridge bound to the Android application context. */ + public AppFunctionsBridge(Context context) { + this(createPlatformBackend(context), DEFAULT_TIMEOUT_MS); + } + + /** Construct an AppFunctionsBridge backed by an explicit backend (for JVM testing). */ + public AppFunctionsBridge(Backend backend, long timeoutMs) { + this.backend = backend; + this.timeoutMs = Math.max(250L, timeoutMs); + } + + /** Whether Android 16+/17 AppFunctionManager is live on this runtime. */ + public boolean isAvailable() { + return backend != null && backend.apiLevel() >= MIN_APP_FUNCTIONS_API && backend.isAvailable(); + } + + /** Discover enabled, compact AppFunction schemas for a single non-blocked package. */ + public DiscoveryOutcome discover(String packageName) { + int api = backend == null ? 0 : backend.apiLevel(); + String pkg = packageName == null ? "" : packageName.trim(); + if (!isAvailable()) { + return DiscoveryOutcome.refused("APP_FUNCTIONS_UNAVAILABLE", api, pkg); + } + if (!pkg.isEmpty()) { + if (!AlphaControlPolicy.isValidPackageName(pkg) || AlphaControlPolicy.isBlockedTarget(pkg, null)) { + return DiscoveryOutcome.refused("BLOCKED_PACKAGE", api, pkg); + } + } + try { + List> docs = backend.queryMetadataDocuments(pkg); + List parsed = new ArrayList<>(); + if (docs != null) { + for (Map doc : docs) { + if (parsed.size() >= MAX_FUNCTIONS_PER_APP) break; + FunctionSchema schema = parseMetadataRecord(doc, pkg); + if (schema == null) continue; + if (AlphaControlPolicy.isBlockedTarget(schema.packageName, null)) continue; + Boolean liveEnabled = backend.checkFunctionEnabled(schema.packageName, schema.functionId); + boolean effectiveEnabled = liveEnabled != null ? liveEnabled : schema.enabled; + if (!effectiveEnabled) continue; + parsed.add(new FunctionSchema( + schema.functionId, + schema.packageName, + schema.displayName, + schema.description, + schema.schemaCategory, + schema.schemaName, + true, + schema.parameterNames + )); + } + } + return DiscoveryOutcome.success(api, pkg, parsed); + } catch (SecurityException denied) { + return DiscoveryOutcome.refused("APP_FUNCTIONS_DENIED", api, pkg); + } catch (Exception failed) { + return DiscoveryOutcome.refused("APP_FUNCTIONS_FAILED", api, pkg); + } + } + + /** Validate and execute a single typed AppFunction call on a non-blocked target package. */ + public ExecutionOutcome execute(String packageName, String functionId, JSONObject rawParameters) { + if (!isAvailable()) { + return ExecutionOutcome.refused("APP_FUNCTIONS_UNAVAILABLE"); + } + String pkg = packageName == null ? "" : packageName.trim(); + if (!AlphaControlPolicy.isValidPackageName(pkg) || AlphaControlPolicy.isBlockedTarget(pkg, null)) { + return ExecutionOutcome.refused("BLOCKED_PACKAGE"); + } + String fnId = functionId == null ? "" : functionId.trim(); + if (!isValidFunctionId(fnId)) { + return ExecutionOutcome.refused("INVALID_FUNCTION_ID"); + } + Map validatedParams = parsePrimitiveParameters(rawParameters); + if (validatedParams == null) { + return ExecutionOutcome.refused("INVALID_PARAMETERS"); + } + Boolean liveEnabled = backend.checkFunctionEnabled(pkg, fnId); + if (Boolean.FALSE.equals(liveEnabled)) { + return ExecutionOutcome.refused("APP_FUNCTION_DISABLED"); + } + try { + return backend.executeFunction(pkg, fnId, validatedParams, timeoutMs); + } catch (SecurityException denied) { + return ExecutionOutcome.refused("APP_FUNCTION_DENIED"); + } catch (RuntimeException failed) { + return ExecutionOutcome.refused("APP_FUNCTION_EXECUTION_FAILED"); + } + } + + /** Validate an AppFunction identifier against safe character and length rules. */ + public static boolean isValidFunctionId(String functionId) { + return functionId != null && FUNCTION_ID_PATTERN.matcher(functionId.trim()).matches(); + } + + /** Extract and validate bounded primitive parameters from a JSON object. */ + public static Map parsePrimitiveParameters(JSONObject rawParameters) { + Map out = new LinkedHashMap<>(); + if (rawParameters == null) return out; + Iterator keys = rawParameters.keys(); + while (keys.hasNext()) { + String key = keys.next(); + if (key == null || key.isEmpty() || key.length() > 80 || out.size() >= MAX_PARAMETERS_PER_FUNCTION) { + return null; + } + Object value = rawParameters.opt(key); + if (value == null || JSONObject.NULL.equals(value)) { + return null; + } + if (value instanceof String str) { + if (str.length() > 1024 || str.indexOf('\0') >= 0) return null; + out.put(key, str); + } else if (value instanceof Boolean bool) { + out.put(key, bool); + } else if (value instanceof Integer || value instanceof Long) { + out.put(key, ((Number) value).longValue()); + } else if (value instanceof Number num) { + double d = num.doubleValue(); + if (!Double.isFinite(d)) return null; + out.put(key, d); + } else { + return null; + } + } + return out; + } + + /** Parse a raw AppSearch metadata property map into a compact {@link FunctionSchema}. */ + public static FunctionSchema parseMetadataRecord(Map record, String packageFilter) { + if (record == null || record.isEmpty()) return null; + String pkg = firstNonEmptyString(record, "packageName", "package"); + String functionId = firstNonEmptyString(record, "functionId", "id"); + if (pkg.isEmpty() && functionId.contains("/")) { + int slash = functionId.indexOf('/'); + pkg = functionId.substring(0, slash); + functionId = functionId.substring(slash + 1); + } + if (!AlphaControlPolicy.isValidPackageName(pkg) || !isValidFunctionId(functionId)) { + return null; + } + if (packageFilter != null && !packageFilter.isEmpty() && !packageFilter.equals(pkg)) { + return null; + } + String displayName = truncate(firstNonEmptyString(record, "displayName", "title", "schemaName"), 64); + String description = truncate(firstNonEmptyString(record, "description", "summary"), MAX_DESCRIPTION_CHARS); + String schemaCategory = truncate(firstNonEmptyString(record, "schemaCategory", "category"), 48); + String schemaName = truncate(firstNonEmptyString(record, "schemaName", "name"), 64); + boolean enabledByDefault = readBoolean(record.get("enabledByDefault"), true); + boolean enabled = readBoolean(record.get("enabled"), enabledByDefault); + List params = readStringList(record.get("parameters"), MAX_PARAMETERS_PER_FUNCTION); + return new FunctionSchema( + functionId, + pkg, + displayName, + description, + schemaCategory, + schemaName, + enabled, + params + ); + } + + /** Translate an Android AppFunctionException error code into a canonical refusal code. */ + public static String mapAppFunctionErrorCode(int errorCode) { + switch (errorCode) { + case 2000: + return "APP_FUNCTION_DENIED"; + case 1002: + return "APP_FUNCTION_DISABLED"; + case 1003: + return "APP_FUNCTION_NOT_FOUND"; + case 1001: + return "INVALID_PARAMETERS"; + case 2001: + return "APP_FUNCTION_CANCELLED"; + case 2002: + return "APP_FUNCTION_POLICY_DISALLOWED"; + default: + return "APP_FUNCTION_EXECUTION_FAILED"; + } + } + + private static String firstNonEmptyString(Map record, String... keys) { + for (String key : keys) { + Object val = record.get(key); + if (val instanceof String s) { + String trimmed = s.trim(); + if (!trimmed.isEmpty()) return trimmed; + } + } + return ""; + } + + private static boolean readBoolean(Object value, boolean fallback) { + if (value instanceof Boolean b) return b; + if (value instanceof String s) return Boolean.parseBoolean(s.trim()); + return fallback; + } + + private static List readStringList(Object value, int limit) { + List out = new ArrayList<>(); + if (value instanceof List list) { + for (Object item : list) { + if (out.size() >= limit) break; + if (item instanceof String s && !s.trim().isEmpty()) { + out.add(truncate(s.trim(), 64)); + } + } + } else if (value instanceof String[] array) { + for (String s : array) { + if (out.size() >= limit) break; + if (s != null && !s.trim().isEmpty()) { + out.add(truncate(s.trim(), 64)); + } + } + } + return out; + } + + private static String truncate(String text, int maxLen) { + if (text == null) return ""; + return text.length() <= maxLen ? text : text.substring(0, maxLen); + } + + private static Backend createPlatformBackend(Context context) { + if (context == null || Build.VERSION.SDK_INT < MIN_APP_FUNCTIONS_API) { + return new UnavailableBackend(Build.VERSION.SDK_INT); + } + return new Api36Backend(context.getApplicationContext()); + } + + private static final class UnavailableBackend implements Backend { + private final int sdkInt; + + UnavailableBackend(int sdkInt) { + this.sdkInt = sdkInt; + } + + @Override + public int apiLevel() { + return sdkInt; + } + + @Override + public boolean isAvailable() { + return false; + } + + @Override + public List> queryMetadataDocuments(String targetPackage) { + return Collections.emptyList(); + } + + @Override + public Boolean checkFunctionEnabled(String targetPackage, String functionId) { + return null; + } + + @Override + public ExecutionOutcome executeFunction( + String targetPackage, + String functionId, + Map parameters, + long timeoutMs + ) { + return ExecutionOutcome.refused("APP_FUNCTIONS_UNAVAILABLE"); + } + } + + /** + * Real Android 16+/17 (API 36/37) backend isolated in a nested class so API < 36 runtimes + * never load API 36 classes. + */ + private static final class Api36Backend implements Backend { + private final Context appContext; + private final ExecutorService ioExecutor = Executors.newSingleThreadExecutor(runnable -> { + Thread thread = new Thread(runnable, "alpha-appfunctions"); + thread.setDaemon(true); + return thread; + }); + + Api36Backend(Context appContext) { + this.appContext = appContext; + } + + @Override + public int apiLevel() { + return Build.VERSION.SDK_INT; + } + + @Override + public boolean isAvailable() { + try { + return appContext.getSystemService(AppFunctionManager.class) != null; + } catch (RuntimeException unavailable) { + return false; + } + } + + @Override + public List> queryMetadataDocuments(String targetPackage) throws Exception { + AppSearchManager searchManager = appContext.getSystemService(AppSearchManager.class); + if (searchManager == null) { + return Collections.emptyList(); + } + CompletableFuture sessionFuture = new CompletableFuture<>(); + searchManager.createGlobalSearchSession(ioExecutor, (AppSearchResult res) -> { + if (res != null && res.isSuccess() && res.getResultValue() != null) { + sessionFuture.complete(res.getResultValue()); + } else { + sessionFuture.complete(null); + } + }); + GlobalSearchSession session = sessionFuture.get(5, TimeUnit.SECONDS); + if (session == null) { + return Collections.emptyList(); + } + try { + SearchSpec.Builder specBuilder = new SearchSpec.Builder() + .addFilterPackageNames(SYSTEM_METADATA_PACKAGE) + .setResultCountPerPage(MAX_FUNCTIONS_PER_APP * 2); + if (targetPackage != null && !targetPackage.isEmpty()) { + specBuilder.addFilterSchemas( + STATIC_METADATA_SCHEMA, + STATIC_METADATA_SCHEMA + "-" + targetPackage + ); + } else { + specBuilder.addFilterSchemas(STATIC_METADATA_SCHEMA); + } + SearchResults results = session.search("", specBuilder.build()); + try { + CompletableFuture> pageFuture = new CompletableFuture<>(); + results.getNextPage(ioExecutor, (AppSearchResult> page) -> { + if (page != null && page.isSuccess() && page.getResultValue() != null) { + pageFuture.complete(page.getResultValue()); + } else { + pageFuture.complete(Collections.emptyList()); + } + }); + List rows = pageFuture.get(5, TimeUnit.SECONDS); + List> records = new ArrayList<>(); + for (SearchResult row : rows) { + GenericDocument doc = row.getGenericDocument(); + if (doc != null) { + records.add(extractDocumentMap(doc)); + } + } + return records; + } finally { + results.close(); + } + } finally { + session.close(); + } + } + + @Override + public Boolean checkFunctionEnabled(String targetPackage, String functionId) { + AppFunctionManager manager = appContext.getSystemService(AppFunctionManager.class); + if (manager == null) return null; + CompletableFuture future = new CompletableFuture<>(); + try { + manager.isAppFunctionEnabled( + functionId, + targetPackage, + ioExecutor, + new OutcomeReceiver() { + @Override + public void onResult(Boolean result) { + future.complete(result); + } + + @Override + public void onError(Exception error) { + future.complete(null); + } + } + ); + return future.get(2, TimeUnit.SECONDS); + } catch (Exception ignored) { + return null; + } + } + + @Override + public ExecutionOutcome executeFunction( + String targetPackage, + String functionId, + Map parameters, + long timeoutMs + ) { + AppFunctionManager manager = appContext.getSystemService(AppFunctionManager.class); + if (manager == null) { + return ExecutionOutcome.refused("APP_FUNCTIONS_UNAVAILABLE"); + } + GenericDocument paramsDoc = buildParametersDocument(parameters); + ExecuteAppFunctionRequest request = new ExecuteAppFunctionRequest.Builder(targetPackage, functionId) + .setParameters(paramsDoc) + .build(); + CancellationSignal signal = new CancellationSignal(); + CompletableFuture future = new CompletableFuture<>(); + manager.executeAppFunction( + request, + ioExecutor, + signal, + new OutcomeReceiver() { + @Override + public void onResult(ExecuteAppFunctionResponse response) { + try { + JSONObject out = new JSONObject(); + out.put("packageName", targetPackage); + out.put("functionId", functionId); + GenericDocument resultDoc = response == null ? null : response.getResultDocument(); + if (resultDoc != null) { + out.put("result", documentToJson(resultDoc, 0)); + } + future.complete(ExecutionOutcome.success(out)); + } catch (JSONException failed) { + future.complete(ExecutionOutcome.refused("APP_FUNCTION_RESPONSE_INVALID")); + } + } + + @Override + public void onError(AppFunctionException error) { + String code = error == null + ? "APP_FUNCTION_EXECUTION_FAILED" + : mapAppFunctionErrorCode(error.getErrorCode()); + future.complete(ExecutionOutcome.refused(code)); + } + } + ); + try { + return future.get(timeoutMs, TimeUnit.MILLISECONDS); + } catch (TimeoutException timedOut) { + signal.cancel(); + return ExecutionOutcome.refused("APP_FUNCTION_TIMEOUT"); + } catch (InterruptedException interrupted) { + signal.cancel(); + Thread.currentThread().interrupt(); + return ExecutionOutcome.refused("APP_FUNCTION_CANCELLED"); + } catch (Exception failed) { + signal.cancel(); + return ExecutionOutcome.refused("APP_FUNCTION_EXECUTION_FAILED"); + } + } + + private static GenericDocument buildParametersDocument(Map parameters) { + @SuppressWarnings("rawtypes") + GenericDocument.Builder builder = new GenericDocument.Builder<>("", "", "AppFunctionParameters"); + for (Map.Entry entry : parameters.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (value instanceof String s) { + builder.setPropertyString(key, s); + } else if (value instanceof Boolean b) { + builder.setPropertyBoolean(key, b); + } else if (value instanceof Long l) { + builder.setPropertyLong(key, l); + } else if (value instanceof Double d) { + builder.setPropertyDouble(key, d); + } + } + return builder.build(); + } + + private static Map extractDocumentMap(GenericDocument doc) { + Map map = new LinkedHashMap<>(); + map.put("id", doc.getId()); + Set propNames = doc.getPropertyNames(); + if (propNames == null) return map; + for (String prop : propNames) { + String str = doc.getPropertyString(prop); + if (str != null) { + map.put(prop, str); + continue; + } + String[] strArray = doc.getPropertyStringArray(prop); + if (strArray != null && strArray.length > 0) { + map.put(prop, strArray); + continue; + } + boolean[] boolArray = doc.getPropertyBooleanArray(prop); + if (boolArray != null && boolArray.length > 0) { + map.put(prop, boolArray[0]); + continue; + } + GenericDocument[] subDocs = doc.getPropertyDocumentArray(prop); + if (subDocs != null && subDocs.length > 0 && "parameters".equals(prop)) { + List paramNames = new ArrayList<>(); + for (GenericDocument sub : subDocs) { + String paramName = sub.getPropertyString("name"); + if (paramName != null && !paramName.isEmpty()) { + paramNames.add(paramName); + } + } + map.put("parameters", paramNames); + } + } + return map; + } + + private static JSONObject documentToJson(GenericDocument doc, int depth) throws JSONException { + JSONObject obj = new JSONObject(); + if (depth > 3) return obj; + Set propNames = doc.getPropertyNames(); + if (propNames == null) return obj; + for (String prop : propNames) { + String str = doc.getPropertyString(prop); + if (str != null) { + obj.put(prop, truncate(str, 1024)); + continue; + } + long[] longs = doc.getPropertyLongArray(prop); + if (longs != null && longs.length > 0) { + obj.put(prop, longs.length == 1 ? longs[0] : new JSONArray(longs)); + continue; + } + double[] doubles = doc.getPropertyDoubleArray(prop); + if (doubles != null && doubles.length > 0) { + obj.put(prop, doubles.length == 1 ? doubles[0] : new JSONArray(doubles)); + continue; + } + boolean[] bools = doc.getPropertyBooleanArray(prop); + if (bools != null && bools.length > 0) { + obj.put(prop, bools.length == 1 ? bools[0] : new JSONArray(bools)); + continue; + } + GenericDocument nested = doc.getPropertyDocument(prop); + if (nested != null) { + obj.put(prop, documentToJson(nested, depth + 1)); + } + } + return obj; + } + } +} diff --git a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/ReversibleProfileController.java b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/ReversibleProfileController.java new file mode 100644 index 0000000000..aef92671bb --- /dev/null +++ b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/ReversibleProfileController.java @@ -0,0 +1,799 @@ +// spec/app/control/profile.md, "Story: Apply and restore reversible OS profiles while preserving manual edits" +package ai.alphacompute.control; + +import android.app.NotificationManager; +import android.content.Context; +import android.content.SharedPreferences; +import android.media.AudioManager; +import android.provider.Settings; +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +/** + * Typed read -> preview -> apply -> restore receipt controller for reversible OS profiles + * (e.g. Focus or Recording mode). + * + *

Core safety invariant: restoration writes back a setting's baseline value ONLY if the current + * live OS value still equals what this profile wrote; any manual edit made by the owner mid-profile + * is preserved idempotently. + */ +public final class ReversibleProfileController { + /** Typed OS settings eligible for reversible profile management. */ + public enum SettingKey { + DO_NOT_DISTURB("dnd_mode"), + NOTIFICATION_SILENCE("notification_silence"), + SCREEN_TIMEOUT_SECONDS("screen_timeout_seconds"), + HOME_SHORTCUTS("home_shortcuts"), + MEDIA_VOLUME("media_volume"), + AUTO_BRIGHTNESS("auto_brightness"); + + public final String wireName; + + SettingKey(String wireName) { + this.wireName = wireName; + } + + /** Resolve a wire name into a typed {@link SettingKey}, or null if unknown. */ + public static SettingKey fromWireName(String name) { + if (name == null) return null; + String trimmed = name.trim(); + for (SettingKey key : values()) { + if (key.wireName.equals(trimmed) || key.name().equalsIgnoreCase(trimmed)) { + return key; + } + } + return null; + } + } + + /** Storage seam backing live OS setting reads and writes. */ + public interface SettingStore { + String read(SettingKey key); + boolean write(SettingKey key, String value); + } + + /** Deterministic in-memory setting store for unit tests and local dry-runs. */ + public static final class InMemorySettingStore implements SettingStore { + private final Map values = new EnumMap<>(SettingKey.class); + + public InMemorySettingStore(Map initialValues) { + if (initialValues != null) { + values.putAll(initialValues); + } + } + + @Override + public synchronized String read(SettingKey key) { + return values.get(key); + } + + @Override + public synchronized boolean write(SettingKey key, String value) { + if (key == null) return false; + if (value == null) { + values.remove(key); + } else { + values.put(key, value); + } + return true; + } + + /** Return a copy of all stored values. */ + public synchronized Map snapshot() { + return new EnumMap<>(values); + } + } + + /** + * Production Android OS setting store backed by system managers and Alpha-owned preferences. + * + *

Every privileged or system-level write fails closed ({@code false}) when the required + * Android permission ({@code isNotificationPolicyAccessGranted()} or {@code Settings.System.canWrite()}) + * is absent or when a value is out of bounds. + */ + public static final class AndroidSettingStore implements SettingStore { + public static final String PREFS_NAME = "alpha_reversible_profiles"; + static final int MIN_TIMEOUT_SECONDS = 15; + static final int MAX_TIMEOUT_SECONDS = 3600; + + private final Context context; + + public AndroidSettingStore(Context context) { + if (context == null) { + throw new IllegalArgumentException("Context is required"); + } + Context app = context.getApplicationContext(); + this.context = app != null ? app : context; + } + + @Override + public String read(SettingKey key) { + if (key == null) return null; + switch (key) { + case DO_NOT_DISTURB: + return readDoNotDisturb(); + case MEDIA_VOLUME: + return readMediaVolume(); + case SCREEN_TIMEOUT_SECONDS: + return readScreenTimeoutSeconds(); + case AUTO_BRIGHTNESS: + return readAutoBrightness(); + case NOTIFICATION_SILENCE: + case HOME_SHORTCUTS: + return readAlphaPref(key); + default: + return null; + } + } + + @Override + public boolean write(SettingKey key, String value) { + if (key == null) return false; + switch (key) { + case DO_NOT_DISTURB: + return writeDoNotDisturb(value); + case MEDIA_VOLUME: + return writeMediaVolume(value); + case SCREEN_TIMEOUT_SECONDS: + return writeScreenTimeoutSeconds(value); + case AUTO_BRIGHTNESS: + return writeAutoBrightness(value); + case NOTIFICATION_SILENCE: + case HOME_SHORTCUTS: + return writeAlphaPref(key, value); + default: + return false; + } + } + + private String readDoNotDisturb() { + try { + NotificationManager nm = context.getSystemService(NotificationManager.class); + if (nm == null) return null; + return interruptionFilterToWire(nm.getCurrentInterruptionFilter()); + } catch (RuntimeException failed) { + return null; + } + } + + private boolean writeDoNotDisturb(String value) { + int filter = wireToInterruptionFilter(value); + if (filter < 0) return false; + try { + NotificationManager nm = context.getSystemService(NotificationManager.class); + if (nm == null || !nm.isNotificationPolicyAccessGranted()) return false; + nm.setInterruptionFilter(filter); + return true; + } catch (SecurityException denied) { + return false; + } catch (RuntimeException failed) { + return false; + } + } + + private String readMediaVolume() { + try { + AudioManager am = context.getSystemService(AudioManager.class); + if (am == null) return null; + int maxIndex = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + int index = am.getStreamVolume(AudioManager.STREAM_MUSIC); + return volumeIndexToWire(index, maxIndex); + } catch (RuntimeException failed) { + return null; + } + } + + private boolean writeMediaVolume(String value) { + try { + AudioManager am = context.getSystemService(AudioManager.class); + if (am == null) return false; + int maxIndex = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + int target = wireToVolumeIndex(value, maxIndex); + if (target < 0) return false; + am.setStreamVolume(AudioManager.STREAM_MUSIC, target, 0); + return true; + } catch (SecurityException denied) { + return false; + } catch (RuntimeException failed) { + return false; + } + } + + private String readScreenTimeoutSeconds() { + try { + int timeoutMs = Settings.System.getInt( + context.getContentResolver(), + Settings.System.SCREEN_OFF_TIMEOUT, + -1 + ); + return timeoutMsToSecondsWire(timeoutMs); + } catch (RuntimeException failed) { + return null; + } + } + + private boolean writeScreenTimeoutSeconds(String value) { + int timeoutMs = secondsWireToTimeoutMs(value); + if (timeoutMs <= 0) return false; + try { + if (!Settings.System.canWrite(context)) return false; + return Settings.System.putInt( + context.getContentResolver(), + Settings.System.SCREEN_OFF_TIMEOUT, + timeoutMs + ); + } catch (SecurityException denied) { + return false; + } catch (RuntimeException failed) { + return false; + } + } + + private String readAutoBrightness() { + try { + int mode = Settings.System.getInt( + context.getContentResolver(), + Settings.System.SCREEN_BRIGHTNESS_MODE, + -1 + ); + return brightnessModeToWire(mode); + } catch (RuntimeException failed) { + return null; + } + } + + private boolean writeAutoBrightness(String value) { + int mode = wireToBrightnessMode(value); + if (mode < 0) return false; + try { + if (!Settings.System.canWrite(context)) return false; + return Settings.System.putInt( + context.getContentResolver(), + Settings.System.SCREEN_BRIGHTNESS_MODE, + mode + ); + } catch (SecurityException denied) { + return false; + } catch (RuntimeException failed) { + return false; + } + } + + private String readAlphaPref(SettingKey key) { + try { + SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + return prefs == null ? null : prefs.getString(key.wireName, null); + } catch (RuntimeException failed) { + return null; + } + } + + private boolean writeAlphaPref(SettingKey key, String value) { + try { + SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); + if (prefs == null) return false; + SharedPreferences.Editor editor = prefs.edit(); + if (value == null) { + editor.remove(key.wireName); + } else { + editor.putString(key.wireName, value); + } + return editor.commit(); + } catch (RuntimeException failed) { + return false; + } + } + + /** Convert Android {@link NotificationManager} interruption filter constant to wire string. */ + static String interruptionFilterToWire(int filter) { + switch (filter) { + case NotificationManager.INTERRUPTION_FILTER_ALL: + return "off"; + case NotificationManager.INTERRUPTION_FILTER_PRIORITY: + return "priority"; + case NotificationManager.INTERRUPTION_FILTER_NONE: + return "total_silence"; + case NotificationManager.INTERRUPTION_FILTER_ALARMS: + return "alarms_only"; + default: + return null; + } + } + + /** Convert wire string to Android {@link NotificationManager} interruption filter, or -1 if invalid. */ + static int wireToInterruptionFilter(String value) { + if (value == null) return -1; + switch (value.trim().toLowerCase(Locale.ROOT)) { + case "off": + case "all": + return NotificationManager.INTERRUPTION_FILTER_ALL; + case "priority": + return NotificationManager.INTERRUPTION_FILTER_PRIORITY; + case "total_silence": + case "none": + return NotificationManager.INTERRUPTION_FILTER_NONE; + case "alarms_only": + case "alarms": + return NotificationManager.INTERRUPTION_FILTER_ALARMS; + default: + return -1; + } + } + + /** Convert stream music volume index to exact wire integer string, or null if out of range. */ + static String volumeIndexToWire(int index, int maxIndex) { + if (index < 0 || maxIndex < 0 || index > maxIndex) return null; + return String.valueOf(index); + } + + /** Parse wire volume string into a bounded Android stream music index, or -1 if invalid. */ + static int wireToVolumeIndex(String value, int maxIndex) { + if (value == null || maxIndex < 0) return -1; + try { + int parsed = Integer.parseInt(value.trim()); + return (parsed >= 0 && parsed <= maxIndex) ? parsed : -1; + } catch (NumberFormatException bad) { + return -1; + } + } + + /** Convert {@link Settings.System#SCREEN_OFF_TIMEOUT} milliseconds to wire seconds string. */ + static String timeoutMsToSecondsWire(int timeoutMs) { + if (timeoutMs <= 0) return null; + int seconds = Math.max(1, Math.round(timeoutMs / 1000.0f)); + return String.valueOf(seconds); + } + + /** Parse wire seconds string to bounded {@link Settings.System#SCREEN_OFF_TIMEOUT} milliseconds, or -1. */ + static int secondsWireToTimeoutMs(String value) { + if (value == null) return -1; + try { + int seconds = Integer.parseInt(value.trim()); + if (seconds < MIN_TIMEOUT_SECONDS || seconds > MAX_TIMEOUT_SECONDS) return -1; + return seconds * 1000; + } catch (NumberFormatException bad) { + return -1; + } + } + + /** Convert {@link Settings.System#SCREEN_BRIGHTNESS_MODE} constant to wire string. */ + static String brightnessModeToWire(int mode) { + if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) return "enabled"; + if (mode == Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL) return "disabled"; + return null; + } + + /** Convert wire string to {@link Settings.System#SCREEN_BRIGHTNESS_MODE}, or -1 if invalid. */ + static int wireToBrightnessMode(String value) { + if (value == null) return -1; + switch (value.trim().toLowerCase(Locale.ROOT)) { + case "enabled": + case "auto": + case "true": + case "on": + return Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC; + case "disabled": + case "manual": + case "false": + case "off": + return Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL; + default: + return -1; + } + } + } + + /** Named reversible OS profile target specification. */ + public static final class ProfileSpec { + public final String profileId; + public final String displayName; + public final Map targetValues; + + public ProfileSpec(String profileId, String displayName, Map targetValues) { + if (profileId == null || profileId.trim().isEmpty()) { + throw new IllegalArgumentException("profileId is required"); + } + this.profileId = profileId.trim(); + this.displayName = displayName == null ? this.profileId : displayName.trim(); + Map copy = new EnumMap<>(SettingKey.class); + if (targetValues != null) { + copy.putAll(targetValues); + } + this.targetValues = Collections.unmodifiableMap(copy); + } + } + + /** Single proposed change computed by {@link #preview(ProfileSpec)}. */ + public static final class SettingChange { + public final SettingKey key; + public final String beforeValue; + public final String targetValue; + + public SettingChange(SettingKey key, String beforeValue, String targetValue) { + this.key = key; + this.beforeValue = beforeValue; + this.targetValue = targetValue; + } + } + + /** Pure dry-run preview describing exact OS changes before applying a profile. */ + public static final class ProfilePreview { + public final String profileId; + public final String displayName; + public final List changes; + public final List unchangedKeys; + + public ProfilePreview( + String profileId, + String displayName, + List changes, + List unchangedKeys + ) { + this.profileId = profileId; + this.displayName = displayName; + this.changes = Collections.unmodifiableList(new ArrayList<>(changes)); + this.unchangedKeys = Collections.unmodifiableList(new ArrayList<>(unchangedKeys)); + } + + /** Convert preview into JSON for agent/UI display. */ + public JSONObject toJson() throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("profileId", profileId); + obj.put("displayName", displayName); + JSONArray changeArr = new JSONArray(); + for (SettingChange change : changes) { + JSONObject item = new JSONObject(); + item.put("key", change.key.wireName); + item.put("before", change.beforeValue == null ? JSONObject.NULL : change.beforeValue); + item.put("target", change.targetValue == null ? JSONObject.NULL : change.targetValue); + changeArr.put(item); + } + obj.put("changes", changeArr); + JSONArray unchangedArr = new JSONArray(); + for (SettingKey key : unchangedKeys) { + unchangedArr.put(key.wireName); + } + obj.put("unchanged", unchangedArr); + return obj; + } + } + + /** Per-key attribution record stored inside an applied profile receipt. */ + public static final class ReceiptEntry { + public final SettingKey key; + public final String baselineValue; + public final String appliedValue; + + public ReceiptEntry(SettingKey key, String baselineValue, String appliedValue) { + this.key = key; + this.baselineValue = baselineValue; + this.appliedValue = appliedValue; + } + } + + /** Record of a manual user edit that was preserved untouched during restore. */ + public static final class PreservedManualEdit { + public final SettingKey key; + public final String baselineValue; + public final String profileAppliedValue; + public final String currentUserValue; + + public PreservedManualEdit( + SettingKey key, + String baselineValue, + String profileAppliedValue, + String currentUserValue + ) { + this.key = key; + this.baselineValue = baselineValue; + this.profileAppliedValue = profileAppliedValue; + this.currentUserValue = currentUserValue; + } + } + + /** Immutable receipt emitted when a profile is applied. */ + public static final class ProfileReceipt { + public final String receiptId; + public final String profileId; + public final long appliedAtMs; + public final long expiresAtMs; + public final Map entries; + public final boolean restored; + + public ProfileReceipt( + String receiptId, + String profileId, + long appliedAtMs, + long expiresAtMs, + Map entries, + boolean restored + ) { + this.receiptId = receiptId; + this.profileId = profileId; + this.appliedAtMs = appliedAtMs; + this.expiresAtMs = expiresAtMs; + Map copy = new EnumMap<>(SettingKey.class); + copy.putAll(entries); + this.entries = Collections.unmodifiableMap(copy); + this.restored = restored; + } + + /** Convert receipt to JSON for the resident agent. */ + public JSONObject toJson() throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("receiptId", receiptId); + obj.put("profileId", profileId); + obj.put("appliedAtMs", appliedAtMs); + obj.put("expiresAtMs", expiresAtMs); + obj.put("restored", restored); + JSONArray applied = new JSONArray(); + for (ReceiptEntry entry : entries.values()) { + JSONObject row = new JSONObject(); + row.put("key", entry.key.wireName); + row.put("baseline", entry.baselineValue == null ? JSONObject.NULL : entry.baselineValue); + row.put("applied", entry.appliedValue == null ? JSONObject.NULL : entry.appliedValue); + applied.put(row); + } + obj.put("entries", applied); + return obj; + } + } + + /** Result returned by {@link #restore(String)}, detailing restored vs preserved manual edits. */ + public static final class RestoreResult { + public final boolean ok; + public final String receiptId; + public final String profileId; + public final boolean alreadyRestored; + public final List restoredKeys; + public final List preservedManualEdits; + + public RestoreResult( + boolean ok, + String receiptId, + String profileId, + boolean alreadyRestored, + List restoredKeys, + List preservedManualEdits + ) { + this.ok = ok; + this.receiptId = receiptId; + this.profileId = profileId; + this.alreadyRestored = alreadyRestored; + this.restoredKeys = Collections.unmodifiableList(new ArrayList<>(restoredKeys)); + this.preservedManualEdits = Collections.unmodifiableList(new ArrayList<>(preservedManualEdits)); + } + + /** Convert restore outcome into JSON for receipts and audit logs. */ + public JSONObject toJson() throws JSONException { + JSONObject obj = new JSONObject(); + obj.put("ok", ok); + obj.put("receiptId", receiptId); + obj.put("profileId", profileId); + obj.put("alreadyRestored", alreadyRestored); + JSONArray restored = new JSONArray(); + for (SettingKey key : restoredKeys) { + restored.put(key.wireName); + } + obj.put("restoredKeys", restored); + JSONArray preserved = new JSONArray(); + for (PreservedManualEdit edit : preservedManualEdits) { + JSONObject item = new JSONObject(); + item.put("key", edit.key.wireName); + item.put("baseline", edit.baselineValue == null ? JSONObject.NULL : edit.baselineValue); + item.put("profileApplied", edit.profileAppliedValue == null ? JSONObject.NULL : edit.profileAppliedValue); + item.put("currentUserValue", edit.currentUserValue == null ? JSONObject.NULL : edit.currentUserValue); + preserved.put(item); + } + obj.put("preservedManualEdits", preserved); + return obj; + } + } + + private final SettingStore store; + private final AtomicInteger nextReceiptSeq = new AtomicInteger(0); + private final Object lock = new Object(); + private final Map receipts = new LinkedHashMap<>(); + private final Map restoreHistory = new LinkedHashMap<>(); + + /** Create a controller over the supplied OS setting store. */ + public ReversibleProfileController(SettingStore store) { + if (store == null) { + throw new IllegalArgumentException("SettingStore is required"); + } + this.store = store; + } + + /** Built-in Focus Mode preset (DND priority + notification silence). */ + public static ProfileSpec focusProfile() { + Map targets = new EnumMap<>(SettingKey.class); + targets.put(SettingKey.DO_NOT_DISTURB, "priority"); + targets.put(SettingKey.NOTIFICATION_SILENCE, "enabled"); + return new ProfileSpec("focus", "Focus Mode", targets); + } + + /** Built-in Recording Mode preset (DND alarms-only + silence + extended timeout + recording shortcuts). */ + public static ProfileSpec recordingProfile() { + Map targets = new EnumMap<>(SettingKey.class); + targets.put(SettingKey.DO_NOT_DISTURB, "alarms_only"); + targets.put(SettingKey.NOTIFICATION_SILENCE, "enabled"); + targets.put(SettingKey.SCREEN_TIMEOUT_SECONDS, "600"); + targets.put(SettingKey.HOME_SHORTCUTS, "recording_pack"); + return new ProfileSpec("recording", "Recording Mode", targets); + } + + /** Resolve a built-in profile preset by id ("focus" or "recording"), or null if unknown. */ + public static ProfileSpec builtInProfile(String profileId) { + if (profileId == null) return null; + switch (profileId.trim().toLowerCase(java.util.Locale.ROOT)) { + case "focus": + return focusProfile(); + case "recording": + return recordingProfile(); + default: + return null; + } + } + + /** Stage 1 (Read): Read current live values for the requested keys without mutating anything. */ + public Map readCurrent(Set keys) { + Map snapshot = new EnumMap<>(SettingKey.class); + if (keys == null) return Collections.unmodifiableMap(snapshot); + synchronized (lock) { + for (SettingKey key : keys) { + snapshot.put(key, store.read(key)); + } + } + return Collections.unmodifiableMap(snapshot); + } + + /** Stage 2 (Preview): Compute exact diff against live OS state with zero mutations. */ + public ProfilePreview preview(ProfileSpec spec) { + if (spec == null) { + throw new IllegalArgumentException("ProfileSpec is required"); + } + List changes = new ArrayList<>(); + List unchanged = new ArrayList<>(); + synchronized (lock) { + for (Map.Entry entry : spec.targetValues.entrySet()) { + String live = store.read(entry.getKey()); + String target = entry.getValue(); + if (Objects.equals(live, target)) { + unchanged.add(entry.getKey()); + } else { + changes.add(new SettingChange(entry.getKey(), live, target)); + } + } + } + return new ProfilePreview(spec.profileId, spec.displayName, changes, unchanged); + } + + /** Stage 3 (Apply): Write only changed settings and record an immutable attribution receipt. */ + public ProfileReceipt apply(ProfileSpec spec, long nowMs, long ttlMs) { + if (spec == null) { + throw new IllegalArgumentException("ProfileSpec is required"); + } + long expiresAtMs = ttlMs > 0L ? nowMs + ttlMs : 0L; + synchronized (lock) { + Map entries = new EnumMap<>(SettingKey.class); + for (Map.Entry target : spec.targetValues.entrySet()) { + SettingKey key = target.getKey(); + String baseline = store.read(key); + String desired = target.getValue(); + if (!Objects.equals(baseline, desired) && store.write(key, desired)) { + entries.put(key, new ReceiptEntry(key, baseline, desired)); + } + } + String receiptId = "profile-" + nextReceiptSeq.incrementAndGet(); + ProfileReceipt receipt = new ProfileReceipt( + receiptId, + spec.profileId, + nowMs, + expiresAtMs, + entries, + false + ); + receipts.put(receiptId, receipt); + return receipt; + } + } + + /** + * Stage 4 (Restore): Idempotently restore ONLY values still attributable to {@code receiptId}, + * preserving any manual user edits made mid-profile. + */ + public RestoreResult restore(String receiptId) { + if (receiptId == null || receiptId.trim().isEmpty()) { + return new RestoreResult(false, "", "", false, Collections.emptyList(), Collections.emptyList()); + } + String id = receiptId.trim(); + synchronized (lock) { + ProfileReceipt receipt = receipts.get(id); + if (receipt == null) { + return new RestoreResult(false, id, "", false, Collections.emptyList(), Collections.emptyList()); + } + RestoreResult previous = restoreHistory.get(id); + if (receipt.restored && previous != null) { + return new RestoreResult( + true, + id, + receipt.profileId, + true, + previous.restoredKeys, + previous.preservedManualEdits + ); + } + List restoredKeys = new ArrayList<>(); + List preservedEdits = new ArrayList<>(); + for (ReceiptEntry entry : receipt.entries.values()) { + String liveValue = store.read(entry.key); + if (Objects.equals(liveValue, entry.appliedValue)) { + if (store.write(entry.key, entry.baselineValue)) { + restoredKeys.add(entry.key); + } + } else { + preservedEdits.add(new PreservedManualEdit( + entry.key, + entry.baselineValue, + entry.appliedValue, + liveValue + )); + } + } + ProfileReceipt closed = new ProfileReceipt( + receipt.receiptId, + receipt.profileId, + receipt.appliedAtMs, + receipt.expiresAtMs, + receipt.entries, + true + ); + receipts.put(id, closed); + RestoreResult result = new RestoreResult( + true, + id, + receipt.profileId, + false, + restoredKeys, + preservedEdits + ); + restoreHistory.put(id, result); + return result; + } + } + + /** Automatically restore every active receipt whose expiry timestamp is at or before {@code nowMs}. */ + public List restoreExpired(long nowMs) { + List dueIds = new ArrayList<>(); + synchronized (lock) { + for (ProfileReceipt receipt : receipts.values()) { + if (!receipt.restored && receipt.expiresAtMs > 0L && nowMs >= receipt.expiresAtMs) { + dueIds.add(receipt.receiptId); + } + } + } + List results = new ArrayList<>(); + for (String id : dueIds) { + results.add(restore(id)); + } + return results; + } + + /** Retrieve a stored receipt by id, or null if absent. */ + public ProfileReceipt getReceipt(String receiptId) { + synchronized (lock) { + return receipts.get(receiptId); + } + } +} diff --git a/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/VirtualDisplaySessionManager.java b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/VirtualDisplaySessionManager.java new file mode 100644 index 0000000000..13e5b4bf50 --- /dev/null +++ b/apps/app/android/alpha-control/src/main/java/ai/alphacompute/control/VirtualDisplaySessionManager.java @@ -0,0 +1,436 @@ +// spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease" +package ai.alphacompute.control; + +import android.view.Display; +import android.view.MotionEvent; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Dual-mode execution coordinator managing visible {@link ExecutionMode#FOREGROUND} control sessions + * (on {@link Display#DEFAULT_DISPLAY}) and headless {@link ExecutionMode#VIRTUAL_DISPLAY} Phone Use + * sessions (on a trusted AOSP v2 VirtualDisplay), automatically surfacing and pausing to foreground + * on human takeover triggers (sign-in, payment, permission, protected screen, or ambiguous target). + */ +public final class VirtualDisplaySessionManager { + /** Where an active external-app control session renders and accepts input. */ + public enum ExecutionMode { + FOREGROUND, + VIRTUAL_DISPLAY + } + + /** Lifecycle state of the managed dual-mode session. */ + public enum SessionState { + IDLE, + RUNNING, + PAUSED_FOR_TAKEOVER, + STOPPED + } + + /** Structured reason requiring immediate human takeover. */ + public enum TakeoverReason { + NONE, + SIGN_IN, + PAYMENT, + PERMISSION, + AMBIGUOUS_TARGET, + PROTECTED_SCREEN, + USER_STOP + } + + /** Abstract bridge host seam allowing direct wiring to AlphaControlBridgeClient v2 or JVM test fakes. */ + public interface BridgeHost { + boolean supportsVirtualDisplay(); + boolean supportsPerDisplayInput(); + boolean supportsCaptureDisplay(); + int createVirtualDisplay(String name, int width, int height, int densityDpi); + boolean releaseVirtualDisplay(int displayId); + boolean launchPackageOnDisplay(int displayId, String packageName, String activityName); + byte[] captureDisplayBytes(int displayId, int maxWidth, int jpegQuality); + boolean injectKeyEventOnDisplay(int displayId, int keyCode, int metaState, int action); + boolean injectMotionEventOnDisplay( + int displayId, int action, float x, float y, long downTime, long eventTime + ); + } + + /** Callback notified whenever a session starts, pauses for takeover, surfaces, or stops. */ + public interface SessionListener { + void onSessionStateChanged(SessionSnapshot snapshot); + } + + /** Immutable snapshot of the active dual-mode session. */ + public static final class SessionSnapshot { + public final int sessionId; + public final String packageName; + public final ExecutionMode mode; + public final int displayId; + public final SessionState state; + public final TakeoverReason takeoverReason; + public final String detail; + public final boolean fellBackToForeground; + public final boolean surfacedToForeground; + + public SessionSnapshot( + int sessionId, + String packageName, + ExecutionMode mode, + int displayId, + SessionState state, + TakeoverReason takeoverReason, + String detail, + boolean fellBackToForeground, + boolean surfacedToForeground + ) { + this.sessionId = sessionId; + this.packageName = packageName == null ? "" : packageName; + this.mode = mode; + this.displayId = displayId; + this.state = state; + this.takeoverReason = takeoverReason; + this.detail = detail == null ? "" : detail; + this.fellBackToForeground = fellBackToForeground; + this.surfacedToForeground = surfacedToForeground; + } + } + + /** Result of starting a dual-mode session. */ + public static final class StartResult { + public final boolean ok; + public final String refusalCode; + public final SessionSnapshot snapshot; + + private StartResult(boolean ok, String refusalCode, SessionSnapshot snapshot) { + this.ok = ok; + this.refusalCode = refusalCode; + this.snapshot = snapshot; + } + + static StartResult started(SessionSnapshot snapshot) { + return new StartResult(true, null, snapshot); + } + + static StartResult refused(String refusalCode, SessionSnapshot snapshot) { + return new StartResult(false, refusalCode, snapshot); + } + } + + public static final int DEFAULT_VD_WIDTH = 1080; + public static final int DEFAULT_VD_HEIGHT = 2400; + public static final int DEFAULT_VD_DENSITY_DPI = 420; + + private static final String[] SIGN_IN_MARKERS = { + "sign in", "log in", "login", "password", "passkey", "two-factor", "2fa", + "verification code", "one-time code", "authenticate", "oauth", "verify identity" + }; + private static final String[] PAYMENT_MARKERS = { + "checkout", "pay now", "place order", "confirm purchase", "complete payment", + "credit card", "debit card", "billing", "cvv", "wire transfer", "send money", "subscribe now" + }; + private static final String[] PERMISSION_MARKERS = { + "allow this app", "grant permission", "permission request", "allow access to", + "install unknown apps", "accessibility permission", "device admin" + }; + + private final BridgeHost bridgeHost; + private final SessionListener listener; + private final AtomicInteger nextSessionId = new AtomicInteger(0); + private final Object lock = new Object(); + private SessionSnapshot current = new SessionSnapshot( + 0, "", ExecutionMode.FOREGROUND, Display.DEFAULT_DISPLAY, SessionState.IDLE, TakeoverReason.NONE, "", false, false + ); + + /** Wrap an {@link AlphaControlBridgeClient} into a {@link BridgeHost}. */ + public static BridgeHost fromClient(AlphaControlBridgeClient client) { + return new BridgeHost() { + @Override + public boolean supportsVirtualDisplay() { + return client != null && client.supportsVirtualDisplay(); + } + + @Override + public boolean supportsPerDisplayInput() { + return client != null && client.supportsPerDisplayInput(); + } + + @Override + public boolean supportsCaptureDisplay() { + return client != null && client.supportsCaptureDisplay(); + } + + @Override + public int createVirtualDisplay(String name, int width, int height, int densityDpi) { + return client == null ? Display.INVALID_DISPLAY : client.createVirtualDisplay(name, width, height, densityDpi); + } + + @Override + public boolean releaseVirtualDisplay(int displayId) { + return client != null && client.releaseVirtualDisplay(displayId); + } + + @Override + public boolean launchPackageOnDisplay(int displayId, String packageName, String activityName) { + return client != null && client.launchPackageOnDisplay(displayId, packageName, activityName); + } + + @Override + public byte[] captureDisplayBytes(int displayId, int maxWidth, int jpegQuality) { + return client == null ? null : client.captureDisplayBytes(displayId, maxWidth, jpegQuality); + } + + @Override + public boolean injectKeyEventOnDisplay(int displayId, int keyCode, int metaState, int action) { + return client != null && client.injectKeyEventOnDisplay(displayId, keyCode, metaState, action); + } + + @Override + public boolean injectMotionEventOnDisplay( + int displayId, int action, float x, float y, long downTime, long eventTime + ) { + return client != null && client.injectMotionEventOnDisplay(displayId, action, x, y, downTime, eventTime); + } + }; + } + + /** Create a session manager bound to the supplied bridge host and optional state listener. */ + public VirtualDisplaySessionManager(BridgeHost bridgeHost, SessionListener listener) { + this.bridgeHost = bridgeHost; + this.listener = listener; + } + + /** Return the current immutable session snapshot. */ + public SessionSnapshot currentSnapshot() { + synchronized (lock) { + return current; + } + } + + /** + * Start a foreground or background VirtualDisplay control session for an allowed package. + * Falls back safely to foreground when {@code allowForegroundFallback} is true and Tier-2 + * VirtualDisplay support is unavailable. + */ + public StartResult startSession( + String packageName, + String activityName, + ExecutionMode requestedMode, + int width, + int height, + int densityDpi, + boolean allowForegroundFallback + ) { + String pkg = packageName == null ? "" : packageName.trim(); + String act = activityName == null ? "" : activityName.trim(); + if (!AlphaControlPolicy.isValidPackageName(pkg) || AlphaControlPolicy.isBlockedTarget(pkg, act)) { + return StartResult.refused("BLOCKED_PACKAGE", currentSnapshot()); + } + ExecutionMode targetMode = requestedMode == null ? ExecutionMode.FOREGROUND : requestedMode; + int w = width > 0 ? width : DEFAULT_VD_WIDTH; + int h = height > 0 ? height : DEFAULT_VD_HEIGHT; + int dpi = densityDpi > 0 ? densityDpi : DEFAULT_VD_DENSITY_DPI; + + SessionSnapshot updated; + synchronized (lock) { + releaseOwnedVirtualDisplayLocked(); + int sessionId = nextSessionId.incrementAndGet(); + if (targetMode == ExecutionMode.VIRTUAL_DISPLAY) { + if (bridgeHost != null && bridgeHost.supportsVirtualDisplay()) { + int displayId = bridgeHost.createVirtualDisplay("phone-use-" + sessionId, w, h, dpi); + if (displayId <= Display.DEFAULT_DISPLAY) { + if (!allowForegroundFallback) { + return StartResult.refused("VIRTUAL_DISPLAY_CREATE_FAILED", current); + } + updated = new SessionSnapshot( + sessionId, pkg, ExecutionMode.FOREGROUND, Display.DEFAULT_DISPLAY, + SessionState.RUNNING, TakeoverReason.NONE, "fallback_create_failed", true, false + ); + } else { + boolean launched = bridgeHost.launchPackageOnDisplay(displayId, pkg, act); + if (!launched) { + bridgeHost.releaseVirtualDisplay(displayId); + if (!allowForegroundFallback) { + return StartResult.refused("VIRTUAL_DISPLAY_LAUNCH_FAILED", current); + } + updated = new SessionSnapshot( + sessionId, pkg, ExecutionMode.FOREGROUND, Display.DEFAULT_DISPLAY, + SessionState.RUNNING, TakeoverReason.NONE, "fallback_launch_failed", true, false + ); + } else { + updated = new SessionSnapshot( + sessionId, pkg, ExecutionMode.VIRTUAL_DISPLAY, displayId, + SessionState.RUNNING, TakeoverReason.NONE, "", false, false + ); + } + } + } else if (allowForegroundFallback) { + updated = new SessionSnapshot( + sessionId, pkg, ExecutionMode.FOREGROUND, Display.DEFAULT_DISPLAY, + SessionState.RUNNING, TakeoverReason.NONE, "virtual_display_unavailable", true, false + ); + } else { + return StartResult.refused("VIRTUAL_DISPLAY_UNAVAILABLE", current); + } + } else { + updated = new SessionSnapshot( + sessionId, pkg, ExecutionMode.FOREGROUND, Display.DEFAULT_DISPLAY, + SessionState.RUNNING, TakeoverReason.NONE, "", false, false + ); + } + current = updated; + } + notifyListener(updated); + return StartResult.started(updated); + } + + /** + * Evaluate screen state and candidate matches to determine whether human takeover is mandatory. + */ + public static TakeoverReason detectTakeoverTrigger( + String packageName, + String activityName, + AlphaControlPolicy.ScreenProtection protection, + List visibleLabels, + int candidateMatchCount + ) { + if (protection != null && protection != AlphaControlPolicy.ScreenProtection.ScreenClear) { + return TakeoverReason.PROTECTED_SCREEN; + } + String pkg = packageName == null ? "" : packageName.trim().toLowerCase(Locale.ROOT); + String act = activityName == null ? "" : activityName.trim().toLowerCase(Locale.ROOT); + if (pkg.contains("permissioncontroller") || pkg.contains("packageinstaller") || act.contains("grantpermissions")) { + return TakeoverReason.PERMISSION; + } + if (act.contains("billing") || act.contains("purchase") || act.contains("payment") || act.contains("checkout")) { + return TakeoverReason.PAYMENT; + } + if (act.contains("login") || act.contains("signin") || act.contains("auth") || act.contains("credential")) { + return TakeoverReason.SIGN_IN; + } + if (visibleLabels != null) { + for (String raw : visibleLabels) { + if (raw == null) continue; + String lower = raw.toLowerCase(Locale.ROOT); + if (containsAny(lower, PERMISSION_MARKERS)) return TakeoverReason.PERMISSION; + if (containsAny(lower, PAYMENT_MARKERS)) return TakeoverReason.PAYMENT; + if (containsAny(lower, SIGN_IN_MARKERS)) return TakeoverReason.SIGN_IN; + } + } + if (candidateMatchCount > 1) { + return TakeoverReason.AMBIGUOUS_TARGET; + } + return TakeoverReason.NONE; + } + + /** + * Pause the active session for human takeover, automatically surfacing any background + * VirtualDisplay task onto {@link Display#DEFAULT_DISPLAY} and releasing the virtual display. + */ + public SessionSnapshot pauseForTakeover(TakeoverReason reason, String detail, String activityName) { + TakeoverReason resolvedReason = reason == null || reason == TakeoverReason.NONE + ? TakeoverReason.AMBIGUOUS_TARGET + : reason; + SessionSnapshot updated; + synchronized (lock) { + boolean surfaced = false; + int priorDisplayId = current.displayId; + String pkg = current.packageName; + if (current.mode == ExecutionMode.VIRTUAL_DISPLAY && priorDisplayId > Display.DEFAULT_DISPLAY) { + if (bridgeHost != null && !pkg.isEmpty() && !AlphaControlPolicy.isBlockedTarget(pkg, activityName)) { + surfaced = bridgeHost.launchPackageOnDisplay(Display.DEFAULT_DISPLAY, pkg, activityName == null ? "" : activityName); + } + releaseOwnedVirtualDisplayLocked(); + } + updated = new SessionSnapshot( + current.sessionId, + pkg, + ExecutionMode.FOREGROUND, + Display.DEFAULT_DISPLAY, + SessionState.PAUSED_FOR_TAKEOVER, + resolvedReason, + detail == null ? "" : detail, + current.fellBackToForeground, + surfaced + ); + current = updated; + } + notifyListener(updated); + return updated; + } + + /** Capture the active session's display (DEFAULT_DISPLAY or managed VirtualDisplay). */ + public byte[] captureActiveDisplay(int maxWidth, int jpegQuality) { + SessionSnapshot snap = currentSnapshot(); + if (snap.state != SessionState.RUNNING || bridgeHost == null || !bridgeHost.supportsCaptureDisplay()) { + return null; + } + return bridgeHost.captureDisplayBytes(snap.displayId, maxWidth, jpegQuality); + } + + /** Inject an allowlisted key event onto the active session's display. */ + public boolean injectKeyOnActiveDisplay(int keyCode, int metaState, int action) { + SessionSnapshot snap = currentSnapshot(); + if (snap.state != SessionState.RUNNING || bridgeHost == null) { + return false; + } + if (snap.displayId != Display.DEFAULT_DISPLAY && !bridgeHost.supportsPerDisplayInput()) { + return false; + } + return bridgeHost.injectKeyEventOnDisplay(snap.displayId, keyCode, metaState, action); + } + + /** Inject a tap gesture onto the active session's display. */ + public boolean injectTapOnActiveDisplay(float x, float y, long downTimeMs) { + SessionSnapshot snap = currentSnapshot(); + if (snap.state != SessionState.RUNNING || bridgeHost == null) { + return false; + } + if (snap.displayId != Display.DEFAULT_DISPLAY && !bridgeHost.supportsPerDisplayInput()) { + return false; + } + return bridgeHost.injectMotionEventOnDisplay(snap.displayId, MotionEvent.ACTION_DOWN, x, y, downTimeMs, downTimeMs) + && bridgeHost.injectMotionEventOnDisplay(snap.displayId, MotionEvent.ACTION_UP, x, y, downTimeMs, downTimeMs + 40L); + } + + /** Stop the active session and idempotently release any owned VirtualDisplay. */ + public SessionSnapshot stopSession(String detail) { + SessionSnapshot updated; + synchronized (lock) { + releaseOwnedVirtualDisplayLocked(); + updated = new SessionSnapshot( + current.sessionId, + current.packageName, + ExecutionMode.FOREGROUND, + Display.DEFAULT_DISPLAY, + SessionState.STOPPED, + TakeoverReason.USER_STOP, + detail == null ? "stopped" : detail, + false, + false + ); + current = updated; + } + notifyListener(updated); + return updated; + } + + private void releaseOwnedVirtualDisplayLocked() { + if (current.mode == ExecutionMode.VIRTUAL_DISPLAY + && current.displayId > Display.DEFAULT_DISPLAY + && bridgeHost != null) { + bridgeHost.releaseVirtualDisplay(current.displayId); + } + } + + private void notifyListener(SessionSnapshot snapshot) { + if (listener != null) { + listener.onSessionStateChanged(snapshot); + } + } + + private static boolean containsAny(String haystack, String[] needles) { + for (String needle : needles) { + if (haystack.contains(needle)) return true; + } + return false; + } +} diff --git a/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/AppFunctionsBridgeTest.java b/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/AppFunctionsBridgeTest.java new file mode 100644 index 0000000000..45d0db6be4 --- /dev/null +++ b/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/AppFunctionsBridgeTest.java @@ -0,0 +1,279 @@ +// spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease" +package ai.alphacompute.control; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.Test; + +/** JUnit tests covering Android 16+/17 AppFunctions schema parsing, filtering, fallback, and execution routing. */ +public final class AppFunctionsBridgeTest { + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } + + private static final class FakeBackend implements AppFunctionsBridge.Backend { + int apiLevel = 36; + boolean available = true; + final List> docs = new ArrayList<>(); + final Map enabledOverrides = new HashMap<>(); + String lastExecutedPackage; + String lastExecutedFunction; + Map lastExecutedParams; + AppFunctionsBridge.ExecutionOutcome nextOutcome = AppFunctionsBridge.ExecutionOutcome.success( + new JSONObject(Map.of("ok", true, "tabId", "t-42")) + ); + + @Override + public int apiLevel() { + return apiLevel; + } + + @Override + public boolean isAvailable() { + return available; + } + + @Override + public List> queryMetadataDocuments(String targetPackage) { + return docs; + } + + @Override + public Boolean checkFunctionEnabled(String targetPackage, String functionId) { + return enabledOverrides.get(targetPackage + "/" + functionId); + } + + @Override + public AppFunctionsBridge.ExecutionOutcome executeFunction( + String targetPackage, + String functionId, + Map parameters, + long timeoutMs + ) { + this.lastExecutedPackage = targetPackage; + this.lastExecutedFunction = functionId; + this.lastExecutedParams = new LinkedHashMap<>(parameters); + return nextOutcome; + } + } + + @Test + public void testApiBelow36SafeFallback() { + FakeBackend backend = new FakeBackend(); + backend.apiLevel = 35; + AppFunctionsBridge bridge = new AppFunctionsBridge(backend, 2_000L); + check(!bridge.isAvailable(), "API 35 must report AppFunctions unavailable"); + + AppFunctionsBridge.DiscoveryOutcome disc = bridge.discover("org.mozilla.firefox"); + check(!disc.ok && "APP_FUNCTIONS_UNAVAILABLE".equals(disc.refusalCode), "API 35 discovery refuses cleanly"); + + AppFunctionsBridge.ExecutionOutcome exec = bridge.execute("org.mozilla.firefox", "browser.openTab", new JSONObject()); + check(!exec.ok && "APP_FUNCTIONS_UNAVAILABLE".equals(exec.refusalCode), "API 35 execution refuses cleanly"); + } + + @Test + public void testDiscoveryFilteringCompactScopingAndBlockedPackages() throws Exception { + FakeBackend backend = new FakeBackend(); + backend.apiLevel = 37; + + Map enabledFirefox = new LinkedHashMap<>(); + enabledFirefox.put("packageName", "org.mozilla.firefox"); + enabledFirefox.put("functionId", "browser.openTab"); + enabledFirefox.put("displayName", "Open Tab"); + enabledFirefox.put("description", "x".repeat(200)); + enabledFirefox.put("schemaCategory", "browser"); + enabledFirefox.put("parameters", List.of("url", "pinned")); + + Map disabledFirefox = new LinkedHashMap<>(); + disabledFirefox.put("packageName", "org.mozilla.firefox"); + disabledFirefox.put("functionId", "browser.clearHistory"); + disabledFirefox.put("enabledByDefault", true); + backend.enabledOverrides.put("org.mozilla.firefox/browser.clearHistory", Boolean.FALSE); + + Map otherApp = new LinkedHashMap<>(); + otherApp.put("packageName", "com.spotify.music"); + otherApp.put("functionId", "media.play"); + + Map blockedApp = new LinkedHashMap<>(); + blockedApp.put("packageName", "com.android.settings"); + blockedApp.put("functionId", "settings.reset"); + + backend.docs.add(enabledFirefox); + backend.docs.add(disabledFirefox); + backend.docs.add(otherApp); + backend.docs.add(blockedApp); + + AppFunctionsBridge bridge = new AppFunctionsBridge(backend, 2_000L); + check(bridge.isAvailable(), "API 37 reports AppFunctions live"); + + AppFunctionsBridge.DiscoveryOutcome scoped = bridge.discover("org.mozilla.firefox"); + check(scoped.ok && scoped.apiLevel == 37, "scoped discovery succeeds on API 37"); + check(scoped.functions.size() == 1, "only enabled functions matching foreground app are returned"); + AppFunctionsBridge.FunctionSchema fn = scoped.functions.get(0); + check("browser.openTab".equals(fn.functionId), "functionId preserved"); + check(fn.description.length() == AppFunctionsBridge.MAX_DESCRIPTION_CHARS, "description compactly capped"); + check(fn.parameterNames.equals(List.of("url", "pinned")), "parameter names preserved"); + + AppFunctionsBridge.DiscoveryOutcome all = bridge.discover(""); + check(all.ok && all.functions.size() == 2, "unscoped discovery still excludes blocked packages and disabled functions"); + + AppFunctionsBridge.DiscoveryOutcome blocked = bridge.discover("com.android.settings"); + check(!blocked.ok && "BLOCKED_PACKAGE".equals(blocked.refusalCode), "blocked package discovery refused"); + } + + @Test + public void testExecutionValidationRoutingAndExecutorWiring() throws Exception { + FakeBackend backend = new FakeBackend(); + backend.apiLevel = 36; + backend.enabledOverrides.put("org.mozilla.firefox/browser.disabled", Boolean.FALSE); + + AppFunctionsBridge bridge = new AppFunctionsBridge(backend, 2_000L); + + check( + "BLOCKED_PACKAGE".equals(bridge.execute("com.android.permissioncontroller", "perm.grant", new JSONObject()).refusalCode), + "blocked package execution refused" + ); + check( + "INVALID_FUNCTION_ID".equals(bridge.execute("org.mozilla.firefox", "bad id!", new JSONObject()).refusalCode), + "invalid function id refused" + ); + check( + "APP_FUNCTION_DISABLED".equals(bridge.execute("org.mozilla.firefox", "browser.disabled", new JSONObject()).refusalCode), + "disabled app function refused before dispatch" + ); + + JSONObject badParams = new JSONObject().put("nested", new JSONObject().put("a", 1)); + check( + "INVALID_PARAMETERS".equals(bridge.execute("org.mozilla.firefox", "browser.openTab", badParams).refusalCode), + "non-primitive parameter refused" + ); + + JSONObject goodParams = new JSONObject() + .put("url", "https://example.org") + .put("pinned", true) + .put("count", 2); + AppFunctionsBridge.ExecutionOutcome ok = bridge.execute("org.mozilla.firefox", "browser.openTab", goodParams); + check(ok.ok && "t-42".equals(ok.result.getString("tabId")), "valid execution returns structured result"); + check("org.mozilla.firefox".equals(backend.lastExecutedPackage), "routed to target package"); + check("browser.openTab".equals(backend.lastExecutedFunction), "routed to function id"); + check(Long.valueOf(2L).equals(backend.lastExecutedParams.get("count")), "int parameter widened to Long for AppSearch"); + + check("APP_FUNCTION_DENIED".equals(AppFunctionsBridge.mapAppFunctionErrorCode(2000)), "error code 2000 maps to DENIED"); + check("APP_FUNCTION_NOT_FOUND".equals(AppFunctionsBridge.mapAppFunctionErrorCode(1003)), "error code 1003 maps to NOT_FOUND"); + check("APP_FUNCTION_DISABLED".equals(AppFunctionsBridge.mapAppFunctionErrorCode(1002)), "error code 1002 maps to DISABLED"); + + backend.docs.add(Map.of( + "packageName", "org.mozilla.firefox", + "functionId", "browser.openTab", + "displayName", "Open Tab", + "parameters", Collections.singletonList("url") + )); + AlphaUiControlExecutor executor = new AlphaUiControlExecutor( + null, + (method, path, body) -> CompletableFuture.completedFuture( + new AlphaUiControlExecutor.TransportResponse(200, "{}".getBytes(StandardCharsets.UTF_8)) + ), + null, + null, + () -> false, + 0L, + bridge, + null, + null + ); + AlphaUiControlExecutor.StepOutcome discovered = executor.executeOperation( + new JSONObject().put("type", "app_functions_discover").put("packageName", "org.mozilla.firefox"), + 0, + "org.mozilla.firefox" + ); + check("done".equals(discovered.outcome), "executor app_functions_discover routes through AppFunctionsBridge"); + JSONArray fns = discovered.result.getJSONArray("functions"); + check(fns.length() == 1 && "browser.openTab".equals(fns.getJSONObject(0).getString("functionId")), "executor returns real discovered functions"); + } + + @Test + public void testAppFunctionExecuteTriggersPostActuationReadbackReceipt() throws Exception { + check( + AlphaUiControlExecutor.shouldRefreshPostActuation("app_function_execute"), + "app_function_execute must trigger post-actuation readback refresh so receipts include postSnapshotId" + ); + check( + !AlphaUiControlExecutor.shouldRefreshPostActuation("app_functions_discover"), + "read-only app_functions_discover does not require post-actuation refresh" + ); + + FakeBackend backend = new FakeBackend(); + backend.apiLevel = 36; + backend.nextOutcome = AppFunctionsBridge.ExecutionOutcome.success( + new JSONObject(Map.of("ok", true, "tabId", "t-99")) + ); + AppFunctionsBridge bridge = new AppFunctionsBridge(backend, 2_000L); + + JSONObject pendingEnvelope = new JSONObject() + .put("op", new JSONObject() + .put("opId", 7) + .put("boundSnapId", 3) + .put("expectedPackage", "org.mozilla.firefox") + .put("op", new JSONObject() + .put("type", "app_function_execute") + .put("functionId", "browser.openTab") + .put("parameters", new JSONObject().put("url", "https://example.org")))); + + java.util.concurrent.atomic.AtomicReference postedReceipt = new java.util.concurrent.atomic.AtomicReference<>(); + AlphaUiControlExecutor executor = new AlphaUiControlExecutor( + null, + (method, path, body) -> { + if ("GET".equals(method) && "/api/alpha-control/next".equals(path)) { + return CompletableFuture.completedFuture( + new AlphaUiControlExecutor.TransportResponse( + 200, + pendingEnvelope.toString().getBytes(StandardCharsets.UTF_8) + ) + ); + } + if ("POST".equals(method) && "/api/alpha-control/receipt".equals(path) && body != null) { + try { + postedReceipt.set(new JSONObject(new String(body, StandardCharsets.UTF_8))); + } catch (Exception ignored) { + postedReceipt.set(null); + } + } + return CompletableFuture.completedFuture( + new AlphaUiControlExecutor.TransportResponse(200, "{}".getBytes(StandardCharsets.UTF_8)) + ); + }, + (op, boundSnapId, expectedPackage) -> { + AppFunctionsBridge.ExecutionOutcome out = bridge.execute( + expectedPackage, + op.optString("functionId", ""), + op.optJSONObject("parameters") + ); + return out.ok + ? new AlphaUiControlExecutor.StepOutcome("done", null, out.result) + : new AlphaUiControlExecutor.StepOutcome("refused", out.refusalCode, null); + }, + (includeNonInteractive, maxNodes, shot) -> 4, + () -> true, + 0L, + bridge, + null, + null + ); + + executor.pollOnce(); + JSONObject receipt = postedReceipt.get(); + check(receipt != null, "pollOnce submitted receipt for app_function_execute"); + check(receipt.getInt("opId") == 7, "receipt carries matching opId"); + check("done".equals(receipt.getString("outcome")), "receipt outcome is done"); + check(receipt.getInt("postSnapshotId") == 4, "receipt carries post-actuation postSnapshotId > boundSnapId"); + check("t-99".equals(receipt.getJSONObject("result").getString("tabId")), "receipt preserves AppFunction structured result"); + } +} diff --git a/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/ReversibleProfileControllerTest.java b/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/ReversibleProfileControllerTest.java new file mode 100644 index 0000000000..d8b063f825 --- /dev/null +++ b/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/ReversibleProfileControllerTest.java @@ -0,0 +1,178 @@ +// spec/app/control/profile.md, "Story: Apply and restore reversible OS profiles while preserving manual edits" +package ai.alphacompute.control; + +import android.app.NotificationManager; +import android.provider.Settings; +import java.nio.charset.StandardCharsets; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import org.json.JSONObject; +import org.junit.Test; + +/** JUnit tests verifying ReversibleProfileController preview purity, manual edit preservation, idempotency, and expiry. */ +public final class ReversibleProfileControllerTest { + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } + + @Test + public void testReadPreviewApplyRestorePreservesManualEditsIdempotently() { + Map initial = new EnumMap<>(ReversibleProfileController.SettingKey.class); + initial.put(ReversibleProfileController.SettingKey.DO_NOT_DISTURB, "off"); + initial.put(ReversibleProfileController.SettingKey.NOTIFICATION_SILENCE, "disabled"); + initial.put(ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS, "60"); + initial.put(ReversibleProfileController.SettingKey.HOME_SHORTCUTS, "default_pack"); + + ReversibleProfileController.InMemorySettingStore store = new ReversibleProfileController.InMemorySettingStore(initial); + ReversibleProfileController controller = new ReversibleProfileController(store); + + Map read = controller.readCurrent(Set.of( + ReversibleProfileController.SettingKey.DO_NOT_DISTURB, + ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS + )); + check("off".equals(read.get(ReversibleProfileController.SettingKey.DO_NOT_DISTURB)), "read returns live DND"); + check("60".equals(read.get(ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS)), "read returns live timeout"); + + ReversibleProfileController.ProfileSpec recording = ReversibleProfileController.recordingProfile(); + ReversibleProfileController.ProfilePreview preview = controller.preview(recording); + check(preview.changes.size() == 4, "preview lists all 4 changes for recording profile"); + check(store.snapshot().equals(initial), "preview must NEVER mutate live settings"); + + long startMs = 10_000L; + long ttlMs = 45 * 60_000L; + ReversibleProfileController.ProfileReceipt receipt = controller.apply(recording, startMs, ttlMs); + check(!receipt.restored && receipt.entries.size() == 4, "apply emits receipt with 4 attributed entries"); + check("alarms_only".equals(store.read(ReversibleProfileController.SettingKey.DO_NOT_DISTURB)), "DND updated"); + check("600".equals(store.read(ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS)), "timeout updated"); + check("recording_pack".equals(store.read(ReversibleProfileController.SettingKey.HOME_SHORTCUTS)), "shortcuts updated"); + + // Owner manually changes screen timeout to 120s mid-profile! + store.write(ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS, "120"); + + ReversibleProfileController.RestoreResult restored = controller.restore(receipt.receiptId); + check(restored.ok && !restored.alreadyRestored, "first restore succeeds"); + check(restored.restoredKeys.size() == 3, "restores the 3 keys still attributable to profile"); + check(restored.preservedManualEdits.size() == 1, "preserves the 1 manually edited key"); + check( + restored.preservedManualEdits.get(0).key == ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS + && "120".equals(restored.preservedManualEdits.get(0).currentUserValue), + "manual edit record captures user's 120s timeout" + ); + + check("off".equals(store.read(ReversibleProfileController.SettingKey.DO_NOT_DISTURB)), "DND restored to baseline"); + check("disabled".equals(store.read(ReversibleProfileController.SettingKey.NOTIFICATION_SILENCE)), "silence restored"); + check("default_pack".equals(store.read(ReversibleProfileController.SettingKey.HOME_SHORTCUTS)), "shortcuts restored"); + check("120".equals(store.read(ReversibleProfileController.SettingKey.SCREEN_TIMEOUT_SECONDS)), "manual 120s timeout preserved!"); + + // Owner later edits DND manually; repeating restore MUST be a safe no-op! + store.write(ReversibleProfileController.SettingKey.DO_NOT_DISTURB, "total_silence"); + ReversibleProfileController.RestoreResult second = controller.restore(receipt.receiptId); + check(second.ok && second.alreadyRestored, "repeated restore is idempotent"); + check("total_silence".equals(store.read(ReversibleProfileController.SettingKey.DO_NOT_DISTURB)), "idempotent restore never overwrites subsequent edits"); + } + + @Test + public void testAutoExpiryAndExecutorProfileRouting() throws Exception { + Map initial = new EnumMap<>(ReversibleProfileController.SettingKey.class); + initial.put(ReversibleProfileController.SettingKey.DO_NOT_DISTURB, "off"); + initial.put(ReversibleProfileController.SettingKey.NOTIFICATION_SILENCE, "disabled"); + ReversibleProfileController.InMemorySettingStore store = new ReversibleProfileController.InMemorySettingStore(initial); + ReversibleProfileController controller = new ReversibleProfileController(store); + + ReversibleProfileController.ProfileReceipt receipt = controller.apply(ReversibleProfileController.focusProfile(), 1_000L, 5_000L); + check(controller.restoreExpired(5_999L).isEmpty(), "not expired before expiresAtMs"); + List expired = controller.restoreExpired(6_000L); + check(expired.size() == 1 && expired.get(0).receiptId.equals(receipt.receiptId), "auto-restores at expiresAtMs"); + check("off".equals(store.read(ReversibleProfileController.SettingKey.DO_NOT_DISTURB)), "baseline restored on expiry"); + + AlphaUiControlExecutor executor = new AlphaUiControlExecutor( + null, + (method, path, body) -> CompletableFuture.completedFuture( + new AlphaUiControlExecutor.TransportResponse(200, "{}".getBytes(StandardCharsets.UTF_8)) + ), + null, + null, + () -> false, + 0L, + null, + null, + controller + ); + AlphaUiControlExecutor.StepOutcome preview = executor.executeOperation( + new JSONObject().put("type", "profile_preview").put("profileId", "focus"), + 0, + "" + ); + check("done".equals(preview.outcome) && preview.result.getJSONArray("changes").length() == 2, "executor previews focus profile"); + + AlphaUiControlExecutor.StepOutcome applied = executor.executeOperation( + new JSONObject().put("type", "profile_apply").put("profileId", "focus").put("durationMs", 60_000), + 0, + "" + ); + check("done".equals(applied.outcome), "executor applies focus profile"); + String receiptId = applied.result.getString("receiptId"); + store.write(ReversibleProfileController.SettingKey.NOTIFICATION_SILENCE, "custom_vip_only"); + + AlphaUiControlExecutor.StepOutcome restored = executor.executeOperation( + new JSONObject().put("type", "profile_restore").put("receiptId", receiptId), + 0, + "" + ); + check("done".equals(restored.outcome), "executor restores focus profile"); + check(restored.result.getJSONArray("restoredKeys").length() == 1, "restored DND only"); + check(restored.result.getJSONArray("preservedManualEdits").length() == 1, "preserved manual notification silence edit"); + check("custom_vip_only".equals(store.read(ReversibleProfileController.SettingKey.NOTIFICATION_SILENCE)), "manual edit intact"); + } + + @Test + public void testAndroidSettingStoreMappingHelpersAndFailClosedValidation() { + boolean rejectedNullContext = false; + try { + new ReversibleProfileController.AndroidSettingStore(null); + } catch (IllegalArgumentException expected) { + rejectedNullContext = true; + } + check(rejectedNullContext, "AndroidSettingStore rejects null Context"); + + check("off".equals(ReversibleProfileController.AndroidSettingStore.interruptionFilterToWire(NotificationManager.INTERRUPTION_FILTER_ALL)), "ALL -> off"); + check("priority".equals(ReversibleProfileController.AndroidSettingStore.interruptionFilterToWire(NotificationManager.INTERRUPTION_FILTER_PRIORITY)), "PRIORITY -> priority"); + check("alarms_only".equals(ReversibleProfileController.AndroidSettingStore.interruptionFilterToWire(NotificationManager.INTERRUPTION_FILTER_ALARMS)), "ALARMS -> alarms_only"); + check("total_silence".equals(ReversibleProfileController.AndroidSettingStore.interruptionFilterToWire(NotificationManager.INTERRUPTION_FILTER_NONE)), "NONE -> total_silence"); + check(ReversibleProfileController.AndroidSettingStore.interruptionFilterToWire(NotificationManager.INTERRUPTION_FILTER_UNKNOWN) == null, "UNKNOWN -> null"); + + check(ReversibleProfileController.AndroidSettingStore.wireToInterruptionFilter("off") == NotificationManager.INTERRUPTION_FILTER_ALL, "off -> ALL"); + check(ReversibleProfileController.AndroidSettingStore.wireToInterruptionFilter("priority") == NotificationManager.INTERRUPTION_FILTER_PRIORITY, "priority -> PRIORITY"); + check(ReversibleProfileController.AndroidSettingStore.wireToInterruptionFilter("alarms_only") == NotificationManager.INTERRUPTION_FILTER_ALARMS, "alarms_only -> ALARMS"); + check(ReversibleProfileController.AndroidSettingStore.wireToInterruptionFilter("total_silence") == NotificationManager.INTERRUPTION_FILTER_NONE, "total_silence -> NONE"); + check(ReversibleProfileController.AndroidSettingStore.wireToInterruptionFilter("bogus") == -1, "invalid DND fails closed"); + check(ReversibleProfileController.AndroidSettingStore.wireToInterruptionFilter(null) == -1, "null DND fails closed"); + + check("7".equals(ReversibleProfileController.AndroidSettingStore.volumeIndexToWire(7, 15)), "valid volume index -> wire"); + check(ReversibleProfileController.AndroidSettingStore.volumeIndexToWire(-1, 15) == null, "negative volume -> null"); + check(ReversibleProfileController.AndroidSettingStore.volumeIndexToWire(16, 15) == null, "above-max volume -> null"); + check(ReversibleProfileController.AndroidSettingStore.wireToVolumeIndex("0", 15) == 0, "0 volume parses"); + check(ReversibleProfileController.AndroidSettingStore.wireToVolumeIndex("15", 15) == 15, "max volume parses"); + check(ReversibleProfileController.AndroidSettingStore.wireToVolumeIndex("16", 15) == -1, "out-of-range volume fails closed"); + check(ReversibleProfileController.AndroidSettingStore.wireToVolumeIndex("-2", 15) == -1, "negative wire volume fails closed"); + check(ReversibleProfileController.AndroidSettingStore.wireToVolumeIndex("loud", 15) == -1, "non-numeric volume fails closed"); + + check("60".equals(ReversibleProfileController.AndroidSettingStore.timeoutMsToSecondsWire(60_000)), "60000ms -> 60s"); + check("600".equals(ReversibleProfileController.AndroidSettingStore.timeoutMsToSecondsWire(600_000)), "600000ms -> 600s"); + check(ReversibleProfileController.AndroidSettingStore.timeoutMsToSecondsWire(0) == null, "0ms -> null"); + check(ReversibleProfileController.AndroidSettingStore.secondsWireToTimeoutMs("600") == 600_000, "600s -> 600000ms"); + check(ReversibleProfileController.AndroidSettingStore.secondsWireToTimeoutMs("14") == -1, "below-min timeout fails closed"); + check(ReversibleProfileController.AndroidSettingStore.secondsWireToTimeoutMs("9999") == -1, "above-max timeout fails closed"); + check(ReversibleProfileController.AndroidSettingStore.secondsWireToTimeoutMs(null) == -1, "null timeout fails closed"); + + check("enabled".equals(ReversibleProfileController.AndroidSettingStore.brightnessModeToWire(Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC)), "AUTOMATIC -> enabled"); + check("disabled".equals(ReversibleProfileController.AndroidSettingStore.brightnessModeToWire(Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL)), "MANUAL -> disabled"); + check(ReversibleProfileController.AndroidSettingStore.brightnessModeToWire(99) == null, "unknown brightness mode -> null"); + check(ReversibleProfileController.AndroidSettingStore.wireToBrightnessMode("enabled") == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC, "enabled -> AUTOMATIC"); + check(ReversibleProfileController.AndroidSettingStore.wireToBrightnessMode("disabled") == Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, "disabled -> MANUAL"); + check(ReversibleProfileController.AndroidSettingStore.wireToBrightnessMode("bright") == -1, "invalid brightness mode fails closed"); + } +} diff --git a/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/VirtualDisplaySessionManagerTest.java b/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/VirtualDisplaySessionManagerTest.java new file mode 100644 index 0000000000..1f151c90e8 --- /dev/null +++ b/apps/app/android/alpha-control/src/test/java/ai/alphacompute/control/VirtualDisplaySessionManagerTest.java @@ -0,0 +1,197 @@ +// spec/app/control/index.md, "Story: Control a third-party app within an owner-approved lease" +package ai.alphacompute.control; + +import android.view.Display; +import android.view.KeyEvent; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import org.junit.Test; + +/** JUnit tests for dual-mode VirtualDisplay lifecycle, foreground fallback, per-display I/O, and human takeover surfacing. */ +public final class VirtualDisplaySessionManagerTest { + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } + + private static final class FakeBridgeHost implements VirtualDisplaySessionManager.BridgeHost { + boolean supportsVd = true; + boolean supportsPerDisplayInput = true; + boolean supportsCapture = true; + boolean launchSucceeds = true; + int nextDisplayId = 10; + final Set activeDisplays = new LinkedHashSet<>(); + final List launches = new ArrayList<>(); + final List keyDisplays = new ArrayList<>(); + final List motionDisplays = new ArrayList<>(); + final List captureDisplays = new ArrayList<>(); + + @Override + public boolean supportsVirtualDisplay() { + return supportsVd; + } + + @Override + public boolean supportsPerDisplayInput() { + return supportsPerDisplayInput; + } + + @Override + public boolean supportsCaptureDisplay() { + return supportsCapture; + } + + @Override + public int createVirtualDisplay(String name, int width, int height, int densityDpi) { + if (!supportsVd) return Display.INVALID_DISPLAY; + int id = nextDisplayId++; + activeDisplays.add(id); + return id; + } + + @Override + public boolean releaseVirtualDisplay(int displayId) { + return activeDisplays.remove(displayId); + } + + @Override + public boolean launchPackageOnDisplay(int displayId, String packageName, String activityName) { + if (!launchSucceeds && displayId != Display.DEFAULT_DISPLAY) return false; + launches.add(displayId + ":" + packageName + ":" + activityName); + return true; + } + + @Override + public byte[] captureDisplayBytes(int displayId, int maxWidth, int jpegQuality) { + captureDisplays.add(displayId); + return new byte[] { 1, 2, 3 }; + } + + @Override + public boolean injectKeyEventOnDisplay(int displayId, int keyCode, int metaState, int action) { + keyDisplays.add(displayId); + return true; + } + + @Override + public boolean injectMotionEventOnDisplay(int displayId, int action, float x, float y, long downTime, long eventTime) { + motionDisplays.add(displayId); + return true; + } + } + + @Test + public void testVirtualDisplayLifecyclePerDisplayRoutingAndTakeoverSurfacing() { + FakeBridgeHost host = new FakeBridgeHost(); + List events = new ArrayList<>(); + VirtualDisplaySessionManager manager = new VirtualDisplaySessionManager(host, events::add); + + VirtualDisplaySessionManager.StartResult blocked = manager.startSession( + "com.android.settings", "", VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, 1080, 2400, 420, true + ); + check(!blocked.ok && "BLOCKED_PACKAGE".equals(blocked.refusalCode), "blocked packages refused on virtual display"); + check(host.activeDisplays.isEmpty(), "no virtual display created for blocked package"); + + VirtualDisplaySessionManager.StartResult started = manager.startSession( + "org.mozilla.firefox", ".HomeActivity", VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, 1080, 2400, 420, true + ); + check(started.ok, "virtual display session starts cleanly"); + check(started.snapshot.mode == VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, "mode is VIRTUAL_DISPLAY"); + check(started.snapshot.displayId == 10, "assigned owned virtual display id"); + check(host.activeDisplays.contains(10), "display tracked as active"); + check(host.launches.contains("10:org.mozilla.firefox:.HomeActivity"), "launched target on virtual display"); + + check(manager.captureActiveDisplay(720, 70) != null, "captures active virtual display"); + check(manager.injectKeyOnActiveDisplay(KeyEvent.KEYCODE_ENTER, 0, KeyEvent.ACTION_DOWN), "injects key on virtual display"); + check(manager.injectTapOnActiveDisplay(120f, 340f, 1000L), "injects tap on virtual display"); + check(host.captureDisplays.equals(List.of(10)), "capture targeted display 10"); + check(host.keyDisplays.equals(List.of(10)), "key injection targeted display 10"); + check(host.motionDisplays.equals(List.of(10, 10)), "tap down+up targeted display 10"); + + VirtualDisplaySessionManager.SessionSnapshot paused = manager.pauseForTakeover( + VirtualDisplaySessionManager.TakeoverReason.SIGN_IN, "OAuth sign-in required", ".AuthActivity" + ); + check(paused.state == VirtualDisplaySessionManager.SessionState.PAUSED_FOR_TAKEOVER, "session paused for takeover"); + check(paused.mode == VirtualDisplaySessionManager.ExecutionMode.FOREGROUND, "takeover shifts mode to foreground"); + check(paused.displayId == Display.DEFAULT_DISPLAY, "takeover targets DEFAULT_DISPLAY"); + check(paused.surfacedToForeground, "background app automatically surfaced to foreground"); + check(host.launches.contains("0:org.mozilla.firefox:.AuthActivity"), "foreground launch executed on display 0"); + check(host.activeDisplays.isEmpty(), "virtual display cleanly released upon takeover"); + + check(manager.captureActiveDisplay(720, 70) == null, "capture refused while paused for takeover"); + check(!manager.injectTapOnActiveDisplay(10f, 20f, 2000L), "input refused while paused for takeover"); + + VirtualDisplaySessionManager.SessionSnapshot stopped = manager.stopSession("owner_stop"); + check(stopped.state == VirtualDisplaySessionManager.SessionState.STOPPED, "stop transitions to STOPPED"); + check(events.size() == 3, "listener notified on start, takeover, and stop"); + } + + @Test + public void testFallbackAndLaunchFailureCleanup() { + FakeBridgeHost noVdHost = new FakeBridgeHost(); + noVdHost.supportsVd = false; + VirtualDisplaySessionManager manager = new VirtualDisplaySessionManager(noVdHost, null); + + VirtualDisplaySessionManager.StartResult strictRefused = manager.startSession( + "org.mozilla.firefox", "", VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, 1080, 2400, 420, false + ); + check(!strictRefused.ok && "VIRTUAL_DISPLAY_UNAVAILABLE".equals(strictRefused.refusalCode), "strict mode refuses when VD unavailable"); + + VirtualDisplaySessionManager.StartResult fallbackOk = manager.startSession( + "org.mozilla.firefox", "", VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, 1080, 2400, 420, true + ); + check(fallbackOk.ok && fallbackOk.snapshot.fellBackToForeground, "graceful fallback to foreground succeeds"); + check(fallbackOk.snapshot.mode == VirtualDisplaySessionManager.ExecutionMode.FOREGROUND, "fallback uses FOREGROUND"); + check(fallbackOk.snapshot.displayId == Display.DEFAULT_DISPLAY, "fallback uses DEFAULT_DISPLAY"); + + FakeBridgeHost failingLaunchHost = new FakeBridgeHost(); + failingLaunchHost.launchSucceeds = false; + VirtualDisplaySessionManager leakGuard = new VirtualDisplaySessionManager(failingLaunchHost, null); + VirtualDisplaySessionManager.StartResult failedLaunch = leakGuard.startSession( + "org.mozilla.firefox", "", VirtualDisplaySessionManager.ExecutionMode.VIRTUAL_DISPLAY, 1080, 2400, 420, false + ); + check(!failedLaunch.ok && "VIRTUAL_DISPLAY_LAUNCH_FAILED".equals(failedLaunch.refusalCode), "launch failure refused"); + check(failingLaunchHost.activeDisplays.isEmpty(), "failed virtual display launch must release VD with zero leaks"); + } + + @Test + public void testTakeoverTriggerClassification() { + check( + VirtualDisplaySessionManager.detectTakeoverTrigger( + "org.mozilla.firefox", ".HomeActivity", AlphaControlPolicy.ScreenProtection.SecureFlag, List.of(), 1 + ) == VirtualDisplaySessionManager.TakeoverReason.PROTECTED_SCREEN, + "SecureFlag triggers PROTECTED_SCREEN" + ); + check( + VirtualDisplaySessionManager.detectTakeoverTrigger( + "org.mozilla.firefox", ".HomeActivity", AlphaControlPolicy.ScreenProtection.ScreenClear, List.of("Enter verification code"), 1 + ) == VirtualDisplaySessionManager.TakeoverReason.SIGN_IN, + "2FA prompt triggers SIGN_IN takeover" + ); + check( + VirtualDisplaySessionManager.detectTakeoverTrigger( + "com.example.shop", ".CheckoutActivity", AlphaControlPolicy.ScreenProtection.ScreenClear, List.of("Pay now"), 1 + ) == VirtualDisplaySessionManager.TakeoverReason.PAYMENT, + "payment screen triggers PAYMENT takeover" + ); + check( + VirtualDisplaySessionManager.detectTakeoverTrigger( + "com.android.permissioncontroller", ".GrantPermissionsActivity", AlphaControlPolicy.ScreenProtection.ScreenClear, List.of(), 1 + ) == VirtualDisplaySessionManager.TakeoverReason.PERMISSION, + "permission prompt triggers PERMISSION takeover" + ); + check( + VirtualDisplaySessionManager.detectTakeoverTrigger( + "org.mozilla.firefox", ".HomeActivity", AlphaControlPolicy.ScreenProtection.ScreenClear, List.of("Delete", "Delete"), 2 + ) == VirtualDisplaySessionManager.TakeoverReason.AMBIGUOUS_TARGET, + "multiple candidate matches trigger AMBIGUOUS_TARGET takeover" + ); + check( + VirtualDisplaySessionManager.detectTakeoverTrigger( + "org.mozilla.firefox", ".HomeActivity", AlphaControlPolicy.ScreenProtection.ScreenClear, List.of("Autoplay off"), 1 + ) == VirtualDisplaySessionManager.TakeoverReason.NONE, + "normal clear screen triggers NONE" + ); + } +} diff --git a/apps/app/aosp/control-bridge/AndroidManifest.xml b/apps/app/aosp/control-bridge/AndroidManifest.xml index 671ffbf128..eddfc8fda2 100644 --- a/apps/app/aosp/control-bridge/AndroidManifest.xml +++ b/apps/app/aosp/control-bridge/AndroidManifest.xml @@ -6,6 +6,9 @@ + + + diff --git a/apps/app/aosp/control-bridge/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl b/apps/app/aosp/control-bridge/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl index f1354d3e5b..bd7be97533 100644 --- a/apps/app/aosp/control-bridge/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl +++ b/apps/app/aosp/control-bridge/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl @@ -9,4 +9,10 @@ interface IAlphaControlBridge { boolean injectKeyEvent(int keyCode, int metaState, int action); boolean injectMotionEvent(int action, float x, float y, long downTime, long eventTime); boolean setAlphaAccessibilityEnabled(boolean enabled); + int createVirtualDisplay(String name, int width, int height, int densityDpi); + boolean releaseVirtualDisplay(int displayId); + boolean launchPackageOnDisplay(int displayId, String packageName, String activityName); + int[] listVirtualDisplays(); + boolean injectKeyEventOnDisplay(int displayId, int keyCode, int metaState, int action); + boolean injectMotionEventOnDisplay(int displayId, int action, float x, float y, long downTime, long eventTime); } diff --git a/apps/app/aosp/control-bridge/privapp-permissions-alpha-control.xml b/apps/app/aosp/control-bridge/privapp-permissions-alpha-control.xml index 6505bc7b78..34365856b0 100644 --- a/apps/app/aosp/control-bridge/privapp-permissions-alpha-control.xml +++ b/apps/app/aosp/control-bridge/privapp-permissions-alpha-control.xml @@ -3,5 +3,8 @@ + + + diff --git a/apps/app/aosp/control-bridge/sepolicy/alpha_control_bridge.te b/apps/app/aosp/control-bridge/sepolicy/alpha_control_bridge.te index b1143c71fb..0f1f9aa4f0 100644 --- a/apps/app/aosp/control-bridge/sepolicy/alpha_control_bridge.te +++ b/apps/app/aosp/control-bridge/sepolicy/alpha_control_bridge.te @@ -10,6 +10,7 @@ binder_use(alpha_control_bridge) allow alpha_control_bridge { accessibility_service activity_service + activity_task_service content_service display_service input_service diff --git a/apps/app/aosp/control-bridge/src/ai/alphacompute/control/AlphaControlBridgeService.java b/apps/app/aosp/control-bridge/src/ai/alphacompute/control/AlphaControlBridgeService.java index da5b05106f..1790c735e1 100644 --- a/apps/app/aosp/control-bridge/src/ai/alphacompute/control/AlphaControlBridgeService.java +++ b/apps/app/aosp/control-bridge/src/ai/alphacompute/control/AlphaControlBridgeService.java @@ -1,15 +1,22 @@ package ai.alphacompute.control; +import android.app.ActivityOptions; import android.app.KeyguardManager; import android.app.Service; +import android.content.ActivityNotFoundException; +import android.content.ComponentName; import android.content.ContentResolver; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.graphics.Bitmap; +import android.graphics.PixelFormat; import android.hardware.HardwareBuffer; +import android.hardware.display.DisplayManager; +import android.hardware.display.VirtualDisplay; import android.hardware.input.InputManagerGlobal; +import android.media.ImageReader; import android.os.Binder; import android.os.Build; import android.os.IBinder; @@ -22,6 +29,7 @@ import android.view.Display; import android.view.IWindowManager; import android.view.InputDevice; +import android.view.InputEvent; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.WindowManagerGlobal; @@ -29,19 +37,29 @@ import android.window.ScreenCaptureInternal; import java.io.IOException; import java.io.OutputStream; +import java.lang.reflect.Method; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.regex.Pattern; /** - * Platform-signed privileged bridge exposing narrowly scoped display capture, - * input injection, and Alpha accessibility toggling solely to the verified - * preinstalled Alpha system package. + * Platform-signed privileged bridge (v2) exposing narrowly scoped display capture, + * trusted virtual display lifecycle, per-display input injection, and Alpha + * accessibility toggling solely to the verified preinstalled Alpha system package. */ public final class AlphaControlBridgeService extends Service { /** Wire protocol version negotiated by AlphaControlBridgeClient. */ - public static final int PROTOCOL_VERSION = 1; + public static final int PROTOCOL_VERSION = 2; /** Bitmask capability for unthrottled non-secure display capture. */ public static final int CAPABILITY_CAPTURE_DISPLAY = 1; @@ -52,6 +70,12 @@ public final class AlphaControlBridgeService extends Service { /** Bitmask capability for toggling Alpha's accessibility service. */ public static final int CAPABILITY_TOGGLE_ACCESSIBILITY = 4; + /** Bitmask capability for managed trusted VirtualDisplay lifecycle and launch. */ + public static final int CAPABILITY_VIRTUAL_DISPLAY = 8; + + /** Bitmask capability for targeting input injection at a specific owned display. */ + public static final int CAPABILITY_PER_DISPLAY_INPUT = 16; + /** Sole authorized client package name. */ public static final String ALPHA_PACKAGE = "ai.alphacompute.alphaphone"; @@ -90,6 +114,96 @@ public final class AlphaControlBridgeService extends Service { static final int MIN_JPEG_QUALITY = 40; static final int MAX_JPEG_QUALITY = 85; + static final int MAX_VIRTUAL_DISPLAYS = 4; + static final int MIN_VIRTUAL_WIDTH = 360; + static final int MAX_VIRTUAL_WIDTH = 1440; + static final int MIN_VIRTUAL_HEIGHT = 640; + static final int MAX_VIRTUAL_HEIGHT = 3200; + static final int MIN_VIRTUAL_DENSITY_DPI = 120; + static final int MAX_VIRTUAL_DENSITY_DPI = 640; + + /** Platform hidden DisplayManager flag enabling touch input on a virtual display. */ + static final int VIRTUAL_DISPLAY_FLAG_SUPPORTS_TOUCH = 1 << 6; + + /** Platform hidden DisplayManager flag destroying hosted tasks upon display release. */ + static final int VIRTUAL_DISPLAY_FLAG_DESTROY_CONTENT_ON_REMOVAL = 1 << 8; + + /** Platform hidden DisplayManager flag marking a virtual display as trusted. */ + static final int VIRTUAL_DISPLAY_FLAG_TRUSTED = 1 << 10; + + private static final Pattern VIRTUAL_DISPLAY_NAME_PATTERN = + Pattern.compile("^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$"); + + private static final Pattern PACKAGE_NAME_PATTERN = + Pattern.compile("^[a-zA-Z][a-zA-Z0-9_]*(\\.[a-zA-Z][a-zA-Z0-9_]*)+$"); + + private static final Pattern ACTIVITY_NAME_PATTERN = + Pattern.compile("^[a-zA-Z0-9_.$]{1,220}$"); + + private static final Set BLOCKED_LAUNCH_PACKAGES; + private static final Map> BLOCKED_ACTIVITY_SUBSTRINGS; + private static final Method SET_DISPLAY_ID_METHOD = resolveSetDisplayIdMethod(); + + static { + final Set blocked = new HashSet<>(); + blocked.add("com.android.permissioncontroller"); + blocked.add("com.google.android.permissioncontroller"); + blocked.add("com.android.packageinstaller"); + blocked.add("com.google.android.packageinstaller"); + blocked.add("com.android.systemui"); + blocked.add("com.android.settings"); + blocked.add("com.google.android.apps.walletnfcrel"); + blocked.add("proton.android.pass"); + blocked.add("com.x8bit.bitwarden"); + blocked.add("com.onepassword.android"); + blocked.add("com.agilebits.onepassword"); + blocked.add("keepass2android.keepass2android"); + blocked.add("com.google.android.apps.authenticator2"); + blocked.add("com.authy.authy"); + blocked.add("ai.alphacompute.alphaphone"); + blocked.add("ai.alphacompute.calendar"); + blocked.add("ai.alphacompute.workflows"); + blocked.add("ai.alphacompute.wallet"); + blocked.add("ai.alphacompute.settings"); + BLOCKED_LAUNCH_PACKAGES = Collections.unmodifiableSet(blocked); + + final Map> activities = new HashMap<>(); + activities.put("com.android.vending", + List.of("PurchaseActivity", "BillingActivity", "FinskyBilling", "AuthActivity", "VerifyApps")); + activities.put("com.google.android.gms", + List.of("Auth", "Account", "Credential", "Wallet", "TapAndPay", "Fido", "Security", "Lockscreen")); + BLOCKED_ACTIVITY_SUBSTRINGS = Collections.unmodifiableMap(activities); + } + + private static final class ManagedVirtualDisplay { + final int displayId; + final String name; + final VirtualDisplay virtualDisplay; + final ImageReader imageReader; + + ManagedVirtualDisplay( + int displayId, + String name, + VirtualDisplay virtualDisplay, + ImageReader imageReader) { + this.displayId = displayId; + this.name = name; + this.virtualDisplay = virtualDisplay; + this.imageReader = imageReader; + } + + void release() { + try { + virtualDisplay.release(); + } finally { + imageReader.close(); + } + } + } + + private final Object virtualDisplayLock = new Object(); + private final Map virtualDisplays = new ConcurrentHashMap<>(); + private final ExecutorService pipeWriter = Executors.newSingleThreadExecutor(runnable -> { Thread thread = new Thread(runnable, "alpha-bridge-capture"); thread.setDaemon(true); @@ -108,13 +222,17 @@ public int getCapabilities() { enforceAlphaCaller(); return CAPABILITY_CAPTURE_DISPLAY | CAPABILITY_INJECT_EVENTS - | CAPABILITY_TOGGLE_ACCESSIBILITY; + | CAPABILITY_TOGGLE_ACCESSIBILITY + | CAPABILITY_VIRTUAL_DISPLAY + | CAPABILITY_PER_DISPLAY_INPUT; } @Override public ParcelFileDescriptor captureDisplay(int displayId, int maxWidth, int jpegQuality) { enforceAlphaCaller(); - if (displayId != Display.DEFAULT_DISPLAY || maxWidth <= 0 || jpegQuality <= 0) { + if (!isTargetDisplayAllowed(displayId, virtualDisplays.keySet()) + || maxWidth <= 0 + || jpegQuality <= 0) { return null; } final int boundedWidth = clampMaxWidth(maxWidth); @@ -132,8 +250,116 @@ public ParcelFileDescriptor captureDisplay(int displayId, int maxWidth, int jpeg @Override public boolean injectKeyEvent(int keyCode, int metaState, int action) { + return injectKeyEventOnDisplay(Display.DEFAULT_DISPLAY, keyCode, metaState, action); + } + + @Override + public boolean injectMotionEvent( + int action, float x, float y, long downTime, long eventTime) { + return injectMotionEventOnDisplay( + Display.DEFAULT_DISPLAY, action, x, y, downTime, eventTime); + } + + @Override + public boolean setAlphaAccessibilityEnabled(boolean enabled) { enforceAlphaCaller(); - if (!isAllowedKeyCode(keyCode) || !isAllowedKeyAction(action)) { + final long token = Binder.clearCallingIdentity(); + try { + final ContentResolver resolver = getContentResolver(); + final String current = Settings.Secure.getString( + resolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); + final String updated = updateEnabledAccessibilityServices(current, enabled); + final boolean wroteServices = Settings.Secure.putString( + resolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, updated); + if (!wroteServices) { + return false; + } + final int accessibilityEnabled = updated.isEmpty() ? 0 : 1; + return Settings.Secure.putInt( + resolver, Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled); + } finally { + Binder.restoreCallingIdentity(token); + } + } + + @Override + public int createVirtualDisplay(String name, int width, int height, int densityDpi) { + enforceAlphaCaller(); + if (!isValidVirtualDisplayName(name) + || !isValidVirtualDisplayGeometry(width, height, densityDpi)) { + return Display.INVALID_DISPLAY; + } + final long token = Binder.clearCallingIdentity(); + try { + if (!isDeviceUnlocked()) { + return Display.INVALID_DISPLAY; + } + return createVirtualDisplayUnlocked(name.trim(), width, height, densityDpi); + } finally { + Binder.restoreCallingIdentity(token); + } + } + + @Override + public boolean releaseVirtualDisplay(int displayId) { + enforceAlphaCaller(); + if (displayId <= Display.DEFAULT_DISPLAY) { + return false; + } + final long token = Binder.clearCallingIdentity(); + try { + final ManagedVirtualDisplay removed; + synchronized (virtualDisplayLock) { + removed = virtualDisplays.remove(displayId); + } + if (removed == null) { + return false; + } + removed.release(); + return true; + } finally { + Binder.restoreCallingIdentity(token); + } + } + + @Override + public boolean launchPackageOnDisplay( + int displayId, String packageName, String activityName) { + enforceAlphaCaller(); + if (!isTargetDisplayAllowed(displayId, virtualDisplays.keySet()) + || !isValidPackageName(packageName) + || isBlockedLaunchTarget(packageName, activityName)) { + return false; + } + final String trimmedActivity = activityName == null ? "" : activityName.trim(); + if (!trimmedActivity.isEmpty() && !isValidActivityClassName(trimmedActivity)) { + return false; + } + final long token = Binder.clearCallingIdentity(); + try { + if (!isDeviceUnlocked()) { + return false; + } + return launchPackageOnDisplayUnlocked( + displayId, packageName.trim(), trimmedActivity); + } finally { + Binder.restoreCallingIdentity(token); + } + } + + @Override + public int[] listVirtualDisplays() { + enforceAlphaCaller(); + return sortedDisplayIds(virtualDisplays.keySet()); + } + + @Override + public boolean injectKeyEventOnDisplay( + int displayId, int keyCode, int metaState, int action) { + enforceAlphaCaller(); + if (!isTargetDisplayAllowed(displayId, virtualDisplays.keySet()) + || !isAllowedKeyCode(keyCode) + || !isAllowedKeyAction(action)) { return false; } final int normalizedMeta = KeyEvent.normalizeMetaState(metaState); @@ -158,6 +384,9 @@ public boolean injectKeyEvent(int keyCode, int metaState, int action) { 0, 0, InputDevice.SOURCE_KEYBOARD); + if (displayId != Display.DEFAULT_DISPLAY && !applyEventDisplayId(event, displayId)) { + return false; + } return inputManager.injectInputEvent( event, InputEventInjectionSync.WAIT_FOR_FINISHED); } finally { @@ -166,10 +395,11 @@ public boolean injectKeyEvent(int keyCode, int metaState, int action) { } @Override - public boolean injectMotionEvent( - int action, float x, float y, long downTime, long eventTime) { + public boolean injectMotionEventOnDisplay( + int displayId, int action, float x, float y, long downTime, long eventTime) { enforceAlphaCaller(); - if (!isAllowedMotionAction(action) + if (!isTargetDisplayAllowed(displayId, virtualDisplays.keySet()) + || !isAllowedMotionAction(action) || !isValidCoordinate(x, y) || downTime <= 0L || eventTime < downTime) { @@ -187,6 +417,10 @@ public boolean injectMotionEvent( final MotionEvent event = MotionEvent.obtain(downTime, eventTime, action, x, y, 0); try { event.setSource(InputDevice.SOURCE_TOUCHSCREEN); + if (displayId != Display.DEFAULT_DISPLAY + && !applyEventDisplayId(event, displayId)) { + return false; + } return inputManager.injectInputEvent( event, InputEventInjectionSync.WAIT_FOR_FINISHED); } finally { @@ -196,28 +430,6 @@ public boolean injectMotionEvent( Binder.restoreCallingIdentity(token); } } - - @Override - public boolean setAlphaAccessibilityEnabled(boolean enabled) { - enforceAlphaCaller(); - final long token = Binder.clearCallingIdentity(); - try { - final ContentResolver resolver = getContentResolver(); - final String current = Settings.Secure.getString( - resolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES); - final String updated = updateEnabledAccessibilityServices(current, enabled); - final boolean wroteServices = Settings.Secure.putString( - resolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, updated); - if (!wroteServices) { - return false; - } - final int accessibilityEnabled = updated.isEmpty() ? 0 : 1; - return Settings.Secure.putInt( - resolver, Settings.Secure.ACCESSIBILITY_ENABLED, accessibilityEnabled); - } finally { - Binder.restoreCallingIdentity(token); - } - } }; private static final class KeyCharacterMapCompat { @@ -231,10 +443,106 @@ public IBinder onBind(Intent intent) { @Override public void onDestroy() { + releaseAllVirtualDisplays(); pipeWriter.shutdownNow(); super.onDestroy(); } + /** Releases every managed virtual display owned by this bridge service. */ + private void releaseAllVirtualDisplays() { + final List snapshot; + synchronized (virtualDisplayLock) { + snapshot = new ArrayList<>(virtualDisplays.values()); + virtualDisplays.clear(); + } + for (ManagedVirtualDisplay managed : snapshot) { + try { + managed.release(); + } catch (RuntimeException ignored) { + } + } + } + + /** Creates and registers a trusted non-secure VirtualDisplay for background control. */ + private int createVirtualDisplayUnlocked( + String sanitizedName, int width, int height, int densityDpi) { + final DisplayManager displayManager = getSystemService(DisplayManager.class); + if (displayManager == null) { + return Display.INVALID_DISPLAY; + } + synchronized (virtualDisplayLock) { + if (virtualDisplays.size() >= MAX_VIRTUAL_DISPLAYS) { + return Display.INVALID_DISPLAY; + } + final ImageReader imageReader = ImageReader.newInstance( + width, height, PixelFormat.RGBA_8888, 2); + final VirtualDisplay virtualDisplay; + try { + virtualDisplay = displayManager.createVirtualDisplay( + "alpha-vd-" + sanitizedName, + width, + height, + densityDpi, + imageReader.getSurface(), + virtualDisplayFlags()); + } catch (RuntimeException creationFailure) { + imageReader.close(); + return Display.INVALID_DISPLAY; + } + if (virtualDisplay == null || virtualDisplay.getDisplay() == null) { + if (virtualDisplay != null) { + virtualDisplay.release(); + } + imageReader.close(); + return Display.INVALID_DISPLAY; + } + final int displayId = virtualDisplay.getDisplay().getDisplayId(); + if (displayId <= Display.DEFAULT_DISPLAY || virtualDisplays.containsKey(displayId)) { + virtualDisplay.release(); + imageReader.close(); + return Display.INVALID_DISPLAY; + } + virtualDisplays.put( + displayId, + new ManagedVirtualDisplay(displayId, sanitizedName, virtualDisplay, imageReader)); + return displayId; + } + } + + /** Launches an allowlisted package or activity onto {@code displayId}. */ + private boolean launchPackageOnDisplayUnlocked( + int displayId, String packageName, String activityName) { + final Intent intent; + if (!activityName.isEmpty()) { + final String resolvedClass = activityName.startsWith(".") + ? packageName + activityName + : activityName; + intent = new Intent(Intent.ACTION_MAIN); + intent.setComponent(new ComponentName(packageName, resolvedClass)); + } else { + final PackageManager pm = getPackageManager(); + if (pm == null) { + return false; + } + intent = pm.getLaunchIntentForPackage(packageName); + if (intent == null) { + return false; + } + } + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + if (displayId != Display.DEFAULT_DISPLAY) { + intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK); + } + final ActivityOptions options = ActivityOptions.makeBasic(); + options.setLaunchDisplayId(displayId); + try { + startActivity(intent, options.toBundle()); + return true; + } catch (ActivityNotFoundException | SecurityException | IllegalArgumentException failed) { + return false; + } + } + /** * Enforces that the IPC caller is exclusively the preinstalled system copy of * Alpha signed by Alpha's canonical release certificate. @@ -420,6 +728,117 @@ private static Bitmap scaleBitmapToMaxWidth(Bitmap source, int maxWidth) { return Bitmap.createScaledBitmap(source, maxWidth, targetHeight, true); } + /** Returns the platform VirtualDisplay flags for a trusted, private, non-secure display. */ + static int virtualDisplayFlags() { + return DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY + | VIRTUAL_DISPLAY_FLAG_SUPPORTS_TOUCH + | VIRTUAL_DISPLAY_FLAG_DESTROY_CONTENT_ON_REMOVAL + | VIRTUAL_DISPLAY_FLAG_TRUSTED; + } + + /** Returns true only when {@code displayId} is DEFAULT_DISPLAY or an owned virtual display. */ + static boolean isTargetDisplayAllowed(int displayId, Collection ownedDisplayIds) { + if (displayId == Display.DEFAULT_DISPLAY) { + return true; + } + return displayId > Display.DEFAULT_DISPLAY + && ownedDisplayIds != null + && ownedDisplayIds.contains(displayId); + } + + /** Returns a deterministically sorted array of owned virtual display ids. */ + static int[] sortedDisplayIds(Collection ownedDisplayIds) { + if (ownedDisplayIds == null || ownedDisplayIds.isEmpty()) { + return new int[0]; + } + final int[] ids = new int[ownedDisplayIds.size()]; + int idx = 0; + for (Integer id : ownedDisplayIds) { + if (id != null && id > Display.DEFAULT_DISPLAY) { + ids[idx++] = id; + } + } + final int[] trimmed = idx == ids.length ? ids : Arrays.copyOf(ids, idx); + Arrays.sort(trimmed); + return trimmed; + } + + /** Validates virtual display names as short alphanumeric/slug identifiers. */ + static boolean isValidVirtualDisplayName(String name) { + return name != null && VIRTUAL_DISPLAY_NAME_PATTERN.matcher(name.trim()).matches(); + } + + /** Validates virtual display geometry within safe display memory bounds. */ + static boolean isValidVirtualDisplayGeometry(int width, int height, int densityDpi) { + return width >= MIN_VIRTUAL_WIDTH + && width <= MAX_VIRTUAL_WIDTH + && height >= MIN_VIRTUAL_HEIGHT + && height <= MAX_VIRTUAL_HEIGHT + && densityDpi >= MIN_VIRTUAL_DENSITY_DPI + && densityDpi <= MAX_VIRTUAL_DENSITY_DPI; + } + + /** Validates an Android application package name. */ + static boolean isValidPackageName(String packageName) { + if (packageName == null) { + return false; + } + final String trimmed = packageName.trim(); + return trimmed.length() <= 160 && PACKAGE_NAME_PATTERN.matcher(trimmed).matches(); + } + + /** Validates an optional activity class name for explicit display launch. */ + static boolean isValidActivityClassName(String activityName) { + return activityName != null && ACTIVITY_NAME_PATTERN.matcher(activityName.trim()).matches(); + } + + /** Returns true when {@code packageName} or {@code activityName} is blocked from bridge launch. */ + static boolean isBlockedLaunchTarget(String packageName, String activityName) { + if (packageName == null) { + return true; + } + final String pkg = packageName.trim(); + if (pkg.isEmpty() || BLOCKED_LAUNCH_PACKAGES.contains(pkg)) { + return true; + } + final List markers = BLOCKED_ACTIVITY_SUBSTRINGS.get(pkg); + if (markers == null || activityName == null) { + return false; + } + final String activity = activityName.trim(); + if (activity.isEmpty()) { + return false; + } + for (String marker : markers) { + if (activity.contains(marker)) { + return true; + } + } + return false; + } + + /** Resolves hidden platform {@code InputEvent.setDisplayId(int)} for per-display injection. */ + private static Method resolveSetDisplayIdMethod() { + try { + return InputEvent.class.getMethod("setDisplayId", int.class); + } catch (NoSuchMethodException unavailable) { + return null; + } + } + + /** Sets the target display id on an {@link InputEvent} when targeting a virtual display. */ + private static boolean applyEventDisplayId(InputEvent event, int displayId) { + if (SET_DISPLAY_ID_METHOD == null) { + return false; + } + try { + SET_DISPLAY_ID_METHOD.invoke(event, displayId); + return true; + } catch (ReflectiveOperationException failed) { + return false; + } + } + /** Clamps requested capture width to the permitted range. */ static int clampMaxWidth(int maxWidth) { return Math.max(MIN_CAPTURE_WIDTH, Math.min(MAX_CAPTURE_WIDTH, maxWidth)); diff --git a/apps/app/aosp/control-bridge/test_bridge_plan.py b/apps/app/aosp/control-bridge/test_bridge_plan.py index d8f9fdeeeb..7cf41f73a5 100644 --- a/apps/app/aosp/control-bridge/test_bridge_plan.py +++ b/apps/app/aosp/control-bridge/test_bridge_plan.py @@ -1,7 +1,6 @@ from pathlib import Path import json import os -import re import subprocess import sys import tempfile @@ -133,6 +132,9 @@ def test_aosp_build_manifest_permissions_and_sepolicy_invariants(self): 'android.permission.READ_FRAME_BUFFER', 'android.permission.ACCESS_SURFACE_FLINGER', 'android.permission.WRITE_SECURE_SETTINGS', + 'android.permission.ADD_TRUSTED_DISPLAY', + 'android.permission.CAPTURE_VIDEO_OUTPUT', + 'android.permission.START_ACTIVITIES_FROM_BACKGROUND', }) self.assertNotIn('android.permission.INTERNET', perms) @@ -144,6 +146,9 @@ def test_aosp_build_manifest_permissions_and_sepolicy_invariants(self): self.assertEqual(granted, { 'android.permission.READ_FRAME_BUFFER', 'android.permission.WRITE_SECURE_SETTINGS', + 'android.permission.ADD_TRUSTED_DISPLAY', + 'android.permission.CAPTURE_VIDEO_OUTPUT', + 'android.permission.START_ACTIVITIES_FROM_BACKGROUND', }) te = (ROOT / 'sepolicy' / 'alpha_control_bridge.te').read_text() @@ -151,7 +156,15 @@ def test_aosp_build_manifest_permissions_and_sepolicy_invariants(self): self.assertIn('app_domain(alpha_control_bridge)', te) self.assertNotIn('net_domain(', te) self.assertIn('neverallow alpha_control_bridge self:{ tcp_socket udp_socket rawip_socket icmp_socket packet_socket }', te) - for svc in ['window_service', 'input_service', 'surfaceflinger_service', 'accessibility_service', 'settings_service']: + for svc in [ + 'window_service', + 'input_service', + 'surfaceflinger_service', + 'accessibility_service', + 'settings_service', + 'display_service', + 'activity_task_service', + ]: self.assertIn(svc, te) seapp = (ROOT / 'sepolicy' / 'seapp_contexts').read_text().strip() @@ -160,6 +173,22 @@ def test_aosp_build_manifest_permissions_and_sepolicy_invariants(self): self.assertIn('isPrivApp=true', seapp) self.assertIn('domain=alpha_control_bridge', seapp) + aosp_aidl = (ROOT / 'aidl/ai/alphacompute/control/IAlphaControlBridge.aidl').read_text() + android_aidl = ( + ROOT.parent.parent + / 'android/alpha-control/src/main/aidl/ai/alphacompute/control/IAlphaControlBridge.aidl' + ).read_text() + self.assertEqual(aosp_aidl, android_aidl, 'AOSP and alpha-control AIDL files must match') + for symbol in [ + 'createVirtualDisplay', + 'releaseVirtualDisplay', + 'launchPackageOnDisplay', + 'listVirtualDisplays', + 'injectKeyEventOnDisplay', + 'injectMotionEventOnDisplay', + ]: + self.assertIn(symbol, aosp_aidl) + service_src = (ROOT / 'src/ai/alphacompute/control/AlphaControlBridgeService.java').read_text() self.assertIn('static final boolean CAPTURE_SECURE_LAYERS = false;', service_src) self.assertIn('PackageManager.MATCH_SYSTEM_ONLY', service_src) @@ -208,8 +237,13 @@ def test_aidl_compiles_with_android_api36_and_policy_runs_on_jvm(self): harness.write_text(f''' package ai.alphacompute.control; +import android.hardware.display.DisplayManager; +import android.view.Display; import android.view.KeyEvent; import android.view.MotionEvent; +import java.util.Arrays; +import java.util.List; +import java.util.Set; public final class BridgePolicyTest {{ private static void check(boolean condition, String label) {{ @@ -227,7 +261,7 @@ def test_aidl_compiles_with_android_api36_and_policy_runs_on_jvm(self): }} public static void main(String[] args) {{ - check(AlphaControlBridgeService.PROTOCOL_VERSION == 1, "protocol version"); + check(AlphaControlBridgeService.PROTOCOL_VERSION == 2, "protocol version v2"); check(!AlphaControlBridgeService.CAPTURE_SECURE_LAYERS, "secure layers hardcoded false"); check("{expected_signer}".equals(toHex(AlphaControlBridgeService.ALPHA_SIGNER_SHA256)), "signer digest matches release-signer.json"); @@ -280,6 +314,50 @@ def test_aidl_compiles_with_android_api36_and_policy_runs_on_jvm(self): check(AlphaControlBridgeService.clampMaxWidth(4096) == 1440, "clamps max width"); check(AlphaControlBridgeService.clampJpegQuality(10) == 40, "clamps min quality"); check(AlphaControlBridgeService.clampJpegQuality(100) == 85, "clamps max quality"); + + int vdFlags = AlphaControlBridgeService.virtualDisplayFlags(); + check((vdFlags & DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY) != 0, "vd own content only"); + check((vdFlags & AlphaControlBridgeService.VIRTUAL_DISPLAY_FLAG_TRUSTED) != 0, "vd trusted flag"); + check((vdFlags & AlphaControlBridgeService.VIRTUAL_DISPLAY_FLAG_SUPPORTS_TOUCH) != 0, "vd supports touch"); + check((vdFlags & DisplayManager.VIRTUAL_DISPLAY_FLAG_SECURE) == 0, "vd must never set SECURE flag"); + check((vdFlags & DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC) == 0, "vd must never be PUBLIC"); + + check(AlphaControlBridgeService.isTargetDisplayAllowed(Display.DEFAULT_DISPLAY, Set.of()), + "allows default display"); + check(AlphaControlBridgeService.isTargetDisplayAllowed(7, Set.of(7, 9)), + "allows owned virtual display"); + check(!AlphaControlBridgeService.isTargetDisplayAllowed(8, Set.of(7, 9)), + "rejects unowned virtual display"); + check(!AlphaControlBridgeService.isTargetDisplayAllowed(-1, Set.of(7)), + "rejects negative displayId"); + + check(Arrays.equals( + AlphaControlBridgeService.sortedDisplayIds(List.of(12, 3, 7)), + new int[] {{ 3, 7, 12 }}), + "sorts owned virtual display ids"); + + check(AlphaControlBridgeService.isValidVirtualDisplayName("phone-use_1"), "accepts slug name"); + check(!AlphaControlBridgeService.isValidVirtualDisplayName(""), "rejects empty name"); + check(!AlphaControlBridgeService.isValidVirtualDisplayName("../bad"), "rejects path-like name"); + + check(AlphaControlBridgeService.isValidVirtualDisplayGeometry(1080, 2400, 420), "accepts phone geometry"); + check(!AlphaControlBridgeService.isValidVirtualDisplayGeometry(200, 2400, 420), "rejects tiny width"); + check(!AlphaControlBridgeService.isValidVirtualDisplayGeometry(1080, 4000, 420), "rejects huge height"); + check(!AlphaControlBridgeService.isValidVirtualDisplayGeometry(1080, 2400, 50), "rejects tiny dpi"); + + check(AlphaControlBridgeService.isBlockedLaunchTarget("com.android.settings", null), + "blocks launching Settings on virtual display"); + check(AlphaControlBridgeService.isBlockedLaunchTarget("com.android.permissioncontroller", null), + "blocks launching PermissionController on virtual display"); + check(AlphaControlBridgeService.isBlockedLaunchTarget("ai.alphacompute.alphaphone", null), + "blocks launching Alpha approval host"); + check(AlphaControlBridgeService.isBlockedLaunchTarget("com.android.vending", "BillingActivity"), + "blocks Play billing activity"); + check(!AlphaControlBridgeService.isBlockedLaunchTarget("org.mozilla.firefox", "org.mozilla.fenix.HomeActivity"), + "allows normal app launch"); + check(AlphaControlBridgeService.isValidActivityClassName(".HomeActivity"), "allows relative activity"); + check(!AlphaControlBridgeService.isValidActivityClassName("bad activity!"), "rejects malformed activity"); + System.out.println("PASS control-bridge compile and policy tests"); }} }} diff --git a/apps/app/test/drivers/app__control.ts b/apps/app/test/drivers/app__control.ts index 0b5a4b5fb9..b6c6595877 100644 --- a/apps/app/test/drivers/app__control.ts +++ b/apps/app/test/drivers/app__control.ts @@ -3,7 +3,8 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import type { Driver, Options } from "../../gen/app__control.conformance.ts"; import type { - ControlEffect, ControlOp, ControlState, ControlTier, ExecutionOutcome, LeaseStatus, ScreenProtection, TargetKind, + ControlEffect, ControlOp, ControlState, ControlTier, ExecutionMode, ExecutionOutcome, + LeaseStatus, ScreenProtection, TakeoverReason, TargetKind, } from "../../gen/app__control.ts"; interface CoordinatorSnapshot { @@ -21,6 +22,8 @@ interface CoordinatorSnapshot { readonly usedOps: number; readonly expiresAtMs: number; readonly status: LeaseStatus; + readonly mode: ExecutionMode; + readonly displayId: number; }; readonly pending: { readonly opId: number; @@ -30,13 +33,16 @@ interface CoordinatorSnapshot { } | null; readonly lastResult: "done" | "refused" | "preempted"; readonly killed: boolean; + readonly needsReconcile: boolean; + readonly takeover: TakeoverReason; + readonly lastReadbackSnapId: number; } type CoordinatorPending = NonNullable; type CoordinatorEffect = | Exclude - | { readonly tag: "DispatchOp"; readonly pending: CoordinatorPending }; + | { readonly tag: "DispatchOp"; readonly pending: CoordinatorPending; readonly mode: ExecutionMode; readonly displayId: number }; interface CoordinatorLike { readState(): CoordinatorSnapshot; @@ -48,7 +54,14 @@ interface CoordinatorLike { nowMs: number, ): { readonly ok: true; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false }; grantLease( - input: { readonly leaseId?: number; readonly packageName: string; readonly maxOps: number; readonly durationMs: number }, + input: { + readonly leaseId?: number; + readonly packageName: string; + readonly maxOps: number; + readonly durationMs: number; + readonly mode?: ExecutionMode; + readonly displayId?: number; + }, nowMs: number, ): { readonly ok: true } | { readonly ok: false }; dispatch( @@ -60,6 +73,11 @@ interface CoordinatorLike { input: Record, nowMs: number, ): { readonly ok: true; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false }; + pauseForTakeover( + reason: TakeoverReason, + nowMs: number, + ): { readonly ok: true; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false }; + resumeAfterTakeover(): { readonly ok: true } | { readonly ok: false }; expireLease(nowMs: number): { readonly ok: true; readonly effects: readonly CoordinatorEffect[] } | { readonly ok: false }; stop(reason: string, nowMs: number): { readonly effects: readonly CoordinatorEffect[] }; } @@ -145,6 +163,9 @@ export interface ObservedControlView { readonly lastResult: ExecutionOutcome; readonly lastOpId: number; readonly killed: boolean; + readonly needsReconcile: boolean; + readonly takeover: TakeoverReason; + readonly lastReadbackSnapId: number; } function packageFor(appId: number, targetKind: TargetKind): string { @@ -162,7 +183,7 @@ function appIdFor(packageName: string): number { function specEffectOf(effect: CoordinatorEffect): ControlEffect { if (effect.tag !== "DispatchOp") return effect; - const { pending } = effect; + const { pending, mode, displayId } = effect; const op = OP_TYPE_TO_SPEC[pending.op.type]; if (op === undefined) throw new Error(`The coordinator dispatched an operation the spec does not name: ${pending.op.type}`); return { @@ -171,6 +192,8 @@ function specEffectOf(effect: CoordinatorEffect): ControlEffect { op, snapId: pending.boundSnapId, appId: appIdFor(pending.expectedPackage), + mode, + displayId, }; } @@ -254,10 +277,13 @@ function projectState(state: ControlState): ObservedControlView { lastResult: state.lastResult, lastOpId: state.lastOpId, killed: state.killed, + needsReconcile: state.needsReconcile, + takeover: state.takeover, + lastReadbackSnapId: state.lastReadbackSnapId, }; } -/** Conformance driver exercising `AlphaControlCoordinator` against `spec/app/control/index.md`. */ +/** Conformance driver exercising `AlphaControlCoordinator` against `spec/app/control/index.md` v2. */ export const driver: Driver = { reset: () => { entries.clear(); @@ -298,6 +324,8 @@ export const driver: Driver = { packageName: packageFor(event.appId, "AllowedApp"), maxOps: event.maxOps, durationMs, + mode: event.mode, + displayId: event.mode === "ModeVirtualDisplay" ? event.leaseId : 0, }, event.now * TIME_SCALE_MS); return moved.ok ? "accepted" : "refused"; } @@ -314,15 +342,28 @@ export const driver: Driver = { return "accepted"; } case "finish": { - if (by !== "Phone") return "refused"; + if (by !== "Phone" || event.readbackSnapId < 0) return "refused"; const moved = coordinator.recordReceipt({ opId: event.opId, outcome: OUTCOME_TO_WIRE[event.verdict], + postSnapshotId: event.readbackSnapId, }, 0); if (!moved.ok) return "refused"; entry.out = moved.effects.map(specEffectOf); return "accepted"; } + case "pauseForTakeover": { + if (by !== "Phone") return "refused"; + const moved = coordinator.pauseForTakeover(event.reason, 0); + if (!moved.ok) return "refused"; + entry.out = moved.effects.map(specEffectOf); + return "accepted"; + } + case "resumeAfterTakeover": { + if (by !== "Owner") return "refused"; + const moved = coordinator.resumeAfterTakeover(); + return moved.ok ? "accepted" : "refused"; + } case "expireLease": { if (by !== "Phone") return "refused"; const moved = coordinator.expireLease(event.now * TIME_SCALE_MS); @@ -356,6 +397,8 @@ export const driver: Driver = { usedOps: state.lease.usedOps, expiresAt: Math.trunc(state.lease.expiresAtMs / TIME_SCALE_MS), status: state.lease.status, + mode: state.lease.mode, + displayId: state.lease.displayId, }, pending: state.pending !== null && pendingOp !== undefined ? { @@ -369,6 +412,9 @@ export const driver: Driver = { lastResult: OUTCOME_FROM_WIRE[state.lastResult], lastOpId: coordinator.currentLastOpId(), killed: state.killed, + needsReconcile: state.needsReconcile, + takeover: state.takeover, + lastReadbackSnapId: state.lastReadbackSnapId, }; }, observeOutput: (key) => entryFor(key).out, diff --git a/apps/app/test/drivers/app__control__profile.ts b/apps/app/test/drivers/app__control__profile.ts new file mode 100644 index 0000000000..021b4d7d30 --- /dev/null +++ b/apps/app/test/drivers/app__control__profile.ts @@ -0,0 +1,145 @@ +// spec/app/control/profile.md, "Story: Apply and restore reversible OS profiles while preserving manual edits" +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import type { Driver, Options } from "../../gen/app__control__profile.conformance.ts"; +import type { ProfilePhase, ProfileState, SettingVal } from "../../gen/app__control__profile.ts"; + +interface ProfileStoreLike { + readCurrent(keys?: readonly ("dnd_mode" | "screen_timeout_seconds")[]): Readonly>>; + manualEdit(key: "dnd_mode" | "screen_timeout_seconds", value: string | undefined): void; + preview(spec: { readonly profileId: string; readonly displayName: string; readonly targetValues: Readonly>> }): unknown; + apply(spec: { readonly profileId: string; readonly displayName: string; readonly targetValues: Readonly>> }, nowMs: number, durationMs?: number): { readonly receiptId: string }; + restore(receiptId: string): { readonly ok: boolean }; +} + +interface ProfilesModuleLike { + readonly ReversibleProfileStore: new (initial?: Readonly>>) => ProfileStoreLike; +} + +function isProfilesModule(value: unknown): value is ProfilesModuleLike { + return typeof value === "object" + && value !== null + && "ReversibleProfileStore" in value + && typeof (value as { readonly ReversibleProfileStore: unknown }).ReversibleProfileStore === "function"; +} + +const moduleUrl = pathToFileURL(path.resolve(import.meta.dirname, "../../../agent/src/plugins/control/profiles.ts")).href; +const loaded: unknown = await import(moduleUrl); +if (!isProfilesModule(loaded)) { + throw new Error(`Expected ReversibleProfileStore export at ${moduleUrl}`); +} +const { ReversibleProfileStore } = loaded; + +/** Observable projection shared by spec/app/control/profile.md and ReversibleProfileStore. */ +export interface ObservedProfileView { + readonly phase: ProfilePhase; + readonly live1: SettingVal; + readonly live2: SettingVal; + readonly receiptCount: number; +} + +interface Entry { + readonly store: ProfileStoreLike; + phase: ProfilePhase; + lastReceiptId: string | null; + receiptCount: number; +} + +const sessions = new Map(); + +function sessionOf(key: string): Entry { + let found = sessions.get(key); + if (found === undefined) { + found = { + store: new ReversibleProfileStore({ dnd_mode: "ValBase", screen_timeout_seconds: "ValBase" }), + phase: "ProfileIdle", + lastReceiptId: null, + receiptCount: 0, + }; + sessions.set(key, found); + } + return found; +} + +function toSettingVal(raw: string | undefined): SettingVal { + if (raw === "ValProfile" || raw === "ValManual") return raw; + return "ValBase"; +} + +function projectProfile(state: ProfileState): ObservedProfileView { + return { + phase: state.phase, + live1: state.live1, + live2: state.live2, + receiptCount: state.receiptCount, + }; +} + +/** Conformance driver verifying `ReversibleProfileStore` against `spec/app/control/profile.md`. */ +export const driver: Driver = { + reset: () => { + sessions.clear(); + }, + dispatch: (key, event) => { + const entry = sessionOf(key); + const live = entry.store.readCurrent(["dnd_mode", "screen_timeout_seconds"]); + const live1 = toSettingVal(live.dnd_mode); + const live2 = toSettingVal(live.screen_timeout_seconds); + switch (event.type) { + case "previewProfile": { + if (entry.phase === "ProfileApplied") return "refused"; + entry.store.preview({ + profileId: "focus", + displayName: "Focus", + targetValues: { dnd_mode: "ValProfile", screen_timeout_seconds: "ValProfile" }, + }); + return "accepted"; + } + case "applyProfile": { + if (entry.phase === "ProfileApplied" || (event.target1 === live1 && event.target2 === live2)) { + return "refused"; + } + const receipt = entry.store.apply({ + profileId: "focus", + displayName: "Focus", + targetValues: { dnd_mode: event.target1, screen_timeout_seconds: event.target2 }, + }, 1_000, 0); + entry.lastReceiptId = receipt.receiptId; + entry.receiptCount += 1; + entry.phase = "ProfileApplied"; + return "accepted"; + } + case "manualEdit": { + const current = event.slot === "SlotOne" ? live1 : live2; + if (event.nextVal === current) return "refused"; + entry.store.manualEdit(event.slot === "SlotOne" ? "dnd_mode" : "screen_timeout_seconds", event.nextVal); + return "accepted"; + } + case "restoreProfile": { + if (entry.phase === "ProfileIdle" || entry.lastReceiptId === null) return "refused"; + const restored = entry.store.restore(entry.lastReceiptId); + if (!restored.ok) return "refused"; + entry.phase = "ProfileRestored"; + return "accepted"; + } + } + }, + observe: (key) => { + const entry = sessionOf(key); + const live = entry.store.readCurrent(["dnd_mode", "screen_timeout_seconds"]); + return { + phase: entry.phase, + live1: toSettingVal(live.dnd_mode), + live2: toSettingVal(live.screen_timeout_seconds), + receiptCount: entry.receiptCount, + }; + }, +}; + +/** Conformance options checking multi-key isolation across reversible profile walks. */ +export const options: Options = { + view: projectProfile, + keys: ["a", "b"], + walks: 150, + steps: 20, +}; diff --git a/spec/app/control/index.md b/spec/app/control/index.md index 285fd42e75..d3814317f2 100644 --- a/spec/app/control/index.md +++ b/spec/app/control/index.md @@ -2,23 +2,31 @@ How the resident agent observes and acts inside third-party Android apps such as Firefox without bypassing the owner's consent or screen security. -The owner grants a bounded lease for one target app at a time; at most one -operation runs at once; every UI operation binds the live observation -snapshot and foreground app; protected screens and blocked security packages -are always refused; and the kill-switch halts actuation and revokes the -lease immediately. On Alpha's own image the accessibility service that -backs the accessibility tier is switched on once at first boot, as +The owner grants a bounded lease for one target app at a time in either +visible foreground mode (`ModeForeground`) or headless background mode on a +trusted virtual display (`ModeVirtualDisplay`, requiring `TierPrivileged`); +at most one operation runs at once; every UI operation binds the live +observation snapshot and target app; protected screens and blocked security +packages are always refused; UI actuation completes only upon observed +post-action readback; interruptions or human takeover pauses require a fresh +observation to reconcile state before retrying (preventing double-toggles); +and the kill-switch halts actuation, releases any owned virtual display, and +revokes the lease immediately. On Alpha's own image the accessibility service +that backs the accessibility tier is switched on once at first boot, as [Image](../image/index.md) sets out, and the owner can turn it off; every -lease is still the owner's to grant. The resident agent keeps this state; -the [overlay](./overlay.md) shows it to the owner as the agent has it. +lease is still the owner's to grant. The resident agent keeps this state; the +[overlay](./overlay.md) shows it to the owner as the agent has it, and +[reversible profiles](./profile.md) specify reversible OS profile receipts. ## Story: Control a third-party app within an owner-approved lease > As the owner, I want to approve Alpha to work inside an app like Firefox -> for a bounded number of steps, and know it cannot act on locked, private, -> or security screens, act on stale screens, or keep going after I tap Stop. +> either visibly or on a managed background virtual display for a bounded +> number of steps, and know it cannot act on locked, private, or security +> screens, act on stale or unreconciled screens, bypass human takeover on +> sign-in/payment/permissions, or keep going after I tap Stop. -### The control state tracks the active capability tier, latest foreground observation, bounded lease, single in-flight operation, and kill-switch +### The control state tracks the active capability tier, latest observation, dual-mode bounded lease, single in-flight operation, reconciliation flag, takeover pause, and kill-switch ```quint type Actor = Owner | Agent | Phone @@ -26,6 +34,8 @@ type TargetKind = AllowedApp | BlockedApp | NoTarget type ScreenProtection = ScreenClear | ScreenLocked | SecureFlag | PrivateTab | SensitiveView type LeaseStatus = LeaseInactive | LeaseActive | LeaseRevoked type ControlTier = TierNone | TierAccessibility | TierPrivileged +type ExecutionMode = ModeForeground | ModeVirtualDisplay +type TakeoverReason = TakeoverNone | TakeoverAuth | TakeoverPayment | TakeoverPermission | TakeoverAmbiguous type ExecutionOutcome = OutcomeDone | OutcomeRefused | OutcomePreempted type ControlOp = OpLaunchPackage | OpOpenUrl | OpReadTree | OpCaptureScreen @@ -33,12 +43,23 @@ type ControlOp = | OpFunctionsDiscover | OpFunctionExecute type Snapshot = { snapId: int, appId: int, targetKind: TargetKind, protection: ScreenProtection } -type ControlLease = { leaseId: int, appId: int, maxOps: int, usedOps: int, expiresAt: int, status: LeaseStatus } +type ControlLease = { + leaseId: int, + appId: int, + maxOps: int, + usedOps: int, + expiresAt: int, + status: LeaseStatus, + mode: ExecutionMode, + displayId: int, +} type PendingOp = { pendingId: int, op: ControlOp, boundSnapId: int, boundAppId: int, active: bool } type ControlEffect = - | DispatchOp({ opId: int, op: ControlOp, snapId: int, appId: int }) + | DispatchOp({ opId: int, op: ControlOp, snapId: int, appId: int, mode: ExecutionMode, displayId: int }) | HaltBridge({ reason: str }) | ClearOverlay + | PauseForTakeover({ reason: TakeoverReason, surfaceToForeground: bool }) + | ReleaseVirtualDisplay({ displayId: int }) type ControlState = { tier: ControlTier, @@ -48,6 +69,9 @@ type ControlState = { lastResult: ExecutionOutcome, lastOpId: int, killed: bool, + needsReconcile: bool, + takeover: TakeoverReason, + lastReadbackSnapId: int, } type ControlMoved = { state: ControlState, out: List[ControlEffect] } @@ -56,11 +80,17 @@ pure val maxLeaseOps = 12 pure val initial: ControlState = { tier: TierNone, foreground: { snapId: 0, appId: 0, targetKind: NoTarget, protection: ScreenClear }, - lease: { leaseId: 0, appId: 0, maxOps: 0, usedOps: 0, expiresAt: 0, status: LeaseInactive }, + lease: { + leaseId: 0, appId: 0, maxOps: 0, usedOps: 0, expiresAt: 0, + status: LeaseInactive, mode: ModeForeground, displayId: 0, + }, pending: { pendingId: 0, op: OpReadTree, boundSnapId: 0, boundAppId: 0, active: false }, lastResult: OutcomeDone, lastOpId: 0, killed: false, + needsReconcile: false, + takeover: TakeoverNone, + lastReadbackSnapId: 0, } pure def screenProtected(p: ScreenProtection): bool = p != ScreenClear @@ -68,47 +98,61 @@ pure def screenProtected(p: ScreenProtection): bool = p != ScreenClear pure def requiresSnapshot(op: ControlOp): bool = op != OpLaunchPackage and op != OpOpenUrl and op != OpFunctionsDiscover -pure def leaseUsable(l: ControlLease, appId: int, now: int): bool = +pure def leaseModeValid(tier: ControlTier, mode: ExecutionMode, displayId: int): bool = + (mode == ModeForeground and displayId == 0) + or (mode == ModeVirtualDisplay and tier == TierPrivileged and displayId > 0) + +pure def leaseUsable(l: ControlLease, tier: ControlTier, appId: int, now: int): bool = l.status == LeaseActive and l.appId == appId and l.usedOps < l.maxOps and now < l.expiresAt + and leaseModeValid(tier, l.mode, l.displayId) pure val tierValues = Set(TierNone, TierAccessibility, TierPrivileged) +pure val opValues = Set(OpLaunchPackage, OpClick, OpFunctionExecute) +pure val protectionValues = Set(ScreenClear, ScreenLocked, SecureFlag) +pure val reasonValues = Set(TakeoverNone, TakeoverAuth, TakeoverPayment) pure val snapIdValues = Set(0, 1, 2) -pure val appIdValues = Set(0, 1, 2) +pure val readbackSnapIdValues = Set(0, 2) +pure val appIdValues = Set(0, 1) pure val leaseIdValues = Set(1, 2) pure val opIdValues = Set(1, 2) pure val maxOpsValues = Set(1, 2) pure val nowValues = Set(1, 5) -pure val expiresAtValues = Set(4, 8) -pure val weight_setTier = 10 -pure val weight_observe = 15 -pure val weight_grantLease = 15 -pure val weight_dispatch = 25 -pure val weight_finish = 15 -pure val weight_killSwitch = 10 +pure val expiresAtValues = Set(4) +pure val displayIdValues = Set(0, 1) ``` -### The phone reports its native control tier, and losing access immediately revokes any active lease and halts pending work +### The phone reports its native control tier, and losing access or privilege revokes any incompatible active lease, releases any virtual display, and halts pending work ```quint pure def canSetTier(c: ControlState, tier: ControlTier, by: Actor): bool = by == Phone and tier != c.tier pure def setTier(c: ControlState, tier: ControlTier, by: Actor): ControlMoved = + val dropVirtual = tier != TierPrivileged and c.lease.status == LeaseActive and c.lease.mode == ModeVirtualDisplay + val revoke = (tier == TierNone and c.lease.status == LeaseActive) or dropVirtual + val releaseEffects = if (dropVirtual and c.lease.displayId > 0) List(ReleaseVirtualDisplay({ displayId: c.lease.displayId })) else List() if (tier == TierNone) { state: { ...c, tier: TierNone, - lease: if (c.lease.status == LeaseActive) { ...c.lease, status: LeaseRevoked } else c.lease, + lease: if (revoke) { ...c.lease, status: LeaseRevoked, mode: ModeForeground, displayId: 0 } else c.lease, pending: { ...c.pending, active: false }, + needsReconcile: if (c.pending.active) true else c.needsReconcile, }, - out: if (c.pending.active) List(HaltBridge({ reason: "tier_disabled" }), ClearOverlay) else List(ClearOverlay), + out: (if (c.pending.active) List(HaltBridge({ reason: "tier_disabled" }), ClearOverlay) else List(ClearOverlay)).concat(releaseEffects), } else { - state: { ...c, tier: tier }, - out: List(), + state: { + ...c, + tier: tier, + lease: if (revoke) { ...c.lease, status: LeaseRevoked, mode: ModeForeground, displayId: 0 } else c.lease, + pending: if (dropVirtual) { ...c.pending, active: false } else c.pending, + needsReconcile: if (dropVirtual and c.pending.active) true else c.needsReconcile, + }, + out: (if (dropVirtual and c.pending.active) List(HaltBridge({ reason: "virtual_display_tier_lost" })) else List()).concat(releaseEffects), } ``` -### Each phone observation advances the snapshot id, preempts in-flight work if the screen turns protected, blocked, or leaves the bound app, and revokes any lease on screen lock +### Each phone observation advances the snapshot id, reconciles post-interrupt state once clear, preempts in-flight work if the screen turns protected, blocked, or leaves the bound app, and revokes any lease on screen lock ```quint pure def canObserve(c: ControlState, snapId: int, appId: int, targetKind: TargetKind, protection: ScreenProtection, by: Actor): bool = @@ -121,49 +165,86 @@ pure def observe(c: ControlState, snapId: int, appId: int, targetKind: TargetKin or (requiresSnapshot(c.pending.op) and (appId != c.pending.boundAppId or targetKind != AllowedApp)) ) val revoke = protection == ScreenLocked and c.lease.status == LeaseActive + val releaseVd = revoke and c.lease.mode == ModeVirtualDisplay and c.lease.displayId > 0 + val reconciled = not(preempt) and not(screenProtected(protection)) and targetKind != BlockedApp + val haltOut = if (preempt) List(HaltBridge({ reason: "screen_changed" })) else List() + val vdOut = if (releaseVd) List(ReleaseVirtualDisplay({ displayId: c.lease.displayId })) else List() { state: { ...c, foreground: nextSnap, - lease: if (revoke) { ...c.lease, status: LeaseRevoked } else c.lease, + lease: if (revoke) { ...c.lease, status: LeaseRevoked, mode: ModeForeground, displayId: 0 } else c.lease, pending: if (preempt) { ...c.pending, active: false } else c.pending, lastResult: if (preempt) OutcomePreempted else c.lastResult, + needsReconcile: if (preempt) true else if (reconciled) false else c.needsReconcile, }, - out: if (preempt) List(HaltBridge({ reason: "screen_changed" })) else List(), + out: haltOut.concat(vdOut), } ``` -### Only the owner may grant a bounded lease for a target app while the screen is clear, unblocked, idle, and backed by an active tier +### Only the owner may grant a bounded dual-mode lease for a target app while the screen is clear, unblocked, idle, reconciled, and backed by a matching tier + +Foreground leases run on `displayId == 0`; headless virtual display leases +require `TierPrivileged` and a positive managed `displayId`. ```quint -pure def canGrantLease(c: ControlState, leaseId: int, appId: int, maxOps: int, expiresAt: int, now: int, by: Actor): bool = +pure def canGrantLease( + c: ControlState, + leaseId: int, + appId: int, + maxOps: int, + expiresAt: int, + now: int, + mode: ExecutionMode, + by: Actor, +): bool = + val targetDisplayId = if (mode == ModeVirtualDisplay) leaseId else 0 by == Owner and c.tier != TierNone and leaseId > c.lease.leaseId and appId > 0 and maxOps >= 1 and maxOps <= maxLeaseOps and expiresAt > now - and not(c.pending.active) and c.foreground.targetKind != BlockedApp and not(screenProtected(c.foreground.protection)) - -pure def grantLease(c: ControlState, leaseId: int, appId: int, maxOps: int, expiresAt: int, now: int, by: Actor): ControlMoved = + and leaseModeValid(c.tier, mode, targetDisplayId) + and not(c.pending.active) and not(c.needsReconcile) + and c.foreground.targetKind != BlockedApp and not(screenProtected(c.foreground.protection)) + +pure def grantLease( + c: ControlState, + leaseId: int, + appId: int, + maxOps: int, + expiresAt: int, + now: int, + mode: ExecutionMode, + by: Actor, +): ControlMoved = + val targetDisplayId = if (mode == ModeVirtualDisplay) leaseId else 0 { state: { ...c, - lease: { leaseId: leaseId, appId: appId, maxOps: maxOps, usedOps: 0, expiresAt: expiresAt, status: LeaseActive }, + lease: { + leaseId: leaseId, + appId: appId, + maxOps: maxOps, + usedOps: 0, + expiresAt: expiresAt, + status: LeaseActive, + mode: mode, + displayId: targetDisplayId, + }, killed: false, + takeover: TakeoverNone, + needsReconcile: false, }, out: List(), } ``` -### The agent dispatches one operation at a time only under an active lease on a clear unblocked screen, binding the exact live snapshot for every UI operation - -Launching an app, opening an HTTPS URL, or discovering AppFunctions may run -before the target app is foregrounded, provided the current screen is clear -and unblocked; every UI observation or actuation operation binds the exact -foreground app and live snapshot id. +### The agent dispatches one operation at a time only under an active reconciled lease on a clear unblocked screen with no takeover pause, binding the exact live snapshot for every UI operation ```quint pure def canDispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = by == Agent and c.tier != TierNone and not(c.killed) and not(c.pending.active) + and not(c.needsReconcile) and c.takeover == TakeoverNone and opId > c.lastOpId and not(screenProtected(c.foreground.protection)) - and c.foreground.targetKind != BlockedApp and leaseUsable(c.lease, appId, now) + and c.foreground.targetKind != BlockedApp and leaseUsable(c.lease, c.tier, appId, now) and (requiresSnapshot(op) implies ( c.foreground.targetKind == AllowedApp and c.foreground.appId == appId and snapId > 0 and snapId == c.foreground.snapId @@ -177,76 +258,141 @@ pure def dispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: pending: { pendingId: opId, op: op, boundSnapId: snapId, boundAppId: appId, active: true }, lastOpId: opId, }, - out: List(DispatchOp({ opId: opId, op: op, snapId: snapId, appId: appId })), + out: List(DispatchOp({ + opId: opId, + op: op, + snapId: snapId, + appId: appId, + mode: c.lease.mode, + displayId: c.lease.displayId, + })), } ``` -### The phone reports when the in-flight operation finishes, and physical preemption revokes the lease and engages the kill-switch +### The phone finishes an in-flight operation only with observed post-action readback for UI steps, and preemption flags state reconciliation before any retry ```quint -pure def canFinish(c: ControlState, opId: int, verdict: ExecutionOutcome, by: Actor): bool = - by == Phone and c.pending.active and c.pending.pendingId == opId +pure def canFinish(c: ControlState, opId: int, verdict: ExecutionOutcome, readbackSnapId: int, by: Actor): bool = + by == Phone and c.pending.active and c.pending.pendingId == opId and readbackSnapId >= 0 + and (verdict == OutcomeDone implies ( + not(requiresSnapshot(c.pending.op)) or readbackSnapId > c.pending.boundSnapId + )) -pure def finish(c: ControlState, opId: int, verdict: ExecutionOutcome, by: Actor): ControlMoved = +pure def finish(c: ControlState, opId: int, verdict: ExecutionOutcome, readbackSnapId: int, by: Actor): ControlMoved = val preempted = verdict == OutcomePreempted + val releaseVd = preempted and c.lease.mode == ModeVirtualDisplay and c.lease.displayId > 0 + val haltOut = if (preempted) List(HaltBridge({ reason: "preempted" })) else List() + val vdOut = if (releaseVd) List(ReleaseVirtualDisplay({ displayId: c.lease.displayId })) else List() { state: { ...c, - lease: if (preempted and c.lease.status == LeaseActive) { ...c.lease, status: LeaseRevoked } else c.lease, + lease: if (preempted and c.lease.status == LeaseActive) { + ...c.lease, status: LeaseRevoked, mode: ModeForeground, displayId: 0 + } else c.lease, pending: { ...c.pending, active: false }, lastResult: verdict, killed: if (preempted) true else c.killed, + needsReconcile: if (preempted) true else c.needsReconcile, + lastReadbackSnapId: if (verdict == OutcomeDone and readbackSnapId > c.lastReadbackSnapId) readbackSnapId else c.lastReadbackSnapId, }, - out: if (preempted) List(HaltBridge({ reason: "preempted" })) else List(), + out: haltOut.concat(vdOut), + } +``` + +### Detecting sign-in, payment, permission, or ambiguous targets pauses actuation for human takeover, surfaces any virtual display job to foreground, and requires reconciliation before resuming + +```quint +pure def canPauseForTakeover(c: ControlState, reason: TakeoverReason, by: Actor): bool = + by == Phone and reason != TakeoverNone and (c.lease.status == LeaseActive or c.pending.active) + +pure def pauseForTakeover(c: ControlState, reason: TakeoverReason, by: Actor): ControlMoved = + val fromVirtual = c.lease.mode == ModeVirtualDisplay and c.lease.displayId > 0 + val pauseOut = List(PauseForTakeover({ reason: reason, surfaceToForeground: fromVirtual })) + val vdOut = if (fromVirtual) List(ReleaseVirtualDisplay({ displayId: c.lease.displayId })) else List() + { + state: { + ...c, + lease: if (fromVirtual) { ...c.lease, mode: ModeForeground, displayId: 0 } else c.lease, + pending: { ...c.pending, active: false }, + lastResult: OutcomePreempted, + needsReconcile: true, + takeover: reason, + }, + out: pauseOut.concat(vdOut), + } + +pure def canResumeAfterTakeover(c: ControlState, by: Actor): bool = + by == Owner and c.takeover != TakeoverNone and not(c.pending.active) and not(c.needsReconcile) + and not(screenProtected(c.foreground.protection)) and c.foreground.targetKind != BlockedApp + +pure def resumeAfterTakeover(c: ControlState, by: Actor): ControlMoved = + { + state: { ...c, takeover: TakeoverNone }, + out: List(), } ``` -### An expired lease is revoked and halts any in-flight operation +### An expired lease is revoked, releases any virtual display, and halts any in-flight operation ```quint pure def canExpireLease(c: ControlState, now: int, by: Actor): bool = by == Phone and c.lease.status == LeaseActive and now >= c.lease.expiresAt pure def expireLease(c: ControlState, now: int, by: Actor): ControlMoved = + val releaseVd = c.lease.mode == ModeVirtualDisplay and c.lease.displayId > 0 + val haltOut = if (c.pending.active) List(HaltBridge({ reason: "lease_expired" })) else List() + val vdOut = if (releaseVd) List(ReleaseVirtualDisplay({ displayId: c.lease.displayId })) else List() { state: { ...c, - lease: { ...c.lease, status: LeaseRevoked }, + lease: { ...c.lease, status: LeaseRevoked, mode: ModeForeground, displayId: 0 }, pending: { ...c.pending, active: false }, + needsReconcile: if (c.pending.active) true else c.needsReconcile, }, - out: if (c.pending.active) List(HaltBridge({ reason: "lease_expired" })) else List(), + out: haltOut.concat(vdOut), } ``` -### The kill-switch immediately revokes any active lease, clears any in-flight operation, and signals the native bridge and overlay +### The kill-switch immediately revokes any active lease, clears any in-flight operation, releases any virtual display, and signals the native bridge and overlay ```quint pure def canKillSwitch(c: ControlState, by: Actor): bool = (by == Owner or by == Phone) and (c.lease.status == LeaseActive or c.pending.active or not(c.killed)) pure def killSwitch(c: ControlState, by: Actor): ControlMoved = + val releaseVd = c.lease.mode == ModeVirtualDisplay and c.lease.displayId > 0 + val vdOut = if (releaseVd) List(ReleaseVirtualDisplay({ displayId: c.lease.displayId })) else List() { state: { ...c, - lease: if (c.lease.status == LeaseActive) { ...c.lease, status: LeaseRevoked } else c.lease, + lease: if (c.lease.status == LeaseActive) { + ...c.lease, status: LeaseRevoked, mode: ModeForeground, displayId: 0 + } else { ...c.lease, mode: ModeForeground, displayId: 0 }, pending: { ...c.pending, active: false }, killed: true, }, - out: List(HaltBridge({ reason: "kill_switch" }), ClearOverlay), + out: List(HaltBridge({ reason: "kill_switch" }), ClearOverlay).concat(vdOut), } ``` ## Story: Enforce formal safety guarantees over external app control > As the owner, I want hard guarantees that no agent action runs on a -> protected or blocked screen, on a stale snapshot, past its lease budget, -> or after the kill-switch is pressed. +> protected or blocked screen, on a stale or unreconciled snapshot, during +> a human takeover pause, on an unauthorized virtual display, past its lease +> budget, or after the kill-switch is pressed. -### No operation is ever active on a protected screen, while killed, or without a live control tier +### No operation is ever active on a protected screen, while killed, unreconciled, paused for takeover, or without a live control tier ```quint pure def alwaysNoActionOnProtectedScreen(c: ControlState): bool = - c.pending.active implies (not(screenProtected(c.foreground.protection)) and not(c.killed) and c.tier != TierNone) + c.pending.active implies ( + not(screenProtected(c.foreground.protection)) + and not(c.killed) + and not(c.needsReconcile) + and c.takeover == TakeoverNone + and c.tier != TierNone + ) ``` ### No operation is ever active over a blocked package, and snapshot-bound operations only run over an allowed foreground app @@ -278,34 +424,47 @@ pure def alwaysNoStaleSnapshotActuation(c: ControlState): bool = ) ``` -### Every lease stays within its operation budget, and any active operation belongs to the active lease +### Every lease stays within its operation budget, virtual display mode requires privileged tier and positive display id, and any active operation belongs to the active lease ```quint pure def alwaysLeaseBounded(c: ControlState): bool = - c.foreground.snapId >= 0 and c.lease.leaseId >= 0 and c.lastOpId >= 0 + c.foreground.snapId >= 0 and c.lease.leaseId >= 0 and c.lastOpId >= 0 and c.lastReadbackSnapId >= 0 and c.lease.maxOps >= 0 and c.lease.maxOps <= maxLeaseOps and c.lease.usedOps >= 0 and c.lease.usedOps <= c.lease.maxOps + and (c.lease.status == LeaseActive implies leaseModeValid(c.tier, c.lease.mode, c.lease.displayId)) + and (c.lease.status != LeaseActive implies (c.lease.mode == ModeForeground and c.lease.displayId == 0)) and (c.pending.active implies ( c.lease.status == LeaseActive and c.lease.appId == c.pending.boundAppId and c.lease.usedOps > 0 )) ``` -### The kill-switch halts immediately, and every dispatched effect honors exact live snapshot, lease, and screen safety +### The kill-switch and takeover pause halt immediately, and every dispatched effect honors exact live snapshot, reconciliation, takeover, dual-mode, lease, and screen safety ```quint pure def stepKillSwitchHaltsImmediately(before: ControlState, via: str, after: ControlState, out: List[ControlEffect]): bool = (via == "killSwitch" implies ( after.killed and not(after.pending.active) and after.lease.status != LeaseActive + and after.lease.mode == ModeForeground and after.lease.displayId == 0 and out.some(e => match e { | HaltBridge(_) => true | _ => false }) )) + and (via == "pauseForTakeover" implies ( + after.takeover != TakeoverNone and after.needsReconcile and not(after.pending.active) + and after.lease.mode == ModeForeground and after.lease.displayId == 0 + and out.some(e => match e { | PauseForTakeover(_) => true | _ => false }) + )) and out.every(e => match e { | DispatchOp(d) => via == "dispatch" and not(screenProtected(before.foreground.protection)) + and not(before.needsReconcile) + and before.takeover == TakeoverNone and before.foreground.targetKind != BlockedApp and before.lease.status == LeaseActive and before.lease.usedOps < before.lease.maxOps and d.appId == before.lease.appId + and d.mode == before.lease.mode + and d.displayId == before.lease.displayId + and leaseModeValid(before.tier, d.mode, d.displayId) and (requiresSnapshot(d.op) implies ( before.foreground.targetKind == AllowedApp and d.appId == before.foreground.appId @@ -315,26 +474,29 @@ pure def stepKillSwitchHaltsImmediately(before: ControlState, via: str, after: C }) ``` -### Protected screens, blocked apps, stale snapshots, exhausted leases, and engaged kill-switches always refuse dispatch +### Protected screens, blocked apps, stale snapshots, unreconciled interrupts, takeover pauses, unprivileged virtual displays, missing UI readback, exhausted leases, and engaged kill-switches always refuse ```quint -pure def lawProtectedScreenRefusesDispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = - screenProtected(c.foreground.protection) implies not(canDispatch(c, opId, op, snapId, appId, now, by)) - -pure def lawBlockedAppRefusesDispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = - c.foreground.targetKind == BlockedApp implies not(canDispatch(c, opId, op, snapId, appId, now, by)) - -pure def lawStaleSnapshotRefusesDispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = - (requiresSnapshot(op) and snapId != c.foreground.snapId) implies not(canDispatch(c, opId, op, snapId, appId, now, by)) - -pure def lawExhaustedLeaseRefusesDispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = - (c.lease.usedOps >= c.lease.maxOps or now >= c.lease.expiresAt) implies not(canDispatch(c, opId, op, snapId, appId, now, by)) - -pure def lawKilledStateRefusesDispatch(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = - c.killed implies not(canDispatch(c, opId, op, snapId, appId, now, by)) +pure def lawUnsafeDispatchAlwaysRefused(c: ControlState, opId: int, op: ControlOp, snapId: int, appId: int, now: int, by: Actor): bool = + (screenProtected(c.foreground.protection) + or c.foreground.targetKind == BlockedApp + or (requiresSnapshot(op) and snapId != c.foreground.snapId) + or c.lease.usedOps >= c.lease.maxOps + or now >= c.lease.expiresAt + or c.killed + or c.needsReconcile + or c.takeover != TakeoverNone) + implies not(canDispatch(c, opId, op, snapId, appId, now, by)) + +pure def lawVirtualDisplayRequiresPrivilegedTier(c: ControlState, displayId: int): bool = + c.tier != TierPrivileged implies not(leaseModeValid(c.tier, ModeVirtualDisplay, displayId)) + +pure def lawUiCompletionRequiresObservedReadback(c: ControlState, opId: int, readbackSnapId: int): bool = + (c.pending.active and requiresSnapshot(c.pending.op) and readbackSnapId <= c.pending.boundSnapId) + implies not(canFinish(c, opId, OutcomeDone, readbackSnapId, Phone)) ``` -### The model can dispatch a UI click, launch an app before foregrounding, exhaust a lease, and halt on the kill-switch +### The model can dispatch foreground and virtual-display actions, launch before foregrounding, pause and resume human takeover, exhaust a lease, and halt on the kill-switch ```quint pure def sometimesOpDispatched(c: ControlState): bool = @@ -343,6 +505,12 @@ pure def sometimesOpDispatched(c: ControlState): bool = pure def sometimesLaunchBeforeForeground(c: ControlState): bool = c.pending.active and c.pending.op == OpLaunchPackage and c.foreground.appId != c.pending.boundAppId +pure def sometimesVirtualDisplayActive(c: ControlState): bool = + c.lease.status == LeaseActive and c.lease.mode == ModeVirtualDisplay and c.lease.displayId > 0 and c.pending.active + +pure def sometimesTakeoverPaused(c: ControlState): bool = + c.takeover == TakeoverAuth and c.needsReconcile and c.lease.mode == ModeForeground + pure def sometimesLeaseExhausted(c: ControlState): bool = c.lease.status == LeaseActive and c.lease.maxOps > 0 and c.lease.usedOps == c.lease.maxOps @@ -352,35 +520,56 @@ pure def sometimesKillSwitchStopped(c: ControlState): bool = pure val eval_witness_sometimesOpDispatched = ( ("setTier", TierPrivileged, Phone), ("observe", 1, 1, AllowedApp, ScreenClear, Phone), - ("grantLease", 1, 1, 2, 8, 1, Owner), + ("grantLease", 1, 1, 2, 4, 1, ModeForeground, Owner), ("dispatch", 1, OpClick, 1, 1, 1, Agent), ) pure val eval_witness_sometimesLaunchBeforeForeground = ( ("setTier", TierPrivileged, Phone), - ("grantLease", 1, 1, 2, 8, 1, Owner), + ("grantLease", 1, 1, 2, 4, 1, ModeForeground, Owner), ("dispatch", 1, OpLaunchPackage, 0, 1, 1, Agent), ) +pure val eval_witness_sometimesVirtualDisplayActive = ( + ("setTier", TierPrivileged, Phone), + ("observe", 1, 1, AllowedApp, ScreenClear, Phone), + ("grantLease", 1, 1, 2, 4, 1, ModeVirtualDisplay, Owner), + ("dispatch", 1, OpClick, 1, 1, 1, Agent), +) +pure val eval_witness_sometimesTakeoverPaused = ( + ("setTier", TierPrivileged, Phone), + ("observe", 1, 1, AllowedApp, ScreenClear, Phone), + ("grantLease", 1, 1, 2, 4, 1, ModeVirtualDisplay, Owner), + ("dispatch", 1, OpClick, 1, 1, 1, Agent), + ("pauseForTakeover", TakeoverAuth, Phone), +) pure val eval_witness_sometimesLeaseExhausted = ( ("setTier", TierPrivileged, Phone), ("observe", 1, 1, AllowedApp, ScreenClear, Phone), - ("grantLease", 1, 1, 1, 8, 1, Owner), + ("grantLease", 1, 1, 1, 4, 1, ModeForeground, Owner), ("dispatch", 1, OpClick, 1, 1, 1, Agent), ) pure val eval_witness_sometimesKillSwitchStopped = ( ("setTier", TierPrivileged, Phone), - ("grantLease", 1, 1, 1, 8, 1, Owner), + ("grantLease", 1, 1, 1, 4, 1, ModeForeground, Owner), ("killSwitch", Owner), ) pure val eval_witness_canFinish = ( ("setTier", TierPrivileged, Phone), ("observe", 1, 1, AllowedApp, ScreenClear, Phone), - ("grantLease", 1, 1, 2, 8, 1, Owner), + ("grantLease", 1, 1, 2, 4, 1, ModeForeground, Owner), ("dispatch", 1, OpClick, 1, 1, 1, Agent), - ("finish", 1, OutcomeDone, Phone), + ("finish", 1, OutcomeDone, 2, Phone), +) +pure val eval_witness_canResumeAfterTakeover = ( + ("setTier", TierPrivileged, Phone), + ("observe", 1, 1, AllowedApp, ScreenClear, Phone), + ("grantLease", 1, 1, 2, 4, 1, ModeVirtualDisplay, Owner), + ("pauseForTakeover", TakeoverAuth, Phone), + ("observe", 2, 1, AllowedApp, ScreenClear, Phone), + ("resumeAfterTakeover", Owner), ) pure val eval_witness_canExpireLease = ( ("setTier", TierPrivileged, Phone), - ("grantLease", 1, 1, 1, 4, 1, Owner), + ("grantLease", 1, 1, 1, 4, 1, ModeForeground, Owner), ("expireLease", 5, Phone), ) ``` diff --git a/spec/app/control/index.proof.dfy b/spec/app/control/index.proof.dfy index 01794c0aad..cc0e163d75 100644 --- a/spec/app/control/index.proof.dfy +++ b/spec/app/control/index.proof.dfy @@ -1,4 +1,4 @@ -// spec/app/control/index.md, "The kill-switch halts immediately, and every dispatched effect honors exact live snapshot, lease, and screen safety" +// spec/app/control/index.md, "The kill-switch and takeover pause halt immediately, and every dispatched effect honors exact live snapshot, reconciliation, takeover, dual-mode, lease, and screen safety" lemma killSwitch_ensures(c: ControlState, by_: Actor) ensures (inv(c) ==> canKillSwitch(c, by_) ==> alwaysNoActionOnProtectedScreen(killSwitch(c, by_).state)) ensures (inv(c) ==> canKillSwitch(c, by_) ==> alwaysBlockedPackagesProtected(killSwitch(c, by_).state)) @@ -11,3 +11,16 @@ lemma killSwitch_ensures(c: ControlState, by_: Actor) assert m.out[0] in m.out; } } + +lemma pauseForTakeover_ensures(c: ControlState, reason: TakeoverReason, by_: Actor) + ensures (inv(c) ==> canPauseForTakeover(c, reason, by_) ==> alwaysNoActionOnProtectedScreen(pauseForTakeover(c, reason, by_).state)) + ensures (inv(c) ==> canPauseForTakeover(c, reason, by_) ==> alwaysBlockedPackagesProtected(pauseForTakeover(c, reason, by_).state)) + ensures (inv(c) ==> canPauseForTakeover(c, reason, by_) ==> alwaysNoStaleSnapshotActuation(pauseForTakeover(c, reason, by_).state)) + ensures (inv(c) ==> canPauseForTakeover(c, reason, by_) ==> alwaysLeaseBounded(pauseForTakeover(c, reason, by_).state)) + ensures (inv(c) ==> canPauseForTakeover(c, reason, by_) ==> stepKillSwitchHaltsImmediately(c, "pauseForTakeover", pauseForTakeover(c, reason, by_).state, pauseForTakeover(c, reason, by_).out)) +{ + if inv(c) && canPauseForTakeover(c, reason, by_) { + var m := pauseForTakeover(c, reason, by_); + assert m.out[0] in m.out; + } +} diff --git a/spec/app/control/profile.md b/spec/app/control/profile.md new file mode 100644 index 0000000000..1d3beb9ce8 --- /dev/null +++ b/spec/app/control/profile.md @@ -0,0 +1,164 @@ +# Reversible OS profiles + +How Alpha previews, applies, and restores temporary OS profiles (such as +Focus or Recording mode) using immutable attribution receipts. Previewing +a profile never mutates live settings; applying records the baseline and +profile-written values for each changed setting; and restoring writes back +a baseline ONLY for settings still holding the profile's applied value, +idempotently preserving every manual edit the owner made mid-profile. + +## Story: Apply and restore reversible OS profiles while preserving manual edits + +> As the owner, I want to preview a temporary Focus or Recording profile, +> apply it with a receipt, tweak any individual setting manually while it +> is active, and restore the profile later knowing my manual edits stay +> untouched and repeated restores are harmless no-ops. + +### A profile receipt tracks the live values, recorded baseline, profile-written targets, attribution flags, and lifecycle phase + +```quint +type SettingVal = ValBase | ValProfile | ValManual +type SettingSlot = SlotOne | SlotTwo +type ProfilePhase = ProfileIdle | ProfileApplied | ProfileRestored + +type ProfileState = { + phase: ProfilePhase, + live1: SettingVal, + live2: SettingVal, + base1: SettingVal, + base2: SettingVal, + applied1: SettingVal, + applied2: SettingVal, + changed1: bool, + changed2: bool, + receiptCount: int, +} + +pure val initial: ProfileState = { + phase: ProfileIdle, + live1: ValBase, + live2: ValBase, + base1: ValBase, + base2: ValBase, + applied1: ValBase, + applied2: ValBase, + changed1: false, + changed2: false, + receiptCount: 0, +} + +pure val weight_previewProfile = 1 +pure val weight_applyProfile = 2 +pure val weight_manualEdit = 2 +pure val weight_restoreProfile = 2 +``` + +### Previewing a profile is completely pure and never mutates live OS settings + +```quint +pure def canPreviewProfile(p: ProfileState): bool = p.phase != ProfileApplied + +pure def previewProfile(p: ProfileState): ProfileState = p +``` + +### Applying a profile records the baseline and profile-written target for each changed setting + +```quint +pure def canApplyProfile(p: ProfileState, target1: SettingVal, target2: SettingVal): bool = + p.phase != ProfileApplied and (target1 != p.live1 or target2 != p.live2) + +pure def applyProfile(p: ProfileState, target1: SettingVal, target2: SettingVal): ProfileState = + { + phase: ProfileApplied, + live1: target1, + live2: target2, + base1: p.live1, + base2: p.live2, + applied1: target1, + applied2: target2, + changed1: p.live1 != target1, + changed2: p.live2 != target2, + receiptCount: p.receiptCount + 1, + } +``` + +### The owner may manually edit any setting at any time, including while a profile is active + +```quint +pure def canManualEdit(p: ProfileState, slot: SettingSlot, nextVal: SettingVal): bool = + (slot == SlotOne and nextVal != p.live1) or (slot == SlotTwo and nextVal != p.live2) + +pure def manualEdit(p: ProfileState, slot: SettingSlot, nextVal: SettingVal): ProfileState = + if (slot == SlotOne) { ...p, live1: nextVal } else { ...p, live2: nextVal } +``` + +### Restoring writes back only values still attributable to the active profile receipt, preserving manual edits idempotently + +```quint +pure def canRestoreProfile(p: ProfileState): bool = + p.phase == ProfileApplied or p.phase == ProfileRestored + +pure def restoreProfile(p: ProfileState): ProfileState = + if (p.phase == ProfileRestored) p + else { + ...p, + phase: ProfileRestored, + live1: if (p.changed1 and p.live1 == p.applied1) p.base1 else p.live1, + live2: if (p.changed2 and p.live2 == p.applied2) p.base2 else p.live2, + } +``` + +## Story: Enforce reversible profile invariants + +> As the owner, I want formal guarantees that previewing changes nothing, +> restoring preserves manual edits made mid-profile, and restoring twice is +> idempotent. + +### Receipt count is monotonic and applied profiles always attribute changed slots to their recorded baseline + +```quint +pure def alwaysReceiptCountNonNegative(p: ProfileState): bool = + p.receiptCount >= 0 and (p.phase == ProfileApplied implies p.receiptCount > 0) +``` + +### Preview never mutates live settings, restore preserves every manual edit while reverting untouched profile values, and repeat restore is an exact no-op + +```quint +pure def stepReversibleProfileInvariants(before: ProfileState, via: str, after: ProfileState): bool = + (via == "previewProfile" implies after == before) + and ((via == "restoreProfile" and before.phase == ProfileRestored) implies after == before) + and ((via == "restoreProfile" and before.phase == ProfileApplied) implies ( + after.phase == ProfileRestored + and ((before.changed1 and before.live1 == before.applied1) implies after.live1 == before.base1) + and ((not(before.changed1) or before.live1 != before.applied1) implies after.live1 == before.live1) + and ((before.changed2 and before.live2 == before.applied2) implies after.live2 == before.base2) + and ((not(before.changed2) or before.live2 != before.applied2) implies after.live2 == before.live2) + )) +``` + +### Restoring after a restore is always an exact no-op, and preview never changes state + +```quint +pure def lawRestoreIsIdempotent(p: ProfileState): bool = + p.phase == ProfileRestored implies restoreProfile(p) == p + +pure def lawPreviewIsPure(p: ProfileState): bool = + previewProfile(p) == p +``` + +### A profile can be applied, manually edited on one slot, restored with that manual edit preserved, and restored again idempotently + +```quint +pure def sometimesRestoredPreservingManualEdit(p: ProfileState): bool = + p.phase == ProfileRestored and p.live1 == ValBase and p.live2 == ValManual + +pure val eval_witness_sometimesRestoredPreservingManualEdit = ( + ("applyProfile", ValProfile, ValProfile), + ("manualEdit", SlotTwo, ValManual), + "restoreProfile", +) +pure val eval_witness_canPreviewProfile = ( + "previewProfile", + "previewProfile", +) +```