@assistant-ui/react-statewire 0.29.1 → 0.31.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.
@@ -4,15 +4,16 @@
4
4
  // empty-draft removal, and the mount sweep (ttl + max).
5
5
 
6
6
  import { beforeEach, describe, expect, it, vi } from "vitest";
7
- import { createTapRoot, useResource } from "@assistant-ui/tap";
7
+ import { useState } from "react";
8
+ import { createTapRoot, flushTapSync, useResource } from "@assistant-ui/tap";
8
9
  import {
9
10
  LocalStorageComposerDrafts,
10
11
  LocalStorageSession,
11
12
  } from "./localStorage";
12
13
 
13
- const PREFIX = "aui:composer-draft:";
14
- const SESSION_PREFIX = "aui:statewire-session:";
15
- const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
14
+ const PREFIX = "aui:composer-draft:u1:";
15
+ const SESSION_PREFIX = "aui:statewire-session:u1:";
16
+ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:u1:";
16
17
 
17
18
  const mount = (options: LocalStorageComposerDrafts.Options) =>
18
19
  createTapRoot(() => useResource(LocalStorageComposerDrafts(options)));
@@ -30,7 +31,7 @@ describe("LocalStorageComposerDrafts", () => {
30
31
  });
31
32
 
32
33
  it("round-trips a draft through a timestamped record", () => {
33
- const root = mount({ threadId: "t1" });
34
+ const root = mount({ threadId: "t1", principal: "u1" });
34
35
  root.getValue().write({ text: "hello", attachments: [] });
35
36
 
36
37
  const record = JSON.parse(localStorage.getItem(`${PREFIX}t1`)!);
@@ -43,16 +44,47 @@ describe("LocalStorageComposerDrafts", () => {
43
44
  root.unmount();
44
45
  });
45
46
 
46
- it("derives the storage key through the key callback", () => {
47
- const root = mount({ threadId: "t1", key: (id) => `user-42:${id}` });
47
+ it("scopes the key per principal, encoding both components", () => {
48
+ const root = mount({ threadId: "t/1", principal: "u:2" });
48
49
  root.getValue().write({ text: "hello", attachments: [] });
49
- expect(localStorage.getItem(`${PREFIX}user-42:t1`)).not.toBeNull();
50
- expect(localStorage.getItem(`${PREFIX}t1`)).toBeNull();
50
+ expect(
51
+ localStorage.getItem("aui:composer-draft:u%3A2:t%2F1"),
52
+ ).not.toBeNull();
53
+ root.unmount();
54
+
55
+ const other = mount({ threadId: "t/1", principal: "u:3" });
56
+ expect(other.getValue().read()).toBeUndefined();
57
+ other.unmount();
58
+ });
59
+
60
+ it("requires remounting drafts when the principal changes", () => {
61
+ let switchPrincipal!: (principal: string) => void;
62
+ const root = createTapRoot(() => {
63
+ const [principal, setPrincipal] = useState("u1");
64
+ switchPrincipal = setPrincipal;
65
+ return useResource(
66
+ LocalStorageComposerDrafts({ threadId: "t1", principal }),
67
+ );
68
+ });
69
+ root.getValue().write({ text: "account A", attachments: [] });
70
+ expect(() => flushTapSync(() => switchPrincipal("u2"))).toThrow(
71
+ /principal changed/,
72
+ );
73
+ expect(localStorage.getItem("aui:composer-draft:u2:t1")).toBeNull();
51
74
  root.unmount();
75
+ const other = mount({ threadId: "t1", principal: "u2" });
76
+ expect(other.getValue().read()).toBeUndefined();
77
+ other.unmount();
78
+ });
79
+
80
+ it("throws on an empty principal", () => {
81
+ expect(() => mount({ threadId: "t1", principal: "" })).toThrow(
82
+ /non-empty principal/,
83
+ );
52
84
  });
53
85
 
54
86
  it("reads undefined without a stored draft and removes the record on clear", () => {
55
- const root = mount({ threadId: "t1" });
87
+ const root = mount({ threadId: "t1", principal: "u1" });
56
88
  expect(root.getValue().read()).toBeUndefined();
57
89
 
58
90
  root.getValue().write({ text: "hello", attachments: [] });
@@ -63,22 +95,27 @@ describe("LocalStorageComposerDrafts", () => {
63
95
  });
64
96
 
65
97
  it("removes the record on an empty write instead of storing it", () => {
66
- const root = mount({ threadId: "t1" });
98
+ const root = mount({ threadId: "t1", principal: "u1" });
67
99
  root.getValue().write({ text: "hello", attachments: [] });
68
100
  root.getValue().write({ text: "", attachments: [] });
69
101
  expect(localStorage.getItem(`${PREFIX}t1`)).toBeNull();
70
102
  root.unmount();
71
103
  });
72
104
 
73
- it("sweeps drafts older than ttl on mount, leaving foreign keys alone", () => {
105
+ it("sweeps drafts older than ttl on mount, leaving other principals and foreign keys alone", () => {
74
106
  const now = Date.now();
75
107
  seed("old", now - 100_000);
76
108
  seed("live", now - 1_000);
109
+ localStorage.setItem(
110
+ "aui:composer-draft:u2:old",
111
+ JSON.stringify({ text: "x", attachments: [], ts: now - 100_000 }),
112
+ );
77
113
  localStorage.setItem("unrelated", "kept");
78
114
 
79
- const root = mount({ threadId: "t1", ttl: 10_000 });
115
+ const root = mount({ threadId: "t1", principal: "u1", ttl: 10_000 });
80
116
  expect(localStorage.getItem(`${PREFIX}old`)).toBeNull();
81
117
  expect(localStorage.getItem(`${PREFIX}live`)).not.toBeNull();
118
+ expect(localStorage.getItem("aui:composer-draft:u2:old")).not.toBeNull();
82
119
  expect(localStorage.getItem("unrelated")).toBe("kept");
83
120
  root.unmount();
84
121
  });
@@ -89,7 +126,7 @@ describe("LocalStorageComposerDrafts", () => {
89
126
  seed("b", now - 2_000);
90
127
  seed("c", now - 1_000);
91
128
 
92
- const root = mount({ threadId: "t1", max: 2 });
129
+ const root = mount({ threadId: "t1", principal: "u1", max: 2 });
93
130
  expect(localStorage.getItem(`${PREFIX}a`)).toBeNull();
94
131
  expect(localStorage.getItem(`${PREFIX}b`)).not.toBeNull();
95
132
  expect(localStorage.getItem(`${PREFIX}c`)).not.toBeNull();
@@ -108,7 +145,7 @@ describe("LocalStorageComposerDrafts", () => {
108
145
  );
109
146
  seed("live", Date.now());
110
147
 
111
- const root = mount({ threadId: "t1" });
148
+ const root = mount({ threadId: "t1", principal: "u1" });
112
149
  expect(localStorage.getItem(`${PREFIX}broken-json`)).toBeNull();
113
150
  expect(localStorage.getItem(`${PREFIX}broken-shape`)).toBeNull();
114
151
  expect(localStorage.getItem(`${PREFIX}broken-attachment`)).toBeNull();
@@ -117,7 +154,7 @@ describe("LocalStorageComposerDrafts", () => {
117
154
  });
118
155
 
119
156
  it("discards a malformed draft encountered during read", () => {
120
- const root = mount({ threadId: "t1" });
157
+ const root = mount({ threadId: "t1", principal: "u1" });
121
158
  localStorage.setItem(`${PREFIX}t1`, "null");
122
159
 
123
160
  expect(root.getValue().read()).toBeUndefined();
@@ -127,7 +164,9 @@ describe("LocalStorageComposerDrafts", () => {
127
164
 
128
165
  it("throws without localStorage", () => {
129
166
  vi.stubGlobal("localStorage", undefined);
130
- expect(() => mount({ threadId: "t1" })).toThrow(/requires localStorage/);
167
+ expect(() => mount({ threadId: "t1", principal: "u1" })).toThrow(
168
+ /requires localStorage/,
169
+ );
131
170
  });
132
171
  });
133
172
 
@@ -169,7 +208,7 @@ describe("LocalStorageSession", () => {
169
208
  });
170
209
 
171
210
  it("round-trips the record with its un-durable commands", () => {
172
- const root = mountSession({ threadId: "t1" });
211
+ const root = mountSession({ threadId: "t1", principal: "u1" });
173
212
  expect(root.getValue().load()).toBeNull();
174
213
 
175
214
  const record = {
@@ -199,7 +238,7 @@ describe("LocalStorageSession", () => {
199
238
  });
200
239
 
201
240
  it("rejects malformed session records without deleting them", () => {
202
- const root = mountSession({ threadId: "t1" });
241
+ const root = mountSession({ threadId: "t1", principal: "u1" });
203
242
  for (const raw of [
204
243
  "{",
205
244
  JSON.stringify({
@@ -240,16 +279,50 @@ describe("LocalStorageSession", () => {
240
279
  root.unmount();
241
280
  });
242
281
 
243
- it("derives the storage key through the key callback", () => {
244
- const root = mountSession({ threadId: "t1", key: (id) => `user-42:${id}` });
282
+ it("scopes the key and lock per principal; another principal loads nothing", async () => {
283
+ const root = mountSession({ threadId: "t/1", principal: "u:2" });
245
284
  root.getValue().save({ clientId: "c-1", lanes: {} });
246
- expect(localStorage.getItem(`${SESSION_PREFIX}user-42:t1`)).not.toBeNull();
247
- expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBeNull();
285
+ await root.getValue().lock!(async () => {});
286
+ expect(
287
+ localStorage.getItem("aui:statewire-session:u%3A2:t%2F1"),
288
+ ).not.toBeNull();
289
+ expect(requested).toEqual(["aui:statewire-session-lock:u%3A2:t%2F1"]);
290
+ root.unmount();
291
+ const other = mountSession({ threadId: "t/1", principal: "u:3" });
292
+ expect(other.getValue().load()).toBeNull();
293
+ other.unmount();
294
+ });
295
+
296
+ it("throws on an empty principal", () => {
297
+ expect(() => mountSession({ threadId: "t1", principal: "" })).toThrow(
298
+ /non-empty principal/,
299
+ );
300
+ });
301
+
302
+ it("requires remounting a session when the principal changes", () => {
303
+ let switchPrincipal!: (principal: string) => void;
304
+ const root = createTapRoot(() => {
305
+ const [principal, setPrincipal] = useState("u1");
306
+ switchPrincipal = setPrincipal;
307
+ return useResource(LocalStorageSession({ threadId: "t1", principal }));
308
+ });
309
+ root.getValue().save({ clientId: "c-u1", lanes: {} });
310
+ expect(() => flushTapSync(() => switchPrincipal("u2"))).toThrow(
311
+ /principal changed/,
312
+ );
313
+ expect(localStorage.getItem("aui:statewire-session:u2:t1")).toBeNull();
248
314
  root.unmount();
315
+ const other = mountSession({ threadId: "t1", principal: "u2" });
316
+ expect(other.getValue().load()).toBeNull();
317
+ other.getValue().save({ clientId: "c-u2", lanes: {} });
318
+ other.unmount();
319
+ const original = mountSession({ threadId: "t1", principal: "u1" });
320
+ expect(original.getValue().load()?.clientId).toBe("c-u1");
321
+ original.unmount();
249
322
  });
250
323
 
251
324
  it("serializes lock sections on a per-key Web Lock", async () => {
252
- const root = mountSession({ threadId: "t1" });
325
+ const root = mountSession({ threadId: "t1", principal: "u1" });
253
326
  const order: string[] = [];
254
327
  let release!: () => void;
255
328
  const held = new Promise<void>((r) => {
@@ -274,7 +347,7 @@ describe("LocalStorageSession", () => {
274
347
  });
275
348
 
276
349
  it("notifies subscribers on storage events for the session key only", () => {
277
- const root = mountSession({ threadId: "t1" });
350
+ const root = mountSession({ threadId: "t1", principal: "u1" });
278
351
  const seen: number[] = [];
279
352
  const unsubscribe = root.getValue().subscribe!(() => seen.push(1));
280
353
 
@@ -326,6 +399,7 @@ describe("LocalStorageSession", () => {
326
399
  });
327
400
  const root = mountSession({
328
401
  threadId: "current",
402
+ principal: "u1",
329
403
  retention: { maxAgeMs: 1 },
330
404
  });
331
405
  await vi.waitFor(() =>
@@ -346,14 +420,14 @@ describe("LocalStorageSession", () => {
346
420
 
347
421
  it("throws without localStorage", () => {
348
422
  vi.stubGlobal("localStorage", undefined);
349
- expect(() => mountSession({ threadId: "t1" })).toThrow(
423
+ expect(() => mountSession({ threadId: "t1", principal: "u1" })).toThrow(
350
424
  /requires localStorage/,
351
425
  );
352
426
  });
353
427
 
354
428
  it("throws without the Web Locks API", () => {
355
429
  delete (navigator as { locks?: unknown }).locks;
356
- expect(() => mountSession({ threadId: "t1" })).toThrow(
430
+ expect(() => mountSession({ threadId: "t1", principal: "u1" })).toThrow(
357
431
  /requires the Web Locks API/,
358
432
  );
359
433
  });
@@ -1,4 +1,4 @@
1
- import { useEffect, useMemo } from "react";
1
+ import { useEffect, useMemo, useRef } from "react";
2
2
  import { resource, useResource } from "@assistant-ui/tap";
3
3
  import { KeyValueSessionStorage } from "statewire/storage";
4
4
  import type { StatewireClient } from "statewire";
@@ -8,6 +8,23 @@ const PREFIX = "aui:composer-draft:";
8
8
  const SESSION_PREFIX = "aui:statewire-session:";
9
9
  const DAY = 86_400_000;
10
10
 
11
+ const scopePrefix = (prefix: string, principal: string) => {
12
+ if (typeof principal !== "string" || principal === "")
13
+ throw new Error("statewire: storage requires a non-empty principal");
14
+ return `${prefix}${encodeURIComponent(principal)}:`;
15
+ };
16
+
17
+ const scopedKey = (prefix: string, principal: string, threadId: string) =>
18
+ `${scopePrefix(prefix, principal)}${encodeURIComponent(threadId)}`;
19
+
20
+ const usePrincipal = (principal: string) => {
21
+ const initial = useRef(principal);
22
+ if (initial.current !== principal)
23
+ throw new Error(
24
+ "statewire: principal changed; remount the account's thread/session",
25
+ );
26
+ };
27
+
11
28
  type StoredDraft = {
12
29
  text: string;
13
30
  attachments: StatewireThread.ComposerDraft["attachments"];
@@ -91,13 +108,13 @@ const loadStored = <T>(
91
108
  return null;
92
109
  };
93
110
 
94
- const sweep = (ttl: number, max: number) => {
111
+ const sweep = (scope: string, ttl: number, max: number) => {
95
112
  const entries: { key: string; ts: number }[] = [];
96
113
  const keys = Array.from({ length: localStorage.length }, (_, index) =>
97
114
  localStorage.key(index),
98
115
  );
99
116
  for (const key of keys) {
100
- if (key === null || !key.startsWith(PREFIX)) continue;
117
+ if (key === null || !key.startsWith(scope)) continue;
101
118
  const stored = loadStored(key, isStoredDraft);
102
119
  if (stored !== null) entries.push({ key, ts: stored.ts });
103
120
  }
@@ -113,7 +130,7 @@ const sweep = (ttl: number, max: number) => {
113
130
 
114
131
  const useLocalStorageComposerDrafts = ({
115
132
  threadId,
116
- key = (id) => id,
133
+ principal,
117
134
  ttl = 7 * DAY,
118
135
  max = 50,
119
136
  }: LocalStorageComposerDrafts.Options): StatewireThread.ComposerStorage => {
@@ -122,11 +139,13 @@ const useLocalStorageComposerDrafts = ({
122
139
  "statewire: LocalStorageComposerDrafts requires localStorage",
123
140
  );
124
141
 
142
+ const scope = scopePrefix(PREFIX, principal);
143
+ usePrincipal(principal);
125
144
  useEffect(() => {
126
- sweep(ttl, max);
127
- }, [ttl, max]);
145
+ sweep(scope, ttl, max);
146
+ }, [scope, ttl, max]);
128
147
 
129
- const storageKey = PREFIX + key(threadId);
148
+ const storageKey = scopedKey(PREFIX, principal, threadId);
130
149
  return useMemo(
131
150
  (): StatewireThread.ComposerStorage => ({
132
151
  read: () => {
@@ -152,7 +171,7 @@ const useLocalStorageComposerDrafts = ({
152
171
  );
153
172
  };
154
173
 
155
- /** Composer draft storage on localStorage, keyed per thread; stale drafts are swept on mount. */
174
+ /** Composer draft storage on localStorage, keyed per principal and thread; stale drafts are swept on mount. */
156
175
  export const LocalStorageComposerDrafts = resource(
157
176
  useLocalStorageComposerDrafts,
158
177
  );
@@ -187,7 +206,7 @@ const sessionBackend: KeyValueSessionStorage.Backend = {
187
206
  const useLocalStorageSession = ({
188
207
  threadId,
189
208
  migrate,
190
- key = (id) => id,
209
+ principal,
191
210
  protocol,
192
211
  retention,
193
212
  onError,
@@ -198,8 +217,11 @@ const useLocalStorageSession = ({
198
217
  throw new Error(
199
218
  "statewire: LocalStorageSession requires the Web Locks API (navigator.locks)",
200
219
  );
201
- const storageKey = SESSION_PREFIX + key(threadId);
202
- const lockName = SESSION_LOCK_PREFIX + key(threadId);
220
+ const scopeKey = scopedKey("", principal, threadId);
221
+ const namespace = scopePrefix(SESSION_PREFIX, principal);
222
+ usePrincipal(principal);
223
+ const storageKey = SESSION_PREFIX + scopeKey;
224
+ const lockName = SESSION_LOCK_PREFIX + scopeKey;
203
225
  useEffect(() => {
204
226
  let release: (() => void) | undefined;
205
227
  let disposed = false;
@@ -219,8 +241,8 @@ const useLocalStorageSession = ({
219
241
  const storage = useResource(
220
242
  KeyValueSessionStorage({
221
243
  backend: sessionBackend,
222
- key: key(threadId),
223
- namespace: SESSION_PREFIX,
244
+ key: encodeURIComponent(threadId),
245
+ namespace,
224
246
  ...(migrate === undefined ? {} : { migrate }),
225
247
  ...(protocol === undefined ? {} : { protocol }),
226
248
  ...(retention === undefined ? {} : { retention }),
@@ -243,7 +265,7 @@ const useLocalStorageSession = ({
243
265
  );
244
266
  };
245
267
 
246
- /** 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. */
268
+ /** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
247
269
  export const LocalStorageSession = resource(useLocalStorageSession);
248
270
 
249
271
  export namespace LocalStorageSession {
@@ -255,8 +277,8 @@ export namespace LocalStorageSession {
255
277
  migrate?: StatewireClient.SessionStorage["migrate"];
256
278
  /** The thread whose session this storage holds. */
257
279
  threadId: string;
258
- /** Derives the storage key from the thread id; defaults to the id itself. */
259
- key?: ((threadId: string) => string) | undefined;
280
+ /** The account whose commands this storage holds. */
281
+ principal: string;
260
282
  };
261
283
  }
262
284
 
@@ -264,11 +286,11 @@ export namespace LocalStorageComposerDrafts {
264
286
  export type Options = {
265
287
  /** The thread whose draft this storage holds. */
266
288
  threadId: string;
267
- /** Derives the storage key from the thread id; defaults to the id itself. */
268
- key?: ((threadId: string) => string) | undefined;
289
+ /** The account whose draft this storage holds. */
290
+ principal: string;
269
291
  /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */
270
292
  ttl?: number | undefined;
271
- /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */
293
+ /** Newest drafts kept across the principal's threads, enforced by the mount sweep. Default 50. */
272
294
  max?: number | undefined;
273
295
  };
274
296
  }
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import type { AppendMessage } from "@assistant-ui/core";
3
- import { toWireMessage } from "./runCommands";
3
+ import { createRunQueueAdapter, toWireMessage } from "./runCommands";
4
+ import type { StatewireThread } from "./StatewireThread";
4
5
 
5
6
  const append = (metadata?: AppendMessage["metadata"]): AppendMessage =>
6
7
  ({
@@ -29,3 +30,45 @@ describe("toWireMessage", () => {
29
30
  });
30
31
  });
31
32
  });
33
+
34
+ describe("createRunQueueAdapter", () => {
35
+ it("keeps the original item's metadata when editing a queue or steer item", () => {
36
+ const parts = [{ type: "text" as const, text: "old" }];
37
+ const queued = { id: "q1", parts, metadata: { source: { tab: 1 } } };
38
+ const steered = { id: "s1", parts, metadata: { source: "panel" } };
39
+ const sent: StatewireThread.RunCommand[] = [];
40
+ const queue = createRunQueueAdapter(
41
+ () => ({ messages: [], runId: "run-1" }),
42
+ [queued],
43
+ [steered],
44
+ (command) => sent.push(command),
45
+ () => {},
46
+ );
47
+
48
+ queue.edit("q1", append({ custom: { source: "composer" } }));
49
+ queue.edit("s1", append());
50
+
51
+ const message = (id: string, metadata: Record<string, unknown>) => ({
52
+ id,
53
+ role: "user",
54
+ parts: [{ type: "text", text: "hi" }],
55
+ metadata,
56
+ });
57
+ expect(sent).toEqual([
58
+ {
59
+ type: "run/enqueue",
60
+ runId: "run-1",
61
+ message: message("q1", { source: { tab: 1 } }),
62
+ },
63
+ {
64
+ type: "run/steer",
65
+ runId: "run-1",
66
+ message: message("s1", { source: "panel" }),
67
+ },
68
+ ]);
69
+ const edited = sent[0] as StatewireThread.RunEnqueueCommand & {
70
+ message: StatewireThread.UserMessage;
71
+ };
72
+ expect(edited.message.metadata!["source"]).not.toBe(queued.metadata.source);
73
+ });
74
+ });
@@ -161,8 +161,7 @@ export const retryCommand = (
161
161
  };
162
162
 
163
163
  export const createRunQueueAdapter = (
164
- messages: readonly { id: string }[],
165
- runId: string | null,
164
+ live: () => { messages: readonly { id: string }[]; runId: string | null },
166
165
  queueItems: readonly StatewireThread.RunQueueItem[],
167
166
  steerQueueItems: readonly StatewireThread.RunQueueItem[],
168
167
  dispatch: (command: StatewireThread.RunCommand) => void,
@@ -172,6 +171,7 @@ export const createRunQueueAdapter = (
172
171
  ) => void,
173
172
  ): ExternalThreadQueueAdapter => {
174
173
  const liveRunId = (): string => {
174
+ const { runId } = live();
175
175
  if (runId === null) throw new Error("statewire: no live run to target");
176
176
  return runId;
177
177
  };
@@ -185,6 +185,7 @@ export const createRunQueueAdapter = (
185
185
  lane: "queue" | "steer",
186
186
  message: AppendMessage,
187
187
  ): StatewireThread.RunCommand => {
188
+ const { messages, runId } = live();
188
189
  if (message.sourceId != null)
189
190
  return resolveEditCommand(messages, message, runId);
190
191
  const fields = sendFields(
@@ -215,7 +216,16 @@ export const createRunQueueAdapter = (
215
216
  );
216
217
  },
217
218
  edit: (queueItemId, message) => {
218
- const wireMessage = toWireMessage(message, queueItemId);
219
+ const { metadata, ...edited } = toWireMessage(message, queueItemId);
220
+ const original = [...queueItems, ...steerQueueItems].find(
221
+ (item) => item.id === queueItemId,
222
+ );
223
+ const wireMessage = {
224
+ ...edited,
225
+ ...(original?.metadata !== undefined && {
226
+ metadata: JSON.parse(JSON.stringify(original.metadata)),
227
+ }),
228
+ };
219
229
  dispatch(
220
230
  laneOf(queueItemId) === "steer"
221
231
  ? { type: "run/steer", runId: liveRunId(), message: wireMessage }