rvlib-shipkit 2.17.1 → 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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ ## 2.18.0
2
+
3
+ - **SK039: VS Code watches none of shipkit's generated folders.** `.vscode/settings.json` excludes `**/.shipkit/cache/**`, `**/.shipkit/tmp/**`, `**/.shipkit/review/**` and `**/trailer/**/out/**` from `files.watcherExclude`, so the files a build, a film or a test writes never wake the extension host. It warns, and the fix pass of every `sk ci` inserts the missing globs into the hand written jsonc, every other byte kept, or writes a settings file holding the exclusion alone. A glob set to `false` stays; a root published to npm or a linked `.vscode/` is left alone. The scaffold's template carries the block.
4
+ - **The hubs' background warms share one budget of the loop.** Every background recompute of every hub waits its turn in one process wide queue, so however many repos the daemon serves, they hold its loop a quarter of the time at most; a first read or a fresh one never queues. The home page with every repo watched stalled the daemon for over a minute at a time.
5
+ - **A verdict shows the moment it is clicked.** The card and its row draw the chosen verdict while it is sent, and show the error and the truth again if the send fails.
6
+ - **The test selection lists an ignored folder as one entry.** With `tests.select` on, the suite listing asked git for every ignored file (700k in one repo, 16 s); it now names an ignored folder once and walks only the folders bun would search.
7
+ - **A note box grows to show its whole placeholder.** `AutoText` sizes an empty box to its hint, and every multi line field of the hub is now `AutoText`.
8
+ - **A stalled browser can no longer hold a slot for hours.** A browser close and a cookie read get 5 s, the slot frees whatever happened, a call to the shot service waits at most twice the ask's cap, and a waiter names how long each holder has held its slot.
9
+ - **A page that reloads mid film fails with its reason** (a dev server's reload on a save) instead of a TypeError.
10
+ - **A slow `push` glides.** The push is drawn with `perspective` at sub pixel positions; `zoompan` stepped by whole pixels and shook.
11
+ - **A shot or a film on a box starts from an empty store of its own.** Each context of the box's warm browser sees only its own `localStorage` and IndexedDB, kept across a reload inside it and removed when it closes, so no value another job left on the origin changes the page. The HTTP cache stays shared and warm. `openBrowser(pw, { store: 'shared' })` keeps the old shared store.
12
+
1
13
  ## 2.17.1
2
14
 
3
15
  - **A `big` title keeps the cut's line breaks.** Each `\n` starts a line, and a line wider than the frame still wraps; the lines used to be joined and wrapped wherever the width fell.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.17.1",
3
+ "version": "2.18.0",
4
4
  "funding": "https://github.com/sponsors/rvion",
5
5
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
6
6
  "license": "MIT",
@@ -0,0 +1,119 @@
1
+ // SK039 vscode watch generated (patterns/vscode-tasks/index.md): VS Code watches no folder shipkit writes for itself.
2
+ // Its file watcher walks the whole workspace, so every file a gate, a shot, a film or a review card writes under
3
+ // these folders woke the editor's extension host, for every repo open in a window.
4
+ //
5
+ // the file is hand-written jsonc: the repair inserts the missing keys after the last one and leaves every other byte,
6
+ // and writes a settings file of its own only where the repo has none
7
+ import { check } from '../check.ts'
8
+ import type { CheckCtx } from '../core/check-ctx.ts'
9
+ import { rootPublishesNpm } from '../core/repo-facts.ts'
10
+ import { indentAt, parseSpans, type Node } from '../scaffold/jsonc-spans.ts'
11
+
12
+ const SETTINGS = '.vscode/settings.json'
13
+ const KEY = 'files.watcherExclude'
14
+
15
+ /** the folders shipkit writes in a repo that no person edits: the gate's cache, scratch, the review store's media,
16
+ * a trailer's built cuts */
17
+ export const GENERATED_GLOBS = ['**/.shipkit/cache/**', '**/.shipkit/tmp/**', '**/.shipkit/review/**', '**/trailer/**/out/**'] as const
18
+
19
+ type Obj = Extract<Node, { kind: 'object' }>
20
+
21
+ /** where new props go in `o`: after its last prop (a comma added when it has none, past a comment ending its line),
22
+ * else right after its brace; the indent of its props */
23
+ function insertPoint(text: string, o: Obj, outer: string): { at: number; comma: number | null; indent: string } {
24
+ const last = o.props.at(-1)
25
+ if (last == null) return { at: o.start + 1, comma: null, indent: `${outer} ` }
26
+ const indent = indentAt(text, last.keyStart)
27
+ let j = last.value.end
28
+ while (j < o.end && /[ \t]/.test(text[j]!)) j++
29
+ const hasComma = text[j] === ','
30
+ const from = hasComma ? j + 1 : last.value.end
31
+ // the rest of the line, a trailing comment included, stays with the prop it follows
32
+ const eol = text.indexOf('\n', from)
33
+ const rest = eol < 0 ? '' : text.slice(from, eol)
34
+ const at = eol >= 0 && eol < o.end && /^\s*(\/\/.*)?$/.test(rest) ? eol : from
35
+ return { at, comma: hasComma ? null : last.value.end, indent }
36
+ }
37
+
38
+ const splice = (text: string, edits: { at: number; put: string }[]): string =>
39
+ edits.sort((a, b) => b.at - a.at).reduce((t, e) => t.slice(0, e.at) + e.put + t.slice(e.at), text)
40
+
41
+ /** the settings text with every generated folder excluded from VS Code's watcher, and the globs it added; null when
42
+ * the file is not one object */
43
+ export function withWatchExcludes(text: string): { text: string; added: string[] } | null {
44
+ const root = parseSpans(text)
45
+ if (root.kind !== 'object') return null
46
+ const prop = root.props.find((p) => p.key === KEY)
47
+ if (prop != null && prop.value.kind !== 'object') return null
48
+ const have = prop == null ? new Map<string, unknown>() : new Map((prop.value as Obj).props.map((p) => [p.key, p.value.kind === 'scalar' ? p.value.value : null]))
49
+ // a glob the repo set to false is its own decision, kept
50
+ const added = GENERATED_GLOBS.filter((g) => !have.has(g))
51
+ if (added.length === 0) return { text, added }
52
+ if (prop != null) {
53
+ const o = prop.value as Obj
54
+ const p = insertPoint(text, o, indentAt(text, prop.keyStart))
55
+ const lines = added.map((g) => `\n${p.indent}"${g}": true`).join(',')
56
+ // an empty object gets its closing brace back on a line of its own
57
+ const close = o.props.length === 0 ? `\n${indentAt(text, prop.keyStart)}` : ''
58
+ const edits = [{ at: p.at, put: `${lines}${close}` }, ...(p.comma != null ? [{ at: p.comma, put: ',' }] : [])]
59
+ return { text: splice(text, edits), added }
60
+ }
61
+ const p = insertPoint(text, root, '')
62
+ const inner = added.map((g) => `${p.indent} "${g}": true`).join(',\n')
63
+ const block = `\n\n${p.indent}// shipkit's generated folders: never watched (SK039)\n${p.indent}"${KEY}": {\n${inner}\n${p.indent}}`
64
+ const edits = [{ at: p.at, put: block }, ...(p.comma != null ? [{ at: p.comma, put: ',' }] : [])]
65
+ return { text: splice(text, edits), added }
66
+ }
67
+
68
+ /** a settings file holding the exclusion alone, for a repo that has none */
69
+ export const freshSettings = (): string =>
70
+ `{\n // shipkit's generated folders: never watched (SK039)\n "${KEY}": {\n${GENERATED_GLOBS.map((g) => ` "${g}": true`).join(',\n')}\n }\n}\n`
71
+
72
+ const PUBLIC_SKIP = `the root unit publishes to npm: ${SETTINGS} belongs to every contributor, so it is never written`
73
+
74
+ function ownSettings(c: CheckCtx): { text: string } | 'none' | 'linked' {
75
+ if (c.isLink('.vscode')) return 'linked'
76
+ if (!c.exists(SETTINGS)) return 'none'
77
+ const text = c.read(SETTINGS)
78
+ return text == null ? 'none' : { text }
79
+ }
80
+
81
+ export const vscodeWatchGenerated = check({
82
+ id: 'SK039',
83
+ // an editor setting behind is waste, not a broken repo: it warns, and the fix pass of every gate repairs it
84
+ blocking: false,
85
+ title: 'vscode watch generated',
86
+ description: "VS Code watches none of shipkit's generated folders: cache, tmp, review, trailer cuts",
87
+ owner: 'patterns/vscode-tasks/index.md',
88
+ runs: { onPreCommit: false, onCi: true, onFull: true, onRelease: false, onHealth: true, onSave: 'moved', onClock: false },
89
+ cache: { by: 'reads' },
90
+ fix: 'ci',
91
+ applies: 'always',
92
+ run: (c) => {
93
+ if (rootPublishesNpm(c.config)) return c.ok(PUBLIC_SKIP)
94
+ const own = ownSettings(c)
95
+ if (own === 'linked') return c.ok('.vscode/ is a link to a shared dir, left alone')
96
+ if (own === 'none') return c.fail(`no ${SETTINGS}: VS Code watches every generated folder (${GENERATED_GLOBS.join(', ')})`)
97
+ let r: ReturnType<typeof withWatchExcludes>
98
+ try { r = withWatchExcludes(own.text) }
99
+ catch (e) { return c.warn(`${SETTINGS} does not parse (${(e as Error).message}), so its watcher exclusions were not checked`) }
100
+ if (r == null) return c.warn(`${SETTINGS}: no object, or ${KEY} is no object, so its exclusions were not checked`)
101
+ if (r.added.length === 0) return c.ok(`${SETTINGS}: VS Code watches no generated folder`)
102
+ c.fail(`${SETTINGS}: ${KEY} misses ${r.added.join(', ')}`)
103
+ },
104
+ repair: (c) => {
105
+ if (rootPublishesNpm(c.config)) return { changed: false, summary: PUBLIC_SKIP }
106
+ const own = ownSettings(c)
107
+ if (own === 'linked') return { changed: false, summary: '.vscode/ is a link, left alone' }
108
+ if (own === 'none') {
109
+ c.write(SETTINGS, freshSettings())
110
+ return { changed: true, summary: `${SETTINGS}: written, VS Code watches no generated folder` }
111
+ }
112
+ const r = withWatchExcludes(own.text)
113
+ if (r == null || r.added.length === 0) return { changed: false, summary: `${SETTINGS} already current, or not one object` }
114
+ c.write(SETTINGS, r.text)
115
+ return { changed: true, summary: `${SETTINGS}: ${KEY} gained ${r.added.join(', ')}` }
116
+ },
117
+ })
118
+
119
+ export default vscodeWatchGenerated
@@ -35,5 +35,13 @@
35
35
 
36
36
  // eslint off, and no formatter on save: formatting is a manual `bun fmt`
37
37
  "eslint.enable": false,
38
- "js/ts.format.enabled": false
38
+ "js/ts.format.enabled": false,
39
+
40
+ // shipkit's generated folders: never watched (SK039)
41
+ "files.watcherExclude": {
42
+ "**/.shipkit/cache/**": true,
43
+ "**/.shipkit/tmp/**": true,
44
+ "**/.shipkit/review/**": true,
45
+ "**/trailer/**/out/**": true
46
+ }
39
47
  }
