@vitrinka/web 0.3.1 → 0.3.2

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.
@@ -18,7 +18,7 @@ import { installUnauthorizedHandler } from './link';
18
18
  import { insideHud } from './hud/host';
19
19
  import { armReconcile, flush, getState, persistNow, reconcile, scheduleFlush } from './queue';
20
20
  import { dropFlight, syncFlight } from './report';
21
- import { onBeforeStop, recoverRedactionPolicy } from './session';
21
+ import { followOtherTabs, onBeforeStop, recoverRedactionPolicy } from './session';
22
22
  import { annotateState, setTabIdentity, subscribe } from './state';
23
23
  const TAB_KEY = 'vitrinka.tab';
24
24
  /** One lane per browser tab: a per-tab id kept in sessionStorage (survives reloads). */
@@ -84,6 +84,8 @@ export function RecorderProvider({ config, children, }) {
84
84
  };
85
85
  const unsubscribe = subscribe(syncLanes);
86
86
  const offBeforeStop = onBeforeStop(flushRRWeb);
87
+ // Another tab's Start, pause or Stop reaches this one (syncLanes follows).
88
+ const unfollow = followOtherTabs();
87
89
  // A reload mid-session: the durable tail needs a drain, the reconcile
88
90
  // poll re-arming, the policy re-applying, and the new document is a nav.
89
91
  scheduleFlush();
