@assistant-ui/react-statewire 0.30.0 → 0.32.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.
Files changed (41) hide show
  1. package/README.md +7 -5
  2. package/dist/StatewireThread.d.ts +341 -343
  3. package/dist/StatewireThread.d.ts.map +1 -1
  4. package/dist/StatewireThread.js +82 -41
  5. package/dist/StatewireThread.js.map +1 -1
  6. package/dist/hooks.d.ts +7 -9
  7. package/dist/hooks.d.ts.map +1 -1
  8. package/dist/hooks.js +1 -2
  9. package/dist/hooks.js.map +1 -1
  10. package/dist/index.d.ts +4 -4
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/inputRequests.d.ts +9 -12
  13. package/dist/inputRequests.d.ts.map +1 -1
  14. package/dist/inputRequests.js +1 -2
  15. package/dist/localStorage.d.ts +29 -32
  16. package/dist/localStorage.d.ts.map +1 -1
  17. package/dist/localStorage.js +54 -21
  18. package/dist/localStorage.js.map +1 -1
  19. package/dist/runCommands.d.ts +34 -34
  20. package/dist/runCommands.d.ts.map +1 -1
  21. package/dist/runCommands.js +10 -4
  22. package/dist/runCommands.js.map +1 -1
  23. package/dist/runsMaterialize.d.ts +2 -5
  24. package/dist/runsMaterialize.d.ts.map +1 -1
  25. package/dist/runsMaterialize.js +1 -2
  26. package/dist/runsOptimistic.d.ts +2 -5
  27. package/dist/runsOptimistic.d.ts.map +1 -1
  28. package/dist/runsOptimistic.js +2 -3
  29. package/dist/runsOptimistic.js.map +1 -1
  30. package/package.json +16 -14
  31. package/src/StatewireThread.drafts.test.tsx +6 -2
  32. package/src/StatewireThread.failed.test.tsx +1 -1
  33. package/src/StatewireThread.runs.test.tsx +1 -1
  34. package/src/StatewireThread.test.tsx +127 -0
  35. package/src/StatewireThread.ts +63 -18
  36. package/src/localStorage.test.ts +108 -29
  37. package/src/localStorage.ts +62 -20
  38. package/src/runCommands.test.ts +44 -1
  39. package/src/runCommands.ts +13 -3
  40. package/src/runsOptimistic.test.ts +1 -1
  41. package/src/runsOptimistic.ts +1 -1
@@ -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
 
