rvlib-shipkit 2.20.0 → 2.22.0

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 (156) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/package.json +1 -1
  3. package/src/asks/asks-queue.ts +8 -7
  4. package/src/assets/kits/identity-kit.ts +158 -2
  5. package/src/checks/SK004-gitignore-policy.check.ts +6 -3
  6. package/src/cli/cmd_Bump.ts +3 -3
  7. package/src/cli/cmd_GlobalProcesses.ts +2 -107
  8. package/src/cli/cmd_Home.ts +1 -1
  9. package/src/cli/cmd_Overview.ts +2 -1
  10. package/src/cli/cmd_Rec.ts +349 -0
  11. package/src/cli/cmd_Releases.ts +42 -3
  12. package/src/cli/cmd_Review.ts +22 -13
  13. package/src/cli/cmd_Secret.ts +10 -3
  14. package/src/cli/cmd_Sign.ts +24 -0
  15. package/src/cli/cmd_Social.ts +57 -8
  16. package/src/cli/cmd_Sound.ts +17 -4
  17. package/src/cli/cmd_Trailer.ts +67 -1
  18. package/src/cli/family-pages.ts +1 -0
  19. package/src/cli/registry.ts +6 -1
  20. package/src/collections/collection-types.ts +1 -1
  21. package/src/collections/review.ts +23 -4
  22. package/src/core/agent-spawn.ts +4 -17
  23. package/src/core/code-lines.ts +49 -0
  24. package/src/core/discover-checks.ts +27 -3
  25. package/src/core/hard-reset.ts +34 -0
  26. package/src/core/layout.ts +6 -0
  27. package/src/core/raw-access.ts +3 -13
  28. package/src/core/throwaway-worktree.ts +72 -0
  29. package/src/home/app-sign.ts +98 -0
  30. package/src/home/gui-app/ShipkitGui.swift +35 -0
  31. package/src/home/gui-app.ts +31 -11
  32. package/src/home/home-routes.ts +6 -0
  33. package/src/home/pm-switch.ts +112 -0
  34. package/src/home/serve-web.ts +1 -1
  35. package/src/identities/identities.ts +17 -6
  36. package/src/media-kinds.ts +5 -3
  37. package/src/media-store/forget.ts +54 -0
  38. package/src/media-store/put.ts +4 -3
  39. package/src/media-store/space.ts +63 -24
  40. package/src/messages/brief.ts +3 -3
  41. package/src/messages/score.ts +2 -0
  42. package/src/recordings/delete.ts +19 -0
  43. package/src/recordings/edit.ts +231 -0
  44. package/src/recordings/load.ts +37 -0
  45. package/src/recordings/marks-draw.ts +111 -0
  46. package/src/recordings/marks-png.ts +25 -0
  47. package/src/recordings/marks.ts +138 -0
  48. package/src/recordings/media-kind.ts +67 -0
  49. package/src/recordings/model.ts +170 -0
  50. package/src/recordings/open.ts +33 -0
  51. package/src/recordings/place.ts +89 -0
  52. package/src/recordings/presets.ts +99 -0
  53. package/src/recordings/recorder-app/Capture.swift +510 -0
  54. package/src/recordings/recorder-app/Clip.swift +107 -0
  55. package/src/recordings/recorder-app/Editor.swift +39 -0
  56. package/src/recordings/recorder-app/Tray.swift +298 -0
  57. package/src/recordings/recorder-app/main.swift +859 -0
  58. package/src/recordings/recorder-app.ts +46 -0
  59. package/src/recordings/recorder.shipkit.ts +11 -0
  60. package/src/recordings/routes.ts +140 -0
  61. package/src/recordings/run-recorder.ts +40 -0
  62. package/src/recordings/share.ts +107 -0
  63. package/src/recordings/take.ts +146 -0
  64. package/src/recordings/view.ts +40 -0
  65. package/src/release/gate-checkout.ts +74 -0
  66. package/src/release/release-scope.ts +35 -26
  67. package/src/release/run-bump.ts +79 -37
  68. package/src/release/run-release.ts +67 -53
  69. package/src/releases/add.ts +38 -5
  70. package/src/releases/before.ts +31 -0
  71. package/src/releases/from-card.ts +105 -20
  72. package/src/releases/model.ts +100 -18
  73. package/src/releases/pictures.ts +29 -8
  74. package/src/repo-config.ts +7 -3
  75. package/src/review/http.ts +1 -1
  76. package/src/review/model.ts +12 -2
  77. package/src/review/stage-card.ts +1 -1
  78. package/src/review/store.ts +12 -2
  79. package/src/review/trailer-desk.ts +20 -0
  80. package/src/review/trailer-model.ts +67 -0
  81. package/src/review/trailer-routes.ts +98 -1
  82. package/src/review/trailer-voices.ts +144 -0
  83. package/src/review/watchers.ts +58 -1
  84. package/src/secrets/manager.ts +18 -1
  85. package/src/serve/hub-app/benign-errors.ts +22 -0
  86. package/src/serve/hub-app/hash-route.ts +27 -15
  87. package/src/serve/hub-app/home-st.ts +23 -5
  88. package/src/serve/hub-app/home.html +1 -0
  89. package/src/serve/hub-app/hub-app.tsx +8 -1
  90. package/src/serve/hub-app/icons.tsx +2 -0
  91. package/src/serve/hub-app/palette-st.ts +1 -0
  92. package/src/serve/hub-app/project-list.css +7 -2
  93. package/src/serve/hub-app/project-list.tsx +10 -0
  94. package/src/serve/hub-app/projects-svc.ts +17 -7
  95. package/src/serve/hub-app/recordings-st.ts +641 -0
  96. package/src/serve/hub-app/recordings-view.tsx +504 -0
  97. package/src/serve/hub-app/recordings.css +82 -0
  98. package/src/serve/hub-app/releases/releases-page.tsx +121 -28
  99. package/src/serve/hub-app/releases/releases-st.ts +46 -4
  100. package/src/serve/hub-app/releases.css +30 -3
  101. package/src/serve/hub-app/repo-sections.ts +1 -1
  102. package/src/serve/hub-app/repo-st.ts +16 -11
  103. package/src/serve/hub-app/review/clip-st.ts +3 -1
  104. package/src/serve/hub-app/review/kit.tsx +3 -3
  105. package/src/serve/hub-app/review/trailer-page.tsx +32 -6
  106. package/src/serve/hub-app/review/trailer-st.ts +184 -8
  107. package/src/serve/hub-app/review/trailer-timeline.tsx +39 -4
  108. package/src/serve/hub-app/review/trailer-voices-st.ts +370 -0
  109. package/src/serve/hub-app/review/trailer-voices.tsx +574 -0
  110. package/src/serve/hub-app/review.css +90 -0
  111. package/src/serve/hub-app/social/comms-page.tsx +10 -5
  112. package/src/serve/hub-app/social/next-release.tsx +118 -0
  113. package/src/serve/hub-app/social/post-card.tsx +31 -3
  114. package/src/serve/hub-app/social/social-model.ts +6 -0
  115. package/src/serve/hub-app/social/social-st.ts +50 -1
  116. package/src/serve/hub-app/social.css +12 -0
  117. package/src/serve/hub-app/tree-build.ts +2 -0
  118. package/src/serve/project-gutter-route.ts +8 -0
  119. package/src/serve/project-gutter.ts +4 -2
  120. package/src/shipkit.ts +2 -2
  121. package/src/shot/box.ts +49 -22
  122. package/src/shot/browser-slot.ts +13 -3
  123. package/src/shot/client.ts +1 -1
  124. package/src/shot/film-box.ts +193 -117
  125. package/src/shot/shooter.ts +20 -8
  126. package/src/smoke/run-smoke.ts +8 -6
  127. package/src/social/compose.ts +14 -0
  128. package/src/social/desk-index.ts +49 -8
  129. package/src/social/discord-layout.ts +6 -2
  130. package/src/social/drafts.ts +1 -1
  131. package/src/social/kinds.ts +3 -2
  132. package/src/social/load.ts +42 -9
  133. package/src/social/publish/index.ts +27 -10
  134. package/src/social/publish/secret.ts +12 -4
  135. package/src/social/release-card.ts +69 -0
  136. package/src/social/release-stage.ts +173 -30
  137. package/src/social/routes.ts +7 -1
  138. package/src/social/stage.ts +45 -22
  139. package/src/trailer/bed.ts +111 -0
  140. package/src/trailer/build.ts +81 -38
  141. package/src/trailer/ffmpeg.ts +14 -0
  142. package/src/trailer/grammar.ts +32 -4
  143. package/src/trailer/graph.ts +12 -1
  144. package/src/trailer/look.ts +7 -0
  145. package/src/trailer/shot-plan.ts +75 -0
  146. package/src/trailer/shot-state.ts +191 -0
  147. package/src/trailer/sound/audio.ts +28 -0
  148. package/src/trailer/sound/brand.ts +53 -3
  149. package/src/trailer/sound/gen.ts +61 -2
  150. package/src/trailer/sound/index.ts +25 -11
  151. package/src/trailer/sound/presets.ts +86 -5
  152. package/src/trailer/sound/run.ts +1 -1
  153. package/src/trailer/sound/takes.ts +94 -0
  154. package/src/trailer/titles.ts +36 -0
  155. package/src/trailer/url.ts +1 -1
  156. package/src/veille/chrome.ts +6 -3
