@dudko.dev/agent-web-react 0.0.31 → 0.0.32

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/dist/index.js CHANGED
@@ -46,13 +46,14 @@ import {
46
46
  ToolIcon,
47
47
  XIcon,
48
48
  errMessage,
49
+ followOtherTabs,
49
50
  formatDuration,
50
51
  formatProbability,
51
52
  formatTokens,
52
53
  imagesInOutput,
53
54
  previewValue,
54
55
  webSearchOf
55
- } from "./chunk-EMF7DTGS.js";
56
+ } from "./chunk-G5GGIMD4.js";
56
57
  import {
57
58
  MCP_APP_POLICY_TOKEN_MAX_CHARS,
58
59
  MCP_APP_SANDBOX_PROXY_READY,
@@ -64,6 +65,7 @@ import {
64
65
 
65
66
  // src/hooks/use-agent.ts
66
67
  import { useCallback, useEffect, useReducer, useRef, useState } from "react";
68
+ import * as core from "@dudko.dev/agent-web";
67
69
  import {
68
70
  createAgent,
69
71
  createRunControl
@@ -226,6 +228,7 @@ var addElicitation = (state, event, extra) => state.elicitations?.some((e) => e.
226
228
  ...event.url ? { url: event.url } : {},
227
229
  ...extra.stepId ? { stepId: extra.stepId } : {},
228
230
  ...extra.subagent ? { subagent: extra.subagent } : {},
231
+ ...extra.remote ? { remote: true } : {},
229
232
  status: "pending"
230
233
  }
231
234
  ]
@@ -442,6 +445,7 @@ var applySubagent = (state, event, ancestors, ctx) => {
442
445
  ...node?.role ? { role: node.role } : {}
443
446
  },
444
447
  ...inner.skill ? { skill: inner.skill } : {},
448
+ ...ctx.remote ? { remote: true } : {},
445
449
  status: "pending"
446
450
  }
447
451
  ]