@@ -19,7 +19,12 @@ export function AutoText({ value, onText, rows = 1, el, className, ...rest }: Pr
19
19
  if (t == null) return
20
20
  t.style.height = 'auto'
21
21
  const edge = t.offsetHeight - t.clientHeight
22
- t.style.height = `${t.scrollHeight + edge}px`
22
+ // an empty box is as tall as its placeholder: the hint reads whole, never cut by a scrollbar
23
+ const hint = t.value === '' && t.placeholder !== ''
24
+ if (hint) t.value = t.placeholder
25
+ const h = t.scrollHeight
26
+ if (hint) t.value = ''
27
+ t.style.height = `${h + edge}px`
23
28
  // a sheet's max-height stops it: only then may it scroll
24
29
  t.style.overflowY = t.scrollHeight > t.clientHeight + 1 ? 'auto' : 'hidden'
25
30
  }, [])
@@ -4,7 +4,7 @@
4
4
  // 304 when the store did not move. His drafts are kept in the browser until they are sent
5
5
  import { makeAutoObservable, observableRef, reaction, runInAction } from 'mobx'
6
6
  import { PAGE, type BoardRow, type ThreadPage, type ThreadRow } from '../../../review/cells.ts'
7
- import { MOVE_LABEL, pasteBlock, STATUS_LABEL, type Move, type ShownStatus, type Spec } from '../../../review/model.ts'
7
+ import { MOVE_LABEL, pasteBlock, STATUS_LABEL, type Move, type ReviewStatus, type ShownStatus, type Spec } from '../../../review/model.ts'
8
8
  import type { PasteHosts } from '../../../review/paste.ts'
