peachsim 0.1.1667 → 0.1.1673

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.
Files changed (178) hide show
  1. package/README.md +1 -1
  2. package/cli/bridge-flow-runner.ts +4 -1
  3. package/cli/commands/coverage-swift.ts +291 -0
  4. package/cli/commands/coverage.ts +168 -24
  5. package/cli/commands/diagnose.ts +1 -19
  6. package/cli/commands/react.ts +3 -18
  7. package/cli/commands/screenshot.ts +1 -1
  8. package/cli/commands/screenshots-capture.ts +1 -1
  9. package/cli/drivers/playwright-provisioning.ts +1 -4
  10. package/cli/drivers/playwright.ts +15 -1
  11. package/cli/scene-video.ts +1 -1
  12. package/cli/ui.ts +20 -0
  13. package/cli/ws-bridge.ts +7 -36
  14. package/detox/frame-identity.cjs +21 -0
  15. package/detox/frame-identity.d.cts +6 -0
  16. package/detox/index.ts +39 -33
  17. package/detox/jest-environment.cjs +4 -1
  18. package/detox/jest-setup-after-env.cjs +0 -4
  19. package/detox/navigation-lifecycle.ts +2 -2
  20. package/detox/proof-observer.ts +126 -0
  21. package/dist-lib/agent-daemon-client.cjs +29 -1
  22. package/dist-lib/agent-events.cjs +1 -1
  23. package/dist-lib/attached-projects.cjs +10 -1
  24. package/dist-lib/auth/shared-session.cjs +1 -1
  25. package/dist-lib/backend-origin.cjs +1 -1
  26. package/dist-lib/beta.cjs +1 -1
  27. package/dist-lib/beta.mjs +1 -1
  28. package/dist-lib/bridge-constants.cjs +1 -1
  29. package/dist-lib/bridge-contract-input.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.mjs +1 -1
  31. package/dist-lib/bridge-contract.cjs +1 -1
  32. package/dist-lib/bridge-contract.mjs +1 -1
  33. package/dist-lib/bundle-channel.cjs +530 -154
  34. package/dist-lib/capture-contract.cjs +1 -1
  35. package/dist-lib/capture-contract.mjs +1 -1
  36. package/dist-lib/cloud-contract.cjs +1 -1
  37. package/dist-lib/cloud-contract.mjs +1 -1
  38. package/dist-lib/cloud-test-args.cjs +1 -1
  39. package/dist-lib/cloud-test-args.mjs +1 -1
  40. package/dist-lib/cloud.cjs +1 -1
  41. package/dist-lib/cloud.mjs +1 -1
  42. package/dist-lib/config.cjs +1 -1
  43. package/dist-lib/config.mjs +1 -1
  44. package/dist-lib/detox/index.cjs +5074 -7353
  45. package/dist-lib/detox/jest-environment.cjs +4 -1
  46. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  47. package/dist-lib/expo-swift-bundle.cjs +578 -151
  48. package/dist-lib/expo-swift-metadata.cjs +1 -1
  49. package/dist-lib/expo-swift-metadata.mjs +1 -1
  50. package/dist-lib/home-paths.cjs +1 -1
  51. package/dist-lib/host/bridge-host.cjs +660 -192
  52. package/dist-lib/host/fetch-proxy-handler.cjs +2 -2
  53. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  54. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  55. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  56. package/dist-lib/host/websocket-proxy.cjs +1 -1
  57. package/dist-lib/index.cjs +206 -6
  58. package/dist-lib/jump-to-source-babel.cjs +1 -1
  59. package/dist-lib/jump-to-source-native.cjs +1 -1
  60. package/dist-lib/kotlin-host.cjs +1 -1
  61. package/dist-lib/menu.cjs +1 -1
  62. package/dist-lib/menu.mjs +1 -1
  63. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  64. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  65. package/dist-lib/metro-production-bundle.cjs +10 -1
  66. package/dist-lib/metro-production-bundle.mjs +12 -1
  67. package/dist-lib/metro.cjs +155 -5
  68. package/dist-lib/native-app-identity-project.cjs +43 -5
  69. package/dist-lib/native-app-identity-project.mjs +43 -5
  70. package/dist-lib/native-app-identity.cjs +1 -1
  71. package/dist-lib/native-app-identity.mjs +1 -1
  72. package/dist-lib/native-firebase-metadata.cjs +1 -1
  73. package/dist-lib/native-firebase-metadata.mjs +1 -1
  74. package/dist-lib/plist.cjs +1 -1
  75. package/dist-lib/plist.mjs +1 -1
  76. package/dist-lib/profiles.cjs +21 -1
  77. package/dist-lib/public-brand.cjs +1 -1
  78. package/dist-lib/public-origins-lib-esm.json +73 -27
  79. package/dist-lib/public-origins-lib-static.json +1 -1
  80. package/dist-lib/public-origins-lib.json +563 -183
  81. package/dist-lib/react-native-host-modules.cjs +1 -1
  82. package/dist-lib/react-native-host-modules.mjs +1 -1
  83. package/dist-lib/reap-browser.cjs +964 -0
  84. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  85. package/dist-lib/sdk.cjs +1 -1
  86. package/dist-lib/sdk.mjs +1 -1
  87. package/dist-lib/skills.cjs +963 -521
  88. package/dist-lib/swift-compile.cjs +276 -86
  89. package/dist-lib/swift-compile.mjs +276 -86
  90. package/dist-lib/swift-package.cjs +34 -4
  91. package/dist-lib/swift-package.mjs +33 -4
  92. package/dist-lib/swift-submit.cjs +2 -2
  93. package/dist-lib/swift-submit.mjs +2 -2
  94. package/dist-lib/swift-toolchain.cjs +25 -44
  95. package/dist-lib/swift.cjs +1 -1
  96. package/dist-lib/vite-swift.cjs +579 -113
  97. package/dist-lib/vite.cjs +61 -2
  98. package/dist-lib/worklet-executable.cjs +1 -1
  99. package/dist-lib/worklet-executable.mjs +1 -1
  100. package/dist-types/packages/peach-engine/src/engine/clipboardContract.d.ts +7 -0
  101. package/dist-types/packages/peach-engine/src/engine/glass-material.d.ts +1 -1
  102. package/dist-types/packages/peach-engine/src/engine/image-loader.d.ts +2 -0
  103. package/dist-types/packages/peach-engine/src/engine/inspect-outline.d.ts +2 -1
  104. package/dist-types/packages/peach-engine/src/engine/liquid-glass.d.ts +1 -0
  105. package/dist-types/packages/peach-engine/src/engine/paint-boundary.d.ts +3 -1
  106. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +7 -0
  107. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime-kind.d.ts +24 -0
  108. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +4 -2
  109. package/dist-types/packages/peach-engine/src/settings/devices.d.ts +1 -0
  110. package/dist-types/packages/peach-globals/src/clipboardBridgeContract.d.ts +18 -0
  111. package/dist-types/packages/peach-globals/src/index.d.ts +1 -1
  112. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  113. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  114. package/package.json +1 -1
  115. package/runtime-companion.json +1 -1
  116. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CFString.h +2 -0
  117. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h +36 -0
  118. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStore.h +439 -0
  119. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStoreCopySpecific.h +216 -0
  120. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStoreKey.h +267 -0
  121. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetwork.h +204 -0
  122. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkConfiguration.h +1393 -0
  123. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkConnection.h +568 -0
  124. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkReachability.h +369 -0
  125. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferences.h +473 -0
  126. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferencesPath.h +179 -0
  127. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferencesSetSpecific.h +95 -0
  128. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCSchemaDefinitions.h +2395 -0
  129. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SystemConfiguration.h +184 -0
  130. package/sdk/ios/usr/include/libkern/OSByteOrder.h +315 -0
  131. package/sdk/ios/usr/include/libkern/machine/OSByteOrder.h +147 -0
  132. package/src/bridge-contract.ts +42 -0
  133. package/src/chromium-admission.ts +196 -0
  134. package/src/host/bridge-host.ts +6 -43
  135. package/src/launch-deadline.ts +74 -0
  136. package/src/nitro-adapter.lock.json +3 -3
  137. package/src/profiles.ts +21 -0
  138. package/src/react-native-coverage/capability-reference-resolution.ts +402 -0
  139. package/src/react-native-coverage/capability-source-references.ts +1296 -0
  140. package/src/react-native-coverage/native-typescript-parser.ts +74 -0
  141. package/src/react-native-coverage/project-aliases.ts +207 -0
  142. package/src/react-native-coverage/verified-reach.ts +47 -0
  143. package/src/reap-browser.ts +1019 -0
  144. package/src/skills/builtin/a11y-review.ts +1 -1
  145. package/src/skills/builtin/perf-profile.ts +1 -1
  146. package/src/skills/builtin/screenshot-all.ts +1 -1
  147. package/src/skills/builtin/visual-diff.ts +1 -1
  148. package/src/swift-compile.ts +107 -56
  149. package/src/swift-coverage/indexdump.ts +80 -0
  150. package/src/swift-coverage/indexing.ts +147 -0
  151. package/src/swift-coverage/package.ts +230 -0
  152. package/src/swift-coverage/provenance.ts +47 -0
  153. package/src/swift-coverage/reader.ts +81 -0
  154. package/src/swift-coverage/source.ts +252 -0
  155. package/src/swift-coverage/types.ts +58 -0
  156. package/src/swift-coverage/xcode-assets.ts +175 -0
  157. package/src/swift-coverage/xcode-bridging.ts +160 -0
  158. package/src/swift-coverage/xcode-packages.ts +251 -0
  159. package/src/swift-coverage/xcode-strings.ts +78 -0
  160. package/src/swift-coverage/xcode.ts +656 -0
  161. package/src/swift-distribution.lock.json +8 -8
  162. package/src/swift-host.ts +21 -1
  163. package/src/swift-objc-import.ts +191 -27
  164. package/src/swift-objc-standin.ts +4 -2
  165. package/src/swift-package-manifest.ts +134 -13
  166. package/src/swift-package.ts +46 -4
  167. package/src/swift-submit.ts +2 -1
  168. package/src/swift-toolchain.ts +36 -61
  169. package/src/worker-system-chunks.ts +3 -10
  170. package/src/xcode-project.ts +5 -5
  171. package/detox/attempt-events.cjs +0 -914
  172. package/detox/attempt-events.d.cts +0 -113
  173. package/detox/motion-change.cjs +0 -524
  174. package/detox/motion-change.d.cts +0 -140
  175. package/detox/motion-leg-starts.cjs +0 -20
  176. package/detox/motion-leg-starts.d.cts +0 -8
  177. package/detox/proof-frame.cjs +0 -190
  178. package/detox/record-block-execution.cjs +0 -78
