@vitrinka/web 0.3.2 → 0.3.4

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.
@@ -39,6 +39,14 @@ export const RECONCILE_MS = 10_000;
39
39
  const OFFLINE_AFTER_MS = 15_000;
40
40
  const BACKLOG_ITEMS = 40;
41
41
  const kv = () => getRecorderStorage();
42
+ /** How often a tab renews its `stopping` mark while its Stop is out. */
43
+ export const STOPPING_RENEW_MS = 20_000;
44
+ /** A mark not renewed for this long outlived its tab: several missed renewals, and past the one wake a minute Chrome allows a long-hidden tab. */
45
+ export const STOPPING_TTL_MS = 90_000;
46
+ /** Is another tab still stopping `rec` (a fresh `stopping` mark)? */
47
+ export function stoppingElsewhere(rec) {
48
+ return rec.stopping !== undefined && Date.now() - Date.parse(rec.stopping) < STOPPING_TTL_MS;
49
+ }
42
50
  function readJson(key, fallback) {
43
51
  const raw = kv().getString(key);
44
52
  if (!raw)
@@ -85,7 +93,61 @@ export function setState(rec) {
85
93
  if (rec === null)
86
94
  kv().remove(REC_KEY);
87
95
  else
88
- safeSet(REC_KEY, JSON.stringify(rec));
96
+ safeSet(REC_KEY, JSON.stringify(stored(rec)));
97
+ }
98
+ /** The session this tab is stopping, its clock at the Stop, and when its mark was last renewed. */
99
+ let stoppingHere = null;
100
+ let stoppingLease = null;
101
+ /** What the other tabs read of `rec`: while this tab stops it, the frozen `stopping` copy. */
102
+ function stored(rec) {
103
+ if (stoppingHere?.sessionId !== rec.sessionId)
104
+ return rec;
105
+ return { ...rec, paused: true, activeMs: stoppingHere.activeMs, resumeAt: null, stopping: stoppingHere.at };
106
+ }
107
+ /**
108
+ * This tab started (`sessionId`) or finished (null) stopping a session. Only
109
+ * the STORED record changes: this tab's own cache stays live, so the tail
110
+ * its Stop still drains (rrweb's last events, settled captures) lands.
111
+ * Finishing writes the record back without the mark.
112
+ */
113
+ export function markStopping(sessionId, activeMs = 0, renewMs = STOPPING_RENEW_MS) {
114
+ const was = stoppingHere?.sessionId;
115
+ if (stoppingLease)
116
+ clearInterval(stoppingLease);
117
+ stoppingLease = null;
118
+ stoppingHere = sessionId ? { sessionId, activeMs, at: new Date().toISOString() } : null;
119
+ // The lease: a Stop whose request hangs is still this tab's, never mistaken for a gone tab's.
120
+ if (sessionId)
121
+ stoppingLease = setInterval(() => renewStopping(sessionId), renewMs);
122
+ const live = getState();
123
+ if (!live || (live.sessionId !== sessionId && live.sessionId !== was))
124
+ return;
125
+ delete live.stopping;
126
+ setState(live);
127
+ }
128
+ /** Re-stamp this tab's `stopping` mark while its Stop is still out. */
129
+ function renewStopping(sessionId) {
130
+ if (stoppingHere?.sessionId !== sessionId)
131
+ return;
132
+ stoppingHere.at = new Date().toISOString();
133
+ const live = getState();
134
+ if (live?.sessionId === sessionId)
135
+ setState(live);
136
+ }
137
+ const beforeStopHooks = new Set();
138
+ export function onBeforeStop(fn) {
139
+ beforeStopHooks.add(fn);
140
+ return () => beforeStopHooks.delete(fn);
141
+ }
142
+ export function runBeforeStopHooks() {
143
+ for (const fn of beforeStopHooks) {
144
+ try {
145
+ fn();
146
+ }
147
+ catch (error) {
148
+ console.warn('vitrinka: before-stop hook failed', error);
149
+ }
150
+ }
89
151
  }
90
152
  /**
91
153
  * Another document of this origin (a second tab) wrote the session record.
@@ -108,6 +170,10 @@ export function adoptStoredState(raw) {
108
170
  }
109
171
  }
110
172
  const cur = getState();
173
+ // Allocations also read storage before its notification arrives. Ship the
174
+ // already-captured DOM tail while the local cache still accepts it.
175
+ if (next?.stopping && next.sessionId === cur?.sessionId && !cur.paused && stoppingHere?.sessionId !== next.sessionId)
176
+ runBeforeStopHooks();
111
177
  if (!next) {
112
178
  if (!cur)
113
179
  return 'unchanged';
@@ -121,6 +187,14 @@ export function adoptStoredState(raw) {
121
187
  // A policy this tab already holds outlives a record written before it.
122
188
  if (next.policy === undefined && cur.policy !== undefined)
123
189
  next.policy = cur.policy;
190
+ // A session this tab is stopping comes back as the frozen copy it wrote
191
+ // (another tab wrote its cache back): this tab's clock and capture stay live.
192
+ if (stoppingHere?.sessionId === next.sessionId) {
193
+ next.paused = cur.paused;
194
+ next.activeMs = cur.activeMs;
195
+ next.resumeAt = cur.resumeAt;
196
+ delete next.stopping;
197
+ }
124
198
  recCache = next;
125
199
  return 'updated';
126
200
  }
@@ -149,6 +223,10 @@ function getBuffer() {
149
223
  }
150
224
  /** Write the in-memory buffer (and the pending chunks) to storage NOW. */
151
225
  export function persistNow() {
226
+ for (const item of pendingAllocations) {
227
+ if (!item.persisted)
228
+ item.persisted = safeSet(item.key, JSON.stringify({ draft: item.draft, seq: item.seq }));
229
+ }
152
230
  persistBuffer();
153
231
  persistChunks();
154
232
  }
@@ -207,7 +285,9 @@ function setChunks(chunks) {
207
285
  persistChunks();
208
286
  }
209
287
  export function queuedCount() {
210
- return getBuffer().length + getChunks().length;
288
+ recoverAllocations();
289
+ pruneAcknowledgedCaptures();
290
+ return getBuffer().length + getChunks().length + pendingAllocations.size;
211
291
  }
212
292
  // -- health + server reconciliation (extension D4/D5/D9) ---------------------
213
293
  let lastSyncAt = 0;
@@ -320,16 +400,203 @@ export function disarmReconcile() {
320
400
  clearInterval(reconcileTimer);
321
401
  reconcileTimer = null;
322
402
  }
323
- /** Allocate `count` consecutive seqs without emitting events; null when not capturing. */
324
- export function allocSeq(count = 1) {
403
+ /** Allocate inside the storage driver's lock; lifecycle writes cannot rewind its watermark. */
404
+ function allocSeq(count) {
325
405
  const rec = getState();
326
- if (!rec || rec.paused || rec.dead || count < 1)
406
+ if (!rec || rec.dead || count < 1)
327
407
  return null;
328
- const first = rec.seq + 1;
329
- rec.seq += count;
408
+ const watermark = readJson('seq', null);
409
+ const first = Math.max(rec.seq, watermark?.sessionId === rec.sessionId ? watermark.seq : 0) + 1;
410
+ // This write must succeed before a seq can be used in another document.
411
+ // On failure the capture stays pending and retries rather than colliding.
412
+ kv().set('seq', JSON.stringify({ sessionId: rec.sessionId, seq: first + count - 1 }));
413
+ rec.seq = first + count - 1;
330
414
  setState(rec);
331
415
  return { seq: first, sessionId: rec.sessionId };
332
416
  }
417
+ /** Document identity is not sessionStorage: duplicated tabs copy that store. */
418
+ export const RECORDER_DOCUMENT_KEY = `${Date.now().toString(36)}.${Math.random().toString(36).slice(2)}`;
419
+ const ALLOCATION_PREFIX = 'allocation.';
420
+ let captureNo = 0;
421
+ const pendingAllocations = new Set();
422
+ const MAX_ALLOCATION_BYTES = 16 * 1024 * 1024;
423
+ let allocationBytes = 0;
424
+ let allocationChunks = 0;
425
+ const allocatedCaptures = new Map();
426
+ let allocationsRecovered = false;
427
+ let allocationBusy = null;
428
+ function removeAllocation(item) {
429
+ if (!pendingAllocations.delete(item))
430
+ return;
431
+ allocationBytes -= item.bytes;
432
+ if (item.draft.kind === 'chunk')
433
+ allocationChunks--;
434
+ }
435
+ function addAllocation(item) {
436
+ pendingAllocations.add(item);
437
+ allocationBytes += item.bytes;
438
+ if (item.draft.kind === 'chunk')
439
+ allocationChunks++;
440
+ while (pendingAllocations.size > MAX_BUFFER || allocationBytes > MAX_ALLOCATION_BYTES || allocationChunks > MAX_PENDING) {
441
+ const oldest = pendingAllocations.values().next().value;
442
+ removeAllocation(oldest);
443
+ kv().remove(oldest.key);
444
+ const error = new Error('vitrinka: pending allocation budget full — oldest capture dropped');
445
+ noteFailure(error);
446
+ console.warn(error.message);
447
+ }
448
+ }
449
+ /** Journals survive pagehide and are safe for another document to help drain. */
450
+ function recoverAllocations(refresh = false) {
451
+ if (allocationsRecovered && !refresh)
452
+ return;
453
+ allocationsRecovered = true;
454
+ const storage = kv();
455
+ if (!storage.withLock)
456
+ return;
457
+ const queuedKeys = new Set([...pendingAllocations].map((item) => item.key));
458
+ for (const key of storage.keys?.() ?? []) {
459
+ if (!key.startsWith(ALLOCATION_PREFIX) || queuedKeys.has(key) || allocatedCaptures.has(key))
460
+ continue;
461
+ const item = readJson(key, null);
462
+ if (item && item.draft && item.draft.sessionId === getState()?.sessionId)
463
+ addAllocation({ ...item, key, persisted: true, bytes: utf8Bytes(JSON.stringify(item)) });
464
+ }
465
+ }
466
+ function appendCapture(draft, seq) {
467
+ const { ts, tabId, tabHost, sessionId } = draft;
468
+ if (draft.kind === 'event') {
469
+ const buffer = getBuffer();
470
+ if (!buffer.some((event) => event.seq === seq))
471
+ buffer.push({ seq, ts, tabId, tabHost, ...draft.event });
472
+ if (buffer.length > MAX_BUFFER) {
473
+ const dropped = buffer.splice(0, buffer.length - MAX_BUFFER);
474
+ clearStoredCaptures(sessionId, new Set(dropped.map((event) => event.seq)));
475
+ console.warn(`vitrinka: retry buffer full — dropped ${dropped.length} oldest events`);
476
+ }
477
+ }
478
+ else {
479
+ const chunks = getChunks();
480
+ if (!chunks.some((chunk) => chunk.seq === seq) && !getBuffer().some((event) => event.seq === seq)) {
481
+ chunks.push({ seq, ts, tabId, tabHost, sessionId, ...draft.part });
482
+ chunkBytes += draft.part.body.length;
483
+ }
484
+ while (chunks.length > MAX_PENDING) {
485
+ const dropped = chunks.shift();
486
+ chunkBytes -= dropped.body.length;
487
+ clearStoredCaptures(sessionId, new Set([dropped.seq]));
488
+ console.warn(`vitrinka: pending chunk queue full — dropped rrweb chunk seq ${dropped.seq}`);
489
+ }
490
+ }
491
+ schedulePersist();
492
+ scheduleFlush();
493
+ }
494
+ function clearStoredCaptures(sessionId, seqs) {
495
+ for (const [key, item] of allocatedCaptures) {
496
+ if (item.sessionId === sessionId && seqs.has(item.seq)) {
497
+ kv().remove(key);
498
+ allocatedCaptures.delete(key);
499
+ const documentKey = key.slice(ALLOCATION_PREFIX.length, key.lastIndexOf('.'));
500
+ const peerKey = `tab.${documentKey}`;
501
+ const peer = readJson(peerKey, null);
502
+ if (peer?.departed && peer.recoverable && !kv().keys?.().some((k) => k.startsWith(`${ALLOCATION_PREFIX}${documentKey}.`)))
503
+ kv().remove(peerKey);
504
+ }
505
+ }
506
+ }
507
+ /** Helpers remove a journal only after ack; the original tab may still cache its retry. */
508
+ function pruneAcknowledgedCaptures() {
509
+ const delivered = new Set();
510
+ for (const [key, item] of allocatedCaptures) {
511
+ if (item.persisted && !kv().getString(key)) {
512
+ delivered.add(item.seq);
513
+ allocatedCaptures.delete(key);
514
+ }
515
+ }
516
+ if (!delivered.size)
517
+ return;
518
+ setBuffer(getBuffer().filter((event) => !delivered.has(event.seq)));
519
+ setChunks(getChunks().filter((chunk) => !delivered.has(chunk.seq)));
520
+ }
521
+ /** A departing document can be acknowledged by a helper only with a full journal. */
522
+ export function tailIsDurable() {
523
+ if (!kv().keys)
524
+ return false;
525
+ const durableSeqs = new Set([...allocatedCaptures].filter(([key]) => kv().getString(key)).map(([, item]) => item.seq));
526
+ for (const item of pendingAllocations) {
527
+ if (item.persisted && item.seq !== undefined && kv().getString(item.key))
528
+ durableSeqs.add(item.seq);
529
+ }
530
+ return [...pendingAllocations].every((item) => item.persisted && !!kv().getString(item.key))
531
+ && getBuffer().every((event) => durableSeqs.has(event.seq))
532
+ && getChunks().every((chunk) => durableSeqs.has(chunk.seq));
533
+ }
534
+ /** One worker per document: evicted drafts cannot stay held by queued lock callbacks. */
535
+ function allocatePending() {
536
+ if (allocationBusy)
537
+ return allocationBusy;
538
+ const storage = kv();
539
+ allocationBusy = trackCapture(Promise.resolve().then(async () => {
540
+ for (const item of pendingAllocations) {
541
+ await storage.withLock('seq', () => {
542
+ if (!pendingAllocations.has(item))
543
+ return;
544
+ if (item.persisted) {
545
+ const saved = readJson(item.key, null);
546
+ // Another tab already delivered this journal; never allocate it twice.
547
+ if (!saved) {
548
+ removeAllocation(item);
549
+ return;
550
+ }
551
+ item.seq = saved.seq;
552
+ }
553
+ adoptStoredState(storage.getString(REC_KEY) ?? null);
554
+ if (getState()?.sessionId !== item.draft.sessionId) {
555
+ removeAllocation(item);
556
+ return;
557
+ }
558
+ const seq = item.seq ?? allocSeq(1)?.seq;
559
+ if (seq === undefined)
560
+ return;
561
+ item.seq = seq;
562
+ // Keep the payload AND its identity until the server acknowledges it.
563
+ // A recovering document reuses this seq even when the old tab is alive.
564
+ if (item.persisted)
565
+ storage.set(item.key, JSON.stringify({ draft: item.draft, seq }));
566
+ allocatedCaptures.set(item.key, { sessionId: item.draft.sessionId, seq, persisted: item.persisted });
567
+ appendCapture(item.draft, seq);
568
+ removeAllocation(item);
569
+ });
570
+ }
571
+ }).catch((error) => {
572
+ noteFailure(error);
573
+ console.warn('vitrinka: seq allocation failed — capture kept for retry', error);
574
+ scheduleFlush();
575
+ notify();
576
+ throw error;
577
+ })).finally(() => { allocationBusy = null; });
578
+ return allocationBusy;
579
+ }
580
+ /** Accept now, persist now, stamp under the shared lock later. */
581
+ function queueCapture(draft) {
582
+ const accepted = getState();
583
+ if (!accepted || accepted.paused || accepted.dead)
584
+ return false;
585
+ recoverAllocations();
586
+ if (kv().withLock) {
587
+ const key = `${ALLOCATION_PREFIX}${RECORDER_DOCUMENT_KEY}.${++captureNo}`;
588
+ const raw = JSON.stringify({ draft });
589
+ const item = { key, draft, persisted: safeSet(key, raw), bytes: utf8Bytes(raw) };
590
+ addAllocation(item);
591
+ void allocatePending();
592
+ }
593
+ else {
594
+ const allocation = allocSeq(1);
595
+ if (allocation)
596
+ appendCapture(draft, allocation.seq);
597
+ }
598
+ return true;
599
+ }
333
600
  /**
334
601
  * In-flight CAPTURES (async network body reads) that have not yet appended
335
602
  * their event. Stop must settle these before draining.
@@ -390,19 +657,10 @@ export function pushEvent(kind, payload, route) {
390
657
  return pushFlightEvent(kind, payload, route);
391
658
  if (rec.paused || rec.dead)
392
659
  return null;
393
- rec.seq++;
394
660
  const ts = new Date().toISOString();
395
- const buffer = getBuffer();
396
- buffer.push({ seq: rec.seq, ts, tabId: route.tabId, tabHost: route.tabHost, kind, payload });
397
- if (buffer.length > MAX_BUFFER) {
398
- const dropped = buffer.length - MAX_BUFFER;
399
- buffer.splice(0, dropped);
400
- console.warn(`vitrinka: retry buffer full — dropped ${dropped} oldest events`);
401
- }
661
+ const { tabId, tabHost } = route;
662
+ queueCapture({ sessionId: rec.sessionId, ts, tabId, tabHost, kind: 'event', event: { kind, payload } });
402
663
  noteActivity();
403
- schedulePersist();
404
- setState(rec);
405
- scheduleFlush();
406
664
  return ts;
407
665
  }
408
666
  /** Push a fully-formed event (chunk rows carry a pre-allocated seq). */
@@ -479,32 +737,13 @@ export function pushRRWebBatch(events, route) {
479
737
  text: `⚠ rrweb event dropped (${(b / 1048576).toFixed(1)} MiB > chunk cap) — replay may be incomplete from here`,
480
738
  }, route);
481
739
  }
