peachsim 0.1.709 → 0.1.711

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 (87) hide show
  1. package/cli/commands/control.ts +55 -1
  2. package/cli/commands/serve.ts +30 -0
  3. package/cli/current-sim.ts +15 -1
  4. package/cli/dev-build-freshness.ts +205 -0
  5. package/cli/drivers/playwright-sim-host.ts +14 -1
  6. package/cli/drivers/playwright.ts +36 -3
  7. package/cli/main.ts +8 -0
  8. package/cli/parent-pid.ts +91 -15
  9. package/cli/ws-bridge.ts +5 -0
  10. package/detox/index.ts +20 -7
  11. package/dist-lib/agent-daemon-client.cjs +1 -1
  12. package/dist-lib/agent-events.cjs +1 -1
  13. package/dist-lib/agent-identity.cjs +1 -1
  14. package/dist-lib/agent-sessions.cjs +1 -1
  15. package/dist-lib/attached-projects.cjs +1 -1
  16. package/dist-lib/auth/shared-session.cjs +1 -1
  17. package/dist-lib/backend-origin.cjs +1 -1
  18. package/dist-lib/beta.cjs +1 -1
  19. package/dist-lib/beta.mjs +1 -1
  20. package/dist-lib/bridge-constants.cjs +1 -1
  21. package/dist-lib/bridge-contract-input.cjs +1 -1
  22. package/dist-lib/bridge-contract-input.mjs +1 -1
  23. package/dist-lib/bridge-contract.cjs +1 -1
  24. package/dist-lib/bridge-contract.mjs +1 -1
  25. package/dist-lib/capture-contract.cjs +1 -1
  26. package/dist-lib/capture-contract.mjs +1 -1
  27. package/dist-lib/cli-constants.cjs +1 -1
  28. package/dist-lib/cloud-contract.cjs +1 -1
  29. package/dist-lib/cloud-contract.mjs +1 -1
  30. package/dist-lib/cloud-test-args.cjs +1 -1
  31. package/dist-lib/cloud-test-args.mjs +1 -1
  32. package/dist-lib/cloud.cjs +1 -1
  33. package/dist-lib/cloud.mjs +1 -1
  34. package/dist-lib/config.cjs +1 -1
  35. package/dist-lib/detox/index.cjs +89 -11
  36. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  37. package/dist-lib/home-paths.cjs +1 -1
  38. package/dist-lib/host/bridge-host.cjs +172 -30
  39. package/dist-lib/host/fetch-proxy-handler.cjs +45 -21
  40. package/dist-lib/host/fetch-proxy-overrides.cjs +2 -2
  41. package/dist-lib/host/fetch-proxy-overrides.mjs +2 -2
  42. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  43. package/dist-lib/host/websocket-proxy.cjs +1 -1
  44. package/dist-lib/index.cjs +78 -5
  45. package/dist-lib/jump-to-source-babel.cjs +1 -1
  46. package/dist-lib/jump-to-source-native.cjs +1 -1
  47. package/dist-lib/kotlin-host.cjs +1 -1
  48. package/dist-lib/menu.cjs +1 -1
  49. package/dist-lib/menu.mjs +1 -1
  50. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  51. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  52. package/dist-lib/metro-production-bundle.cjs +1 -1
  53. package/dist-lib/metro-production-bundle.mjs +1 -1
  54. package/dist-lib/metro.cjs +1 -1
  55. package/dist-lib/native-app-identity.cjs +1 -1
  56. package/dist-lib/native-app-identity.mjs +1 -1
  57. package/dist-lib/native-firebase-metadata.cjs +1 -1
  58. package/dist-lib/native-firebase-metadata.mjs +1 -1
  59. package/dist-lib/plist.cjs +1 -1
  60. package/dist-lib/plist.mjs +1 -1
  61. package/dist-lib/profiles.cjs +1 -1
  62. package/dist-lib/public-brand.cjs +1 -1
  63. package/dist-lib/react-native-host-modules.cjs +1 -1
  64. package/dist-lib/react-native-host-modules.mjs +1 -1
  65. package/dist-lib/render-mode.cjs +1 -1
  66. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  67. package/dist-lib/sdk.cjs +1 -1
  68. package/dist-lib/sdk.mjs +1 -1
  69. package/dist-lib/skills.cjs +331 -51
  70. package/dist-lib/swift-compile.cjs +8 -2
  71. package/dist-lib/swift-compile.mjs +8 -2
  72. package/dist-lib/swift-package.cjs +1 -1
  73. package/dist-lib/swift-package.mjs +1 -1
  74. package/dist-lib/swift-submit.cjs +2 -2
  75. package/dist-lib/swift-submit.mjs +2 -2
  76. package/dist-lib/swift-toolchain.cjs +1 -1
  77. package/dist-lib/swift.cjs +1 -1
  78. package/dist-lib/vite-swift.cjs +9 -3
  79. package/dist-lib/vite.cjs +1 -1
  80. package/package.json +2 -1
  81. package/src/host/bridge-host.ts +65 -0
  82. package/src/host/fetch-proxy-handler.ts +52 -23
  83. package/src/host/fetch-proxy-overrides.ts +5 -1
  84. package/src/host/fetch-proxy-transport.ts +82 -0
  85. package/src/runtime-assets.ts +1 -1
  86. package/src/swift-compile.ts +8 -2
  87. package/src/swift-submit.ts +2 -1