@@ -0,0 +1,196 @@
1
+ // host-wide admission for playwright chromium launches. every launcher on a
2
+ // machine (agents' probes, peach sim hosts, captures, tests) shares one queue,
3
+ // so a burst of sessions waits its turn instead of piling GPU chromes onto the
4
+ // box until it swap-thrashes. queue waits belong to the caller's run budget,
5
+ // before capture startup deadlines, and must be cancelled with that caller.
6
+ //
7
+ // each launch (or detox file's sequential launches) reserves one ticket named
8
+ // `<pid>-<start>-<random>` in a fixed
9
+ // directory, then waits until its ticket ranks inside the limit among live
10
+ // tickets ordered by creation time. a ticket is released when the browser
11
+ // closes or the process exits; a ticket whose process died (SIGKILL) is pruned
12
+ // by the next waiter. the ranking is a fair FIFO without a lock: tickets only
13
+ // ever leave from ahead of a waiter, never cut in front of it. the peach bridge
14
+ // reads the same queue to free an idle sim's slot only while a launch waits.
15
+ //
16
+ // self-contained on purpose: packages/peach-engine/src/playwright-sim-host.ts
17
+ // inlines both functions into its CJS source with toString(), so they take node
18
+ // modules and each other as arguments and close over nothing.
19
+
20
+ export type ChromiumQueueDeps = {
21
+ fs: typeof import('node:fs')
22
+ os: typeof import('node:os')
23
+ path: typeof import('node:path')
24
+ childProcess: typeof import('node:child_process')
25
+ }
26
+
27
+ export type ChromiumAdmissionDeps = ChromiumQueueDeps & {
28
+ // the label printed while waiting, so a stalled caller says why
29
+ label: string
30
+ // readChromiumQueue, passed in because an inlined copy cannot name it
31
+ readQueue: typeof readChromiumQueue
32
+ signal?: AbortSignal
33
+ }
34
+
35
+ export type ChromiumQueue = {
36
+ dir: string
37
+ limit: number
38
+ // live tickets in creation order: the first `limit` hold slots, the rest wait
39
+ tickets: string[]
40
+ }
41
+
42
+ // reads the machine's queue, pruning tickets whose process died. `verified`
43
+ // caches each ticket's pid start-time match across reads, and `own` is never
44
+ // pruned.
45
+ export function readChromiumQueue(
46
+ deps: ChromiumQueueDeps,
47
+ verified: Map<string, boolean>,
48
+ own?: string,
49
+ ): ChromiumQueue {
50
+ const { fs, os, path, childProcess } = deps
51
+ // a session TMPDIR is per agent, so the queue lives at the machine's /tmp
52
+ const dir = path.join(
53
+ process.platform === 'win32' ? os.tmpdir() : '/tmp',
54
+ 'chromium-admission',
55
+ )
56
+ fs.mkdirSync(dir, { recursive: true })
57
+ // one GPU chrome per three cores: a sim chrome holds its gpu process, a
58
+ // renderer and a compositor busy, and the box keeps cores for builds. the
59
+ // queue is machine-wide, so every caller ranks against the machine's cores:
60
+ // a caller pinned to a few cpus must not read a smaller limit than the rest
61
+ const limit = Math.max(2, Math.floor(os.cpus().length / 3))
62
+
63
+ // a pid alone can be reused; the ticket's start second must match the
64
+ // process's own start time, read once per ticket
65
+ const live = (entry: string): boolean => {
66
+ const match = /^(\d+)-(\d+)-/.exec(entry)
67
+ if (!match) return false
68
+ const pid = Number(match[1])
69
+ try {
70
+ process.kill(pid, 0)
71
+ } catch (err) {
72
+ // EPERM: alive, owned by another user
73
+ if (!(err instanceof Error && 'code' in err && err.code === 'EPERM')) return false
74
+ }
75
+ const known = verified.get(entry)
76
+ if (known !== undefined) return known
77
+ let same = pid === process.pid
78
+ if (!same) {
79
+ let started = ''
80
+ try {
81
+ started = childProcess
82
+ .execFileSync('ps', ['-p', String(pid), '-o', 'lstart='], { encoding: 'utf8' })
83
+ .trim()
84
+ } catch (err) {
85
+ // ps exits 1 when the pid is gone; any other failure (spawn pressure,
86
+ // timeout) proves nothing, so the ticket stays and is checked again
87
+ const gone = err instanceof Error && 'status' in err && err.status === 1
88
+ if (!gone) return true
89
+ }
90
+ const startedAt = Date.parse(started)
91
+ if (started && Number.isNaN(startedAt)) return true
92
+ same = Math.abs(startedAt / 1000 - Number(match[2])) <= 2
93
+ }
94
+ verified.set(entry, same)
95
+ return same
96
+ }
97
+
98
+ const tickets: { entry: string; created: bigint }[] = []
99
+ for (const entry of fs.readdirSync(dir)) {
100
+ if (entry !== own && !live(entry)) {
101
+ try {
102
+ fs.unlinkSync(path.join(dir, entry))
103
+ } catch {}
104
+ continue
105
+ }
106
+ try {
107
+ // tickets are never written after creation, so ctime is creation time
108
+ tickets.push({
109
+ entry,
110
+ created: fs.statSync(path.join(dir, entry), { bigint: true }).ctimeNs,
111
+ })
112
+ } catch {}
113
+ }
114
+ tickets.sort((a, b) =>
115
+ a.created === b.created
116
+ ? a.entry < b.entry
117
+ ? -1
118
+ : 1
119
+ : a.created < b.created
120
+ ? -1
121
+ : 1,
122
+ )
123
+ return { dir, limit, tickets: tickets.map((t) => t.entry) }
124
+ }
125
+
126
+ export async function acquireChromiumAdmission(
127
+ deps: ChromiumAdmissionDeps,
128
+ ): Promise<() => void> {
129
+ const { fs, path, label, readQueue, signal } = deps
130
+ signal?.throwIfAborted()
131
+ const queuedAt = Date.now()
132
+ const verified = new Map<string, boolean>()
133
+ const startedAt = Math.round(Date.now() / 1000 - process.uptime())
134
+ const name = `${process.pid}-${startedAt}-${Math.random().toString(36).slice(2, 10)}`
135
+ const ticket = path.join(readQueue(deps, verified, name).dir, name)
136
+ fs.closeSync(fs.openSync(ticket, 'wx'))
137
+ let released = false
138
+ const release = () => {
139
+ if (released) return
140
+ released = true
141
+ process.removeListener('exit', release)
142
+ try {
143
+ fs.unlinkSync(ticket)
144
+ } catch {}
145
+ process.stderr.write(`[chromium-admission] ${label}: released ${name}\n`)
146
+ }
147
+ process.on('exit', release)
148
+ signal?.addEventListener('abort', release, { once: true })
149
+
150
+ let waited = false
151
+ try {
152
+ while (true) {
153
+ signal?.throwIfAborted()
154
+ const { limit, tickets } = readQueue(deps, verified, name)
155
+ const rank = tickets.indexOf(name)
156
+ if (rank < 0) {
157
+ throw new Error(`[chromium-admission] ${label}: reservation disappeared`)
158
+ }
159
+ if (rank < limit) {
160
+ process.stderr.write(
161
+ `[chromium-admission] ${label}: admitted ${name} after ${Date.now() - queuedAt}ms\n`,
162
+ )
163
+ return release
164
+ }
165
+ if (!waited) {
166
+ const holders = tickets.slice(0, limit).map((t) => t.split('-')[0])
167
+ process.stderr.write(
168
+ `[chromium-admission] ${label}: ${limit} chromium launches already run on this machine (pids ${holders.join(' ')}), queued ${rank - limit + 1}\n`,
169
+ )
170
+ waited = true
171
+ }
172
+ await new Promise<void>((resolve, reject) => {
173
+ const abort = () => {
174
+ clearTimeout(timer)
175
+ signal?.removeEventListener('abort', abort)
176
+ reject(
177
+ new Error(`[chromium-admission] ${label}: cancelled`, {
178
+ cause: signal?.reason,
179
+ }),
180
+ )
181
+ }
182
+ const timer = setTimeout(() => {
183
+ signal?.removeEventListener('abort', abort)
184
+ resolve()
185
+ }, 500)
186
+ signal?.addEventListener('abort', abort, { once: true })
187
+ if (signal?.aborted) abort()
188
+ })
189
+ }
190
+ } catch (error) {
191
+ release()
192
+ throw error
193
+ } finally {
194
+ signal?.removeEventListener('abort', release)
195
+ }
196
+ }
@@ -5,7 +5,6 @@ import { createServer, type IncomingMessage, type ServerResponse } from 'http'
5
5
  import os from 'os'