@@ -113,6 +115,7 @@ export function RecorderProvider({ config, children, }) {
113
115
  document.removeEventListener('visibilitychange', onVisible);
114
116
  unsubscribe();
115
117
  offBeforeStop();
118
+ unfollow();
116
119
  uninstallClicks();
117
120
  uninstallControl();
118
121
  uninstall401();
@@ -139,10 +139,13 @@ export function RecorderPill(p) {
139
139
  const rec = p.snap.recording;
140
140
  const annotating = p.snap.annotating;
141
141
  const hold = p.menuOpen || p.composing || annotating || face === 'flow';
142
- // Content a closing segment keeps for its closing frames.
142
+ // Content a closing segment keeps for its closing frames — an ended
143
+ // recording's clock stands where it stopped, never ticking on.
143
144
  const lastRec = useRef(rec);
144
145
  if (rec)
145
146
  lastRec.current = rec;
147
+ else if (lastRec.current && lastRec.current.resumedAt !== null)
148
+ lastRec.current = { ...lastRec.current, activeMs: elapsedOf(lastRec.current, p.now), resumedAt: null };
146
149
  const lastFlow = useRef(p.flow);
147
150
  if (p.flow.face !== 'none')
148
151
  lastFlow.current = p.flow;
@@ -247,8 +250,10 @@ export function RecorderPill(p) {
247
250
  return (_jsx("button", { type: "button", className: "tab", "aria-label": "Show recorder", "data-state": bad ? 'bad' : rec && !rec.paused ? 'rec' : 'idle', ...p.handle, onClick: () => p.onMove({ spot: untuck(p.place) }) }));
248
251
  }
249
252
  const chip = shownRec ? syncChip(shownRec.sync, p.now) : null;
250
- const bad = chip?.kind === 'offline' || chip?.kind === 'error';
251
- const state = bad ? 'bad' : !shownRec || shownRec.paused || shownRec.dead ? 'paused' : 'rec';
253
+ // The state is the LIVE recording's: an ended one lends its closing frames content, never its state.
254
+ const live = rec ? syncChip(rec.sync, p.now).kind : null;
255
+ const bad = live === 'offline' || live === 'error';
256
+ const state = bad ? 'bad' : !rec || rec.paused || rec.dead ? 'paused' : 'rec';
252
257
  const unlinked = !p.snap.linked;
253
258
  const puckLabel = unlinked ? 'Link recorder' : 'Start recording';
254
259
  const confirming = p.flow.face === 'confirm';
@@ -63,6 +63,8 @@ export interface SessionState {
63
63
  policy?: RedactionPolicy | null;
64
64
  }
65
65
  export type { RecorderEvent };
66
+ /** Storage key of the session record — shared by every tab of the origin. */
67
+ export declare const REC_KEY = "rec";
66
68
  /**
67
69
  * The LIVE session record — a mutable alias of the cache, not a copy. Treat it
68
70
  * as READ-ONLY unless you pass the object you mutated straight to `setState()`
@@ -70,6 +72,18 @@ export type { RecorderEvent };
70
72
  */
71
73
  export declare function getState(): SessionState | null;
72
74
  export declare function setState(rec: SessionState | null): void;
75
+ export type StoredChange = 'joined' | 'updated' | 'ended' | 'unchanged';
76
+ /**
77
+ * Another document of this origin (a second tab) wrote the session record.
78
+ * The store is shared, this cache is not — a tab that joined a recording on
79
+ * load would otherwise keep painting and capturing it after another tab
80
+ * stopped it. So: a stop there ends the session here, dropping this tab's
81
+ * undelivered tail (the server no longer accepts it); a session started
82
+ * there is joined, as a reload joins it; the same session takes the stored
83
+ * record (a pause, a dead verdict) but never a lower seq than this tab
84
+ * already allocated. Nothing is written back.
85
+ */
86
+ export declare function adoptStoredState(raw: string | null): StoredChange;
73
87
  /** Write the in-memory buffer (and the pending chunks) to storage NOW. */
74
88
  export declare function persistNow(): void;
75
89
  export declare function queuedCount(): number;
@@ -65,6 +65,8 @@ function safeSet(key, value) {
65
65
  return false;
66
66
  }
67
67
  }
68
+ /** Storage key of the session record — shared by every tab of the origin. */
69
+ export const REC_KEY = 'rec';
68
70
  // The session record is small and read on every event — cache it in memory and
69
71
  // write through, so the capture hot path never parses JSON.
70
72
  let recCache;
@@ -75,15 +77,57 @@ let recCache;
75
77
  */
76
78
  export function getState() {
77
79
  if (recCache === undefined)
78
- recCache = readJson('rec', null);
80
+ recCache = readJson(REC_KEY, null);
79
81
  return recCache;
80
82
  }
81
83
  export function setState(rec) {
82
84
  recCache = rec;
83
85
  if (rec === null)
84
- kv().remove('rec');
86
+ kv().remove(REC_KEY);
85
87
  else
86
- safeSet('rec', JSON.stringify(rec));
88
+ safeSet(REC_KEY, JSON.stringify(rec));
89
+ }
90
+ /**
91
+ * Another document of this origin (a second tab) wrote the session record.
92
+ * The store is shared, this cache is not — a tab that joined a recording on
93
+ * load would otherwise keep painting and capturing it after another tab
94
+ * stopped it. So: a stop there ends the session here, dropping this tab's
95
+ * undelivered tail (the server no longer accepts it); a session started
96
+ * there is joined, as a reload joins it; the same session takes the stored
97
+ * record (a pause, a dead verdict) but never a lower seq than this tab
98
+ * already allocated. Nothing is written back.
99
+ */
100
+ export function adoptStoredState(raw) {
101
+ let next = null;
102
+ if (raw) {
103
+ try {
104
+ next = JSON.parse(raw);
105
+ }
106
+ catch {
107
+ return 'unchanged';
108
+ }
109
+ }
110
+ const cur = getState();
111
+ if (!next) {
112
+ if (!cur)
113
+ return 'unchanged';
114
+ recCache = null;
115
+ dropLocalTail();
116
+ disarmReconcile();
117
+ return 'ended';
118
+ }
119
+ if (cur?.sessionId === next.sessionId) {
120
+ next.seq = Math.max(next.seq, cur.seq);
121
+ // A policy this tab already holds outlives a record written before it.
122
+ if (next.policy === undefined && cur.policy !== undefined)
123
+ next.policy = cur.policy;
124
+ recCache = next;
125
+ return 'updated';
126
+ }
127
+ recCache = next;
128
+ // A tail this tab still held belongs to another session, never to this one.
129
+ dropLocalTail();
130
+ return 'joined';
87
131
  }
88
132
  /**
89
133
  * The event buffer lives in memory and is FLUSHED TO STORAGE on a debounce
@@ -92,6 +136,12 @@ export function setState(rec) {
92
136
  const PERSIST_DEBOUNCE_MS = 700;
93
137
  let bufferCache;
94
138
  let persistTimer = null;
139
+ /**
140
+ * This tab let go of its tail for another tab's session (dropLocalTail): its
141
+ * empty caches must not overwrite the stored tail that tab owns — not even
142
+ * on pagehide — until this tab queues work of its own again.
143
+ */
144
+ let tailDropped = false;
95
145
  function getBuffer() {
96
146
  if (bufferCache === undefined)
97
147
  bufferCache = readJson('buffer', []);
@@ -107,10 +157,11 @@ function persistBuffer() {
107
157
  clearTimeout(persistTimer);
108
158
  persistTimer = null;
109
159
  }
110
- if (bufferCache !== undefined)
160
+ if (bufferCache !== undefined && !tailDropped)
111
161
  safeSet('buffer', JSON.stringify(bufferCache));
112
162
  }
113
163
  function schedulePersist() {
164
+ tailDropped = false;
114
165
  if (persistTimer)
115
166
  return;
116
167
  persistTimer = setTimeout(() => {
@@ -121,6 +172,7 @@ function schedulePersist() {
121
172
  }
122
173
  function setBuffer(buffer) {
123
174
  bufferCache = buffer;
175
+ tailDropped = false;
124
176
  persistBuffer();
125
177
  }
126
178
  // -- pending rrweb chunks ----------------------------------------------------
@@ -135,6 +187,8 @@ function getChunks() {
135
187
  }
136
188
  /** Best-effort: persisted while small, memory-only (and said so) beyond the budget. */
137
189
  function persistChunks() {
190
+ if (tailDropped)
191
+ return;
138
192
  const chunks = getChunks();
139
193
  if (chunks.length === 0) {
140
194
  kv().remove('chunks');
@@ -149,6 +203,7 @@ function persistChunks() {
149
203
  function setChunks(chunks) {
150
204
  chunkCache = chunks;
151
205
  chunkBytes = chunks.reduce((n, c) => n + c.body.length, 0);
206
+ tailDropped = false;
152
207
  persistChunks();
153
208
  }
154
209
  export function queuedCount() {
@@ -308,6 +363,14 @@ export async function capturesSettled(deadlineMs = CAPTURES_SETTLE_MS) {
308
363
  }
309
364
  return true;
310
365
  }
366
+ /**
367
+ * Did this tab's session change while an upload for `rec` was out — ended
368
+ * or replaced by another tab (adoptStoredState)? Then the upload's outcome
369
+ * must not touch the queue, which belongs to the next session now.
370
+ */
371
+ function movedOn(rec) {
372
+ return getState()?.sessionId !== rec.sessionId;
373
+ }
311
374
  /** Is `id` the session currently in state AND still accepting capture? */
312
375
  export function isSessionLive(id) {
313
376
  const rec = getState();
@@ -467,6 +530,10 @@ async function drainPending(limit = 5) {
467
530
  }
468
531
  try {
469
532
  const up = await uploadChunk(rec.sessionId, item.seq, item.body);
533
+ // Another tab ended or replaced the session while this upload was out:
534
+ // its tail is gone here, and nothing of it may re-enter the queue.
535
+ if (movedOn(rec))
536
+ return getChunks().length === 0;
470
537
  // The event row joins the buffer only now, keeping its original seq —
471
538
  // a late retry fills the stream's gap.
472
539
  pushRawEvent({
@@ -482,6 +549,8 @@ async function drainPending(limit = 5) {
482
549
  gone.add(item.seq);
483
550
  }
484
551
  catch (e) {
552
+ if (movedOn(rec))
553
+ return getChunks().length === 0;
485
554
  if (e instanceof VitrinkaApiError && permanentStatus(e.status)) {
486
555
  console.warn(`vitrinka: rrweb chunk seq ${item.seq} rejected permanently (${e.status}) — dropped`);
487
556
  gone.add(item.seq);
@@ -570,6 +639,8 @@ async function flushInner(opts) {
570
639
  await api('POST', `/api/v1/sessions/${rec.sessionId}/events`, { events: batch }, opts);
571
640
  }
572
641
  catch (e) {
642
+ if (movedOn(rec))
643
+ return false;
573
644
  if (e instanceof VitrinkaApiError && permanentStatus(e.status)) {
574
645
  markSessionDead(`server rejected this session (${e.status})`);
575
646
  return false;
@@ -580,6 +651,10 @@ async function flushInner(opts) {
580
651
  scheduleFlush();
581
652
  return false;
582
653
  }
654
+ // Acked for a session this tab no longer holds: the buffer is another
655
+ // session's now, and its seqs restart — never filter it by these.
656
+ if (movedOn(rec))
657
+ return true;
583
658
  noteSync();
584
659
  serverMaxSeq = Math.max(serverMaxSeq, batch[batch.length - 1]?.seq ?? serverMaxSeq);
585
660
  notify();
@@ -611,6 +686,20 @@ export function resetQueues() {
611
686
  setBuffer([]);
612
687
  setChunks([]);
613
688
  }
689
+ /**
690
+ * Forget this tab's buffers WITHOUT writing storage: another tab owns the
691
+ * stored record now, and its own tail there must survive.
692
+ */
693
+ function dropLocalTail() {
694
+ if (persistTimer) {
695
+ clearTimeout(persistTimer);
696
+ persistTimer = null;
697
+ }
698
+ bufferCache = [];
699
+ chunkCache = [];
700
+ chunkBytes = 0;
701
+ tailDropped = true;
702
+ }
614
703
  /** Test-only: drop all module state so suites cannot leak into each other. */
615
704
  export function __resetForTests() {
616
705
  __dropCachesForTests();
@@ -639,6 +728,7 @@ export function __dropCachesForTests() {
639
728
  flushTimer = null;
640
729
  }
641
730
  flushBusy = false;
731
+ tailDropped = false;
642
732
  recCache = undefined;
643
733
  bufferCache = undefined;
644
734
  chunkCache = undefined;
@@ -19,5 +19,7 @@ export declare function updateRecent(sessionId: string, patch: Partial<Omit<HudR
19
19
  * is skipped, its link arrives with its stop. Never rejects.
20
20
  */
21
21
  export declare function refreshRecents(live: string | null): Promise<void>;
22
+ /** Another tab wrote the list (its stop saved a recording): read it afresh. */
23
+ export declare function forgetRecents(): void;
22
24
  /** Test-only: forget the in-memory list (storage stays). */
23
25
  export declare function __resetRecentsForTests(): void;
@@ -73,6 +73,11 @@ export async function refreshRecents(live) {
73
73
  }
74
74
  }
75
75
  }
76
+ /** Another tab wrote the list (its stop saved a recording): read it afresh. */
77
+ export function forgetRecents() {
78
+ cache = undefined;
79
+ notify();
80
+ }
76
81
  /** Test-only: forget the in-memory list (storage stays). */
77
82
  export function __resetRecentsForTests() {
78
83
  cache = undefined;
@@ -17,8 +17,8 @@ import { type SessionState } from './queue';
17
17
  export { currentRoute, notify, subscribe } from './state';
18
18
  export type { SessionDone } from '../protocol';
19
19
  /** Sent as `meta.recorder`; bumped with the package version. */
20
- export declare const RECORDER_VERSION = "0.3.1";
21
- export declare const RECORDER_ID = "web/0.3.1";
20
+ export declare const RECORDER_VERSION = "0.3.2";
21
+ export declare const RECORDER_ID = "web/0.3.2";
22
22
  /** What `POST /api/v1/sessions` answers (the fields this recorder keeps). */
23
23
  export interface SessionOut {
24
24
  id: string;
@@ -30,6 +30,14 @@ export interface SessionOut {
30
30
  workspace?: string;
31
31
  }
32
32
  export declare function recoverRedactionPolicy(): void;
33
+ /**
34
+ * Keep this document on the recording its other tabs share: the session
35
+ * record and the recents live in storage every tab of the origin reads, but
36
+ * each document caches them. A Stop in one tab ends the session in the
37
+ * others (their pills go idle, their lanes stop sending into it), a Start
38
+ * is joined as a reload joins it, a pause follows. Returns the unsubscribe.
39
+ */
40
+ export declare function followOtherTabs(): () => void;
33
41
  export declare function elapsedOf(rec: SessionState | null): number;
34
42
  export interface StartOptions {
35
43
  title?: string;
@@ -1,12 +1,13 @@
1
1
  import { api, fetchPolicy, permanentStatus, VitrinkaApiError } from './api';
2
2
  import { redactUrl, setRedactionPolicy } from './capture/redact';
3
3
  import { recorderConfig } from './config';
4
- import { armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, pushEvent, queuedCount, resetHealth, resetIdle, resetQueues, setState, } from './queue';
5
- import { noteRecent, updateRecent } from './recents';
4
+ import { adoptStoredState, armReconcile, capturesSettled, disarmReconcile, drainBuffer, getState, pushEvent, queuedCount, REC_KEY, resetHealth, resetIdle, resetQueues, setState, } from './queue';
5
+ import { forgetRecents, noteRecent, RECENTS_KEY, updateRecent } from './recents';
6
6
  import { currentRoute, notify } from './state';
7
+ import { getRecorderStorage } from './storage';
7
8
  export { currentRoute, notify, subscribe } from './state';
8
9
  /** Sent as `meta.recorder`; bumped with the package version. */
9
- export const RECORDER_VERSION = '0.3.1';
10
+ export const RECORDER_VERSION = '0.3.2';
10
11
  export const RECORDER_ID = `web/${RECORDER_VERSION}`;
11
12
  /**
12
13
  * Re-apply a RECOVERED session's redaction policy after a reload — and
@@ -37,6 +38,39 @@ export function recoverRedactionPolicy() {
37
38
  policyRecoveryInFlight = false;
38
39
  });
39
40
  }
41
+ /**
42
+ * Keep this document on the recording its other tabs share: the session
43
+ * record and the recents live in storage every tab of the origin reads, but
44
+ * each document caches them. A Stop in one tab ends the session in the
45
+ * others (their pills go idle, their lanes stop sending into it), a Start
46
+ * is joined as a reload joins it, a pause follows. Returns the unsubscribe.
47
+ */
48
+ export function followOtherTabs() {
49
+ const storage = getRecorderStorage();
50
+ const offRec = storage.watch?.(REC_KEY, (raw) => {
51
+ const had = getState()?.policy;
52
+ const change = adoptStoredState(raw);
53
+ if (change === 'unchanged')
54
+ return;
55
+ if (change === 'ended')
56
+ setRedactionPolicy(null);
57
+ if (change === 'joined') {
58
+ recoverRedactionPolicy();
59
+ armReconcile();
60
+ }
61
+ // The starting tab writes the workspace policy after its first record:
62
+ // its rules apply here the moment they arrive.
63
+ const policy = getState()?.policy;
64
+ if (change === 'updated' && had === undefined && policy !== undefined)
65
+ setRedactionPolicy(policy);
66
+ notify();
67
+ });
68
+ const offRecents = storage.watch?.(RECENTS_KEY, forgetRecents);
69
+ return () => {
70
+ offRec?.();
71
+ offRecents?.();
72
+ };
73
+ }
40
74
  export function elapsedOf(rec) {
41
75
  if (!rec)
42
76
  return 0;
@@ -236,7 +270,9 @@ export async function stopSession() {
236
270
  console.warn('vitrinka: stopping with unsettled captures — a late event may not make this session');
237
271
  }
238
272
  if (!(await drainBuffer())) {
239
- const held = getState();
273
+ const live = getState();
274
+ // Another tab may have moved on to a session of its own meanwhile — never this stop's to hold.
275
+ const held = live?.sessionId === rec.sessionId ? live : null;
240
276
  if (held?.dead)
241
277
  completeDeadStop(held.deadReason);
242
278
  if (held && !held.paused) {
@@ -266,9 +302,13 @@ export async function stopSession() {
266
302
  // A permanent refusal still ends the recording locally, but it was not saved.
267
303
  const boardUrl = done?.board?.url ?? rec.boardUrl;
268
304
  updateRecent(rec.sessionId, { status: done ? 'saved' : 'unsaved', durationMs, ...(boardUrl ? { boardUrl } : {}) });
269
- setState(null);
270
- setRedactionPolicy(null);
271
- resetQueues();
305
+ // Another tab may have ended this session or started the next one while
306
+ // the stop was out: the state and the queues are then not this stop's to clear.
307
+ if (getState()?.sessionId === rec.sessionId) {
308
+ setState(null);
309
+ setRedactionPolicy(null);
310
+ resetQueues();
311
+ }
272
312
  notify();
273
313
  return done;
274
314
  }
@@ -18,6 +18,12 @@ export interface RecorderStorage {
18
18
  set(key: string, value: string): void;
19
19
  /** Delete a key; a no-op when absent. */
20
20
  remove(key: string): void;
21
+ /**
22
+ * Hear another document (a second tab) write `key` — `null` when it was
23
+ * removed; returns the unsubscribe. Optional: a driver no other document
24
+ * shares (memory) has nothing to hear.
25
+ */
26
+ watch?(key: string, onChange: (value: string | null) => void): () => void;
21
27
  }
22
28
  /**
23
29
  * Install a storage driver. Call before the recorder mounts; calling after
@@ -47,6 +47,17 @@ export function localRecorderStorage() {
47
47
  getString: (k) => ls.getItem(PREFIX + k),
48
48
  set: (k, v) => ls.setItem(PREFIX + k, v),
49
49
  remove: (k) => ls.removeItem(PREFIX + k),
50
+ // localStorage is shared by every tab of the origin; its `storage`
51
+ // event reaches the OTHER documents only. A clear() (key null) is not
52
+ // a write of `k` and is ignored.
53
+ watch: (k, onChange) => {
54
+ const on = (e) => {
55
+ if (e.storageArea === ls && e.key === PREFIX + k)
56
+ onChange(e.newValue);
57
+ };
58
+ globalThis.addEventListener('storage', on);
59
+ return () => globalThis.removeEventListener('storage', on);
60
+ },
50
61
  };
51
62
  }
52
63
  catch {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vitrinka/web",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "vitrinka toolkit for React DOM apps — the journey recorder: capture manual-testing sessions (rrweb DOM stream, clicks, navigation, network, console, notes) straight into vitrinka boards.",
5
5
  "license": "Elastic-2.0",
6
6
  "repository": {