@@ -881,6 +881,9 @@ export interface BuildShellUrlOptions {
881
881
  // shell pins at boot over the device profile's own version. an oracle on a
882
882
  // newer os than the profile compares only when the sim runs that os era.
883
883
  osVersion?: string
884
+ // appearance scheme (light|dark|auto) stamped as ?theme=, which the shell
885
+ // reads at boot over the persisted scheme. set by `peach open -t/--theme`.
886
+ theme?: string
884
887
  resolvedBundle?: ResolvedDevBundle
885
888
  project?: ResolvedAppProject | null
886
889
  // deterministic-capture mode, stamped onto the engine URL as ?proof=1. the
@@ -951,6 +954,7 @@ export async function buildShellUrl(
951
954
  !opts.posture &&
952
955
  !opts.orientation &&
953
956
  !opts.osVersion &&
957
+ !opts.theme &&
954
958
  !opts.env?.length &&
955
959
  !opts.dotEnv
956
960
  )
@@ -961,6 +965,7 @@ export async function buildShellUrl(
961
965
  if (opts.posture) url.searchParams.set('posture', opts.posture)
962
966
  if (opts.orientation) url.searchParams.set('orientation', opts.orientation)
963
967
  if (opts.osVersion) url.searchParams.set('osVersion', opts.osVersion)
968
+ if (opts.theme) url.searchParams.set('theme', opts.theme)
964
969
  if (opts.proof) url.searchParams.set('proof', '1')
965
970
  for (const entry of opts.env ?? []) url.searchParams.append('env', entry)
966
971
  return url.toString()
@@ -1179,6 +1184,21 @@ export function signalDriverLaunchConnected(result: DriverLaunchResult): boolean
1179
1184
  }
1180
1185
  }
1181
1186
 
1187
+ // the playwright host exits fast with [unserved] when its initial navigation
1188
+ // is connection-refused: nothing serves the url, so no sim can ever
1189
+ // register. surface that as the failure instead of the generic host-crashed
1190
+ // line below.
1191
+ function readUnservedUrl(result: DriverLaunchResult): string | null {
1192
+ if (!result.diagnosticLogPath) return null
1193
+ try {
1194
+ const detail = fs.readFileSync(result.diagnosticLogPath, 'utf8')
1195
+ const match = detail.match(/\[unserved\] nothing serves (\S+)/)
1196
+ return match ? match[1] : null
1197
+ } catch {
1198
+ return null
1199
+ }
1200
+ }
1201
+
1182
1202
  function printDriverDiagnosticLogTail(result: DriverLaunchResult) {
1183
1203
  if (!result.diagnosticLogPath) return
1184
1204
  try {
@@ -1509,6 +1529,8 @@ export async function runOpenCommand(
1509
1529
  '--os-version',
1510
1530
  '--viewport',
1511
1531
  '--env',
1532
+ '--theme',
1533
+ '-t',
1512
1534
  ],
1513
1535
  })
1514
1536
  const requestedProfileId = args.find((_, i) => args[i - 1] === '--profile')
@@ -1552,6 +1574,30 @@ export async function runOpenCommand(
1552
1574
  rnxExit(1)
1553
1575
  }
1554
1576
 