482
- const alloc = parts.length ? allocSeq(parts.length) : null;
483
- if (!alloc)
484
- return 0;
485
- const chunks = getChunks();
486
740
  const ts = new Date().toISOString();
487
- parts.forEach((p, i) => {
488
- chunks.push({
489
- seq: alloc.seq + i,
490
- ts,
491
- tabId: route.tabId,
492
- tabHost: route.tabHost,
493
- sessionId: alloc.sessionId,
494
- count: p.count,
495
- body: p.body,
496
- });
497
- chunkBytes += p.body.length;
498
- });
499
- while (chunks.length > MAX_PENDING) {
500
- const drop = chunks.shift();
501
- if (drop)
502
- chunkBytes -= drop.body.length;
503
- console.warn(`vitrinka: pending chunk queue full — dropped rrweb chunk seq ${drop?.seq}`);
741
+ const { tabId, tabHost } = route;
742
+ for (const part of parts) {
743
+ if (!queueCapture({ sessionId: rec.sessionId, ts, tabId, tabHost, kind: 'chunk', part }))
744
+ return 0;
504
745
  }
505
746
  noteActivity();
506
- schedulePersist();
507
- scheduleFlush();
508
747
  return parts.length;
509
748
  }
510
749
  /**
@@ -553,6 +792,7 @@ async function drainPending(limit = 5) {
553
792
  return getChunks().length === 0;
554
793
  if (e instanceof VitrinkaApiError && permanentStatus(e.status)) {
555
794
  console.warn(`vitrinka: rrweb chunk seq ${item.seq} rejected permanently (${e.status}) — dropped`);
795
+ clearStoredCaptures(item.sessionId, new Set([item.seq]));
556
796
  gone.add(item.seq);
557
797
  continue;
558
798
  }
@@ -590,6 +830,11 @@ export async function flush(opts = {}) {
590
830
  async function flushInner(opts) {
591
831
  if (getState()?.dead)
592
832
  return false;
833
+ recoverAllocations(true);
834
+ if (pendingAllocations.size)
835
+ await allocatePending();
836
+ if (pendingAllocations.size)
837
+ return false;
593
838
  const pendingClear = await drainPending();
594
839
  if (!pendingClear)
595
840
  scheduleFlush();
@@ -626,6 +871,7 @@ async function flushInner(opts) {
626
871
  batchBytes += b;
627
872
  }
628
873
  if (oversized.size) {
874
+ clearStoredCaptures(rec.sessionId, oversized);
629
875
  setBuffer(getBuffer().filter((ev) => !oversized.has(ev.seq)));
630
876
  if (!batch.length) {
631
877
  scheduleFlush();
@@ -656,10 +902,11 @@ async function flushInner(opts) {
656
902
  if (movedOn(rec))
657
903
  return true;
658
904
  noteSync();
659
- serverMaxSeq = Math.max(serverMaxSeq, batch[batch.length - 1]?.seq ?? serverMaxSeq);
905
+ serverMaxSeq = Math.max(serverMaxSeq, ...batch.map((event) => event.seq));
660
906
  notify();
661
907
  // Remove EXACTLY the sent seqs — events pushed during the in-flight POST survive.
662
908
  const sent = new Set(batch.map((e) => e.seq));
909
+ clearStoredCaptures(rec.sessionId, sent);
663
910
  const rest = getBuffer().filter((e) => !sent.has(e.seq));
664
911
  setBuffer(rest);
665
912
  if (rest.length)
@@ -670,7 +917,9 @@ async function flushInner(opts) {
670
917
  export async function drainBuffer(deadlineMs = 60000) {
671
918
  const t0 = Date.now();
672
919
  while (Date.now() - t0 < deadlineMs) {
673
- if (getBuffer().length === 0 && getChunks().length === 0)
920
+ // A peer may journal its departure after an already-running flush scanned storage.
921
+ recoverAllocations(true);
922
+ if (queuedCount() === 0)
674
923
  return true;
675
924
  const sent = await flush();
676
925
  if (getState()?.dead)
@@ -683,6 +932,13 @@ export async function drainBuffer(deadlineMs = 60000) {
683
932
  }
684
933
  /** Reset buffers for a fresh session. */