@@ -147,7 +186,10 @@ describe("LocalStorageSession", () => {
147
186
  callback?: () => Promise<unknown>,
148
187
  ) => {
149
188
  const cb = typeof options === "function" ? options : callback!;
150
- if (name.startsWith("aui:statewire-session-active:"))
189
+ if (
190
+ name.startsWith("aui:statewire-session-active:") ||
191
+ name.startsWith("statewire-tab:")
192
+ )
151
193
  return Promise.resolve().then(() => cb());
152
194
  requested.push(name);
153
195
  const run = chain.then(() => cb());
@@ -169,7 +211,7 @@ describe("LocalStorageSession", () => {
169
211
  });
170
212
 
171
213
  it("round-trips the record with its un-durable commands", () => {
172
- const root = mountSession({ threadId: "t1" });
214
+ const root = mountSession({ threadId: "t1", principal: "u1" });
173
215
  expect(root.getValue().load()).toBeNull();
174
216
 
175
217
  const record = {
@@ -179,6 +221,8 @@ describe("LocalStorageSession", () => {
179
221
  nextSeq: 3,
180
222
  commands: [
181
223
  {
224
+ id: "cmd-2",
225
+ ts: 1,
182
226
  seq: 2,
183
227
  method: "run/steer",
184
228
  params: [{ text: "hi" }],
@@ -191,7 +235,7 @@ describe("LocalStorageSession", () => {
191
235
  root.getValue().save(record);
192
236
  expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
193
237
  ...record,
194
- statewireStorageVersion: 3,
238
+ statewireStorageVersion: 4,
195
239
  savedAt: expect.any(Number),
196
240
  });
197
241
  expect(root.getValue().load()).toEqual(record);
@@ -199,7 +243,7 @@ describe("LocalStorageSession", () => {
199
243
  });
200
244
 
201
245
  it("rejects malformed session records without deleting them", () => {
202
- const root = mountSession({ threadId: "t1" });
246
+ const root = mountSession({ threadId: "t1", principal: "u1" });
203
247
  for (const raw of [
204
248
  "{",
205
249
  JSON.stringify({
@@ -240,16 +284,50 @@ describe("LocalStorageSession", () => {
240
284
  root.unmount();
241
285
  });
242
286
 
243
- it("derives the storage key through the key callback", () => {
244
- const root = mountSession({ threadId: "t1", key: (id) => `user-42:${id}` });
287
+ it("scopes the key and lock per principal; another principal loads nothing", async () => {
288
+ const root = mountSession({ threadId: "t/1", principal: "u:2" });
245
289
  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();
290
+ await root.getValue().lock!(async () => {});
291
+ expect(
292
+ localStorage.getItem("aui:statewire-session:u%3A2:t%2F1"),
293
+ ).not.toBeNull();
294
+ expect(requested).toEqual(["aui:statewire-session-lock:u%3A2:t%2F1"]);
295
+ root.unmount();
296
+ const other = mountSession({ threadId: "t/1", principal: "u:3" });
297
+ expect(other.getValue().load()).toBeNull();
298
+ other.unmount();
299
+ });
300
+
301
+ it("throws on an empty principal", () => {
302
+ expect(() => mountSession({ threadId: "t1", principal: "" })).toThrow(
303
+ /non-empty principal/,
304
+ );
305
+ });
306
+
307
+ it("requires remounting a session when the principal changes", () => {
308
+ let switchPrincipal!: (principal: string) => void;
309
+ const root = createTapRoot(() => {
310
+ const [principal, setPrincipal] = useState("u1");
311
+ switchPrincipal = setPrincipal;
312
+ return useResource(LocalStorageSession({ threadId: "t1", principal }));
313
+ });
314
+ root.getValue().save({ clientId: "c-u1", lanes: {} });
315
+ expect(() => flushTapSync(() => switchPrincipal("u2"))).toThrow(
316
+ /principal changed/,
317
+ );
318
+ expect(localStorage.getItem("aui:statewire-session:u2:t1")).toBeNull();
248
319
  root.unmount();
320
+ const other = mountSession({ threadId: "t1", principal: "u2" });
321
+ expect(other.getValue().load()).toBeNull();
322
+ other.getValue().save({ clientId: "c-u2", lanes: {} });
323
+ other.unmount();
324
+ const original = mountSession({ threadId: "t1", principal: "u1" });
325
+ expect(original.getValue().load()?.clientId).toBe("c-u1");
326
+ original.unmount();
249
327
  });
250
328
 
251
329
  it("serializes lock sections on a per-key Web Lock", async () => {
252
- const root = mountSession({ threadId: "t1" });
330
+ const root = mountSession({ threadId: "t1", principal: "u1" });
253
331
  const order: string[] = [];
254
332
  let release!: () => void;
255
333
  const held = new Promise<void>((r) => {
@@ -274,7 +352,7 @@ describe("LocalStorageSession", () => {
274
352
  });
275
353
 
276
354
  it("notifies subscribers on storage events for the session key only", () => {
277
- const root = mountSession({ threadId: "t1" });
355
+ const root = mountSession({ threadId: "t1", principal: "u1" });
278
356
  const seen: number[] = [];
279
357
  const unsubscribe = root.getValue().subscribe!(() => seen.push(1));
280
358
 
@@ -326,6 +404,7 @@ describe("LocalStorageSession", () => {
326
404
  });
327
405
  const root = mountSession({
328
406
  threadId: "current",
407
+ principal: "u1",
329
408
  retention: { maxAgeMs: 1 },
330
409
  });
331
410
  await vi.waitFor(() =>
@@ -346,14 +425,14 @@ describe("LocalStorageSession", () => {
346
425
 
347
426
  it("throws without localStorage", () => {
348
427
  vi.stubGlobal("localStorage", undefined);
349
- expect(() => mountSession({ threadId: "t1" })).toThrow(
428
+ expect(() => mountSession({ threadId: "t1", principal: "u1" })).toThrow(
350
429
  /requires localStorage/,
351
430
  );
352
431
  });
353
432
 
354
433
  it("throws without the Web Locks API", () => {
355
434
  delete (navigator as { locks?: unknown }).locks;
356
- expect(() => mountSession({ threadId: "t1" })).toThrow(
435
+ expect(() => mountSession({ threadId: "t1", principal: "u1" })).toThrow(
357
436
  /requires the Web Locks API/,
358
437
  );
359
438
  });
@@ -1,4 +1,4 @@
1
- import { useEffect, useMemo } from "react";
1
+ import { useEffect, useMemo, useRef, useState } 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
  );
@@ -161,6 +180,8 @@ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
161
180
 
162
181
  const SESSION_ACTIVE_PREFIX = "aui:statewire-session-active:";
163
182
 
183
+ const TAB_LOCK_PREFIX = "statewire-tab:";
184
+
164
185
  const sessionBackend: KeyValueSessionStorage.Backend = {
165
186
  getItem: (key) => localStorage.getItem(key),
166
187
  setItem: (key, value) => localStorage.setItem(key, value),
@@ -187,7 +208,7 @@ const sessionBackend: KeyValueSessionStorage.Backend = {
187
208
  const useLocalStorageSession = ({
188
209
  threadId,
189
210
  migrate,
190
- key = (id) => id,
211
+ principal,
191
212
  protocol,
192
213
  retention,
193
214
  onError,
@@ -198,8 +219,24 @@ const useLocalStorageSession = ({
198
219
  throw new Error(
199
220
  "statewire: LocalStorageSession requires the Web Locks API (navigator.locks)",
200
221
  );
201
- const storageKey = SESSION_PREFIX + key(threadId);
202
- const lockName = SESSION_LOCK_PREFIX + key(threadId);
222
+ const scopeKey = scopedKey("", principal, threadId);
223
+ const namespace = scopePrefix(SESSION_PREFIX, principal);
224
+ usePrincipal(principal);
225
+ const storageKey = SESSION_PREFIX + scopeKey;
226
+ const lockName = SESSION_LOCK_PREFIX + scopeKey;
227
+ const [tabId] = useState(() => crypto.randomUUID());
228
+ const latestOnError = useRef(onError);
229
+ latestOnError.current = onError;
230
+ useEffect(() => {
231
+ let release: (() => void) | undefined;
232
+ const held = new Promise<void>((resolve) => {
233
+ release = resolve;
234
+ });
235
+ void navigator.locks
236
+ .request(TAB_LOCK_PREFIX + tabId, () => held)
237
+ .catch((error: unknown) => latestOnError.current?.(error));
238
+ return () => release?.();
239
+ }, [tabId]);
203
240
  useEffect(() => {
204
241
  let release: (() => void) | undefined;
205
242
  let disposed = false;
@@ -219,8 +256,8 @@ const useLocalStorageSession = ({
219
256
  const storage = useResource(
220
257
  KeyValueSessionStorage({
221
258
  backend: sessionBackend,
222
- key: key(threadId),
223
- namespace: SESSION_PREFIX,
259
+ key: encodeURIComponent(threadId),
260
+ namespace,
224
261
  ...(migrate === undefined ? {} : { migrate }),
225
262
  ...(protocol === undefined ? {} : { protocol }),
226
263
  ...(retention === undefined ? {} : { retention }),
@@ -231,6 +268,11 @@ const useLocalStorageSession = ({
231
268
  (): StatewireClient.SessionStorage => ({
232
269
  ...storage,
233
270
  lock: (fn) => navigator.locks.request(lockName, async () => fn()),
271
+ owner: {
272
+ id: tabId,
273
+ whenGone: (id, signal) =>
274
+ navigator.locks.request(TAB_LOCK_PREFIX + id, { signal }, () => {}),
275
+ },
234
276
  subscribe: (listener) => {
235
277
  const onStorage = (event: StorageEvent) => {
236
278
  if (event.key === storageKey) listener();
@@ -239,11 +281,11 @@ const useLocalStorageSession = ({
239
281
  return () => window.removeEventListener("storage", onStorage);
240
282
  },
241
283
  }),
242
- [storage, storageKey, lockName],
284
+ [storage, storageKey, lockName, tabId],
243
285
  );
244
286
  };
245
287
 
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. */
288
+ /** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
247
289
  export const LocalStorageSession = resource(useLocalStorageSession);
248
290
 
249
291
  export namespace LocalStorageSession {
@@ -255,8 +297,8 @@ export namespace LocalStorageSession {
255
297
  migrate?: StatewireClient.SessionStorage["migrate"];
256
298
  /** The thread whose session this storage holds. */
257
299
  threadId: string;
258
- /** Derives the storage key from the thread id; defaults to the id itself. */
259
- key?: ((threadId: string) => string) | undefined;
300
+ /** The account whose commands this storage holds. */
301
+ principal: string;
260
302
  };
261
303
  }
262
304
 
@@ -264,11 +306,11 @@ export namespace LocalStorageComposerDrafts {
264
306
  export type Options = {
265
307
  /** The thread whose draft this storage holds. */
266
308
  threadId: string;
267
- /** Derives the storage key from the thread id; defaults to the id itself. */
268
- key?: ((threadId: string) => string) | undefined;
309
+ /** The account whose draft this storage holds. */
310
+ principal: string;
269
311
  /** Draft lifetime in milliseconds, enforced by the mount sweep. Default 7 days. */
270
312
  ttl?: number | undefined;
271
- /** Newest drafts kept across all keys, enforced by the mount sweep. Default 50. */
313
+ /** Newest drafts kept across the principal's threads, enforced by the mount sweep. Default 50. */
272
314
  max?: number | undefined;
273
315
  };
274
316
  }
@@ -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 }
@@ -6,7 +6,7 @@ import { runsOptimistic } from "./runsOptimistic";
6
6
 
7
7
  type Draft = Record<string, any>;
8
8
 
9
- const ctx = { ts: 0, seq: 7 };
9
+ const ctx = { ts: 0, seq: 7, held: null };
10
10
 
11
11
  const mount = (entry?: Draft): Draft =>
12
12
  entry === undefined
@@ -147,7 +147,7 @@ export const runsOptimistic = (
147
147
  const draft = mount as RunsDraft;
148
148
  const commandRunId = (command.params[0] as { runId?: string } | undefined)
149
149
  ?.runId;
150
- const runId = commandRunId ?? `optimistic-${ctx.seq}`;
150
+ const runId = commandRunId ?? `optimistic-${ctx.seq ?? `q${ctx.ts}`}`;
151
151
  switch (command.method) {
152
152
  case "run/enqueue":
153
153
  case "run/steer": {