package/src/shot/box.ts CHANGED
@@ -1,15 +1,16 @@
1
1
  // THE BOX ROUTE: a repo whose repo.config.ts `browsers.box` names an ssh host films there when it runs on a Mac. Every
2
2
  // browser start of the repo (a take, a Shooter: sk shot, look sheets, thumbs, the trailer's films) asks `openBrowser`,
3
- // which on such a Mac connects to the box's warm chromium (film-box.ts) instead of launching one: its devtools reached
4
- // through an ssh forward, each localhost page it opens reached back on this Mac through a reverse forward (the urls
5
- // unchanged), its frames drawn and encoded on the box's GPU, only the result crossing back. Anywhere else, or with
6
- // SK_FILM_HERE=1 for one run, it launches here as before, under the browser cap either way.
3
+ // which on such a Mac connects to the box's warm chromium of the slot it holds (film-box.ts: one browser per slot, so
4
+ // no film shares a GPU process with another) instead of launching one: its devtools reached through an ssh forward,
5
+ // each localhost page it opens reached back on this Mac through a reverse forward (the urls unchanged), its frames
6
+ // drawn and encoded on the box's GPU, only the result crossing back. Anywhere else, or with SK_FILM_HERE=1 for one
7
+ // run, it launches here as before, under the browser cap either way.
7
8
  //
8
9
  // The one constraint a reader breaks first: a box that does not answer is one loud line and nothing filmed, never a
9
10
  // browser launched on the Mac instead (the Mac is the machine the route protects).
10
11
  import { createHash } from 'crypto'
11
12
  import { readFileSync } from 'fs'
12
- import { browserCap, browserSlot, filmBox, HERE_ENV } from './browser-slot.ts'
13
+ import { browserCap, browserLease, type BrowserLease, filmBox, HERE_ENV } from './browser-slot.ts'
13
14
  import { CDP_PORT } from './film-box.ts'
14
15
  import { JOB_STORE_END, jobId, jobStoreScript } from './job-store.ts'
15
16
 
