agent-device 0.21.22 → 0.21.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.22.apk → agent-device-android-ime-helper-0.21.24.apk} +0 -0
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.24.apk.sha256 +1 -0
- package/android/ime-helper/dist/{agent-device-android-ime-helper-0.21.22.manifest.json → agent-device-android-ime-helper-0.21.24.manifest.json} +4 -4
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.24.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.24.apk.sha256 +1 -0
- package/android/snapshot-helper/dist/{agent-device-android-snapshot-helper-0.21.22.manifest.json → agent-device-android-snapshot-helper-0.21.24.manifest.json} +6 -6
- package/apple/macos-helper/Sources/AgentDeviceMacOSHelper/SnapshotTraversal.swift +12 -6
- package/apple/macos-helper/Tests/AgentDeviceMacOSHelperTests/RectResponseTests.swift +21 -0
- package/apple/snapshot-bridge/README.md +9 -7
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandDispatch.swift +56 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+CommandExecution.swift +14 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Lifecycle.swift +8 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+Models.swift +12 -0
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotCaptureTarget.swift +1 -1
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+SnapshotExecution.swift +29 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntry.swift +34 -10
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextEntryFocus.swift +19 -5
- package/dist/apple/runner/AgentDeviceRunner/AgentDeviceRunnerUITests/RunnerTests+TextTyping.swift +3 -3
- package/dist/src/adapter.js +1 -1
- package/dist/src/adb.js +1 -1
- package/dist/src/agent-browser-lifecycle.js +1 -1
- package/dist/src/agent-browser-process-record.js +1 -1
- package/dist/src/agent-browser-provider.js +1 -1
- package/dist/src/agent-device-client.js +2 -2
- package/dist/src/alert-runtime.js +1 -1
- package/dist/src/alert.js +1 -1
- package/dist/src/android-adb.d.ts +3 -2
- package/dist/src/android-input-ownership.js +1 -1
- package/dist/src/app-backend.js +1 -1
- package/dist/src/app-inventory.d.ts +4 -0
- package/dist/src/app-launch.js +1 -1
- package/dist/src/app-lifecycle.js +1 -1
- package/dist/src/app-log-reconnect.js +1 -1
- package/dist/src/app-log-runtime2.js +3 -3
- package/dist/src/app-resolution.js +2 -2
- package/dist/src/app-state-runtime.d.ts +15 -0
- package/dist/src/apple-runner-platform.js +1 -1
- package/dist/src/application-lifecycle-interaction.js +1 -1
- package/dist/src/aws-device-farm-connection.js +1 -0
- package/dist/src/back-mode.js +1 -1
- package/dist/src/backend-snapshot-options.js +1 -1
- package/dist/src/browserstack-connection.js +1 -0
- package/dist/src/browserstack-device-features.js +1 -0
- package/dist/src/browserstack.js +1 -0
- package/dist/src/cache.js +1 -1
- package/dist/src/cli-config.js +1 -1
- package/dist/src/cli-help.js +35 -19
- package/dist/src/cli-runner.js +1 -1
- package/dist/src/cli.js +3 -4
- package/dist/src/client-companion-tunnel.js +1 -0
- package/dist/src/client-metro-companion.js +1 -1
- package/dist/src/client-metro.js +1 -1
- package/dist/src/client-options.js +3 -3
- package/dist/src/client-types.d.ts +7 -5
- package/dist/src/cloud-artifacts.d.ts +9 -2
- package/dist/src/code-signature-cache.js +1 -1
- package/dist/src/command-metadata.js +1 -1
- package/dist/src/command-schema.js +1 -1
- package/dist/src/command-tools.js +2 -2
- package/dist/src/connection-runtime.js +1 -1
- package/dist/src/connection-verification.js +1 -0
- package/dist/src/connection.js +5 -5
- package/dist/src/contracts.d.ts +1 -1
- package/dist/src/daemon-client-lease-beat.js +1 -1
- package/dist/src/daemon-client-lifecycle.js +1 -1
- package/dist/src/daemon-client-transport.js +1 -1
- package/dist/src/daemon-http.js +1 -1
- package/dist/src/daemon-policy-file.js +1 -1
- package/dist/src/daemon-registration-owner.js +1 -1
- package/dist/src/device-claim-inspection.js +1 -1
- package/dist/src/device-input-state.d.ts +2 -15
- package/dist/src/device-readiness-runtime.js +1 -1
- package/dist/src/device-selection-resolver.js +1 -1
- package/dist/src/device-session.js +3 -1
- package/dist/src/device.js +1 -1
- package/dist/src/device2.js +1 -1
- package/dist/src/device3.js +1 -1
- package/dist/src/dispatch-resolve.js +3 -3
- package/dist/src/doctor-facade.js +1 -1
- package/dist/src/durable-capture-resource.js +1 -1
- package/dist/src/durable-resource.js +1 -1
- package/dist/src/exec.js +1 -1
- package/dist/src/file.js +1 -1
- package/dist/src/find.js +1 -1
- package/dist/src/finders.js +1 -1
- package/dist/src/format.js +2 -1
- package/dist/src/gesture-admission.js +1 -1
- package/dist/src/gesture-plan-types.d.ts +2 -5
- package/dist/src/gesture-runtime.js +1 -1
- package/dist/src/helper.js +2 -2
- package/dist/src/human-control.js +1 -1
- package/dist/src/ime-rebind.js +1 -0
- package/dist/src/ime-settings-record.js +1 -0
- package/dist/src/ime-state.js +1 -0
- package/dist/src/index.d.ts +3 -3
- package/dist/src/input-actions.js +1 -1
- package/dist/src/input-actions2.js +1 -1
- package/dist/src/install-source2.js +1 -1
- package/dist/src/instance-client.js +1 -1
- package/dist/src/interaction-positionals.js +1 -1
- package/dist/src/interaction-ref-policy.js +1 -1
- package/dist/src/interaction.js +1 -1
- package/dist/src/interaction2.js +1 -1
- package/dist/src/interactor.js +5 -5
- package/dist/src/interactors.js +1 -1
- package/dist/src/internal/bin.js +1 -1
- package/dist/src/internal/daemon.js +1 -1
- package/dist/src/inventory2.js +1 -1
- package/dist/src/ios-client.js +4 -4
- package/dist/src/ios-snapshot-acquisition.js +1 -1
- package/dist/src/ios-snapshot-engine.js +1 -1
- package/dist/src/ios-snapshot-runtime.js +1 -1
- package/dist/src/launch-confirmation.js +1 -1
- package/dist/src/lease-scope.js +1 -1
- package/dist/src/lease.js +1 -1
- package/dist/src/limrun.d.ts +4 -555
- package/dist/src/load.js +1 -1
- package/dist/src/local-interactor-operation-set.js +1 -1
- package/dist/src/log-stream.js +33 -0
- package/dist/src/managed-device-scope.js +1 -1
- package/dist/src/manifest.js +1 -0
- package/dist/src/mechanics.js +16 -16
- package/dist/src/mobile-snapshot-semantics.js +1 -1
- package/dist/src/node-http.js +1 -0
- package/dist/src/observation.js +1 -2
- package/dist/src/overlay.js +3 -3
- package/dist/src/owner-identity.js +3 -3
- package/dist/src/perf-facade.js +1 -1
- package/dist/src/perf-runtime-plan.js +1 -1
- package/dist/src/perf-target.js +1 -1
- package/dist/src/physical-device-control.js +1 -1
- package/dist/src/platform-request-scope.js +1 -1
- package/dist/src/platform-runtime-app-log-process.js +1 -1
- package/dist/src/platform-runtime-open-target.js +1 -1
- package/dist/src/platform-runtime-operation-host.js +4 -4
- package/dist/src/platform-runtime-runtime-hints.js +1 -1
- package/dist/src/platform-runtime-screen-recording-finalizer-host.js +1 -1
- package/dist/src/platform-runtime-screen-recording-process-host.js +1 -1
- package/dist/src/platform-runtime-unavailable.js +1 -1
- package/dist/src/platform-runtime.js +1 -1
- package/dist/src/platform-runtime2.js +1 -1
- package/dist/src/plugin.js +1 -0
- package/dist/src/plugins/webdriver.d.ts +111 -0
- package/dist/src/plugins/webdriver.js +1 -0
- package/dist/src/plugins.d.ts +2 -1
- package/dist/src/plugins2.js +1 -1
- package/dist/src/process-exit.js +1 -1
- package/dist/src/process.js +1 -1
- package/dist/src/provider-credential-fingerprint.js +1 -1
- package/dist/src/provider-device-admission.js +1 -1
- package/dist/src/provider-device-runtime.d.ts +556 -0
- package/dist/src/provider-policy.js +1 -0
- package/dist/src/provider-profile-fields.js +1 -1
- package/dist/src/provider-webdriver.js +1 -2
- package/dist/src/providers.js +1 -1
- package/dist/src/proxy.js +2 -2
- package/dist/src/react-devtools.js +2 -0
- package/dist/src/react-native.js +1 -1
- package/dist/src/record-runtime.js +1 -1
- package/dist/src/record-trace.js +1 -1
- package/dist/src/recording.js +1 -1
- package/dist/src/registry.js +24 -24
- package/dist/src/remote-bridge.js +1 -0
- package/dist/src/remote-config-core.js +1 -0
- package/dist/src/remote-config.js +1 -1
- package/dist/src/remote-config2.js +1 -1
- package/dist/src/remote-connection-state.js +1 -0
- package/dist/src/replay.js +2 -2
- package/dist/src/request-admission.js +1 -1
- package/dist/src/request-runtime-binding.js +1 -1
- package/dist/src/result-serialization.js +1 -1
- package/dist/src/retry.js +1 -1
- package/dist/src/retry2.js +1 -0
- package/dist/src/runner-artifact-manifest.js +1 -1
- package/dist/src/runner-cache-metadata.js +2 -3
- package/dist/src/runner-cache-retention.js +1 -0
- package/dist/src/runner-cache-trim.js +1 -0
- package/dist/src/runner-client.js +1 -1
- package/dist/src/runner-dev-tools-security.js +1 -1
- package/dist/src/runner-device-readiness.js +1 -1
- package/dist/src/runner-device-set.js +1 -0
- package/dist/src/runner-disposal.js +1 -1
- package/dist/src/runner-error-classification.js +1 -1
- package/dist/src/runner-exchange.js +1 -1
- package/dist/src/runner-lease.js +1 -0
- package/dist/src/runner-operations-facade.js +1 -1
- package/dist/src/runner-session-types.js +1 -1
- package/dist/src/runner-start-budget.js +1 -1
- package/dist/src/runner-toolchain-probe.js +2 -0
- package/dist/src/runner.js +1 -1
- package/dist/src/runtime-deployment.js +1 -0
- package/dist/src/runtime.js +1 -1
- package/dist/src/runtime10.js +1 -2
- package/dist/src/runtime11.js +2 -0
- package/dist/src/runtime2.js +2 -5
- package/dist/src/runtime3.js +5 -1
- package/dist/src/runtime4.js +1 -5
- package/dist/src/runtime5.js +5 -1
- package/dist/src/runtime6.js +1 -1
- package/dist/src/runtime7.js +1 -1
- package/dist/src/runtime8.js +1 -1
- package/dist/src/runtime9.js +1 -1
- package/dist/src/screen-recording-transport.js +1 -1
- package/dist/src/screenshot-density.js +1 -1
- package/dist/src/screenshot-overlay-draw.js +1 -1
- package/dist/src/screenshot3.js +2 -2
- package/dist/src/script.js +1 -1
- package/dist/src/scroll-gesture.js +1 -1
- package/dist/src/sdk-batch.js +2 -2
- package/dist/src/sdk-contracts.d.ts +25 -33
- package/dist/src/sdk-contracts.js +2 -2
- package/dist/src/sdk-device.js +1 -1
- package/dist/src/sdk-finders.d.ts +1 -1
- package/dist/src/sdk-finders.js +1 -1
- package/dist/src/sdk-remote-config.d.ts +4 -0
- package/dist/src/sdk-remote-config.js +1 -1
- package/dist/src/sdk-selectors.d.ts +1 -1
- package/dist/src/sdk-selectors.js +1 -1
- package/dist/src/selection.js +0 -0
- package/dist/src/selector-pipeline-policy.js +1 -1
- package/dist/src/selector-runtime.js +1 -1
- package/dist/src/selectors.js +1 -1
- package/dist/src/server.js +2 -2
- package/dist/src/session-snapshot.js +1 -1
- package/dist/src/session2.js +5 -5
- package/dist/src/simctl.js +1 -1
- package/dist/src/simulator-boot.js +1 -1
- package/dist/src/simulator-state.js +1 -1
- package/dist/src/simulator.js +1 -1
- package/dist/src/snapshot-capture-annotations.js +1 -1
- package/dist/src/snapshot-desktop-projection.js +1 -1
- package/dist/src/snapshot-private-evidence.js +1 -0
- package/dist/src/snapshot-runtime-binding.js +1 -1
- package/dist/src/snapshot-runtime.js +1 -1
- package/dist/src/snapshot-state.js +1 -1
- package/dist/src/snapshot4.js +1 -1
- package/dist/src/src2.js +1 -1
- package/dist/src/src3.js +1 -1
- package/dist/src/src4.js +1 -1
- package/dist/src/src5.js +1 -1
- package/dist/src/src6.js +1 -1
- package/dist/src/src7.js +1 -1
- package/dist/src/src8.js +20 -20
- package/dist/src/store.js +1 -1
- package/dist/src/target-evidence.js +1 -1
- package/dist/src/text-entry-focus.js +1 -1
- package/dist/src/tool-provider2.js +1 -1
- package/dist/src/touch-runtime2.js +1 -1
- package/dist/src/tree.js +1 -1
- package/dist/src/type-text-runtime.js +1 -1
- package/dist/src/video.js +1 -1
- package/package.json +24 -16
- package/server.json +2 -2
- package/android/ime-helper/dist/agent-device-android-ime-helper-0.21.22.apk.sha256 +0 -1
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.22.apk +0 -0
- package/android/snapshot-helper/dist/agent-device-android-snapshot-helper-0.21.22.apk.sha256 +0 -1
- package/dist/src/capabilities.js +0 -1
- package/dist/src/compatibility-policy.js +0 -1
- package/dist/src/daemon-artifacts.js +0 -1
- package/dist/src/device-claim-rule.js +0 -1
- package/dist/src/human-control-contract.js +0 -1
- package/dist/src/prepare-kind.js +0 -1
- package/dist/src/provider-device-runtimes.js +0 -1
- package/dist/src/screen-recording-admission-ledger.js +0 -1
- package/dist/src/screenshot-runtime.js +0 -1
- package/dist/src/session-routing.js +0 -1
- package/dist/src/session-runtime-admission.js +0 -1
- package/dist/src/session-stream.js +0 -27
- package/dist/src/timeouts.js +0 -1
- package/dist/src/touch-reference-frame.js +0 -1
- package/dist/src/vars.js +0 -2
- package/dist/src/viewport.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Ar as e,Or as t,Pr as n,Zr as r,kr as i}from"./sdk-batch.js";import{t as a}from"./scroll-indicator.js";function o(e){if(e.length===0)return{nodes:e,hiddenCount:0,summaryLines:[]};let{visibility:t,visibleNodeIndexes:n,offscreenNodes:r,hintedContainers:i}=c(e),a=n.size===0?e:e.filter(e=>n.has(e.index));return{nodes:a.map(e=>m(e,i.directionsByContainer)),hiddenCount:n.size===0?0:e.length-a.length,summaryLines:h(r.filter(e=>!i.coveredNodeIndexes.has(e.index)&&v(e)),t)}}function s(e){if(e.length===0)return new Map;let{hintedContainers:t}=c(e);return p(t.directionsByContainer)}function c(e){let n=t(e),r=n.nodeByIndex,i=new Set,a=[];for(let t of e){if(n.isVisibleInEffectiveViewport(t)){b(t,i,r);continue}a.push(t)}return{visibility:n,visibleNodeIndexes:i,offscreenNodes:a,hintedContainers:f(e,a,i,r)}}function l(t,n){return t.hittable&&e(t.rect,n)}function u(t,n){if(!t.rect)return null;let i=n.resolveEffectiveViewport(t);if(i&&!r(t.rect,i)){let e=d(t.rect,i);if(e)return e}let a=n.resolveViewport(t.rect);if(a&&!e(t.rect,a)){let e=d(t.rect,a);if(e)return e}return null}function d(e,t){let n=e.x+e.width/2,r=e.y+e.height/2,i=[{direction:`down`,amount:r-(t.y+t.height)},{direction:`up`,amount:t.y-r},{direction:`right`,amount:n-(t.x+t.width)},{direction:`left`,amount:t.x-n}],a=null;for(let e of i)e.amount>0&&(!a||e.amount>a.amount)&&(a=e);return a?.direction??null}function f(e,t,n,r){let i=new Map,a=new Map,o=new Set;for(let e of t){if(!e.rect)continue;let t=x(e,n,r);if(!t?.rect)continue;let s=_(e.rect,t.rect);if(!s)continue;let c=i.get(t.index)??new Set;c.add(s),i.set(t.index,c);let l=a.get(t.index)??new Set;l.add(s),a.set(t.index,l),o.add(e.index)}return S(e,n,r,i,a),{directionsByContainer:i,coveredNodeIndexes:o}}function p(e){let t=new Map;for(let[n,r]of e){let e={};r.has(`above`)&&(e.hiddenContentAbove=!0),r.has(`below`)&&(e.hiddenContentBelow=!0),(e.hiddenContentAbove||e.hiddenContentBelow)&&t.set(n,e)}return t}function m(e,t){let n=t.get(e.index);if(!n||n.size===0)return e;let r=e.hiddenContentAbove===!0||n.has(`above`)?!0:void 0,i=e.hiddenContentBelow===!0||n.has(`below`)?!0:void 0;return{...e,hiddenContentAbove:r,hiddenContentBelow:i}}function h(e,t){let n=new Map;for(let r of e){let e=g(r,t);if(!e)continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return[`above`,`below`].flatMap(e=>{let t=n.get(e);if(!t||t.length===0)return[];let r=y(t).slice(0,3).map(e=>`"${e}"`),i=t.length===1?`interactive item`:`interactive items`,a=r.length>0?`: ${r.join(`, `)}`:``;return[`[off-screen ${e}] ${t.length} ${i}${a}`]})}function g(e,t){if(!e.rect)return null;let n=t.resolveEffectiveViewport(e);return n?_(e.rect,n):null}function _(e,t){return e.y+e.height<=t.y?`above`:e.y>=t.y+t.height?`below`:null}function v(e){if(e.hittable===!0)return!0;let t=(e.type??``).toLowerCase();return t.includes(`button`)||t.includes(`link`)||t.includes(`textfield`)||t.includes(`edittext`)||t.includes(`searchfield`)||t.includes(`checkbox`)||t.includes(`radio`)||t.includes(`switch`)||t.includes(`menuitem`)||!!n(e)}function y(e){let t=new Set,r=[];for(let i of e){let e=n(i);!e||t.has(e)||(t.add(e),r.push(e))}return r}function b(e,t,n){let r=e,i=new Set;for(;r&&!i.has(r.index);)i.add(r.index),t.add(r.index),r=typeof r.parentIndex==`number`?n.get(r.parentIndex):void 0}function x(e,t,n){return i(e,n,e=>t.has(e.index))}function S(e,t,n,r,i){for(let a of e){let e=C(a);if(!e||e.size===0)continue;let o=x(a,t,n);if(!o)continue;let s=r.get(o.index)??new Set,c=i.get(o.index);for(let t of e)c&&c.size>0&&!c.has(t)||s.add(t);r.set(o.index,s)}}function C(e){let t=a(e.label,e.value);if(!t)return null;let n=new Set;return t.above&&n.add(`above`),t.below&&n.add(`below`),n.size>0?n:null}export{l as i,u as n,s as r,o as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Readable as e}from"node:stream";import{pipeline as t}from"node:stream/promises";import{TLSSocket as n}from"node:tls";async function r(n,r,s){if(r.method===`TRACE`){i(s,404);return}let c=a(r);if(!c){i(s,400);return}let l=await n.handle(o(c,r,s));s.statusCode=l.status;for(let[e,t]of l.headers)s.setHeader(e,t);if(!l.body){s.end();return}await t(e.fromWeb(l.body),s)}function i(e,t){e.statusCode=t,e.end()}function a(e){let t=e.socket instanceof n?`https`:`http`,r=URL.parse(e.url??`/`,`${t}://${e.headers.host??`127.0.0.1`}`);return!r||r.username||r.password?null:r}function o(t,n,r){let i=n.method??`GET`,a=i!==`GET`&&i!==`HEAD`;return new Request(t,{method:i,headers:s(n),signal:c(n,r),...a?{body:e.toWeb(n),duplex:`half`}:{}})}function s(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers))if(r!==void 0)for(let e of Array.isArray(r)?r:[r])t.append(n,e);return t}function c(e,t){let n=new AbortController,r=()=>{t.writableFinished||n.signal.aborted||n.abort(Error(`Proxy client disconnected before the response ended`))};return e.on(`aborted`,r),t.on(`close`,r),t.closed&&r(),n.signal}export{r as serveProxyRequest};
|
package/dist/src/observation.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{P as e}from"./sdk-contracts.js";import{n as t}from"./device-shell.js";
|
|
2
|
-
`);for(let e of r)for(let r of i){let i=r.indexOf(e);if(i===-1)continue;e===n&&(t=!0);let a=r.trim(),o=b(r.slice(i+e.length).split(`}`)[0]?.trim()??``,a);if(o)return{focusObserved:t,focus:o}}return{focusObserved:t,focus:null}}function b(e,t){let n=s.exec(e)?.[1];if(n)return{package:n,focusedWindow:`Application Not Responding: ${n}`,raw:t};let r=e.toLowerCase();if(!r.includes(`isn't responding`)&&!r.includes(`is not responding`))return null;let i=e.trim().replaceAll(/\s+/g,` `),a=c.exec(i)?.[1];return{...a?{package:a}:{},focusedWindow:i,raw:t}}function x(e){return new RegExp(e.map(S).join(`|`))}function S(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}export{d as createAndroidObservationAdapter};
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{n as t}from"./device-shell.js";import{n,o as r,t as i}from"./app-parsers.js";const a=[[`dumpsys`,`window`,`windows`],[`dumpsys`,`window`]],o=[[`dumpsys`,`activity`,`activities`],[`dumpsys`,`activity`]],s=RegExp(`(?:${n.map(y).join(`|`)})(.*)$`,`gm`),c=new Set([`com.android.permissioncontroller`,`com.google.android.permissioncontroller`,`com.android.packageinstaller`,`com.google.android.packageinstaller`]),l=new Map;function u(n){return Object.freeze({readAppState:async e=>await f(n,e),readBlockingDialog:async e=>await p(n,e),async readAppFocus(e,t,r={}){let i=d(n,e);return r.requireNoBlockingDialog&&(await p(n,e,i)).status===`dialog`?!1:(await f(n,e,i)).package===t},readSnapshotNodes:async e=>await n.readSnapshotNodes(e),async tap(e,r,i){return await n.runAdb(e,t(`adb`,`shell`,[`input`,`tap`,String(Math.round(r)),String(Math.round(i))]),{allowFailure:!0})},openApp:async(e,t)=>await n.openApp(e,t),async readScreenSize(r){let i=(await n.runAdb(r,t(`adb`,`shell`,[`wm`,`size`]))).stdout.match(/Physical size:\s*(\d+)x(\d+)/);if(!i)throw new e(`COMMAND_FAILED`,`Unable to read screen size`);return{width:Number(i[1]),height:Number(i[2])}},async isPermissionPackage(e){return c.has(e)}})}function d(e,n){let r=new Map;return i=>{let a=i.join(` `),o=r.get(a)??e.runAdb(n,t(`adb`,`shell`,i),{allowFailure:!0}).then(e=>(h(n,a,e.stdout),e.stdout));return r.set(a,o),o}}async function f(e,t,n=d(e,t)){for(let e of m(t,`foreground`)){let t=_(await n(e));if(t)return t}return{}}async function p(e,t,n=d(e,t)){for(let e of m(t,`blockingDialog`)){let t=r(await n(e));if(t.focus)return{status:`dialog`,focus:t.focus};if(t.focusObserved)return{status:`clear`}}return{status:`unknown`}}function m(e,t){let n=t===`foreground`?[a,o]:[a],r=l.get(e.id);return n.flatMap(e=>{if(!r)return e;let n=e=>r.get(`${t} ${e.join(` `)}`)===!1,i=e.filter(e=>!n(e));return i.length===0||i.length===e.length?e:[...i,...e.filter(n)]})}function h(e,t,r){if(!r)return;let a=l.get(e.id)??new Map;g(a,`foreground ${t}`,v(n).test(r)),g(a,`blockingDialog ${t}`,v([i]).test(r)),l.set(e.id,a)}function g(e,t,n){e.get(t)!==!0&&e.set(t,n)}function _(e){for(let t of e.matchAll(s)){let e=t[1]?.match(/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/);if(e?.[1]&&e[2])return{package:e[1],activity:e[2]}}return null}function v(e){return new RegExp(e.map(y).join(`|`))}function y(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}export{u as createAndroidObservationAdapter};
|
package/dist/src/overlay.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{F as e,P as t,S as n,b as r}from"./sdk-contracts.js";import{
|
|
2
|
-
`)}function J(e){let t=
|
|
3
|
-
`).toLowerCase(),n=X(e,
|
|
1
|
+
import{F as e,P as t,S as n,b as r}from"./sdk-contracts.js";import{Pr as i,Rr as a,Yn as o,ar as s,ei as c}from"./sdk-batch.js";import{n as l}from"./scroll-indicator.js";import{a as u,n as d,o as f,t as p}from"./react-native-overlay.js";function m(e){let t=v(e.label),n=v(e.value),r=v(e.identifier),i=te(r)?r:``;return y(e.type??``)?n||t||i:t||n||i}function ee(e,t){if(t===`text-view`||t===`text-field`||t===`search`)return!0;let n=a(e.type??``),r=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`textview`)||n.includes(`textarea`)||n.includes(`textfield`)||n.includes(`securetextfield`)||n.includes(`searchfield`)||n.includes(`edittext`)||r.includes(`text area`)||r.includes(`text field`)}function h(e){let t=e.replaceAll(/\s+/g,` `).trim();return t.length<=48?t:`${t.slice(0,45)}...`}function g(e,t){let n=m(e),r=ee(e,t);return{text:n,isLargeSurface:r,shouldSummarize:r&&_(n)}}function _(e){return e?e.length>80||/[\r\n]/.test(e):!1}function v(e){return typeof e==`string`?e.trim():``}function y(e){let t=a(e);return t.includes(`textfield`)||t.includes(`securetextfield`)||t.includes(`searchfield`)||t.includes(`edittext`)||t.includes(`textview`)||t.includes(`textarea`)}function te(e){return e?!/^[\w.]+:id\/[\w.-]+$/i.test(e)&&!/^_?NS:\d+$/i.test(e):!1}function b(e,t={}){let r=[],i=[];for(let a of e){let e=a.depth??0,o=a.label?.trim()||a.value?.trim()||a.identifier?.trim()||``,s=n(a.type??`Element`),c=a.inheritsLabel===!0||a.inheritsIdentifier===!0;if(s===`group`&&!o&&!c)continue;for(;r.length>0&&e<=r.at(-1);)r.pop();let l=r.length;r.push(e),i.push({node:a,depth:l,type:s,text:x(a,l,!1,s,t)})}return i}function x(e,t,r,i,a={}){let o=i??n(e.type??`Element`),s=g(e,o),c=re(e,o,a,s),l=` `.repeat(t),u=e.ref?`@${e.ref}`:``,d=ie(e,o,a,s);!c&&(e.inheritsLabel===!0||e.inheritsIdentifier===!0)&&d.push(`same label as parent`);let f=d.map(e=>` [${e}]`).join(``),p=c?` "${c}"`:``,m=C(e);return r?`${l}${u} [${o}]${f}${m}`.trimEnd():`${l}${u} [${o}]${p}${f}${m}`.trimEnd()}function S(e){return{matches:e.length,candidates:e.slice(0,5).map(e=>x(e,0,!1))}}function C(e){let t=e.actions?.filter(e=>e.trim().length>0);return!t||t.length===0?``:` actions: [${t.map(e=>`"${k(ne(e))}"`).join(`, `)}]`}function ne(e){return e.replaceAll(/\s+/g,` `).replaceAll(/[\u0000-\u001f\u007f-\u009f]/g,``).trim()}function w(e,t){let n=e.label?.trim();if(n&&D(t,n))return``;let r=e.value?.trim();if(E(t)){if(r)return r;if(n)return n}else if(n)return n;if(r)return r;let i=e.identifier?.trim();return!i||O(i)&&(t===`group`||t===`image`||t===`list`||t===`collection`)?``:i}function T(e){let t=[];return e.enabled===!1&&t.push(`disabled`),e.selected===!0&&t.push(`selected`),e.checked!==void 0&&t.push(e.checked?`checked`:`unchecked`),t}function E(e){return e===`text-field`||e===`text-view`||e===`search`}function D(e,t){return e!==`scroll-area`&&e!==`list`&&e!==`collection`&&e!==`table`?!1:l(t)}function O(e){return/^[\w.]+:id\/[\w.-]+$/i.test(e)}function re(e,t,n,r){return!n.summarizeTextSurfaces||!r.shouldSummarize?w(e,t):ae(e,t,r.text)||w(e,t)}function ie(e,t,n,r){let i=[...T(e),...e.presentationHints??[]];return!n.summarizeTextSurfaces||(e.focused===!0&&i.push(`focused`),E(t)&&i.push(`editable`),oe(e,t)&&i.push(`scrollable`),!r.shouldSummarize)?A(i):(i.push(`preview:"${k(h(r.text))}"`),i.push(`truncated`),A(i))}function ae(e,t,n){let r=v(e.label);if(r&&r!==n)return r;let i=v(e.identifier);if(i&&!O(i)&&i!==n)return i;switch(t){case`text`:case`text-view`:return`Text view`;case`text-field`:return`Text field`;case`search`:return`Search field`;default:return``}}function oe(e,t){if(t===`scroll-area`)return!0;let n=(e.type??``).toLowerCase(),r=`${e.role??``} ${e.subrole??``}`.toLowerCase();return n.includes(`scroll`)||r.includes(`scroll`)}function k(e){return e.replaceAll(`\\`,String.raw`\\`).replaceAll(`"`,String.raw`\"`)}function A(e){return[...new Set(e)]}const j={state:`sparse`,backend:`tree`,reason:`legacy iOS capture exposed only the application root`,reasonCode:`sparse-tree`},M={sparse:`capture was sparse`,truncated:`capture was truncated`,unsettled:`the surface was still changing after a gesture`};function N(e){return typeof e==`string`&&Object.hasOwn(M,e)}function P(e){if(e.scope!==void 0)return`scope`;if(e.depth!==void 0)return`depth`}function F(e,t=`is`){let n=`${t} absent`;return e===`scope`?`${n} does not support --scope; it requires an unscoped capture`:`${n} does not support --depth; it requires a full-depth capture`}function I(e,t){let n=t[0]?z(t[0]):void 0,r=t.length;if(e.truncated===!0)return{kind:`truncated`,matches:r,...n?{firstMatch:n}:{}};let i=L(e);return i?{kind:`sparse`,matches:r,...n?{firstMatch:n}:{},quality:{state:i.state,backend:i.backend,...i.reason?{reason:i.reason}:{},...i.reasonCode?{reasonCode:i.reasonCode}:{}}}:r===0?{kind:e.postGestureOutcome?.kind===`unsettled`?`unsettled`:`absent`,matches:0}:{kind:`present`,matches:r,firstMatch:n}}function L(e){let t=e.snapshotQuality;return t?.state===`sparse`?{state:t.state,backend:t.backend,...t.reason?{reason:t.reason}:{},...t.reasonCode?{reasonCode:t.reasonCode}:{}}:R(e)?j:void 0}function R(e){return e.snapshotQuality||e.backend!==`xctest`||e.nodes.length!==1?!1:a(e.nodes[0]?.type??``)===`application`}function z(e){let t=o(e),n=s(i(e),256);return{...t,...n&&n!==t.label?{text:n}:{}}}const B={selectorNotFound:`selector_not_found`,predicateFailed:`predicate_failed`,refNotFound:`ref_not_found`,refUnlabeled:`ref_unlabeled`,targetBoundsInvalid:`target_bounds_invalid`,captureSparse:`capture_sparse`,targetCovered:`target_covered`};function V(e,n=`is`){return new t(`INVALID_ARGS`,F(e,n),{command:n,predicate:`absent`,rejectedOption:e})}function H(e,n,r=`is`){let i=`firstMatch`in n?n.firstMatch:void 0,a={command:r,reason:B.predicateFailed,predicate:`absent`,selector:e,matches:n.matches,observation:n.kind,...i?{firstMatch:i}:{},...n.kind===`sparse`?{snapshotQuality:n.quality}:{},...n.kind===`truncated`?{truncated:!0}:{}};if(n.kind===`present`){let i=n.matches>1;return new t(`COMMAND_FAILED`,`${r} absent failed for selector ${e}: ${n.matches} match${i?`es`:``} found`,{...a,...i?{hint:`Refine the selector to match no elements.`}:{}})}return new t(`COMMAND_FAILED`,`${r} absent could not prove absence for selector ${e}: ${M[n.kind]}`,{...a,hint:`Retry after the accessibility capture is complete.`})}function U(n,r,i=`is`){let a=e(r),o=typeof a.details?.reason==`string`?a.details.reason:typeof a.details?.androidSnapshotHelperFailureReason==`string`?a.details.androidSnapshotHelperFailureReason:void 0;return new t(`COMMAND_FAILED`,`${i} absent could not prove absence for selector ${n}: capture was unreadable`,{command:i,reason:B.predicateFailed,predicate:`absent`,selector:n,matches:0,observation:`unreadable`,captureErrorCode:a.code,...o?{captureErrorReason:o}:{},hint:`Retry after the accessibility capture is readable.`},a)}const W=/\b(logbox|redbox|reload js|copy stack|component stack|call stack|runtime error|open debugger to view warnings)\b/,G=[/\b[\w.$<>/-]+\.(?:tsx?|jsx?):\d+(?::\d+)?\b/,/\b[\w.$<>/-]+\.(?:tsx?|jsx?)\s+\(\d+:\d+\)/],K=new Set([`x`,`×`,`✕`,`✖`,`⨯`]);function q(e){if(J(e).detected)return[`Hint: React Native warning/error overlay detected. It overlays part of the app and should be handled before interacting.`,`Run: agent-device react-native dismiss-overlay`,`The command verifies the overlay is gone. Run agent-device snapshot -i afterward only when you need fresh refs for the next action.`].join(`
|
|
2
|
+
`)}function J(e){let t=se(e),n=t.detected?ce(t):null;return{detected:t.detected,dismissNodes:t.dismissNodes,minimizeNodes:t.minimizeNodes,collapsedNodes:t.collapsedNodes,primaryAction:n}}function se(e){let t=e.map(le).join(`
|
|
3
|
+
`).toLowerCase(),n=X(e,he),r=X(e,f),i=X(e,d,ye),a=X(e,Y),o=de(t),s=fe(t);return{dismissNodes:n,minimizeNodes:r,collapsedNodes:i,detected:me({text:t,hasReactNativeStackFrame:o,hasOverlayControl:pe(t,n,r),hasControllessRedBoxText:s,collapsedNodes:i,openDebuggerWarningNodes:a})}}function ce(e){let t=xe(e.dismissNodes);if(t)return we(t,Te(t));let n=Ee(e.collapsedNodes.filter(be));return n?.rect?{action:`close-collapsed-banner`,point:ke(n),rect:n.rect,ref:n.ref,label:$(n)}:null}function le(e){return[e.label,e.value,e.identifier,e.type,e.role].filter(Boolean).join(` `)}function ue(e){return W.test(e)}function de(e){return G.some(t=>t.test(e))}function fe(e){return/\buncaught\b/.test(e)&&/unable to download asset/.test(e)}function pe(e,t,n){return t.length>0||n.length>0||/\b(reload js|copy stack)\b/.test(e)}function me(e){return e.collapsedNodes.length>0||e.openDebuggerWarningNodes.length>0||e.hasControllessRedBoxText||e.hasOverlayControl&&(ue(e.text)||e.hasReactNativeStackFrame)}function Y(e){return e.includes(`open debugger to view warnings`)||/^!,\s+open debugger\b/.test(e)}function he(e){return u(e)||ge(e)||_e(e)}function ge(e){return/^close(?:\s*\([^)]*\))?$/i.test(e)}function _e(e){return K.has(e)}function ve(e){return/^!,\s+/.test(e)}function ye(e){return!e.rect||e.rect.height<=180}function be(e){let t=$(e)?.trim().toLowerCase()??``;return(Y(t)||ve(t))&&p(e)}function X(e,t,n=()=>!0){let r=[];for(let i of e)i.ref&&n(i)&&[i.label,i.value,i.identifier].map(e=>e?.trim().toLowerCase()).filter(e=>!!e).some(e=>t(e))&&r.push(i);return r}function xe(e){return Z(e,Ce)}function Se(e){let t=[e.type,e.role,e.subrole].join(` `).toLowerCase();return/\b(button|menuitem|link)\b/.test(t)}function Ce(e){return[Q(Se(e)),Q(e.hittable),-(e.rect?c(e.rect):1/0)]}function we(e,t){if(!e.rect)throw Error(`React Native overlay target node must have rect`);return{action:t,point:r(e.rect),rect:e.rect,ref:e.ref,label:$(e)}}function Te(e){let t=$(e)?.trim().toLowerCase();return t&&u(t)?`dismiss`:`close`}function Ee(e){return Z(e,De)}function Z(e,t){let n=e.filter(e=>e.rect);return n.length===0?null:n.sort((e,n)=>Oe(t(n),t(e)))[0]??null}function De(e){return[Q(e.hittable),e.rect?.width??0,e.rect?.y??0]}function Q(e){return+(e===!0)}function Oe(e,t){for(let n=0;n<e.length;n+=1){let r=e[n]-t[n];if(r!==0)return r}return 0}function ke(e){if(!e.rect)throw Error(`Collapsed React Native warning node must have rect`);let t=Math.min(e.rect.height,52),n=Math.min(36,Math.max(18,t*.45));return{x:Math.round(Ae(e.rect.x+e.rect.width-n,e.rect.x+1,e.rect.x+e.rect.width-1)),y:Math.round(e.rect.y+t/2)}}function Ae(e,t,n){return Math.min(n,Math.max(t,e))}function $(e){return e.label??e.value??e.identifier}export{m as _,U as a,I as c,L as d,b as f,T as g,x as h,H as i,R as l,S as m,q as n,B as o,w as p,V as r,P as s,J as t,N as u,y as v};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{r as e}from"./diagnostics.js";import{l as t,m as n}from"./exec.js";import{
|
|
2
|
-
`)){let e=/^\s*(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(n);if(!e)continue;let r=Number.parseInt(e[1],10);!Number.isInteger(r)||r<=0||t.set(r,{state:e[2],startTime:e[3]})}}catch{}return t}function
|
|
3
|
-
`)){let e
|
|
1
|
+
import{r as e}from"./diagnostics.js";import{l as t,m as n}from"./exec.js";import{i as r}from"./retry.js";import i from"node:crypto";import a from"node:fs";import o from"node:path";function s(e){l(e.destination,t=>{let n={encoding:typeof e.contents==`string`?`utf8`:void 0,...e.mode===void 0?{}:{mode:e.mode}};a.writeFileSync(t,e.contents,n),e.publish===`link-exclusive`?a.linkSync(t,e.destination):a.renameSync(t,e.destination)})}function c(e){let t=o.dirname(e.destination);l(e.destination,n=>{let r,i=!1,o;try{u(e.destination),r=a.openSync(n,`wx`,e.mode??384),a.writeFileSync(r,e.contents,`utf8`),a.fsyncSync(r),a.closeSync(r),r=void 0,u(e.destination),e.publish===`link-exclusive`?a.linkSync(n,e.destination):a.renameSync(n,e.destination),ee(t)}catch(e){i=!0,o=e}if(r!==void 0)try{a.closeSync(r)}catch(e){i||(i=!0,o=e)}if(i)throw o})}function l(t,n){let r=te(t);try{return n(r)}finally{try{a.rmSync(r,{force:!0})}catch(n){e({level:`warn`,phase:`atomic_file_cleanup_failed`,data:{destination:t,temporaryPath:r,error:n instanceof Error?n.message:String(n)}})}}}function ee(e){let t;try{t=a.openSync(e,`r`),a.fsyncSync(t)}catch{}finally{if(t!==void 0)try{a.closeSync(t)}catch{}}}function te(e){return o.join(o.dirname(e),`.${o.basename(e)}.${process.pid}-${i.randomUUID()}.tmp`)}function u(e){let t=ne(e);if(t?.isSymbolicLink())throw Error(`Refusing to replace a durable file symbolic link: ${e}`);if(t&&!t.isFile())throw Error(`Refusing to replace a durable path that is not a regular file: ${e}`)}function ne(e){try{return a.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}const d=1e3,f=`/bin/ps`,p=2e3,m=`powershell.exe`;function h(){return process.env}function re(e){return h()[e]}function g(e){process.stderr.write(e)}function _(){return process.cwd()}function v(){return process.execPath}function ie(){return process.version}function y(){return process.platform}function ae(){return process.pid}function b(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}function x(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(-e,0),!0}catch(e){return e.code===`EPERM`}}async function S(e,t=d){if(A())return await I(e,t);let[n,r,i]=await Promise.all([D(e,`lstart=`,t),D(e,`command=`,t),D(e,`state=`,t)]);return{startTime:n,command:r,zombie:i===null?null:i.startsWith(`Z`)}}function C(e){return E(e,`lstart=`)}function oe(e){return E(e,`command=`)}function w(e){return A()?!1:E(e,`state=`)?.startsWith(`Z`)??!1}function T(e){let t=new Map,r=B(e);if(r.length===0)return t;if(A()){for(let e of N(r,p))e.startTime!==null&&t.set(e.pid,{state:`R`,startTime:e.startTime});return t}try{let e=n(f,[`-p`,r.join(`,`),`-o`,`pid=,state=,lstart=`],{allowFailure:!0,timeoutMs:d});if(e.exitCode!==0)return t;for(let n of e.stdout.split(`
|
|
2
|
+
`)){let e=/^\s*(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(n);if(!e)continue;let r=Number.parseInt(e[1],10);!Number.isInteger(r)||r<=0||t.set(r,{state:e[2],startTime:e[3]})}}catch{}return t}function E(e,t){if(!Number.isInteger(e)||e<=0)return null;if(A())return P(e,t);try{return O(n(f,[`-p`,String(e),`-o`,t],{allowFailure:!0,timeoutMs:d}))}catch{return null}}async function D(e,n,r){if(!Number.isInteger(e)||e<=0)return null;try{return O(await t(f,[`-p`,String(e),`-o`,n],{allowFailure:!0,timeoutMs:r}))}catch{return null}}function O(e){if(e.exitCode!==0)return null;let t=e.stdout.trim();return t.length>0?t:null}function k(e,t,n){let r=[];for(let i of e.replace(/^\uFEFF/,``).split(`
|
|
3
|
+
`)){let e=t.exec(i);if(!e)continue;let a=Number.parseInt(e[1],10);if(!Number.isInteger(a)||a<=0)continue;let o=Number.parseInt(e[2],10);r.push(n(e,a,Number.isInteger(o)&&o>0?o:void 0))}return r}function se(e){return k(e,/^\s*(\d+)\s+(\d+)\s+(.+?)\s*$/,(e,t,n)=>({pid:t,ppid:n,command:e[3]}))}function A(){return y()===`win32`}const ce=` | ForEach-Object { $birth = if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('yyyyMMddHHmmssfffffff', [System.Globalization.CultureInfo]::InvariantCulture) } else { '' }; '{0}|{1}|{2}|{3}' -f $_.ProcessId, $_.ParentProcessId, $birth,`+String.raw` ($_.CommandLine -replace '[\r\n]+', ' ') }`;function j(e){return[`-NoProfile`,`-NonInteractive`,`-Command`,`[Console]::OutputEncoding=[System.Text.Encoding]::UTF8; ${e.length>0?`Get-CimInstance -ClassName Win32_Process -Filter '${e.map(e=>`ProcessId=${e}`).join(` OR `)}'`:`Get-CimInstance -ClassName Win32_Process`}${ce}`]}function M(e){return k(e,/^(\d+)\|(\d+)\|([^|]*)\|(.*)\r?$/,(e,t,n)=>({pid:t,...n===void 0?{}:{ppid:n},startTime:e[3].length>0?e[3]:null,command:e[4].length>0?e[4]:null}))}function N(e,t){try{let r=n(m,j(e),{allowFailure:!0,timeoutMs:t});return r.exitCode===0?M(r.stdout):[]}catch{return[]}}function P(e,t){let n=N([e],p).find(t=>t.pid===e);return n?t===`lstart=`?n.startTime:t===`command=`?n.command:`R`:null}function F(e){return Math.max(e,p)}async function I(e,n){if(!Number.isInteger(e)||e<=0)return{startTime:null,command:null,zombie:null};try{let r=await t(m,j([e]),{allowFailure:!0,timeoutMs:F(n)});if(r.exitCode!==0)return{startTime:null,command:null,zombie:null};let i=M(r.stdout).find(t=>t.pid===e);return i?{startTime:i.startTime,command:i.command,zombie:!1}:{startTime:null,command:null,zombie:null}}catch{return{startTime:null,command:null,zombie:null}}}async function L(e){let n=await(e.runCommand??t)(m,j([]),{allowFailure:!0,timeoutMs:F(e.timeoutMs)});return n.exitCode===0?M(n.stdout).map(e=>({pid:e.pid,...e.ppid===void 0?{}:{ppid:e.ppid},command:e.command??``})):[]}async function R(e){if(A())return await L(e);let n=await(e.runCommand??t)(e.runCommand?`ps`:f,[`-ax`,`-o`,`pid=,ppid=,command=`],{allowFailure:!0,timeoutMs:e.timeoutMs});return n.exitCode===0?se(n.stdout):[]}function z(e,t){let n=new Set(B(e)),r=!0;for(;r;){r=!1;for(let e of t)e.ppid===void 0||!n.has(e.ppid)||n.has(e.pid)||(n.add(e.pid),r=!0)}return t.filter(e=>n.has(e.pid))}function B(e,t={}){return[...new Set(e)].filter(e=>Number.isInteger(e)&&e>0&&e!==t.excludePid)}function V(e,t){let n=B(e,{excludePid:process.pid}),r=0;for(let e of n)try{process.kill(e,t),r+=1}catch{}return r}async function H(e,t){if(!b(e))return!0;let n=Date.now();for(;Date.now()-n<t;)if(await r(50),!b(e))return!0;return!b(e)}async function U(e){let t=B(e.pids,{excludePid:process.pid});t.length!==0&&(V(t,`SIGTERM`),await Promise.all(t.map(async t=>await H(t,e.termTimeoutMs))),V(t.filter(e=>b(e)),`SIGKILL`),await Promise.all(t.map(async t=>await H(t,e.killTimeoutMs))))}const W=1e3,G=[`-n`,`hw.optional.arm64`];let K,q;function le(){return q===void 0?(K??=de(process.platform,process.arch).then(J),K):Promise.resolve(q)}function ue(){return q??J(Y(process.platform===`darwin`&&pe(),process.arch))}function J(e){return q??=e,q}async function de(e,t){return Y(e===`darwin`&&await fe(),t)}function Y(e,t){return e?`arm64`:t===`x64`?`x86_64`:t}async function fe(){try{let e=await t(`/usr/sbin/sysctl`,G,{allowFailure:!0,timeoutMs:W});return e.exitCode===0&&e.stdout.trim()===`1`}catch{return!1}}function pe(){try{let e=n(`/usr/sbin/sysctl`,G,{allowFailure:!0,timeoutMs:W});return e.exitCode===0&&e.stdout.trim()===`1`}catch{return!1}}function X(e){return typeof e==`number`&&Number.isInteger(e)&&e>0&&e<=2147483647}function me(){return{pid:process.pid,startTime:C(process.pid)}}function Z(e,t){return e.pid===t.pid&&e.startTime===t.startTime}function he(e,t){return e.pid!==t.pid||!!(e.startTime&&t.startTime&&e.startTime!==t.startTime)}function ge(e){return Q(e.owner)||$(e,T([e.owner.pid]).get(e.owner.pid)??null)}function _e(e,t){return Q(e.owner)||$(e,t)}function Q(e){if(!X(e.pid))return`unknown`;if(!b(e.pid))return`owner-process-dead`}function $(e,t){let{owner:n,stateDir:r}=e;return ve(n,t)?`owner-process-dead`:n.startTime&&ye(n,t)?`owner-process-reused`:r?be(r):`live`}function ve(e,t){return t===void 0?w(e.pid):t?.state.startsWith(`Z`)??!1}function ye(e,t){let n=t===void 0?C(e.pid):t?.startTime??null;return n!==null&&n!==e.startTime}function be(e){try{return a.statSync(e),`live`}catch(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`?`owner-state-dir-gone`:`unknown`}}export{c as A,S as C,B as D,U as E,l as M,H as O,oe as S,V as T,R as _,Z as a,re as b,_ as c,ie as d,y as f,w as g,x as h,he as i,s as j,g as k,h as l,b as m,_e as n,me as o,ae as p,X as r,z as s,ge as t,v as u,le as v,C as w,T as x,ue as y};
|
package/dist/src/perf-facade.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as e}from"./sdk-contracts.js";import{d as t,m as n,p as r,w as i}from"./sdk-device.js";import{cr as a}from"./sdk-batch.js";import{o,r as s,u as c}from"./exec.js";import"./command.js";import{t as l}from"./parser.js";import{n as u,t as d}from"./numeric.js";import{C as f,D as ee,g as te,i as ne,m as p,o as m,u as h,w as re,y as ie}from"./host-file.js";import{a as ae,o as g}from"./tool-provider.js";import{o as oe,t as se}from"./devicectl.js";import{n as ce}from"./simctl.js";import _ from"node:path";import{fileURLToPath as v}from"node:url";function y(e,t){for(let n of e){if(t(n))return n;let e=y(n.children,t);if(e)return e}}function b(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...b(r.children,t));return n}function le(e,t){return e.children.find(e=>e.name===t)?.text??null}function x(e,t){let n=y(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>le(e,`mnemonic`)??``):[]}function S(e){if(!e||e.children.some(e=>e.name===`sentinel`)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function C(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:S(e):null}function w(e,t){for(let n of e)w(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:S(n),process:E(n)})}function T(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:E(e):null}function E(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=S(y(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).trim().replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}function ue(e){return new Map(b(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function D(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}const O=new Set([`backtrace`,`tagged-backtrace`]);function k(e,t=10){let n=l(e),r=ue(n),i=new Map,a=0,o=0;for(let e of b(n,e=>e.name===`row`)){let t=A(e,r),n=de(e,r);if(t===void 0||!n)continue;let s=n.attributes.name?.trim()||`<unknown>`,c=fe(n,r),l=`${c??``}\u0000${s}`,u=i.get(l);i.set(l,{symbol:s,binary:c,weightNs:(u?.weightNs??0)+t}),a+=1,o+=t}let s=Math.max(0,Math.floor(t)),c=[...i.values()].sort((e,t)=>t.weightNs-e.weightNs||e.symbol.localeCompare(t.symbol)).slice(0,s).map(({symbol:e,binary:t,weightNs:n})=>({symbol:e,binary:t,selfSampleMs:j(n),selfSamplePercent:o>0?u(n/o*100):0}));return{sampleCount:a,totalSampleWeightMs:j(o),topFunctions:c}}function A(e,t){let n=D(e.children.find(e=>e.name===`weight`),t);if(!n?.text)return;let r=Number(n.text);return Number.isFinite(r)&&r>0?r:void 0}function de(e,t){return D(D(e.children.find(e=>O.has(e.name)),t)?.children.find(e=>e.name===`frame`),t)}function fe(e,t){return D(e.children.find(e=>e.name===`binary`),t)?.attributes.name?.trim()||void 0}function j(e){return Math.round(e/1e6*1e3)/1e3}async function pe(e){let t=await _e(e.device,e.appBundleId);await m(_.dirname(e.outPath));let n=P({device:e.device,template:e.template,target:t.pids,outPath:e.outPath}),r=new Date().toISOString(),a=await F(n,e.outPath,{device:e.device,appBundleId:e.appBundleId,failureMessage:`Failed to start Apple xctrace ${e.mode} capture for ${e.appBundleId}`},async()=>{let e=c(`xcrun`,n,{allowFailure:!0}),t=await ye(e.wait);return t?{failure:t}:{recorded:e}});return{kind:`xctrace`,mode:e.mode,template:e.template,outPath:e.outPath,appBundleId:e.appBundleId,deviceId:e.device.id,platform:i(e.device),targetPids:t.pids,targetProcesses:t.processNames,startedAt:r,child:a.child,wait:a.wait}}async function me(e,t=e.outPath){t!==e.outPath&&await m(_.dirname(t));let n=o(await L(e,{failOnForcedKill:!0}),`Failed to stop Apple xctrace ${e.mode} capture`,t=>({tracePath:e.outPath,captureCleanedUp:!0,hint:B(t.stdout,t.stderr)}));return t!==e.outPath&&await re(e.outPath,t).catch(async()=>{await ne(e.outPath,t),await f(e.outPath)}),await z(t,{message:`xctrace produced no trace data`,hint:`Keep the Apple device unlocked and connected, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.deviceId,stdout:n.stdout,stderr:n.stderr}),{kind:`xctrace`,mode:e.mode,template:e.template,outPath:t,appBundleId:e.appBundleId,deviceId:e.deviceId,platform:e.platform,targetPids:e.targetPids,targetProcesses:e.targetProcesses,startedAt:e.startedAt,endedAt:new Date().toISOString()}}async function he(e){return await L(e,{failOnForcedKill:!1})}async function ge(t){let n=await p(`agent-device-xctrace-report-`),r=_.join(n,`trace-toc.xml`),i=_.join(n,`time-profile.xml`);try{let n=await N({tracePath:t.tracePath,outPath:r,query:`toc`,failureMessage:`Failed to export Apple xctrace report metadata`,failureDetails:{tracePath:t.tracePath}}),a=await N({tracePath:t.tracePath,outPath:i,query:{schema:`time-profile`},failureMessage:`Failed to export Apple xctrace Time Profiler samples`,failureDetails:{tracePath:t.tracePath}}),o=be({...t,tocXml:n,timeProfileXml:a});if(o.summary.sampleCount===0)throw new e(`COMMAND_FAILED`,`Apple xctrace CPU report contained no samples`,{tracePath:t.tracePath,tableSchemas:o.summary.tableSchemas,hint:`Keep the app active while recording, then retry. Open the raw trace in Instruments if it still contains no Time Profiler samples.`});return await m(_.dirname(t.outPath)),await ee(t.outPath,`${JSON.stringify(o,null,2)}\n`),o}finally{await f(n).catch(()=>{})}}async function M(e){let t=P({device:e.device,template:e.template,target:e.target,timeLimit:e.timeLimit,outPath:e.tracePath}),{result:n,...r}=await F(t,e.tracePath,e,async()=>{let e=new Date().toISOString(),n=await g(t,{allowFailure:!0,timeoutMs:6e4});return n.exitCode===0?{recorded:{result:n,startedAt:e,endedAt:new Date().toISOString(),capturedAtMs:Date.now()}}:{failure:n}});return e.requireTraceData&&await z(e.tracePath,{message:`${e.failureMessage}: xctrace produced no trace data`,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:n.stdout,stderr:n.stderr}),r}async function N(e){let t=[`xctrace`,`export`,`--input`,e.tracePath,...e.query===`toc`?[`--toc`]:[`--xpath`,`/trace-toc/run/data/table[@schema="${e.query.schema}"]`],`--output`,e.outPath];return o(await g(t,{allowFailure:!0,timeoutMs:15e3}),e.failureMessage,n=>({cmd:`xcrun`,args:t,...e.failureDetails,hint:B(n.stdout,n.stderr)})),await ie(e.outPath)}async function _e(n,i){if(!t(n.platform))throw new e(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on Android.`,{platform:n.platform,hint:`Android native profiling belongs to the Android perf rollout and is not implemented under Apple xctrace.`});let{readAppleProcessSamples:o,resolveAppleExecutable:s,resolveIosDevicePerfTarget:c}=await import(`./perf-target.js`);if(r(n)&&n.kind===`device`){let e=await c(n,i);return{pids:e.map(e=>e.pid),processNames:a(e.map(e=>_.basename(v(e.executable))))}}let l=await s(n,i),u=await o(n,l);if(u.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${i}`,{appBundleId:i,deviceId:n.id,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});return{pids:u.map(e=>e.pid),processNames:[l.executableName]}}function P(e){return[`xctrace`,`record`,`--template`,e.template,...r(e.device)?[`--device`,e.device.id]:[],...e.target===`all-processes`?[`--all-processes`]:e.target.flatMap(e=>[`--attach`,String(e)]),...e.timeLimit?[`--time-limit`,e.timeLimit]:[],`--output`,e.outPath,`--quiet`,`--no-prompt`]}async function F(t,n,r,i){for(let a=1;;a+=1){await ve(n,a);let o=await i();if(`recorded`in o)return o.recorded;if(a<3&&I(o.failure))continue;let{failure:c}=o;throw new e(`COMMAND_FAILED`,r.failureMessage,s(c,{cmd:`xcrun`,args:t,appBundleId:r.appBundleId,deviceId:r.device.id,hint:B(c.stdout,c.stderr)}))}}function I(e){let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`_lockkperf`)||t.includes(`could not lock kperf`)||t.includes(`likely another session just started`)}async function ve(e,t){t<=1||(await f(e).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)))}async function ye(e){return await Promise.race([e,new Promise(e=>setTimeout(e,500))])}async function L(t,n){t.child.kill(`SIGINT`);let r=await R(t.wait,45e3);if(r)return r;t.child.kill(`SIGKILL`);let i=await R(t.wait,5e3);if(i&&!n.failOnForcedKill)return i;throw i?new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop`,{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,tracePath:t.outPath,captureCleanedUp:!0,forcedKill:!0,hint:`xctrace did not finish after SIGINT, so it was force-killed. Retry the perf command after confirming no other xctrace session is active.`}):new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop after SIGKILL`,{tracePath:t.outPath,captureCleanedUp:!1,forcedKill:!0,hint:`xctrace did not exit after SIGKILL. Inspect running xctrace processes before retrying.`})}async function R(e,t){return await Promise.race([e,new Promise(e=>setTimeout(e,t))])}async function z(t,n){let r=await h(t).catch(()=>null);if(!(r?.isDirectory()===!0?(await te(t).catch(()=>[])).length>0:(r?.size??0)>0))throw new e(`COMMAND_FAILED`,n.message,{tracePath:t,appBundleId:n.appBundleId,deviceId:n.deviceId,stdout:n.stdout,stderr:n.stderr,hint:n.hint})}function be(e){let t=l(e.tocXml),n=b(t,e=>e.name===`run`),r=a(b(t,e=>e.name===`table`).map(e=>e.attributes.schema).filter(e=>typeof e==`string`&&e.length>0)).sort(),i=k(e.timeProfileXml);return{kind:`xctrace`,mode:`cpu-profile`,template:e.template,tracePath:e.tracePath,reportPath:e.outPath,appBundleId:e.appBundleId,generatedAt:new Date().toISOString(),summary:{runCount:n.length,tableSchemas:r,...i}}}function B(e,t){let n=oe(e,t);if(n)return n;let r=`${e}\n${t}`.toLowerCase();return r.includes(`no device matched`)||r.includes(`failed to find device`)?se:r.includes(`timed out`)?`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`:`Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it.`}const V=`xctrace-animation-hitches`;function xe(e){let t=Se(e.frameLifetimesXml),n=Ce(e.displayInfoXml),r=we(e.hitchesXml).filter(t=>De(t,e.processIds,e.processNames)),i=r.length,o=Math.max(0,Math.round(Date.parse(e.windowEndedAt)-Date.parse(e.windowStartedAt))),s=H(r,Date.parse(e.windowStartedAt));return{droppedFramePercent:t>0?u(i/t*100):0,droppedFrameCount:i,totalFrameCount:t,sampleWindowMs:o,windowStartedAt:e.windowStartedAt,windowEndedAt:e.windowEndedAt,measuredAt:e.measuredAt,method:V,matchedProcesses:a(r.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:n===void 0?void 0:d(1e3/n),refreshRateHz:n,worstWindows:s.length>0?s:void 0}}function Se(e){return ke(e,`hitches-frame-lifetimes`).length}function Ce(e){if(!e)return;let{rows:t,schema:n}=U(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){w(e.children,i);let t=C(e.children[r],i);if(t!==null&&t>0)return t}}function we(e){let t=l(e),n=Te(t);if(!n)return[];let r=new Map;return b(t,e=>e.name===`row`).map(e=>Ee(e,n,r)).filter(e=>!!e)}function Te(e){let t=x(e,`hitches`),n={start:t.indexOf(`start`),duration:t.indexOf(`duration`),process:t.indexOf(`process`),isSystem:t.indexOf(`is-system`)};return Object.values(n).every(e=>e>=0)?n:null}function Ee(e,t,n){if(w(e.children,n),Ae(e.children[t.isSystem],n)===!0)return null;let r=C(e.children[t.start],n),i=C(e.children[t.duration],n);if(r===null||i===null)return null;let a=T(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function De(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function H(e,t){if(e.length===0)return[];let n=[...e].sort((e,t)=>e.startNs-t.startNs),r=[],i=[];for(let e of n){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}r.push(i),i=[e]}return i.length>0&&r.push(i),r.map(e=>Oe(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function Oe(e,t){let n=Math.min(...e.map(e=>e.startNs)),r=Math.max(...e.map(e=>e.startNs+e.durationNs)),i=Math.max(0,Math.round(n/1e6)),a=Math.max(i,Math.round(r/1e6));return{startOffsetMs:i,endOffsetMs:a,startAt:new Date(t+i).toISOString(),endAt:new Date(t+a).toISOString(),missedDeadlineFrameCount:e.length,worstFrameMs:d(Math.max(...e.map(e=>e.durationNs))/1e6)}}function ke(e,t){return U(e,t).rows}function U(e,t){let n=l(e),r=x(n,t);return{rows:r.length===0?[]:b(n,e=>e.name===`row`),schema:r}}function Ae(e,t){let n=C(e,t);return n===null?null:n!==0}const W=`ps-process-snapshot`,G=`xctrace-activity-monitor`,K=`leaks-output-graph`,q=12e4;async function je(t,n){if(r(t)&&t.kind===`device`)return await Ve(t,n);let{readAppleProcessSamples:i,resolveAppleExecutable:a}=await import(`./perf-target.js`),o=await a(t,n),s=await i(t,o);if(s.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});let c=new Date().toISOString();return $({residentMemoryKb:s.reduce((e,t)=>e+t.rssKb,0),measuredAt:c,matchedProcesses:[o.executableName],memoryMethod:W})}async function Me(t,n,r){let i=Y(t);if(!i.memgraph)return{available:!1,kind:`memgraph`,reason:i.reason,hint:i.hint,support:i};let a=await Ge(t,n,i);if(a.available===!1)return a;let{process:o}=a;await m(_.dirname(r));let c=await Fe(r),l;try{l=await Ne(t,r,o.pid)}catch(e){throw await J(r,c),Pe(t,n,o,r,e)}if(l.exitCode!==0)throw await J(r,c),new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,s(l,{kind:`memgraph`,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),path:r,hint:Q(t,l.stdout,l.stderr)}));let u=await h(r).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await J(r,c),new e(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:n,pid:o.pid,path:r,hint:`Retry with a writable --out path. If the file is still empty, run with --debug and inspect leaks output.`});return{available:!0,kind:`memgraph`,path:r,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:K,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),support:i}}async function Ne(e,t,r){return n(e)?await ae(`leaks`,[`--outputGraph=${t}`,String(r)],{allowFailure:!0,timeoutMs:q}):await g(ce(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(r)]),{allowFailure:!0,timeoutMs:q})}function Pe(t,n,r,i,a){if(a instanceof e){let o=a.details??{};return new e(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:Q(t,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, run with --debug and inspect leaks output.`},a)}async function Fe(e){return await h(e).then(e=>e.isFile()).catch(()=>!1)}async function J(e,t){t||await f(e).catch(()=>{})}async function Ie(t,n){if(!r(t)||t.kind!==`device`)throw new e(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:i(t),deviceKind:t.kind});let{resolveIosDevicePerfTarget:o}=await import(`./perf-target.js`),s=await o(t,n),c=await ze(t,n,s);return xe({hitchesXml:c.hitchesXml,frameLifetimesXml:c.frameLifetimesXml,displayInfoXml:c.displayInfoXml,processIds:s.map(e=>e.pid),processNames:a(s.map(e=>_.basename(v(e.executable)))),windowStartedAt:c.windowStartedAt,windowEndedAt:c.windowEndedAt,measuredAt:c.windowEndedAt})}function Le(e){return r(e)&&e.kind===`device`?{method:V,description:`Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`short 2s xctrace Animation Hitches record of the active app process`,resetsAfterRead:!1}:{method:V,description:`Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.`,unit:`percent`,primaryField:`droppedFramePercent`}}function Re(e){if(r(e)&&e.kind===`device`)return{method:G,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=n(e)?`host ps for the running macOS app executable resolved from the bundle ID.`:`xcrun simctl spawn ps, with host ps fallback, for the running iOS simulator app executable resolved from the bundle ID.`;return{method:W,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function Y(e){return r(e)&&e.kind===`device`?{platform:i(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Physical iOS device memgraph capture is not exposed through reliable local agent-device tooling.`,hint:`Use perf memory sample for a compact resident-memory reading, or reproduce on an iOS simulator/macOS target for memgraph capture.`}:r(e)&&e.kind===`simulator`?{platform:i(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`iOS simulator processes are host-visible through simctl spawn leaks.`,hint:`Keep the simulator app running in the foreground while the memgraph is captured.`}:n(e)?{platform:i(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`macOS app processes are host-visible to leaks --outputGraph.`,hint:`Grant Terminal/agent process permissions if macOS denies process inspection.`}:{platform:i(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Apple memgraph capture is available only for iOS simulator and macOS app sessions.`,hint:`Use perf memory sample on supported app sessions, or rerun against iOS simulator/macOS for memgraph capture.`}}async function ze(e,t,n){let r=await p(`agent-device-ios-frame-perf-`),i=_.join(r,`animation-hitches.trace`);try{let a=await M({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,timeLimit:`2s`,target:n.map(e=>e.pid),requireTraceData:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`}),o={device:e,appBundleId:t,tracePath:i,tempDir:r};return{windowStartedAt:a.startedAt,windowEndedAt:a.endedAt,hitchesXml:await X(o,`hitches`),frameLifetimesXml:await X(o,`hitches-frame-lifetimes`),displayInfoXml:await X(o,`device-display-info`).catch(()=>void 0)}}finally{await f(r).catch(()=>{})}}async function X(e,t){return await N({tracePath:e.tracePath,outPath:_.join(e.tempDir,`${t}.xml`),query:{schema:t},failureMessage:`Failed to export iOS device ${t} data`,failureDetails:{appBundleId:e.appBundleId,deviceId:e.device.id}})}async function Be(t){let n=l(t),r=x(n,`activity-monitor-process-live`);if(r.length===0)throw new e(`COMMAND_FAILED`,`Failed to parse xctrace activity-monitor-process-live schema`);let i=r.indexOf(`pid`),a=r.indexOf(`process`),o=r.indexOf(`memory-real`);if(i<0||a<0||o<0)throw new e(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=b(n,e=>e.name===`row`),c=[],u=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;w(t,u);let n=C(t[i],u),r=T(t[a],u)?.name;n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:C(t[o],u)})}return c}async function Ve(t,n){let{resolveIosDevicePerfTarget:r}=await import(`./perf-target.js`),i=await r(t,n),a=await He(t,n),o=Ue(await Be(a.xml),i,n,t);if(o.residentMemoryBytes===null)throw new e(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return $({residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,memoryMethod:G})}async function He(e,t){let n=await p(`agent-device-ios-perf-`),r=_.join(n,`sample.trace`);try{return{capturedAtMs:(await M({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,timeLimit:`1s`,target:`all-processes`,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`})).capturedAtMs,xml:await X({device:e,appBundleId:t,tracePath:r,tempDir:n},`activity-monitor-process-live`)}}finally{await f(n).catch(()=>{})}}function Ue(t,n,r,i){let o=new Set(n.map(e=>e.pid)),s=new Set(n.map(e=>_.basename(v(e.executable)))),c=t.filter(e=>o.has(e.pid)||s.has(e.processName));if(c.length===0)throw new e(`COMMAND_FAILED`,`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:i.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});let l=new Map;for(let e of c){let t=l.get(e.pid);if(!t){l.set(e.pid,e);continue}l.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,residentMemoryBytes:qe(t.residentMemoryBytes,e.residentMemoryBytes)})}let u=[...l.values()],d=u.map(e=>e.residentMemoryBytes).filter(e=>e!==null);return{residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:a(u.map(e=>e.processName))}}function Z(e){let[t=``]=e.trim().split(/\s+/,1);return t}async function We(t,n,r){let{readAppleProcessSamples:i}=await import(`./perf-target.js`),a=(await i(t,r)).sort((e,t)=>t.rssKb-e.rssKb)[0];if(a)return a;throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{kind:`memgraph`,appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf memory snapshot.`})}async function Ge(e,t,n){try{let{resolveAppleExecutable:n}=await import(`./perf-target.js`);return{available:!0,process:await We(e,t,await n(e,t))}}catch(t){if(Ke(e,t))return{available:!1,kind:`memgraph`,reason:`iOS simulator memgraph capture needs process tools inside simctl spawn, but this simulator runtime did not provide ps.`,hint:`Use perf memory sample when available, or retry memgraph on a simulator runtime that includes process tools such as ps and leaks.`,support:{...n,memgraph:!1}};throw t}}function Ke(t,n){if(!r(t)||t.kind!==`simulator`||!(n instanceof e))return!1;let i=n.details??{},a=Array.isArray(i.args)?i.args.join(` `):``,o=typeof i.stderr==`string`?i.stderr:``,s=`${n.message}\n${o}`.toLowerCase();return a.includes(`simctl spawn`)&&a.includes(` ps `)&&s.includes(`no such file`)}function Q(e,t,r){let i=`${t}\n${r}`.toLowerCase();return i.includes(`timed out`)||i.includes(`timeout`)?`Apple memgraph capture can take longer than metric sampling. Keep the app running and retry; if it times out again, collect a smaller reproduction before capturing leaks --outputGraph.`:i.includes(`not found`)||i.includes(`no such file`)?`Install Xcode command line tools and ensure leaks is available, then retry.`:i.includes(`permission`)||i.includes(`denied`)||i.includes(`not authorized`)?n(e)?`Grant the agent terminal process permission to inspect this macOS app, then retry.`:`Keep the simulator booted and app running; if inspection is denied, retry with a debug simulator build.`:`Keep the app process running and retry perf memory snapshot with --debug if the failure persists.`}function $(e){return{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}function qe(e,t){return e===null?t:t===null?e:Math.max(e,t)}export{Le as buildAppleFrameSamplingMetadata,Re as buildAppleMemorySamplingMetadata,Y as buildAppleMemorySnapshotSupport,Me as captureAppleMemorySnapshot,he as cleanupAppleXctracePerfCapture,I as isRetryableIosDeviceTraceRecordFailure,B as resolveIosDevicePerfHint,Ie as sampleAppleFramePerf,je as sampleAppleMemoryPerf,pe as startAppleXctracePerfCapture,me as stopAppleXctracePerfCapture,ge as writeAppleXctracePerfReport};
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{E as t,f as n,g as r,h as i}from"./sdk-device.js";import{lr as a}from"./sdk-batch.js";import{o,r as s,u as c}from"./exec.js";import"./command.js";import{t as l}from"./parser.js";import{n as u,t as d}from"./numeric.js";import{C as f,D as ee,g as te,i as ne,m as p,o as m,u as h,w as re,y as ie}from"./host-file.js";import{a as ae,o as g}from"./tool-provider.js";import{o as oe,t as se}from"./devicectl.js";import{n as ce}from"./simctl.js";import _ from"node:path";import{fileURLToPath as v}from"node:url";function y(e,t){for(let n of e){if(t(n))return n;let e=y(n.children,t);if(e)return e}}function b(e,t){let n=[];for(let r of e)t(r)&&n.push(r),n.push(...b(r.children,t));return n}function le(e,t){return e.children.find(e=>e.name===t)?.text??null}function x(e,t){let n=y(e,e=>e.name===`schema`&&e.attributes.name===t);return n?n.children.filter(e=>e.name===`col`).map(e=>le(e,`mnemonic`)??``):[]}function S(e){if(!e||e.children.some(e=>e.name===`sentinel`)||!e.text)return null;let t=Number(e.text);return Number.isFinite(t)?t:null}function C(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.numberValue??null:S(e):null}function w(e,t){for(let n of e)w(n.children,t),n.attributes.id&&t.set(n.attributes.id,{numberValue:S(n),process:E(n)})}function T(e,t){return e?e.attributes.ref?t.get(e.attributes.ref)?.process??null:E(e):null}function E(e){if(!e||e.children.some(e=>e.name===`sentinel`))return null;let t=S(y(e.children,e=>e.name===`pid`)),n=(e.attributes.fmt??``).trim().replace(/\s+\(\d+\)$/,``).trim();return t===null&&n.length===0?null:{pid:t??void 0,name:n.length>0?n:void 0}}function ue(e){return new Map(b(e,e=>!!e.attributes.id).flatMap(e=>{let t=e.attributes.id;return t?[[t,e]]:[]}))}function D(e,t){if(e)return e.attributes.ref?t.get(e.attributes.ref):e}const O=new Set([`backtrace`,`tagged-backtrace`]);function k(e,t=10){let n=l(e),r=ue(n),i=new Map,a=0,o=0;for(let e of b(n,e=>e.name===`row`)){let t=A(e,r),n=de(e,r);if(t===void 0||!n)continue;let s=n.attributes.name?.trim()||`<unknown>`,c=fe(n,r),l=`${c??``}\u0000${s}`,u=i.get(l);i.set(l,{symbol:s,binary:c,weightNs:(u?.weightNs??0)+t}),a+=1,o+=t}let s=Math.max(0,Math.floor(t)),c=[...i.values()].sort((e,t)=>t.weightNs-e.weightNs||e.symbol.localeCompare(t.symbol)).slice(0,s).map(({symbol:e,binary:t,weightNs:n})=>({symbol:e,binary:t,selfSampleMs:j(n),selfSamplePercent:o>0?u(n/o*100):0}));return{sampleCount:a,totalSampleWeightMs:j(o),topFunctions:c}}function A(e,t){let n=D(e.children.find(e=>e.name===`weight`),t);if(!n?.text)return;let r=Number(n.text);return Number.isFinite(r)&&r>0?r:void 0}function de(e,t){return D(D(e.children.find(e=>O.has(e.name)),t)?.children.find(e=>e.name===`frame`),t)}function fe(e,t){return D(e.children.find(e=>e.name===`binary`),t)?.attributes.name?.trim()||void 0}function j(e){return Math.round(e/1e6*1e3)/1e3}async function pe(e){let n=await _e(e.device,e.appBundleId);await m(_.dirname(e.outPath));let r=P({device:e.device,template:e.template,target:n.pids,outPath:e.outPath}),i=new Date().toISOString(),a=await F(r,e.outPath,{device:e.device,appBundleId:e.appBundleId,failureMessage:`Failed to start Apple xctrace ${e.mode} capture for ${e.appBundleId}`},async()=>{let e=c(`xcrun`,r,{allowFailure:!0}),t=await ye(e.wait);return t?{failure:t}:{recorded:e}});return{kind:`xctrace`,mode:e.mode,template:e.template,outPath:e.outPath,appBundleId:e.appBundleId,deviceId:e.device.id,platform:t(e.device),targetPids:n.pids,targetProcesses:n.processNames,startedAt:i,child:a.child,wait:a.wait}}async function me(e,t=e.outPath){t!==e.outPath&&await m(_.dirname(t));let n=o(await L(e,{failOnForcedKill:!0}),`Failed to stop Apple xctrace ${e.mode} capture`,t=>({tracePath:e.outPath,captureCleanedUp:!0,hint:B(t.stdout,t.stderr)}));return t!==e.outPath&&await re(e.outPath,t).catch(async()=>{await ne(e.outPath,t),await f(e.outPath)}),await z(t,{message:`xctrace produced no trace data`,hint:`Keep the Apple device unlocked and connected, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.deviceId,stdout:n.stdout,stderr:n.stderr}),{kind:`xctrace`,mode:e.mode,template:e.template,outPath:t,appBundleId:e.appBundleId,deviceId:e.deviceId,platform:e.platform,targetPids:e.targetPids,targetProcesses:e.targetProcesses,startedAt:e.startedAt,endedAt:new Date().toISOString()}}async function he(e){return await L(e,{failOnForcedKill:!1})}async function ge(t){let n=await p(`agent-device-xctrace-report-`),r=_.join(n,`trace-toc.xml`),i=_.join(n,`time-profile.xml`);try{let n=await N({tracePath:t.tracePath,outPath:r,query:`toc`,failureMessage:`Failed to export Apple xctrace report metadata`,failureDetails:{tracePath:t.tracePath}}),a=await N({tracePath:t.tracePath,outPath:i,query:{schema:`time-profile`},failureMessage:`Failed to export Apple xctrace Time Profiler samples`,failureDetails:{tracePath:t.tracePath}}),o=be({...t,tocXml:n,timeProfileXml:a});if(o.summary.sampleCount===0)throw new e(`COMMAND_FAILED`,`Apple xctrace CPU report contained no samples`,{tracePath:t.tracePath,tableSchemas:o.summary.tableSchemas,hint:`Keep the app active while recording, then retry. Open the raw trace in Instruments if it still contains no Time Profiler samples.`});return await m(_.dirname(t.outPath)),await ee(t.outPath,`${JSON.stringify(o,null,2)}\n`),o}finally{await f(n).catch(()=>{})}}async function M(e){let t=P({device:e.device,template:e.template,target:e.target,timeLimit:e.timeLimit,outPath:e.tracePath}),{result:n,...r}=await F(t,e.tracePath,e,async()=>{let e=new Date().toISOString(),n=await g(t,{allowFailure:!0,timeoutMs:6e4});return n.exitCode===0?{recorded:{result:n,startedAt:e,endedAt:new Date().toISOString(),capturedAtMs:Date.now()}}:{failure:n}});return e.requireTraceData&&await z(e.tracePath,{message:`${e.failureMessage}: xctrace produced no trace data`,hint:`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`,appBundleId:e.appBundleId,deviceId:e.device.id,stdout:n.stdout,stderr:n.stderr}),r}async function N(e){let t=[`xctrace`,`export`,`--input`,e.tracePath,...e.query===`toc`?[`--toc`]:[`--xpath`,`/trace-toc/run/data/table[@schema="${e.query.schema}"]`],`--output`,e.outPath];return o(await g(t,{allowFailure:!0,timeoutMs:15e3}),e.failureMessage,n=>({cmd:`xcrun`,args:t,...e.failureDetails,hint:B(n.stdout,n.stderr)})),await ie(e.outPath)}async function _e(t,r){if(!n(t.platform))throw new e(`UNSUPPORTED_OPERATION`,`Apple xctrace perf is not supported on Android.`,{platform:t.platform,hint:`Android native profiling belongs to the Android perf rollout and is not implemented under Apple xctrace.`});let{readAppleProcessSamples:o,resolveAppleExecutable:s,resolveIosDevicePerfTarget:c}=await import(`./perf-target.js`);if(i(t)&&t.kind===`device`){let e=await c(t,r);return{pids:e.map(e=>e.pid),processNames:a(e.map(e=>_.basename(v(e.executable))))}}let l=await s(t,r),u=await o(t,l);if(u.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${r}`,{appBundleId:r,deviceId:t.id,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});return{pids:u.map(e=>e.pid),processNames:[l.executableName]}}function P(e){return[`xctrace`,`record`,`--template`,e.template,...i(e.device)?[`--device`,e.device.id]:[],...e.target===`all-processes`?[`--all-processes`]:e.target.flatMap(e=>[`--attach`,String(e)]),...e.timeLimit?[`--time-limit`,e.timeLimit]:[],`--output`,e.outPath,`--quiet`,`--no-prompt`]}async function F(t,n,r,i){for(let a=1;;a+=1){await ve(n,a);let o=await i();if(`recorded`in o)return o.recorded;if(a<3&&I(o.failure))continue;let{failure:c}=o;throw new e(`COMMAND_FAILED`,r.failureMessage,s(c,{cmd:`xcrun`,args:t,appBundleId:r.appBundleId,deviceId:r.device.id,hint:B(c.stdout,c.stderr)}))}}function I(e){let t=`${e.stdout}\n${e.stderr}`.toLowerCase();return t.includes(`_lockkperf`)||t.includes(`could not lock kperf`)||t.includes(`likely another session just started`)}async function ve(e,t){t<=1||(await f(e).catch(()=>{}),await new Promise(e=>setTimeout(e,1500)))}async function ye(e){return await Promise.race([e,new Promise(e=>setTimeout(e,500))])}async function L(t,n){t.child.kill(`SIGINT`);let r=await R(t.wait,45e3);if(r)return r;t.child.kill(`SIGKILL`);let i=await R(t.wait,5e3);if(i&&!n.failOnForcedKill)return i;throw i?new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop`,{exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr,tracePath:t.outPath,captureCleanedUp:!0,forcedKill:!0,hint:`xctrace did not finish after SIGINT, so it was force-killed. Retry the perf command after confirming no other xctrace session is active.`}):new e(`COMMAND_FAILED`,`Timed out waiting for Apple xctrace capture to stop after SIGKILL`,{tracePath:t.outPath,captureCleanedUp:!1,forcedKill:!0,hint:`xctrace did not exit after SIGKILL. Inspect running xctrace processes before retrying.`})}async function R(e,t){return await Promise.race([e,new Promise(e=>setTimeout(e,t))])}async function z(t,n){let r=await h(t).catch(()=>null);if(!(r?.isDirectory()===!0?(await te(t).catch(()=>[])).length>0:(r?.size??0)>0))throw new e(`COMMAND_FAILED`,n.message,{tracePath:t,appBundleId:n.appBundleId,deviceId:n.deviceId,stdout:n.stdout,stderr:n.stderr,hint:n.hint})}function be(e){let t=l(e.tocXml),n=b(t,e=>e.name===`run`),r=a(b(t,e=>e.name===`table`).map(e=>e.attributes.schema).filter(e=>typeof e==`string`&&e.length>0)).sort(),i=k(e.timeProfileXml);return{kind:`xctrace`,mode:`cpu-profile`,template:e.template,tracePath:e.tracePath,reportPath:e.outPath,appBundleId:e.appBundleId,generatedAt:new Date().toISOString(),summary:{runCount:n.length,tableSchemas:r,...i}}}function B(e,t){let n=oe(e,t);if(n)return n;let r=`${e}\n${t}`.toLowerCase();return r.includes(`no device matched`)||r.includes(`failed to find device`)?se:r.includes(`timed out`)?`Keep the iOS device unlocked and connected by cable, keep the app active, then retry perf.`:`Ensure the iOS device is unlocked, trusted, visible to xctrace, and the target app stays active while perf samples it.`}const V=`xctrace-animation-hitches`;function xe(e){let t=Se(e.frameLifetimesXml),n=Ce(e.displayInfoXml),r=we(e.hitchesXml).filter(t=>De(t,e.processIds,e.processNames)),i=r.length,o=Math.max(0,Math.round(Date.parse(e.windowEndedAt)-Date.parse(e.windowStartedAt))),s=H(r,Date.parse(e.windowStartedAt));return{droppedFramePercent:t>0?u(i/t*100):0,droppedFrameCount:i,totalFrameCount:t,sampleWindowMs:o,windowStartedAt:e.windowStartedAt,windowEndedAt:e.windowEndedAt,measuredAt:e.measuredAt,method:V,matchedProcesses:a(r.map(e=>e.processName).filter(e=>typeof e==`string`&&e.length>0)),frameDeadlineMs:n===void 0?void 0:d(1e3/n),refreshRateHz:n,worstWindows:s.length>0?s:void 0}}function Se(e){return ke(e,`hitches-frame-lifetimes`).length}function Ce(e){if(!e)return;let{rows:t,schema:n}=U(e,`device-display-info`),r=n.indexOf(`max-refresh-rate`);if(r<0)return;let i=new Map;for(let e of t){w(e.children,i);let t=C(e.children[r],i);if(t!==null&&t>0)return t}}function we(e){let t=l(e),n=Te(t);if(!n)return[];let r=new Map;return b(t,e=>e.name===`row`).map(e=>Ee(e,n,r)).filter(e=>!!e)}function Te(e){let t=x(e,`hitches`),n={start:t.indexOf(`start`),duration:t.indexOf(`duration`),process:t.indexOf(`process`),isSystem:t.indexOf(`is-system`)};return Object.values(n).every(e=>e>=0)?n:null}function Ee(e,t,n){if(w(e.children,n),Ae(e.children[t.isSystem],n)===!0)return null;let r=C(e.children[t.start],n),i=C(e.children[t.duration],n);if(r===null||i===null)return null;let a=T(e.children[t.process],n);return{startNs:r,durationNs:i,pid:a?.pid,processName:a?.name}}function De(e,t,n){return e.pid!==void 0&&t.includes(e.pid)?!0:e.processName?n.includes(e.processName):!1}function H(e,t){if(e.length===0)return[];let n=[...e].sort((e,t)=>e.startNs-t.startNs),r=[],i=[];for(let e of n){let t=i.at(-1);if(!t||e.startNs-(t.startNs+t.durationNs)<=5e8){i.push(e);continue}r.push(i),i=[e]}return i.length>0&&r.push(i),r.map(e=>Oe(e,t)).sort((e,t)=>t.missedDeadlineFrameCount-e.missedDeadlineFrameCount||t.worstFrameMs-e.worstFrameMs).slice(0,3).sort((e,t)=>e.startOffsetMs-t.startOffsetMs)}function Oe(e,t){let n=Math.min(...e.map(e=>e.startNs)),r=Math.max(...e.map(e=>e.startNs+e.durationNs)),i=Math.max(0,Math.round(n/1e6)),a=Math.max(i,Math.round(r/1e6));return{startOffsetMs:i,endOffsetMs:a,startAt:new Date(t+i).toISOString(),endAt:new Date(t+a).toISOString(),missedDeadlineFrameCount:e.length,worstFrameMs:d(Math.max(...e.map(e=>e.durationNs))/1e6)}}function ke(e,t){return U(e,t).rows}function U(e,t){let n=l(e),r=x(n,t);return{rows:r.length===0?[]:b(n,e=>e.name===`row`),schema:r}}function Ae(e,t){let n=C(e,t);return n===null?null:n!==0}const W=`ps-process-snapshot`,G=`xctrace-activity-monitor`,K=`leaks-output-graph`,q=12e4;async function je(t,n){if(i(t)&&t.kind===`device`)return await Ve(t,n);let{readAppleProcessSamples:r,resolveAppleExecutable:a}=await import(`./perf-target.js`),o=await a(t,n),s=await r(t,o);if(s.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf.`});let c=new Date().toISOString();return $({residentMemoryKb:s.reduce((e,t)=>e+t.rssKb,0),measuredAt:c,matchedProcesses:[o.executableName],memoryMethod:W})}async function Me(t,n,r){let i=Y(t);if(!i.memgraph)return{available:!1,kind:`memgraph`,reason:i.reason,hint:i.hint,support:i};let a=await Ge(t,n,i);if(a.available===!1)return a;let{process:o}=a;await m(_.dirname(r));let c=await Fe(r),l;try{l=await Ne(t,r,o.pid)}catch(e){throw await J(r,c),Pe(t,n,o,r,e)}if(l.exitCode!==0)throw await J(r,c),new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,s(l,{kind:`memgraph`,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),path:r,hint:Q(t,l.stdout,l.stderr)}));let u=await h(r).catch(()=>null);if(!u?.isFile()||u.size<=0)throw await J(r,c),new e(`COMMAND_FAILED`,`Apple memgraph artifact is missing or empty`,{kind:`memgraph`,appBundleId:n,pid:o.pid,path:r,hint:`Retry with a writable --out path. If the file is still empty, run with --debug and inspect leaks output.`});return{available:!0,kind:`memgraph`,path:r,sizeBytes:u.size,measuredAt:new Date().toISOString(),method:K,appBundleId:n,pid:o.pid,processName:_.basename(Z(o.command)),support:i}}async function Ne(e,t,n){return r(e)?await ae(`leaks`,[`--outputGraph=${t}`,String(n)],{allowFailure:!0,timeoutMs:q}):await g(ce(e,[`spawn`,e.id,`leaks`,`--outputGraph=${t}`,String(n)]),{allowFailure:!0,timeoutMs:q})}function Pe(t,n,r,i,a){if(a instanceof e){let o=a.details??{};return new e(a.code,`Failed to capture Apple memgraph for ${n}`,{...o,kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:Q(t,typeof o.stdout==`string`?o.stdout:``,typeof o.stderr==`string`&&o.stderr.length>0?o.stderr:a.message)},a)}return new e(`COMMAND_FAILED`,`Failed to capture Apple memgraph for ${n}`,{kind:`memgraph`,appBundleId:n,pid:r.pid,processName:_.basename(Z(r.command)),path:i,hint:`Retry perf memory snapshot. If it still fails, run with --debug and inspect leaks output.`},a)}async function Fe(e){return await h(e).then(e=>e.isFile()).catch(()=>!1)}async function J(e,t){t||await f(e).catch(()=>{})}async function Ie(n,r){if(!i(n)||n.kind!==`device`)throw new e(`COMMAND_FAILED`,`Apple frame-health sampling is currently available only on connected iOS devices.`,{metric:`fps`,platform:t(n),deviceKind:n.kind});let{resolveIosDevicePerfTarget:o}=await import(`./perf-target.js`),s=await o(n,r),c=await ze(n,r,s);return xe({hitchesXml:c.hitchesXml,frameLifetimesXml:c.frameLifetimesXml,displayInfoXml:c.displayInfoXml,processIds:s.map(e=>e.pid),processNames:a(s.map(e=>_.basename(v(e.executable)))),windowStartedAt:c.windowStartedAt,windowEndedAt:c.windowEndedAt,measuredAt:c.windowEndedAt})}function Le(e){return i(e)&&e.kind===`device`?{method:V,description:`Rendered-frame hitch health from xctrace Animation Hitches on connected iOS devices. Dropped frames are counted from native hitch rows for the attached app process, with total frames from the same trace frame-lifetime table.`,unit:`percent`,primaryField:`droppedFramePercent`,window:`short 2s xctrace Animation Hitches record of the active app process`,resetsAfterRead:!1}:{method:V,description:`Unavailable on iOS simulators and macOS because local Apple tooling does not expose reliable app frame hitches for these targets.`,unit:`percent`,primaryField:`droppedFramePercent`}}function Re(e){if(i(e)&&e.kind===`device`)return{method:G,description:`Resident memory snapshot from a short xctrace Activity Monitor sample on the connected iOS device.`,unit:`kB`};let t=r(e)?`host ps for the running macOS app executable resolved from the bundle ID.`:`xcrun simctl spawn ps, with host ps fallback, for the running iOS simulator app executable resolved from the bundle ID.`;return{method:W,description:`Resident memory snapshot from ${t}`,unit:`kB`}}function Y(e){return i(e)&&e.kind===`device`?{platform:t(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Physical iOS device memgraph capture is not exposed through reliable local agent-device tooling.`,hint:`Use perf memory sample for a compact resident-memory reading, or reproduce on an iOS simulator/macOS target for memgraph capture.`}:i(e)&&e.kind===`simulator`?{platform:t(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`iOS simulator processes are host-visible through simctl spawn leaks.`,hint:`Keep the simulator app running in the foreground while the memgraph is captured.`}:r(e)?{platform:t(e),deviceKind:e.kind,memgraph:!0,method:K,reason:`macOS app processes are host-visible to leaks --outputGraph.`,hint:`Grant Terminal/agent process permissions if macOS denies process inspection.`}:{platform:t(e),deviceKind:e.kind,memgraph:!1,method:K,reason:`Apple memgraph capture is available only for iOS simulator and macOS app sessions.`,hint:`Use perf memory sample on supported app sessions, or rerun against iOS simulator/macOS for memgraph capture.`}}async function ze(e,t,n){let r=await p(`agent-device-ios-frame-perf-`),i=_.join(r,`animation-hitches.trace`);try{let a=await M({device:e,appBundleId:t,tracePath:i,template:`Animation Hitches`,timeLimit:`2s`,target:n.map(e=>e.pid),requireTraceData:!0,failureMessage:`Failed to record iOS frame-health sample for ${t}`}),o={device:e,appBundleId:t,tracePath:i,tempDir:r};return{windowStartedAt:a.startedAt,windowEndedAt:a.endedAt,hitchesXml:await X(o,`hitches`),frameLifetimesXml:await X(o,`hitches-frame-lifetimes`),displayInfoXml:await X(o,`device-display-info`).catch(()=>void 0)}}finally{await f(r).catch(()=>{})}}async function X(e,t){return await N({tracePath:e.tracePath,outPath:_.join(e.tempDir,`${t}.xml`),query:{schema:t},failureMessage:`Failed to export iOS device ${t} data`,failureDetails:{appBundleId:e.appBundleId,deviceId:e.device.id}})}async function Be(t){let n=l(t),r=x(n,`activity-monitor-process-live`);if(r.length===0)throw new e(`COMMAND_FAILED`,`Failed to parse xctrace activity-monitor-process-live schema`);let i=r.indexOf(`pid`),a=r.indexOf(`process`),o=r.indexOf(`memory-real`);if(i<0||a<0||o<0)throw new e(`COMMAND_FAILED`,`xctrace activity-monitor-process-live export is missing expected columns`);let s=b(n,e=>e.name===`row`),c=[],u=new Map;for(let e of s){let t=e.children;if(t.length===0)continue;w(t,u);let n=C(t[i],u),r=T(t[a],u)?.name;n===null||!Number.isFinite(n)||!r||c.push({pid:n,processName:r,residentMemoryBytes:C(t[o],u)})}return c}async function Ve(t,n){let{resolveIosDevicePerfTarget:r}=await import(`./perf-target.js`),i=await r(t,n),a=await He(t,n),o=Ue(await Be(a.xml),i,n,t);if(o.residentMemoryBytes===null)throw new e(`COMMAND_FAILED`,`Incomplete Activity Monitor sample for ${n}`,{appBundleId:n,deviceId:t.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});return $({residentMemoryKb:o.residentMemoryBytes/1024,measuredAt:new Date(a.capturedAtMs).toISOString(),matchedProcesses:o.matchedProcesses,memoryMethod:G})}async function He(e,t){let n=await p(`agent-device-ios-perf-`),r=_.join(n,`sample.trace`);try{return{capturedAtMs:(await M({device:e,appBundleId:t,tracePath:r,template:`Activity Monitor`,timeLimit:`1s`,target:`all-processes`,failureMessage:`Failed to record iOS device Activity Monitor sample for ${t}`})).capturedAtMs,xml:await X({device:e,appBundleId:t,tracePath:r,tempDir:n},`activity-monitor-process-live`)}}finally{await f(n).catch(()=>{})}}function Ue(t,n,r,i){let o=new Set(n.map(e=>e.pid)),s=new Set(n.map(e=>_.basename(v(e.executable)))),c=t.filter(e=>o.has(e.pid)||s.has(e.processName));if(c.length===0)throw new e(`COMMAND_FAILED`,`No Activity Monitor sample found for ${r}`,{appBundleId:r,deviceId:i.id,hint:`Keep the app running in the foreground while perf samples the device, then retry.`});let l=new Map;for(let e of c){let t=l.get(e.pid);if(!t){l.set(e.pid,e);continue}l.set(e.pid,{pid:e.pid,processName:e.processName||t.processName,residentMemoryBytes:qe(t.residentMemoryBytes,e.residentMemoryBytes)})}let u=[...l.values()],d=u.map(e=>e.residentMemoryBytes).filter(e=>e!==null);return{residentMemoryBytes:d.length>0?d.reduce((e,t)=>e+t,0):null,matchedProcesses:a(u.map(e=>e.processName))}}function Z(e){let[t=``]=e.trim().split(/\s+/,1);return t}async function We(t,n,r){let{readAppleProcessSamples:i}=await import(`./perf-target.js`),a=(await i(t,r)).sort((e,t)=>t.rssKb-e.rssKb)[0];if(a)return a;throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{kind:`memgraph`,appBundleId:n,hint:`Run open <app> for this session again to ensure the Apple app is active, then retry perf memory snapshot.`})}async function Ge(e,t,n){try{let{resolveAppleExecutable:n}=await import(`./perf-target.js`);return{available:!0,process:await We(e,t,await n(e,t))}}catch(t){if(Ke(e,t))return{available:!1,kind:`memgraph`,reason:`iOS simulator memgraph capture needs process tools inside simctl spawn, but this simulator runtime did not provide ps.`,hint:`Use perf memory sample when available, or retry memgraph on a simulator runtime that includes process tools such as ps and leaks.`,support:{...n,memgraph:!1}};throw t}}function Ke(t,n){if(!i(t)||t.kind!==`simulator`||!(n instanceof e))return!1;let r=n.details??{},a=Array.isArray(r.args)?r.args.join(` `):``,o=typeof r.stderr==`string`?r.stderr:``,s=`${n.message}\n${o}`.toLowerCase();return a.includes(`simctl spawn`)&&a.includes(` ps `)&&s.includes(`no such file`)}function Q(e,t,n){let i=`${t}\n${n}`.toLowerCase();return i.includes(`timed out`)||i.includes(`timeout`)?`Apple memgraph capture can take longer than metric sampling. Keep the app running and retry; if it times out again, collect a smaller reproduction before capturing leaks --outputGraph.`:i.includes(`not found`)||i.includes(`no such file`)?`Install Xcode command line tools and ensure leaks is available, then retry.`:i.includes(`permission`)||i.includes(`denied`)||i.includes(`not authorized`)?r(e)?`Grant the agent terminal process permission to inspect this macOS app, then retry.`:`Keep the simulator booted and app running; if inspection is denied, retry with a debug simulator build.`:`Keep the app process running and retry perf memory snapshot with --debug if the failure persists.`}function $(e){return{residentMemoryKb:Math.round(e.residentMemoryKb),measuredAt:e.measuredAt,method:e.memoryMethod,matchedProcesses:e.matchedProcesses}}function qe(e,t){return e===null?t:t===null?e:Math.max(e,t)}export{Le as buildAppleFrameSamplingMetadata,Re as buildAppleMemorySamplingMetadata,Y as buildAppleMemorySnapshotSupport,Me as captureAppleMemorySnapshot,he as cleanupAppleXctracePerfCapture,I as isRetryableIosDeviceTraceRecordFailure,B as resolveIosDevicePerfHint,Ie as sampleAppleFramePerf,je as sampleAppleMemoryPerf,pe as startAppleXctracePerfCapture,me as stopAppleXctracePerfCapture,ge as writeAppleXctracePerfReport};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import"./diagnostics2.js";import{O as n,d as r,j as i}from"./sdk-device.js";import{At as a,Mt as o,Nt as s,Ot as c,kt as l}from"./sdk-batch.js";import{m as u}from"./observability.js";import{A as d,a as f,o as p}from"./owner-identity.js";import{a as ee,t as m}from"./file.js";import"./process.js";import{c as h,i as g,l as _,r as v,s as y,t as b,u as x}from"./device-claim-inspection.js";import{n as S,t as C}from"./durable-capture-resource.js";import w from"node:crypto";import T from"node:fs";import E from"node:path";async function D(e){let t=await e.observeDeviceBoot?.observeBootTimeMs(e.device);if(t?.observed!==!0||t.bootedAtMs<=e.claim.updatedAtMs)return;let{session:n,workspace:r,stateDir:i}=e.claim;return{session:n,workspace:r,stateDir:i,bootedAtMs:t.bootedAtMs}}function O(e){t({level:`info`,phase:`device_claim_reboot_released`,data:{deviceKey:e.deviceKey,ownerSession:e.claim.session,ownerStateDir:e.claim.stateDir,ownerWorkspace:e.claim.workspace,claimUpdatedAtMs:e.claim.updatedAtMs,deviceBootedAtMs:e.bootedAtMs}})}function k(e){let t=_(e.deviceKey);T.mkdirSync(E.dirname(t),{recursive:!0,mode:448}),d({destination:t,contents:`${JSON.stringify(e)}\n`,mode:384})}async function A(e,t){let n=p();return await ee({acquire:()=>m({lockDirPath:`${_(e)}.lock`,owner:{pid:n.pid,startTime:n.startTime,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`device claim for ${e}`}),task:t})}async function te(e){let t=v(_(e.deviceKey));return t?t.claim&&P(t.claim,e.stateDir,e.owner)?(R(e.deviceKey,t.claim),{status:`available`}):t.claim&&F(t.claim,e,e.owner)?{status:`held`,ownership:ne(t.claim)}:await re(t,e):{status:`available`}}function ne(e){if(e.updatedAtMs>=Date.now())return y(e);let t={...e,updatedAtMs:Date.now()};return k(t),y(t)}async function re(e,t){let n=e.claim;if(!n)return I(t.deviceKey,e),{status:`conflict`,conflict:e};let r=await ie({classification:e.classification,claim:n,device:t.device,observeDeviceBoot:t.observeDeviceBoot});if(!r.settles)return I(t.deviceKey,e),{status:`conflict`,conflict:e};let i=await j(n,t.reconcileOrphanedDeviceClaim);return i.status===`retained`?(I(t.deviceKey,e,i.reason),{status:`conflict`,conflict:e}):r.tookOver?(O({deviceKey:t.deviceKey,claim:n,bootedAtMs:r.tookOver.bootedAtMs}),{status:`available`,tookOver:r.tookOver}):{status:`available`}}async function ie(e){if(b(e.classification))return{settles:!0};let t=await D(e);return t?{settles:!0,tookOver:t}:{settles:!1}}async function j(e,t){let n=await t(e);if(n.status===`retained`)return n;try{T.unlinkSync(_(e.deviceKey))}catch(e){if(e.code!==`ENOENT`)throw e}return{status:`reconciled`}}function M(e,t,n){return e.stateDir===t&&f({pid:e.ownerPid,startTime:e.ownerStartTime},n)}function N(e){return e.abandonedAtMs!==void 0}function P(e,t,n){return N(e)&&M(e,t,n)}function F(e,t,n){return e.session===t.session&&e.workspace===t.workspace&&M(e,t.stateDir,n)}function I(e,n,r){t({level:`warn`,phase:`device_claim_conflict`,data:{deviceKey:e,classification:n.classification,...L(n),...r?{reconciliationReason:r}:{}}})}function L(e){return e.allocatorClaim?{ownerStateDir:e.allocatorClaim.stateDir,allocatorInstanceId:e.allocatorClaim.allocator.instanceId,identityIncarnationId:e.allocatorClaim.allocator.identityIncarnationId}:{ownerSession:e.claim?.session,ownerStateDir:e.claim?.stateDir}}function R(e,n){t({level:`info`,phase:`device_claim_abandoned_superseded`,data:{deviceKey:e,abandonedSession:n.session,abandonedAtMs:n.abandonedAtMs}})}function z(e){return`transient:${e}`}async function B(e){let t=W(e.device),n=h(t);return await A(n,async()=>await H({...e,deviceKey:n,identity:t}))}async function V(e){let t=W(e.device),n=h(t);return await A(n,async()=>{let r=v(_(n));return r?.claim&&!N(r.claim)&&M(r.claim,e.stateDir,p())?{status:`covered-by-owned-claim`}:await H({device:e.device,deviceKey:n,identity:t,session:z(e.command),workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim})})}async function H(e){let{deviceKey:t,identity:n}=e,r=p(),i=await te({...e,owner:r});if(i.status===`conflict`)return i;if(i.status===`held`)return{status:`acquired`,ownership:i.ownership};let a=Date.now(),o={schemaVersion:2,deviceKey:t,device:{...n,name:e.device.name},session:e.session,workspace:e.workspace,stateDir:e.stateDir,ownerPid:r.pid,ownerStartTime:r.startTime,ownerToken:w.randomUUID(),createdAtMs:a,updatedAtMs:a};return k(o),{status:`acquired`,ownership:y(o),...i.tookOver?{tookOver:i.tookOver}:{}}}function U(e){let t=h(W(e)),n=v(_(t))?.claim;return n!==void 0&&n.deviceKey===t&&!N(n)&&f({pid:n.ownerPid,startTime:n.ownerStartTime},p())}function W(e){return i({...e,...r(e.platform)?{appleOs:n(e)}:{}})}async function G(e){let t=[];for(let n of g(e.selectors))t.push(await K(n,e.reconcile));return t}async function K(e,n){let r=e.claim,i={fileName:e.fileName,classification:e.classification,...e.deviceKey?{deviceKey:e.deviceKey}:{},...r?{device:r.device,session:r.session,workspace:r.workspace,stateDir:r.stateDir}:{},...e.allocatorClaim?{device:e.allocatorClaim.device,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}:{}};if(!r||!b(e.classification))return{...i,status:`refused`,reason:ae(e.classification)};if(_(r.deviceKey)!==E.join(x(),e.fileName))return{...i,status:`refused`,reason:`claim-file-name-mismatch`};let{deviceKey:a,ownerToken:o}=r;return await A(a,async()=>{let e=v(_(a));if(!e?.claim||e.claim.ownerToken!==o||!b(e.classification))return{...i,status:`changed`,reason:`claim-changed-during-release`};let s=await j(e.claim,n);return s.status===`retained`?{...i,status:`retained`,reason:s.reason}:(t({level:`info`,phase:`device_claim_stale_released`,data:{deviceKey:a,ownerSession:r.session,ownerStateDir:r.stateDir}}),{...i,status:`released`})})}const q=Object.freeze({live:`live-owner`,"owner-process-reused":`owner-pid-reused`,"owner-state-dir-gone":`owner-process-still-running`,unknown:`owner-liveness-unknown`,inconsistent:`claim-record-inconsistent`,"allocator-inconsistent":`allocator-claim-record-inconsistent`,"allocator-held":`allocator-held-owner`,"owner-process-dead":`claim-record-unreadable`,"owner-daemon-superseded":`claim-record-unreadable`});function ae(e){return q[e]}async function J(e){return e?await Y(e,(e,t)=>{try{T.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)throw e;return`absent`}return`deleted`},e=>e?e.claim?`ownership-changed`:`unattributable`:`absent`):`absent`}async function oe(e){return e?await Y(e,e=>{let t=Date.now();return k({...e,abandonedAtMs:t,updatedAtMs:t}),`abandoned`},e=>e?`ownership-changed`:`absent`):`absent`}async function se(e){return e?await Y(e,e=>(k({...e,updatedAtMs:Date.now()}),{status:`renewed`}),e=>({status:`lost`,conflict:e})):{status:`lost`,conflict:void 0}}async function Y(e,t,n){return await A(e.deviceKey,async()=>{let r=_(e.deviceKey),i=v(r);if(!i)return n(void 0);let a=i.claim;return!a||!ce(a,e)?n(i):t(a,r)})}function ce(e,t){return e.ownerToken===t.ownerToken&&f({pid:e.ownerPid,startTime:e.ownerStartTime},{pid:t.ownerPid,startTime:t.ownerStartTime})}async function le(e,t){let n=x(),r;try{r=T.readdirSync(n,{withFileTypes:!0})}catch{return{examined:0,reconciled:0,retained:0,changed:0}}let i=0,a=0,o=0,s=0;for(let c of r){if(!c.isFile()||!c.name.endsWith(`.json`))continue;let r=E.join(n,c.name),l=v(r);if(!l?.claim||!X(l.classification,l.claim.stateDir,t))continue;i+=1;let{deviceKey:u,ownerToken:d}=l.claim;if(_(u)!==r){o+=1;continue}await A(u,async()=>{let n=v(r);if(!n?.claim||!X(n.classification,n.claim.stateDir,t)||n.claim.ownerToken!==d){s+=1;return}if((await j(n.claim,e)).status===`retained`){o+=1;return}a+=1})}return{examined:i,reconciled:a,retained:o,changed:s}}function X(e,t,n){return b(e)?e!==`owner-daemon-superseded`||E.resolve(t)===E.resolve(n):!1}const ue=S({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),Z=C({resourceKind:`audio-probe`,displayName:`audio probe`,store:ue,completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function de(e){return Z.adoptStarted(e)}function fe(e){return Z.finishLive(e)}const pe=S({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),Q=C({resourceKind:`perf-capture`,displayName:`perf capture`,store:pe,completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function $(e){return Q.adoptStarted(e)}function me(e){return Q.finishLive(e)}function he(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:c});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:a}):Object.freeze({kind:`memory-sample`,request:e,use:l});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:o}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:o});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:s})}}function ge(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return _e(n,t);if(r===`cpu`)return ve(n,t.outPath);if(r===`trace`)return ye(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function _e(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!u(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function ve(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function ye(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}export{se as _,Q as a,fe as c,V as d,J as f,G as g,le as h,me as i,oe as l,U as m,he as n,de as o,W as p,$ as r,Z as s,ge as t,B as u};
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import"./diagnostics2.js";import{A as n,N as r,f as i}from"./sdk-device.js";import{At as a,Mt as o,Nt as s,Ot as c,kt as l}from"./sdk-batch.js";import{m as u}from"./observability.js";import{a as d,j as ee,o as f}from"./owner-identity.js";import{a as p,t as m}from"./file.js";import"./process.js";import{c as h,i as g,l as _,r as v,s as y,t as b,u as x}from"./device-claim-inspection.js";import{n as S,t as C}from"./durable-capture-resource.js";import w from"node:crypto";import T from"node:fs";import E from"node:path";async function D(e){let t=await e.observeDeviceBoot?.observeBootTimeMs(e.device);if(t?.observed!==!0||t.bootedAtMs<=e.claim.updatedAtMs)return;let{session:n,workspace:r,stateDir:i}=e.claim;return{session:n,workspace:r,stateDir:i,bootedAtMs:t.bootedAtMs}}function O(e){t({level:`info`,phase:`device_claim_reboot_released`,data:{deviceKey:e.deviceKey,ownerSession:e.claim.session,ownerStateDir:e.claim.stateDir,ownerWorkspace:e.claim.workspace,claimUpdatedAtMs:e.claim.updatedAtMs,deviceBootedAtMs:e.bootedAtMs}})}function k(e){let t=_(e.deviceKey);T.mkdirSync(E.dirname(t),{recursive:!0,mode:448}),ee({destination:t,contents:`${JSON.stringify(e)}\n`,mode:384})}async function A(e,t){let n=f();return await p({acquire:()=>m({lockDirPath:`${_(e)}.lock`,owner:{pid:n.pid,startTime:n.startTime,acquiredAtMs:Date.now()},timeoutMs:3e4,description:`device claim for ${e}`}),task:t})}async function te(e){let t=v(_(e.deviceKey));return t?t.claim&&P(t.claim,e.stateDir,e.owner)?(R(e.deviceKey,t.claim),{status:`available`}):t.claim&&F(t.claim,e,e.owner)?{status:`held`,ownership:ne(t.claim)}:await re(t,e):{status:`available`}}function ne(e){if(e.updatedAtMs>=Date.now())return y(e);let t={...e,updatedAtMs:Date.now()};return k(t),y(t)}async function re(e,t){let n=e.claim;if(!n)return I(t.deviceKey,e),{status:`conflict`,conflict:e};let r=await ie({classification:e.classification,claim:n,device:t.device,observeDeviceBoot:t.observeDeviceBoot});if(!r.settles)return I(t.deviceKey,e),{status:`conflict`,conflict:e};let i=await j(n,t.reconcileOrphanedDeviceClaim);return i.status===`retained`?(I(t.deviceKey,e,i.reason),{status:`conflict`,conflict:e}):r.tookOver?(O({deviceKey:t.deviceKey,claim:n,bootedAtMs:r.tookOver.bootedAtMs}),{status:`available`,tookOver:r.tookOver}):{status:`available`}}async function ie(e){if(b(e.classification))return{settles:!0};let t=await D(e);return t?{settles:!0,tookOver:t}:{settles:!1}}async function j(e,t){let n=await t(e);if(n.status===`retained`)return n;try{T.unlinkSync(_(e.deviceKey))}catch(e){if(e.code!==`ENOENT`)throw e}return{status:`reconciled`}}function M(e,t,n){return e.stateDir===t&&d({pid:e.ownerPid,startTime:e.ownerStartTime},n)}function N(e){return e.abandonedAtMs!==void 0}function P(e,t,n){return N(e)&&M(e,t,n)}function F(e,t,n){return e.session===t.session&&e.workspace===t.workspace&&M(e,t.stateDir,n)}function I(e,n,r){t({level:`warn`,phase:`device_claim_conflict`,data:{deviceKey:e,classification:n.classification,...L(n),...r?{reconciliationReason:r}:{}}})}function L(e){return e.allocatorClaim?{ownerStateDir:e.allocatorClaim.stateDir,allocatorInstanceId:e.allocatorClaim.allocator.instanceId,identityIncarnationId:e.allocatorClaim.allocator.identityIncarnationId}:{ownerSession:e.claim?.session,ownerStateDir:e.claim?.stateDir}}function R(e,n){t({level:`info`,phase:`device_claim_abandoned_superseded`,data:{deviceKey:e,abandonedSession:n.session,abandonedAtMs:n.abandonedAtMs}})}function z(e){return`transient:${e}`}async function B(e){let t=W(e.device),n=h(t);return await A(n,async()=>await H({...e,deviceKey:n,identity:t}))}async function V(e){let t=W(e.device),n=h(t);return await A(n,async()=>{let r=v(_(n));return r?.claim&&!N(r.claim)&&M(r.claim,e.stateDir,f())?{status:`covered-by-owned-claim`}:await H({device:e.device,deviceKey:n,identity:t,session:z(e.command),workspace:e.workspace,stateDir:e.stateDir,reconcileOrphanedDeviceClaim:e.reconcileOrphanedDeviceClaim})})}async function H(e){let{deviceKey:t,identity:n}=e,r=f(),i=await te({...e,owner:r});if(i.status===`conflict`)return i;if(i.status===`held`)return{status:`acquired`,ownership:i.ownership};let a=Date.now(),o={schemaVersion:2,deviceKey:t,device:{...n,name:e.device.name},session:e.session,workspace:e.workspace,stateDir:e.stateDir,ownerPid:r.pid,ownerStartTime:r.startTime,ownerToken:w.randomUUID(),createdAtMs:a,updatedAtMs:a};return k(o),{status:`acquired`,ownership:y(o),...i.tookOver?{tookOver:i.tookOver}:{}}}function U(e){let t=h(W(e)),n=v(_(t))?.claim;return n!==void 0&&n.deviceKey===t&&!N(n)&&d({pid:n.ownerPid,startTime:n.ownerStartTime},f())}function W(e){return r({...e,...i(e.platform)?{appleOs:n(e)}:{}})}async function G(e){let t=[];for(let n of g(e.selectors))t.push(await K(n,e.reconcile));return t}async function K(e,n){let r=e.claim,i={fileName:e.fileName,classification:e.classification,...e.deviceKey?{deviceKey:e.deviceKey}:{},...r?{device:r.device,session:r.session,workspace:r.workspace,stateDir:r.stateDir}:{},...e.allocatorClaim?{device:e.allocatorClaim.device,stateDir:e.allocatorClaim.stateDir,allocator:e.allocatorClaim.allocator}:{}};if(!r||!b(e.classification))return{...i,status:`refused`,reason:q(e.classification)};if(_(r.deviceKey)!==E.join(x(),e.fileName))return{...i,status:`refused`,reason:`claim-file-name-mismatch`};let{deviceKey:a,ownerToken:o}=r;return await A(a,async()=>{let e=v(_(a));if(!e?.claim||e.claim.ownerToken!==o||!b(e.classification))return{...i,status:`changed`,reason:`claim-changed-during-release`};let s=await j(e.claim,n);return s.status===`retained`?{...i,status:`retained`,reason:s.reason}:(t({level:`info`,phase:`device_claim_stale_released`,data:{deviceKey:a,ownerSession:r.session,ownerStateDir:r.stateDir}}),{...i,status:`released`})})}const ae=Object.freeze({live:`live-owner`,"owner-process-reused":`owner-pid-reused`,"owner-state-dir-gone":`owner-process-still-running`,unknown:`owner-liveness-unknown`,inconsistent:`claim-record-inconsistent`,"allocator-inconsistent":`allocator-claim-record-inconsistent`,"allocator-held":`allocator-held-owner`,"owner-process-dead":`claim-record-unreadable`,"owner-daemon-superseded":`claim-record-unreadable`});function q(e){return ae[e]}async function J(e){return e?await Y(e,(e,t)=>{try{T.unlinkSync(t)}catch(e){if(e.code!==`ENOENT`)throw e;return`absent`}return`deleted`},e=>e?e.claim?`ownership-changed`:`unattributable`:`absent`):`absent`}async function oe(e){return e?await Y(e,e=>{let t=Date.now();return k({...e,abandonedAtMs:t,updatedAtMs:t}),`abandoned`},e=>e?`ownership-changed`:`absent`):`absent`}async function se(e){return e?await Y(e,e=>(k({...e,updatedAtMs:Date.now()}),{status:`renewed`}),e=>({status:`lost`,conflict:e})):{status:`lost`,conflict:void 0}}async function Y(e,t,n){return await A(e.deviceKey,async()=>{let r=_(e.deviceKey),i=v(r);if(!i)return n(void 0);let a=i.claim;return!a||!ce(a,e)?n(i):t(a,r)})}function ce(e,t){return e.ownerToken===t.ownerToken&&d({pid:e.ownerPid,startTime:e.ownerStartTime},{pid:t.ownerPid,startTime:t.ownerStartTime})}async function le(e,t){let n=x(),r;try{r=T.readdirSync(n,{withFileTypes:!0})}catch{return{examined:0,reconciled:0,retained:0,changed:0}}let i=0,a=0,o=0,s=0;for(let c of r){if(!c.isFile()||!c.name.endsWith(`.json`))continue;let r=E.join(n,c.name),l=v(r);if(!l?.claim||!X(l.classification,l.claim.stateDir,t))continue;i+=1;let{deviceKey:u,ownerToken:d}=l.claim;if(_(u)!==r){o+=1;continue}await A(u,async()=>{let n=v(r);if(!n?.claim||!X(n.classification,n.claim.stateDir,t)||n.claim.ownerToken!==d){s+=1;return}if((await j(n.claim,e)).status===`retained`){o+=1;return}a+=1})}return{examined:i,reconciled:a,retained:o,changed:s}}function X(e,t,n){return b(e)?e!==`owner-daemon-superseded`||E.resolve(t)===E.resolve(n):!1}const ue=S({resourceKind:`audio-probe`,fileName:`audio-probe.resource.json`,displayName:`Audio probe`}),Z=C({resourceKind:`audio-probe`,displayName:`audio probe`,store:ue,completionMetadata:e=>({backend:e.backend??`unknown`,source:e.source,durationMs:e.durationMs,elapsedMs:e.elapsedMs,bucketMs:e.bucketMs,sampleCount:e.sampleCount,heard:e.heard}),failedFinishPolicy:`dispose-on-failed-finish`,messages:{noActive:`no active audio probe`,cleanupPendingHint:`Keep audio-probe.resource.json and retry stop through its exact runtime owner.`}});function de(e){return Z.adoptStarted(e)}function fe(e){return Z.finishLive(e)}const pe=S({resourceKind:`perf-capture`,fileName:`perf-capture.resource.json`,displayName:`Perf capture`}),Q=C({resourceKind:`perf-capture`,displayName:`perf capture`,store:pe,completionMetadata:e=>({kind:typeof e.kind==`string`?e.kind:`unknown`,mode:typeof e.mode==`string`?e.mode:`unknown`,...typeof e.outPath==`string`?{outPath:e.outPath}:{}}),failedFinishPolicy:`preserve-retry-material`,messages:{noActive:`no active native perf capture`,cleanupPendingHint:`Keep perf-capture.resource.json and retry stop through its exact runtime owner.`}});function $(e){return Q.adoptStarted(e)}function me(e){return Q.finishLive(e)}function he(e){if(e.area===`frames`)return Object.freeze({kind:`frames`,request:e,use:c});if(e.area===`memory`)return e.action===`snapshot`?Object.freeze({kind:`memory-snapshot`,request:e,use:a}):Object.freeze({kind:`memory-sample`,request:e,use:l});if(e.area===`trace`)return e.action===`start`?Object.freeze({kind:`capture-start`,request:e,use:o}):Object.freeze({kind:`capture-stop`,request:e});switch(e.action){case`start`:return Object.freeze({kind:`capture-start`,request:e,use:o});case`stop`:return Object.freeze({kind:`capture-stop`,request:e});case`report`:return Object.freeze({kind:`profile-report`,request:e,use:s})}}function ge(t){let n=t.positionals??[],r=n[0]?.toLowerCase();if(r===`frames`){let i=n[1]?.toLowerCase();if(i!==void 0&&i!==`sample`||n.length>2||t.kind!==void 0)throw new e(`INVALID_ARGS`,`perf action must be frames, memory sample|snapshot, cpu profile start|stop|report, or trace start|stop`);return Object.freeze({area:r,action:`sample`})}if(r===`memory`)return _e(n,t);if(r===`cpu`)return ve(n,t.outPath);if(r===`trace`)return ye(n,t.outPath);throw new e(`INVALID_ARGS`,`perf requires frames, memory, cpu, or trace`)}function _e(t,n){let r=(t[1]??`sample`).toLowerCase();if(r!==`sample`&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`perf memory requires sample or snapshot`);if(n.kind!==void 0&&r!==`snapshot`)throw new e(`INVALID_ARGS`,`--kind is only supported with perf memory snapshot`);if(r===`sample`&&t.length>2)throw new e(`INVALID_ARGS`,`perf memory sample does not accept additional positionals`);if(r===`snapshot`&&t.length>3)throw new e(`INVALID_ARGS`,`perf memory snapshot accepts at most one positional kind`);let i=n.kind??t[2];if(i!==void 0&&!u(i))throw new e(`INVALID_ARGS`,`perf memory snapshot --kind must be android-hprof or memgraph`);return Object.freeze({area:`memory`,action:r,...i===void 0?{}:{kind:i},...n.outPath===void 0?{}:{outPath:n.outPath}})}function ve(t,n){if(t[1]?.toLowerCase()!==`profile`)throw new e(`INVALID_ARGS`,`perf cpu requires profile`);let r=t[2]?.toLowerCase();if(r!==`start`&&r!==`stop`&&r!==`report`)throw new e(`INVALID_ARGS`,`perf cpu profile action must be start, stop, or report`);let i=t[3]?.toLowerCase();if(i!==`xctrace`&&i!==`simpleperf`)throw new e(`INVALID_ARGS`,`perf cpu profile requires --kind xctrace or simpleperf`);let a=n??t[5];return Object.freeze({area:`cpu`,subject:`profile`,action:r,kind:i,...t[4]?{template:t[4]}:{},...a?{outPath:a}:{},...t[6]?{tracePath:t[6]}:{}})}function ye(t,n){let r=t[1]?.toLowerCase();if(r!==`start`&&r!==`stop`)throw new e(`INVALID_ARGS`,`perf trace action must be start or stop`);let i=t[2]?.toLowerCase();if(i!==`xctrace`&&i!==`perfetto`)throw new e(`INVALID_ARGS`,`perf trace requires --kind xctrace or perfetto`);let a=n??t[4];return Object.freeze({area:`trace`,action:r,kind:i,...t[3]?{template:t[3]}:{},...a?{outPath:a}:{}})}export{se as _,Q as a,fe as c,V as d,J as f,G as g,le as h,me as i,oe as l,U as m,he as n,de as o,W as p,$ as r,Z as s,ge as t,B as u};
|
package/dist/src/perf-target.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{P as e}from"./sdk-contracts.js";import{k as t}from"./sdk-batch-runner.js";import{
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{k as t}from"./sdk-batch-runner.js";import{g as n}from"./sdk-device.js";import{o as r}from"./exec.js";import"./command.js";import{a as i,o as a}from"./tool-provider.js";import{t as o}from"./physical-device-control.js";import{n as s}from"./simctl.js";import{t as c}from"./plist.js";import l from"node:path";import{fileURLToPath as u}from"node:url";const d=15e3;function f(e){let n=[];for(let r of t(e)){let e=r.match(/^(\d+)\s+([0-9]+(?:\.[0-9]+)?)\s+(\d+)\s+(.+)$/);if(!e)continue;let[t,i,a,o]=e.slice(1);if(t===void 0||i===void 0||a===void 0||o===void 0)continue;let s=Number(t),c=Number(i),l=Number(a),u=o.trim();!Number.isFinite(s)||!Number.isFinite(c)||!Number.isFinite(l)||n.push({pid:s,cpuPercent:c,rssKb:l,command:u})}return n}async function p(t,r){let i=n(t)?await h(r):await g(t,r),a=n(t)?l.join(i,`Contents`,`Info.plist`):l.join(i,`Info.plist`),o=await c(a,`CFBundleExecutable`);if(!o)throw new e(`COMMAND_FAILED`,`Failed to resolve executable for ${r}`,{appBundleId:r,appPath:i});return{executableName:o,executablePath:n(t)?l.join(i,`Contents`,`MacOS`,o):l.join(i,o)}}async function m(t,n){let{appBundleUrl:r,processes:i}=await o(t).resolveAppProcesses(t,n),a=u(r);if(i.length===0)throw new e(`COMMAND_FAILED`,`No running process found for ${n}`,{appBundleId:n,deviceId:t.id,appBundlePath:a,hint:`Run open <app> for this session again to ensure the iOS app is active, then retry perf.`});return i}async function h(t){let n=`kMDItemCFBundleIdentifier == "${t.replaceAll(`"`,String.raw`\"`)}"`,a=r(await i(`mdfind`,[n],{allowFailure:!0,timeoutMs:d}),`Failed to resolve macOS app bundle for ${t}`,{appBundleId:t}).stdout.split(`
|
|
2
2
|
`).map(e=>e.trim()).find(e=>e.endsWith(`.app`));if(!a)throw new e(`APP_NOT_INSTALLED`,`No macOS app found for ${t}`,{appBundleId:t});return a}async function g(t,n){let i=s(t,[`get_app_container`,t.id,n,`app`]),o=r(await a(i,{allowFailure:!0,timeoutMs:d}),`Failed to resolve iOS simulator app container for ${n}`,{appBundleId:n,hint:`Ensure the iOS simulator app is installed and booted, then retry perf.`}).stdout.trim();if(o.length===0)throw new e(`APP_NOT_INSTALLED`,`No iOS simulator app container found for ${n}`,{appBundleId:n});return o}async function _(e,t){let r=n(e)?await i(`ps`,[`-axo`,`pid=,%cpu=,rss=,command=`],{timeoutMs:d}):await v(s(e,[`spawn`,e.id,`ps`,`-axo`,`pid=,%cpu=,rss=,command=`])),{matchesAppleExecutableProcess:a}=await import(`./perf-process-identity.js`);return f(r.stdout).filter(e=>a(e.command,t))}async function v(e){let t=await a(e,{allowFailure:!0,timeoutMs:d});return t.exitCode===0?t:await i(`ps`,[`-axo`,`pid=,%cpu=,rss=,command=`],{timeoutMs:d})}export{_ as readAppleProcessSamples,p as resolveAppleExecutable,m as resolveIosDevicePerfTarget};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{P as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import"./diagnostics2.js";import{r as n}from"./exec.js";import"./command.js";import{n as r}from"./retry.js";import{E as i}from"./host-file.js";import{c as a}from"./config.js";import{o}from"./tool-provider.js";import{c as s,n as c,o as l,r as u,s as d,t as f}from"./devicectl.js";import{i as p,n as ee,r as m}from"./physical-device-apps.js";import"./runner.js";import{t as h}from"./runner-cache-metadata.js";const g=1e4;async function _(e,t,n={}){let r=[`device`,`process`,`launch`,`--device`,e.id];n.payloadUrl&&r.push(`--payload-url`,n.payloadUrl),r.push(t),n.launchArgs&&n.launchArgs.length>0&&r.push(`--`,...n.launchArgs),await d(r,{action:`launch iOS app`,deviceId:e.id})}async function v(t,r){try{let i=await w(t.id,15e3,3e3,r);if(i.status===`unreadable`)throw new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{kind:`probe_inconclusive`,deviceId:t.id,stdout:i.result.stdout,stderr:i.result.stderr,hint:`CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device.`});if(i.status===`reported`){let n=i.details.tunnelState?.toLowerCase();if(n===`connecting`)throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,{kind:`not_ready`,deviceId:t.id,tunnelState:n,hint:`Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`});return}throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,n(i.result,{kind:`not_ready`,deviceId:t.id,tunnelState:i.details.tunnelState,hint:R(i.result.stdout,i.result.stderr)}))}catch(e){throw y(t.id,e)}}function y(t,n){return!(n instanceof e)||n.code!==`COMMAND_FAILED`?x(t,n):(typeof n.details?.kind==`string`?n.details.kind:``)===`not_ready`?n:b(t,n)}function b(t,n){let r=n.details??{},i=String(r.stdout??``),a=String(r.stderr??``),o=Number(r.timeoutMs??15e3),s=`CoreDevice did not respond within ${o}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,cause:n.message,timeoutMs:o,stdout:i,stderr:a,hint:i||a?R(i,a):s},n)}function x(t,n){return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,hint:`Reconnect the device, keep it unlocked, and retry.`},n instanceof Error?n:void 0)}async function S(e,t){return(await C(e,t??g))?.tunnelIp??null}async function C(e,t,n){if(!(t>0))return null;let r=Math.max(1,Math.min(g,t));try{let t=await w(e.id,r,0,n);return t.status!==`reported`||t.details.outcome&&t.details.outcome!==`success`?null:t.details}catch{return null}}async function w(e,t,n=0,r){let i=Math.max(5,Math.ceil(t/1e3)),a=await s({jsonPrefix:`agent-device-coredevice-info`,args:[`devicectl`,`device`,`info`,`details`,`--device`,e,`--timeout`,String(i)],signal:r,timeoutMs:t+n});return a.ok?{status:`reported`,details:O(a.payload)}:a.reason===`unreadable-json`?{status:`unreadable`,result:a.result}:{status:`failed`,result:a.result,details:O(a.payload)}}function T(e){let t=e,n=D(t.device);return{connectionProperties:E(D(t.connectionProperties),D(n?.connectionProperties)),deviceProperties:E(D(t.deviceProperties),D(n?.deviceProperties))}}function E(e,t){if(!e)return t;if(!t)return e;let n={...t};for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function D(e){return e&&typeof e==`object`?e:void 0}function O(e){let t=D(e?.result);if(!t)return{};let{connectionProperties:n,deviceProperties:r}=T(t);return{...k(`outcome`,A(e?.info?.outcome)),...k(`tunnelState`,A(n?.tunnelState)),...k(`tunnelIp`,A(n?.tunnelIPAddress)),...k(`developerModeStatus`,A(r?.developerModeStatus)),...k(`developerDiskImageServicesAvailable`,j(r?.ddiServicesAvailable)),...k(`bootState`,A(r?.bootState))}}function k(e,t){return t===void 0?{}:{[e]:t}}function A(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function j(e){return typeof e==`boolean`?e:void 0}const M={developerModeOff:u,developerDiskImageUnavailable:c};function N(e){return e.tunnelState===`connected`&&e.bootState===`booted`}function P(e){return`The device reported its developer disk image as unavailable while it was not observable (tunnelState=${e.tunnelState??`unknown`}, bootState=${e.bootState??`unknown`}). Unlock it, keep it connected by cable until \`xcrun devicectl device info details\` reports tunnelState=connected and bootState=booted, then retry.`}async function F(e,t=1e4,n){let r=await C(e,t,n);if(!r)return{available:!1,reason:`device_readiness_unreadable`,hint:"Read the device state directly with `xcrun devicectl device info details --device <id> --json-output -`, keeping the device unlocked and connected by cable, then retry."};let i=I(r.developerModeStatus),a=L(r.developerDiskImageServicesAvailable);return a===`unavailable`&&i!==`disabled`&&!N(r)?{available:!1,reason:`device_readiness_unreadable`,hint:P(r)}:{available:!0,developerMode:i,developerDiskImage:a,remedies:M}}function I(e){let t=e?.toLowerCase();return t===`enabled`?`enabled`:t===`disabled`?`disabled`:`unknown`}function L(e){return e===!0?`available`:e===!1?`unavailable`:`unknown`}function R(e,t){return l(e,t)||(`${e}\n${t}`.toLowerCase().includes(`timed out waiting for all destinations`)?`Xcode destination did not become available in time. Keep device unlocked and retry.`:f)}async function z(t,n,i,s=a){let c=r.fromTimeoutMs(s),l={exitCode:1,stdout:``,stderr:``};for(let e of h)if(l=await o([`devicectl`,`device`,`copy`,`from`,`--device`,t.id,`--source`,n,`--destination`,i,`--domain-type`,`appDataContainer`,`--domain-identifier`,e],{allowFailure:!0,timeoutMs:B(c,s)}),l.exitCode===0)return;let u=l.stderr.trim()||l.stdout.trim()||`devicectl exited with code ${l.exitCode}`;throw new e(`COMMAND_FAILED`,`Failed to copy runner file from iOS device: ${u}`)}function B(t,n){let r=t.remainingMs();if(r>0)return r;throw new e(`COMMAND_FAILED`,`iOS runner file copy timed out after ${n}ms`,{timeoutMs:n,step:`runner file copy`})}function V(t){if(!(t instanceof e))return{reason:t instanceof Error?t.message:String(t)};let n=t.details??{},r=Array.isArray(n.args)?n.args.filter(e=>typeof e==`string`).join(` `):void 0;return{errorCode:t.code,reason:t.message,timeoutMs:typeof n.timeoutMs==`number`?n.timeoutMs:void 0,exitCode:typeof n.exitCode==`number`?n.exitCode:void 0,stderr:typeof n.stderr==`string`&&n.stderr.trim()?n.stderr:void 0,stdout:typeof n.stdout==`string`&&n.stdout.trim()?n.stdout:void 0,commandArgs:r}}function H(e){let t=e.details??{},n=typeof t.stdout==`string`?t.stdout:``,r=typeof t.stderr==`string`?t.stderr:``,i=Array.isArray(t.args)?t.args.filter(e=>typeof e==`string`).join(` `):``;return`${e.message}\n${n}\n${r}\n${i}`.toLowerCase()}async function U(e,t,n){if(!n.preferRunner)try{await d([`device`,`capture`,`screenshot`,`--device`,e.id,`--destination`,t],{action:`capture iOS screenshot`,deviceId:e.id});return}catch(t){if(!Y(t))throw t;J(e,t)}let r=await G(e,n,!1);await K(r,t)||await z(e,q(r),t)}async function W(t,n,r){if(!await K(await G(t,r,!0),n))throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: XCTest runner returned no inline image`,{deviceId:t.id,backend:`xctest`})}async function G(e,t,n){return await t.runRunnerCommand(e,{command:`screenshot`,appBundleId:t.appBundleId,fullscreen:t.fullscreen,inlineScreenshot:n},t.runnerOptions??{})}async function K(e,t){let n=e.imageBase64;return typeof n!=`string`||n.length===0?!1:(await i(t,Buffer.from(n,`base64`)),!0)}function q(t){let n=t.message;if(typeof n==`string`&&n.length>0)return n;throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: runner returned no file path`)}function J(e,n){t({level:`warn`,phase:`ios_screenshot_fallback`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:`devicectl_screenshot`,to:`runner`,...V(n)}})}function Y(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=H(t);return n.includes(`unknown option '--device'`)||n.includes(`unknown subcommand`)&&n.includes(`screenshot`)||n.includes(`unrecognized subcommand`)&&n.includes(`screenshot`)}const X={coredevice:{backend:`coredevice`,ensureReady:v,listApps:ee,launchApp:_,terminateApp:async(e,t)=>await p(e,t),resolveAppProcesses:m,captureScreenshot:U,copyRunnerFile:z,resolveTunnel:async(e,t)=>({tunnelIp:await S(e,t)}),readDeviceReadiness:F},xctest:{backend:`xctest`,ensureReady:ie,listApps:Q,launchApp:ae,terminateApp:oe,resolveAppProcesses:$,captureScreenshot:W,copyRunnerFile:re,resolveTunnel:te,readDeviceReadiness:ne}};function Z(e){return X[e.iosPhysicalDeviceBackend===`xctest`?`xctest`:`coredevice`]}async function Q(t){throw new e(`UNSUPPORTED_OPERATION`,`App inventory is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use an installed app bundle ID when opening the device.`})}async function $(t){throw new e(`UNSUPPORTED_OPERATION`,`Process lookup is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use a CoreDevice-backed iOS device for performance sampling.`})}async function te(t){throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices have no CoreDevice tunnel.`,{deviceId:t.id,backend:`xctest`,hint:`Connect the device by cable so it is reachable through usbmux.`})}async function ne(e){return{available:!1,reason:`device_readiness_unreadable`,hint:`This device is driven through XCTest (device ${e.id}), which does not report Developer Mode or developer disk image state. Check the device's own Settings if development tooling fails to start on it.`}}async function re(t){throw new e(`UNSUPPORTED_OPERATION`,`Runner file copy is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`})}async function ie(t,r){let i=[`xcdevice`,`wait`,`--both`,`--timeout=15`,t.id],a=await o(i,{allowFailure:!0,signal:r,timeoutMs:18e3});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`iOS device is not ready for XCTest automation`,n(a,{cmd:`xcrun`,args:i,deviceId:t.id,backend:`xctest`,hint:"Keep the device unlocked, trusted, connected, and visible in `xcrun xcdevice list`, then retry."}))}async function ae(t,n,r){if(r.payloadUrl||r.launchArgs&&r.launchArgs.length>0)throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices do not support deep links or launch arguments during open.`,{deviceId:t.id,backend:`xctest`,hint:`Open the installed app by bundle ID without a URL or --launch-args.`});await r.runRunnerCommand(t,{command:`activate`,appBundleId:n},r.runnerOptions??{})}async function oe(e,t,n){await n.runRunnerCommand(e,{command:`terminate`,appBundleId:t},n.runnerOptions??{})}export{H as n,V as r,Z as t};
|
|
1
|
+
import{P as e}from"./sdk-contracts.js";import{r as t}from"./diagnostics.js";import"./diagnostics2.js";import{r as n}from"./exec.js";import{t as r}from"./retry.js";import"./command.js";import"./retry2.js";import{E as i}from"./host-file.js";import{c as a}from"./config.js";import{o}from"./tool-provider.js";import{c as s,n as c,o as l,r as u,s as d,t as f}from"./devicectl.js";import{i as p,n as ee,r as m}from"./physical-device-apps.js";import"./runner.js";import{t as h}from"./runner-cache-metadata.js";const g=1e4;async function _(e,t,n={}){let r=[`device`,`process`,`launch`,`--device`,e.id];n.payloadUrl&&r.push(`--payload-url`,n.payloadUrl),r.push(t),n.launchArgs&&n.launchArgs.length>0&&r.push(`--`,...n.launchArgs),await d(r,{action:`launch iOS app`,deviceId:e.id})}async function v(t,r){try{let i=await w(t.id,15e3,3e3,r);if(i.status===`unreadable`)throw new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{kind:`probe_inconclusive`,deviceId:t.id,stdout:i.result.stdout,stderr:i.result.stderr,hint:`CoreDevice returned success but readiness JSON output was missing or invalid. Retry; if it persists restart Xcode and the iOS device.`});if(i.status===`reported`){let n=i.details.tunnelState?.toLowerCase();if(n===`connecting`)throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,{kind:`not_ready`,deviceId:t.id,tunnelState:n,hint:`Device tunnel is still connecting. Keep the device unlocked and connected by cable until it is fully available in Xcode Devices, then retry.`});return}throw new e(`COMMAND_FAILED`,`iOS device is not ready for automation`,n(i.result,{kind:`not_ready`,deviceId:t.id,tunnelState:i.details.tunnelState,hint:R(i.result.stdout,i.result.stderr)}))}catch(e){throw y(t.id,e)}}function y(t,n){return!(n instanceof e)||n.code!==`COMMAND_FAILED`?x(t,n):(typeof n.details?.kind==`string`?n.details.kind:``)===`not_ready`?n:b(t,n)}function b(t,n){let r=n.details??{},i=String(r.stdout??``),a=String(r.stderr??``),o=Number(r.timeoutMs??15e3),s=`CoreDevice did not respond within ${o}ms. Keep the device unlocked and trusted, then retry; if it persists restart Xcode and the iOS device.`;return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,cause:n.message,timeoutMs:o,stdout:i,stderr:a,hint:i||a?R(i,a):s},n)}function x(t,n){return new e(`COMMAND_FAILED`,`iOS device readiness probe failed`,{deviceId:t,hint:`Reconnect the device, keep it unlocked, and retry.`},n instanceof Error?n:void 0)}async function S(e,t){return(await C(e,t??g))?.tunnelIp??null}async function C(e,t,n){if(!(t>0))return null;let r=Math.max(1,Math.min(g,t));try{let t=await w(e.id,r,0,n);return t.status!==`reported`||t.details.outcome&&t.details.outcome!==`success`?null:t.details}catch{return null}}async function w(e,t,n=0,r){let i=Math.max(5,Math.ceil(t/1e3)),a=await s({jsonPrefix:`agent-device-coredevice-info`,args:[`devicectl`,`device`,`info`,`details`,`--device`,e,`--timeout`,String(i)],signal:r,timeoutMs:t+n});return a.ok?{status:`reported`,details:O(a.payload)}:a.reason===`unreadable-json`?{status:`unreadable`,result:a.result}:{status:`failed`,result:a.result,details:O(a.payload)}}function T(e){let t=e,n=D(t.device);return{connectionProperties:E(D(t.connectionProperties),D(n?.connectionProperties)),deviceProperties:E(D(t.deviceProperties),D(n?.deviceProperties))}}function E(e,t){if(!e)return t;if(!t)return e;let n={...t};for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function D(e){return e&&typeof e==`object`?e:void 0}function O(e){let t=D(e?.result);if(!t)return{};let{connectionProperties:n,deviceProperties:r}=T(t);return{...k(`outcome`,A(e?.info?.outcome)),...k(`tunnelState`,A(n?.tunnelState)),...k(`tunnelIp`,A(n?.tunnelIPAddress)),...k(`developerModeStatus`,A(r?.developerModeStatus)),...k(`developerDiskImageServicesAvailable`,j(r?.ddiServicesAvailable)),...k(`bootState`,A(r?.bootState))}}function k(e,t){return t===void 0?{}:{[e]:t}}function A(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function j(e){return typeof e==`boolean`?e:void 0}const M={developerModeOff:u,developerDiskImageUnavailable:c};function N(e){return e.tunnelState===`connected`&&e.bootState===`booted`}function P(e){return`The device reported its developer disk image as unavailable while it was not observable (tunnelState=${e.tunnelState??`unknown`}, bootState=${e.bootState??`unknown`}). Unlock it, keep it connected by cable until \`xcrun devicectl device info details\` reports tunnelState=connected and bootState=booted, then retry.`}async function F(e,t=1e4,n){let r=await C(e,t,n);if(!r)return{available:!1,reason:`device_readiness_unreadable`,hint:"Read the device state directly with `xcrun devicectl device info details --device <id> --json-output -`, keeping the device unlocked and connected by cable, then retry."};let i=I(r.developerModeStatus),a=L(r.developerDiskImageServicesAvailable);return a===`unavailable`&&i!==`disabled`&&!N(r)?{available:!1,reason:`device_readiness_unreadable`,hint:P(r)}:{available:!0,developerMode:i,developerDiskImage:a,remedies:M}}function I(e){let t=e?.toLowerCase();return t===`enabled`?`enabled`:t===`disabled`?`disabled`:`unknown`}function L(e){return e===!0?`available`:e===!1?`unavailable`:`unknown`}function R(e,t){return l(e,t)||(`${e}\n${t}`.toLowerCase().includes(`timed out waiting for all destinations`)?`Xcode destination did not become available in time. Keep device unlocked and retry.`:f)}async function z(t,n,i,s=a){let c=r.fromTimeoutMs(s),l={exitCode:1,stdout:``,stderr:``};for(let e of h)if(l=await o([`devicectl`,`device`,`copy`,`from`,`--device`,t.id,`--source`,n,`--destination`,i,`--domain-type`,`appDataContainer`,`--domain-identifier`,e],{allowFailure:!0,timeoutMs:B(c,s)}),l.exitCode===0)return;let u=l.stderr.trim()||l.stdout.trim()||`devicectl exited with code ${l.exitCode}`;throw new e(`COMMAND_FAILED`,`Failed to copy runner file from iOS device: ${u}`)}function B(t,n){let r=t.remainingMs();if(r>0)return r;throw new e(`COMMAND_FAILED`,`iOS runner file copy timed out after ${n}ms`,{timeoutMs:n,step:`runner file copy`})}function V(t){if(!(t instanceof e))return{reason:t instanceof Error?t.message:String(t)};let n=t.details??{},r=Array.isArray(n.args)?n.args.filter(e=>typeof e==`string`).join(` `):void 0;return{errorCode:t.code,reason:t.message,timeoutMs:typeof n.timeoutMs==`number`?n.timeoutMs:void 0,exitCode:typeof n.exitCode==`number`?n.exitCode:void 0,stderr:typeof n.stderr==`string`&&n.stderr.trim()?n.stderr:void 0,stdout:typeof n.stdout==`string`&&n.stdout.trim()?n.stdout:void 0,commandArgs:r}}function H(e){let t=e.details??{},n=typeof t.stdout==`string`?t.stdout:``,r=typeof t.stderr==`string`?t.stderr:``,i=Array.isArray(t.args)?t.args.filter(e=>typeof e==`string`).join(` `):``;return`${e.message}\n${n}\n${r}\n${i}`.toLowerCase()}async function U(e,t,n){if(!n.preferRunner)try{await d([`device`,`capture`,`screenshot`,`--device`,e.id,`--destination`,t],{action:`capture iOS screenshot`,deviceId:e.id});return}catch(t){if(!Y(t))throw t;J(e,t)}let r=await G(e,n,!1);await K(r,t)||await z(e,q(r),t)}async function W(t,n,r){if(!await K(await G(t,r,!0),n))throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: XCTest runner returned no inline image`,{deviceId:t.id,backend:`xctest`})}async function G(e,t,n){return await t.runRunnerCommand(e,{command:`screenshot`,appBundleId:t.appBundleId,fullscreen:t.fullscreen,inlineScreenshot:n},t.runnerOptions??{})}async function K(e,t){let n=e.imageBase64;return typeof n!=`string`||n.length===0?!1:(await i(t,Buffer.from(n,`base64`)),!0)}function q(t){let n=t.message;if(typeof n==`string`&&n.length>0)return n;throw new e(`COMMAND_FAILED`,`Failed to capture iOS screenshot: runner returned no file path`)}function J(e,n){t({level:`warn`,phase:`ios_screenshot_fallback`,data:{platform:e.platform,deviceKind:e.kind,deviceId:e.id,from:`devicectl_screenshot`,to:`runner`,...V(n)}})}function Y(t){if(!(t instanceof e)||t.code!==`COMMAND_FAILED`)return!1;let n=H(t);return n.includes(`unknown option '--device'`)||n.includes(`unknown subcommand`)&&n.includes(`screenshot`)||n.includes(`unrecognized subcommand`)&&n.includes(`screenshot`)}const X={coredevice:{backend:`coredevice`,ensureReady:v,listApps:ee,launchApp:_,terminateApp:async(e,t)=>await p(e,t),resolveAppProcesses:m,captureScreenshot:U,copyRunnerFile:z,resolveTunnel:async(e,t)=>({tunnelIp:await S(e,t)}),readDeviceReadiness:F},xctest:{backend:`xctest`,ensureReady:ie,listApps:Q,launchApp:ae,terminateApp:oe,resolveAppProcesses:$,captureScreenshot:W,copyRunnerFile:re,resolveTunnel:te,readDeviceReadiness:ne}};function Z(e){return X[e.iosPhysicalDeviceBackend===`xctest`?`xctest`:`coredevice`]}async function Q(t){throw new e(`UNSUPPORTED_OPERATION`,`App inventory is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use an installed app bundle ID when opening the device.`})}async function $(t){throw new e(`UNSUPPORTED_OPERATION`,`Process lookup is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`,hint:`Use a CoreDevice-backed iOS device for performance sampling.`})}async function te(t){throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices have no CoreDevice tunnel.`,{deviceId:t.id,backend:`xctest`,hint:`Connect the device by cable so it is reachable through usbmux.`})}async function ne(e){return{available:!1,reason:`device_readiness_unreadable`,hint:`This device is driven through XCTest (device ${e.id}), which does not report Developer Mode or developer disk image state. Check the device's own Settings if development tooling fails to start on it.`}}async function re(t){throw new e(`UNSUPPORTED_OPERATION`,`Runner file copy is unavailable on this XCTest-backed physical iOS device.`,{deviceId:t.id,backend:`xctest`})}async function ie(t,r){let i=[`xcdevice`,`wait`,`--both`,`--timeout=15`,t.id],a=await o(i,{allowFailure:!0,signal:r,timeoutMs:18e3});if(a.exitCode!==0)throw new e(`COMMAND_FAILED`,`iOS device is not ready for XCTest automation`,n(a,{cmd:`xcrun`,args:i,deviceId:t.id,backend:`xctest`,hint:"Keep the device unlocked, trusted, connected, and visible in `xcrun xcdevice list`, then retry."}))}async function ae(t,n,r){if(r.payloadUrl||r.launchArgs&&r.launchArgs.length>0)throw new e(`UNSUPPORTED_OPERATION`,`XCTest-backed physical iOS devices do not support deep links or launch arguments during open.`,{deviceId:t.id,backend:`xctest`,hint:`Open the installed app by bundle ID without a URL or --launch-args.`});await r.runRunnerCommand(t,{command:`activate`,appBundleId:n},r.runnerOptions??{})}async function oe(e,t,n){await n.runRunnerCommand(e,{command:`terminate`,appBundleId:t},n.runnerOptions??{})}export{H as n,V as r,Z as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./diagnostics.js";import"./diagnostics2.js";import{
|
|
1
|
+
import{r as e}from"./diagnostics.js";import"./diagnostics2.js";import{I as t}from"./sdk-device.js";import{N as n,Qt as r,ht as i,jt as a}from"./sdk-batch.js";import{r as o}from"./session-paths.js";import{i as s,n as c,r as l}from"./session-artifact-paths.js";import{n as u}from"./process.js";import{t as d}from"./daemon-resolution.js";import{r as f}from"./request-cancel.js";import{t as p}from"./request.js";import{r as m}from"./platform-runtime.js";import{a as h,s as g}from"./perf-runtime-plan.js";import"./durable-capture-resource.js";import{c as _,n as v,r as y}from"./screen-recording-resource-recovery.js";import{n as b}from"./app-log-session-resource.js";import x from"node:path";const S=i({required:[`appLogReattach`,`appLogCleanup`]});function C(e){return b.recoverAll({sessionsDir:e.sessionsDir,...T(e)})}function w(e){return b.recoverOne({sessionsDir:e.sessionsDir,...T(e)},e.resourcePath)}function T(e){return{scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await E(e.gateway,t,n)}}async function E(e,t,n){return await y({gateway:e,envelope:t,scope:n,create:e=>{let t=r(e,S);return Object.freeze({reattach:async e=>await t.operations.appLogReattach({envelope:e}),cleanup:async e=>await t.operations.appLogCleanup({envelope:e}),[Symbol.asyncDispose]:async()=>await e[Symbol.asyncDispose]()})}})}function D(e){return g.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await O(e.gateway,t,n)},e.resourcePath)}async function O(e,t,i){return await y({gateway:e,envelope:t,scope:i,create:e=>k({runtime:r(e,n),dispose:async()=>await e[Symbol.asyncDispose]()})})}function k(e){return Object.freeze({reattach:async t=>await e.runtime.operations.audioProbeReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.audioProbeCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function A(e){return h.recoverOne({sessionsDir:e.sessionsDir,scope:e.scope,perRecordDeadlineMs:e.perRecordDeadlineMs,onDiagnostic:e.onDiagnostic,acquireControl:async(t,n)=>await j(e.gateway,t,n)},e.resourcePath)}async function j(e,t,n){return await y({gateway:e,envelope:t,scope:n,create:e=>M({runtime:r(e,a),dispose:async()=>await e[Symbol.asyncDispose]()})})}function M(e){return Object.freeze({reattach:async t=>await e.runtime.operations.perfNativeCaptureReattach({envelope:t}),cleanup:async t=>await e.runtime.operations.perfNativeCaptureCleanup({envelope:t}),[Symbol.asyncDispose]:e.dispose})}function N(t){return async n=>{let r=d(n.stateDir).sessionsDir,i=x.join(r,o(n.session));try{for(let e of Object.values(P)){let a=F(e,n,i);if(a.status===`retained`)return{status:`retained`,reason:a.reason};if(a.status===`owned`&&await e.recover(t,r,a.resourcePath)===`retained`)return{status:`retained`,reason:`${e.resourceKind}-cleanup-pending`}}return{status:`reconciled`}}catch(t){return e({level:`warn`,phase:`device_claim_orphan_reconciliation_failed`,data:{deviceKey:n.deviceKey,ownerSession:n.session,error:t instanceof Error?t.message:String(t)}}),{status:`retained`,reason:`durable-resource-reconciliation-failed`}}}}const P={"app-log":{resourceKind:`app-log`,store:b.store,recover:async(e,t,n)=>await w({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"screen-recording":{resourceKind:`screen-recording`,store:_.store,recover:async(e,t,n)=>await v({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"audio-probe":{resourceKind:`audio-probe`,store:g.store,recover:async(e,t,n)=>await D({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})},"perf-capture":{resourceKind:`perf-capture`,store:h.store,recover:async(e,t,n)=>await A({sessionsDir:t,resourcePath:n,gateway:e.gateway,scope:e.scope})}};function F(e,n,r){let i=e.store.resolvePath(r),a=e.store.read(i);return a.status===`missing`?{status:`missing`}:a.status===`unreattachable`?{status:`retained`,reason:`${e.resourceKind}-${a.reason}`}:a.envelope.sessionId!==n.session||!t(a.envelope.device,n.device)?{status:`retained`,reason:`${e.resourceKind}-owner-mismatch`}:{status:`owned`,resourcePath:i}}function I(e,t){let n=t??(t=>L(t,e));return async e=>{let t=n(e.stateDir);try{return await t.reconcile(e)}finally{await t.dispose()}}}function L(e,t){let n=d(e),r=m({sessionsDir:n.sessionsDir,ownedProcesses:u({stateDir:n.baseDir,sessionsDir:n.sessionsDir,resolveSessionDir:e=>s(n.sessionsDir,e)}),resolveSessionArtifacts:e=>({outputPath:c(n.sessionsDir,e),pidPath:l(n.sessionsDir,e)})});return{reconcile:N({gateway:r,scope:t}),dispose:async()=>{await r.shutdown()}}}const R=new AbortController().signal;function z(t){return Object.freeze({signal:f(t.meta?.requestId)??R,diagnostics:Object.freeze({emit:t=>e(t)}),progress:Object.freeze({report:e=>p({type:`command`,status:`progress`,message:e.message})})})}function B(){return Object.freeze({signal:R,diagnostics:Object.freeze({emit:t=>e(t)}),progress:Object.freeze({report:()=>{}})})}export{C as i,z as n,I as r,B as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{O as e,S as t,m as n,w as r}from"./owner-identity.js";import{i}from"./verified-file.js";import{u as a}from"./exec.js";import"./file.js";import"./command.js";import"./process.js";import{p as o}from"./src7.js";import s from"node:fs";import c from"node:path";function l(e){let t=c.resolve(e.sessionsDir),n=c.resolve(e.pathname);if(c.basename(n)!==e.basename)throw Error(`${e.label} is outside the daemon-owned sessions directory`);if(s.existsSync(t)&&s.existsSync(c.dirname(n))){let r=s.realpathSync.native(t),i=s.realpathSync.native(c.dirname(n));if(i!==r&&!i.startsWith(`${r}${c.sep}`))throw Error(`${e.label} resolves outside the daemon-owned sessions directory`);return c.join(i,e.basename)}if(n!==t&&!n.startsWith(`${t}${c.sep}`))throw Error(`${e.label} is outside the daemon-owned sessions directory`);return n}const u=`app-log.pid`;function d(e,t={}){let n=c.resolve(e),r=t.launch??h;return Object.freeze({start:async(e,t)=>await m(n,e,r,t),readMarker:async e=>T(n,e),clearMarker:async e=>D(n,e),inspect:async e=>k(e),terminate:async e=>await A(e)})}async function f(e){let t=[],n=[];if(!s.existsSync(e))return{recovered:t,retained:n};let r=c.resolve(e);for(let e of s.readdirSync(r,{withFileTypes:!0})){if(!e.isDirectory())continue;let i=c.join(r,e.name);if(s.existsSync(c.join(i,`app-log.resource.json`)))continue;let a=c.join(i,u),o=T(r,a);if(o.status!==`missing`){if(o.status===`invalid`){n.push({markerPath:a,reason:`invalid`,message:o.message});continue}if(await A(o.marker)===`ownership-lost`){let e=p(o.marker.command);n.push({markerPath:a,reason:`ownership-lost`,...e?{device:e}:{}});continue}D(r,a),t.push(a)}}return Object.freeze({recovered:Object.freeze(t),retained:Object.freeze(n)})}function p(e){let t=/(?:^|\s)(?:\S*\/)?adb\s+-s\s+([^\s]+)/.exec(e)?.[1];if(t)return Object.freeze({id:t,family:`android`,kind:t.startsWith(`emulator-`)?`emulator`:`device`,target:`mobile`});let n=/(?:^|\s)xcrun\s+(?:--set\s+\S+\s+)?simctl\s+spawn\s+([^\s]+)/.exec(e)?.[1];if(n)return Object.freeze({id:n,family:`apple`,appleOs:`ios`,kind:`simulator`,target:`mobile`});let r=/(?:^|\s)xcrun\s+devicectl\b[^\n]*?\s--device\s+([^\s]+)/.exec(e)?.[1];if(r)return Object.freeze({id:r,family:`apple`,appleOs:`ios`,kind:`device`,target:`mobile`,iosPhysicalDeviceBackend:`coredevice`})}async function m(e,t,n,r){_(e,t.markerPath),r?.throwIfAborted();let i=await n(t.command,r),a=i.child,o=v(a,t.output),s=await y(e,t.markerPath,i),c=i.wait.then(async e=>(await o(),e)).finally(()=>{t.markerPath&&s&&S(e,t.markerPath,s)}),l=b(a,c);return{marker:s,wait:c,terminate:l,[Symbol.asyncDispose]:l}}function h(e,t){let n=g(e);return a(n.executable,[...n.args],{allowFailure:n.allowFailure,cwd:n.cwd,env:n.env?{...process.env,...n.env}:void 0,captureOutput:!1,signal:t})}function g(e){return e.kind===`host`?e.request:{executable:`adb`,args:[`-s`,e.serial,...e.args],...e.options}}function _(e,t){if(t&&T(e,t).status!==`missing`)throw Error(`Existing app-log process marker evidence must be recovered before start`)}function v(e,t){let n=Promise.resolve(),r,i=i=>{n=n.then(async()=>await t.write(i)).catch(t=>{r??=t,typeof e.exitCode!=`number`&&e.kill(`SIGKILL`)})};return e.stdout?.on(`data`,i),e.stderr?.on(`data`,i),async()=>{if(await n,r!==void 0)throw r}}async function y(e,t,n){let r=n.child.pid?await w(n.child.pid):void 0;try{if(!r)throw Error(`Managed app-log process did not expose a complete ownership marker`);return t&&E(e,t,r),r}catch(e){throw n.child.kill(`SIGKILL`),await n.wait.catch(()=>void 0),e}}function b(e,t){let n;return async()=>await(n??=(async()=>{typeof e.exitCode!=`number`&&(e.kill(`SIGINT`),await x(t,2e3)||e.kill(`SIGKILL`),await t.catch(()=>void 0))})())}async function x(e,t){return await new Promise(n=>{let r=setTimeout(()=>n(!1),t),i=()=>{clearTimeout(r),n(!0)};e.then(i,i)})}function S(e,t,n){let r=T(e,t);r.status===`decoded`&&r.marker.pid===n.pid&&r.marker.startTime===n.startTime&&r.marker.command===n.command&&D(e,t)}function C(e){let n=r(e),i=t(e);if(!(!n||!i))return Object.freeze({pid:e,startTime:n,command:i})}async function w(e){for(let t=0;t<5;t+=1){let t=C(e);if(t)return t;await new Promise(e=>setTimeout(e,10))}}function T(e,t){let n=O(e,t),r;try{let e=i(n);if(e===void 0)return{status:`missing`};r=e}catch(e){return{status:`invalid`,message:e instanceof Error?e.message:`App-log process marker is invalid`}}try{let e=JSON.parse(s.readFileSync(r,`utf8`));return o(e)}catch(e){return{status:`invalid`,message:e instanceof Error?e.message:`App-log process marker is invalid`}}finally{s.closeSync(r)}}function E(e,t,n){let r=O(e,t);if(T(e,r).status!==`missing`)throw Error(`Existing app-log process marker evidence must be recovered before replacement`);s.mkdirSync(c.dirname(r),{recursive:!0});let i=`${r}.${process.pid}.${Date.now()}.tmp`,a,o=!1,l=!1;try{a=s.openSync(i,`wx`,384),s.writeFileSync(a,`${JSON.stringify(n)}\n`),s.fsyncSync(a),s.closeSync(a),a=void 0,s.linkSync(i,r),o=!0,s.unlinkSync(i);let e=s.openSync(c.dirname(r),`r`);try{s.fsyncSync(e)}finally{s.closeSync(e)}l=!0}finally{if(a!==void 0)try{s.closeSync(a)}catch{}if(!l)for(let e of o?[r,i]:[i])try{s.unlinkSync(e)}catch{}}}function D(e,t){let n=O(e,t);try{s.unlinkSync(n)}catch(e){if(e.code!==`ENOENT`)throw e}}function O(e,t){return l({sessionsDir:e,pathname:t,basename:u,label:`App-log process marker`})}function k(e){return n(e.pid)?j(e)?`owned-alive`:`ownership-lost`:`missing`}async function A(t){if(!n(t.pid))return`already-missing`;if(!j(t))return`ownership-lost`;try{process.kill(t.pid,`SIGTERM`)}catch{return`already-missing`}if(!await e(t.pid,2e3)){if(!j(t))return`ownership-lost`;try{process.kill(t.pid,`SIGKILL`)}catch{return`already-missing`}await e(t.pid,2e3)}return n(t.pid)?`ownership-lost`:`terminated`}function j(e){return!e.startTime||!e.command?!1:r(e.pid)===e.startTime&&t(e.pid)===e.command}export{f as n,l as r,d as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime.js";import{P as t}from"./sdk-contracts.js";import{a as n,i as r,o as i,r as a}from"./sdk-batch-runner.js";import{
|
|
1
|
+
import{r as e}from"./rolldown-runtime.js";import{P as t}from"./sdk-contracts.js";import{a as n,i as r,o as i,r as a}from"./sdk-batch-runner.js";import{f as o,g as s}from"./sdk-device.js";import{i as c}from"./session.js";import{t as l}from"./platform-runtime-android-mechanics.js";var u=e({resolveRequestedOpenSurface:()=>f,resolveSessionAppBundleIdForTarget:()=>C,validateOpenRelaunchTarget:()=>_});const d=new Set([`app`,`desktop`,`frontmost-app`]);function f(e){let{device:t,surfaceFlag:n,openTarget:r,existingSurface:i}=e;return t.platform===`linux`?p(n,r,i):s(t)?m(n,r,i):h(n)}function p(e,n,r){if(!e)return r??`app`;let i=c(e);if(!d.has(i))throw new t(`INVALID_ARGS`,`Linux supports --surface app, desktop, and frontmost-app (got "${e}")`);return g(i,n),i}function m(e,t,n){if(!e)return n??`app`;let r=c(e);return r!==`app`&&r!==`menubar`&&g(r,t),r}function h(e){if(e)throw new t(`INVALID_ARGS`,`surface is only supported on macOS and Linux`);return`app`}function g(e,n){if(e!==`app`&&e!==`menubar`&&n)throw new t(`INVALID_ARGS`,`open --surface ${e} does not accept an app target`)}async function _(e){let{target:t,platform:n,surface:i}=e;if(t&&r(t))return`open --relaunch does not support URL targets.`;if(i!==void 0&&i!==`app`)return`open --relaunch is supported only for app surfaces.`;if(n===`android`&&t){let{classifyAndroidAppTarget:e,formatAndroidInstalledPackageRequiredMessage:n}=await l();if(e(t)===`binary`)return n(t)}}async function v(e,t,c){if(!(!o(e.platform)||!t))return r(t)?s(e)?void 0:e.kind===`device`?i(c,t):n(t)?a:c??await y(e,t):await b(e,t)}async function y(e,t){try{let{resolveIosSimulatorDeepLinkBundleId:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}catch{return}}async function b(e,t){try{let{resolveIosApp:n}=await import(`./app-resolution-facade.js`);return await n(e,t)}catch{return}}function x(e,t){return e.platform===`android`&&!!(t&&r(t))}function S(e){let t=e?.trim();if(!(!t||r(t)||!t.includes(`.`)))return t}async function C(e,t,n){return e.platform===`harmonyos`?S(t)??n:await v(e,t,n)??await w(e,t)??(x(e,t)?n:void 0)}async function w(e,t){if(!(e.platform!==`android`||!t))try{let{resolveAndroidPackageForOpen:n}=await l();return await n(e,t)}catch{return}}export{_ as i,f as n,C as r,u as t};
|