@@ -466,6 +470,7 @@ var applySubagent = (state, event, ancestors, ctx) => {
466
470
  case "mcp.elicitation-requested": {
467
471
  const node = inner.subagent ? known.subagents.find((s) => s.id === inner.subagent.id) : void 0;
468
472
  return addElicitation(known, inner, {
473
+ ...ctx.remote ? { remote: true } : {},
469
474
  // The subagent's own step ids mean nothing here: the step that delegated it does.
470
475
  stepId: (node ?? known.subagents.find((s) => s.id === event.id))?.stepId,
471
476
  ...inner.subagent ? {
@@ -504,6 +509,7 @@ var applySubagent = (state, event, ancestors, ctx) => {
504
509
  return fileDeleted(known, inner.path);
505
510
  // An app a subagent's call came with is shown in the turn too, and says whose call it was.
506
511
  case "mcp.app": {
512
+ if (ctx.remote) return known;
507
513
  const node = known.subagents.find((s) => s.id === event.id);
508
514
  return addApp(known, inner, {
509
515
  id: event.id,
@@ -595,14 +601,37 @@ var streamAssistant = (messages, content) => {
595
601
  }
596
602
  return messages;
597
603
  };
604
+ var WAITING_ID = "waiting-for-session";
605
+ var withoutBusy = (state) => {
606
+ if (!state.sessionBusy) return state;
607
+ const { sessionBusy: _over, ...rest } = state;
608
+ void _over;
609
+ return { ...rest, queued: rest.queued.filter((q) => q.id !== WAITING_ID) };
610
+ };
611
+ var withoutSubmitted = (state) => {
612
+ if (!state.submitted) return state;
613
+ const { submitted, ...rest } = state;
614
+ const ids = /* @__PURE__ */ new Set([submitted.userId, submitted.assistantId]);
615
+ return { ...rest, messages: rest.messages.filter((m) => !ids.has(m.id)) };
616
+ };
617
+ var keepSubmitted = (state) => {
618
+ if (!state.submitted) return state;
619
+ const { submitted: _kept, ...rest } = state;
620
+ void _kept;
621
+ return rest;
622
+ };
598
623
  var applyEvent = (state, event, ctx) => {
599
624
  switch (event.type) {
600
625
  case "run.start": {
601
- const base = resetRun(state);
626
+ const base = resetRun(ctx.remote ? state : withoutSubmitted(state));
602
627
  const userId = `msg-${base.seq}`;
603
628
  const assistantId = `msg-${base.seq + 1}`;
604
629
  return {
605
630
  ...base,
631
+ // Another tab's run keeps the view of it; a run of this tab's ends it (and any wait).
632
+ ...ctx.remote && state.remote ? { remote: state.remote } : {},
633
+ // ...and this tab's sent turn, still waiting for its own run.start (or a session.busy).
634
+ ...ctx.remote && state.submitted ? { submitted: state.submitted } : {},
606
635
  goal: event.goal,
607
636
  runStartedAt: ctx.at,
608
637
  runMessageId: assistantId,
@@ -613,9 +642,16 @@ var applyEvent = (state, event, ctx) => {
613
642
  role: "user",
614
643
  content: event.goal,
615
644
  pending: false,
645
+ ...ctx.remote ? { remote: true } : {},
616
646
  ...ctx.attachments?.length ? { attachments: ctx.attachments } : {}
617
647
  },
618
- { id: assistantId, role: "assistant", content: "", pending: true }
648
+ {
649
+ id: assistantId,
650
+ role: "assistant",
651
+ content: "",
652
+ pending: true,
653
+ ...ctx.remote ? { remote: true } : {}
654
+ }
619
655
  ],
620
656
  seq: base.seq + 2
621
657
  };
@@ -849,9 +885,15 @@ var applyEvent = (state, event, ctx) => {
849
885
  case "file.deleted":
850
886
  return fileDeleted(state, event.path);
851
887
  case "mcp.app":
852
- return addApp(state, event);
888
+ return ctx.remote ? state : addApp(state, event);
853
889
  case "message.queued":
854
- return state.queued.some((q) => q.id === event.id) ? state : { ...state, queued: [...state.queued, { id: event.id, text: event.text }] };
890
+ return state.queued.some((q) => q.id === event.id) ? state : {
891
+ ...state,
892
+ queued: [
893
+ ...state.queued,
894
+ { id: event.id, text: event.text, ...event.origin ? { origin: event.origin } : {} }
895
+ ]
896
+ };
855
897
  case "message.delivered": {
856
898
  const anchor = event.at === "round" ? runningStepId(state.steps) : event.at === "step" ? state.steps[state.steps.length - 1]?.id : void 0;
857
899
  return {
@@ -859,7 +901,13 @@ var applyEvent = (state, event, ctx) => {
859
901
  queued: state.queued.filter((q) => q.id !== event.id),
860
902
  notes: [
861
903
  ...state.notes,
862
- { id: event.id, text: event.text, at: event.at, ...anchor ? { stepId: anchor } : {} }
904
+ {
905
+ id: event.id,
906
+ text: event.text,
907
+ at: event.at,
908
+ ...anchor ? { stepId: anchor } : {},
909
+ ...event.origin ? { origin: event.origin } : {}
910
+ }
863
911
  ]
864
912
  };
865
913
  }
@@ -886,6 +934,8 @@ var applyEvent = (state, event, ctx) => {
886
934
  };
887
935
  case "mcp.elicitation-requested":
888
936
  return addElicitation(state, event, {
937
+ // Asked in the tab that runs the tool call: shown here, answered there.
938
+ ...ctx.remote ? { remote: true } : {},
889
939
  stepId: event.step?.id,
890
940
  ...event.subagent ? { subagent: event.subagent } : {}
891
941
  });
@@ -905,6 +955,8 @@ var applyEvent = (state, event, ctx) => {
905
955
  ...event.subagent ? { subagent: event.subagent } : {},
906
956
  ...event.app ? { app: event.app } : {},
907
957
  ...event.skill ? { skill: event.skill } : {},
958
+ // Asked in the tab that runs the tool: shown here, answered there.
959
+ ...ctx.remote ? { remote: true } : {},
908
960
  status: "pending"
909
961
  }
910
962
  ]
@@ -989,9 +1041,26 @@ var applyEvent = (state, event, ctx) => {
989
1041
  };
990
1042
  case "budget.exceeded":
991
1043
  return { ...state, budget: { kind: event.kind, tokens: event.tokens, cap: event.cap } };
992
- case "stopped":
1044
+ case "session.busy":
1045
+ state = withoutSubmitted(state);
993
1046
  return {
994
1047
  ...state,
1048
+ sessionBusy: { heldBy: event.heldBy, ...ctx.goal ? { goal: ctx.goal } : {} },
1049
+ // What the user sent waits with the run: shown as queued, not lost.
1050
+ ...ctx.goal ? {
1051
+ queued: [
1052
+ ...state.queued.filter((q) => q.id !== WAITING_ID),
1053
+ { id: WAITING_ID, text: ctx.goal }
1054
+ ]
1055
+ } : {}
1056
+ };
1057
+ case "session.acquired":
1058
+ return withoutBusy(state);
1059
+ case "stopped":
1060
+ if (!ctx.remote && state.sessionBusy) return withoutBusy(state);
1061
+ if (!ctx.remote && state.submitted) return withoutSubmitted(state);
1062
+ return {
1063
+ ...withoutBusy(state),
995
1064
  stopped: true,
996
1065
  // Nothing of the run is waiting any more once it has stopped (an app's request is not
997
1066
  // the run's).
@@ -1017,7 +1086,7 @@ var applyEvent = (state, event, ctx) => {
1017
1086
  };
1018
1087
  }
1019
1088
  return event.phase === "run" ? {
1020
- ...state,
1089
+ ...withoutBusy(keepSubmitted(state)),
1021
1090
  error: event.error,
1022
1091
  messages: finalizeAssistant(
1023
1092
  state.messages,
@@ -1062,6 +1131,8 @@ var syncRunMessage = (state) => {
1062
1131
  messages[i] = { ...m, ...patch };
1063
1132
  return { ...state, messages };
1064
1133
  };
1134
+ var pendingApprovalsOf = (state) => state.approvals.filter((a) => a.status === "pending" && !a.remote);
1135
+ var agentStatusOf = (state) => state.remote?.running && (state.status === "ready" || state.status === "idle") ? "running" : state.status;
1065
1136
  var agentStateReducer = (state, action) => {
1066
1137
  switch (action.type) {
1067
1138
  case "reset":
@@ -1073,22 +1144,68 @@ var agentStateReducer = (state, action) => {
1073
1144
  };
1074
1145
  case "notebook":
1075
1146
  return { ...state, learned: action.lessons };
1147
+ case "submitted": {
1148
+ if (state.submitted) return state;
1149
+ const userId = `msg-${state.seq}`;
1150
+ const assistantId = `msg-${state.seq + 1}`;
1151
+ return {
1152
+ ...state,
1153
+ submitted: { userId, assistantId },
1154
+ messages: [
1155
+ ...state.messages,
1156
+ {
1157
+ id: userId,
1158
+ role: "user",
1159
+ content: action.goal,
1160
+ pending: false,
1161
+ ...action.attachments?.length ? { attachments: action.attachments } : {}
1162
+ },
1163
+ { id: assistantId, role: "assistant", content: "", pending: true }
1164
+ ],
1165
+ seq: state.seq + 2
1166
+ };
1167
+ }
1076
1168
  case "status":
1077
1169
  return {
1078
1170
  ...state,
1079
1171
  status: action.status,
1080
1172
  error: action.status === "error" ? action.error : void 0
1081
1173
  };
1174
+ case "remote": {
1175
+ const remote = action.remote;
1176
+ if (!remote) {
1177
+ const { remote: _gone, ...rest } = state;
1178
+ void _gone;
1179
+ return rest;
1180
+ }
1181
+ if (remote.ended === "gone" && state.remote?.running) {
1182
+ return syncRunMessage({
1183
+ ...state,
1184
+ remote,
1185
+ messages: finalizeAssistant(state.messages, state.finalText, { error: true })
1186
+ });
1187
+ }
1188
+ return { ...state, remote };
1189
+ }
1082
1190
  case "event": {
1083
1191
  const next = syncRunMessage(
1084
- applyEvent(state, action.event, { at: action.at, attachments: action.attachments })
1192
+ applyEvent(state, action.event, {
1193
+ at: action.at,
1194
+ attachments: action.attachments,
1195
+ ...action.remote ? { remote: true } : {},
1196
+ ...action.goal ? { goal: action.goal } : {}
1197
+ })
1085
1198
  );
1086
1199
  const cap = action.maxEvents ?? 200;
1087
1200
  const events = cap > 0 ? [...state.events, action.event].slice(-cap) : [...state.events, action.event];
1088
1201
  return { ...next, events };
1089
1202
  }
1090
1203
  case "undelivered":
1091
- return { ...state, queued: [], undelivered: action.texts };
1204
+ return {
1205
+ ...state,
1206
+ queued: action.keepQueued ? state.queued : [],
1207
+ undelivered: action.texts
1208
+ };
1092
1209
  case "load": {
1093
1210
  const maxSeq = action.messages.reduce((n, m) => {
1094
1211
  const k = Number(/^msg-(\d+)$/.exec(m.id)?.[1] ?? -1);
@@ -1109,6 +1226,10 @@ var agentStateReducer = (state, action) => {
1109
1226
  };
1110
1227
 
1111
1228
  // src/hooks/use-agent.ts
1229
+ var dbNameOf = (store) => {
1230
+ const name = store?.dbName;
1231
+ return typeof name === "string" && name ? name : void 0;
1232
+ };
1112
1233
  var useAgent = (config, options = {}) => {
1113
1234
  const [state, dispatch] = useReducer(agentStateReducer, void 0, createInitialAgentState);
1114
1235
  const agentRef = useRef(void 0);
@@ -1181,6 +1302,57 @@ var useAgent = (config, options = {}) => {
1181
1302
  cancelled = true;
1182
1303
  };
1183
1304
  }, [generation, autoStart, ...deps ?? []]);
1305
+ const watchRef = useRef(void 0);
1306
+ const startedRef = useRef(false);
1307
+ const watchDb = options.watch !== false && config.sessionLock !== "off" ? dbNameOf(config.memory) : void 0;
1308
+ useEffect(() => {
1309
+ const watchSession3 = core.watchSession;
1310
+ if (!watchDb || typeof watchSession3 !== "function") return;
1311
+ const watch = watchSession3({
1312
+ dbName: watchDb,
1313
+ sessionId,
1314
+ onEvent: (event) => {
1315
+ if (startedRef.current) return;
1316
+ dispatch({
1317
+ type: "event",
1318
+ event,
1319
+ remote: true,
1320
+ maxEvents: optionsRef.current.maxEvents,
1321
+ at: Date.now()
1322
+ });
1323
+ },
1324
+ onState: (s) => {
1325
+ if (startedRef.current && s.running) return;
1326
+ dispatch({
1327
+ type: "remote",
1328
+ remote: {
1329
+ running: s.running,
1330
+ ...s.runId ? { runId: s.runId } : {},
1331
+ ...s.ended ? { ended: s.ended } : {}
1332
+ }
1333
+ });
1334
+ }
1335
+ });
1336
+ watchRef.current = watch;
1337
+ return () => {
1338
+ watch.close();
1339
+ if (watchRef.current === watch) watchRef.current = void 0;
1340
+ };
1341
+ }, [watchDb, sessionId]);
1342
+ const skillsDb = dbNameOf(typeof config.learning === "object" ? config.learning.store : void 0);
1343
+ useEffect(() => {
1344
+ return followOtherTabs(
1345
+ core,
1346
+ skillsDb,
1347
+ (change) => change.kind === "skills",
1348
+ () => {
1349
+ const agent = agentRef.current;
1350
+ if (!agent || typeof agent.reloadLearnedSkills !== "function") return;
1351
+ void agent.reloadLearnedSkills().then((skills) => dispatch({ type: "notebook", lessons: lessonsOf(skills) })).catch(() => {
1352
+ });
1353
+ }
1354
+ );
1355
+ }, [skillsDb]);
1184
1356
  useEffect(
1185
1357
  () => () => {
1186
1358
  abortRef.current?.abort();
@@ -1199,7 +1371,17 @@ var useAgent = (config, options = {}) => {
1199
1371
  const control = createRunControl();
1200
1372
  controlRef.current = control;
1201
1373
  let left = [];
1374
+ let stopped = false;
1375
+ let began = false;
1376
+ const shownGoal = runOptions?.label ?? goal;
1202
1377
  dispatch({ type: "status", status: "running" });
1378
+ if (shownGoal.trim()) {
1379
+ dispatch({
1380
+ type: "submitted",
1381
+ goal: shownGoal,
1382
+ ...runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}
1383
+ });
1384
+ }
1203
1385
  try {
1204
1386
  const result = await agent.run(goal, {
1205
1387
  signal: controller.signal,
@@ -1209,12 +1391,18 @@ var useAgent = (config, options = {}) => {
1209
1391
  ...runOptions?.files?.length ? { files: runOptions.files } : {},
1210
1392
  onEvent: (event) => {
1211
1393
  const start = event.type === "run.start";
1394
+ if (start) {
1395
+ startedRef.current = true;
1396
+ began = true;
1397
+ }
1212
1398
  const shown = start && runOptions?.label ? { ...event, goal: runOptions.label } : event;
1213
1399
  dispatch({
1214
1400
  type: "event",
1215
1401
  event: shown,
1216
1402
  maxEvents: optionsRef.current.maxEvents,
1217
1403
  at: Date.now(),
1404
+ // What the user sent waits with the run: shown as queued meanwhile.
1405
+ ...event.type === "session.busy" && shownGoal.trim() ? { goal: shownGoal } : {},
1218
1406
  ...start && runOptions?.attachments?.length ? { attachments: runOptions.attachments } : {}
1219
1407
  });
1220
1408
  try {
@@ -1224,6 +1412,7 @@ var useAgent = (config, options = {}) => {
1224
1412
  }
1225
1413
  });
1226
1414
  left = result.undelivered ?? [];
1415
+ stopped = result.stopped;
1227
1416
  return result;
1228
1417
  } catch (err) {
1229
1418
  left = control.pending();
@@ -1235,11 +1424,13 @@ var useAgent = (config, options = {}) => {
1235
1424
  return void 0;
1236
1425
  } finally {
1237
1426
  abortRef.current = void 0;
1427
+ startedRef.current = false;
1238
1428
  controlRef.current = void 0;
1239
1429
  settleAll({ approved: false, reason: "the run ended" });
1240
1430
  dispatch({ type: "status", ...buildStatusRef.current });
1431
+ if (stopped && !began && shownGoal.trim()) left = [shownGoal, ...left];
1241
1432
  if (left.length > 0) {
1242
- if (!controller.signal.aborted && optionsRef.current.followUp !== false) {
1433
+ if (!controller.signal.aborted && !stopped && optionsRef.current.followUp !== false) {
1243
1434
  dispatch({ type: "undelivered", texts: [] });
1244
1435
  void runRef.current?.(left.join("\n\n"));
1245
1436
  } else {
@@ -1254,6 +1445,24 @@ var useAgent = (config, options = {}) => {
1254
1445
  );
1255
1446
  runRef.current = run;
1256
1447
  const send = useCallback((text) => controlRef.current?.send(text) ?? false, []);
1448
+ const sendRemote = useCallback((text) => {
1449
+ const watch = watchRef.current;
1450
+ const clean = typeof text === "string" ? text.trim() : "";
1451
+ if (!watch?.state.running || !clean) return false;
1452
+ void watch.send(clean).then((ok) => {
1453
+ if (!ok) {
1454
+ dispatch({
1455
+ type: "undelivered",
1456
+ texts: [...stateRef.current.undelivered, clean],
1457
+ keepQueued: true
1458
+ });
1459
+ }
1460
+ });
1461
+ return true;
1462
+ }, []);
1463
+ const stopRemote = useCallback(() => {
1464
+ if (watchRef.current?.state.running) void watchRef.current.stop();
1465
+ }, []);
1257
1466
  const stopSubagent = useCallback(
1258
1467
  (id) => controlRef.current?.stopSubagent(id) ?? false,
1259
1468
  []
@@ -1370,11 +1579,16 @@ var useAgent = (config, options = {}) => {
1370
1579
  }
1371
1580
  return result;
1372
1581
  }, []);
1582
+ const remoteRunning = state.remote?.running === true;
1373
1583
  return {
1374
1584
  ...state,
1585
+ // `running` over ready / idle only: a build in progress or an error stays visible.
1586
+ status: agentStatusOf(state),
1375
1587
  run,
1376
1588
  stop,
1589
+ stopRemote,
1377
1590
  send,
1591
+ sendRemote,
1378
1592
  stopSubagent,
1379
1593
  forgetSkill,
1380
1594
  sendUndelivered,
@@ -1382,9 +1596,10 @@ var useAgent = (config, options = {}) => {
1382
1596
  reset,
1383
1597
  reload,
1384
1598
  agent: agentRef.current,
1385
- isRunning: state.status === "running",
1386
- isReady: state.status === "ready",
1387
- pendingApprovals: state.approvals.filter((a) => a.status === "pending"),
1599
+ isRunning: state.status === "running" || remoteRunning,
1600
+ isReady: state.status === "ready" && !remoteRunning,
1601
+ // Another tab's consent requests are answered there, never here.
1602
+ pendingApprovals: pendingApprovalsOf(state),
1388
1603
  approve,
1389
1604
  deny,
1390
1605
  approvalMode,
@@ -1399,26 +1614,36 @@ var useAgent = (config, options = {}) => {
1399
1614
 
1400
1615
  // src/hooks/use-chat-history.ts
1401
1616
  import { useCallback as useCallback2, useEffect as useEffect2, useMemo, useRef as useRef2, useState as useState2 } from "react";
1617
+ import * as core3 from "@dudko.dev/agent-web";
1402
1618
 
1403
1619
  // src/chat-history.ts
1620
+ import * as core2 from "@dudko.dev/agent-web";
1404
1621
  var DB_VERSION = 1;
1405
1622
  var req = (r) => new Promise((resolve, reject) => {
1406
1623
  r.onsuccess = () => resolve(r.result);
1407
1624
  r.onerror = () => reject(r.error);
1408
1625
  });
1626
+ var committed = (tx, r) => new Promise((resolve, reject) => {
1627
+ tx.oncomplete = () => resolve();
1628
+ tx.onabort = () => reject(tx.error ?? r.error ?? new Error("the transaction was aborted"));
1629
+ tx.onerror = () => reject(tx.error ?? r.error);
1630
+ });
1409
1631
  var ChatHistoryStore = class {
1632
+ /** The IndexedDB database (undefined in memory): the name its `chats` notices go out under. */
1410
1633
  dbName;
1634
+ name;
1411
1635
  storeName;
1412
1636
  memory;
1413
1637
  db;
1414
1638
  constructor(opts = {}) {
1415
- this.dbName = opts.dbName ?? "agent-web-react";
1639
+ this.name = opts.dbName ?? "agent-web-react";
1416
1640
  this.storeName = opts.storeName ?? "chats";
1417
1641
  if (opts.memory || typeof indexedDB === "undefined") this.memory = /* @__PURE__ */ new Map();
1642
+ this.dbName = this.memory ? void 0 : this.name;
1418
1643
  }
1419
1644
  open() {
1420
1645
  this.db ??= new Promise((resolve, reject) => {
1421
- const r = indexedDB.open(this.dbName, DB_VERSION);
1646
+ const r = indexedDB.open(this.name, DB_VERSION);
1422
1647
  r.onupgradeneeded = () => {
1423
1648
  if (!r.result.objectStoreNames.contains(this.storeName)) {
1424
1649
  r.result.createObjectStore(this.storeName, { keyPath: "id" });
@@ -1436,6 +1661,54 @@ var ChatHistoryStore = class {
1436
1661
  const db = await this.open();
1437
1662
  return db.transaction(this.storeName, mode).objectStore(this.storeName);
1438
1663
  }
1664
+ /** One write in its own transaction, resolved once it committed - then the notice. */
1665
+ async write(op, notice) {
1666
+ const db = await this.open();
1667
+ const tx = db.transaction(this.storeName, "readwrite");
1668
+ await committed(tx, op(tx.objectStore(this.storeName)));
1669
+ this.announce(notice);
1670
+ }
1671
+ announce(notice) {
1672
+ if (typeof core2.postStorageChange === "function") {
1673
+ core2.postStorageChange(this.dbName, { kind: "chats", ...notice });
1674
+ }
1675
+ }
1676
+ /**
1677
+ * Read the stored record and write what `merge` makes of it in ONE readwrite transaction: no
1678
+ * other tab's save can land between the read and the write. `merge` is synchronous (a
1679
+ * transaction does not survive an await). Resolves with what was written, once committed.
1680
+ */
1681
+ async putMerged(id, merge) {
1682
+ if (this.memory) {
1683
+ const record = merge(this.memory.get(id));
1684
+ this.memory.set(record.id, structuredClone(record));
1685
+ return record;
1686
+ }
1687
+ const db = await this.open();
1688
+ const tx = db.transaction(this.storeName, "readwrite");
1689
+ const store = tx.objectStore(this.storeName);
1690
+ let written;
1691
+ let failed;
1692
+ const read = store.get(id);
1693
+ const done = committed(tx, read);
1694
+ read.onsuccess = () => {
1695
+ try {
1696
+ written = merge(read.result);
1697
+ store.put(written);
1698
+ } catch (err) {
1699
+ failed = err;
1700
+ tx.abort();
1701
+ }
1702
+ };
1703
+ try {
1704
+ await done;
1705
+ } catch (err) {
1706
+ throw failed ?? err;
1707
+ }
1708
+ if (!written) throw new Error("the chat could not be saved");
1709
+ this.announce({ op: "put", key: id });
1710
+ return written;
1711
+ }
1439
1712
  async list() {
1440
1713
  const all = this.memory ? [...this.memory.values()] : await req((await this.tx("readonly")).getAll());
1441
1714
  return all.map(({ messages, ...rest }) => ({ ...rest, messageCount: messages.length })).sort((a, b) => b.updatedAt - a.updatedAt);
@@ -1449,21 +1722,21 @@ var ChatHistoryStore = class {
1449
1722
  this.memory.set(record.id, structuredClone(record));
1450
1723
  return;
1451
1724
  }
1452
- await req((await this.tx("readwrite")).put(record));
1725
+ await this.write((store) => store.put(record), { op: "put", key: record.id });
1453
1726
  }
1454
1727
  async delete(id) {
1455
1728
  if (this.memory) {
1456
1729
  this.memory.delete(id);
1457
1730
  return;
1458
1731
  }
1459
- await req((await this.tx("readwrite")).delete(id));
1732
+ await this.write((store) => store.delete(id), { op: "delete", key: id });
1460
1733
  }
1461
1734
  async clear() {
1462
1735
  if (this.memory) {
1463
1736
  this.memory.clear();
1464
1737
  return;
1465
1738
  }
1466
- await req((await this.tx("readwrite")).clear());
1739
+ await this.write((store) => store.clear(), { op: "clear" });
1467
1740
  }
1468
1741
  };
1469
1742
  var chatTitle = (messages) => {
@@ -1474,6 +1747,61 @@ var chatTitle = (messages) => {
1474
1747
  var newChatId = () => `chat-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
1475
1748
 
1476
1749
  // src/hooks/use-chat-history.ts
1750
+ var USAGE_KEYS = [
1751
+ "inputTokens",
1752
+ "outputTokens",
1753
+ "totalTokens",
1754
+ "reasoningTokens",
1755
+ "cachedInputTokens",
1756
+ "cacheWriteTokens"
1757
+ ];
1758
+ var sumUsage = (base, more) => {
1759
+ const out = { ...base ?? {} };
1760
+ for (const u of more) {
1761
+ if (!u) continue;
1762
+ for (const k of USAGE_KEYS) out[k] = (out[k] ?? 0) + (u[k] ?? 0);
1763
+ }
1764
+ for (const k of USAGE_KEYS) out[k] ??= 0;
1765
+ return out;
1766
+ };
1767
+ var renumber = (own, after) => {
1768
+ let next = after.reduce(
1769
+ (max, m) => Math.max(max, Number(/^msg-(\d+)$/.exec(m.id)?.[1] ?? -1)),
1770
+ -1
1771
+ );
1772
+ return own.map((m) => ({ ...m, id: `msg-${next += 1}` }));
1773
+ };
1774
+ var unchangedSince = (messages, base) => base !== void 0 && messages.length === base.known.size && messages.every((m) => base.known.has(m));
1775
+ var mergeChatRecord = (view, stored, base) => {
1776
+ const local = view.messages.filter((m) => !m.remote);
1777
+ if (!stored || base && stored.updatedAt <= base.updatedAt) {
1778
+ return { record: { ...view, messages: local }, merged: false };
1779
+ }
1780
+ const own = local.filter((m) => !base?.known.has(m));
1781
+ const messages = [...stored.messages, ...renumber(own, stored.messages)];
1782
+ return {
1783
+ record: {
1784
+ ...view,
1785
+ createdAt: stored.createdAt,
1786
+ title: chatTitle(messages),
1787
+ messages,
1788
+ totalUsage: sumUsage(
1789
+ stored.totalUsage,
1790
+ own.map((m) => m.role === "assistant" ? m.usage : void 0)
1791
+ )
1792
+ },
1793
+ merged: true
1794
+ };
1795
+ };
1796
+ var saveChat = async (store, view, base) => {
1797
+ let merged = false;
1798
+ const record = await store.putMerged(view.id, (stored) => {
1799
+ const out = mergeChatRecord(view, stored, base);
1800
+ merged = out.merged;
1801
+ return out.record;
1802
+ });
1803
+ return { record, merged };
1804
+ };
1477
1805
  var useChatHistory = (agent, options = {}) => {
1478
1806
  const enabled = options.enabled !== false;
1479
1807
  const store = useMemo(() => options.store ?? new ChatHistoryStore(), [options.store]);
@@ -1482,6 +1810,8 @@ var useChatHistory = (agent, options = {}) => {
1482
1810
  const createdRef = useRef2(/* @__PURE__ */ new Map());
1483
1811
  const agentRef = useRef2(agent);
1484
1812
  agentRef.current = agent;
1813
+ const baseRef = useRef2(void 0);
1814
+ const staleRef = useRef2(void 0);
1485
1815
  const refresh = useCallback2(async () => {
1486
1816
  try {
1487
1817
  setChats(await store.list());
@@ -1496,6 +1826,7 @@ var useChatHistory = (agent, options = {}) => {
1496
1826
  const record = await store.get(id).catch(() => void 0);
1497
1827
  if (!record) return;
1498
1828
  createdRef.current.set(id, record.createdAt);
1829
+ baseRef.current = { id, known: new Set(record.messages), updatedAt: record.updatedAt };
1499
1830
  agentRef.current.loadChat({
1500
1831
  sessionId: record.id,
1501
1832
  messages: record.messages,
@@ -1528,13 +1859,43 @@ var useChatHistory = (agent, options = {}) => {
1528
1859
  active = false;
1529
1860
  };
1530
1861
  }, [enabled, store]);
1531
- const { messages, totalUsage, sessionId, isRunning } = agent;
1532
1862
  useEffect2(() => {
1533
- if (!enabled || loading || isRunning || messages.length === 0) return;
1863
+ if (!enabled) return;
1864
+ let openSaved;
1865
+ return followOtherTabs(
1866
+ core3,
1867
+ store.dbName,
1868
+ (change) => {
1869
+ if (change.kind !== "chats") return false;
1870
+ if (change.op === "put" && change.key === agentRef.current.sessionId) openSaved = change.key;
1871
+ return true;
1872
+ },
1873
+ () => {
1874
+ void refresh();
1875
+ const key = openSaved;
1876
+ openSaved = void 0;
1877
+ const current = agentRef.current;
1878
+ if (key === void 0 || key !== current.sessionId) return;
1879
+ if (current.remote?.running) staleRef.current = key;
1880
+ else if (!current.isRunning) void select(key);
1881
+ }
1882
+ );
1883
+ }, [enabled, store, refresh, select]);
1884
+ const { messages, totalUsage, sessionId, isRunning, remote } = agent;
1885
+ useEffect2(() => {
1886
+ if (!enabled || loading || isRunning) return;
1887
+ if (staleRef.current === sessionId) {
1888
+ staleRef.current = void 0;
1889
+ void select(sessionId);
1890
+ return;
1891
+ }
1892
+ if (remote || messages.length === 0) return;
1893
+ const base = baseRef.current?.id === sessionId ? baseRef.current : void 0;
1894
+ if (unchangedSince(messages, base)) return;
1534
1895
  const now = Date.now();
1535
1896
  const createdAt = createdRef.current.get(sessionId) ?? now;
1536
1897
  createdRef.current.set(sessionId, createdAt);
1537
- const record = {
1898
+ const view = {
1538
1899
  id: sessionId,
1539
1900
  title: chatTitle(messages),
1540
1901
  createdAt,
@@ -1542,14 +1903,24 @@ var useChatHistory = (agent, options = {}) => {
1542
1903
  messages,
1543
1904
  totalUsage
1544
1905
  };
1545
- void store.put(record).then(refresh).catch(() => {
1906
+ void (async () => {
1907
+ const { record, merged } = await saveChat(store, view, base);
1908
+ baseRef.current = {
1909
+ id: sessionId,
1910
+ known: new Set(merged ? record.messages : messages),
1911
+ updatedAt: record.updatedAt
1912
+ };
1913
+ await refresh();
1914
+ if (merged && agentRef.current.sessionId === sessionId) await select(sessionId);
1915
+ })().catch(() => {
1546
1916
  });
1547
- }, [enabled, loading, isRunning, messages, totalUsage, sessionId, store, refresh]);
1917
+ }, [enabled, loading, isRunning, remote, messages, totalUsage, sessionId, store, refresh, select]);
1548
1918
  return { chats, currentId: sessionId, loading, select, newChat, remove };
1549
1919
  };
1550
1920
 
1551
1921
  // src/hooks/use-virtual-files.ts
1552
1922
  import { useCallback as useCallback3, useEffect as useEffect3, useState as useState3 } from "react";
1923
+ import * as core4 from "@dudko.dev/agent-web";
1553
1924
  var readDataUrl = (file) => new Promise((resolve, reject) => {
1554
1925
  const r = new FileReader();
1555
1926
  r.onload = () => resolve(String(r.result));
@@ -1574,7 +1945,18 @@ var useVirtualFiles = (vfs, prefix = "/") => {
1574
1945
  useEffect3(() => {
1575
1946
  if (!vfs) return;
1576
1947
  void refresh();
1577
- return vfs.onChange(() => void refresh());
1948
+ const local = vfs.onChange(() => void refresh());
1949
+ const namespace = vfs.namespace;
1950
+ const remote = followOtherTabs(
1951
+ core4,
1952
+ vfs.dbName,
1953
+ (change) => change.kind === "files" && (!namespace || change.namespace === namespace),
1954
+ () => void refresh()
1955
+ );
1956
+ return () => {
1957
+ local();
1958
+ remote();
1959
+ };
1578
1960
  }, [vfs, refresh]);
1579
1961
  const upload = useCallback3(
1580
1962
  async (file, dir = "/uploads") => {
@@ -1670,11 +2052,25 @@ var useSpeechToText = (options = {}) => {
1670
2052
  };
1671
2053
 
1672
2054
  // src/hooks/use-credentials.ts
1673
- import { useCallback as useCallback5, useMemo as useMemo2, useState as useState5 } from "react";
2055
+ import { useCallback as useCallback5, useEffect as useEffect5, useMemo as useMemo2, useState as useState5 } from "react";
2056
+ import * as core5 from "@dudko.dev/agent-web";
1674
2057
  import { VaultCredentialStore } from "@dudko.dev/agent-web";
2058
+ var storeDbName = (store) => {
2059
+ const name = store?.dbName;
2060
+ return typeof name === "string" && name ? name : void 0;
2061
+ };
1675
2062
  var useCredentials = (store) => {
1676
2063
  const resolved = useMemo2(() => store ?? new VaultCredentialStore(), [store]);
1677
2064
  const [version, setVersion] = useState5(0);
2065
+ const dbName = storeDbName(resolved);
2066
+ useEffect5(() => {
2067
+ return followOtherTabs(
2068
+ core5,
2069
+ dbName,
2070
+ (change) => change.kind === "credentials",
2071
+ () => setVersion((v) => v + 1)
2072
+ );
2073
+ }, [dbName]);
1678
2074
  const setKey = useCallback5(
1679
2075
  async (ref, key) => {
1680
2076
  await resolved.setApiKey(ref, key);
@@ -2078,6 +2474,11 @@ var defaultLabels = {
2078
2474
  discardUndelivered: "Discard",
2079
2475
  stopSubagent: "Stop this subagent",
2080
2476
  subagentStopped: "stopped",
2477
+ remoteRunning: "Running in another tab: follow it here, write to it or stop it.",
2478
+ remoteWaitingConsent: "It waits for an answer in the other tab.",
2479
+ remoteGone: "The tab running this conversation closed before it finished.",
2480
+ sessionBusy: (heldBy) => heldBy === "this-tab" ? "Waiting for the other run of this conversation to finish\u2026" : "Waiting for the other tab to finish this conversation\u2026",
2481
+ fromAnotherTab: "from another tab",
2081
2482
  failed: "failed",
2082
2483
  toolCostTitle: "Estimated tokens of the arguments and of the result fed back to the model (chars / 4), and the call's duration",
2083
2484
  tierNames: { light: "light", standard: "standard", strong: "strong" },
@@ -2396,11 +2797,11 @@ var useAgentContext = () => {
2396
2797
  var useOptionalAgentContext = () => useContext2(AgentContext);
2397
2798
 
2398
2799
  // src/components/AgentChat.tsx
2399
- import { useEffect as useEffect13, useRef as useRef9, useState as useState15 } from "react";
2800
+ import { useEffect as useEffect14, useRef as useRef9, useState as useState15 } from "react";
2400
2801
  import { createPortal } from "react-dom";
2401
2802
 
2402
2803
  // src/hooks/use-mcp-app-host.ts
2403
- import { useCallback as useCallback7, useEffect as useEffect5, useMemo as useMemo4, useRef as useRef5, useState as useState7 } from "react";
2804
+ import { useCallback as useCallback7, useEffect as useEffect6, useMemo as useMemo4, useRef as useRef5, useState as useState7 } from "react";
2404
2805
 
2405
2806
  // src/mcp-app.ts
2406
2807
  import { mcpAppOrigin } from "@dudko.dev/agent-web";
@@ -3240,7 +3641,7 @@ var useMcpAppHost = ({
3240
3641
  connectionRef.current = connection;
3241
3642
  const approveRef = useRef5(approve);
3242
3643
  approveRef.current = approve;
3243
- useEffect5(
3644
+ useEffect6(
3244
3645
  () => () => {
3245
3646
  for (const { resolve } of waiting.current.values()) resolve(false);
3246
3647
  waiting.current.clear();
@@ -3571,11 +3972,11 @@ var AppRequestPrompt = ({
3571
3972
  };
3572
3973
 
3573
3974
  // src/components/McpAppFrame.tsx
3574
- import { useEffect as useEffect6, useLayoutEffect, useMemo as useMemo5, useRef as useRef6, useState as useState8 } from "react";
3975
+ import { useEffect as useEffect7, useLayoutEffect, useMemo as useMemo5, useRef as useRef6, useState as useState8 } from "react";
3575
3976
  import { Fragment, jsx as jsx4, jsxs as jsxs2 } from "react/jsx-runtime";
3576
3977
  var HOST_INFO = { name: "@dudko.dev/agent-web-react", version: "1" };
3577
3978
  var MAX_LISTED_CALLS = 12;
3578
- var useIsoLayoutEffect = typeof window === "undefined" ? useEffect6 : useLayoutEffect;
3979
+ var useIsoLayoutEffect = typeof window === "undefined" ? useEffect7 : useLayoutEffect;
3579
3980
  var userActivation = () => typeof navigator === "undefined" ? void 0 : navigator.userActivation?.isActive;
3580
3981
  var silentSandboxes = /* @__PURE__ */ new Set();
3581
3982
  var warned = /* @__PURE__ */ new Set();
@@ -3637,7 +4038,7 @@ var McpAppFrame = ({
3637
4038
  const appRef = useRef6(app);
3638
4039
  appRef.current = app;
3639
4040
  const live = !collapsed;
3640
- useEffect6(() => {
4041
+ useEffect7(() => {
3641
4042
  if (!live) return;
3642
4043
  if (!hostRef.current.connected) {
3643
4044
  setLoaded({ unavailable: true });
@@ -3675,7 +4076,7 @@ var McpAppFrame = ({
3675
4076
  () => !resource || !placement ? void 0 : placement.mode === "origin" ? buildMcpAppSandboxShell(placement.url) : buildMcpAppDocument(resource.html, resource.csp),
3676
4077
  [resource, placement]
3677
4078
  );
3678
- useEffect6(() => {
4079
+ useEffect7(() => {
3679
4080
  const reason = placement?.mode === "opaque" ? placement.reason : void 0;
3680
4081
  if (reason && reason !== "no-answer" && sandboxUrl !== void 0) {
3681
4082
  warnOnce(
@@ -3684,7 +4085,7 @@ var McpAppFrame = ({
3684
4085
  );
3685
4086
  }
3686
4087
  }, [placement, sandboxUrl]);
3687
- useEffect6(() => {
4088
+ useEffect7(() => {
3688
4089
  const frame = iframeRef.current;
3689
4090
  if (!live || !resource || !frame || !placement || broken) return;
3690
4091
  const abort = new AbortController();
@@ -3829,7 +4230,7 @@ var McpAppFrame = ({
3829
4230
  }, [live, resource, reload, variant, app.id, placement, broken, timeoutMs]);
3830
4231
  const fullscreen = mode === "fullscreen" && live && !broken;
3831
4232
  const waitingNow = host.isWaiting(app);
3832
- useEffect6(() => {
4233
+ useEffect7(() => {
3833
4234
  if (fullscreen && waitingNow) leaveRef.current?.();
3834
4235
  }, [fullscreen, waitingNow]);
3835
4236
  useIsoLayoutEffect(() => {
@@ -3864,7 +4265,7 @@ var McpAppFrame = ({
3864
4265
  ro?.disconnect();
3865
4266
  };
3866
4267
  }, [fullscreen]);
3867
- useEffect6(() => {
4268
+ useEffect7(() => {
3868
4269
  if (!fullscreen) return;
3869
4270
  const before = document.activeElement;
3870
4271
  exitRef.current?.focus();
@@ -3881,10 +4282,10 @@ var McpAppFrame = ({
3881
4282
  if (frame && (before === frame || document.activeElement === document.body)) frame.focus();
3882
4283
  };
3883
4284
  }, [fullscreen]);
3884
- useEffect6(() => {
4285
+ useEffect7(() => {
3885
4286
  if (theme) bridgeRef.current?.updateContext({ theme });
3886
4287
  }, [theme]);
3887
- useEffect6(() => {
4288
+ useEffect7(() => {
3888
4289
  if (!menu) return;
3889
4290
  const close = (e) => {
3890
4291
  if (e instanceof KeyboardEvent ? e.key === "Escape" : !menuRef.current?.contains(e.target)) {
@@ -4189,7 +4590,7 @@ var McpAppLine = ({ app, note, action, onAction, labels, className }) => {
4189
4590
  };
4190
4591
 
4191
4592
  // src/components/AgentComposer.tsx
4192
- import { useEffect as useEffect7, useLayoutEffect as useLayoutEffect2, useMemo as useMemo6, useRef as useRef7, useState as useState9 } from "react";
4593
+ import { useEffect as useEffect8, useLayoutEffect as useLayoutEffect2, useMemo as useMemo6, useRef as useRef7, useState as useState9 } from "react";
4193
4594
  import { Fragment as Fragment2, jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
4194
4595
  var thinkingDefaults = (l) => [
4195
4596
  { id: "off", label: l.thinkingLevels.off },
@@ -4201,7 +4602,7 @@ var thinkingDefaults = (l) => [
4201
4602
  var MODES = ["autopilot", "ask-writes", "ask-all", "read-only"];
4202
4603
  var ModeIcon = ({ mode }) => mode === "autopilot" ? /* @__PURE__ */ jsx5(BoltIcon, { size: 14 }) : mode === "read-only" ? /* @__PURE__ */ jsx5(EyeIcon, { size: 14 }) : /* @__PURE__ */ jsx5(ShieldIcon, { size: 14 });
4203
4604
  var attachSeq = 0;
4204
- var useIsoLayoutEffect2 = typeof window === "undefined" ? useEffect7 : useLayoutEffect2;
4605
+ var useIsoLayoutEffect2 = typeof window === "undefined" ? useEffect8 : useLayoutEffect2;
4205
4606
  var useMenuPlacement = (open, anchor, align) => {
4206
4607
  const [style, setStyle] = useState9();
4207
4608
  useIsoLayoutEffect2(() => {
@@ -4293,7 +4694,7 @@ var AgentComposer = ({
4293
4694
  const modeRef = useRef7(null);
4294
4695
  const [dropRect, setDropRect] = useState9();
4295
4696
  const [compactBar, setCompactBar] = useState9(false);
4296
- useEffect7(() => {
4697
+ useEffect8(() => {
4297
4698
  const el = rootRef.current;
4298
4699
  if (!el || typeof ResizeObserver === "undefined") return;
4299
4700
  const ro = new ResizeObserver(
@@ -4306,13 +4707,16 @@ var AgentComposer = ({
4306
4707
  const inputRef = useRef7(null);
4307
4708
  const draftId = draft?.id;
4308
4709
  const draftText = draft?.text;
4309
- useEffect7(() => {
4710
+ useEffect8(() => {
4310
4711
  if (draftId === void 0 || !draftText) return;
4311
4712
  setText((t) => t.trim() ? `${t.trimEnd()}
4312
4713
  ${draftText}` : draftText);
4313
4714
  inputRef.current?.focus();
4314
4715
  }, [draftId, draftText]);
4315
4716
  const busy = agent.isRunning;
4717
+ const following = !!agent.remote?.running && !agent.sessionBusy;
4718
+ const steerTo = following ? agent.sendRemote : agent.send;
4719
+ const stopIt = following ? agent.stopRemote : agent.stop;
4316
4720
  const ready = agent.isReady && !disabled;
4317
4721
  const caps = agent.agent?.capabilities;
4318
4722
  const stt = useSpeechToText({
@@ -4323,7 +4727,7 @@ ${draftText}` : draftText);
4323
4727
  const [startedAt, setStartedAt] = useState9();
4324
4728
  const [now, setNow] = useState9(() => Date.now());
4325
4729
  const [lastElapsed, setLastElapsed] = useState9();
4326
- useEffect7(() => {
4730
+ useEffect8(() => {
4327
4731
  if (!busy) {
4328
4732
  if (startedAt !== void 0) setLastElapsed(Date.now() - startedAt);
4329
4733
  setStartedAt(void 0);
@@ -4356,7 +4760,7 @@ ${draftText}` : draftText);
4356
4760
  name: "stop",
4357
4761
  description: L.commandDescriptions.stop,
4358
4762
  group: L.commandGroups.commands,
4359
- run: agent.stop
4763
+ run: stopIt
4360
4764
  },
4361
4765
  {
4362
4766
  name: "autopilot",
@@ -4408,7 +4812,7 @@ ${draftText}` : draftText);
4408
4812
  }
4409
4813
  }
4410
4814
  return [...out, ...commands];
4411
- }, [agent, builtinCommands, skillCommands, commands, thinking, L]);
4815
+ }, [agent, stopIt, builtinCommands, skillCommands, commands, thinking, L]);
4412
4816
  const slash = parseSlash(text);
4413
4817
  const matches = slash && !/\s/.test(text.trimStart()) ? filterCommands(allCommands, slash.name) : [];
4414
4818
  const palette = menu === "commands" && !slash ? allCommands : matches;
@@ -4416,8 +4820,8 @@ ${draftText}` : draftText);
4416
4820
  const commandsStyle = useMenuPlacement(paletteOpen, rootRef, "stretch");
4417
4821
  const modelStyle = useMenuPlacement(menu === "model", modelRef, "left");
4418
4822
  const modeStyle = useMenuPlacement(menu === "mode", modeRef, "right");
4419
- useEffect7(() => setActive(0), [text, menu]);
4420
- useEffect7(() => {
4823
+ useEffect8(() => setActive(0), [text, menu]);
4824
+ useEffect8(() => {
4421
4825
  if (!menu) return;
4422
4826
  const onDown = (e) => {
4423
4827
  if (!rootRef.current?.contains(e.target)) setMenu(void 0);
@@ -4512,7 +4916,7 @@ ${draftText}` : draftText);
4512
4916
  };
4513
4917
  const addFilesRef = useRef7(addFiles);
4514
4918
  addFilesRef.current = addFiles;
4515
- useEffect7(() => {
4919
+ useEffect8(() => {
4516
4920
  if (attachments === false) return;
4517
4921
  const target = dropZone === "window" ? globalThis.window : dropZone === "self" ? rootRef.current : dropZone.current;
4518
4922
  if (!target) return;
@@ -4582,7 +4986,7 @@ ${draftText}` : draftText);
4582
4986
  const raw = text.trim();
4583
4987
  const intent = steerIntent({ raw, busy, steering, hasAttachments: pending.length > 0 });
4584
4988
  if (intent === "steer") {
4585
- if (agent.send(raw)) setText("");
4989
+ if (steerTo(raw)) setText("");
4586
4990
  return;
4587
4991
  }
4588
4992
  if (intent === "attachments") {
@@ -4693,6 +5097,7 @@ ${draftText}` : draftText);
4693
5097
  agent.queued.map((q) => /* @__PURE__ */ jsxs3("div", { className: "awr-queued__item", role: "status", children: [
4694
5098
  /* @__PURE__ */ jsx5(ClockIcon, { size: 13, className: "awr-queued__icon" }),
4695
5099
  /* @__PURE__ */ jsx5("span", { className: "awr-queued__text", title: q.text, children: q.text }),
5100
+ q.origin === "another-tab" && /* @__PURE__ */ jsx5("span", { className: "awr-queued__origin", children: L.fromAnotherTab }),
4696
5101
  /* @__PURE__ */ jsx5("span", { className: "awr-queued__state", children: L.queuedWaiting })
4697
5102
  ] }, q.id)),
4698
5103
  agent.undelivered.length > 0 && /* @__PURE__ */ jsxs3("div", { className: "awr-queued__item awr-queued__item--undelivered", role: "status", children: [
@@ -4974,7 +5379,7 @@ ${draftText}` : draftText);
4974
5379
  {
4975
5380
  type: "button",
4976
5381
  className: "awr-sendbtn awr-sendbtn--stop",
4977
- onClick: agent.stop,
5382
+ onClick: stopIt,
4978
5383
  "aria-label": L.stop,
4979
5384
  children: /* @__PURE__ */ jsx5(StopIcon, { size: 16 })
4980
5385
  }
@@ -5150,7 +5555,7 @@ var ContextMeter = ({
5150
5555
  };
5151
5556
 
5152
5557
  // src/components/ElicitationPrompt.tsx
5153
- import { useEffect as useEffect8, useId, useState as useState10 } from "react";
5558
+ import { useEffect as useEffect9, useId, useState as useState10 } from "react";
5154
5559
  import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
5155
5560
  var reasonText = (outcome, L) => {
5156
5561
  const reason = outcome.reason;
@@ -5161,7 +5566,7 @@ var reasonText = (outcome, L) => {
5161
5566
  };
5162
5567
  var useNow = (active) => {
5163
5568
  const [now, setNow] = useState10(() => Date.now());
5164
- useEffect8(() => {
5569
+ useEffect9(() => {
5165
5570
  if (!active) return;
5166
5571
  setNow(Date.now());
5167
5572
  const timer = setInterval(() => setNow(Date.now()), 1e3);
@@ -5473,7 +5878,7 @@ var ElicitationPrompt = ({
5473
5878
  };
5474
5879
 
5475
5880
  // src/components/FilesPanel.tsx
5476
- import { Fragment as Fragment4, useEffect as useEffect9, useRef as useRef8, useState as useState11 } from "react";
5881
+ import { Fragment as Fragment4, useEffect as useEffect10, useRef as useRef8, useState as useState11 } from "react";
5477
5882
  import { Fragment as Fragment5, jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
5478
5883
  var PREVIEW_CHARS = 2e4;
5479
5884
  var FilesPanel = ({
@@ -5492,7 +5897,7 @@ var FilesPanel = ({
5492
5897
  const fs = useVirtualFiles(vfs, prefix);
5493
5898
  const [preview, setPreview] = useState11();
5494
5899
  const inputRef = useRef8(null);
5495
- useEffect9(() => {
5900
+ useEffect10(() => {
5496
5901
  if (preview && !fs.files.some((f) => f.path === preview.path)) setPreview(void 0);
5497
5902
  }, [fs.files, preview]);
5498
5903
  const open = async (f) => {
@@ -5601,7 +6006,7 @@ var FilesPanel = ({
5601
6006
  };
5602
6007
 
5603
6008
  // src/components/FileChips.tsx
5604
- import { Fragment as Fragment6, useEffect as useEffect11, useMemo as useMemo7, useState as useState13 } from "react";
6009
+ import { Fragment as Fragment6, useEffect as useEffect12, useMemo as useMemo7, useState as useState13 } from "react";
5605
6010
 
5606
6011
  // src/file-kinds.ts
5607
6012
  import { MEDIA_IMAGE_TYPES, isTextMime } from "@dudko.dev/agent-web";
@@ -5622,7 +6027,7 @@ var fileKindOf = (path, mediaType) => {
5622
6027
  var fileNameOf = (path) => path.split("/").filter(Boolean).pop() || "file";
5623
6028
 
5624
6029
  // src/components/Media.tsx
5625
- import { useEffect as useEffect10, useState as useState12 } from "react";
6030
+ import { useEffect as useEffect11, useState as useState12 } from "react";
5626
6031
  import { MEDIA_AUDIO_TYPES, MEDIA_IMAGE_TYPES as MEDIA_IMAGE_TYPES2 } from "@dudko.dev/agent-web";
5627
6032
  import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
5628
6033
  var mediaFamilyOf = (mediaType) => {
@@ -5640,7 +6045,7 @@ var bytesOf = (content, encoding) => {
5640
6045
  };
5641
6046
  var useFileUrl = (files, path, mediaType) => {
5642
6047
  const [url, setUrl] = useState12(void 0);
5643
- useEffect10(() => {
6048
+ useEffect11(() => {
5644
6049
  if (!files || !mediaType) return;
5645
6050
  let made;
5646
6051
  let gone = false;
@@ -5998,7 +6403,7 @@ var FileChips = ({
5998
6403
  const [file, setFile] = useState13();
5999
6404
  const open = written.find((f) => f.path === openPath);
6000
6405
  const stamp = live.files.find((f) => f.path === openPath)?.updatedAt;
6001
- useEffect11(() => {
6406
+ useEffect12(() => {
6002
6407
  if (!vfs || !openPath) return setFile(void 0);
6003
6408
  let gone = false;
6004
6409
  vfs.read(openPath).then((f) => {
@@ -6124,11 +6529,11 @@ var FileChip = ({
6124
6529
  import { Fragment as Fragment9 } from "react";
6125
6530
 
6126
6531
  // src/components/SubagentTree.tsx
6127
- import { Fragment as Fragment8, useEffect as useEffect12, useState as useState14 } from "react";
6532
+ import { Fragment as Fragment8, useEffect as useEffect13, useState as useState14 } from "react";
6128
6533
  import { jsx as jsx13, jsxs as jsxs11 } from "react/jsx-runtime";
6129
6534
  var useElapsed = (startedAt, running) => {
6130
6535
  const [now, setNow] = useState14(void 0);
6131
- useEffect12(() => {
6536
+ useEffect13(() => {
6132
6537
  if (!running || startedAt === void 0) return;
6133
6538
  setNow(Date.now());
6134
6539
  const timer = setInterval(() => setNow(Date.now()), 1e3);
@@ -6308,7 +6713,8 @@ var UserNoteRow = ({
6308
6713
  return /* @__PURE__ */ jsxs12("li", { className: `awr-note awr-note--${note.at}`, children: [
6309
6714
  /* @__PURE__ */ jsx14(SendIcon, { size: 12, className: "awr-note__icon" }),
6310
6715
  /* @__PURE__ */ jsx14("span", { className: "awr-note__where", children: L.noteAt[note.at] }),
6311
- /* @__PURE__ */ jsx14("q", { className: "awr-note__text", children: note.text })
6716
+ /* @__PURE__ */ jsx14("q", { className: "awr-note__text", children: note.text }),
6717
+ note.origin === "another-tab" && /* @__PURE__ */ jsx14("span", { className: "awr-note__origin", children: L.fromAnotherTab })
6312
6718
  ] });
6313
6719
  };
6314
6720
  var decisionNote = (d, L) => {
@@ -6868,7 +7274,7 @@ var usePrefersDark = () => {
6868
7274
  const [dark, setDark] = useState15(
6869
7275
  () => typeof matchMedia === "function" && matchMedia(query).matches
6870
7276
  );
6871
- useEffect13(() => {
7277
+ useEffect14(() => {
6872
7278
  if (typeof matchMedia !== "function") return;
6873
7279
  const mq = matchMedia(query);
6874
7280
  const on = () => setDark(mq.matches);
@@ -6908,6 +7314,7 @@ var AgentChatInner = ({
6908
7314
  activityOpen = false,
6909
7315
  showElicitation = true,
6910
7316
  showSkillPreview = true,
7317
+ showOtherTabs = true,
6911
7318
  elicitations,
6912
7319
  onElicitationAnswer,
6913
7320
  renderElicitation,
@@ -6963,7 +7370,7 @@ var AgentChatInner = ({
6963
7370
  const chats = history ? external ?? own : void 0;
6964
7371
  const rootRef = useRef9(null);
6965
7372
  const [narrow, setNarrow] = useState15(void 0);
6966
- useEffect13(() => {
7373
+ useEffect14(() => {
6967
7374
  const el = rootRef.current;
6968
7375
  if (!el || typeof ResizeObserver === "undefined") return setNarrow(false);
6969
7376
  const measure = () => setNarrow(el.getBoundingClientRect().width < narrowWidth);
@@ -6989,7 +7396,7 @@ var AgentChatInner = ({
6989
7396
  };
6990
7397
  const bodyRef = useRef9(null);
6991
7398
  const stickRef = useRef9(true);
6992
- useEffect13(() => {
7399
+ useEffect14(() => {
6993
7400
  const el = bodyRef.current;
6994
7401
  if (el && stickRef.current) el.scrollTop = el.scrollHeight;
6995
7402
  }, [
@@ -7020,7 +7427,7 @@ var AgentChatInner = ({
7020
7427
  const panelAllowed = appPanel !== false && appPanel !== null;
7021
7428
  const panelTarget = typeof appPanel === "object" && appPanel ? appPanel : void 0;
7022
7429
  const asSheet = !panelTarget && (appPanel === "sheet" || Boolean(narrow));
7023
- useEffect13(() => {
7430
+ useEffect14(() => {
7024
7431
  if (panelApp && !agent.messages.some((m) => m.apps?.some((a) => a.id === panelApp.id))) {
7025
7432
  setPanelAppState(void 0);
7026
7433
  onAppPanel?.(void 0);
@@ -7071,6 +7478,12 @@ var AgentChatInner = ({
7071
7478
  const Files = components.FilesPanel ?? FilesPanel;
7072
7479
  const Approvals = components.ApprovalPrompt ?? ToolApprovalPrompt;
7073
7480
  const Elicitations = components.ElicitationPrompt ?? ElicitationPrompt;
7481
+ const tabNotes = showOtherTabs ? [
7482
+ agent.remote?.running && L.remoteRunning,
7483
+ agent.remote?.running && agent.approvals.some((a) => a.remote && a.status === "pending") && L.remoteWaitingConsent,
7484
+ agent.remote?.ended === "gone" && L.remoteGone,
7485
+ agent.sessionBusy && L.sessionBusy(agent.sessionBusy.heldBy)
7486
+ ].filter((t) => typeof t === "string") : [];
7074
7487
  const loading = agent.modelLoad && agent.modelLoad.progress < 1;
7075
7488
  const showReplan = agent.replan && agent.replan.mode !== "continue";
7076
7489
  const replanFailedEarly = showReplanFailed && agent.replan?.failed === true && agent.steps.length === 0;
@@ -7251,6 +7664,7 @@ var AgentChatInner = ({
7251
7664
  ),
7252
7665
  /* @__PURE__ */ jsxs17("div", { className: cx("awr-chat__footer", classNames.footer), children: [
7253
7666
  slots.footerStart,
7667
+ tabNotes.length > 0 && /* @__PURE__ */ jsx18("div", { className: "awr-tabnote", role: "status", children: tabNotes.map((text) => /* @__PURE__ */ jsx18("p", { className: "awr-tabnote__text", children: text }, text)) }),
7254
7668
  showContext !== false && /* @__PURE__ */ jsx18(
7255
7669
  ContextMeter,
7256
7670
  {
@@ -7500,7 +7914,7 @@ var ApprovalModeSwitch = ({
7500
7914
  );
7501
7915
 
7502
7916
  // src/components/ApiKeyForm.tsx
7503
- import { useEffect as useEffect14, useState as useState17 } from "react";
7917
+ import { useEffect as useEffect15, useState as useState17 } from "react";
7504
7918
  import { jsx as jsx23, jsxs as jsxs21 } from "react/jsx-runtime";
7505
7919
  var ApiKeyForm = ({
7506
7920
  credentials,
@@ -7513,7 +7927,7 @@ var ApiKeyForm = ({
7513
7927
  const [value, setValue] = useState17("");
7514
7928
  const [present, setPresent] = useState17(false);
7515
7929
  const [busy, setBusy] = useState17(false);
7516
- useEffect14(() => {
7930
+ useEffect15(() => {
7517
7931
  let active = true;
7518
7932
  credentials.hasKey(credentialRef).then((has) => {
7519
7933
  if (active) setPresent(has);
@@ -7622,7 +8036,11 @@ import {
7622
8036
  AttachmentsNotSupportedError,
7623
8037
  ImagesNotSupportedError,
7624
8038
  supportsImages,
7625
- supportsPdf
8039
+ supportsPdf,
8040
+ onStorageChange,
8041
+ postStorageChange as postStorageChange2,
8042
+ watchSession as watchSession2,
8043
+ SessionBusyError
7626
8044
  } from "@dudko.dev/agent-web";
7627
8045
  export {
7628
8046
  APP_DEFAULT_HEIGHT,
@@ -7687,6 +8105,7 @@ export {
7687
8105
  ModelLoadBar,
7688
8106
  PlanView,
7689
8107
  SandboxedFrame,
8108
+ SessionBusyError,
7690
8109
  SourceView,
7691
8110
  StepList,
7692
8111
  SubagentRow,
@@ -7700,6 +8119,7 @@ export {
7700
8119
  VfsSkillStore,
7701
8120
  VirtualFileSystem,
7702
8121
  agentStateReducer,
8122
+ agentStatusOf,
7703
8123
  appDisplayModeAllowed,
7704
8124
  appDownloadOf,
7705
8125
  appDownloadRefusal,
@@ -7755,22 +8175,28 @@ export {
7755
8175
  mcpAppSandboxShellCsp,
7756
8176
  mcpAppSandboxTarget,
7757
8177
  mediaFamilyOf,
8178
+ mergeChatRecord,
7758
8179
  mergeLabels,
7759
8180
  newChatId,
7760
8181
  noticesOf,
8182
+ onStorageChange,
7761
8183
  parseSkillMarkdown,
7762
8184
  parseSlash,
8185
+ pendingApprovalsOf,
8186
+ postStorageChange2 as postStorageChange,
7763
8187
  preloadWebLLMModel2 as preloadWebLLMModel,
7764
8188
  resolveAppDownload,
7765
8189
  sandboxTokens,
7766
8190
  sandboxedCsp,
7767
8191
  saveAppFile,
8192
+ saveChat,
7768
8193
  serveSubagentWorker,
7769
8194
  steerIntent,
7770
8195
  subagentTree,
7771
8196
  supportsImages,
7772
8197
  supportsPdf,
7773
8198
  tokenizeHtml,
8199
+ unchangedSince,
7774
8200
  unloadWebLLMModel2 as unloadWebLLMModel,
7775
8201
  usageLine,
7776
8202
  useAgent,
@@ -7784,6 +8210,7 @@ export {
7784
8210
  useSpeechToText,
7785
8211
  useVirtualFiles,
7786
8212
  useWebLLMModel,
8213
+ watchSession2 as watchSession,
7787
8214
  webSearchOf,
7788
8215
  withAttachments,
7789
8216
  withCspFirst,