6
6
  import path from 'path'
7
7
  import { WebSocket, WebSocketServer } from 'ws'
8
- import { readChromiumQueue } from '../../../../scripts/lib/chromium-admission.ts'
9
8
  import { automaticPeachUpdatesEnabled } from '../automatic-update-policy.ts'
10
9
  import {
11
10
  AUTOMATION_SIM_IDLE_REAP_TTL_MS,
@@ -13,7 +12,12 @@ import {
13
12
  SOOTSIM_BRIDGE_SIM_CLOSE_CODE,
14
13
  SOOTSIM_BRIDGE_SIM_CLOSE_REASON,
15
14
  } from '../bridge-constants.ts'
16
- import { commandWritesSim, type WsCommand } from '../bridge-contract.ts'
15
+ import {
16
+ commandWritesSim,
17
+ type BridgeSimInfo,
18
+ type WsCommand,
19
+ } from '../bridge-contract.ts'
20
+ import { readChromiumQueue } from '../chromium-admission.ts'
17
21
  import { getCliVersion } from '../cli-version.ts'
18
22
  import { activeDesktopHostApp } from '../desktop-host-delivery.ts'
19
23
  import { handleExpoSwiftRequest } from '../expo-swift-host.ts'
@@ -73,47 +77,6 @@ import {
73
77
 
74
78
  const SOOTSIM_CROSS_ORIGIN_EMBEDDER_POLICY = 'require-corp'
75
79
 
76
- export interface BridgeSimInfo {
77
- id: string
78
- origin?: string
79
- url?: string
80
- title?: string
81
- userAgent?: string
82
- connectedAt: number
83
- lastSeenAt: number
84
- lastActiveAt?: number
85
- isPrimary: boolean
86
- readyState: 'open' | 'closing' | 'closed'
87
- attachedCliCount?: number
88
- lockedBy?: string
89
- lockedByKind?: 'cli' | 'user-active'
90
- lockExpiresAt?: number
91
- // true when the lease belongs to the caller asking for this list. the
92
- // server computes it because `lockedBy` is a display string (a cliLabel
93
- // like "open --describe", or "active user") and cannot be compared
94
- // against an identity key by the client.
95
- lockedByMe?: boolean
96
- userFocused?: boolean
97
- userVisible?: boolean
98
- visibilityState?: string
99
- documentFocused?: boolean
100
- /** registration "kind" — lets a single daemon host multiple surface
101
- * types. omitted / unknown defaults to 'sootsim'. the contrast web
102
- * IDE registers with kind='contrast'; CLI consumers filter by this
103
- * rather than running a parallel bridge. */
104
- kind?: string
105
- /** opaque metadata supplied at register time (e.g. projectId, route,
106
- * attached iOS sim id for a contrast tab). free-form by design — the
107
- * daemon does not interpret it, only stores + reports it back. */
108
- meta?: Record<string, unknown>
109
- /** why a retained disconnected sim left, e.g. which owned browser host
110
- * exited. present only on readyState 'closed' entries served with
111
- * includeRetained. */
112
- disconnectCause?: string
113
- /** epoch-ms the sim socket closed. present with disconnectCause. */
114
- disconnectedAt?: number
115
- }
116
-
117
80
  export interface BridgeLockInfo {
118
81
  by: string
119
82
  expiresInMs: number
@@ -0,0 +1,74 @@
1
+ import { execFileSync } from 'node:child_process'
2
+ import { readFileSync } from 'node:fs'
3
+ import * as os from 'node:os'
4
+ import * as path from 'node:path'
5
+
6
+ // the team machine load governor SIGSTOPs a job and records the held pids in
7
+ // this ledger (`{ [rootPid]: [{ pid }] }`, `{}` when nothing is held). a plain
8
+ // setTimeout keeps running across that hold, and a stopped process also wakes
9
+ // with its whole budget already spent, so a browser launch the governor held
10
+ // fails for load it never caused. this deadline advances only while no held pid
11
+ // is this process, one of its ancestors, or one of its descendants, and never
12
+ // counts a gap longer than a few ticks (this process itself being stopped).
13
+ const LEDGER_PATH = path.join(
14
+ process.env.TM_HOME || path.join(os.homedir(), '.team-machine'),
15
+ 'governor-pauses.json',
16
+ )
17
+ const TICK_MS = 500
18
+ const MAX_COUNTED_GAP_MS = TICK_MS * 3
19
+
20
+ function heldPids(): number[] {
21
+ try {
22
+ const ledger: Record<string, { pid: number }[]> = JSON.parse(
23
+ readFileSync(LEDGER_PATH, 'utf8'),
24
+ )
25
+ return Object.values(ledger).flatMap((procs) => procs.map((proc) => proc.pid))
26
+ } catch {
27
+ return []
28
+ }
29
+ }
30
+
31
+ // true when any held pid is this process, an ancestor, or a descendant.
32
+ function holdsThisProcessTree(held: number[]): boolean {
33
+ const parents = new Map<number, number>()
34
+ for (const line of execFileSync('ps', ['-A', '-o', 'pid=,ppid='], {
35
+ encoding: 'utf8',
36
+ }).split('\n')) {
37
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number)
38
+ if (pid && ppid !== undefined) parents.set(pid, ppid)
39
+ }
40
+ const ancestors = new Set<number>()
41
+ for (let pid: number | undefined = process.pid, hops = 0; pid && hops < 64; hops++) {
42
+ ancestors.add(pid)
43
+ pid = parents.get(pid)
44
+ }
45
+ // a held pid counts when it is this process or an ancestor, or when this
46
+ // process is on its own parent chain. sharing a common ancestor does not.
47
+ return held.some((start) => {
48
+ if (ancestors.has(start)) return true
49
+ for (let pid = parents.get(start), hops = 0; pid && hops < 64; hops++) {
50
+ if (pid === process.pid) return true
51
+ pid = parents.get(pid)
52
+ }
53
+ return false
54
+ })
55
+ }
56
+
57
+ // calls `onExpire` once `budgetMs` of unheld time has passed. returns cancel.
58
+ export function startLaunchDeadline(budgetMs: number, onExpire: () => void): () => void {
59
+ let remaining = budgetMs
60
+ let last = Date.now()
61
+ const poll = setInterval(() => {
62
+ const now = Date.now()
63
+ const elapsed = Math.min(now - last, MAX_COUNTED_GAP_MS)
64
+ last = now
65
+ const held = heldPids()
66
+ if (held.length > 0 && holdsThisProcessTree(held)) return
67
+ remaining -= elapsed
68
+ if (remaining <= 0) {
69
+ clearInterval(poll)
70
+ onExpire()
71
+ }
72
+ }, TICK_MS)
73
+ return () => clearInterval(poll)
74
+ }
@@ -16,11 +16,11 @@
16
16
  "checksum": "1e19ea768fd4e821aae34b8966c4ddcee45615c4b3cf018979b061aee2fb5504"
17
17
  },
18
18
  "framework": {
19
- "distribution": "ca4dfda0ca14bc49",
19
+ "distribution": "433f607a19978269",
20
20
  "wireAbi": "ed0b01fcc0a79236d88ef9ac7950ac30932dfc19c19112c69d1d6a039a489292"
21
21
  },
22
22
  "archive": {
23
- "sha256": "e5c94039c146c3f35b1a9e32368c2a6c605140be79e386cac57ad2bae06a9a3d",
24
- "size": 31177
23
+ "sha256": "17c176f0bee02e9aa3417d12328986d80c489c8734337d2af7b53f2393a5119c",
24
+ "size": 31176
25
25
  }
26
26
  }