1577
+ // -t / --theme <light|dark|auto> seeds the appearance for the opened sim,
1578
+ // stamped on the engine URL as ?theme= next to ?device=: the shell reads it
1579
+ // at boot over the persisted scheme. without this the flag fell into the
1580
+ // positional target (`peach open -t dark` opened `?open=-t`) and the theme
1581
+ // was silently dropped. validated up here so a bad flag fails before the
1582
+ // bridge spawns.
1583
+ const themeFlagIndex = args.findIndex((arg) => arg === '--theme' || arg === '-t')
1584
+ const themeArg = themeFlagIndex === -1 ? undefined : args[themeFlagIndex + 1]
1585
+ if (themeFlagIndex !== -1 && themeArg === undefined) {
1586
+ console.error(' peach open: --theme expects light, dark, or auto')
1587
+ rnxExit(1)
1588
+ }
1589
+ if (
1590
+ themeArg !== undefined &&
1591
+ themeArg !== 'light' &&
1592
+ themeArg !== 'dark' &&
1593
+ themeArg !== 'auto'
1594
+ ) {
1595
+ console.error(
1596
+ ` peach open: --theme must be light, dark, or auto, got "${themeArg}"`,
1597
+ )
1598
+ rnxExit(1)
1599
+ }
1600
+
1555
1601
  if (isAppDeepLinkTarget(target)) {
1556
1602
  if (openInNewSim) {
1557
1603
  console.error(
@@ -1798,6 +1844,7 @@ export async function runOpenCommand(
1798
1844
  posture: postureArg,
1799
1845
  orientation: orientationArg,
1800
1846
  osVersion: osVersionArg,
1847
+ theme: themeArg,
1801
1848
  resolvedBundle,
1802
1849
  project,
1803
1850
  proof: args.includes('--proof'),
@@ -2041,7 +2088,14 @@ export async function runOpenCommand(
2041
2088
  )
2042
2089
  if (outcome.kind === 'host-exit') {
2043
2090
  printDriverDiagnosticLogTail(result)
2044
- console.error(` ${driver.name} host crashed — sim is no longer attached`)
2091
+ const unserved = readUnservedUrl(result)
2092
+ if (unserved) {
2093
+ console.error(
2094
+ ` nothing serves ${unserved} — start the shell or daemon that owns it, then try again`,
2095
+ )
2096
+ } else {
2097
+ console.error(` ${driver.name} host crashed — sim is no longer attached`)
2098
+ }
2045
2099
  rnxExit(1)
2046
2100
  }
2047
2101
  if (outcome.kind === 'timeout') {
@@ -15,7 +15,15 @@ import {
15
15
  readDaemonLockfile,
16
16
  } from '../../src/home-paths'
17
17
  import { SootSimBridgeHost } from '../../src/host/bridge-host'
18
+ import {
19
+ findMonorepoRoot,
20
+ resolveDevCheckoutRuntimeRoot,
21
+ } from '../../src/runtime-assets'
18
22
  import { rnxExit } from '../run-rnx'
23
+ import {
24
+ DEV_BUILD_REBUILD_COMMAND,
25
+ findStaleDevBuildRoutes,
26
+ } from '../dev-build-freshness'
19
27
  import { resolveDefaultUploadOrigin } from './upload'
20
28
 
21
29
  interface ServeOptions {
@@ -76,6 +84,28 @@ examples:
76
84
  rnxExit(1)
77
85
  }
78
86
 
87
+ // in a dev checkout serve() serves the dev-stack build directly, so a
88
+ // source edit without a rebuild would hand sims yesterday's engine with no
89
+ // complaint. refuse before binding when the build is stale. installed
90
+ // runtimes are versioned and immutable, so they skip this check.
91
+ if (resolveDevCheckoutRuntimeRoot()) {
92
+ const monorepoRoot = findMonorepoRoot()
93
+ const stale = monorepoRoot ? findStaleDevBuildRoutes(monorepoRoot) : []
94
+ if (stale.length > 0) {
95
+ for (const route of stale) {
96
+ console.error(
97
+ route.artifactMtimeMs === null
98
+ ? ` peach serve: ${route.route} build was never completed — ${route.newestSourcePath} has no served bundle.`
99
+ : ` peach serve: ${route.route} build is stale — ${route.newestSourcePath} is newer than the served bundle.`,
100
+ )
101
+ }
102
+ console.error(
103
+ ` rebuild with \`${DEV_BUILD_REBUILD_COMMAND}\` (or run bun dev so watch:sootsim keeps it current), then try again.`,
104
+ )
105
+ rnxExit(1)
106
+ }
107
+ }
108
+
79
109
  ensureRnxHome()
80
110
  // use the explicit upload/auth origin when configured, otherwise production.
81
111
  // never probe a local Contrast stack during bridge startup.
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, rmSync } from 'fs'
2
2
  import { tmpdir } from 'os'
3
3
  import { basename, dirname, join, resolve } from 'path'
4
- import { getParentPid, getProcessComm } from './parent-pid'
4
+ import { getParentPid, getProcessComm, getProcessPgid } from './parent-pid'
5
5
  import { writeSecureJsonAtomic } from './secure-file'
6
6
 
7
7
  const CURRENT_SIM_VERSION = 2 as const
@@ -145,6 +145,20 @@ export function getStableOwnerPid(): number | null {
145
145
  return findTopAncestor(process.ppid)
146
146
  }
147
147
 
148
+ // the process group of the stable owning session, for leases that must die
149
+ // with the session: the bridge frees a cli lease whose owner group no longer
150
+ // exists instead of blocking other callers until the TTL burns out. the
151
+ // owner's group, not this process's own — an interactive shell runs each
152
+ // command in a fresh foreground group, so our own pgid would die with every
153
+ // invocation and no lease would ever survive it. null when ancestry is
154
+ // unreadable; the lease then behaves as before (TTL only).
155
+ export function getOwnerProcessGroupId(): number | null {
156
+ const owner = getStableOwnerPid()
157
+ if (!owner || owner <= 1) return null
158
+ const pgid = getProcessPgid(owner)
159
+ return pgid !== null && pgid > 1 ? pgid : null
160
+ }
161
+
148
162
  export function getCurrentSimPath() {
149
163
  if (process.env[CURRENT_SIM_PATH_ENV]) {
150
164
  return resolve(process.env[CURRENT_SIM_PATH_ENV])
@@ -0,0 +1,205 @@
1
+ // dev-build freshness gate for `peach serve`.
2
+ //
3
+ // inside the Contrast monorepo checkout serve() serves public/sootsim — the
4
+ // dev-stack engine build — directly (see resolveDevCheckoutRuntimeRoot).
5
+ // without the dev watch running (bun dev's watch:sootsim) that build goes
6
+ // stale the moment an engine/shell source is edited, and serve() would hand
7
+ // sims the old bundle with no complaint. this module compares source and
8
+ // artifact mtimes per build route and reports which routes are stale, so
9
+ // serve can refuse before binding instead of serving yesterday's engine.
10
+ //
11
+ // the route table mirrors scripts/dev/watch-peach-artifacts.ts ROUTES (the
12
+ // authority on which sources feed which build). it is duplicated here rather
13
+ // than imported because the watcher pulls chokidar plus engine/bundler
14
+ // modules the CLI binary must not bundle — keep the two in sync: a source
15
+ // the watch rebuilds on must appear below, or serve will call a stale build
16
+ // fresh. deliberately omitted: the canvaskit binary inputs (resolved from a
17
+ // manifest at watch time, never hand-edited) and the deps-web inputs (a
18
+ // different served tree, not the engine serve() serves).
19
+
20
+ import { readdirSync, statSync, type Dirent } from 'node:fs'
21
+ import { join, relative, sep } from 'node:path'
22
+
23
+ export const DEV_BUILD_REBUILD_COMMAND = 'bun run build:sootsim'
24
+
25
+ export type DevBuildRouteId = 'shell' | 'engine' | 'tenant'
26
+
27
+ export interface StaleDevBuildRoute {
28
+ route: DevBuildRouteId
29
+ // repo-relative posix path of the newest source, for the error message.
30
+ newestSourcePath: string
31
+ // null when an artifact sentinel is missing (never built).
32
+ artifactMtimeMs: number | null
33
+ }
34
+
35
+ interface DevBuildRoute {
36
+ id: DevBuildRouteId
37
+ // repo-relative source files or dirs feeding this route's build.
38
+ sources: string[]
39
+ // repo-relative artifact sentinel files or dirs the build refreshes. a
40
+ // missing sentinel (or an empty dir) means the route was never built.
41
+ artifacts: string[]
42
+ }
43
+
44
+ const PEACHSIM_ENGINE_INPUTS = [
45
+ 'packages/peachsim/src/worklets-babel.ts',
46
+ 'packages/peachsim/src/vite-plugin.ts',
47
+ 'packages/peachsim/src/native-seam-manifest.ts',
48
+ 'packages/peachsim/src/bridge-constants.ts',
49
+ 'packages/peachsim/src/backend-origin.ts',
50
+ 'packages/peachsim/src/dev-bundle-resolution.ts',
51
+ ]
52
+
53
+ const ENGINE_SOURCES = [
54
+ 'packages/peach-engine/src',
55
+ 'packages/peach-engine/public',
56
+ 'packages/peach-engine/scripts/license-banner.ts',
57
+ 'packages/peach-engine/scripts/canvaskit-graphite-variant.ts',
58
+ 'packages/peach-engine/vite.build.config.ts',
59
+ 'packages/peach-engine/package.json',
60
+ 'packages/peach-compat/src',
61
+ 'packages/peach-swipeable/src',
62
+ ...PEACHSIM_ENGINE_INPUTS,
63
+ ]
64
+
65
+ const ROUTES: DevBuildRoute[] = [
66
+ {
67
+ id: 'shell',
68
+ sources: [
69
+ 'packages/peach-shell/src',
70
+ 'packages/peach-shell/index.html',
71
+ 'packages/peach-shell/vite.build.config.ts',
72
+ 'packages/peach-shell/package.json',
73
+ 'packages/peach-plugin-three-mode/src',
74
+ 'packages/peach-plugin-screenshot/src',
75
+ 'packages/peach-plugin-recording/src',
76
+ 'packages/peachsim/src/vite-plugin.ts',
77
+ 'packages/peachsim/src/bridge-constants.ts',
78
+ ],
79
+ // the shell bundle (hashed assets). index.html is deliberately NOT a
80
+ // sentinel: inject-manifest rewrites it after every engine build, so its
81
+ // mtime no longer proves the shell bundle is fresh.
82
+ artifacts: ['public/sootsim/assets'],
83
+ },
84
+ {
85
+ id: 'engine',
86
+ sources: ENGINE_SOURCES,
87
+ // rewritten by every engine build; doubles as the build's completion mark.
88
+ artifacts: ['public/sootsim/engine/.vite/manifest.json'],
89
+ },
90
+ {
91
+ id: 'tenant',
92
+ sources: [...ENGINE_SOURCES, 'packages/peach-engine/vite.config.tenant.ts'],
93
+ artifacts: [
94
+ 'public/sootsim/engine-tenant/worker.js',
95
+ 'public/sootsim/engine-tenant/worker.prod.js',
96
+ ],
97
+ },
98
+ ]
99
+
100
+ // install/build output must never count as either side of the comparison:
101
+ // an `npm install` refreshing node_modules mtimes is not a source edit.
102
+ const EXCLUDED_DIR_NAMES = new Set([
103
+ 'node_modules',
104
+ '.git',
105
+ 'dist',
106
+ 'build',
107
+ '.vite',
108
+ 'coverage',
109
+ '.turbo',
110
+ ])
111
+
112
+ interface NewestFile {
113
+ mtimeMs: number
114
+ absolutePath: string
115
+ }
116
+
117
+ function newestUnder(root: string): NewestFile | null {
118
+ let newest: NewestFile | null = null
119
+ const stack: string[] = [root]
120
+ while (stack.length > 0) {
121
+ const dir = stack.pop()
122
+ if (dir === undefined) continue
123
+ let entries: Dirent[]
124
+ try {
125
+ entries = readdirSync(dir, { withFileTypes: true })
126
+ } catch {
127
+ continue
128
+ }
129
+ for (const entry of entries) {
130
+ if (entry.isDirectory()) {
131
+ if (!EXCLUDED_DIR_NAMES.has(entry.name)) stack.push(join(dir, entry.name))
132
+ continue
133
+ }
134
+ if (!entry.isFile() && !entry.isSymbolicLink()) continue
135
+ let mtimeMs: number
136
+ try {
137
+ mtimeMs = statSync(join(dir, entry.name)).mtimeMs
138
+ } catch {
139
+ continue
140
+ }
141
+ if (!newest || mtimeMs > newest.mtimeMs) {
142
+ newest = { mtimeMs, absolutePath: join(dir, entry.name) }
143
+ }
144
+ }
145
+ }
146
+ return newest
147
+ }
148
+
149
+ function newestForEntry(monorepoRoot: string, repoPath: string): NewestFile | null {
150
+ const absolute = join(monorepoRoot, repoPath)
151
+ let stat: ReturnType<typeof statSync> | null = null
152
+ try {
153
+ stat = statSync(absolute)
154
+ } catch {
155
+ return null
156
+ }
157
+ if (stat.isDirectory()) return newestUnder(absolute)
158
+ if (stat.isFile()) return { mtimeMs: stat.mtimeMs, absolutePath: absolute }
159
+ return null
160
+ }
161
+
162
+ function toRepoPath(monorepoRoot: string, absolutePath: string): string {
163
+ return relative(monorepoRoot, absolutePath).split(sep).join('/')
164
+ }
165
+
166
+ /** every route whose sources are newer than its served artifacts (or whose
167
+ * artifacts are missing). empty means the dev build is fresh. unreadable
168
+ * entries are skipped: a guardrail that cannot run must not brick serve. */
169
+ export function findStaleDevBuildRoutes(monorepoRoot: string): StaleDevBuildRoute[] {
170
+ const stale: StaleDevBuildRoute[] = []
171
+ for (const route of ROUTES) {
172
+ let newestSource: NewestFile | null = null
173
+ for (const source of route.sources) {
174
+ const found = newestForEntry(monorepoRoot, source)
175
+ if (found && (!newestSource || found.mtimeMs > newestSource.mtimeMs)) {
176
+ newestSource = found
177
+ }
178
+ }
179
+ let newestArtifact: NewestFile | null = null
180
+ let artifactMissing = false
181
+ for (const artifact of route.artifacts) {
182
+ const found = newestForEntry(monorepoRoot, artifact)
183
+ if (!found) {
184
+ artifactMissing = true
185
+ continue
186
+ }
187
+ if (!newestArtifact || found.mtimeMs > newestArtifact.mtimeMs) {
188
+ newestArtifact = found
189
+ }
190
+ }
191
+ if (!newestSource) continue
192
+ if (
193
+ artifactMissing ||
194
+ !newestArtifact ||
195
+ newestSource.mtimeMs > newestArtifact.mtimeMs
196
+ ) {
197
+ stale.push({
198
+ route: route.id,
199
+ newestSourcePath: toRepoPath(monorepoRoot, newestSource.absolutePath),
200
+ artifactMtimeMs: newestArtifact ? newestArtifact.mtimeMs : null,
201
+ })
202
+ }
203
+ }
204
+ return stale
205
+ }
@@ -49,6 +49,7 @@ const url = process.env.SOOTSIM_PW_URL;
49
49
  // window.__sootsimBridgePort so the page skips its shell-port heuristic (which
50
50
  // assumes the default offset and breaks when the dev bridge drifted).
51
51
  const bridgePort = process.env.SOOTSIM_PW_BRIDGE_PORT || '';
52
+ const fetchProxySpki = process.env.PEACH_PW_FETCH_PROXY_SPKI || '';
52
53
  const headless = process.env.SOOTSIM_PW_HEADLESS === '1';
53
54
  const callerUserDataDir = process.env.SOOTSIM_PW_USERDATADIR || '';
54
55
  // pid of the session that launched us (its topmost non-init ancestor). when
@@ -403,6 +404,7 @@ const cleanupProfile = () => {
403
404
  opts.args.push('--enable-features=Vulkan');
404
405
  }
405
406
  opts.args.push(${JSON.stringify(chromeDisabledFeaturesSwitch())});
407
+ if (fetchProxySpki) opts.args.push('--ignore-certificate-errors-spki-list=' + fetchProxySpki);
406
408
  if (cdpPort) opts.args.push('--remote-debugging-port=' + cdpPort);
407
409
  if (extraChromeArgs.length) opts.args.push(...extraChromeArgs);
408
410
  // headed: size the OS window to the (phone-shaped) viewport too, plus
@@ -584,7 +586,18 @@ const cleanupProfile = () => {
584
586
  try {
585
587
  await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
586
588
  } catch (err) {
587
- process.stderr.write('[goto] ' + String((err && err.message) || err) + '\\n');
589
+ const message = String((err && err.message) || err);
590
+ process.stderr.write('[goto] ' + message + '\\n');
591
+ // nothing serves this url: the page is a dead error document that can
592
+ // never register, and nothing re-navigates — waiting out the connect
593
+ // timeout burns 125s proving it (peach test on an unserved shell). exit
594
+ // now so the caller fails fast. a goto TIMEOUT keeps waiting (a
595
+ // slow-but-alive server may still finish loading the page); only
596
+ // connection-level failures, where no server exists at all, are fatal.
597
+ if (/ERR_CONNECTION_REFUSED|ERR_ADDRESS_UNREACHABLE|ERR_NAME_NOT_RESOLVED/.test(message)) {
598
+ process.stderr.write('[unserved] nothing serves ' + url + '; closing playwright host\\n');
599
+ void shutdown(3);
600
+ }
588
601
  }
589
602
  keepAlive = setInterval(() => {}, 1 << 30);
590
603
  // browser disconnect (e.g. user killed chrome from outside) → tear down.
@@ -100,6 +100,38 @@ async function launch(opts: DriverLaunchOptions): Promise<DriverLaunchResult> {
100
100
  }
101
101
  }
102
102
 
103
+ const targetUrl = new URL(opts.url)
104
+ let fetchProxySpki = ''
105
+ if (opts.bridgePort) {
106
+ try {
107
+ const response = await fetch(
108
+ `http://127.0.0.1:${opts.bridgePort}/__peach/fetch-transport`,
109
+ { signal: AbortSignal.timeout(10_000) },
110
+ )
111
+ if (!response.ok) throw new Error(`transport discovery returned ${response.status}`)
112
+ const descriptor: unknown = await response.json()
113
+ if (!descriptor || typeof descriptor !== 'object')
114
+ throw new Error('invalid fetch transport')
115
+ const origin = Reflect.get(descriptor, 'origin')
116
+ const spki = Reflect.get(descriptor, 'spki')
117
+ if (
118
+ typeof origin !== 'string' ||
119
+ !/^https:\/\/127\.0\.0\.1:\d+$/.test(origin) ||
120
+ typeof spki !== 'string' ||
121
+ !/^[A-Za-z0-9+/]{43}=$/.test(spki)
122
+ ) {
123
+ throw new Error('invalid fetch transport')
124
+ }
125
+ targetUrl.searchParams.set('fetchProxyOrigin', origin)
126
+ fetchProxySpki = spki
127
+ } catch (error) {
128
+ return {
129
+ launched: false,
130
+ message: `fetch transport discovery failed: ${String(error)}`,
131
+ }
132
+ }
133
+ }
134
+
103
135
  // keep browser discovery, installation, and the detached host on one exact
104
136
  // cache contract even if another caller mutates process.env during launch.
105
137
  const playwrightEnv = { ...process.env }
@@ -137,7 +169,8 @@ async function launch(opts: DriverLaunchOptions): Promise<DriverLaunchResult> {
137
169
  ...playwrightEnv,
138
170
  SOOTSIM_PW_MODULE: resolved.modulePath,
139
171
  SOOTSIM_PW_EXECUTABLE: provisioning.executablePath,
140
- SOOTSIM_PW_URL: opts.url,
172
+ SOOTSIM_PW_URL: targetUrl.href,
173
+ PEACH_PW_FETCH_PROXY_SPKI: fetchProxySpki,
141
174
  SOOTSIM_PW_BRIDGE_PORT: opts.bridgePort ? String(opts.bridgePort) : '',
142
175
  SOOTSIM_PW_HEADLESS: (opts.headless ?? true) ? '1' : '0',
143
176
  SOOTSIM_PW_USERDATADIR: resolveUserDataDir(opts),
@@ -196,10 +229,10 @@ async function launch(opts: DriverLaunchOptions): Promise<DriverLaunchResult> {
196
229
  const ownerNote = ` — browser closes after ${idleMinutes} min with no peach command, or when pid ${ownerPid}${ownerComm ? ` (${ownerComm})` : ''} exits`
197
230
  return {
198
231
  launched: true,
199
- message: `playwright chrome launched → ${opts.url}${ownerNote}`,
232
+ message: `playwright chrome launched → ${targetUrl.href}${ownerNote}`,
200
233
  pid: child.pid,
201
234
  target: resolved.spec,
202
- attachUrl: opts.url,
235
+ attachUrl: targetUrl.href,
203
236
  connectAckFile,
204
237
  diagnosticLogPath: errLog,
205
238
  }
package/cli/main.ts CHANGED
@@ -302,6 +302,14 @@ const commandArgsWithSim = globalSimTarget
302
302
  ? ['--sim', globalSimTarget, ...parsed.commandArgs]
303
303
  : parsed.commandArgs
304
304
 
305
+ // an invalid theme used to die silently inside settingsStore.apply (the
306
+ // schema options reject it and apply returns false), so `peach --theme
307
+ // appearance open 8081` opened with no theme and no error. refuse it here.
308
+ if (theme && theme !== 'light' && theme !== 'dark' && theme !== 'auto') {
309
+ console.error(` peach: --theme must be light, dark, or auto, got "${theme}"`)
310
+ await exitWithFlush(1)
311
+ }
312
+
305
313
  // apply device/theme to settings store if provided
306
314
  if (device || theme) {
307
315
  const { settingsStore } = await import('peach-engine/settings/store')
package/cli/parent-pid.ts CHANGED
@@ -14,6 +14,7 @@ type CommLookup = (pid: number) => string | null
14
14
 
15
15
  let cached: Lookup | null = null
16
16
  let cachedComm: CommLookup | null = null
17
+ let cachedPgid: Lookup | null = null
17
18
 
18
19
  export function getParentPid(pid: number): number | null {
19
20
  if (!cached) cached = build()
@@ -36,6 +37,18 @@ export function getProcessComm(pid: number): string | null {
36
37
  }
37
38
  }
38
39
 
40
+ // process group id for a pid, or null when unreadable. process.getpgid
41
+ // exists on node but not on bun, so this mirrors the ppid lookup backends
42
+ // instead of branching runtimes at the call site.
43
+ export function getProcessPgid(pid: number): number | null {
44
+ if (!cachedPgid) cachedPgid = buildPgid()
45
+ try {
46
+ return cachedPgid(pid)
47
+ } catch {
48
+ return null
49
+ }
50
+ }
51
+
39
52
  function buildComm(): CommLookup {
40
53
  if (process.platform === 'linux') {
41
54
  return (pid) => {
@@ -78,40 +91,74 @@ function build(): Lookup {
78
91
  return () => null
79
92
  }
80
93
 
81
- // one snapshot of the whole process tree, shared by the ppid and comm lookups.
82
- // macOS has no /proc and Node cannot call libproc, so each lookup used to shell
83
- // out to `lsof -R -p <pid>` with a 2000ms budget — measured at 3.5s, 7.1s and
84
- // 7.9s on a loaded box, so every hop of an ancestor walk timed out, the walk
85
- // resolved to null, and `contrast ide open` launched a browser host with an
86
- // empty owner pid that `ide close` could never attribute. `ps -eo pid,ppid,comm`
87
- // answers for every process at once in ~0.1-0.9s. the short TTL keeps one walk
88
- // on one snapshot while a long-lived caller still sees the tree change.
94
+ function buildPgid(): Lookup {
95
+ if (process.platform === 'linux') {
96
+ return (pid) => {
97
+ try {
98
+ const raw = readFileSync(`/proc/${pid}/stat`, 'utf8')
99
+ const end = raw.lastIndexOf(')')
100
+ if (end < 0) return null
101
+ const rest = raw
102
+ .slice(end + 1)
103
+ .trim()
104
+ .split(/\s+/)
105
+ // fields after (comm): state, ppid, pgrp, ...
106
+ const pgid = Number(rest[2])
107
+ return Number.isFinite(pgid) && pgid > 0 ? pgid : null
108
+ } catch {
109
+ return null
110
+ }
111
+ }
112
+ }
113
+ if (process.platform === 'darwin') {
114
+ const ffi = tryBuildDarwinPgidFfi()
115
+ if (ffi) return ffi
116
+ return (pid) => {
117
+ const pgid = readProcessTable().get(pid)?.pgid
118
+ return pgid !== undefined && pgid > 0 ? pgid : null
119
+ }
120
+ }
121
+ return () => null
122
+ }
123
+
124
+ // one snapshot of the whole process tree, shared by the ppid, pgid and comm
125
+ // lookups. macOS has no /proc and Node cannot call libproc, so each lookup
126
+ // used to shell out to `lsof -R -p <pid>` with a 2000ms budget — measured at
127
+ // 3.5s, 7.1s and 7.9s on a loaded box, so every hop of an ancestor walk timed
128
+ // out, the walk resolved to null, and `contrast ide open` launched a browser
129
+ // host with an empty owner pid that `ide close` could never attribute.
130
+ // `ps -eo pid,ppid,pgid,comm` answers for every process at once in ~0.1-0.9s.
131
+ // the short TTL keeps one walk on one snapshot while a long-lived caller
132
+ // still sees the tree change.
89
133
  const PROCESS_TABLE_TTL_MS = 2000
90
- let processTable: { readAt: number; rows: Map<number, { ppid: number; comm: string }> } =
91
- { readAt: 0, rows: new Map() }
134
+ let processTable: {
135
+ readAt: number
136
+ rows: Map<number, { ppid: number; pgid: number; comm: string }>
137
+ } = { readAt: 0, rows: new Map() }
92
138
 
93
- function readProcessTable(): Map<number, { ppid: number; comm: string }> {
139
+ function readProcessTable(): Map<number, { ppid: number; pgid: number; comm: string }> {
94
140
  const now = Date.now()
95
141
  if (processTable.readAt && now - processTable.readAt < PROCESS_TABLE_TTL_MS) {
96
142
  return processTable.rows
97
143
  }
98
- const rows = new Map<number, { ppid: number; comm: string }>()
144
+ const rows = new Map<number, { ppid: number; pgid: number; comm: string }>()
99
145
  try {
100
- const out = execFileSync('ps', ['-eo', 'pid=,ppid=,comm='], {
146
+ const out = execFileSync('ps', ['-eo', 'pid=,ppid=,pgid=,comm='], {
101
147
  encoding: 'utf8',
102
148
  timeout: 5000,
103
149
  maxBuffer: 8 * 1024 * 1024,
104
150
  stdio: ['ignore', 'pipe', 'ignore'],
105
151
  })
106
152
  for (const line of out.split('\n')) {
107
- const parsed = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/)
153
+ const parsed = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/)
108
154
  if (!parsed) continue
109
155
  // libproc reports pbi_comm — the executable's basename, truncated to
110
156
  // MAXCOMLEN — and the immortal-host patterns are written against that
111
157
  // shape, while `ps -o comm` prints the full path. normalize to one.
112
158
  rows.set(Number(parsed[1]), {
113
159
  ppid: Number(parsed[2]),
114
- comm: (parsed[3].split('/').at(-1) ?? '').slice(0, PBI_COMM_LEN),
160
+ pgid: Number(parsed[3]),
161
+ comm: (parsed[4].split('/').at(-1) ?? '').slice(0, PBI_COMM_LEN),
115
162
  })
116
163
  }
117
164
  } catch {
@@ -202,3 +249,32 @@ function tryBuildDarwinCommFfi(): CommLookup | null {
202
249
  return null
203
250
  }
204
251
  }
252
+
253
+ // uint32 pbi_pgid — after the 12 leading 4-byte fields, pbi_comm[16],
254
+ // pbi_name[32] and pbi_nfiles. source: <sys/proc_info.h> in the macOS SDK.
255
+ const PBI_PGID_OFFSET = 100
256
+
257
+ function tryBuildDarwinPgidFfi(): Lookup | null {
258
+ if (!process.versions?.bun) return null
259
+ try {
260
+ const r = createRequire(import.meta.url)
261
+ const { dlopen, FFIType } = r('bun:ffi')
262
+ const lib = dlopen('/usr/lib/libproc.dylib', {
263
+ proc_pidinfo: {
264
+ args: [FFIType.i32, FFIType.i32, FFIType.u64, FFIType.ptr, FFIType.i32],
265
+ returns: FFIType.i32,
266
+ },
267
+ })
268
+ const buf = Buffer.alloc(PROC_BSDINFO_SIZE)
269
+ return (pid) => {
270
+ const ret = Number(
271
+ lib.symbols.proc_pidinfo(pid, PROC_PIDTBSDINFO, 0n, buf, PROC_BSDINFO_SIZE),
272
+ )
273
+ if (ret <= 0) return null
274
+ const pgid = buf.readUInt32LE(PBI_PGID_OFFSET)
275
+ return pgid > 0 ? pgid : null
276
+ }
277
+ } catch {
278
+ return null
279
+ }
280
+ }
package/cli/ws-bridge.ts CHANGED
@@ -25,6 +25,7 @@ import {
25
25
  import { createCloudBridgeForParsed } from './cloud-client'
26
26
  import {
27
27
  getCliIdentity,
28
+ getOwnerProcessGroupId,
28
29
  readCurrentSim,
29
30
  readCurrentSimId,
30
31
  saveCurrentSimId,
@@ -592,6 +593,10 @@ export function createBridge(wsPort: number, opts: WsBridgeOptions = {}): WsBrid
592
593
  cliIdentityKey: identity.key,
593
594
  cliIdentitySource: identity.source,
594
595
  cliLabel: opts.cliLabel,
596
+ // lets the bridge free this cli's leases once its owning
597
+ // session is entirely gone, instead of blocking others
598
+ // until the TTL burns out. null when ancestry is unreadable.
599
+ cliOwnerPgid: getOwnerProcessGroupId(),
595
600
  }),
596
601
  )
597
602
  } catch {}