9
9
  import type { Role } from '../../../review/role.ts'
10
10
  import type { RepoSt } from '../repo-st.ts'
@@ -319,8 +319,18 @@ export class ReviewSt {
319
319
  return `${f ? `${f}&` : ''}limit=${this.shown}`
320
320
  }
321
321
 
322
+ /** the verdict he just gave, by thread head: its row shows it at once, while the store takes it */
323
+ answering: Record<string, ReviewStatus> = {}
324
+
325
+ setAnswering(head: string, status: ReviewStatus | null): void {
326
+ if (status === null) delete this.answering[head]
327
+ else this.answering[head] = status
328
+ }
329
+
322
330
  get rows(): ThreadRow[] {
323
- return this.page?.rows ?? []
331
+ const rows = this.page?.rows ?? []
332
+ const a = this.answering
333
+ return Object.keys(a).length === 0 ? rows : rows.map((r) => (a[r.head] ? { ...r, status: a[r.head]! } : r))
324
334
  }
325
335
 
326
336
  /** more rows sit on the server past the ones shown */
@@ -300,7 +300,7 @@ const Composer = observer(({ rv, card }: { rv: ReviewSt; card: ThreadSt }) => {
300
300
  const views = card.headItem?.views ?? []
301
301
  const reactions = card.outgoingReactions
302
302
  const verdicts = card.takesVerdict
303
- const sent = h?.kind === 'version' ? card.verdictsOn(h.id).findLast((x) => x.current)?.verdict : undefined
303
+ const sent = h?.kind === 'version' ? card.chosenOn(h.id) : undefined
304
304
  const newest = card.newest
305
305
  const parked = card.parked === null ? null : card.versionOf(card.parked)
306
306
  return (
@@ -137,6 +137,8 @@ export class ThreadSt {
137
137
  /** an option row folded or unfolded by hand, by `<item>#<view>` */
138
138
  openRows: Record<string, boolean> = {}
139
139
  busy = false
140
+ /** the verdict he just gave: shown as chosen the moment he clicks, while the store takes it */
141
+ sending: { on: string; status: ReviewStatus } | null = null
140
142
  /** « 📣 post »'s box: his word while it is open, null when shut */
141
143
  postBox: string | null = null
142
144
  private readonly clips = new Map<string, ClipSt>()
@@ -431,6 +433,12 @@ export class ThreadSt {
431
433
  // ── what was said on each view ──
432
434
 
433
435
  /** the verdicts on one version, oldest first */
436
+ /** the verdict a version shows as chosen: the one being sent, else its current one */
437
+ chosenOn(id: string): ReviewStatus | undefined {
438
+ if (this.sending?.on === id) return this.sending.status
439
+ return this.verdictsOn(id).findLast((x) => x.current)?.verdict
440
+ }
441
+
434
442
  verdictsOn(id: string): VerdictCell[] {
435
443
  return this.cells.filter((c): c is VerdictCell => c.kind === 'verdict' && c.on === id)
436
444
  }
@@ -757,8 +765,11 @@ export class ThreadSt {
757
765
  return
758
766
  }
759
767
  const d = this.draft
768
+ const head = this.data?.head ?? h.id
760
769
  this.busy = true
761
770
  this.error = null
771
+ this.sending = { on: h.id, status }
772
+ this.rv.setAnswering(head, status)
762
773
  try {
763
774
  const pick = isChoice(h.item) && isApproved(status) && d.pick !== undefined ? { pick: d.pick } : {}
764
775
  await postJson(this.rv.url(`/api/review/${h.id}/feedback`), { status, comment: d.comment, rects: d.rects, reactions: d.reactions ?? [], ...pick })
@@ -767,7 +778,12 @@ export class ThreadSt {
767
778
  } catch (e) {
768
779
  runInAction(() => (this.error = (e as Error).message))
769
780
  } finally {
770
- runInAction(() => (this.busy = false))
781
+ // the store's answer is in by now, or the send failed: either way what shows is the truth again
782
+ runInAction(() => {
783
+ this.busy = false
784
+ this.sending = null
785
+ this.rv.setAnswering(head, null)
786
+ })
771
787
  }
772
788
  }
773
789
 
@@ -4,6 +4,7 @@
4
4
  import { observer } from 'mobx-react-lite'
5
5
  import { useState, type CSSProperties, type ReactNode } from 'react'
6
6
  import { BRANDS, brandHex } from '../../../social/brands.ts'
7
+ import { AutoText } from '../auto-text.tsx'
7
8
  import { renderMd, renderMdInline } from '../md.ts'
8
9
  import { plain } from './social-model.ts'
9
10
  import type { DraftNote, SocialSt } from './social-st.ts'
@@ -145,11 +146,10 @@ export const NotesBox = observer((p: { so: SocialSt; notes: readonly DraftNote[]
145
146
  return (
146
147
  <div className="so-notes">
147
148
  <div className="so-noteline">
148
- <textarea
149
- rows={1}
149
+ <AutoText
150
150
  placeholder={p.placeholder}
151
151
  value={text}
152
- onChange={(e) => setText(e.currentTarget.value)}
152
+ onText={setText}
153
153
  onKeyDown={(e) => {
154
154
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void send()
155
155
  }}
@@ -8,6 +8,7 @@ import { CopyFrame, Count, ExpandButton, Field, Fold, FoldCard, Logo, Md, popup
8
8
  import { angleCards, isClip, isVertical, logoStacks, sharing, STATUS, TEXT_FIELD, TITLE_MAX, type DeskAccount, type Media, type Place, type SocialPost } from './social-model.ts'
9
9
  import type { SocialSt } from './social-st.ts'
10
10
  import { Caret } from '../icons.tsx'
11
+ import { AutoText } from '../auto-text.tsx'
11
12
 
12
13
  /** the platforms of some messages, each lit once posted there; a group's accounts one stack of overlapping logos */
13
14
  export const Logos = observer((p: { so: SocialSt; posts: readonly SocialPost[]; size: number }) => {
@@ -406,7 +407,7 @@ const EditBox = observer((p: { so: SocialSt; post: SocialPost; label: string })
406
407
  </Field>
407
408
  ) : null}
408
409
  <Field label={p.label}>
409
- <textarea className="so-editor" autoFocus rows={Math.min(20, Math.max(3, e.text.split('\n').length + 1))} value={e.text} onChange={(ev) => so.typeEdit(p.post, { text: ev.currentTarget.value })} onKeyDown={keys} />
410
+ <AutoText className="so-editor" autoFocus rows={3} value={e.text} onText={(text) => so.typeEdit(p.post, { text })} onKeyDown={keys} />
410
411
  </Field>
411
412
  <Field label="Tags">
412
413
  <input className="so-input" placeholder="#gamedev #indiedev" value={e.tags} onChange={(ev) => so.typeEdit(p.post, { tags: ev.currentTarget.value })} onKeyDown={keys} />
@@ -107,7 +107,7 @@ a.so-icon:visited{color:var(--dim)}
107
107
  .so-partchip{font-size:13px;font-weight:700;padding:0 var(--s2);line-height:24px;border-radius:4px;background:var(--sel);color:var(--accent)}
108
108
  .so-notes{display:flex;flex-direction:column;gap:var(--s1);padding:var(--s2);border-radius:6px;border:1px solid color-mix(in srgb,var(--warn) 45%,var(--line));background:color-mix(in srgb,var(--warn) 7%,var(--panel))}
109
109
  .so-noteline{display:flex;gap:var(--s2);align-items:flex-end}
110
- .so-noteline textarea{flex:1;min-height:0;font:12.5px/1.45 system-ui,sans-serif;padding:var(--s1) var(--s2);resize:vertical}
110
+ .so-noteline textarea{flex:1;min-width:0;font:12.5px/1.45 system-ui,sans-serif;padding:var(--s1) var(--s2)}
111
111
  .so-said{text-align:left;font-size:12px;padding:var(--s1) var(--s2);border:0;border-left:3px solid var(--tone);background:none;white-space:pre-wrap;cursor:pointer}
112
112
  .so-saidstate{font-size:10px;font-weight:700;text-transform:uppercase;color:var(--tone)}
113
113
  .so-text{font-size:13px}
@@ -11,6 +11,7 @@ import { renderMd } from '../md.ts'
11
11
  import type { RepoSt } from '../repo-st.ts'
12
12
  import { PANEL, PhoneTop } from '../review/review-page.tsx'
13
13
  import type { FieldView, Picture, StoresSt, StoreView } from './stores-st.ts'
14
+ import { AutoText } from '../auto-text.tsx'
14
15
 
15
16
  export const StoresPage = observer(({ app }: { app: RepoSt }) => {
16
17
  const so = app.stores
@@ -158,7 +159,7 @@ const FieldCard = observer(({ so, f }: { so: StoresSt; f: FieldView }) => {
158
159
  </div>
159
160
  {editing ? (
160
161
  <>
161
- <textarea className="sto-edit" autoFocus rows={Math.min(24, Math.max(4, (so.editing?.text ?? '').split('\n').length + 1))} value={so.editing?.text ?? ''} onChange={(e) => so.type(e.currentTarget.value)} onKeyDown={keys} />
162
+ <AutoText className="sto-edit" autoFocus rows={4} value={so.editing?.text ?? ''} onText={(t) => so.type(t)} onKeyDown={keys} />
162
163
  <div className="sto-acts">
163
164
  <button disabled={so.busy || (so.editing?.text.trim() ?? '') === ''} onClick={() => void so.saveEdit(f)}>Save</button>
164
165
  <button className="ghost" onClick={() => so.cancelEdit()}>Cancel</button>
@@ -198,12 +199,12 @@ const NoteBox = observer(({ so, asset, said }: { so: StoresSt; asset: string; sa
198
199
  {n.answer ? <div className="rv-dim">↳ {n.answer}</div> : null}
199
200
  </button>
200
201
  ))}
201
- <textarea
202
+ <AutoText
202
203
  autoFocus
203
204
  rows={2}
204
205
  placeholder="a note on this: it goes to the review page, an agent takes it"
205
206
  value={text}
206
- onChange={(e) => so.typeNote(asset, e.currentTarget.value)}
207
+ onText={(t) => so.typeNote(asset, t)}
207
208
  onKeyDown={(e) => {
208
209
  if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) void so.sendNote(asset)
209
210
  }}
@@ -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`)
@@ -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,10 +11,16 @@ 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 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
+ }
18
24
  type PwContext = {
19
25
  newPage(): Promise<PwPage>
20
26
  newCDPSession(p: PwPage): Promise<{ send(m: string, p?: Record<string, unknown>): Promise<unknown> }>
@@ -76,21 +82,30 @@ async function forward(box: string, spec: string[], own: { p: ReturnType<typeof
76
82
 
77
83
  const LOCAL = new Set(['localhost', '127.0.0.1', '[::1]'])
78
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
+
79
94
  /** the box's default context as a launched browser's newContext: each context a set of pages there, the viewport set
80
- * per page; one context because only it keeps the profile's HTTP cache */
81
- 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') {
82
97
  return {
83
98
  isConnected: () => b.isConnected(),
84
99
  on: (e: 'disconnected', cb: () => void) => b.on(e, cb),
85
100
  close: async () => {
86
- await Promise.all(all.splice(0).map((p) => p.close().catch(() => undefined)))
101
+ await Promise.all(all.splice(0).map(closed))
87
102
  await b.close()
88
103
  },
89
104
  async newContext(o: { viewport: { width: number; height: number }; deviceScaleFactor: number }) {
90
105
  const ctx = b.contexts()[0]
91
106
  if (ctx == null) throw new Error('the box browser has no default context')
92
107
  const pages: PwPage[] = []
93
- const scripts: string[] = []
108
+ const scripts: string[] = store === 'job' ? [jobStoreScript(jobId())] : []
94
109
  return {
95
110
  async newPage() {
96
111
  const p = await ctx.newPage()
@@ -111,7 +126,7 @@ function asLaunched(b: PwBrowser, all: PwPage[]) {
111
126
  for (const p of pages) await p.addInitScript(s)
112
127
  },
113
128
  async close() {
114
- await Promise.all(pages.splice(0).map((p) => p.close().catch(() => undefined)))
129
+ await Promise.all(pages.splice(0).map(closed))
115
130
  },
116
131
  }
117
132
  },
@@ -120,7 +135,7 @@ function asLaunched(b: PwBrowser, all: PwPage[]) {
120
135
 
121
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
122
137
  * browser slots held until close */
123
- 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>> {
124
139
  const say = o.say ?? ((l: string) => console.error(l))
125
140
  const cap = await browserCap(o.root)
126
141
  const box = filmBox(cap)
@@ -142,7 +157,7 @@ export async function openBrowser<B>(pw: Pw, o: { root?: string; who: string; ar
142
157
  say(`${o.who}: filming on ${box} (${state.split(' ').slice(0, 2).join(' ')}, ${Math.round(performance.now() - t)} ms to its browser)`)
143
158
  const reached = new Set<number>()
144
159
  const pages: PwPage[] = []
145
- const browser = asLaunched(b, pages)
160
+ const browser = asLaunched(b, pages, o.store)
146
161
  return {
147
162
  browser: browser as B,
148
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)})]?.()`
@@ -82,6 +82,8 @@ export const LIVE_MS = 10_000
82
82
  export const BROWSER_IDLE_MS = 60_000
83
83
  /** the niceness of the process that launches the browser: chromium inherits it */
84
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
85
87
  /** a page that paints nothing once the screencast starts is filmed from one still taken after this */
86
88
  const FIRST_FRAME_MS = 1000
87
89
 
@@ -155,12 +157,15 @@ export class Shooter {
155
157
  if (s) await this.#keep(s.ctx)
156
158
  const b = this.#browser
157
159
  this.#browser = null
158
- await b?.close().catch(() => undefined)
159
- this.#free()
160
+ try {
161
+ if (b) await withCap('closing the browser', CLOSE_MS, b.close()).catch(() => undefined)
162
+ } finally {
163
+ this.#free()
164
+ }
160
165
  }
161
166
 
162
167
  async #keep(ctx: Context): Promise<void> {
163
- this.#jar = await ctx.cookies().catch(() => this.#jar)
168
+ this.#jar = await withCap('reading the cookies', CLOSE_MS, ctx.cookies()).catch(() => this.#jar)
164
169
  }
165
170
 
166
171
  #free(): void {
@@ -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(/^\.\//, '')
@@ -54,6 +54,14 @@ export interface StitchInput {
54
54
  }
55
55
 
56
56
  const n3 = (x: number): string => (+x.toFixed(4)).toString()
57
+
58
+ /** a shot's slow push in, from whole to `push` over its `frames`, centred: sampled at sub pixel positions (perspective,
59
+ * cubic), where zoompan's crop steps by whole pixels, so a slow push held still for frames, then jumped */
60
+ export function pushFilter(push: number, frames: number, skip: number, [W, H]: readonly [number, number]): string {
61
+ const z = `(1+${n3(push - 1)}*(in+${skip})/${frames})`
62
+ const [x0, x1, y0, y1] = [`W/2*(1-1/${z})`, `W/2*(1+1/${z})`, `H/2*(1-1/${z})`, `H/2*(1+1/${z})`]
63
+ return `,scale=${W}:${H},perspective=x0='${x0}':y0='${y0}':x1='${x1}':y1='${y0}':x2='${x0}':y2='${y1}':x3='${x1}':y3='${y1}':interpolation=cubic:eval=frame`
64
+ }
57
65
  const even = (x: number): number => 2 * Math.round(x / 2)
58
66
 
59
67
  /** the grid's margin round the cells and the gap between them, and the corners' radius, in frame heights */
@@ -312,9 +320,7 @@ export function pieceArgs(a: Pick<StitchInput, 't' | 'sources' | 'titles' | 'loo
312
320
  const frames = Math.min(spans[i]!.b, p.to) - spans[i]!.a - skip
313
321
  count[i] = frames
314
322
  const push = s.push && s.push > 1 ? s.push : null
315
- const pushF = push
316
- ? `,scale=${W * 2}:${H * 2},zoompan=z='1+${n3(push - 1)}*(on+${skip})/${Math.round(len * fps)}':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=1:s=${W}x${H}:fps=${fps}`
317
- : ''
323
+ const pushF = push ? pushFilter(push, Math.round(len * fps), skip, [W, H]) : ''
318
324
  const [ax, ay] = s.frameAt ?? [0.5, 0.5]
319
325
  const cropF = s.frame && s.frame > 1 ? `crop=w='2*trunc(iw/${n3(s.frame)}/2)':h='2*trunc(ih/${n3(s.frame)}/2)':x='min(max(iw*${n3(ax)}-ow/2,0),iw-ow)':y='min(max(ih*${n3(ay)}-oh/2,0),ih-oh)'` : null
320
326
  const frameF = cropF ? `,${cropF},scale=${W}:${H}` : ''