rvlib-shipkit 2.17.0 → 2.18.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 (52) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/package.json +1 -1
  3. package/src/checks/SK039-vscode-watch-generated.check.ts +119 -0
  4. package/src/cli/cmd_Review.ts +4 -0
  5. package/src/core/discover-checks.ts +18 -5
  6. package/src/home/beat.ts +30 -0
  7. package/src/home/home-paths.ts +1 -0
  8. package/src/home/pm.ts +3 -1
  9. package/src/home/run-daemon.ts +5 -2
  10. package/src/home/run-web.ts +4 -2
  11. package/src/home/supervise.ts +18 -1
  12. package/src/review/model.ts +11 -0
  13. package/src/scaffold/files/vscode-settings.json +9 -1
  14. package/src/serve/hub-app/auto-text.tsx +6 -1
  15. package/src/serve/hub-app/hub-app.tsx +28 -2
  16. package/src/serve/hub-app/icons.tsx +1 -0
  17. package/src/serve/hub-app/identities-view.tsx +1 -1
  18. package/src/serve/hub-app/kept-cols.tsx +47 -8
  19. package/src/serve/hub-app/layout-st.ts +37 -3
  20. package/src/serve/hub-app/review/review-kit.ts +8 -0
  21. package/src/serve/hub-app/review/review-page.tsx +1 -1
  22. package/src/serve/hub-app/review/review-st.ts +38 -6
  23. package/src/serve/hub-app/review/review-thread.tsx +2 -1
  24. package/src/serve/hub-app/review/review-views.tsx +91 -20
  25. package/src/serve/hub-app/review/thread-st.ts +23 -1
  26. package/src/serve/hub-app/review/trailer-page.tsx +1 -1
  27. package/src/serve/hub-app/review.css +24 -0
  28. package/src/serve/hub-app/social/comms-page.tsx +1 -1
  29. package/src/serve/hub-app/social/kit.tsx +3 -3
  30. package/src/serve/hub-app/social/post-card.tsx +2 -1
  31. package/src/serve/hub-app/social/social-page.tsx +1 -1
  32. package/src/serve/hub-app/social.css +1 -1
  33. package/src/serve/hub-app/stores/stores-page.tsx +5 -4
  34. package/src/serve/hub-app/veille/veille-page.tsx +3 -2
  35. package/src/serve/serve-hub.ts +4 -4
  36. package/src/serve/warm-cell.ts +63 -1
  37. package/src/shot/box.ts +32 -9
  38. package/src/shot/browser-slot.ts +8 -1
  39. package/src/shot/client.ts +9 -4
  40. package/src/shot/clip-encoder.ts +5 -2
  41. package/src/shot/job-store.ts +167 -0
  42. package/src/shot/shooter.ts +31 -4
  43. package/src/social/load.ts +3 -1
  44. package/src/suite/select.ts +32 -6
  45. package/src/trailer/grammar.ts +2 -0
  46. package/src/trailer/graph.ts +9 -3
  47. package/src/trailer/sound/presets.ts +3 -3
  48. package/src/trailer/sound/run.ts +22 -14
  49. package/src/trailer/titles.ts +1 -1
  50. package/src/wiki/lint-md.ts +4 -2
  51. package/src/wiki/run-wiki.ts +11 -5
  52. package/src/wiki/scan-md.ts +3 -1
@@ -11,6 +11,7 @@ import type { RepoSt } from '../repo-st.ts'
11
11
  import { PANEL, PhoneTop } from '../review/review-page.tsx'
12
12
  import { type FeedRow, type Platform, shelfOf, SHELVES, type VeilleSt, WINDOWS } from './veille-st.ts'
13
13
  import { Caret } from '../icons.tsx'
14
+ import { AutoText } from '../auto-text.tsx'
14
15
 
15
16
  const short = (n: number | null): string => (n == null ? '–' : n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e4 ? `${Math.round(n / 1e3)}k` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n))
16
17
  const age = (ms: number): string => (ms < 3600_000 ? `${Math.max(1, Math.round(ms / 60_000))} min` : ms < 48 * 3600_000 ? `${Math.round(ms / 3600_000)} h` : `${Math.round(ms / 86_400_000)} j`)