@@ -34,6 +35,28 @@ export type Pw = { chromium: { launch(o: { headless: boolean; args: string[] }):
34
35
  * url (the box needs this Mac's localhost port forwarded); `close` ends it and frees its slot */
35
36
  export type Opened<B> = { browser: B; where: string; reach(url: string): Promise<void>; close(): Promise<void> }
36
37
 
38
+ /** a browser close that has not answered in this long (a stalled box route) is left behind, so its slot frees */
39
+ export const CLOSE_MS = 5000
40
+
41
+ /** the close of a browser, left after CLOSE_MS, then its slot freed whatever the close did */
42
+ const closeThenFree = async (close: () => Promise<void>, free: () => void): Promise<void> => {
43
+ try {
44
+ await Promise.race([close().catch(() => undefined), Bun.sleep(CLOSE_MS)])
45
+ } finally {
46
+ free()
47
+ }
48
+ }
49
+
50
+ /** wait for one of the repo's browser slots where its browser would run (on its box from a Mac), and hold it until
51
+ * the release: a caller that waits in the queue apart from its own timed work holds it first (openBrowser `held`) */
52
+ export async function slotFor(o: { root?: string; who: string; say?: (l: string) => void }): Promise<BrowserLease> {
53
+ const box = filmBox(await browserCap(o.root))
54
+ return browserLease(o.who, { ...(o.root ? { root: o.root } : {}), ...(o.say ? { say: o.say } : {}), onBox: box != null })
55
+ }
56
+
57
+ /** the name the box knows a slot's browser by: the repo and the slot's index */
58
+ export const boxSlotKey = (repo: string, slot: number): string => `${repo.replace(/[^\w.-]/g, '_')}-${slot}`
59
+
37
60
  const SSH = (box: string) => ['ssh', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes', box]
38
61
  /** where the box's devtools answer on this Mac */
39
62
  const localCdp = (box: string): number => 40000 + (parseInt(createHash('sha1').update(box).digest('hex').slice(0, 4), 16) % 9000)
@@ -52,10 +75,10 @@ async function run(cmd: string[], stdin?: Uint8Array): Promise<{ code: number; o
52
75
  return { code: await p.exited, out, err }
53
76
  }
54
77
 
55
- /** the box's warm browser answering, its script uploaded first when the box lacks this version of it */
56
- async function boxUp(box: string, version: string, say: (l: string) => void): Promise<string> {
78
+ /** the box's warm browser of a slot answering, its script uploaded first when the box lacks this version of it */
79
+ async function boxUp(box: string, version: string, key: string, say: (l: string) => void): Promise<string> {
57
80
  const script = `${FILM_DIR}/film-box-${BOX_HASH}.ts`
58
- const go = () => run([...SSH(box), `if exist ${script.replaceAll('/', '\\')} (bun ${script} up ${version}) else (exit ${MISSING})`])
81
+ const go = () => run([...SSH(box), `if exist ${script.replaceAll('/', '\\')} (bun ${script} up ${version} ${key}) else (exit ${MISSING})`])
59
82
  let r = await go()
60
83
  if (r.code === MISSING) {
61
84
  await run([...SSH(box), `mkdir ${FILM_DIR.replaceAll('/', '\\')} 2>nul`])
@@ -134,27 +157,28 @@ export function asLaunched(b: PwBrowser, all: PwPage[], store: BoxStore = 'job')
134
157
  }
135
158
 
136
159
  /** a browser for `who` of the repo at `root`: on its box from a Mac (filmBox), else launched here; one of the repo's
137
- * browser slots held until close */
138
- export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void; store?: BoxStore }): Promise<Opened<B>> {
160
+ * browser slots held until close (`held`: one its caller already holds from slotFor, freed here as one taken here) */
161
+ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void; store?: BoxStore; held?: BrowserLease }): Promise<Opened<B>> {
139
162
  const say = o.say ?? ((l: string) => console.error(l))
140
163
  const cap = await browserCap(o.root)
141
164
  const box = filmBox(cap)
142
- const release = await browserSlot(o.who, { ...(o.root ? { root: o.root } : {}), say, onBox: box != null })
165
+ const lease = o.held ?? (await slotFor({ ...(o.root ? { root: o.root } : {}), who: o.who, say }))
166
+ const release = lease.release
143
167
  try {
144
- if (box == null) {
168
+ if (box == null || cap == null) {
145
169
  const b = (await pw.chromium.launch({ headless: true, args: o.args })) as B & { close(): Promise<void> }
146
- return { browser: b, where: 'here', reach: async () => undefined, close: () => b.close().catch(() => undefined).finally(release) }
170
+ return { browser: b, where: 'here', reach: async () => undefined, close: () => closeThenFree(() => b.close(), release) }
147
171
  }
148
172
  const t = performance.now()
149
173
  const version = (JSON.parse(readFileSync(Bun.resolveSync('playwright-core/package.json', import.meta.dir), 'utf8')) as { version: string }).version
150
- const state = await boxUp(box, version, say)
174
+ const state = await boxUp(box, version, boxSlotKey(cap.repo, lease.slot), say)
151
175
  const own: { p: ReturnType<typeof Bun.spawn> | null } = { p: null }
152
- // the box's browser answers on the port up names (a replacement runs beside a draining one on another)
176
+ // the slot's browser answers on the port up names
153
177
  const port = Number(/ port (\d+)/.exec(state)?.[1] ?? CDP_PORT)
154
178
  const cdp = localCdp(box) + (port - CDP_PORT)
155
179
  await forward(box, ['-L', `${cdp}:127.0.0.1:${port}`], own)
156
180
  const b = await pw.chromium.connectOverCDP(`http://127.0.0.1:${cdp}`)
157
- say(`${o.who}: filming on ${box} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to its browser)`)
181
+ say(`${o.who}: filming on ${box}, browser ${boxSlotKey(cap.repo, lease.slot)} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to it)`)
158
182
  const reached = new Set<number>()
159
183
  const pages: PwPage[] = []
160
184
  const browser = asLaunched(b, pages, o.store)
@@ -169,12 +193,15 @@ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; ar
169
193
  await forward(box, ['-R', `${port}:127.0.0.1:${port}`], own)
170
194
  reached.add(port)
171
195
  },
172
- async close() {
173
- // its pages close, the connection drops, the box's browser stays warm
174
- await browser.close().catch(() => undefined)
175
- own.p?.kill()
176
- release()
177
- },
196
+ // its pages close, the connection drops, the box's browser stays warm
197
+ close: () =>
198
+ closeThenFree(
199
+ () => browser.close(),
200
+ () => {
201
+ own.p?.kill()
202
+ release()
203
+ },
204
+ ),
178
205
  }
179
206
  } catch (e) {
180
207
  release()
@@ -59,12 +59,22 @@ export function holderWords(h: { pid: number; check: string; since: number }, no
59
59
  return `pid ${h.pid} (${h.check}, held ${age})`
60
60
  }
61
61
 
62
+ /** a browser slot held: its index in the repo's pool (the box runs one browser per index, film-box.ts), its release */
63
+ export type BrowserLease = { slot: number; release: () => void }
64
+
65
+ type SlotOptions = { root?: string; say?: (l: string) => void; pollMs?: number; onBox?: boolean }
66
+
62
67
  /** wait for one of the repo's browser slots and hold it until the returned release (or this process ends), saying
63
68
  * once whom it waits on; outside any repo there is no cap and nothing is held. `onBox`: the browser runs on the
64
69
  * repo's box, this Mac only drives it */
65
- export async function browserSlot(who: string, o: { root?: string; say?: (l: string) => void; pollMs?: number; onBox?: boolean } = {}): Promise<() => void> {
70
+ export async function browserSlot(who: string, o: SlotOptions = {}): Promise<() => void> {
71
+ return (await browserLease(who, o)).release
72
+ }
73
+
74
+ /** browserSlot with the slot's index: on the box, the index names the browser the slot films in */
75
+ export async function browserLease(who: string, o: SlotOptions = {}): Promise<BrowserLease> {
66
76
  const c = await browserCap(o.root)
67
- if (c == null) return () => undefined
77
+ if (c == null) return { slot: 0, release: () => undefined }
68
78
  const no = browserRefusal(c, who, o.onBox === true)
69
79
  if (no != null) throw new Error(no)
70
80
  const say = o.say ?? ((l: string) => console.error(l))
@@ -77,5 +87,5 @@ export async function browserSlot(who: string, o: { root?: string; say?: (l: str
77
87
  say(`${who}: waiting for a browser of ${c.repo}${box ? ` on ${box.host}` : ''}, all ${cap} held (repo.config.ts ${key}): ${held.map((h) => holderWords(h)).join(', ') || 'a holder starting'}`),
78
88
  })
79
89
  if (got == null) throw new Error(`${who}: the browser slot wait of ${c.repo} stopped with no slot`)
80
- return got.release
90
+ return got
81
91
  }
@@ -99,7 +99,7 @@ async function ask(route: '/shot' | '/clip', a: ShotAsk | ClipAsk, log: (l: stri
99
99
  const { pmUp, pmUrl } = await import('../home/home-paths.ts')
100
100
  if (process.env['CI'] == null && process.env['SHIPKIT_NO_HOME'] == null && (await pmUp())) {
101
101
  log(`shot: starting the shot service (sk gp start ${SHOT_PROCESS})`)
102
- const { pmSwitchDeps, switchProcess } = await import('../cli/cmd_GlobalProcesses.ts')
102
+ const { pmSwitchDeps, switchProcess } = await import('../home/pm-switch.ts')
103
103
  const code = await switchProcess(SHOT_PROCESS, 'start', pmSwitchDeps(log, pmUrl()), 60_000)
104
104
  if (code !== 0) throw new Error(`the shot service did not start through pm: sk gp shows where it stands`)
105
105
  const started = await post(route, a)
@@ -1,34 +1,81 @@
1
1
  // the box half of the box route (box.ts): run by bun on the box that films for a repo (repo.config.ts browsers.box),
2
- // uploaded there by its content hash, node builtins only. One warm chromium on the box's discrete GPU, its devtools on
3
- // 127.0.0.1:CDP_PORT (the Mac reaches it through ssh), its profile kept, so its HTTP cache outlives each film. It is
4
- // chromium's headless shell: the full chromium's headless mode composites a WebGPU canvas black in the box's session 0
5
- // (no display). The shell ships without the DirectX shader compiler Dawn's D3D12 loads, so it gets the full
6
- // chromium's copy; the full chromium also reads the discrete GPU's LUID off chrome://gpu, which the shell lacks.
7
- // up <playwright version> the browser answering (started when down: installed when missing, its GPU's LUID found)
8
- // watch <pid> closes a page whose film died, ends the browser once nothing used it for IDLE_MS (started
9
- // by up, outside the ssh session)
10
- // the constraint a reader breaks first: Windows OpenSSH ends every process of its session when it closes, so the
11
- // browser and the watcher are created through WMI, outside it
2
+ // uploaded there by its content hash, node builtins only. One warm chromium PER BROWSER SLOT of a repo (`<repo>-<slot>`,
3
+ // the Mac's slot index, browser-slot.ts), each on the box's discrete GPU with its own devtools port (the Mac reaches it
4
+ // through ssh) and its own profile, kept, so its HTTP cache outlives each film. A browser per slot because chromium
5
+ // runs every page of a browser through ONE GPU process: measured on wm (2026-11-10), a page booting there tripled
6
+ // another page's play (6.1 s alone, 20.9 s beside it; 6.1 s beside a boot in a browser of its own), and a look sheet's
7
+ // five tabs held that process at 100 % of a core while the 4090 idled. It is chromium's headless shell: the full
8
+ // chromium's headless mode composites a WebGPU canvas black in the box's session 0 (no display). The shell ships
9
+ // without the DirectX shader compiler Dawn's D3D12 loads, so it gets the full chromium's copy; the full chromium also
10
+ // reads the discrete GPU's LUID off chrome://gpu, which the shell lacks.
11
+ // up <playwright version> <slot key> the slot's browser answering, any page left in it closed (started when down
12
+ // or of another version: installed when missing, its GPU's LUID found)
13
+ // watch <slot key> <pid> <port> closes a page whose film died, ends the browser once nothing used it for
14
+ // IDLE_MS or its devtools went deaf (started by up, outside the ssh session)
15
+ // the constraint a reader breaks first: a slot is held by one film at a time on the Mac, so its browser is that film's
16
+ // alone: up may close its pages and replace it, and never touches another slot's browser. Windows OpenSSH ends every
17
+ // process of its session when it closes, so the browser and the watcher are created through WMI, outside it
12
18
  import { createHash } from 'node:crypto'
13
- import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
19
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
14
20
  import { homedir, uptime } from 'node:os'
15
21
  import { dirname, join } from 'node:path'
16
22
 
23
+ /** the base the Mac maps a box port onto its own (box.ts localCdp); older versions ran their one browser on it */
17
24
  export const CDP_PORT = 9333
25
+ /** the ports a slot's browser takes: past the 9333 and 9336 of older versions */
26
+ export const FIRST_PORT = 9340
27
+ const LAST_PORT = 9439
18
28
  const PROBE_PORT = 9334
19
- /** the browser ends once no film touched it for this long and no page holds a url */
29
+ /** the browser ends once no film touched its slot for this long and it shows no page */
20
30
  const IDLE_MS = 10 * 60_000
21
- /** and past this long with no film, whatever its pages */
22
- const STALE_MS = 60 * 60_000
31
+ /** how long a devtools answer may take before the browser counts as not answering (a busy one answers in under 0.1 s) */
32
+ const ANSWER_MS = 5000
33
+ /** every SWEEP_MS the watcher looks; a page no client drives two sweeps in a row is closed, a browser whose devtools
34
+ * did not answer DEAF_SWEEPS sweeps in a row is ended */
35
+ const SWEEP_MS = 5000
36
+ const DEAF_SWEEPS = 6
23
37
 
24
38
  const DIR = join(homedir(), 'dev', 'shipkit-film')
25
- const USED = join(DIR, 'used')
26
- const PID = join(DIR, 'browser.pid')
39
+ const SLOTS = join(DIR, 'slots')
40
+ const LOG = join(DIR, 'film-box.log')
41
+ /** the one browser of older versions, ended once it drives no page */
42
+ const LEGACY_PID = join(DIR, 'browser.pid')
43
+ const LEGACY_USED = join(DIR, 'used')
44
+ const LEGACY_QUIET_MS = 2 * 60_000
27
45
  const say = (s: string) => console.error(`box: ${s}`)
28
46
 
29
- /** this script's version: a browser another version started is replaced */
47
+ /** this script's version: a slot's browser another version started is replaced */
30
48
  const VERSION = createHash('sha1').update(readFileSync(import.meta.path)).digest('hex').slice(0, 12)
31
49
 
50
+ /** a slot key as the Mac sends it: a file name */
51
+ export const slotKeyOk = (key: string): boolean => /^[\w.-]{1,80}$/.test(key)
52
+
53
+ /** the first port of FIRST_PORT..LAST_PORT that no slot's live browser holds and nothing answers on */
54
+ export async function freePort(taken: Set<number>, answering: (port: number) => Promise<boolean>): Promise<number> {
55
+ for (let p = FIRST_PORT; p <= LAST_PORT; p++) if (!taken.has(p) && !(await answering(p))) return p
56
+ throw new Error(`no free devtools port in ${FIRST_PORT}..${LAST_PORT}`)
57
+ }
58
+
59
+ /** what a slot's file holds: its browser's pid, the script version that started it, its devtools port */
60
+ export type SlotBrowser = { pid: number; version: string; port: number }
61
+ export const slotLine = (b: SlotBrowser): string => `${b.pid} ${b.version} ${b.port}`
62
+ export function parseSlotLine(s: string): SlotBrowser | null {
63
+ const [pid, version, port] = s.trim().split(' ')
64
+ return Number(pid) > 0 && Number(port) > 0 ? { pid: Number(pid), version: version ?? '', port: Number(port) } : null
65
+ }
66
+
67
+ const pidFile = (key: string) => join(SLOTS, `${key}.pid`)
68
+ const usedFile = (key: string) => join(SLOTS, `${key}.used`)
69
+ const readSlot = (key: string): SlotBrowser | null => (existsSync(pidFile(key)) ? parseSlotLine(readFileSync(pidFile(key), 'utf8')) : null)
70
+
71
+ /** one line of what the box did to its browsers (started, ended and why, pages closed), kept under 1 MB */
72
+ function log(line: string): void {
73
+ try {
74
+ if ((statSync(LOG, { throwIfNoEntry: false })?.size ?? 0) > 1 << 20) rmSync(LOG, { force: true })
75
+ appendFileSync(LOG, `${new Date().toISOString()} ${line}\n`)
76
+ } catch {}
77
+ }
78
+
32
79
  /** playwright's own switches for a launched chromium (chromiumSwitches, headless), so a page films here as it would
33
80
  * under a launch: --disable-ipc-flooding-protection above all, without which chromium drops a page's history updates
34
81
  * past 200 in 10 s and a take's clock (its hash's stop=) froze at frame 201 */
@@ -70,9 +117,9 @@ const BROWSER_ARGS = [
70
117
  '--lang=en-US',
71
118
  ]
72
119
 
73
- async function answers(port: number): Promise<boolean> {
120
+ async function answers(port: number, ms = ANSWER_MS): Promise<boolean> {
74
121
  try {
75
- return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(1000) })).ok
122
+ return (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(ms) })).ok
76
123
  } catch {
77
124
  return false
78
125
  }
@@ -112,7 +159,7 @@ function detached(line: string): number {
112
159
  return pid
113
160
  }
114
161
 
115
- const kill = (pid: number) => Bun.spawnSync(['taskkill', '/T', '/F', '/PID', String(pid)], { stdout: 'ignore', stderr: 'ignore' })
162
+ const killTree = (pid: number) => Bun.spawnSync(['taskkill', '/T', '/F', '/PID', String(pid)], { stdout: 'ignore', stderr: 'ignore' })
116
163
 
117
164
  const alive = (pid: number) => {
118
165
  try {
@@ -123,6 +170,20 @@ const alive = (pid: number) => {
123
170
  }
124
171
  }
125
172
 
173
+ /** the pid still names a headless shell: Windows hands a dead process's pid to the next one */
174
+ function isShell(pid: number): boolean {
175
+ const p = Bun.spawnSync(['tasklist', '/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH'], { stdout: 'pipe', stderr: 'ignore' })
176
+ return p.stdout.toString().toLowerCase().includes('chrome-headless-shell')
177
+ }
178
+
179
+ /** a browser ended, said in the log, once its pid is still a headless shell; waits until it is gone (its profile freed) */
180
+ async function end(pid: number, why: string): Promise<void> {
181
+ if (!isShell(pid)) return
182
+ log(`end ${pid}: ${why}`)
183
+ killTree(pid)
184
+ for (let i = 0; i < 50 && alive(pid); i++) await Bun.sleep(100)
185
+ }
186
+
126
187
  const quote = (s: string) => `"${s}"`
127
188
 
128
189
  /** the LUID of the box's discrete GPU as chromium names it (`high,low`): chromium on Windows draws on the adapter the
@@ -135,16 +196,18 @@ async function discreteLuid(exe: string): Promise<string | null> {
135
196
  const profile = join(DIR, 'probe-profile')
136
197
  const pid = detached([exe, '--headless=new', `--remote-debugging-port=${PROBE_PORT}`, `--user-data-dir=${profile}`, '--no-first-run', 'about:blank'].map(quote).join(' '))
137
198
  try {
138
- for (let i = 0; i < 100 && !(await answers(PROBE_PORT)); i++) await Bun.sleep(100)
139
- const target = (await (await fetch(`http://127.0.0.1:${PROBE_PORT}/json/new?chrome://gpu`, { method: 'PUT' })).json()) as { webSocketDebuggerUrl: string }
199
+ for (let i = 0; i < 100 && !(await answers(PROBE_PORT, 1000)); i++) await Bun.sleep(100)
200
+ const target = (await (await fetch(`http://127.0.0.1:${PROBE_PORT}/json/new?chrome://gpu`, { method: 'PUT', signal: AbortSignal.timeout(ANSWER_MS) })).json()) as { webSocketDebuggerUrl: string }
140
201
  const text = await new Promise<string>((done, fail) => {
141
202
  const ws = new WebSocket(target.webSocketDebuggerUrl)
203
+ const t = setTimeout(() => (ws.close(), fail(new Error('chrome://gpu: no answer in 10 s'))), 10_000)
142
204
  let n = 0
143
205
  const ask = () => ws.send(JSON.stringify({ id: ++n, method: 'Runtime.evaluate', params: { expression: "document.querySelector('info-view')?.shadowRoot?.textContent ?? ''", returnByValue: true } }))
144
206
  ws.onopen = ask
145
207
  ws.onmessage = (e) => {
146
208
  const v = (JSON.parse(String(e.data)) as { result?: { result?: { value?: string } } }).result?.result?.value ?? ''
147
209
  if (/GPU0/.test(v)) {
210
+ clearTimeout(t)
148
211
  ws.close()
149
212
  done(v)
150
213
  } else if (n > 50) fail(new Error('chrome://gpu named no GPU in 5 s'))
@@ -158,135 +221,148 @@ async function discreteLuid(exe: string): Promise<string | null> {
158
221
  return got
159
222
  } finally {
160
223
  // its profile stays for the next boot's probe: chromium holds its files a while after the kill
161
- kill(pid)
224
+ killTree(pid)
162
225
  }
163
226
  }
164
227
 
165
- /** the browser up now, as browser.pid holds it: its pid, the script version that started it, its devtools port */
166
- function current(): { pid: number; version: string; port: number } | null {
167
- if (!existsSync(PID)) return null
168
- const [pid, version, port] = readFileSync(PID, 'utf8').trim().split(' ')
169
- return Number(pid) > 0 ? { pid: Number(pid), version: version ?? '', port: Number(port) || CDP_PORT } : null
228
+ /** one devtools call on the browser's own socket, ANSWER_MS at most */
229
+ async function browserCall<T>(port: number, method: string, params: Record<string, unknown> = {}): Promise<T> {
230
+ const { webSocketDebuggerUrl } = (await (await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(ANSWER_MS) })).json()) as { webSocketDebuggerUrl: string }
231
+ return await new Promise<T>((done, fail) => {
232
+ const ws = new WebSocket(webSocketDebuggerUrl)
233
+ const t = setTimeout(() => (ws.close(), fail(new Error(`${method}: no answer in ${ANSWER_MS / 1000} s`))), ANSWER_MS)
234
+ ws.onopen = () => ws.send(JSON.stringify({ id: 1, method, params }))
235
+ ws.onmessage = (e) => {
236
+ clearTimeout(t)
237
+ ws.close()
238
+ done((JSON.parse(String(e.data)) as { result: T }).result)
239
+ }
240
+ ws.onerror = () => fail(new Error(`${method}: the browser's socket failed`))
241
+ })
170
242
  }
171
243
 
172
- async function up(version: string): Promise<void> {
244
+ type Target = { targetId: string; type: string; url: string; attached: boolean }
245
+
246
+ /** the pages that show something (about:blank aside) */
247
+ async function pages(port: number): Promise<Target[]> {
248
+ const { targetInfos } = await browserCall<{ targetInfos: Target[] }>(port, 'Target.getTargets')
249
+ return targetInfos.filter((p) => p.type === 'page' && p.url !== 'about:blank')
250
+ }
251
+
252
+ /** the slot's browser answering for the film that holds the slot now: warm, or started (a lock serializes the starts:
253
+ * the ports they pick, the LUID probe) */
254
+ async function up(version: string, key: string): Promise<void> {
255
+ if (!slotKeyOk(key)) throw new Error(`up: '${key}' is not a slot key`)
173
256
  const t = performance.now()
174
- mkdirSync(DIR, { recursive: true })
175
- writeFileSync(USED, String(Date.now()))
176
- const warm = async () => {
177
- const c = current()
178
- return c != null && c.version === VERSION && (await answers(c.port)) ? c : null
179
- }
180
- const w = await warm()
181
- if (w) {
182
- console.log(`up warm ${Math.round(performance.now() - t)} port ${w.port}`)
257
+ mkdirSync(SLOTS, { recursive: true })
258
+ writeFileSync(usedFile(key), String(Date.now()))
259
+ const c = readSlot(key)
260
+ if (c != null && c.version === VERSION && alive(c.pid) && (await answers(c.port))) {
261
+ // the slot is this film's: a page still open in its browser is a film's that died or never closed it
262
+ const left = await pages(c.port).catch(() => [])
263
+ for (const p of left) await browserCall(c.port, 'Target.closeTarget', { targetId: p.targetId }).catch(() => undefined)
264
+ if (left.length) log(`${key}: ${left.length} page(s) left by an earlier film closed`)
265
+ console.log(`up warm ${Math.round(performance.now() - t)} port ${c.port}${left.length ? `, ${left.length} page(s) an earlier film left closed` : ''}`)
183
266
  return
184
267
  }
185
- // several films asking at once start one browser: the first starts it, the others wait and find it warm
186
- const lock = join(DIR, 'up.lock')
268
+ if (c != null) await end(c.pid, `${key}: ${c.version !== VERSION ? 'another film-box version' : 'its devtools did not answer'}`)
269
+ await start(version, key, t)
270
+ }
271
+
272
+ async function start(version: string, key: string, t: number): Promise<void> {
273
+ const lock = join(DIR, 'start.lock')
187
274
  for (;;) {
188
275
  try {
189
276
  mkdirSync(lock)
190
277
  break
191
278
  } catch {
192
279
  if (Date.now() - (statSync(lock, { throwIfNoEntry: false })?.mtimeMs ?? Date.now()) > 60_000) rmSync(lock, { recursive: true, force: true })
193
- await Bun.sleep(200)
280
+ await Bun.sleep(100)
194
281
  }
195
282
  }
283
+ let b: SlotBrowser
284
+ let luid: string | null
196
285
  try {
197
- const again = await warm()
198
- if (again) console.log(`up warm ${Math.round(performance.now() - t)} port ${again.port}`)
199
- else await start(version, t)
286
+ await endLegacy()
287
+ const exe = chromium(version)
288
+ luid = await discreteLuid(exe.full)
289
+ if (luid == null) say('no discrete GPU named in chrome://gpu: the browser draws on the default adapter')
290
+ const taken = new Set<number>()
291
+ for (const f of readdirSync(SLOTS).filter((f) => f.endsWith('.pid'))) {
292
+ const s = parseSlotLine(readFileSync(join(SLOTS, f), 'utf8'))
293
+ if (s != null && alive(s.pid)) taken.add(s.port)
294
+ }
295
+ const port = await freePort(taken, (p) => answers(p, 300))
296
+ const args = [`--remote-debugging-port=${port}`, `--user-data-dir=${join(DIR, `profile-${key}`)}`, ...BROWSER_ARGS, ...(luid ? [`--use-adapter-luid=${luid}`] : []), 'about:blank']
297
+ b = { pid: detached([exe.shell, ...args].map(quote).join(' ')), version: VERSION, port }
298
+ writeFileSync(pidFile(key), slotLine(b))
200
299
  } finally {
201
300
  rmSync(lock, { recursive: true, force: true })
202
301
  }
302
+ for (let i = 0; i < 150 && !(await answers(b.port, 1000)); i++) await Bun.sleep(100)
303
+ if (!(await answers(b.port))) throw new Error(`the browser of ${key} (pid ${b.pid}) did not answer on 127.0.0.1:${b.port} in 15 s`)
304
+ detached([process.execPath, import.meta.path, 'watch', key, String(b.pid), String(b.port)].map(quote).join(' '))
305
+ log(`${key}: started ${b.pid} on ${b.port}`)
306
+ console.log(`up started ${Math.round(performance.now() - t)} port ${b.port} pid ${b.pid}${luid ? ` luid ${luid}` : ''}`)
203
307
  }
204
308
 
205
- /** a new browser on the port the old one does not hold, with its own profile (chromium locks one per process): the
206
- * old one, if a film still runs in it, drains (its watcher ends it once no film drives a page), never killed mid take */
207
- async function start(version: string, t: number): Promise<void> {
208
- const old = current()
209
- const oldUp = old != null && alive(old.pid) && (await answers(old.port))
210
- const port = oldUp && old.port === CDP_PORT ? CDP_PORT + 3 : CDP_PORT
211
- if (old != null && !oldUp) kill(old.pid)
212
- if (oldUp) {
213
- if ((await filming(old.port).catch(() => 0)) === 0) kill(old.pid)
214
- else detached([process.execPath, import.meta.path, 'watch', String(old.pid), String(old.port), 'drain'].map(quote).join(' '))
215
- }
216
- const exe = chromium(version)
217
- const luid = await discreteLuid(exe.full)
218
- if (luid == null) say('no discrete GPU named in chrome://gpu: the browser draws on the default adapter')
219
- const args = [`--remote-debugging-port=${port}`, `--user-data-dir=${join(DIR, `profile-${port}`)}`, ...BROWSER_ARGS, ...(luid ? [`--use-adapter-luid=${luid}`] : []), 'about:blank']
220
- const pid = detached([exe.shell, ...args].map(quote).join(' '))
221
- writeFileSync(PID, `${pid} ${VERSION} ${port}`)
222
- for (let i = 0; i < 150 && !(await answers(port)); i++) await Bun.sleep(100)
223
- if (!(await answers(port))) throw new Error(`the browser (pid ${pid}) did not answer on 127.0.0.1:${port} in 15 s`)
224
- detached([process.execPath, import.meta.path, 'watch', String(pid), String(port)].map(quote).join(' '))
225
- console.log(`up started ${Math.round(performance.now() - t)} port ${port} pid ${pid}${luid ? ` luid ${luid}` : ''}${oldUp ? `, the old one on ${old.port} draining` : ''}`)
226
- }
227
-
228
- /** one devtools call on the browser's own socket */
229
- async function browserCall<T>(port: number, method: string, params: Record<string, unknown> = {}): Promise<T> {
230
- const { webSocketDebuggerUrl } = (await (await fetch(`http://127.0.0.1:${port}/json/version`)).json()) as { webSocketDebuggerUrl: string }
231
- return await new Promise<T>((done, fail) => {
232
- const ws = new WebSocket(webSocketDebuggerUrl)
233
- const t = setTimeout(() => (ws.close(), fail(new Error(`${method}: no answer in 5 s`))), 5000)
234
- ws.onopen = () => ws.send(JSON.stringify({ id: 1, method, params }))
235
- ws.onmessage = (e) => {
236
- clearTimeout(t)
237
- ws.close()
238
- done((JSON.parse(String(e.data)) as { result: T }).result)
239
- }
240
- ws.onerror = () => fail(new Error(`${method}: the browser's socket failed`))
241
- })
242
- }
243
-
244
- type Target = { targetId: string; type: string; url: string; attached: boolean }
245
-
246
- /** the pages a film drives now */
247
- async function filming(port: number): Promise<number> {
248
- const { targetInfos } = await browserCall<{ targetInfos: Target[] }>(port, 'Target.getTargets')
249
- return targetInfos.filter((p) => p.type === 'page' && p.url !== 'about:blank' && p.attached).length
309
+ /** the one browser older versions shared between every film, ended once no film drives a page in it and none asked
310
+ * for it in LEGACY_QUIET_MS (a process still running older code connects between its up and its first page) */
311
+ async function endLegacy(): Promise<void> {
312
+ if (!existsSync(LEGACY_PID)) return
313
+ if (Date.now() - (statSync(LEGACY_USED, { throwIfNoEntry: false })?.mtimeMs ?? 0) < LEGACY_QUIET_MS) return
314
+ const [pid, , port] = readFileSync(LEGACY_PID, 'utf8').trim().split(' ')
315
+ const busy = await pages(Number(port) || CDP_PORT).then(
316
+ (p) => p.some((t) => t.attached),
317
+ () => false,
318
+ )
319
+ if (busy) return
320
+ await end(Number(pid), 'the shared browser of an older film-box version')
321
+ rmSync(LEGACY_PID, { force: true })
250
322
  }
251
323
 
252
- /** every SWEEP_MS: a page no client drives two sweeps in a row is closed (its film's process died and left it drawing
253
- * on the GPU); every IDLE_CHECK_MS the idle rule. `drain`: a replaced browser, ended once no film drives a page */
254
- const SWEEP_MS = 5000
255
- const IDLE_CHECK_MS = 30_000
256
-
257
- async function watch(pid: number, port: number, drain: boolean): Promise<void> {
324
+ async function watch(key: string, pid: number, port: number): Promise<void> {
258
325
  let orphans = new Set<string>()
259
- for (let n = 1; ; n++) {
326
+ let deaf = 0
327
+ for (;;) {
260
328
  await Bun.sleep(SWEEP_MS)
261
329
  if (!alive(pid)) return
262
- let busy = false
263
- let driven = 1
330
+ // replaced: the slot's next up started another browser
331
+ if (readSlot(key)?.pid !== pid) return void (await end(pid, `${key}: replaced`))
332
+ let shown: Target[]
264
333
  try {
265
- const { targetInfos } = await browserCall<{ targetInfos: Target[] }>(port, 'Target.getTargets')
266
- const pages = targetInfos.filter((t) => t.type === 'page' && t.url !== 'about:blank')
267
- busy = pages.length > 0
268
- driven = pages.filter((t) => t.attached).length
269
- const now = new Set(pages.filter((t) => !t.attached).map((t) => t.targetId))
270
- for (const id of now) if (orphans.has(id)) await browserCall(port, 'Target.closeTarget', { targetId: id })
271
- orphans = now
272
- } catch {}
273
- if (drain && driven === 0) return void kill(pid)
274
- if ((n * SWEEP_MS) % IDLE_CHECK_MS !== 0) continue
275
- const idle = Date.now() - (statSync(USED, { throwIfNoEntry: false })?.mtimeMs ?? 0)
276
- if (idle > STALE_MS || (idle > IDLE_MS && !busy)) {
277
- kill(pid)
278
- if (current()?.pid === pid) rmSync(PID, { force: true })
279
- return
334
+ shown = await pages(port)
335
+ deaf = 0
336
+ } catch {
337
+ if (++deaf < DEAF_SWEEPS) continue
338
+ await end(pid, `${key}: its devtools did not answer for ${(DEAF_SWEEPS * SWEEP_MS) / 1000} s`)
339
+ return forget(key, pid)
340
+ }
341
+ const now = new Set(shown.filter((t) => !t.attached).map((t) => t.targetId))
342
+ for (const id of now)
343
+ if (orphans.has(id)) {
344
+ await browserCall(port, 'Target.closeTarget', { targetId: id }).catch(() => undefined)
345
+ log(`${key}: a page no film drives closed`)
346
+ }
347
+ orphans = now
348
+ const idle = Date.now() - (statSync(usedFile(key), { throwIfNoEntry: false })?.mtimeMs ?? 0)
349
+ if (idle > IDLE_MS && shown.length === 0) {
350
+ await end(pid, `${key}: idle`)
351
+ return forget(key, pid)
280
352
  }
281
353
  }
282
354
  }
283
355
 
356
+ function forget(key: string, pid: number): void {
357
+ if (readSlot(key)?.pid === pid) rmSync(pidFile(key), { force: true })
358
+ }
359
+
284
360
  if (import.meta.main) {
285
- const [cmd, arg, port, mode] = process.argv.slice(2)
286
- if (cmd === 'up' && arg) await up(arg)
287
- else if (cmd === 'watch' && Number(arg) > 0) await watch(Number(arg), Number(port) || CDP_PORT, mode === 'drain')
361
+ const [cmd, a, b, c] = process.argv.slice(2)
362
+ if (cmd === 'up' && a && b) await up(a, b)
363
+ else if (cmd === 'watch' && b && Number(b) > 0 && Number(c) > 0) await watch(a!, Number(b), Number(c))
288
364
  else {
289
- console.error('usage: film-box.ts up <playwright version> | watch <browser pid> [port] [drain]')
365
+ console.error('usage: film-box.ts up <playwright version> <slot key> | watch <slot key> <browser pid> <port>')
290
366
  process.exit(2)
291
367
  }
292
368
  }