685
934
  export function resetQueues() {
935
+ for (const key of allocatedCaptures.keys())
936
+ kv().remove(key);
937
+ for (const item of pendingAllocations)
938
+ kv().remove(item.key);
939
+ allocatedCaptures.clear();
940
+ pendingAllocations.clear();
941
+ allocationBytes = allocationChunks = 0;
686
942
  setBuffer([]);
687
943
  setChunks([]);
688
944
  }
@@ -698,6 +954,9 @@ function dropLocalTail() {
698
954
  bufferCache = [];
699
955
  chunkCache = [];
700
956
  chunkBytes = 0;
957
+ pendingAllocations.clear();
958
+ allocationBytes = allocationChunks = 0;
959
+ allocatedCaptures.clear();
701
960
  tailDropped = true;
702
961
  }
703
962
  /** Test-only: drop all module state so suites cannot leak into each other. */
@@ -707,6 +966,10 @@ export function __resetForTests() {
707
966
  kv().remove('rec');
708
967
  kv().remove('buffer');
709
968
  kv().remove('chunks');
969
+ kv().remove('seq');
970
+ for (const key of kv().keys?.() ?? [])
971
+ if (key.startsWith(ALLOCATION_PREFIX))
972
+ kv().remove(key);
710
973
  resetIdle();
711
974
  }