@@ -66,7 +67,7 @@ export const VeillePage = observer(({ app }: { app: RepoSt }) => {
66
67
  return (
67
68
  <>
68
69
  <Toast v={v} />
69
- <KeptCols id="veille">
70
+ <KeptCols id="veille" folds={{}} layout={app.home.layout}>
70
71
  <Panel id="veille-deck" defaultSize="72%" minSize={480} className="rv-pane" style={PANEL}>
71
72
  <Deck v={v} />
72
73
  </Panel>
@@ -389,7 +390,7 @@ const ReplyPanel = observer(({ v }: { v: VeilleSt }) => {
389
390
  </div>
390
391
  <label className="vl-label">
391
392
  Notre réponse
392
- <textarea rows={5} placeholder="« Proposer » la demande à un agent, ou écris la ici (la voix de l'identité)" value={text} onChange={(e) => v.setText(r.key, e.currentTarget.value)} />
393
+ <AutoText rows={5} placeholder="« Proposer » la demande à un agent, ou écris la ici (la voix de l'identité)" value={text} onText={(t) => v.setText(r.key, t)} />
393
394
  </label>
394
395
  <div className={`vl-small ${text.length > v.max ? 't-red vl-over' : 'rv-dim'}`}>
395
396
  {text.length} / {v.max}
@@ -32,7 +32,7 @@ import { projectGutter } from './project-gutter-route.ts'
32
32
  import { sameOrigin } from './same-origin.ts'
33
33
  import { LAYOUT } from '../core/layout.ts'
34
34
  import { heldNow, heldText } from '../core/last-good.ts'
35
- import { WarmCell } from './warm-cell.ts'
35
+ import { WarmCell, warmQueue } from './warm-cell.ts'
36
36
  import { resourcesAnswer, testRunsAnswer } from './resources-wire.ts'
37
37
  import { readmeRoutes } from './readme-route.ts'
38
38
  import { reviewRoutes } from '../review/routes.ts'
@@ -185,15 +185,15 @@ export function hubHandler(d: HubDeps, o: { base?: string; projects?: Gutter } =
185
185
  const projects = o.projects ?? projectGutter({ root: d.root })
186
186
  // the answers a page waits on when a repo shows, kept warm in memory: a
187
187
  // request answers from here and never walks the repo (warm-cell.ts)
188
- const warmOpts = { stamp: d.stamp, maxAgeMs: WARM_MAX_AGE_MS }
188
+ const warmOpts = { stamp: d.stamp, maxAgeMs: WARM_MAX_AGE_MS, queue: warmQueue }
189
189
  const rows = new WarmCell<Rows>(async () => {
190
190
  await d.refresh?.()
191
191
  const cols = d.collections()
192
192
  return { collections: cols.map((c) => ({ id: c.id, title: c.title, media: c.media })), resources: await projectResources(cols, d.hubProblems?.collector) }
193
193
  }, { ...warmOpts, what: `warm rows: ${d.name}` })
194
194
  // the run record and the config are all it reads, and the stamp sees both
195
- const timeline = d.timeline == null ? null : new WarmCell(d.timeline, { stamp: d.stamp, what: `warm timeline: ${d.name}` })
196
- const graphs = new Map(d.graphs.map((g) => [g.id, new WarmCell(async () => g.load(), { maxAgeMs: WARM_MAX_AGE_MS, what: `warm graph ${g.id}: ${d.name}` })]))
195
+ const timeline = d.timeline == null ? null : new WarmCell(d.timeline, { stamp: d.stamp, queue: warmQueue, what: `warm timeline: ${d.name}` })
196
+ const graphs = new Map(d.graphs.map((g) => [g.id, new WarmCell(async () => g.load(), { maxAgeMs: WARM_MAX_AGE_MS, queue: warmQueue, what: `warm graph ${g.id}: ${d.name}` })]))
197
197
  const fresh = (req: Request): boolean => new URL(req.url).searchParams.get('fresh') === '1'
198
198
  /** the last gzipped list, answered again to the next page while it holds */
199
199
  let zipped: Parameters<typeof resourcesAnswer>[3] = null
@@ -19,7 +19,66 @@ export const WARM_WATCH_MS = 30_000
19
19
  * after it ended: a 1.5s answer at most every 15s, a 50ms one at once */
20
20
  export const WARM_SPACING = 10
21
21
 
22
+ /** a background recompute of the queue waits this many times the last one's length after it ended, whichever cell
23
+ * it was: however many repos one process serves, their background warms hold its loop a quarter of the time at most */
24
+ export const WARM_GAP = 3
25
+
26
+ /** the background recomputes of every cell given it, one at a time, spaced by WARM_GAP times the last one's length.
27
+ * Per cell spacing alone let fourteen watched repos, each a tenth of the time, hold the daemon's loop more than all
28
+ * of it on a loaded machine. A reader waiting on an answer never queues: only the recomputes behind a served answer */
29
+ export class WarmQueue {
30
+ private waiting: { key: object; go: () => Promise<unknown> }[] = []
31
+ private busy = false
32
+ private nextAt = 0
33
+ private timer: ReturnType<typeof setTimeout> | null = null
34
+
35
+ constructor(private readonly gap = WARM_GAP, private readonly now: () => number = () => performance.now()) {}
36
+
37
+ /** `go` in its turn; a key already waiting keeps its place and is not queued twice */
38
+ add(key: object, go: () => Promise<unknown>): void {
39
+ if (this.waiting.some((w) => w.key === key)) return
40
+ this.waiting.push({ key, go })
41
+ this.pump()
42
+ }
43
+
44
+ get length(): number {
45
+ return this.waiting.length
46
+ }
47
+
48
+ private pump(): void {
49
+ if (this.busy || this.timer != null) return
50
+ const next = this.waiting[0]
51
+ if (next == null) return
52
+ const wait = this.nextAt - this.now()
53
+ if (wait > 0) {
54
+ this.timer = setTimeout(() => {
55
+ this.timer = null
56
+ this.pump()
57
+ }, wait)
58
+ this.timer.unref?.()
59
+ return
60
+ }
61
+ this.waiting.shift()
62
+ this.busy = true
63
+ const start = this.now()
64
+ void next
65
+ .go()
66
+ .catch(() => {})
67
+ .finally(() => {
68
+ const end = this.now()
69
+ this.nextAt = end + this.gap * (end - start)
70
+ this.busy = false
71
+ this.pump()
72
+ })
73
+ }
74
+ }
75
+
76
+ /** the process's one queue: every hub of the daemon gives its warm cells this one */
77
+ export const warmQueue = new WarmQueue()
78
+
22
79
  export type WarmCellOpts = {
80
+ /** the queue its background recomputes take turns in; none, each runs at once */
81
+ queue?: WarmQueue
23
82
  /** a cheap fingerprint of what the answer reads (file stats): a new one
24
83
  * marks the answer stale */
25
84
  stamp?: () => string
@@ -78,7 +137,10 @@ export class WarmCell<T> {
78
137
  * kicks again. On a failure the last answer stays */
79
138
  private kick(): void {
80
139
  if (this.last != null && this.now() < this.last.end + WARM_SPACING * this.last.ms) return
81
- void this.run().catch(() => {})
140
+ const q = this.o.queue
141
+ if (q == null) return void this.run().catch(() => {})
142
+ // in its turn, only when the answer still needs it: a reader may have computed it meanwhile
143
+ q.add(this, () => (this.stale || this.gen !== this.runGen ? this.run() : Promise.resolve()))
82
144
  }
83
145
 
84
146
  /** a reader asked within WARM_WATCH_MS */
package/src/shot/box.ts CHANGED
@@ -11,11 +11,22 @@ import { createHash } from 'crypto'
11
11
  import { readFileSync } from 'fs'
12
12
  import { browserCap, browserSlot, filmBox, HERE_ENV } from './browser-slot.ts'
13
13
  import { CDP_PORT } from './film-box.ts'
14
+ import { JOB_STORE_END, jobId, jobStoreScript } from './job-store.ts'
14
15
 
15
16
 
16
17
  /** the slice of playwright the route drives: a browser to connect to, its default context, a page's viewport */
17
- type PwPage = { setViewportSize(v: { width: number; height: number }): Promise<void>; addInitScript(s: { content: string }): Promise<void>; close(): Promise<void> }
18
- type PwContext = { newPage(): Promise<PwPage>; newCDPSession(p: PwPage): Promise<{ send(m: string, p?: Record<string, unknown>): Promise<unknown> }> }
18
+ type PwPage = {
19
+ setViewportSize(v: { width: number; height: number }): Promise<void>
20
+ addInitScript(s: { content: string }): Promise<void>
21
+ evaluate(expression: string): Promise<unknown>
22
+ close(): Promise<void>
23
+ }
24
+ type PwContext = {
25
+ newPage(): Promise<PwPage>
26
+ newCDPSession(p: PwPage): Promise<{ send(m: string, p?: Record<string, unknown>): Promise<unknown> }>
27
+ cookies(): Promise<unknown[]>
28
+ addCookies(c: unknown[]): Promise<void>
29
+ }
19
30
  export type PwBrowser = { contexts(): PwContext[]; close(): Promise<void>; isConnected(): boolean; on(e: 'disconnected', cb: () => void): void }
20
31
  export type Pw = { chromium: { launch(o: { headless: boolean; args: string[] }): Promise<unknown>; connectOverCDP(url: string): Promise<PwBrowser> } }
21
32
 
@@ -71,21 +82,30 @@ async function forward(box: string, spec: string[], own: { p: ReturnType<typeof
71
82
 
72
83
  const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]'])
73
84
 
85
+ /** whose local store a box page sees: its context's own (job-store.ts), or the origin's one store every job shares */
86
+ export type BoxStore = 'job' | 'shared'
87
+
88
+ /** a page's store removed before it closes; a page that does not answer (frozen, gone) is let go after END_MS, its
89
+ * leftovers swept later by the stale beat rule */
90
+ const END_MS = 500
91
+ const closed = (p: PwPage): Promise<void> =>
92
+ Promise.race([p.evaluate(JOB_STORE_END).catch(() => undefined), Bun.sleep(END_MS)]).then(() => p.close().catch(() => undefined))
93
+
74
94
  /** the box's default context as a launched browser's newContext: each context a set of pages there, the viewport set
75
- * per page; one context because only it keeps the profile's HTTP cache */
76
- function asLaunched(b: PwBrowser, all: PwPage[]) {
95
+ * per page, its own local store unless `store` is 'shared'; one context because only it keeps the profile's HTTP cache */
96
+ export function asLaunched(b: PwBrowser, all: PwPage[], store: BoxStore = 'job') {
77
97
  return {
78
98
  isConnected: () => b.isConnected(),
79
99
  on: (e: 'disconnected', cb: () => void) => b.on(e, cb),
80
100
  close: async () => {
81
- await Promise.all(all.splice(0).map((p) => p.close().catch(() => undefined)))
101
+ await Promise.all(all.splice(0).map(closed))
82
102
  await b.close()
83
103
  },
84
104
  async newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number }) {
85
105
  const ctx = b.contexts()[0]
86
106
  if (ctx == null) throw new Error('the box browser has no default context')
87
107
  const pages: PwPage[] = []
88
- const scripts: string[] = []
108
+ const scripts: string[] = store === 'job' ? [jobStoreScript(jobId())] : []
89
109
  return {
90
110
  async newPage() {
91
111
  const p = await ctx.newPage()
@@ -98,12 +118,15 @@ function asLaunched(b: PwBrowser, all: PwPage[]) {
98
118
  return p
99
119
  },
100
120
  newCDPSession: (p: PwPage) => ctx.newCDPSession(p),
121
+ // the one default context holds every page's cookies already
122
+ cookies: () => ctx.cookies(),
123
+ addCookies: async () => undefined,
101
124
  async addInitScript(s: { content: string }) {
102
125
  scripts.push(s.content)
103
126
  for (const p of pages) await p.addInitScript(s)
104
127
  },
105
128
  async close() {
106
- await Promise.all(pages.splice(0).map((p) => p.close().catch(() => undefined)))
129
+ await Promise.all(pages.splice(0).map(closed))
107
130
  },
108
131
  }
109
132
  },
@@ -112,7 +135,7 @@ function asLaunched(b: PwBrowser, all: PwPage[]) {
112
135
 
113
136
  /** a browser for `who` of the repo at `root`: on its box from a Mac (filmBox), else launched here; one of the repo's
114
137
  * browser slots held until close */
115
- export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void }): Promise<Opened<B>> {
138
+ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; args: string[]; say?: (l: string) => void; store?: BoxStore }): Promise<Opened<B>> {
116
139
  const say = o.say ?? ((l: string) => console.error(l))
117
140
  const cap = await browserCap(o.root)
118
141
  const box = filmBox(cap)
@@ -134,7 +157,7 @@ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; ar
134
157
  say(`${o.who}: filming on ${box} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to its browser)`)
135
158
  const reached = new Set<number>()
136
159
  const pages: PwPage[] = []
137
- const browser = asLaunched(b, pages)
160
+ const browser = asLaunched(b, pages, o.store)
138
161
  return {
139
162
  browser: browser as B,
140
163
  where: box,
@@ -52,6 +52,13 @@ export function browserRefusal(c: Pick<BrowserCap, 'repo' | 'box'>, who: string,
52
52
  return `${who}: ${c.repo} films on ${c.box.host} (repo.config.ts browsers.box), so no browser of it starts on this Mac: a browser goes through shot/box.ts openBrowser (${HERE_ENV}=1 films here for one run, the owner's call)`
53
53
  }
54
54
 
55
+ /** a slot holder as a waiter names it: its pid, what it runs, how long it has held the slot */
56
+ export function holderWords(h: { pid: number; check: string; since: number }, now = Date.now()): string {
57
+ const min = Math.floor((now - h.since) / 60_000)
58
+ const age = min < 1 ? 'under a minute' : min < 60 ? `${min} min` : `${Math.floor(min / 60)} h ${String(min % 60).padStart(2, '0')} min`
59
+ return `pid ${h.pid} (${h.check}, held ${age})`
60
+ }
61
+
55
62
  /** wait for one of the repo's browser slots and hold it until the returned release (or this process ends), saying
56
63
  * once whom it waits on; outside any repo there is no cap and nothing is held. `onBox`: the browser runs on the
57
64
  * repo's box, this Mac only drives it */
@@ -67,7 +74,7 @@ export async function browserSlot(who: string, o: { root?: string; say?: (l: str
67
74
  const got = await takeSlot(pool, { repo: c.repo, check: who }, {
68
75
  pollMs: o.pollMs ?? 250,
69
76
  onWait: (held) =>
70
- say(`${who}: waiting for a browser of ${c.repo}${box ? ` on ${box.host}` : ''}, all ${cap} held (repo.config.ts ${key}): ${held.map((h) => `pid ${h.pid} (${h.check})`).join(', ') || 'a holder starting'}`),
77
+ 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'}`),
71
78
  })
72
79
  if (got == null) throw new Error(`${who}: the browser slot wait of ${c.repo} stopped with no slot`)
73
80
  return got.release
@@ -3,7 +3,7 @@
3
3
  // and shoot in process only when the machine has no pm (CI, SHIPKIT_NO_HOME). A repo filmed by its box films there
4
4
  // from a Mac (box.ts), on a Shooter of this process.
5
5
  // `sk shot` and the trailer's `url` film both call these.
6
- import { DEFAULT_FPS, DEFAULT_VIEWPORT, DEFAULT_WAIT_MS, type ClipAsk, type ShotAsk, shotUrlBase, type Viewport } from './shot-ask.ts'
6
+ import { capMsOf, DEFAULT_FPS, DEFAULT_VIEWPORT, DEFAULT_WAIT_MS, type ClipAsk, type ShotAsk, shotUrlBase, type Viewport } from './shot-ask.ts'
7
7
  import type { ShotDone } from './shooter.ts'
8
8
 
9
9
  /** the global process id pm knows the service by (shot.shipkit.ts) */
@@ -77,11 +77,16 @@ async function held<T>(who: string, i: ShotInput, log: (l: string) => void, run:
77
77
  }
78
78
 
79
79
  /** null when nothing listens (start it), else the service's answer; a refusal throws its reason */
80
- async function post(route: string, a: ShotAsk): Promise<ShotDone | null> {
80
+ /** how long an ask may wait on the service: its own cap, and as long again for the asks queued before it */
81
+ export const serviceWaitMs = (a: ShotAsk | ClipAsk): number => 2 * capMsOf(a)
82
+
83
+ async function post(route: string, a: ShotAsk | ClipAsk): Promise<ShotDone | null> {
81
84
  let r: Response
85
+ const ms = serviceWaitMs(a)
82
86
  try {
83
- r = await fetch(`${shotUrlBase()}${route}`, { method: 'POST', body: JSON.stringify(a), headers: { 'content-type': 'application/json' } })
84
- } catch {
87
+ r = await fetch(`${shotUrlBase()}${route}`, { method: 'POST', body: JSON.stringify(a), headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(ms) })
88
+ } catch (e) {
89
+ if (e instanceof Error && e.name === 'TimeoutError') throw new Error(`the shot service on ${shotUrlBase()} did not answer ${route} of ${a.url} in ${Math.round(ms / 1000)} s: sk gp restart ${SHOT_PROCESS}`)
85
90
  return null
86
91
  }
87
92
  if (!r.ok) throw new Error(await r.text())
@@ -221,7 +221,9 @@ export async function installClip(a: PageClipAsk): Promise<string | null> {
221
221
  /** IN THE PAGE: the stream made since the last take, at most `max` bytes (whole chunks, one at least), base64; '' when
222
222
  * none waits */
223
223
  export async function takeClip(max: number): Promise<string> {
224
- const st = (window as unknown as { __skClip: ClipState }).__skClip
224
+ const st = (window as unknown as { __skClip?: ClipState }).__skClip
225
+ // the page is a new document: it reloaded mid film (a dev server's hot reload when a file is saved)
226
+ if (st == null) throw new Error('the page reloaded while it was filmed (a dev server reloads on a save): film a page that holds still, a build or a server no lane writes to')
225
227
  if (st.failed) throw new Error(st.failed)
226
228
  const from = st.next
227
229
  let bytes = 0
@@ -239,7 +241,8 @@ export async function takeClip(max: number): Promise<string> {
239
241
  }
240
242
 
241
243
  /** IN THE PAGE: resolves once the film ran and the encoder flushed */
242
- export const clipDone = (): Promise<PageClipDone> => (window as unknown as { __skClip: ClipState }).__skClip.done
244
+ export const clipDone = (): Promise<PageClipDone> =>
245
+ (window as unknown as { __skClip?: ClipState }).__skClip?.done ?? Promise.reject(new Error('the page reloaded while it was filmed (a dev server reloads on a save): film a page that holds still, a build or a server no lane writes to'))
243
246
 
244
247
  /** the most stream one take carries, bytes: its base64 is a third more */
245
248
  export const TAKE = 8 << 20
@@ -0,0 +1,167 @@
1
+ // a box context's own store (box.ts asLaunched): every job on the box shares its browser's one default context for the
2
+ // HTTP cache, so an init script gives each context its own view of an origin's localStorage and IndexedDB, keys and
3
+ // databases prefixed `shipkit.job.<id>:` in the real store, the way a launched browser's context starts empty and stays
4
+ // its own. sessionStorage stays native (per tab already). Page: wiki/tools/shipkit/home-unit-files.md, `shot`.
5
+ //
6
+ // The one constraint a reader breaks first: `installJobStore` runs in the page as its own source text (toString), so it
7
+ // closes over nothing from this module and calls the native methods it captured, never the patched ones.
8
+
9
+ /** a job's pages write their beat this often; another job's page sweeps a namespace whose beat is older than STALE_MS */
10
+ const BEAT_MS = 30_000
11
+ const STALE_MS = 10 * 60_000
12
+ /** where the page half keeps its end, for the close */
13
+ const END = 'shipkit.job-store'
14
+
15
+ /** a new context's id: no `:`, so a prefixed key splits once */
16
+ export const jobId = (): string => crypto.randomUUID().replaceAll('-', '').slice(0, 12)
17
+
18
+ /** the page half: localStorage and indexedDB seen through the job's prefix, other jobs' storage events dropped, the
19
+ * stale namespaces of dead jobs removed */
20
+ function installJobStore(id: string, beatMs: number, staleMs: number, end: string): void {
21
+ const PREFIX = 'shipkit.job.'
22
+ const NS = `${PREFIX}${id}:`
23
+ const BEAT = `${PREFIX}${id}`
24
+ const w = window as unknown as Record<PropertyKey, unknown> & Window
25
+ let real: Storage
26
+ try {
27
+ real = w.localStorage
28
+ } catch {
29
+ return // an opaque origin (about:blank, data:) has no store
30
+ }
31
+ const SP = Storage.prototype
32
+ const { getItem, setItem, removeItem, key } = SP
33
+ const length = Object.getOwnPropertyDescriptor(SP, 'length')!.get!
34
+ const all = (): string[] => {
35
+ const out: string[] = []
36
+ for (let i = 0, n = length.call(real) as number; i < n; i++) {
37
+ const k = key.call(real, i)
38
+ if (k != null) out.push(k)
39
+ }
40
+ return out
41
+ }
42
+ const own = (): string[] => all().flatMap((k) => (k.startsWith(NS) ? [k.slice(NS.length)] : []))
43
+ const item = (k: PropertyKey): string | null => getItem.call(real, NS + String(k))
44
+ const put = (k: PropertyKey, v: unknown): void => setItem.call(real, NS + String(k), String(v))
45
+ const drop = (k: PropertyKey): void => removeItem.call(real, NS + String(k))
46
+ const api: Record<string, unknown> = {
47
+ getItem: item,
48
+ setItem: put,
49
+ removeItem: drop,
50
+ clear: () => own().forEach(drop),
51
+ key: (i: number) => own()[i] ?? null,
52
+ }
53
+ const builtin = (p: PropertyKey) => typeof p === 'symbol' || p in SP
54
+ // a Storage as the page reads it: methods, length, and named items (`localStorage.foo`, Object.keys, JSON.stringify)
55
+ const store = new Proxy(Object.create(SP) as Storage, {
56
+ get(_, p, receiver) {
57
+ if (p === 'length') return own().length
58
+ if (typeof p === 'string' && Object.hasOwn(api, p)) return api[p]
59
+ if (builtin(p)) return Reflect.get(SP, p, receiver)
60
+ return item(p) ?? undefined
61
+ },
62
+ set(_, p, v) {
63
+ if (typeof p === 'symbol') return false
64
+ put(p, v)
65
+ return true
66
+ },
67
+ has: (_, p) => builtin(p) || item(p) !== null,
68
+ deleteProperty(_, p) {
69
+ if (typeof p === 'string') drop(p)
70
+ return true
71
+ },
72
+ ownKeys: () => own(),
73
+ getOwnPropertyDescriptor(_, p) {
74
+ const v = typeof p === 'string' ? item(p) : null
75
+ return v === null ? undefined : { value: v, writable: true, enumerable: true, configurable: true }
76
+ },
77
+ defineProperty(_, p, d) {
78
+ if (typeof p === 'symbol' || !('value' in d) || d.configurable === false) return false
79
+ put(p, d.value)
80
+ return true
81
+ },
82
+ getPrototypeOf: () => SP,
83
+ })
84
+ Object.defineProperty(w, 'localStorage', { get: () => store, configurable: true, enumerable: true })
85
+
86
+ // a storage event of the real store reaches the page only when it is this job's, its key without the prefix
87
+ const ours = new WeakSet<Event>()
88
+ w.addEventListener(
89
+ 'storage',
90
+ (e) => {
91
+ if (ours.has(e) || e.storageArea !== real) return
92
+ e.stopImmediatePropagation()
93
+ if (e.key == null || !e.key.startsWith(NS)) return
94
+ const again = new StorageEvent('storage', { key: e.key.slice(NS.length), oldValue: e.oldValue, newValue: e.newValue, url: e.url })
95
+ Object.defineProperty(again, 'storageArea', { value: store })
96
+ ours.add(again)
97
+ w.dispatchEvent(again)
98
+ },
99
+ true,
100
+ )
101
+
102
+ const F = w.indexedDB != null ? IDBFactory.prototype : null
103
+ const open = F?.open
104
+ const del = F?.deleteDatabase
105
+ const dbs = F?.databases
106
+ if (F && open && del) {
107
+ F.open = function (this: IDBFactory, name: string, ...rest: [number?]) {
108
+ return open.call(this, NS + String(name), ...rest)
109
+ }
110
+ F.deleteDatabase = function (this: IDBFactory, name: string) {
111
+ return del.call(this, NS + String(name))
112
+ }
113
+ if (dbs)
114
+ F.databases = async function (this: IDBFactory) {
115
+ return (await dbs.call(this)).flatMap((d) => (d.name?.startsWith(NS) ? [{ ...d, name: d.name.slice(NS.length) }] : []))
116
+ }
117
+ const name = Object.getOwnPropertyDescriptor(IDBDatabase.prototype, 'name')!.get!
118
+ Object.defineProperty(IDBDatabase.prototype, 'name', {
119
+ get(this: IDBDatabase) {
120
+ const n = name.call(this) as string
121
+ return n.startsWith(NS) ? n.slice(NS.length) : n
122
+ },
123
+ configurable: true,
124
+ enumerable: true,
125
+ })
126
+ }
127
+
128
+ const beat = () => {
129
+ try {
130
+ setItem.call(real, BEAT, String(Date.now()))
131
+ } catch {}
132
+ }
133
+ beat()
134
+ const beating = setInterval(beat, beatMs)
135
+
136
+ // the dead jobs' leftovers: a namespace whose beat is stale or gone (the jobs that run beat, this one just did)
137
+ const jobOf = (k: string): string | null => (k.startsWith(PREFIX) ? k.slice(PREFIX.length).split(':')[0]! : null)
138
+ const keys = all()
139
+ const live = new Set(keys.filter((k) => jobOf(k) === k.slice(PREFIX.length) && Date.now() - Number(getItem.call(real, k)) < staleMs).map(jobOf))
140
+ for (const k of keys) {
141
+ const j = jobOf(k)
142
+ if (j != null && !live.has(j)) removeItem.call(real, k)
143
+ }
144
+ const idb = w.indexedDB
145
+ if (dbs && del)
146
+ void dbs
147
+ .call(idb)
148
+ .then((list) => {
149
+ for (const d of list) if (d.name && jobOf(d.name) != null && !live.has(jobOf(d.name))) del.call(idb, d.name)
150
+ })
151
+ .catch(() => undefined)
152
+
153
+ Object.defineProperty(w, Symbol.for(end), {
154
+ configurable: true,
155
+ value: async () => {
156
+ clearInterval(beating)
157
+ for (const k of all()) if (k === BEAT || k.startsWith(NS)) removeItem.call(real, k)
158
+ if (dbs && del) for (const d of await dbs.call(idb)) if (d.name?.startsWith(NS)) del.call(idb, d.name)
159
+ },
160
+ })
161
+ }
162
+
163
+ /** the init script of the context `id`, added to each of its pages before any other */
164
+ export const jobStoreScript = (id: string): string => `(${installJobStore.toString()})(${JSON.stringify(id)}, ${BEAT_MS}, ${STALE_MS}, ${JSON.stringify(END)})`
165
+
166
+ /** run in a page of the context before it closes: its keys and databases on the page's origin go */
167
+ export const JOB_STORE_END = `globalThis[Symbol.for(${JSON.stringify(END)})]?.()`
@@ -55,7 +55,16 @@ export async function consoleWords(m: { args?(): { jsonValue(): Promise<unknown>
55
55
  return null
56
56
  }
57
57
  }
58
- type Context = { newPage(): Promise<Page>; newCDPSession(p: Page): Promise<Cdp>; addInitScript(s: { content: string }): Promise<void>; close(): Promise<void> }
58
+ /** a cookie as playwright reads and writes it */
59
+ type Cookie = { name: string; value: string; domain: string; path: string } & Record<string, unknown>
60
+ type Context = {
61
+ newPage(): Promise<Page>
62
+ newCDPSession(p: Page): Promise<Cdp>
63
+ addInitScript(s: { content: string }): Promise<void>
64
+ cookies(): Promise<Cookie[]>
65
+ addCookies(c: Cookie[]): Promise<void>
66
+ close(): Promise<void>
67
+ }
59
68
  export type Browser = {
60
69
  newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number; locale?: string }): Promise<Context>
61
70
  close(): Promise<void>
@@ -73,6 +82,8 @@ export const LIVE_MS = 10_000
73
82
  export const BROWSER_IDLE_MS = 60_000
74
83
  /** the niceness of the process that launches the browser: chromium inherits it */
75
84
  export const SHOT_NICE = 10
85
+ /** a browser close that has not answered in this long (a stalled box route) is left behind, so its slot frees */
86
+ export const CLOSE_MS = 5000
76
87
  /** a page that paints nothing once the screencast starts is filmed from one still taken after this */
77
88
  const FIRST_FRAME_MS = 1000
78
89
 
@@ -111,6 +122,9 @@ export class Shooter {
111
122
  /** before a page goes to a url: the box route forwards this machine's localhost port to the box */
112
123
  #reach: (url: string) => Promise<void> = async () => undefined
113
124
  #slot: Slot | null = null
125
+ /** the cookies a closed context held, given to the next one: a sign in survives a shot at another viewport, a
126
+ * clip and the idle close. Memory only, never on disk */
127
+ #jar: Cookie[] = []
114
128
  #idle: ReturnType<typeof setTimeout> | null = null
115
129
  #live: ReturnType<typeof setTimeout> | null = null
116
130
 
@@ -138,11 +152,20 @@ export class Shooter {
138
152
  async close(): Promise<void> {
139
153
  if (this.#idle) clearTimeout(this.#idle)
140
154
  if (this.#live) clearTimeout(this.#live)
155
+ const s = this.#slot
141
156
  this.#slot = null
157
+ if (s) await this.#keep(s.ctx)
142
158
  const b = this.#browser
143
159
  this.#browser = null
144
- await b?.close().catch(() => undefined)
145
- this.#free()
160
+ try {
161
+ if (b) await withCap('closing the browser', CLOSE_MS, b.close()).catch(() => undefined)
162
+ } finally {
163
+ this.#free()
164
+ }
165
+ }
166
+
167
+ async #keep(ctx: Context): Promise<void> {
168
+ this.#jar = await withCap('reading the cookies', CLOSE_MS, ctx.cookies()).catch(() => this.#jar)
146
169
  }
147
170
 
148
171
  #free(): void {
@@ -198,7 +221,9 @@ export class Shooter {
198
221
 
199
222
  async #context(a: ShotAsk): Promise<Context> {
200
223
  const b = await this.#ensureBrowser()
201
- return b.newContext({ viewport: a.viewport, deviceScaleFactor: a.dpr, locale: 'en-US' })
224
+ const ctx = await b.newContext({ viewport: a.viewport, deviceScaleFactor: a.dpr, locale: 'en-US' })
225
+ if (this.#jar.length > 0) await ctx.addCookies(this.#jar)
226
+ return ctx
202
227
  }
203
228
 
204
229
  static #listen(page: Page, errors: string[]): void {
@@ -224,6 +249,7 @@ export class Shooter {
224
249
  if (move === 'boot') {
225
250
  const old = this.#slot
226
251
  this.#slot = null
252
+ if (old) await this.#keep(old.ctx)
227
253
  await old?.ctx.close().catch(() => undefined)
228
254
  const t = performance.now()
229
255
  const ctx = await this.#context(a)
@@ -330,6 +356,7 @@ export class Shooter {
330
356
  const note = `${d.frames} frames ${d.width}x${d.height} at ${a.fps} fps ${how}, canvas ${d.canvasOfViewport}, ${mb} MB H.264 from the page's WebCodecs, muxed`
331
357
  return { out: a.out, ms: ms(t0), phases, errors, note, ...stepped }
332
358
  } finally {
359
+ await this.#keep(ctx)
333
360
  await ctx.close().catch(() => undefined)
334
361
  }
335
362
  }
@@ -121,6 +121,8 @@ const read = (abs: string): string => readFileSync(abs, 'utf8')
121
121
 
122
122
  /** the group whose messages need a compiled 9:16 video */
123
123
  export const VERTICAL = 'vertical'
124
+ /** the contract's two formats: always a heading a draft may use, even before the identity has an account in them */
125
+ const FORMATS = ['short', VERTICAL] as const
124
126
  /** the name of a compiled vertical video */
125
127
  export const VERTICAL_FILE = /-vertical\.mp4$/
126
128
 
@@ -208,7 +210,7 @@ export function loadDesk(root: string, ids: Identities, o: { speaksAs?: string |
208
210
  }
209
211
  named.add(speaker.id)
210
212
  const accounts = identities.find((i) => i.id === speaker.id)!.accounts
211
- const groups = new Map([...new Set(accounts.map((a) => a.group).filter((g) => g !== ''))].map((g) => [g, accounts.filter((a) => a.group === g).map((a) => a.id)]))
213
+ const groups = new Map([...new Set([...FORMATS, ...accounts.map((a) => a.group).filter((g) => g !== '')])].map((g) => [g, accounts.filter((a) => a.group === g).map((a) => a.id)]))
212
214
  const d = parseDraft(raw, file, groups)
213
215
  errors.push(...d.errors)
214
216
  const media = new Map<string, Media>()
@@ -477,16 +477,39 @@ export function envFilesOf(rawArgs: string[], cwdRel: string): string[] {
477
477
  export function suiteFiles(top: string, cwdRel: string, testRoot: string | null, ignores: string[], isTest: (f: string) => boolean): string[] {
478
478
  const under = posix.normalize(posix.join(cwdRel, testRoot ?? '.'))
479
479
  const at = under === '.' ? '.' : under
480
- // bun discovers what git ignores too, an install excepted
481
- const listed = [
482
- ...git(top, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', at]).split('\0'),
483
- ...git(top, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--', at]).split('\0').filter((f) => !f.split('/').includes('node_modules')),
484
- ]
485
480
  const res = ignores.map((g) => globRe(g))
481
+ const relOf = (f: string): string => (cwdRel === '' || cwdRel === '.' ? f : f.slice(cwdRel.length + 1))
482
+ // bun discovers what git ignores too, an install excepted. Git lists an ignored folder as one entry
483
+ // (--directory), where listing its files walked every one of them first: 701,496 files and 12 s in a repo
484
+ // whose ignored data/ holds 655k. The folders bun would search are walked here, and a folder a bun ignore
485
+ // pattern covers whole (`data/**`) is never opened
486
+ const listed = git(top, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', at]).split('\0')
487
+ const covered = (dir: string): boolean => res.some((re) => re.test(`${relOf(dir)}/${PROBE}`))
488
+ const walk = (dir: string): void => {
489
+ let entries: import('fs').Dirent[]
490
+ try {
491
+ entries = readdirSync(join(top, dir), { withFileTypes: true })
492
+ } catch {
493
+ return
494
+ }
495
+ for (const e of entries) {
496
+ if (e.name === 'node_modules' || e.name.startsWith('.')) continue
497
+ const p = `${dir}/${e.name}`
498
+ const folder = e.isDirectory() || (e.isSymbolicLink() && statSync(join(top, p), { throwIfNoEntry: false })?.isDirectory() === true)
499
+ if (folder) {
500
+ if (!covered(p)) walk(p)
501
+ } else if (isTest(p)) listed.push(p)
502
+ }
503
+ }
504
+ for (const f of git(top, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory', '--', at]).split('\0')) {
505
+ if (f === '' || f.split('/').some((x) => x === 'node_modules' || x.startsWith('.'))) continue
506
+ if (!f.endsWith('/')) listed.push(f)
507
+ else if (!covered(f.slice(0, -1))) walk(f.slice(0, -1))
508
+ }
486
509
  const out: string[] = []
487
510
  for (const f of listed) {
488
511
  if (f === '' || !isTest(f) || !existsSync(join(top, f))) continue
489
- const rel = cwdRel === '' || cwdRel === '.' ? f : f.slice(cwdRel.length + 1)
512
+ const rel = relOf(f)
490
513
  if (inDotDir(rel)) continue
491
514
  if (res.some((re) => re.test(rel))) continue
492
515
  out.push(rel)
@@ -494,6 +517,9 @@ export function suiteFiles(top: string, cwdRel: string, testRoot: string | null,
494
517
  return [...new Set(out)].sort()
495
518
  }
496
519
 
520
+ /** a file name no test has: a folder whose every path an ignore pattern matches matches it too */
521
+ const PROBE = '\u0000probe'
522
+
497
523
  /** a bun ignore pattern as a regexp: `**` any depth, `*` one segment */
498
524
  export function globRe(glob: string): RegExp {
499
525
  const g = glob.replace(/^\.\//, '')
@@ -212,6 +212,8 @@ export interface SoundGen {
212
212
  export interface SoundRun {
213
213
  cmd: string
214
214
  reads?: string[]
215
+ /** the work runs on another machine (ElevenLabs, the comfy box): it never waits on this machine's load */
216
+ remote?: true
215
217
  }
216
218
 
217
219
  export interface Sfx {