@dudko.dev/agent-web-react 0.0.40 → 0.0.42

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.
package/README.md CHANGED
@@ -853,7 +853,7 @@ use them standalone. The full guide: [docs/chat.md](docs/chat.md).
853
853
  | Component | Purpose |
854
854
  | --- | --- |
855
855
  | `<AgentChat>` | Full panel: transcript with per-answer activity + composer + optional history and files panels. Reads a `controller` prop or the `<AgentProvider>` context. Says when the conversation runs in another tab of the site, waits for an answer there, or waits for it (`showOtherTabs`). |
856
- | `<AgentComposer>` | The input and its toolbar: attachments, commands, timer, agents, model/thinking, consent, mic, send/stop. The model menu takes `section` per option (a heading over each run of options, e.g. one per provider); both chip menus work from the keyboard (arrows, Home / End, Escape) - see [docs/chat.md](docs/chat.md#the-model-menu-sections-and-keys). `attachments` takes `{ accept, maxBytes, imageMaxDimension, imageMaxPixels, maxSourceBytes, imageMaxSourcePixels, maxImages, maxTotalBytes }`: `maxBytes` (20 MB) is checked on what is sent, so a photo over it is downscaled (1568 px / 1.15 MP) and sent with the note "downscaled from …", and a file `convertFile` turns into text is judged by its text - neither is refused for its original; that original may be up to `maxSourceBytes` (50 MB, never below `maxBytes`), and a picture's up to `imageMaxSourcePixels` (200 MP, read from the header before decoding); one message holds at most `maxImages` pictures (20) and `maxTotalBytes` (20 MB) of attachments as they go - a file past either is left out in words, the rest kept - see [docs/chat.md](docs/chat.md#attachments-images-pdfs-files-urls). |
856
+ | `<AgentComposer>` | The input and its toolbar: attachments, commands, timer, agents, model/thinking, consent, mic, send/stop. The model menu takes `section` per option (a heading over each run of options, e.g. one per provider); both chip menus work from the keyboard (arrows, Home / End, Escape) - see [docs/chat.md](docs/chat.md#the-model-menu-sections-and-keys). `attachments` takes `{ accept, maxBytes, imageMaxDimension, imageMaxPixels, maxSourceBytes, imageMaxSourcePixels, maxImages, maxTotalBytes }`: `maxBytes` (20 MB) is checked on what is sent, so a photo over it is downscaled (1568 px / 1.15 MP) and sent with the note "downscaled from …", and a file `convertFile` turns into text is judged by its text - neither is refused for its original; that original may be up to `maxSourceBytes` (50 MB, never below `maxBytes`), and a picture's up to `imageMaxSourcePixels` (200 MP, read from the header before decoding); one message holds at most `maxImages` pictures (20) and `maxTotalBytes` (20 MB) of attachments as they go - a file past either is left out in words, the rest kept. `convertFile` may return a chip `note` and `images` (`ConvertedImage`: `{ name, blob }`, e.g. a scanned PDF's pages) that go as pictures under the same bounds - see [docs/chat.md](docs/chat.md#attachments-images-pdfs-files-urls). |
857
857
  | `<MessageList>` | The transcript; each answer with its steps, tool calls, thoughts, usage. |
858
858
  | `<StepList>` / `<ToolCallRow>` | Execution steps / one tool call with its cost and images. With model tiers: the tier / model badge, the escalation line, the earlier attempt's calls (`showTiers`); a replanner failure as a warning (`showReplanFailed`); the decision model's note (`showDecisions`); the subagent tree under its step (`showSubagents`); a `web_search` call's results as plain text and safe links (`showSearchResults`). |
859
859
  | `<SubagentTree>` / `<SubagentRow>` | The run's subagents - static ones and the helpers the model started - as an indented tree: status, model, tokens, time and a Stop button per node (`onStop`, `showUsage`, `showTools`, `renderSubagent`). |
@@ -996,7 +996,9 @@ the hooks keep them in step, with nothing to configure beyond a shared `memory`
996
996
  for it (`sessionBusy`, "Waiting for the other tab to finish this conversation…", the goal shown
997
997
  queued - "waiting for the other tab to finish", `queuedForSession`, its `queued` entry marked
998
998
  `session`, while the wait lasts) and then goes, with that turn in the agent's memory; a saved chat
999
- keeps both turns, in order (`saveChat`: one transaction, merged by message identity).
999
+ keeps both turns, in order (`saveChat`: one transaction, merged by message identity) - also when
1000
+ a tab the browser froze saves its turn after the other tab saved the next one (each turn placed
1001
+ by when it began, `ChatMessage.startedAt`).
1000
1002
  - **Another tab deletes or upgrades the database** ("delete everything", a newer copy of the site):
1001
1003
  `ChatHistoryStore` closes its connection on `versionchange`, like the core's stores, so that tab is
1002
1004
  not held up; the next use opens a new, empty database (after an upgrade by a newer copy, an error
@@ -881,6 +881,14 @@ interface ChatMessage {
881
881
  * `useChatHistory` saves a chat from here with that tab's own copy, never this one.
882
882
  */
883
883
  remote?: true;
884
+ /**
885
+ * When the run of its turn began (ms epoch: the hook's `at` on `run.start`); the user message and
886
+ * the answer of a turn carry the same. Absent without the hook's timestamps and on chats saved
887
+ * before it existed. It keeps a turn in its place when two tabs save one chat: one run of a
888
+ * conversation goes at a time (the session lock), so the turn that began first is the earlier
889
+ * one, whichever tab saved first (`mergeChatRecord`).
890
+ */
891
+ startedAt?: number;
884
892
  /** User turn: what was attached (images, files). */
885
893
  attachments?: ChatAttachment[];
886
894
  /** Assistant turn: the run's steps — tool calls, thoughts, subagents — as they happened. */
@@ -881,6 +881,14 @@ interface ChatMessage {
881
881
  * `useChatHistory` saves a chat from here with that tab's own copy, never this one.
882
882
  */
883
883
  remote?: true;
884
+ /**
885
+ * When the run of its turn began (ms epoch: the hook's `at` on `run.start`); the user message and
886
+ * the answer of a turn carry the same. Absent without the hook's timestamps and on chats saved
887
+ * before it existed. It keeps a turn in its place when two tabs save one chat: one run of a
888
+ * conversation goes at a time (the session lock), so the turn that began first is the earlier
889
+ * one, whichever tab saved first (`mergeChatRecord`).
890
+ */
891
+ startedAt?: number;
884
892
  /** User turn: what was attached (images, files). */
885
893
  attachments?: ChatAttachment[];
886
894
  /** Assistant turn: the run's steps — tool calls, thoughts, subagents — as they happened. */
package/dist/index.cjs CHANGED
@@ -1004,6 +1004,7 @@ var applyEvent = (state, event, ctx) => {
1004
1004
  const base2 = resetRun(ctx.remote ? state : withoutSubmitted(state));
1005
1005
  const userId = `msg-${base2.seq}`;
1006
1006
  const assistantId = `msg-${base2.seq + 1}`;
1007
+ const began = ctx.at !== void 0 ? { startedAt: ctx.at } : {};
1007
1008
  return {
1008
1009
  ...base2,
1009
1010
  // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).
@@ -1021,6 +1022,7 @@ var applyEvent = (state, event, ctx) => {
1021
1022
  content: event.goal,
1022
1023
  pending: false,
1023
1024
  ...ctx.remote ? { remote: true } : {},
1025
+ ...began,
1024
1026
  ...ctx.attachments?.length ? { attachments: ctx.attachments } : {}
1025
1027
  },
1026
1028
  {
@@ -1028,7 +1030,8 @@ var applyEvent = (state, event, ctx) => {
1028
1030
  role: "assistant",
1029
1031
  content: "",
1030
1032
  pending: true,
1031
- ...ctx.remote ? { remote: true } : {}
1033
+ ...ctx.remote ? { remote: true } : {},
1034
+ ...began
1032
1035
  }
1033
1036
  ],
1034
1037
  seq: base2.seq + 2
@@ -2272,6 +2275,22 @@ var renumber = (own, after) => {
2272
2275
  );
2273
2276
  return own.map((m) => ({ ...m, id: `msg-${next += 1}` }));
2274
2277
  };
2278
+ var turnAt = (m) => typeof m.startedAt === "number" && Number.isFinite(m.startedAt) ? m.startedAt : void 0;
2279
+ var placeByTurn = (stored, own) => {
2280
+ let i = stored.length;
2281
+ while (i > 0 && turnAt(stored[i - 1]) !== void 0) i -= 1;
2282
+ const out = stored.slice(0, i);
2283
+ for (const m of own) {
2284
+ const at = turnAt(m);
2285
+ while (i < stored.length && (at === void 0 || turnAt(stored[i]) <= at)) {
2286
+ out.push(stored[i]);
2287
+ i += 1;
2288
+ }
2289
+ out.push(m);
2290
+ }
2291
+ return [...out, ...stored.slice(i)];
2292
+ };
2293
+ var ownUnsaved = (messages, base2) => messages.some((m) => !m.remote && !base2?.known.has(m));
2275
2294
  var unchangedSince = (messages, base2) => base2 !== void 0 && messages.length === base2.known.size && messages.every((m) => base2.known.has(m));
2276
2295
  var mergeChatRecord = (view, stored, base2, texts) => {
2277
2296
  const local = view.messages.filter((m) => !m.remote);
@@ -2279,7 +2298,7 @@ var mergeChatRecord = (view, stored, base2, texts) => {
2279
2298
  return { record: { ...view, messages: local }, merged: false };
2280
2299
  }
2281
2300
  const own = local.filter((m) => !base2?.known.has(m));
2282
- const messages = [...stored.messages, ...renumber(own, stored.messages)];
2301
+ const messages = placeByTurn(stored.messages, renumber(own, stored.messages));
2283
2302
  return {
2284
2303
  record: {
2285
2304
  ...view,
@@ -2314,7 +2333,18 @@ var useChatHistory = (agent, options = {}) => {
2314
2333
  const agentRef = (0, import_react2.useRef)(agent);
2315
2334
  agentRef.current = agent;
2316
2335
  const baseRef = (0, import_react2.useRef)(void 0);
2336
+ const loadingRef = (0, import_react2.useRef)(void 0);
2337
+ if (loadingRef.current && agent.messages !== loadingRef.current) loadingRef.current = void 0;
2317
2338
  const staleRef = (0, import_react2.useRef)(void 0);
2339
+ const queueRef = (0, import_react2.useRef)(Promise.resolve());
2340
+ const serially = (0, import_react2.useCallback)((task) => {
2341
+ const next = queueRef.current.then(task);
2342
+ queueRef.current = next.catch(() => {
2343
+ });
2344
+ return next;
2345
+ }, []);
2346
+ const baseOf = (id) => baseRef.current?.id === id ? baseRef.current : void 0;
2347
+ const unsavedHere = (messages2, id) => !loadingRef.current && ownUnsaved(messages2, baseOf(id));
2318
2348
  const refresh = (0, import_react2.useCallback)(async () => {
2319
2349
  try {
2320
2350
  setChats(await store.list());
@@ -2324,19 +2354,79 @@ var useChatHistory = (agent, options = {}) => {
2324
2354
  const newChat = (0, import_react2.useCallback)(() => {
2325
2355
  agentRef.current.loadChat({ sessionId: newChatId(), messages: [] });
2326
2356
  }, []);
2327
- const select = (0, import_react2.useCallback)(
2357
+ const show = (0, import_react2.useCallback)((record) => {
2358
+ createdRef.current.set(record.id, record.createdAt);
2359
+ baseRef.current = {
2360
+ id: record.id,
2361
+ known: new Set(record.messages),
2362
+ updatedAt: record.updatedAt
2363
+ };
2364
+ loadingRef.current ??= agentRef.current.messages;
2365
+ agentRef.current.loadChat({
2366
+ sessionId: record.id,
2367
+ messages: record.messages,
2368
+ totalUsage: record.totalUsage
2369
+ });
2370
+ }, []);
2371
+ const saveOpen = (0, import_react2.useCallback)(
2328
2372
  async (id) => {
2329
- const record = await store.get(id).catch(() => void 0);
2330
- if (!record) return;
2331
- createdRef.current.set(id, record.createdAt);
2332
- baseRef.current = { id, known: new Set(record.messages), updatedAt: record.updatedAt };
2333
- agentRef.current.loadChat({
2334
- sessionId: record.id,
2335
- messages: record.messages,
2336
- totalUsage: record.totalUsage
2337
- });
2373
+ const current = agentRef.current;
2374
+ if (current.sessionId !== id || current.isRunning) return;
2375
+ const { messages: messages2, totalUsage: totalUsage2, remote: remote2 } = current;
2376
+ if (messages2.length === 0) return;
2377
+ const base2 = baseOf(id);
2378
+ if (loadingRef.current || unchangedSince(messages2, base2)) return;
2379
+ if (remote2 && !ownUnsaved(messages2, base2)) return;
2380
+ const now = Date.now();
2381
+ const createdAt = createdRef.current.get(id) ?? now;
2382
+ createdRef.current.set(id, createdAt);
2383
+ const view = {
2384
+ id,
2385
+ title: chatTitle(messages2, textsRef.current),
2386
+ createdAt,
2387
+ updatedAt: now,
2388
+ messages: messages2,
2389
+ totalUsage: totalUsage2
2390
+ };
2391
+ const { record, merged } = await saveChat(store, view, base2, textsRef.current);
2392
+ baseRef.current = {
2393
+ id,
2394
+ known: new Set(merged ? record.messages : messages2),
2395
+ updatedAt: record.updatedAt
2396
+ };
2397
+ await refresh();
2398
+ if (merged && agentRef.current.sessionId === id) show(record);
2338
2399
  },
2339
- [store]
2400
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2401
+ [store, show]
2402
+ );
2403
+ const reread = (0, import_react2.useCallback)(
2404
+ (id) => serially(async () => {
2405
+ const settled = () => {
2406
+ const current = agentRef.current;
2407
+ if (current.sessionId !== id) return false;
2408
+ if (current.isRunning) {
2409
+ if (current.remote?.running) staleRef.current = id;
2410
+ return false;
2411
+ }
2412
+ return true;
2413
+ };
2414
+ if (!settled()) return;
2415
+ if (unsavedHere(agentRef.current.messages, id)) return saveOpen(id);
2416
+ const record = await store.get(id).catch(() => void 0);
2417
+ if (!record || !settled()) return;
2418
+ if (unsavedHere(agentRef.current.messages, id)) return saveOpen(id);
2419
+ show(record);
2420
+ }),
2421
+ // eslint-disable-next-line react-hooks/exhaustive-deps
2422
+ [store, serially, saveOpen, show]
2423
+ );
2424
+ const select = (0, import_react2.useCallback)(
2425
+ (id) => serially(async () => {
2426
+ const record = await store.get(id).catch(() => void 0);
2427
+ if (record) show(record);
2428
+ }),
2429
+ [store, serially, show]
2340
2430
  );
2341
2431
  const remove = (0, import_react2.useCallback)(
2342
2432
  async (id) => {
@@ -2380,44 +2470,34 @@ var useChatHistory = (agent, options = {}) => {
2380
2470
  const current = agentRef.current;
2381
2471
  if (key === void 0 || key !== current.sessionId) return;
2382
2472
  if (current.remote?.running) staleRef.current = key;
2383
- else if (!current.isRunning) void select(key);
2473
+ else if (!current.isRunning) void reread(key);
2384
2474
  }
2385
2475
  );
2386
- }, [enabled, store, refresh, select]);
2476
+ }, [enabled, store, refresh, reread]);
2387
2477
  const { messages, totalUsage, sessionId, isRunning, remote } = agent;
2388
2478
  (0, import_react2.useEffect)(() => {
2389
2479
  if (!enabled || loading || isRunning) return;
2390
2480
  if (staleRef.current === sessionId) {
2391
2481
  staleRef.current = void 0;
2392
- void select(sessionId);
2482
+ void reread(sessionId).catch(() => {
2483
+ });
2393
2484
  return;
2394
2485
  }
2395
- if (remote || messages.length === 0) return;
2396
- const base2 = baseRef.current?.id === sessionId ? baseRef.current : void 0;
2397
- if (unchangedSince(messages, base2)) return;
2398
- const now = Date.now();
2399
- const createdAt = createdRef.current.get(sessionId) ?? now;
2400
- createdRef.current.set(sessionId, createdAt);
2401
- const view = {
2402
- id: sessionId,
2403
- title: chatTitle(messages, textsRef.current),
2404
- createdAt,
2405
- updatedAt: now,
2406
- messages,
2407
- totalUsage
2408
- };
2409
- void (async () => {
2410
- const { record, merged } = await saveChat(store, view, base2, textsRef.current);
2411
- baseRef.current = {
2412
- id: sessionId,
2413
- known: new Set(merged ? record.messages : messages),
2414
- updatedAt: record.updatedAt
2415
- };
2416
- await refresh();
2417
- if (merged && agentRef.current.sessionId === sessionId) await select(sessionId);
2418
- })().catch(() => {
2486
+ if (messages.length === 0) return;
2487
+ void serially(() => saveOpen(sessionId)).catch(() => {
2419
2488
  });
2420
- }, [enabled, loading, isRunning, remote, messages, totalUsage, sessionId, store, refresh, select]);
2489
+ }, [
2490
+ enabled,
2491
+ loading,
2492
+ isRunning,
2493
+ remote,
2494
+ messages,
2495
+ totalUsage,
2496
+ sessionId,
2497
+ serially,
2498
+ saveOpen,
2499
+ reread
2500
+ ]);
2421
2501
  return { chats, currentId: sessionId, loading, select, newChat, remove };
2422
2502
  };
2423
2503
 
@@ -6967,6 +7047,47 @@ ${draftText}` : draftText);
6967
7047
  if (full) noRoom[full].push(name);
6968
7048
  else setPending((cur) => [...cur, a]);
6969
7049
  };
7050
+ const sendAs = async (name, f, kind, mediaType, transform, id) => {
7051
+ const blob = transform === "downscale" ? await downscaleImage(f, {
7052
+ maxDimension: imageMax,
7053
+ maxPixels: attachCfg.imageMaxPixels
7054
+ }) : f;
7055
+ const sentOver = attachmentOverLimit({ bytes: blob.size }, "sent", transform, bounds);
7056
+ if (sentOver) return overLimitText(name, sentOver);
7057
+ add(name, {
7058
+ id,
7059
+ name,
7060
+ kind,
7061
+ mediaType: blob.type || mediaType,
7062
+ dataUrl: await readDataUrl2(blob),
7063
+ bytes: blob.size,
7064
+ ...blob !== f ? { note: L.downscaledFrom(L.bytes(f.size)) } : {}
7065
+ });
7066
+ return void 0;
7067
+ };
7068
+ const addImage = async (name, blob, id) => {
7069
+ const mediaType = blob.type || "image/jpeg";
7070
+ if (attachmentKindOf(mediaType, name) !== "image") return L.binaryText(name);
7071
+ const transform = attachmentTransformOf({
7072
+ kind: "image",
7073
+ mediaType,
7074
+ imageMaxDimension: imageMax,
7075
+ converts: false
7076
+ });
7077
+ const size = transform === "downscale" ? await imageSizeOf(blob) : void 0;
7078
+ const over = attachmentOverLimit(
7079
+ { bytes: blob.size, pixels: size && size.width * size.height },
7080
+ "original",
7081
+ transform,
7082
+ bounds
7083
+ );
7084
+ if (over) return overLimitText(name, over);
7085
+ if (messageOverLimit(pendingRef.current, { kind: "image", bytes: 0 }, bounds) === "images") {
7086
+ noRoom.images.push(name);
7087
+ return void 0;
7088
+ }
7089
+ return sendAs(name, blob, "image", mediaType, transform, id);
7090
+ };
6970
7091
  for (const f of list) {
6971
7092
  const mediaType = f.type || "application/octet-stream";
6972
7093
  const name = f.name || `pasted-${Date.now()}.${mediaType.split("/")[1] ?? "bin"}`;
@@ -7005,9 +7126,9 @@ ${draftText}` : draftText);
7005
7126
  const converted = await convertFile(f);
7006
7127
  if (converted) {
7007
7128
  const bytes = new Blob([converted.text]).size;
7008
- const sentOver2 = attachmentOverLimit({ bytes }, "sent", transform, bounds);
7009
- if (sentOver2) {
7010
- problem = overLimitText(name, sentOver2);
7129
+ const sentOver = attachmentOverLimit({ bytes }, "sent", transform, bounds);
7130
+ if (sentOver) {
7131
+ problem = overLimitText(name, sentOver);
7011
7132
  continue;
7012
7133
  }
7013
7134
  add(name, {
@@ -7017,8 +7138,18 @@ ${draftText}` : draftText);
7017
7138
  mediaType: "text/markdown",
7018
7139
  text: converted.text,
7019
7140
  bytes,
7020
- note: L.convertedFrom(name)
7141
+ note: converted.note ?? L.convertedFrom(name)
7021
7142
  });
7143
+ const images = converted.images ?? [];
7144
+ if (images.length > 0) {
7145
+ const imageRefusal = attachmentRefusal("image", caps);
7146
+ if (imageRefusal) problem = imageRefusal;
7147
+ else
7148
+ for (const image of images) {
7149
+ const said3 = await addImage(image.name, image.blob, `att-${attachSeq += 1}`);
7150
+ if (said3) problem = said3;
7151
+ }
7152
+ }
7022
7153
  continue;
7023
7154
  }
7024
7155
  }
@@ -7026,24 +7157,8 @@ ${draftText}` : draftText);
7026
7157
  problem = refusal;
7027
7158
  continue;
7028
7159
  }
7029
- const blob = transform === "downscale" ? await downscaleImage(f, {
7030
- maxDimension: imageMax,
7031
- maxPixels: attachCfg.imageMaxPixels
7032
- }) : f;
7033
- const sentOver = attachmentOverLimit({ bytes: blob.size }, "sent", transform, bounds);
7034
- if (sentOver) {
7035
- problem = overLimitText(name, sentOver);
7036
- continue;
7037
- }
7038
- add(name, {
7039
- id,
7040
- name,
7041
- kind,
7042
- mediaType: blob.type || mediaType,
7043
- dataUrl: await readDataUrl2(blob),
7044
- bytes: blob.size,
7045
- ...blob !== f ? { note: L.downscaledFrom(L.bytes(f.size)) } : {}
7046
- });
7160
+ const said2 = await sendAs(name, f, kind, mediaType, transform, id);
7161
+ if (said2) problem = said2;
7047
7162
  } catch (err) {
7048
7163
  problem = `${name}: ${err instanceof Error ? err.message : String(err)}`;
7049
7164
  }