@assistant-ui/react-statewire 0.18.0 → 0.19.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.
@@ -2,7 +2,7 @@ import { StatewireThread } from "./StatewireThread.js";
2
2
  //#region src/localStorage.d.ts
3
3
  /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
4
4
  declare const LocalStorageComposerDrafts: import("@assistant-ui/tap").Resource<StatewireThread.ComposerStorage, [LocalStorageComposerDrafts.Options]>;
5
- /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */
5
+ /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */
6
6
  declare const LocalStorageSession: import("@assistant-ui/tap").Resource<StatewireClient.SessionStorage, [LocalStorageSession.Options]>;
7
7
  declare namespace LocalStorageSession {
8
8
  type Options = {
@@ -1 +1 @@
1
- {"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;cA4Ea,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA4B1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;;IAEV;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
1
+ {"version":3,"file":"localStorage.d.ts","names":[],"sources":["../src/localStorage.ts"],"mappings":";;;cA4Ea,wDAA0B,SAAA,gBAAA,kBAAA,2BAAA;;cA4C1B,iDAAmB,SAAA,gBAAA,iBAAA,oBAAA;kBAEf;OACH;;IAEV;;IAEA,QAAQ;;;kBAIK;OACH;;IAEV;;IAEA,QAAQ;;IAER;;IAEA"}
@@ -57,9 +57,12 @@ const useLocalStorageComposerDrafts = ({ threadId, key = (id) => id, ttl = 7 * D
57
57
  };
58
58
  /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
59
59
  const LocalStorageComposerDrafts = resource(useLocalStorageComposerDrafts);
60
+ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
60
61
  const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
61
62
  if (typeof localStorage === "undefined") throw new Error("statewire: LocalStorageSession requires localStorage");
63
+ if (typeof navigator === "undefined" || navigator.locks === void 0) throw new Error("statewire: LocalStorageSession requires the Web Locks API (navigator.locks)");
62
64
  const storageKey = SESSION_PREFIX + key(threadId);
65
+ const lockName = SESSION_LOCK_PREFIX + key(threadId);
63
66
  return useMemo(() => ({
64
67
  load: () => {
65
68
  const raw = localStorage.getItem(storageKey);
@@ -68,10 +71,18 @@ const useLocalStorageSession = ({ threadId, key = (id) => id }) => {
68
71
  },
69
72
  save: (record) => {
70
73
  localStorage.setItem(storageKey, JSON.stringify(record));
74
+ },
75
+ lock: (fn) => navigator.locks.request(lockName, async () => fn()),
76
+ subscribe: (listener) => {
77
+ const onStorage = (event) => {
78
+ if (event.key === storageKey) listener();
79
+ };
80
+ window.addEventListener("storage", onStorage);
81
+ return () => window.removeEventListener("storage", onStorage);
71
82
  }
72
- }), [storageKey]);
83
+ }), [storageKey, lockName]);
73
84
  };
74
- /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */
85
+ /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */
75
86
  const LocalStorageSession = resource(useLocalStorageSession);
76
87
  //#endregion
77
88
  export { LocalStorageComposerDrafts, LocalStorageSession };
@@ -1 +1 @@
1
- {"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","StoredDraft","text","attachments","ComposerDraft","ts","sweep","ttl","max","entries","key","i","localStorage","length","startsWith","JSON","parse","getItem","push","now","Date","fresh","filter","removeItem","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","raw","undefined","write","draft","setItem","stringify","clear","useLocalStorageSession","LocalStorageSession","SessionStorage","load","SessionRecord","save","record"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i)!;\n if (!key.startsWith(PREFIX)) continue;\n const { ts } = JSON.parse(localStorage.getItem(key)!) as StoredDraft;\n entries.push({ key, ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n useEffect(() => {\n sweep(ttl, max);\n }, [ttl, max]);\n\n const storageKey = PREFIX + key(threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const raw = localStorage.getItem(storageKey);\n if (raw === null) return undefined;\n const { text, attachments } = JSON.parse(raw) as StoredDraft;\n return { text, attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst useLocalStorageSession = ({\n threadId,\n key = (id) => id,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n\n const storageKey = SESSION_PREFIX + key(threadId);\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n load: () => {\n const raw = localStorage.getItem(storageKey);\n if (raw === null) return null;\n return JSON.parse(raw) as StatewireClient.SessionRecord;\n },\n save: (record) => {\n localStorage.setItem(storageKey, JSON.stringify(record));\n },\n }),\n [storageKey],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n /** The thread whose session this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;AAKA,MAAMK,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,SAASC,KAAaC,QAAgB;CAC1C,MAAMC,UAAyC,CAAA;CAC/C,KAAK,IAAIE,IAAI,GAAGA,IAAIC,aAAaC,QAAQF,KAAK;EAC5C,MAAMD,MAAME,aAAaF,IAAIC,CAAC;EAC9B,IAAI,CAACD,IAAII,WAAWhB,MAAM,GAAG;EAC7B,MAAM,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AAU,CACb;AACF;;AAGA,MAAaJ,6BAA6BpC,SACxCiC,6BACF;AAEA,MAAMgB,0BAA0B,EAC9Bf,UACAnB,OAAOoB,OAAOA,SACmD;CACjE,IAAI,OAAOlB,iBAAiB,aAC1B,MAAM,IAAIsB,MAAM,sDAAsD;CAExE,MAAMC,aAAapC,iBAAiBW,IAAImB,QAAQ;CAChD,OAAOnC,eACkC;EACrCqD,YAAY;GACV,MAAMV,MAAMzB,aAAaK,QAAQkB,UAAU;GAC3C,IAAIE,QAAQ,MAAM,OAAO;GACzB,OAAOtB,KAAKC,MAAMqB,GAAG;EACvB;EACAY,OAAOC,WAAW;GAChBtC,aAAa6B,QAAQN,YAAYpB,KAAK2B,UAAUQ,MAAM,CAAC;EACzD;CACF,IACA,CAACf,UAAU,CACb;AACF;;AAGA,MAAaU,sBAAsBlD,SAASiD,sBAAsB"}
1
+ {"version":3,"file":"localStorage.js","names":["useEffect","useMemo","resource","StatewireClient","StatewireThread","PREFIX","SESSION_PREFIX","DAY","StoredDraft","text","attachments","ComposerDraft","ts","sweep","ttl","max","entries","key","i","localStorage","length","startsWith","JSON","parse","getItem","push","now","Date","fresh","filter","removeItem","sort","a","b","slice","useLocalStorageComposerDrafts","threadId","id","LocalStorageComposerDrafts","Options","ComposerStorage","Error","storageKey","read","raw","undefined","write","draft","setItem","stringify","clear","SESSION_LOCK_PREFIX","useLocalStorageSession","LocalStorageSession","SessionStorage","navigator","locks","lockName","load","SessionRecord","save","record","lock","fn","request","subscribe","listener","onStorage","event","StorageEvent","window","addEventListener","removeEventListener"],"sources":["../src/localStorage.ts"],"sourcesContent":["import { useEffect, useMemo } from \"react\";\nimport { resource } from \"@assistant-ui/tap\";\nimport type { StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nconst PREFIX = \"aui:composer-draft:\";\nconst SESSION_PREFIX = \"aui:statewire-session:\";\nconst DAY = 86_400_000;\n\ntype StoredDraft = {\n text: string;\n attachments: StatewireThread.ComposerDraft[\"attachments\"];\n ts: number;\n};\n\nconst sweep = (ttl: number, max: number) => {\n const entries: { key: string; ts: number }[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const key = localStorage.key(i)!;\n if (!key.startsWith(PREFIX)) continue;\n const { ts } = JSON.parse(localStorage.getItem(key)!) as StoredDraft;\n entries.push({ key, ts });\n }\n const now = Date.now();\n const fresh = entries.filter(({ key, ts }) => {\n if (now - ts <= ttl) return true;\n localStorage.removeItem(key);\n return false;\n });\n fresh.sort((a, b) => b.ts - a.ts);\n for (const { key } of fresh.slice(max)) localStorage.removeItem(key);\n};\n\nconst useLocalStorageComposerDrafts = ({\n threadId,\n key = (id) => id,\n ttl = 7 * DAY,\n max = 50,\n}: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\n \"statewire: LocalStorageComposerDrafts requires localStorage\",\n );\n\n useEffect(() => {\n sweep(ttl, max);\n }, [ttl, max]);\n\n const storageKey = PREFIX + key(threadId);\n return useMemo(\n (): StatewireThread.ComposerStorage => ({\n read: () => {\n const raw = localStorage.getItem(storageKey);\n if (raw === null) return undefined;\n const { text, attachments } = JSON.parse(raw) as StoredDraft;\n return { text, attachments };\n },\n write: (draft) => {\n if (draft.text === \"\" && draft.attachments.length === 0) {\n localStorage.removeItem(storageKey);\n return;\n }\n localStorage.setItem(\n storageKey,\n JSON.stringify({ ...draft, ts: Date.now() }),\n );\n },\n clear: () => {\n localStorage.removeItem(storageKey);\n },\n }),\n [storageKey],\n );\n};\n\n/** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */\nexport const LocalStorageComposerDrafts = resource(\n useLocalStorageComposerDrafts,\n);\n\nconst SESSION_LOCK_PREFIX = \"aui:statewire-session-lock:\";\n\nconst useLocalStorageSession = ({\n threadId,\n key = (id) => id,\n}: LocalStorageSession.Options): StatewireClient.SessionStorage => {\n if (typeof localStorage === \"undefined\")\n throw new Error(\"statewire: LocalStorageSession requires localStorage\");\n // localStorage is shared across tabs: record mutations must serialize.\n if (typeof navigator === \"undefined\" || navigator.locks === undefined)\n throw new Error(\n \"statewire: LocalStorageSession requires the Web Locks API (navigator.locks)\",\n );\n\n const storageKey = SESSION_PREFIX + key(threadId);\n const lockName = SESSION_LOCK_PREFIX + key(threadId);\n return useMemo(\n (): StatewireClient.SessionStorage => ({\n load: () => {\n const raw = localStorage.getItem(storageKey);\n if (raw === null) return null;\n return JSON.parse(raw) as StatewireClient.SessionRecord;\n },\n save: (record) => {\n localStorage.setItem(storageKey, JSON.stringify(record));\n },\n lock: (fn) => navigator.locks.request(lockName, async () => fn()),\n subscribe: (listener) => {\n const onStorage = (event: StorageEvent) => {\n if (event.key === storageKey) listener();\n };\n window.addEventListener(\"storage\", onStorage);\n return () => window.removeEventListener(\"storage\", onStorage);\n },\n }),\n [storageKey, lockName],\n );\n};\n\n/** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */\nexport const LocalStorageSession = resource(useLocalStorageSession);\n\nexport namespace LocalStorageSession {\n export type Options = {\n /** The thread whose session this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n };\n}\n\nexport namespace LocalStorageComposerDrafts {\n export type Options = {\n /** The thread whose draft this storage holds. */\n threadId: string;\n /** Derives the storage key from the thread id; defaults to the id itself. */\n key?: ((threadId: string) => string) | undefined;\n /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */\n ttl?: number | undefined;\n /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */\n max?: number | undefined;\n };\n}\n"],"mappings":";;;AAKA,MAAMK,SAAS;AACf,MAAMC,iBAAiB;AACvB,MAAMC,MAAM;AAQZ,MAAMM,SAASC,KAAaC,QAAgB;CAC1C,MAAMC,UAAyC,CAAA;CAC/C,KAAK,IAAIE,IAAI,GAAGA,IAAIC,aAAaC,QAAQF,KAAK;EAC5C,MAAMD,MAA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CAAC,CAC7C;EACF;EACAwB,aAAa;GACX/B,aAAaW,WAAWY,UAAU;EACpC;CACF,IACA,CAACA,UAAU,CACb;AACF;;AAGA,MAAaJ,6BAA6BpC,SACxCiC,6BACF;AAEA,MAAMgB,sBAAsB;AAE5B,MAAMC,0BAA0B,EAC9BhB,UACAnB,OAAOoB,OAAOA,SACmD;CACjE,IAAI,OAAOlB,iBAAiB,aAC1B,MAAM,IAAIsB,MAAM,sDAAsD;CAExE,IAAI,OAAOc,cAAc,eAAeA,UAAUC,UAAUX,KAAAA,GAC1D,MAAM,IAAIJ,MACR,6EACF;CAEF,MAAMC,aAAapC,iBAAiBW,IAAImB,QAAQ;CAChD,MAAMqB,WAAWN,sBAAsBlC,IAAImB,QAAQ;CACnD,OAAOnC,eACkC;EACrCyD,YAAY;GACV,MAAMd,MAAMzB,aAAaK,QAAQkB,UAAU;GAC3C,IAAIE,QAAQ,MAAM,OAAO;GACzB,OAAOtB,KAAKC,MAAMqB,GAAG;EACvB;EACAgB,OAAOC,WAAW;GAChB1C,aAAa6B,QAAQN,YAAYpB,KAAK2B,UAAUY,MAAM,CAAC;EACzD;EACAC,OAAOC,OAAOR,UAAUC,MAAMQ,QAAQP,UAAU,YAAYM,GAAG,CAAC;EAChEE,YAAYC,aAAa;GACvB,MAAMC,aAAaC,UAAwB;IACzC,IAAIA,MAAMnD,QAAQyB,YAAYwB,SAAS;GACzC;GACAI,OAAOC,iBAAiB,WAAWJ,SAAS;GAC5C,aAAaG,OAAOE,oBAAoB,WAAWL,SAAS;EAC9D;CACF,IACA,CAACzB,YAAYe,QAAQ,CACvB;AACF;;AAGA,MAAaJ,sBAAsBnD,SAASkD,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -37,7 +37,7 @@
37
37
  "@assistant-ui/store": "^0.3.0",
38
38
  "@assistant-ui/tap": "^0.9.7",
39
39
  "assistant-stream": "^0.3.37",
40
- "statewire": "^0.10.0"
40
+ "statewire": "^0.11.0"
41
41
  },
42
42
  "peerDependencies": {
43
43
  "@assistant-ui/core": ">=0.3.12",
@@ -12,6 +12,7 @@ import {
12
12
 
13
13
  const PREFIX = "aui:composer-draft:";
14
14
  const SESSION_PREFIX = "aui:statewire-session:";
15
+ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
15
16
 
16
17
  const mount = (options: LocalStorageComposerDrafts.Options) =>
17
18
  createTapRoot(() => useResource(LocalStorageComposerDrafts(options)));
@@ -105,9 +106,30 @@ describe("LocalStorageSession", () => {
105
106
  const mountSession = (options: LocalStorageSession.Options) =>
106
107
  createTapRoot(() => useResource(LocalStorageSession(options)));
107
108
 
109
+ const requested: string[] = [];
110
+ const stubWebLocks = () => {
111
+ let chain: Promise<unknown> = Promise.resolve();
112
+ Object.defineProperty(navigator, "locks", {
113
+ configurable: true,
114
+ value: {
115
+ request: (name: string, cb: () => Promise<unknown>) => {
116
+ requested.push(name);
117
+ const run = chain.then(() => cb());
118
+ chain = run.then(
119
+ () => {},
120
+ () => {},
121
+ );
122
+ return run;
123
+ },
124
+ },
125
+ });
126
+ };
127
+
108
128
  beforeEach(() => {
109
129
  vi.unstubAllGlobals();
110
130
  localStorage.clear();
131
+ requested.length = 0;
132
+ stubWebLocks();
111
133
  });
112
134
 
113
135
  it("round-trips the record with its un-durable commands", () => {
@@ -141,10 +163,60 @@ describe("LocalStorageSession", () => {
141
163
  root.unmount();
142
164
  });
143
165
 
166
+ it("serializes lock sections on a per-key Web Lock", async () => {
167
+ const root = mountSession({ threadId: "t1" });
168
+ const order: string[] = [];
169
+ let release!: () => void;
170
+ const held = new Promise<void>((r) => {
171
+ release = r;
172
+ });
173
+ const first = root.getValue().lock!(async () => {
174
+ order.push("first:enter");
175
+ await held;
176
+ order.push("first:exit");
177
+ });
178
+ const second = root.getValue().lock!(async () => {
179
+ order.push("second");
180
+ });
181
+ release();
182
+ await Promise.all([first, second]);
183
+ expect(order).toEqual(["first:enter", "first:exit", "second"]);
184
+ expect(requested).toEqual([
185
+ `${SESSION_LOCK_PREFIX}t1`,
186
+ `${SESSION_LOCK_PREFIX}t1`,
187
+ ]);
188
+ root.unmount();
189
+ });
190
+
191
+ it("notifies subscribers on storage events for the session key only", () => {
192
+ const root = mountSession({ threadId: "t1" });
193
+ const seen: number[] = [];
194
+ const unsubscribe = root.getValue().subscribe!(() => seen.push(1));
195
+
196
+ const fire = (key: string) =>
197
+ window.dispatchEvent(new StorageEvent("storage", { key }));
198
+ fire(`${SESSION_PREFIX}t1`);
199
+ fire(`${SESSION_PREFIX}other`);
200
+ fire("unrelated");
201
+ expect(seen).toEqual([1]);
202
+
203
+ unsubscribe();
204
+ fire(`${SESSION_PREFIX}t1`);
205
+ expect(seen).toEqual([1]);
206
+ root.unmount();
207
+ });
208
+
144
209
  it("throws without localStorage", () => {
145
210
  vi.stubGlobal("localStorage", undefined);
146
211
  expect(() => mountSession({ threadId: "t1" })).toThrow(
147
212
  /requires localStorage/,
148
213
  );
149
214
  });
215
+
216
+ it("throws without the Web Locks API", () => {
217
+ delete (navigator as { locks?: unknown }).locks;
218
+ expect(() => mountSession({ threadId: "t1" })).toThrow(
219
+ /requires the Web Locks API/,
220
+ );
221
+ });
150
222
  });
@@ -78,14 +78,22 @@ export const LocalStorageComposerDrafts = resource(
78
78
  useLocalStorageComposerDrafts,
79
79
  );
80
80
 
81
+ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
82
+
81
83
  const useLocalStorageSession = ({
82
84
  threadId,
83
85
  key = (id) => id,
84
86
  }: LocalStorageSession.Options): StatewireClient.SessionStorage => {
85
87
  if (typeof localStorage === "undefined")
86
88
  throw new Error("statewire: LocalStorageSession requires localStorage");
89
+ // localStorage is shared across tabs: record mutations must serialize.
90
+ if (typeof navigator === "undefined" || navigator.locks === undefined)
91
+ throw new Error(
92
+ "statewire: LocalStorageSession requires the Web Locks API (navigator.locks)",
93
+ );
87
94
 
88
95
  const storageKey = SESSION_PREFIX + key(threadId);
96
+ const lockName = SESSION_LOCK_PREFIX + key(threadId);
89
97
  return useMemo(
90
98
  (): StatewireClient.SessionStorage => ({
91
99
  load: () => {
@@ -96,12 +104,20 @@ const useLocalStorageSession = ({
96
104
  save: (record) => {
97
105
  localStorage.setItem(storageKey, JSON.stringify(record));
98
106
  },
107
+ lock: (fn) => navigator.locks.request(lockName, async () => fn()),
108
+ subscribe: (listener) => {
109
+ const onStorage = (event: StorageEvent) => {
110
+ if (event.key === storageKey) listener();
111
+ };
112
+ window.addEventListener("storage", onStorage);
113
+ return () => window.removeEventListener("storage", onStorage);
114
+ },
99
115
  }),
100
- [storageKey],
116
+ [storageKey, lockName],
101
117
  );
102
118
  };
103
119
 
104
- /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict. */
120
+ /** Session storage on localStorage, keyed per thread: the lane identity plus the commands awaiting a durable verdict; sharers serialize through a per-key Web Lock. */
105
121
  export const LocalStorageSession = resource(useLocalStorageSession);
106
122
 
107
123
  export namespace LocalStorageSession {