package/src/profiles.ts CHANGED
@@ -53,6 +53,27 @@ export function playwrightProfileUserDataDir(profileId: string): string {
53
53
  return path.join(profilesDir(), 'playwright', normalizeProfileId(profileId))
54
54
  }
55
55
 
56
+ // chrome records its owner as the SingletonLock symlink target "<host>-<pid>".
57
+ // a lock whose pid is gone is stale and chrome reclaims it itself.
58
+ export function liveBrowserPidForPlaywrightProfile(profileId: string): number | null {
59
+ let target: string
60
+ try {
61
+ target = fs.readlinkSync(
62
+ path.join(playwrightProfileUserDataDir(profileId), 'SingletonLock'),
63
+ )
64
+ } catch {
65
+ return null
66
+ }
67
+ const pid = Number(target.slice(target.lastIndexOf('-') + 1))
68
+ if (!Number.isInteger(pid) || pid < 1) return null
69
+ try {
70
+ process.kill(pid, 0)
71
+ return pid
72
+ } catch (error) {
73
+ return error instanceof Error && Reflect.get(error, 'code') === 'EPERM' ? pid : null
74
+ }
75
+ }
76
+
56
77
  function readIndexRaw(): ProfileIndex {
57
78
  try {
58
79
  const parsed = JSON.parse(