712
975
  /** Test-only: the recorded events currently buffered (in order). */
@@ -719,6 +982,11 @@ export function __chunksForTests() {
719
982
  }
720
983
  /** Test-only: drop the in-memory caches while LEAVING storage intact (a reload). */
721
984
  export function __dropCachesForTests() {
985
+ pendingAllocations.clear();
986
+ allocationBytes = allocationChunks = 0;
987
+ allocatedCaptures.clear();
988
+ allocationsRecovered = false;
989
+ allocationBusy = null;
722
990
  if (persistTimer) {
723
991
  clearTimeout(persistTimer);
724
992
  persistTimer = null;
@@ -729,6 +997,10 @@ export function __dropCachesForTests() {
729
997
  }
730
998
  flushBusy = false;
731
999
  tailDropped = false;
1000
+ stoppingHere = null;
1001
+ if (stoppingLease)
1002
+ clearInterval(stoppingLease);
1003
+ stoppingLease = null;
732
1004
  recCache = undefined;
733
1005
  bufferCache = undefined;
734
1006
  chunkCache = undefined;
@@ -14,6 +14,35 @@ export declare function readRecents(): readonly HudRecent[];
14
14
  export declare function noteRecent(entry: HudRecent): void;
15
15
  /** Patch a recording in place; a no-op for one not listed. */
16
16
  export declare function updateRecent(sessionId: string, patch: Partial<Omit<HudRecent, 'sessionId'>>): void;
17
+ /** What the reconcile read answers (the fields a recent can use). */
18
+ interface SessionRead {
19
+ status?: string;
20
+ deletedAt?: string | null;
21
+ boardUrl?: string;
22
+ board?: {
23
+ url?: string;
24
+ };
25
+ projection?: {
26
+ state?: string;
27
+ };
28
+ }
29
+ /** A session answer's board link: the server's `boardUrl`, or an older server's `board.url`. */
30
+ export declare function boardUrlOf(s: Pick<SessionRead, 'boardUrl' | 'board'> | null | undefined): string | undefined;
31
+ /** How often, and how long, a saved session is read until its board exists (the extension's D11 numbers). */
32
+ export declare const BOARD_POLL_MS = 1500;
33
+ export declare const BOARD_WAIT_MS: number;
34
+ /**
35
+ * The server answered a stop (or a report) before the session's board was
36
+ * built — it projects after the stop, stills first, 30–60 s. Read the
37
+ * session until it names its board and put the link on the recent, where
38
+ * the Saved face and the menu pick it up. Ends on a failed or empty
39
+ * projection, a gone or refused session, or after `forMs`; a transient
40
+ * error keeps waiting. Never rejects.
41
+ */
42
+ export declare function awaitBoard(sessionId: string, { everyMs, forMs }?: {
43
+ everyMs?: number;
44
+ forMs?: number;
45
+ }): Promise<void>;
17
46
  /**
18
47
  * Fill the board links the list lacks — `live` (the recording in progress)
19
48
  * is skipped, its link arrives with its stop. Never rejects.
@@ -23,3 +52,4 @@ export declare function refreshRecents(live: string | null): Promise<void>;
23
52
  export declare function forgetRecents(): void;
24
53
  /** Test-only: forget the in-memory list (storage stays). */
25
54
  export declare function __resetRecentsForTests(): void;
55
+ export {};
@@ -1,4 +1,4 @@
1
- import { api, VitrinkaApiError } from './api';
1
+ import { api, permanentStatus, VitrinkaApiError } from './api';
2
2
  import { notify } from './state';
3
3
  import { getRecorderStorage } from './storage';
4
4
  export const RECENTS_KEY = 'recents';
@@ -47,6 +47,53 @@ export function updateRecent(sessionId, patch) {
47
47
  return;
48
48
  write(list.map((r) => (r.sessionId === sessionId ? { ...r, ...patch } : r)));
49
49
  }
50
+ /** A session answer's board link: the server's `boardUrl`, or an older server's `board.url`. */
51
+ export function boardUrlOf(s) {
52
+ return s?.boardUrl || s?.board?.url || undefined;
53
+ }
54
+ /** How often, and how long, a saved session is read until its board exists (the extension's D11 numbers). */
55
+ export const BOARD_POLL_MS = 1_500;
56
+ export const BOARD_WAIT_MS = 10 * 60_000;
57
+ const awaiting = new Set();
58
+ /**
59
+ * The server answered a stop (or a report) before the session's board was
60
+ * built — it projects after the stop, stills first, 30–60 s. Read the
61
+ * session until it names its board and put the link on the recent, where
62
+ * the Saved face and the menu pick it up. Ends on a failed or empty
63
+ * projection, a gone or refused session, or after `forMs`; a transient
64
+ * error keeps waiting. Never rejects.
65
+ */
66
+ export async function awaitBoard(sessionId, { everyMs = BOARD_POLL_MS, forMs = BOARD_WAIT_MS } = {}) {
67
+ if (awaiting.has(sessionId))
68
+ return;
69
+ awaiting.add(sessionId);
70
+ const until = Date.now() + forMs;
71
+ try {
72
+ while (Date.now() < until) {
73
+ await new Promise((res) => setTimeout(res, everyMs));
74
+ try {
75
+ const s = await api('GET', `/api/v1/sessions/${sessionId}`);
76
+ const boardUrl = boardUrlOf(s);
77
+ if (boardUrl)
78
+ return updateRecent(sessionId, { boardUrl });
79
+ if (s.deletedAt)
80
+ return updateRecent(sessionId, { status: 'deleted' });
81
+ if (s.projection?.state === 'failed' || s.projection?.state === 'empty')
82
+ return;
83
+ }
84
+ catch (e) {
85
+ if (e instanceof VitrinkaApiError && e.status === 404)
86
+ return updateRecent(sessionId, { status: 'deleted' });
87
+ if (e instanceof VitrinkaApiError && permanentStatus(e.status))
88
+ return;
89
+ console.warn(`vitrinka: waiting for the board of session ${sessionId}`, e);
90
+ }
91
+ }
92
+ }
93
+ finally {
94
+ awaiting.delete(sessionId);
95
+ }
96
+ }
50
97
  /** Ids already asked this document — a refused read is not retried on every menu open. */
51
98
  const asked = new Set();
52
99
  /**
@@ -59,11 +106,14 @@ export async function refreshRecents(live) {
59
106
  asked.add(r.sessionId);
60
107
  try {
61
108
  const s = await api('GET', `/api/v1/sessions/${r.sessionId}`);
62
- const boardUrl = s.boardUrl ?? s.board?.url;
109
+ const boardUrl = boardUrlOf(s);
63
110
  if (s.deletedAt)
64
111
  updateRecent(r.sessionId, { status: 'deleted' });
65
112
  else if (boardUrl)
66
113
  updateRecent(r.sessionId, { boardUrl, ...(s.status === 'done' ? { status: 'saved' } : {}) });
114
+ // Still projecting (the document that waited for it reloaded or left): wait here instead.
115
+ else if (s.projection?.state === 'running')
116
+ void awaitBoard(r.sessionId);
67
117
  }
68
118
  catch (e) {
69
119
  if (e instanceof VitrinkaApiError && e.status === 404)
@@ -82,4 +132,5 @@ export function forgetRecents() {
82
132
  export function __resetRecentsForTests() {
83
133
  cache = undefined;
84
134
  asked.clear();
135
+ awaiting.clear();
85
136
  }
@@ -29,6 +29,7 @@ export declare function holdReport(on: boolean): void;
29
29
  */
30
30
  export declare function sendReport(note: ReportNote): Promise<{
31
31
  boardUrl?: string;
32
+ sessionId?: string;
32
33
  }>;
33
34
  /** The provider unmounted: forget the buffer and any held clip; a remount re-arms. */
34
35
  export declare function dropFlight(): void;
@@ -4,7 +4,7 @@ import { checkoutRRWeb } from './capture/rrweb';
4
4
  import { recorderConfig, vitrinkaLinked } from './config';
5
5
  import { clipHasSnapshot, flightActive, startFlightBuffer, stopFlightBuffer, takeFlightClip } from './flight';
6
6
  import { EVENTS_PER_POST, getState, MAX_BATCH_BYTES, splitRRWebEvents, utf8Bytes } from './queue';
7
- import { noteRecent } from './recents';
7
+ import { awaitBoard, boardUrlOf, noteRecent } from './recents';
8
8
  import { addAnnotation, createSession, imagePixels } from './session';
9
9
  import { currentRoute, notify } from './state';
10
10
  // -- the gate ----------------------------------------------------------------
@@ -196,7 +196,7 @@ const steps = [
196
196
  (j) => postEvents(j.sessionId, [j.note]),
197
197
  async (j) => {
198
198
  const done = await api('PATCH', `/api/v1/sessions/${j.sessionId}`, { status: 'done' });
199
- const url = done.board?.url;
199
+ const url = boardUrlOf(done);
200
200
  if (url)
201
201
  j.boardUrl = url;
202
202
  },
@@ -244,7 +244,9 @@ export async function sendReport(note) {
244
244
  status: 'saved',
245
245
  ...(j.boardUrl ? { boardUrl: j.boardUrl } : {}),
246
246
  });
247
- return j.boardUrl ? { boardUrl: j.boardUrl } : {};
247
+ if (!j.boardUrl)
248
+ void awaitBoard(j.sessionId);
249
+ return { ...(j.boardUrl ? { boardUrl: j.boardUrl } : {}), sessionId: j.sessionId };
248
250
  }
249
251
  /** The provider unmounted: forget the buffer and any held clip; a remount re-arms. */
250
252
  export function dropFlight() {
@@ -15,10 +15,11 @@ import type { RedactionPolicy } from '@vitrinka/redact';
15
15
  import type { SessionDone } from '../protocol';
16
16
  import { type SessionState } from './queue';
17
17
  export { currentRoute, notify, subscribe } from './state';
18
+ export { onBeforeStop } from './queue';
18
19
  export type { SessionDone } from '../protocol';
19
20
  /** Sent as `meta.recorder`; bumped with the package version. */
20
- export declare const RECORDER_VERSION = "0.3.2";
21
- export declare const RECORDER_ID = "web/0.3.2";
21
+ export declare const RECORDER_VERSION = "0.3.4";
22
+ export declare const RECORDER_ID = "web/0.3.4";
22
23
  /** What `POST /api/v1/sessions` answers (the fields this recorder keeps). */
23
24
  export interface SessionOut {
24
25
  id: string;
@@ -81,7 +82,10 @@ export declare function imagePixels(r: ViewRect): ViewRect;
81
82
  export declare function addAnnotation(text: string, rect: ViewRect, selector: string, opts?: {
82
83
  task?: boolean;
83
84
  }): void;
84
- export declare function onBeforeStop(fn: () => void): () => void;
85
+ /**
86
+ * Hooks that run at the top of Stop, before the drain snapshot — the rrweb
87
+ * lane ships its sub-2s tail here so the last DOM events make the session.
88
+ */
85
89
  /**
86
90
  * Stop the session. Throws with the queued-item count when the server is
87
91
  * unreachable — the durable tail is NEVER deleted; capture freezes paused and