@kadaliao/dsh-bots 0.9.0 → 0.10.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.
package/client.js CHANGED
@@ -20,6 +20,10 @@ window.__ModuleLoader__.load({
20
20
 
21
21
  const NS = 'bots';
22
22
  const PANEL_ID = 'bots';
23
+ /** The Bots this page is (package.json): the Host says which one it runs, and a stale Host is pointed out. */
24
+ const BOTS_VERSION = '0.10.0';
25
+ /** How close to a new topic Harness closing the panel counts as caused by it (it archived the conversation behind). */
26
+ const ROTATE_WINDOW_MS = 3000;
23
27
  const R = '/__dsh_bots/';
24
28
  const STATE_POLL_MS = 5000;
25
29
  /** While a bot works (or a picture is being drawn), its live status is polled this often (`activity`, a small answer). */
@@ -799,23 +803,20 @@ button.dshb-tline:hover{background:${C.hover}}
799
803
  .dshb-msg-act:hover{color:${C.primary};background:${C.hover}}
800
804
  .dshb-msg-actbox{position:absolute;top:0;right:0;z-index:1}
801
805
  @media (hover:none){.dshb-msg-act{opacity:.65}}
802
- .dshb-topicbar{display:flex;flex-direction:column;gap:5px;width:min(520px,100%);min-width:0;padding:8px 11px;border:1px solid ${C.border1};border-radius:11px;background:${C.layer1};font-size:${SMALL};cursor:pointer;text-align:left;transition:border-color .12s,background .12s}
803
- .dshb-topicbar:hover{border-color:${C.border};background:${C.layer2}}
804
- .dshb-topicbar:focus-visible{outline:2px solid ${C.label};outline-offset:1px}
805
- .dshb-topicbar[data-unread=true]{border-color:${tint(C.label, 45)}}
806
- .dshb-topicbar[data-flash=true]{animation:dshb-flash 1.8s ease-out}
807
- .dshb-topictask{display:flex;align-items:center;gap:6px;width:100%;min-width:0;min-height:26px;padding:2px 6px;border:none;border-radius:7px;background:${C.base};color:${C.primary};font:inherit;font-size:${TINY};text-align:left;cursor:pointer}
808
- .dshb-topictask:hover{background:${C.hover}}
809
- .dshb-moved{display:inline-flex;align-items:center;gap:6px;max-width:min(520px,100%);min-width:0;font-size:${TINY};color:${C.muted}}
810
- .dshb-moved:hover{color:${C.label}}
811
- .dshb-pillrow{position:absolute;left:0;right:0;top:-42px;display:flex;justify-content:center;pointer-events:none;z-index:2}
812
- .dshb-pill{pointer-events:auto;display:inline-flex;align-items:center;gap:7px;height:30px;padding:0 13px;border-radius:999px;border:1px solid ${C.border};background:${C.base};color:${C.primary};font:inherit;font-size:${SMALL};font-weight:600;cursor:pointer;box-shadow:0 4px 14px rgba(0,0,0,.14);max-width:calc(100% - 32px);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
813
- .dshb-pill:hover{background:${C.layer2}}
806
+ .dshb-threadbar{display:inline-flex;align-items:center;gap:5px;max-width:100%;height:24px;padding:0 9px;border:none;border-radius:999px;background:${tint(C.label, 8)};color:${C.label};font:inherit;font-size:${TINY};font-weight:600;cursor:pointer;white-space:nowrap;transition:background .12s}
807
+ .dshb-threadbar:hover{background:${tint(C.label, 15)}}
808
+ .dshb-threadbar:focus-visible{outline:2px solid ${C.label};outline-offset:1px}
809
+ .dshb-qline{display:block;width:100%;min-width:0;margin:0;padding:1px 0 1px 8px;border:none;border-left:2px solid ${C.border};background:transparent;color:${C.muted};font:inherit;font-size:${TINY};line-height:1.5;text-align:left;word-break:break-word}
810
+ button.dshb-qline{cursor:pointer}
811
+ button.dshb-qline:hover{color:${C.primary};border-left-color:${C.label}}
812
+ .dshb-qline-light{color:inherit;opacity:.75;border-left-color:currentColor}
813
+ button.dshb-qline-light:hover{color:inherit;opacity:1}
814
+ .dshb-threaddiv{display:flex;align-items:center;gap:10px;margin:8px 0 2px;color:${C.faint};font-size:${TINY}}
815
+ .dshb-threaddiv-line{flex:1;height:1px;background:${C.border1}}
814
816
  .dshb-threadpane{width:420px;flex:none;display:flex;flex-direction:column;min-height:0;min-width:0;border-left:1px solid ${C.border1};background:${C.base}}
815
817
  .dshb-threadhead{display:flex;align-items:center;gap:10px;padding:12px 12px 10px 16px;border-bottom:1px solid ${C.border1};min-width:0}
816
818
  @container (max-width: 860px){.dshb-threadpane{position:absolute;inset:0;width:auto;z-index:6;border-left:none}}
817
819
  @media (max-width: 760px){.dshb-threadpane{position:absolute;inset:0;width:auto;z-index:6;border-left:none}}
818
- @keyframes dshb-flash{0%{box-shadow:0 0 0 3px ${tint(C.label, 50)}}100%{box-shadow:0 0 0 0 ${tint(C.label, 0)}}}
819
820
  @keyframes dshb-breathe{0%{box-shadow:0 0 0 0 ${tint(C.ok, 45)}}70%{box-shadow:0 0 0 5px ${tint(C.ok, 0)}}100%{box-shadow:0 0 0 0 ${tint(C.ok, 0)}}}
820
821
  @keyframes dshb-pulse{0%{box-shadow:0 0 0 0 rgba(34,197,94,.6)}70%{box-shadow:0 0 0 5px rgba(34,197,94,0)}100%{box-shadow:0 0 0 0 rgba(34,197,94,0)}}
821
822
  @keyframes dshb-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
@@ -1348,16 +1349,16 @@ button.dshb-tline:hover{background:${C.hover}}
1348
1349
 
1349
1350
  /**
1350
1351
  * A thread of one bot: the user's prompts right, the bot's replies left, DMs as cards. With `fold`
1351
- * (the main timeline of a chat with topics), replies inside a topic are not listed: each root gets its
1352
- * topic bar instead (`topic` props: `{index, topics, onOpen, unread, flash}`).
1352
+ * (a chat as it was said), a message with a thread gets a link to it under it (`fold`: `{index, onOpen}`).
1353
+ * `quoteOf(m, prev)`: the message `m` quotes, shown on top of it (null for none); `onQuote(m)` opens it.
1353
1354
  */
1354
- function MessageList({ t, items, botId, empty, fold = null, onReply, onRetry, movedIn }) {
1355
+ function MessageList({ t, items, botId, empty, fold = null, onReply, onRetry, movedIn, quoteOf, onQuote }) {
1355
1356
  const count = items.length;
1356
1357
  if (count === 0) return empty;
1357
1358
  const names = threadNamesOf(items);
1358
1359
  const rows = [];
1359
1360
  let lastDay = '';
1360
- const shown = fold ? fold.index.main : items;
1361
+ const shown = (fold ? fold.index.main : items).filter((m) => !selfTalk(m));
1361
1362
  shown.forEach((m, i) => {
1362
1363
  const at = toMs(m.at);
1363
1364
  let day = '';
@@ -1392,15 +1393,14 @@ button.dshb-tline:hover{background:${C.hover}}
1392
1393
  return;
1393
1394
  }
1394
1395
  const prev = shown[i - 1];
1395
- // A root with its topic bar under it ends a run: the next message starts with its own header.
1396
- const prevBar = fold && prev && fold.index.roots.has(prev.id) && topicBarShows(fold, prev.id);
1397
- // Answers to two chats of one turn keep their own headers (where each went), and so do two tasks.
1398
- const grouped = !prevBar && prev && !isTraffic(prev) && prev.from === m.from && prev.to === m.to && prev.kind === m.kind && prev.via === m.via && prev.thread === m.thread && messageTicket(prev) === messageTicket(m) && at - toMs(prev.at) < 5 * 60_000;
1399
- rows.push(h(MessageRow, { key: m.id ?? i, t, m, botId, grouped, names, onReply, onRetry, moved: movedIn ? movedIn(m) : false }));
1400
- if (fold && fold.index.roots.has(m.id)) {
1401
- const bar = m.movedTo ? h(MovedBar, { key: `mv${m.id}`, t, m, fold }) : topicBarShows(fold, m.id) ? h(TopicBar, { key: `tb${m.id}`, t, m, fold }) : null;
1402
- if (bar) rows.push(bar);
1403
- }
1396
+ // A message with its thread bar under it ends a run: the next message starts with its own header.
1397
+ const prevBar = fold && prev && threadBarShows(fold, prev.id);
1398
+ // A reply in a thread quotes the message it answers, unless that is the thread's message just above.
1399
+ const quote = quoteOf ? quoteOf(m, prev) : null;
1400
+ // Answers to two chats of one turn keep their own headers (where each went), and so do two tasks; a quoted reply starts a run.
1401
+ const grouped = !quote && !prevBar && prev && !isTraffic(prev) && prev.from === m.from && prev.to === m.to && prev.kind === m.kind && prev.via === m.via && prev.thread === m.thread && messageTicket(prev) === messageTicket(m) && at - toMs(prev.at) < 5 * 60_000;
1402
+ rows.push(h(MessageRow, { key: m.id ?? i, t, m, botId, grouped, names, onReply, onRetry, moved: movedIn ? movedIn(m) : false, quote, onQuote }));
1403
+ if (fold && threadBarShows(fold, m.id)) rows.push(h(ThreadBar, { key: `tb${m.id}`, t, m, fold }));
1404
1404
  });
1405
1405
  const level = botMessagesLevel();
1406
1406
  return h(
@@ -1409,117 +1409,63 @@ button.dshb-tline:hover{background:${C.hover}}
1409
1409
  rows.map((r) => (r && r.traffic ? h(BotTraffic, { key: r.key, t, items: r.items, level }) : r)),
1410
1410
  );
1411
1411
  }
1412
- /** The tasks of a topic (the Host's TicketRows for it). */
1413
- const topicTasks = (fold, rootId) => {
1414
- const list = fold?.topics?.[rootId]?.tickets;
1415
- return Array.isArray(list) ? list.filter((r) => r && typeof r.id === 'string') : [];
1416
- };
1417
- /** Whether a root shows a bar: it was moved, or its topic has replies or tasks. */
1418
- function topicBarShows(fold, rootId) {
1412
+ /** Whether a message shows its thread's link: it is answering there, or its replies are not all right under it. */
1413
+ function threadBarShows(fold, rootId) {
1419
1414
  const r = fold?.index?.roots.get(rootId);
1420
1415
  if (!r) return false;
1421
- if (r.root?.movedTo) return true;
1422
- return r.replies.length > 0 || topicTasks(fold, rootId).length > 0;
1416
+ const f = threadFacts(r);
1417
+ return f.running || (f.count > 0 && !r.together);
1423
1418
  }
1424
1419
 
1425
1420
  /**
1426
- * The bar under a topic's root in the main timeline: how many replies, who said the latest and what,
1427
- * the topic's tasks (alive while they work), and a dot when there is something new. It opens the topic.
1421
+ * The link under a message that has a thread, as a chat app has: how many replies, and "replying…"
1422
+ * while the thread answers. The replies are in the chat, quoted; this opens the thread on its own.
1428
1423
  */
1429
- function TopicBar({ t, m, fold }) {
1430
- const r = fold.index.roots.get(m.id);
1431
- const n = r.replies.length;
1432
- const last = r.last;
1433
- const who = last ? party(t, last.from) : null;
1434
- const tasks = topicTasks(fold, m.id).slice(0, 3);
1435
- const unread = fold.unread?.has(m.id) === true;
1424
+ function ThreadBar({ t, m, fold }) {
1425
+ const f = threadFacts(fold.index.roots.get(m.id));
1436
1426
  const mine = m.from === 'user';
1437
1427
  return h(
1438
1428
  'div',
1439
- { style: { display: 'flex', justifyContent: mine ? 'flex-end' : 'flex-start', paddingLeft: mine ? 0 : 40, margin: '3px 0 6px' } },
1429
+ { style: { display: 'flex', justifyContent: mine ? 'flex-end' : 'flex-start', paddingLeft: mine ? 0 : 40, margin: '3px 0 2px' } },
1440
1430
  h(
1441
- 'div',
1442
- {
1443
- role: 'button',
1444
- tabIndex: 0,
1445
- className: 'dshb-topicbar dshb-fade',
1446
- 'data-dsh-bots-topic-bar': m.id,
1447
- 'data-unread': unread ? 'true' : undefined,
1448
- 'data-flash': fold.flash === m.id ? 'true' : undefined,
1449
- title: t('openTopic'),
1450
- onClick: () => fold.onOpen(m.id),
1451
- onKeyDown: (e) => {
1452
- if (e.key === 'Enter' || e.key === ' ') {
1453
- e.preventDefault?.();
1454
- fold.onOpen(m.id);
1455
- }
1456
- },
1457
- },
1458
- h(
1459
- 'div',
1460
- { style: { display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 } },
1461
- h('span', { style: { color: C.label, display: 'inline-flex', flex: 'none' } }, Icon.chat(13)),
1462
- h('span', { 'data-dsh-bots-topic-count': n, style: { fontWeight: 650, color: C.label, flex: 'none' } }, n === 0 ? t('topicLabel') : t(n === 1 ? 'topicReplyOne' : 'topicReplies', { n })),
1463
- last && who ? h('span', { style: { color: C.faint, flex: 'none' } }, '·') : null,
1464
- last && who ? h(PartyAvatar, { p: who, size: 16 }) : null,
1465
- last && who ? h('span', { style: { fontWeight: 600, color: C.primary, flex: 'none', maxWidth: 140, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, who.name) : null,
1466
- last ? h('span', { style: { color: C.faint, flex: 'none', fontSize: TINY } }, fmtClock(toMs(last.at))) : null,
1467
- h('span', { style: { flex: 1 } }),
1468
- unread ? h('span', { 'data-dsh-bots-topic-unread': m.id, title: t('topicUnread'), style: { width: 8, height: 8, borderRadius: '50%', background: C.error, flex: 'none' } }) : null,
1469
- h('span', { style: { color: C.faint, display: 'inline-flex', flex: 'none' } }, Icon.arrow(11)),
1470
- ),
1471
- last ? h('div', { className: 'dshb-clamp2', 'data-dsh-bots-topic-last': last.id ?? true, style: { color: C.muted, fontSize: SMALL, lineHeight: 1.45, wordBreak: 'break-word' } }, plainPreview(last.text)) : null,
1472
- tasks.length
1473
- ? h(
1474
- 'div',
1475
- { style: { display: 'flex', flexDirection: 'column', gap: 3 } },
1476
- tasks.map((row) => {
1477
- const live = row.stage === 'working' ? liveTask(row.id) ?? (row.activity && typeof row.activity === 'object' ? row.activity : null) : null;
1478
- return h(
1479
- 'button',
1480
- {
1481
- key: row.id,
1482
- type: 'button',
1483
- className: 'dshb-topictask',
1484
- 'data-dsh-bots-topic-task': row.id,
1485
- 'data-stage': row.stage,
1486
- title: t('openTask'),
1487
- onClick: (e) => {
1488
- e?.stopPropagation?.();
1489
- openTicket(row.id);
1490
- },
1491
- },
1492
- h('span', { style: { color: C.muted, display: 'inline-flex', flex: 'none' } }, Icon.tasks(12)),
1493
- h(BotFace, { id: row.botId, size: 14 }),
1494
- h('span', { style: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, taskTitle(t, row)),
1495
- live ? h(LiveChip, { t, a: live }) : h(TaskChip, { t, row }),
1496
- );
1497
- }),
1498
- )
1431
+ 'button',
1432
+ { type: 'button', className: 'dshb-threadbar dshb-fade', 'data-dsh-bots-thread-bar': m.id, title: t('openThread'), onClick: () => fold.onOpen(m.id) },
1433
+ h('span', { style: { display: 'inline-flex', flex: 'none' } }, Icon.chat(12)),
1434
+ h('span', { 'data-dsh-bots-thread-replies': f.count }, f.count === 0 ? t('threadWord') : t(f.count === 1 ? 'threadReplyOne' : 'threadReplies', { n: f.count })),
1435
+ f.running
1436
+ ? h('span', { 'data-dsh-bots-thread-running': m.id, style: { display: 'inline-flex', alignItems: 'center', gap: 4, fontWeight: 500 } }, h('span', { style: { width: 6, height: 6, borderRadius: '50%', background: C.label, animation: 'dshb-blink 1.2s ease-in-out infinite' } }), t('threadRunning'))
1499
1437
  : null,
1438
+ h('span', { style: { display: 'inline-flex', flex: 'none', opacity: 0.7 } }, Icon.arrow(10)),
1500
1439
  ),
1501
1440
  );
1502
1441
  }
1503
- /** Where a top-level message went when the dispatcher placed it in another topic: a link to that topic. */
1504
- function MovedBar({ t, m, fold }) {
1505
- const target = fold.index.byId.get(m.movedTo);
1506
- const title = target ? excerpt(target.text, 40) : '';
1507
- const mine = m.from === 'user';
1442
+
1443
+ /** The message a reply quotes, on top of it as a chat app shows a quoted reply: who and a line or two; it opens the thread. */
1444
+ function QuoteLine({ t, q, light = false, onOpen }) {
1445
+ const who = q.from === 'user' && str(q.who) ? { name: str(q.who) } : party(t, q.from);
1446
+ const body = h('span', { className: 'dshb-clamp2' }, h('span', { style: { fontWeight: 600 } }, t('quoteWho', { name: who.name })), plainPreview(q.text));
1447
+ const className = light ? 'dshb-qline dshb-qline-light' : 'dshb-qline';
1448
+ if (!onOpen) return h('div', { className, 'data-dsh-bots-quoted': q.id }, body);
1508
1449
  return h(
1509
- 'div',
1510
- { style: { display: 'flex', justifyContent: mine ? 'flex-end' : 'flex-start', paddingLeft: mine ? 0 : 40, margin: '2px 0 6px' } },
1511
- h(
1512
- 'button',
1513
- { type: 'button', className: 'dshb-link dshb-moved', 'data-dsh-bots-moved': m.movedTo, title: t('openTopic'), onClick: () => fold.onOpen(m.movedTo) },
1514
- h('span', { style: { display: 'inline-flex', flex: 'none' } }, Icon.layers(12)),
1515
- h('span', { style: { minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, title ? t('movedTo', { title }) : t('movedToTopic')),
1516
- h('span', { style: { display: 'inline-flex', flex: 'none' } }, Icon.arrow(11)),
1517
- ),
1450
+ 'button',
1451
+ {
1452
+ type: 'button',
1453
+ className,
1454
+ 'data-dsh-bots-quoted': q.id,
1455
+ title: t('openThread'),
1456
+ onClick: (e) => {
1457
+ e?.stopPropagation?.();
1458
+ onOpen();
1459
+ },
1460
+ },
1461
+ body,
1518
1462
  );
1519
1463
  }
1520
1464
 
1521
1465
  /** A message between two bots (a delegation, a report, a DM), or a scheduled prompt: secondary traffic. */
1522
1466
  const isTraffic = (m) => m?.kind === 'system' || ((m?.kind === 'dm' || m?.kind === 'report') && m.from !== 'user' && m.to !== 'user');
1467
+ /** A bot's message to itself: work it hands itself (or its own report back). The chat leaves it out: to the person it is the bot at work. */
1468
+ const selfTalk = (m) => isTraffic(m) && m.kind !== 'system' && str(m.from) !== '' && m.from === m.to;
1523
1469
  /** How much of what bots say to each other a chat shows (a team setting): 'line' | 'short' | 'full'. */
1524
1470
  function botMessagesLevel() {
1525
1471
  const v = store.state?.display?.botMessages ?? store.settings?.settings?.display?.botMessages;
@@ -1677,7 +1623,7 @@ button.dshb-tline:hover{background:${C.hover}}
1677
1623
  return null;
1678
1624
  }
1679
1625
 
1680
- function MessageRow({ t, m, botId, grouped, names, onReply, onRetry, moved = false }) {
1626
+ function MessageRow({ t, m, botId, grouped, names, onReply, onRetry, moved = false, quote = null, onQuote }) {
1681
1627
  if (m.kind === 'topic') {
1682
1628
  const at = toMs(m.at);
1683
1629
  return h(
@@ -1721,7 +1667,12 @@ button.dshb-tline:hover{background:${C.hover}}
1721
1667
  'div',
1722
1668
  { style: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6, width: '100%', minWidth: 0 } },
1723
1669
  h(ReplyAction, { t, m, onReply }),
1724
- h('div', { style: { maxWidth: '78%', minWidth: 0, padding: '8px 12px', borderRadius: '14px 14px 4px 14px', background: C.label, color: C.onLabel, fontSize: FONT, opacity: m.local && !m.failed ? 0.8 : 1, boxShadow: m.failed ? `0 0 0 2px ${C.error}` : undefined } }, h(Clamp, { t, text: m.text, lines: 14, light: true })),
1670
+ h(
1671
+ 'div',
1672
+ { style: { maxWidth: '78%', minWidth: 0, padding: '8px 12px', borderRadius: '14px 14px 4px 14px', background: C.label, color: C.onLabel, fontSize: FONT, opacity: m.local && !m.failed ? 0.8 : 1, boxShadow: m.failed ? `0 0 0 2px ${C.error}` : undefined } },
1673
+ quote ? h('div', { style: { marginBottom: 5 } }, h(QuoteLine, { t, q: quote, light: true, onOpen: onQuote ? () => onQuote(m) : null })) : null,
1674
+ h(Clamp, { t, text: m.text, lines: 14, light: true }),
1675
+ ),
1725
1676
  ),
1726
1677
  state,
1727
1678
  h('div', { style: { width: 'min(480px, 78%)', display: 'flex', justifyContent: 'flex-end' } }, h(LinkCards, { t, text: m.text, align: 'flex-end' })),
@@ -1753,10 +1704,12 @@ button.dshb-tline:hover{background:${C.hover}}
1753
1704
  m.to !== 'user' && to.kind === 'bot' && m.to !== botId ? h('span', { style: { color: C.faint } }, `→ ${to.name}`) : null,
1754
1705
  h('span', { style: { color: C.faint } }, time),
1755
1706
  m.via ? h(Badge, { color: CHANNEL_COLORS[m.via] ?? C.muted, title: t('sentToChannel', { app: place }), 'data-dsh-bots-via': m.via }, `→ ${place}`) : null,
1756
- report ? h(ReportChip, { t, status: report }) : null,
1707
+ // A finished answer is just the answer; a question or a block says so.
1708
+ report && report !== 'done' ? h(ReportChip, { t, status: report }) : null,
1757
1709
  notice ? h(StageChip, { t, stage: notice }) : null,
1758
1710
  ticketId ? h('button', { type: 'button', className: 'dshb-link', 'data-dsh-bots-report-task': ticketId, onClick: () => openTicket(ticketId), style: { fontSize: TINY } }, t('openTask')) : null,
1759
1711
  ),
1712
+ quote ? h(QuoteLine, { t, q: quote, onOpen: onQuote ? () => onQuote(m) : null }) : null,
1760
1713
  h('div', { className: 'dshb-reply', 'data-dsh-bots-reply-text': true }, h(Clamp, { t, text: m.text, lines: 24, variant: 'body' })),
1761
1714
  choices.length
1762
1715
  ? h(
@@ -2299,8 +2252,9 @@ button.dshb-tline:hover{background:${C.hover}}
2299
2252
  }
2300
2253
 
2301
2254
  /**
2302
- * A bot's chat (or every message, without `botId`), polled: `items` oldest first and, per panel topic,
2303
- * `topics[rootId] = {key, tickets}` (PLAN-0.9 §7.3). With `topic`, only that topic's messages.
2255
+ * A bot's chat (or every message, without `botId`), polled: `items` oldest first (the main timeline)
2256
+ * and, per message with a thread, `threads[rootId]`, its summary (PLAN-0.10 §7.2). With `topic`, one
2257
+ * thread: its root and its replies.
2304
2258
  */
2305
2259
  function useMessages(botId, active = true, topic = '') {
2306
2260
  const [data, setData] = useState(null);
@@ -2320,26 +2274,26 @@ button.dshb-tline:hover{background:${C.hover}}
2320
2274
  if (!alive.current) return;
2321
2275
  if (r && Array.isArray(r.items)) {
2322
2276
  setFailed(false);
2323
- const topics = r.topics && typeof r.topics === 'object' ? r.topics : {};
2324
- // Same messages in the same states and the same tasks: keep what is shown (no re-render).
2325
- const sig = `${r.items.map((m) => `${m?.id}${m?.pending ? '~' : ''}${m?.movedTo ? `>${m.movedTo}` : ''}`).join(',')}|${JSON.stringify(topics)}`;
2326
- setData((prev) => (prev && prev.sig === sig ? prev : { items: r.items, topics, sig }));
2277
+ // A Host of 0.9 called them topics.
2278
+ const threads = r.threads && typeof r.threads === 'object' ? r.threads : r.topics && typeof r.topics === 'object' ? r.topics : {};
2279
+ // Same messages in the same states and the same threads: keep what is shown (no re-render).
2280
+ const sig = `${r.items.map((m) => `${m?.id}${m?.pending ? '~' : ''}${m?.movedTo ? `>${m.movedTo}` : ''}`).join(',')}|${JSON.stringify(threads)}`;
2281
+ setData((prev) => (prev && prev.sig === sig ? prev : { items: r.items, threads, sig }));
2327
2282
  } else setFailed(true);
2328
2283
  })
2329
2284
  .catch(() => {
2330
2285
  if (alive.current) setFailed(true);
2331
2286
  });
2332
2287
  usePoll(() => (active ? load() : undefined), CHAT_POLL_MS, [botId, active, topic]);
2333
- return { items: data ? data.items : null, topics: data ? data.topics : {}, failed, reload: load };
2288
+ return { items: data ? data.items : null, threads: data ? data.threads : {}, failed, reload: load };
2334
2289
  }
2335
2290
 
2336
- // --- panel topics (PLAN-0.9): every top-level message is a topic's root ---------------------
2291
+ // --- threads (PLAN-0.10): a reply to a message, talked over beside the chat --------------------
2337
2292
 
2338
- /** The topic a message's thread is: the one it was moved into, else its own (a root's is its id), else ''. */
2339
- const topicOfMsg = (m) => str(m?.movedTo) || str(m?.topic);
2340
- /** A message is a reply inside topic `root` (moved in, or written there), not the root itself. */
2341
- const inTopic = (m, root) => Boolean(root) && m?.id !== root && (m?.topic === root || m?.movedTo === root);
2342
- /** A short excerpt of a message for a quote or a label. */
2293
+ /** The thread a message is in: the one it was put into (0.9), else the root it names (a root of 0.9 names itself), else ''. */
2294
+ const threadOfMsg = (m) => str(m?.movedTo) || (str(m?.topic) && str(m.topic) !== str(m?.id) ? str(m.topic) : '');
2295
+ /** A message is a reply inside thread `root` (put there, or written there), not the root itself. */
2296
+ const inThread = (m, root) => Boolean(root) && m?.id !== root && (m?.topic === root || m?.movedTo === root);
2343
2297
  /** Markdown as a line of plain text, for a preview: no emphasis marks, headings, list markers or link targets. */
2344
2298
  const plainPreview = (text) =>
2345
2299
  str(text)
@@ -2350,23 +2304,29 @@ button.dshb-tline:hover{background:${C.hover}}
2350
2304
  .replace(/(^|[\s(])[*_](\S[^*_]*?)[*_](?=[\s).,!?:;,。!?:;]|$)/g, '$1$2')
2351
2305
  .replace(/\s+/g, ' ')
2352
2306
  .trim();
2307
+ /** A short excerpt of a message for a quote or a label. */
2353
2308
  const excerpt = (text, n = 48) => {
2354
2309
  const line = plainPreview(str(text).split('\n').find((l) => plainPreview(l) !== '') ?? '');
2355
2310
  return [...line].length > n ? `${[...line].slice(0, n - 1).join('').trimEnd()}…` : line;
2356
2311
  };
2312
+ /** One thread's summary as the Host gives it (PLAN-0.10 §7.2), or null. */
2313
+ const summaryOf = (threads, rootId) => {
2314
+ const s = threads && typeof threads === 'object' ? threads[rootId] : null;
2315
+ return s && typeof s === 'object' ? s : null;
2316
+ };
2357
2317
  /**
2358
- * A chat's messages folded into topics: `main` (what the main timeline shows: messages outside any
2359
- * topic, and the roots), and per root its replies (oldest first) and its latest activity. A reply whose
2360
- * root is not among the messages stays in the main timeline, so nothing goes missing.
2318
+ * A chat and its threads. The Host lists the chat as it was said (`items`: a reply in a thread
2319
+ * among the rest, with the message it quotes) and a summary per thread (`threads`). `main`: every
2320
+ * message in order; per root: its replies known here and the Host's summary.
2361
2321
  */
2362
- function topicIndex(items) {
2322
+ function threadIndex(items, threads = {}) {
2363
2323
  const byId = new Map();
2364
2324
  for (const m of items) if (m && m.id != null) byId.set(m.id, m);
2365
2325
  const roots = new Map();
2366
2326
  const rootOf = (id) => {
2367
2327
  let r = roots.get(id);
2368
2328
  if (!r) {
2369
- r = { root: byId.get(id), replies: [], lastAt: toMs(byId.get(id)?.at) || 0, last: null, botAt: 0 };
2329
+ r = { root: byId.get(id), replies: [], summary: summaryOf(threads, id) };
2370
2330
  roots.set(id, r);
2371
2331
  }
2372
2332
  return r;
@@ -2374,63 +2334,79 @@ button.dshb-tline:hover{background:${C.hover}}
2374
2334
  const main = [];
2375
2335
  for (const m of items) {
2376
2336
  if (!m) continue;
2377
- const own = str(m.topic);
2378
- if (own && own === m.id) {
2379
- rootOf(m.id);
2380
- main.push(m);
2337
+ main.push(m);
2338
+ const home = threadOfMsg(m);
2339
+ if (home && home !== m.id) {
2340
+ // What bots said to each other about a thread's tasks is not counted as a reply.
2341
+ if (!isTraffic(m)) rootOf(home).replies.push(m);
2342
+ continue;
2381
2343
  }
2382
- // A moved root stays where it was and is listed in the topic it went to; a reply only there.
2383
- const home = str(m.movedTo) || (own && own !== m.id ? own : '');
2384
- if (home && byId.has(home) && home !== m.id) {
2385
- const r = rootOf(home);
2386
- // What bots said to each other about the topic's tasks is shown in the topic, not counted as a reply.
2387
- if (isTraffic(m)) continue;
2388
- r.replies.push(m);
2389
- const at = toMs(m.at) || 0;
2390
- if (at >= r.lastAt) r.lastAt = at;
2391
- if (!r.last || at >= (toMs(r.last.at) || 0)) r.last = m;
2392
- // When a bot (or anyone not you) last said something here: what can be unread.
2393
- if (m.from !== 'user' && at > r.botAt) r.botAt = at;
2394
- } else if (!(own && own === m.id)) main.push(m);
2344
+ if (summaryOf(threads, m.id)) rootOf(m.id);
2395
2345
  }
2396
2346
  for (const r of roots.values()) r.replies.sort((a, b) => (toMs(a.at) || 0) - (toMs(b.at) || 0));
2347
+ // A thread whose replies all come right under its root (what bots say to each other aside) reads as the chat itself.
2348
+ const pos = new Map(main.map((m, i) => [m.id, i]));
2349
+ for (const [id, r] of roots) {
2350
+ const at = pos.get(id);
2351
+ let k = 0;
2352
+ let together = at !== undefined;
2353
+ for (let j = (at ?? main.length) + 1; together && j < main.length && k < r.replies.length; j += 1) {
2354
+ if (isTraffic(main[j])) continue;
2355
+ if (main[j].id !== r.replies[k].id) together = false;
2356
+ else k += 1;
2357
+ }
2358
+ r.together = together && k === r.replies.length;
2359
+ }
2397
2360
  return { byId, roots, main };
2398
2361
  }
2399
- /** Where the "seen" marks of topics live: the browser's storage, or null when there is none (then nothing is unread). */
2400
- function seenStorage() {
2401
- try {
2402
- const s = typeof window !== 'undefined' ? window.localStorage : undefined;
2403
- return s && typeof s.getItem === 'function' && typeof s.setItem === 'function' ? s : null;
2404
- } catch {
2405
- return null;
2406
- }
2362
+ /**
2363
+ * What a thread's bar shows: how many replies, the latest one (`{from, text, at}`), how many of the
2364
+ * bot's replies are unread, whether it is answering now, and its tasks. The Host's summary, with the
2365
+ * replies sent from here that it has not counted yet.
2366
+ */
2367
+ function threadFacts(r) {
2368
+ const s = r?.summary ?? {};
2369
+ const replies = r?.replies ?? [];
2370
+ const latestHere = replies[replies.length - 1] ?? null;
2371
+ const hostLast = s.last && typeof s.last === 'object' ? { ...s.last, at: s.lastAt } : null;
2372
+ const hostAt = Number(s.lastAt) || 0;
2373
+ const last = latestHere && (toMs(latestHere.at) || 0) >= hostAt ? latestHere : hostLast;
2374
+ const count = Math.max(Number(s.count) || 0, replies.length);
2375
+ const tickets = Array.isArray(s.tickets) ? s.tickets.filter((row) => row && typeof row.id === 'string') : [];
2376
+ return { count, last, lastAt: Math.max(hostAt, toMs(latestHere?.at) || 0), unread: Math.max(0, Number(s.unread) || 0), running: s.running === true, answering: s.answering === true, tickets };
2407
2377
  }
2408
- const seenKey = (botId) => `dshb:topics-seen:${botId}`;
2409
- /** The seen marks of a bot's topics (`{rootId: ms}`), `{}` when none were kept yet (`fresh`), or null without storage. */
2410
- function readSeen(botId) {
2411
- const s = seenStorage();
2412
- if (!s) return null;
2413
- try {
2414
- const raw = s.getItem(seenKey(botId));
2415
- if (raw === null || raw === undefined) return { marks: {}, fresh: true };
2416
- const v = JSON.parse(raw);
2417
- return { marks: v && typeof v === 'object' && !Array.isArray(v) ? v : {}, fresh: false };
2418
- } catch {
2419
- return null;
2378
+ /**
2379
+ * The message a reply in a thread quotes (Bots 0.10): the Host's `quote`, else as the Host picks it
2380
+ * from what is here (one sent from here): the message the person replied to, a bot's the person's
2381
+ * latest message of the thread before it, else the thread's root. Null for a message of the chat itself.
2382
+ */
2383
+ function quoteFor(m, index) {
2384
+ if (m?.quote && typeof m.quote === 'object' && m.quote.id != null) return m.quote;
2385
+ const root = threadOfMsg(m);
2386
+ if (!root) return null;
2387
+ let target = str(m.replyTo) ? index.byId.get(m.replyTo) : null;
2388
+ if (!target && m.from !== 'user') {
2389
+ for (const x of index.roots.get(root)?.replies ?? []) {
2390
+ if (x.id === m.id) break;
2391
+ if (x.from === 'user' && x.kind === 'user') target = x;
2392
+ }
2420
2393
  }
2394
+ target = target || index.byId.get(root);
2395
+ return target ? { id: target.id, from: target.from, text: str(target.text), ...(str(target.who) ? { who: str(target.who) } : {}) } : null;
2421
2396
  }
2422
- function writeSeen(botId, marks) {
2423
- const s = seenStorage();
2424
- if (!s) return;
2425
- try {
2426
- // Only the newest topics are worth keeping.
2427
- const keep = Object.entries(marks).sort((a, b) => b[1] - a[1]).slice(0, 400);
2428
- s.setItem(seenKey(botId), JSON.stringify(Object.fromEntries(keep)));
2429
- } catch {
2430
- // A full or blocked storage: unread marks are a convenience.
2431
- }
2397
+ /**
2398
+ * Whether a message of the chat shows its quote: a reply the person picked always does; any other
2399
+ * message of a thread does unless the message above it is of the same thread (or is its root).
2400
+ */
2401
+ function chatQuote(m, prev, index) {
2402
+ const root = threadOfMsg(m);
2403
+ if (!root) return null;
2404
+ const picked = m.from === 'user' && (str(m.replyTo) !== '' || (str(m.topic) !== '' && str(m.topic) !== str(m.id)));
2405
+ if (!picked && prev && (threadOfMsg(prev) || prev.id) === root) return null;
2406
+ return quoteFor(m, index);
2432
2407
  }
2433
2408
 
2409
+
2434
2410
  /** A first chat: the bot's bio and three opening messages to start from. */
2435
2411
  function ChatEmpty({ t, bot, onPick }) {
2436
2412
  const primary = bot.role === 'primary' || bot.id === store.state?.primaryId;
@@ -2628,20 +2604,6 @@ button.dshb-tline:hover{background:${C.hover}}
2628
2604
  const extra = local.filter((m) => !ids.has(m.id));
2629
2605
  return extra.length ? [...items, ...extra] : items;
2630
2606
  }
2631
- /** Whether a topic's bar is on screen in the scrolling `box` (no box, no DOM: not on screen). */
2632
- function barOnScreen(box, id) {
2633
- if (!box || typeof box.querySelector !== 'function' || typeof box.getBoundingClientRect !== 'function') return false;
2634
- let el = null;
2635
- try {
2636
- el = box.querySelector(`[data-dsh-bots-topic-bar="${String(id).replace(/["\\]/g, '\\$&')}"]`);
2637
- } catch {
2638
- el = null;
2639
- }
2640
- if (!el || typeof el.getBoundingClientRect !== 'function') return false;
2641
- const a = el.getBoundingClientRect();
2642
- const b = box.getBoundingClientRect();
2643
- return a.bottom > b.top + 8 && a.top < b.bottom - 8;
2644
- }
2645
2607
  /** The line above a composer naming the message a reply answers, with a way to drop it. */
2646
2608
  function QuoteBar({ t, m, onCancel, attr = 'data-dsh-bots-quote' }) {
2647
2609
  const who = party(t, m.from);
@@ -2656,103 +2618,57 @@ button.dshb-tline:hover{background:${C.hover}}
2656
2618
  }
2657
2619
 
2658
2620
  function ChatTab({ t, bot, env, toast }) {
2659
- const { items: listed, topics, failed, reload } = useMessages(bot.id);
2621
+ const { items: listed, threads, failed, reload } = useMessages(bot.id);
2660
2622
  const [text, setText] = useState('');
2661
2623
  // Messages sent from here: shown at once (queued), then the Host's own copy; a failed one stays to be sent again.
2662
2624
  const [local, setLocal] = useState([]);
2663
- // The message the main composer replies to, the topic open beside the chat, the bar to point out.
2664
- const [quote, setQuote] = useState(null);
2625
+ // The thread open beside the chat; the message the next one replies to (quoted above the composer).
2665
2626
  const [open, setOpen] = useState('');
2666
- const [flash, setFlash] = useState('');
2667
- // Which topics were read up to when (null: no storage, so nothing is unread).
2668
- const [seen, setSeen] = useState(() => readSeen(bot.id));
2669
- const [offscreen, setOffscreen] = useState('');
2670
- const offscreenRef = useRef('');
2671
- const measuring = useRef(false);
2627
+ const [quote, setQuote] = useState(null);
2628
+ const input = useRef(null);
2672
2629
  // The quick poll may know before the state does that it started or stopped.
2673
2630
  const live = liveBot(bot);
2674
2631
  const running = live.status === 'running' || Boolean(live.activity);
2675
2632
  const items = mergeLocal(listed, local);
2676
- const index = topicIndex(items ?? []);
2677
- const lastMain = index.main[index.main.length - 1];
2678
- const thread = useStickToBottom(`${index.main.length}:${lastMain?.id ?? ''}:${running}`);
2679
- const [topicBusy, setTopicBusy] = useState(false);
2680
-
2681
- // The Host listed what was sent from here: its copies take over.
2682
- useEffect(() => {
2683
- if (!Array.isArray(listed) || !local.some((m) => !m.failed)) return;
2684
- const ids = new Set(listed.map((m) => m?.id));
2685
- if (local.some((m) => ids.has(m.id))) setLocal((list) => list.filter((m) => !ids.has(m.id)));
2686
- }, [listed]);
2687
- // First time here: what is already there counts as read; only replies from now on are new.
2688
- useEffect(() => {
2689
- if (!seen || !seen.fresh || !Array.isArray(listed)) return;
2690
- const marks = {};
2691
- for (const [id, r] of index.roots) marks[id] = r.lastAt;
2692
- writeSeen(bot.id, marks);
2693
- setSeen({ marks, fresh: false });
2694
- }, [listed === null, seen?.fresh]);
2695
- const markSeen = (id, at) => {
2696
- if (!id || !at) return;
2697
- setSeen((prev) => {
2698
- if (!prev || (Number(prev.marks[id]) || 0) >= at) return prev;
2699
- const marks = { ...prev.marks, [id]: at };
2700
- writeSeen(bot.id, marks);
2701
- return { marks, fresh: false };
2702
- });
2703
- };
2704
- // A topic with a reply you have not seen: the latest reply is a bot's, newer than when you last looked.
2705
- const unread = new Set();
2706
- if (seen && !seen.fresh) {
2707
- for (const [id, r] of index.roots) {
2708
- if (id === open || !r.botAt || r.root?.movedTo) continue;
2709
- const mark = Number(seen.marks[id]) || toMs(r.root?.at) || 0;
2710
- if (r.botAt > mark) unread.add(id);
2633
+ const index = threadIndex(items ?? [], threads);
2634
+ // A thread answering now, or work the bot handed itself: the chat shows the bot at work at its end, where the answer will be.
2635
+ const answering = !running && [...index.roots.values()].some((r) => threadFacts(r).answering);
2636
+ let ownWork = null;
2637
+ if (!running) {
2638
+ for (let i = index.main.length - 1; i >= 0 && !ownWork; i -= 1) {
2639
+ const m = index.main[i];
2640
+ if (selfTalk(m) && m.from === bot.id && m.kind === 'dm' && !messageReport(m)) ownWork = liveTask(messageTicket(m));
2711
2641
  }
2712
2642
  }
2713
- const unreadIds = [...unread].sort((a, b) => index.roots.get(b).botAt - index.roots.get(a).botAt);
2714
- const unreadKey = unreadIds.join(',');
2715
- const measure = () => {
2716
- const box = thread.box.current;
2717
- const key = unreadIds.filter((id) => !barOnScreen(box, id)).join(',');
2718
- if (key !== offscreenRef.current) {
2719
- offscreenRef.current = key;
2720
- setOffscreen(key);
2721
- }
2643
+ const lastMain = index.main[index.main.length - 1];
2644
+ const thread = useStickToBottom(`${index.main.length}:${lastMain?.id ?? ''}:${running}:${answering}:${Boolean(ownWork)}`);
2645
+ const [topicBusy, setTopicBusy] = useState(false);
2646
+ // The chat the panel shows comes back to it when Harness closes the panel over a new topic.
2647
+ store.lastChat = bot.id;
2648
+ /** The Host listed these (the chat, or the open thread): its copies take over from what was sent from here. */
2649
+ const dropListed = (list) => {
2650
+ if (!Array.isArray(list) || !local.some((m) => !m.failed)) return;
2651
+ const ids = new Set(list.map((m) => m?.id));
2652
+ if (local.some((m) => !m.failed && ids.has(m.id))) setLocal((rows) => rows.filter((m) => m.failed || !ids.has(m.id)));
2722
2653
  };
2723
- useEffect(() => {
2724
- measure();
2725
- }, [unreadKey]);
2726
- const measureSoon = () => {
2727
- if (measuring.current) return;
2728
- measuring.current = true;
2729
- const run = () => {
2730
- measuring.current = false;
2731
- measure();
2732
- };
2733
- if (typeof requestAnimationFrame === 'function') requestAnimationFrame(run);
2734
- else setTimeout(run, 60);
2654
+ useEffect(() => dropListed(listed), [listed]);
2655
+ const openThread = (id) => {
2656
+ if (id) setOpen(id);
2735
2657
  };
2736
- const hidden = offscreen ? offscreen.split(',').filter((id) => unread.has(id)) : [];
2737
- const pointAt = (id) => {
2658
+ // Reply quotes the message above the composer, as a chat app does; what is sent then answers it in its thread.
2659
+ const replyTo = (m) => {
2660
+ setQuote(m);
2738
2661
  try {
2739
- const el = thread.box.current?.querySelector?.(`[data-dsh-bots-topic-bar="${String(id).replace(/["\\]/g, '\\$&')}"]`);
2740
- el?.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
2662
+ input.current?.focus?.();
2741
2663
  } catch {
2742
- // Scrolling is a nicety.
2664
+ // Focus is a nicety.
2743
2665
  }
2744
- setFlash(id);
2745
- setTimeout(() => setFlash((f) => (f === id ? '' : f)), 1800);
2746
- measureSoon();
2747
- };
2748
- const openTopic = (id) => {
2749
- if (!id) return;
2750
- setOpen(id);
2751
- markSeen(id, index.roots.get(id)?.lastAt ?? Date.now());
2752
2666
  };
2753
2667
 
2754
2668
  const startTopic = () => {
2755
2669
  setTopicBusy(true);
2670
+ // Starting a topic archives the last conversation, and Harness closes the panel over it: it comes back.
2671
+ store.rotatingAt = Date.now();
2756
2672
  postJson('topic/new', { id: bot.id })
2757
2673
  .then((r) => {
2758
2674
  if (r?.ok) {
@@ -2761,18 +2677,23 @@ button.dshb-tline:hover{background:${C.hover}}
2761
2677
  void refreshState();
2762
2678
  } else toast(r?.reason || t('actionFailed'), 'error');
2763
2679
  })
2764
- .finally(() => setTopicBusy(false));
2680
+ .finally(() => {
2681
+ setTopicBusy(false);
2682
+ env.keepPanel?.(bot.id);
2683
+ });
2765
2684
  };
2766
2685
  /**
2767
- * Send `body` (a reply in a topic with `replyTo`): it shows at once as queued, the Host's copy
2768
- * replaces it, and a failure stays with a way to send again. Resolves `{ok, topic}`.
2686
+ * Send `body` to the chat, or with `replyTo` into a thread (`root`: the thread's root, when known):
2687
+ * it shows at once as queued, the Host's copy replaces it, and a failure stays with a way to send
2688
+ * again. Resolves `{ok, topic}` (the thread it went into, '' for the chat).
2769
2689
  */
2770
- const sendText = (body, replyTo = '', again = '', topicHint = '') => {
2690
+ const sendText = (body, replyTo = '', again = '', root = '') => {
2771
2691
  const id = again || `local-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
2772
2692
  const target = replyTo ? index.byId.get(replyTo) : null;
2773
- // The topic it goes into (the Host says for sure): the pane's own, else the one of the message it answers.
2774
- const topic = replyTo ? topicHint || (target ? topicOfMsg(target) || target.id : replyTo) : id;
2775
- const row = { id, local: true, pending: true, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, at: Date.now(), topic, ...(replyTo ? { replyTo } : {}) };
2693
+ // The thread it goes into (the Host says for sure): the pane's own, else the thread of the message it answers, else that message's.
2694
+ const topic = replyTo ? root || (target ? threadOfMsg(target) || target.id : replyTo) : '';
2695
+ const quoted = target ? { id: target.id, from: target.from, text: str(target.text), ...(str(target.who) ? { who: str(target.who) } : {}) } : null;
2696
+ const row = { id, local: true, pending: true, from: 'user', to: bot.id, chat: bot.id, kind: 'user', text: body, at: Date.now(), ...(topic ? { topic } : {}), ...(replyTo && replyTo !== topic ? { replyTo } : {}), ...(quoted ? { quote: quoted } : {}) };
2776
2697
  setLocal((list) => [...list.filter((m) => m.id !== id), row]);
2777
2698
  return postJson('send', { to: bot.id, text: body, ...(replyTo ? { replyTo } : {}) }).then((r) => {
2778
2699
  if (r?.ok) {
@@ -2780,7 +2701,7 @@ button.dshb-tline:hover{background:${C.hover}}
2780
2701
  setLocal((list) => list.flatMap((m) => (m.id !== id ? [m] : msg ? [{ ...msg, pending: msg.pending ?? true, chat: msg.chat ?? bot.id }] : [])));
2781
2702
  void reload();
2782
2703
  void refreshState();
2783
- return { ok: true, topic: msg ? topicOfMsg(msg) || topic : topic };
2704
+ return { ok: true, topic: msg ? str(msg.topic) || topic : topic };
2784
2705
  }
2785
2706
  setLocal((list) => list.map((m) => (m.id === id ? { ...m, pending: false, failed: true } : m)));
2786
2707
  toast(r?.reason || t('sendFailed'), 'error');
@@ -2789,27 +2710,24 @@ button.dshb-tline:hover{background:${C.hover}}
2789
2710
  };
2790
2711
  const retry = (m) => {
2791
2712
  if (!m?.local) return;
2792
- void sendText(str(m.text), str(m.replyTo), m.id, m.replyTo ? str(m.topic) : '');
2713
+ const root = threadOfMsg(m);
2714
+ void sendText(str(m.text), root ? str(m.replyTo) || root : '', m.id, root);
2793
2715
  };
2794
2716
  const send = () => {
2795
2717
  const body = text.trim();
2796
2718
  if (!body) return;
2797
- const replyTo = quote?.id ?? '';
2719
+ const to = quote?.id ?? '';
2798
2720
  setText('');
2799
2721
  setQuote(null);
2800
- if (!replyTo) thread.stick();
2801
- void sendText(body, replyTo).then((r) => {
2802
- // A reply went into its topic: open it there, where the answer will come.
2803
- if (r.ok && replyTo) openTopic(r.topic);
2804
- else if (!replyTo) thread.stick();
2805
- });
2722
+ thread.stick();
2723
+ void sendText(body, to).then(() => thread.stick());
2806
2724
  };
2807
2725
  // A pasted link previews above the composer, as it will in the thread.
2808
2726
  const previewUrl = linksIn(useDebounced(text, 400))[0] ?? '';
2809
- const fold = { index, topics, onOpen: openTopic, unread, flash };
2727
+ const fold = { index, onOpen: openThread };
2810
2728
  return h(
2811
2729
  'div',
2812
- { className: 'dshb-chatwrap', 'data-dsh-bots-chat': bot.id, 'data-topic-open': open || undefined },
2730
+ { className: 'dshb-chatwrap', 'data-dsh-bots-chat': bot.id, 'data-thread-open': open || undefined },
2813
2731
  h(
2814
2732
  'div',
2815
2733
  { className: 'dshb-chatmain' },
@@ -2819,10 +2737,7 @@ button.dshb-tline:hover{background:${C.hover}}
2819
2737
  className: 'dshb-scroll',
2820
2738
  'data-dsh-bots-thread': bot.id,
2821
2739
  ref: thread.box,
2822
- onScroll: (e) => {
2823
- thread.onScroll(e);
2824
- if (unreadIds.length) measureSoon();
2825
- },
2740
+ onScroll: thread.onScroll,
2826
2741
  style: { flex: 1, padding: '6px 24px' },
2827
2742
  },
2828
2743
  h(
@@ -2835,29 +2750,18 @@ button.dshb-tline:hover{background:${C.hover}}
2835
2750
  items,
2836
2751
  botId: bot.id,
2837
2752
  fold,
2838
- onReply: (m) => setQuote(m),
2753
+ onReply: replyTo,
2839
2754
  onRetry: retry,
2755
+ quoteOf: (m, prev) => chatQuote(m, prev, index),
2756
+ onQuote: (m) => openThread(threadOfMsg(m) || m.id),
2840
2757
  empty: h(ChatEmpty, { t, bot, onPick: setText }),
2841
2758
  }),
2842
- running ? h('div', { style: { maxWidth: 880, margin: '0 auto' } }, h(WorkingRow, { t, bot, a: live.activity, attr: bot.id })) : null,
2759
+ running || answering || ownWork ? h('div', { style: { maxWidth: 880, margin: '0 auto' } }, h(WorkingRow, { t, bot, a: running ? live.activity : ownWork, attr: bot.id })) : null,
2843
2760
  ),
2844
2761
  ),
2845
2762
  h(
2846
2763
  'div',
2847
2764
  { style: { padding: '10px 24px 16px', borderTop: `1px solid ${C.border1}`, background: C.base, position: 'relative' } },
2848
- hidden.length
2849
- ? h(
2850
- 'div',
2851
- { className: 'dshb-pillrow' },
2852
- h(
2853
- 'button',
2854
- { type: 'button', className: 'dshb-pill', 'data-dsh-bots-new-replies': hidden.length, onClick: () => pointAt(hidden[0]) },
2855
- h('span', { style: { width: 7, height: 7, borderRadius: '50%', background: C.error, flex: 'none' } }),
2856
- hidden.length === 1 ? t('newReplyOne') : t('newReplies', { n: hidden.length }),
2857
- h('span', { style: { display: 'inline-flex' } }, Icon.chevron(11)),
2858
- ),
2859
- )
2860
- : null,
2861
2765
  h(
2862
2766
  'div',
2863
2767
  { style: { maxWidth: 880, margin: '0 auto' } },
@@ -2873,15 +2777,19 @@ button.dshb-tline:hover{background:${C.hover}}
2873
2777
  { style: { display: 'flex', alignItems: 'flex-end', gap: 8 } },
2874
2778
  h('textarea', {
2875
2779
  'data-dsh-bots-composer': true,
2780
+ ref: input,
2876
2781
  value: text,
2877
2782
  rows: Math.min(8, Math.max(1, text.split('\n').length)),
2878
- placeholder: quote ? t('topicComposer') : t('composer', { handle: bot.handle }),
2783
+ placeholder: t('composer', { handle: bot.handle }),
2879
2784
  onChange: (e) => setText(e.target.value),
2880
2785
  onKeyDown: (e) => {
2881
2786
  if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
2882
2787
  e.preventDefault();
2883
2788
  send();
2884
- } else if (e.key === 'Escape' && quote) setQuote(null);
2789
+ } else if (e.key === 'Escape' && quote) {
2790
+ e.stopPropagation?.();
2791
+ setQuote(null);
2792
+ }
2885
2793
  },
2886
2794
  style: { flex: 1, minWidth: 0, minHeight: 32, maxHeight: 200, resize: 'none', border: 'none', outline: 'none', background: 'transparent', color: C.primary, font: 'inherit', fontSize: FONT, lineHeight: 1.5, padding: '6px 8px' },
2887
2795
  }),
@@ -2901,35 +2809,61 @@ button.dshb-tline:hover{background:${C.hover}}
2901
2809
  ),
2902
2810
  ),
2903
2811
  ),
2904
- // Last in the tree: the topic beside the chat (over it when the panel is narrow).
2905
- open ? h(ThreadPane, { key: open, t, bot, rootId: open, base: index, baseTopics: topics, local, onClose: () => setOpen(''), onSend: sendText, onRetry: retry, onSeen: markSeen }) : null,
2812
+ // Last in the tree: the thread beside the chat (over it when the panel is narrow).
2813
+ open
2814
+ ? h(ThreadPane, {
2815
+ key: open,
2816
+ t,
2817
+ bot,
2818
+ rootId: open,
2819
+ base: index,
2820
+ local,
2821
+ onClose: () => setOpen(''),
2822
+ onSend: sendText,
2823
+ onRetry: retry,
2824
+ onSeen: () => void reload(),
2825
+ onListed: dropListed,
2826
+ })
2827
+ : null,
2906
2828
  );
2907
2829
  }
2908
2830
 
2909
2831
  /**
2910
- * One topic beside the chat: its root, every reply (and the messages the dispatcher moved into it),
2911
- * its tasks while they run, and a composer whose messages go into this topic (or answer one of its
2912
- * messages). It polls the topic on its own, starting from what the chat already shows.
2832
+ * One thread beside the chat (PLAN-0.10 §7.7): its root on top, the replies under it (and its tasks
2833
+ * while they run), and a composer whose messages go into this thread, answering its root or one of
2834
+ * its messages; a thread has no threads of its own. It polls the thread on its own, starting from
2835
+ * what the chat already knows, and tells the Host when its new replies have been read.
2913
2836
  */
2914
- function ThreadPane({ t, bot, rootId, base, baseTopics, local, onClose, onSend, onRetry, onSeen }) {
2915
- const { items, topics } = useMessages(bot.id, true, rootId);
2837
+ function ThreadPane({ t, bot, rootId, base, local, onClose, onSend, onRetry, onSeen, onListed }) {
2838
+ const { items, threads, reload } = useMessages(bot.id, true, rootId);
2916
2839
  const [text, setText] = useState('');
2917
2840
  const [quote, setQuote] = useState(null);
2918
- const fromBase = [base.byId.get(rootId), ...(base.roots.get(rootId)?.replies ?? [])].filter(Boolean);
2919
- const list = mergeLocal(Array.isArray(items) && items.length ? items : fromBase, local) ?? [];
2841
+ const seenAsked = useRef('');
2842
+ const known = base.roots.get(rootId);
2843
+ const fromBase = [base.byId.get(rootId), ...(known?.replies ?? [])].filter(Boolean);
2844
+ // What the thread lists, with what the chat already knew of it (sent from here, rows of 0.9) and what is being sent.
2845
+ const list = mergeLocal(mergeLocal(Array.isArray(items) && items.length ? items : fromBase, fromBase), local) ?? [];
2920
2846
  const root = list.find((m) => m?.id === rootId) ?? base.byId.get(rootId) ?? null;
2921
2847
  const seenIds = new Set();
2922
2848
  const replies = list
2923
- .filter((m) => inTopic(m, rootId) && !seenIds.has(m.id) && seenIds.add(m.id))
2849
+ .filter((m) => inThread(m, rootId) && !seenIds.has(m.id) && seenIds.add(m.id))
2924
2850
  .sort((a, b) => (toMs(a.at) || 0) - (toMs(b.at) || 0));
2925
- const shown = root ? [root, ...replies] : replies;
2926
- const lastAt = Math.max(toMs(root?.at) || 0, ...replies.map((m) => toMs(m.at) || 0));
2927
- const tasks = topicTasks({ topics: Array.isArray(items) ? topics : baseTopics }, rootId);
2851
+ const summary = Array.isArray(items) ? summaryOf(threads, rootId) : known?.summary ?? null;
2852
+ const facts = threadFacts({ summary, replies: [] });
2928
2853
  const stick = useStickToBottom(`${replies.length}:${replies[replies.length - 1]?.id ?? ''}`);
2929
- // Open means read: what arrives while it is open is read too.
2930
2854
  useEffect(() => {
2931
- onSeen?.(rootId, lastAt);
2932
- }, [rootId, lastAt]);
2855
+ if (Array.isArray(items)) onListed?.(items);
2856
+ }, [items]);
2857
+ // Open, on screen and loaded: its new replies are read (once per state of the thread).
2858
+ const seenKey = `${rootId}:${facts.lastAt}:${facts.unread}`;
2859
+ useEffect(() => {
2860
+ if (!Array.isArray(items) || facts.unread <= 0 || !visible() || seenAsked.current === seenKey) return;
2861
+ seenAsked.current = seenKey;
2862
+ void postJson('threads/seen', { bot: bot.id, root: rootId }).then(() => {
2863
+ void reload();
2864
+ onSeen?.();
2865
+ });
2866
+ }, [seenKey, items === null]);
2933
2867
  const send = () => {
2934
2868
  const body = text.trim();
2935
2869
  if (!body) return;
@@ -2937,9 +2871,13 @@ button.dshb-tline:hover{background:${C.hover}}
2937
2871
  setText('');
2938
2872
  setQuote(null);
2939
2873
  stick.stick();
2940
- void onSend(body, replyTo, '', rootId).then(() => stick.stick());
2874
+ void onSend(body, replyTo, '', rootId).then(() => {
2875
+ stick.stick();
2876
+ void reload();
2877
+ });
2941
2878
  };
2942
2879
  const count = replies.filter((m) => !isTraffic(m)).length;
2880
+ const pick = (m) => setQuote(m.id === rootId ? null : m);
2943
2881
  return h(
2944
2882
  'aside',
2945
2883
  {
@@ -2956,30 +2894,46 @@ button.dshb-tline:hover{background:${C.hover}}
2956
2894
  h(
2957
2895
  'div',
2958
2896
  { style: { display: 'flex', flexDirection: 'column', minWidth: 0, flex: 1 } },
2959
- h('span', { style: { fontWeight: 700, fontSize: SMALL } }, t('topicTitle')),
2897
+ h('span', { style: { fontWeight: 700, fontSize: SMALL } }, t('threadPaneTitle')),
2960
2898
  h('span', { 'data-dsh-bots-thread-title': true, style: { fontSize: TINY, color: C.muted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, root ? excerpt(root.text, 80) : ''),
2961
2899
  ),
2962
- h('button', { type: 'button', className: 'dshb-btn dshb-btn-ghost dshb-btn-sm dshb-btn-icon', 'data-dsh-bots-thread-close': rootId, title: t('closeTopic'), 'aria-label': t('closeTopic'), onClick: onClose }, Icon.close(14)),
2900
+ h('button', { type: 'button', className: 'dshb-btn dshb-btn-ghost dshb-btn-sm dshb-btn-icon', 'data-dsh-bots-thread-close': rootId, title: t('closeThread'), 'aria-label': t('closeThread'), onClick: onClose }, Icon.close(14)),
2963
2901
  ),
2964
- tasks.length ? h('div', { 'data-dsh-bots-thread-tasks': tasks.length, style: { padding: '6px 10px', borderBottom: `1px solid ${C.border1}`, display: 'flex', flexDirection: 'column', gap: 2, maxHeight: '32%', overflow: 'auto' } }, tasks.map((row) => h(TaskRow, { key: row.id, t, row }))) : null,
2902
+ facts.tickets.length ? h('div', { 'data-dsh-bots-thread-tasks': facts.tickets.length, style: { padding: '6px 10px', borderBottom: `1px solid ${C.border1}`, display: 'flex', flexDirection: 'column', gap: 2, maxHeight: '32%', overflow: 'auto' } }, facts.tickets.map((row) => h(TaskRow, { key: row.id, t, row }))) : null,
2965
2903
  h(
2966
2904
  'div',
2967
2905
  { className: 'dshb-scroll', 'data-dsh-bots-thread-body': rootId, ref: stick.box, onScroll: stick.onScroll, style: { flex: 1, padding: '4px 16px 12px' } },
2968
2906
  h(
2969
2907
  'div',
2970
2908
  { ref: stick.content },
2971
- shown.length
2909
+ root ? h(MessageList, { t, items: [root], botId: bot.id, onReply: pick, onRetry, empty: null }) : null,
2910
+ h(
2911
+ 'div',
2912
+ { className: 'dshb-threaddiv', 'data-dsh-bots-thread-count': count },
2913
+ h('span', { className: 'dshb-threaddiv-line' }),
2914
+ h('span', { style: { flex: 'none', maxWidth: '80%', textAlign: 'center' } }, count ? t(count === 1 ? 'threadReplyOne' : 'threadReplies', { n: count }) : t('threadEmpty')),
2915
+ h('span', { className: 'dshb-threaddiv-line' }),
2916
+ ),
2917
+ replies.length
2972
2918
  ? h(MessageList, {
2973
2919
  t,
2974
- items: shown,
2920
+ items: replies,
2975
2921
  botId: bot.id,
2976
- onReply: (m) => setQuote(m.id === rootId ? null : m),
2922
+ onReply: pick,
2977
2923
  onRetry,
2978
2924
  movedIn: (m) => m.movedTo === rootId && m.id !== rootId,
2925
+ // In the thread the root goes without saying: a reply quotes another message of it only.
2926
+ quoteOf: (m) => {
2927
+ const to = str(m.replyTo);
2928
+ if (!to || to === rootId || m.from !== 'user') return null;
2929
+ if (m.quote?.id === to) return m.quote;
2930
+ const target = list.find((x) => x?.id === to);
2931
+ return target ? { id: target.id, from: target.from, text: str(target.text), ...(str(target.who) ? { who: str(target.who) } : {}) } : null;
2932
+ },
2979
2933
  empty: null,
2980
2934
  })
2981
2935
  : null,
2982
- h('div', { 'data-dsh-bots-thread-count': count, style: { fontSize: TINY, color: C.faint, textAlign: 'center', padding: '10px 0 0' } }, count ? t(count === 1 ? 'topicReplyOne' : 'topicReplies', { n: count }) : t('topicEmpty')),
2936
+ facts.running ? h('div', { 'data-dsh-bots-thread-working': rootId, style: { fontSize: TINY, color: C.label, padding: '6px 0 0 40px' } }, t('threadRunning')) : null,
2983
2937
  ),
2984
2938
  ),
2985
2939
  h(
@@ -2996,7 +2950,7 @@ button.dshb-tline:hover{background:${C.hover}}
2996
2950
  'data-dsh-bots-thread-composer': rootId,
2997
2951
  value: text,
2998
2952
  rows: Math.min(6, Math.max(1, text.split('\n').length)),
2999
- placeholder: t('topicComposer'),
2953
+ placeholder: t('threadComposer'),
3000
2954
  onChange: (e) => setText(e.target.value),
3001
2955
  onKeyDown: (e) => {
3002
2956
  if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
@@ -3685,6 +3639,20 @@ button.dshb-tline:hover{background:${C.hover}}
3685
3639
  }
3686
3640
 
3687
3641
  /** Once, after an upgrade moved an existing team to router mode: what changed and where to switch back. */
3642
+ /** The Bots the Host runs, as its state says (`botsVersion`; a Host that names it `version` as a string too), or ''. */
3643
+ const hostVersion = (state) => {
3644
+ const v = state?.botsVersion ?? state?.version;
3645
+ return typeof v === 'string' && /^\d+\.\d+\.\d+/.test(v.trim()) ? v.trim() : '';
3646
+ };
3647
+ /** The window reloaded after an update but Harness still runs the Bots it started with: say how to finish. */
3648
+ function VersionBanner({ t, server }) {
3649
+ return h(
3650
+ 'div',
3651
+ { role: 'status', 'data-dsh-bots-version-stale': server, className: 'dshb-fade', style: { display: 'flex', alignItems: 'center', gap: 10, margin: '12px 24px 0', padding: '9px 14px', borderRadius: 12, border: `1px solid ${tint(C.warn, 45)}`, background: tint(C.warn, 9), fontSize: SMALL, lineHeight: 1.5 } },
3652
+ h('span', { style: { color: C.warn, display: 'inline-flex', flex: 'none' } }, Icon.alert(15)),
3653
+ h('span', { style: { flex: 1, minWidth: 0 } }, t('versionStale', { server, client: BOTS_VERSION })),
3654
+ );
3655
+ }
3688
3656
  function RouterNoticeBanner({ t, onOpenDispatcher, onDismiss }) {
3689
3657
  return h(
3690
3658
  'div',
@@ -4060,6 +4028,8 @@ button.dshb-tline:hover{background:${C.hover}}
4060
4028
  const isPrimary = bot.role === 'primary' || bot.id === store.state?.primaryId;
4061
4029
  const routing = isPrimary && routerActiveOf();
4062
4030
  const routerDeny = new Set(routing ? routerDenyOf(catalog) : []);
4031
+ // In a team, Harness's sub-agents are off for the dispatcher: its teammates help instead (the other bots keep theirs).
4032
+ const teamDeny = new Set(isPrimary && Array.isArray(catalog?.teamDeny) ? catalog.teamDeny.map(String) : []);
4063
4033
  const routerAllow = new Set(draft.routerAllow);
4064
4034
  const routerBlocked = (names) => names.filter((x) => routerDeny.has(x) && !routerAllow.has(x));
4065
4035
  const inEffect = routing ? new Set([...draft.deny, ...routerBlocked([...routerDeny])]) : denied;
@@ -4150,9 +4120,10 @@ button.dshb-tline:hover{background:${C.hover}}
4150
4120
  'div',
4151
4121
  { 'data-dsh-bots-abilities': true, style: { display: 'flex', flexDirection: 'column', border: `1px solid ${C.border1}`, borderRadius: 12, overflow: 'hidden', background: C.layer1 } },
4152
4122
  abilities.map((ab, i) => {
4153
- const on = abilityOn(ab, inEffect);
4123
+ const teamOff = ab.available.length > 0 && ab.available.every((x) => teamDeny.has(x));
4124
+ const on = !teamOff && abilityOn(ab, inEffect);
4154
4125
  const warn = ab.risky && on;
4155
- const gated = ab.available.filter((x) => routerDeny.has(x));
4126
+ const gated = teamOff ? [] : ab.available.filter((x) => routerDeny.has(x));
4156
4127
  const blocked = routerBlocked(gated);
4157
4128
  const whole = gated.length > 0 && gated.length === ab.available.length;
4158
4129
  return h(
@@ -4167,6 +4138,7 @@ button.dshb-tline:hover{background:${C.hover}}
4167
4138
  { style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' } },
4168
4139
  h('span', { style: { fontWeight: 600, color: on ? C.primary : C.muted } }, pick(ab.name, lang)),
4169
4140
  ab.risky ? h(Badge, { color: '#d97706' }, Icon.alert(10), t('risky')) : null,
4141
+ teamOff ? h(Badge, { color: C.muted, title: t('teamOffHint'), 'data-dsh-bots-team-off': ab.id }, t('teamOff')) : null,
4170
4142
  gated.length
4171
4143
  ? blocked.length
4172
4144
  ? h(Badge, { color: C.muted, title: blocked.join(', '), 'data-dsh-bots-router-off': ab.id }, t(whole ? 'routerOff' : 'routerPartOff'))
@@ -4179,7 +4151,7 @@ button.dshb-tline:hover{background:${C.hover}}
4179
4151
  h('span', { style: { fontSize: TINY, color: C.muted } }, pick(ab.description, lang)),
4180
4152
  ),
4181
4153
  h('span', { className: 'dshb-mono', title: ab.available.join(', '), style: { fontSize: 11, color: C.faint, flex: 'none' } }, t('nTools', { n: ab.available.length })),
4182
- h(Switch, { on, title: pick(ab.name, lang), onChange: (v) => set(gated.length ? toggleRouterAbility(draft, ab, v, routerDeny) : { deny: toggleAbility(draft.deny, ab, v) }), 'data-dsh-bots-ability-switch': ab.id }),
4154
+ h(Switch, { on, disabled: teamOff, title: teamOff ? t('teamOffHint') : pick(ab.name, lang), onChange: (v) => set(gated.length ? toggleRouterAbility(draft, ab, v, routerDeny) : { deny: toggleAbility(draft.deny, ab, v) }), 'data-dsh-bots-ability-switch': ab.id }),
4183
4155
  );
4184
4156
  }),
4185
4157
  ),
@@ -5896,7 +5868,7 @@ button.dshb-tline:hover{background:${C.hover}}
5896
5868
  else if (tab === 'skills') body = h(SkillsTab, { key: bot.id, t, bot, toast, catalog, setTab, env });
5897
5869
  else if (tab === 'schedules') body = h(SchedulesTab, { key: bot.id, t, bot, toast, catalog });
5898
5870
  else if (tab === 'apps') body = h(AppsTab, { key: bot.id, t, bot, toast, catalog });
5899
- else if (tab === 'memory') body = h(MemoryTab, { key: bot.id, t, bot, toast, onSettings });
5871
+ else if (tab === 'memory') body = h(MemoryTab, { key: bot.id, t, bot, env, toast, onSettings });
5900
5872
  else body = h(ChatTab, { key: bot.id, t, bot, env, toast });
5901
5873
  return h(
5902
5874
  'div',
@@ -6538,13 +6510,16 @@ button.dshb-tline:hover{background:${C.hover}}
6538
6510
  }
6539
6511
  const memModelText = (t, m) => (m ? `${m.provider} · ${m.model}` : t('botsOwnModel'));
6540
6512
 
6541
- function MemoryTab({ t, bot, toast, onSettings }) {
6513
+ function MemoryTab({ t, bot, env, toast, onSettings }) {
6542
6514
  const { data, reload } = useJson(`memory?bot=${encodeURIComponent(bot.id)}`, 15_000);
6543
6515
  const [busy, setBusy] = useState(false);
6544
6516
  const name = bot.name || `@${bot.handle}`;
6545
6517
  const topic = data?.topic;
6546
6518
  const startTopic = () => {
6547
6519
  setBusy(true);
6520
+ // Harness may close the panel over the conversation this archives: it comes back on this bot (see ChatTab).
6521
+ store.rotatingAt = Date.now();
6522
+ store.lastChat = bot.id;
6548
6523
  postJson('topic/new', { id: bot.id })
6549
6524
  .then((r) => {
6550
6525
  if (r?.ok) {
@@ -6553,7 +6528,10 @@ button.dshb-tline:hover{background:${C.hover}}
6553
6528
  void refreshState();
6554
6529
  } else toast(r?.reason || t('actionFailed'), 'error');
6555
6530
  })
6556
- .finally(() => setBusy(false));
6531
+ .finally(() => {
6532
+ setBusy(false);
6533
+ env?.keepPanel?.(bot.id);
6534
+ });
6557
6535
  };
6558
6536
  return h(
6559
6537
  'div',
@@ -7520,6 +7498,7 @@ button.dshb-tline:hover{background:${C.hover}}
7520
7498
  h(
7521
7499
  'div',
7522
7500
  { style: { flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', minHeight: 0 } },
7501
+ hostVersion(s.state) && hostVersion(s.state) !== BOTS_VERSION ? h(VersionBanner, { t, server: hostVersion(s.state) }) : null,
7523
7502
  !noticeGone && routerNotice.pending(s.state)
7524
7503
  ? h(RouterNoticeBanner, {
7525
7504
  t,
@@ -7919,20 +7898,18 @@ button.dshb-tline:hover{background:${C.hover}}
7919
7898
  replyAction: 'Reply',
7920
7899
  replyingTo: 'Replying to {name}',
7921
7900
  cancelReply: 'Cancel the reply',
7922
- topicLabel: 'Topic',
7923
- topicTitle: 'Topic',
7924
- topicReplyOne: '1 reply',
7925
- topicReplies: '{n} replies',
7926
- topicEmpty: 'No replies yet.',
7927
- topicComposer: 'Reply in this topic',
7928
- topicUnread: 'New replies',
7929
- openTopic: 'Open the topic',
7930
- closeTopic: 'Close the topic',
7931
- movedTo: 'Put into “{title}”',
7932
- movedToTopic: 'Put into another topic',
7933
- movedIn: 'Moved into this topic',
7934
- newReplyOne: 'A topic has a new reply',
7935
- newReplies: '{n} topics have new replies',
7901
+ threadWord: 'Thread',
7902
+ threadPaneTitle: 'Thread',
7903
+ threadReplyOne: '1 reply',
7904
+ threadReplies: '{n} replies',
7905
+ threadEmpty: 'No replies yet. Replying here quotes this message',
7906
+ quoteWho: '{name}: ',
7907
+ threadComposer: 'Reply in this thread',
7908
+ threadRunning: 'Replying…',
7909
+ openThread: 'Open the thread',
7910
+ closeThread: 'Close the thread',
7911
+ movedIn: 'Moved into this thread',
7912
+ versionStale: 'Harness still runs Bots {server}; this page is {client}. Quit and reopen Harness to finish the update.',
7936
7913
  msgPending: 'Queued',
7937
7914
  msgPendingHint: 'Delivered; the bot takes it as soon as it finishes its current step.',
7938
7915
  msgFailed: 'Not sent',
@@ -8526,6 +8503,8 @@ button.dshb-tline:hover{background:${C.hover}}
8526
8503
  routerWaiting: 'Router mode starts once the team has another bot; until then {name} does the work itself.',
8527
8504
  abilitiesRouterHint: 'What {name} can do with the Harness’s built-in tools. In Router mode it does not run commands, write files, use sub-agents, draw or make Office files; turn one back on below if it needs it.',
8528
8505
  routerOff: 'Off in Router mode',
8506
+ teamOff: 'Off for the dispatcher',
8507
+ teamOffHint: 'The dispatcher hands work in parallel to its teammates, so the panel shows it as their tasks. The other bots keep sub-agents.',
8529
8508
  routerPartOff: 'Partly off in Router mode',
8530
8509
  routerAllowed: 'On in Router mode',
8531
8510
  routerAllowBack: 'Turn back on',
@@ -8817,20 +8796,18 @@ button.dshb-tline:hover{background:${C.hover}}
8817
8796
  replyAction: '回复',
8818
8797
  replyingTo: '回复 {name}',
8819
8798
  cancelReply: '取消回复',
8820
- topicLabel: '话题',
8821
- topicTitle: '话题',
8822
- topicReplyOne: '1 条回复',
8823
- topicReplies: '{n} 条回复',
8824
- topicEmpty: '还没有回复。',
8825
- topicComposer: '在话题里回复',
8826
- topicUnread: '有新回复',
8827
- openTopic: '打开话题',
8828
- closeTopic: '关闭话题',
8829
- movedTo: '已归入「{title}」',
8830
- movedToTopic: '已归入另一个话题',
8831
- movedIn: '归入此话题',
8832
- newReplyOne: '1 个话题有新回复',
8833
- newReplies: '{n} 个话题有新回复',
8799
+ threadWord: '讨论串',
8800
+ threadPaneTitle: '讨论串',
8801
+ threadReplyOne: '1 条回复',
8802
+ threadReplies: '{n} 条回复',
8803
+ threadEmpty: '还没有回复。在这里回复会引用这条消息',
8804
+ quoteWho: '{name}:',
8805
+ threadComposer: '在讨论串里回复',
8806
+ threadRunning: '正在回复…',
8807
+ openThread: '打开讨论串',
8808
+ closeThread: '关闭讨论串',
8809
+ movedIn: '归入此讨论串',
8810
+ versionStale: 'Harness 里运行的还是 Bots {server},界面是 {client}。退出并重新打开 Harness 后生效。',
8834
8811
  msgPending: '排队中',
8835
8812
  msgPendingHint: '已送达,bot 做完手头这一步就会看到。',
8836
8813
  msgFailed: '发送失败',
@@ -9308,7 +9285,7 @@ button.dshb-tline:hover{background:${C.hover}}
9308
9285
  channelPrivate: '只有配对过的人能找到团队,其他人一律忽略(每天最多回一句“这是私人 Bot”)。在群里,只有 @ 它或回复它时才会回答。',
9309
9286
  viaChannel: '{app} · {who}',
9310
9287
  sentToChannel: '也已发到 {app}',
9311
- threadPart: '话题',
9288
+ threadPart: '讨论串',
9312
9289
  threadTopic: '话题',
9313
9290
  notSent: '未发出',
9314
9291
  notSentChats: '没有发到任何聊天:这一轮涉及多个聊天({chats})。',
@@ -9413,6 +9390,8 @@ button.dshb-tline:hover{background:${C.hover}}
9413
9390
  routerWaiting: '团队里再有一个 Bot 后才开始只调度,在此之前 {name} 自己动手。',
9414
9391
  abilitiesRouterHint: '{name} 能用 Harness 内置工具做哪些事。只调度时它不执行命令、不写文件、不用子代理、不作图也不做 Office 文档;确实需要时可以在下面逐项打开。',
9415
9392
  routerOff: '只调度时关闭',
9393
+ teamOff: '调度员不用',
9394
+ teamOffHint: '调度员把要并行的活交给队友,面板里能看到他们各自的任务;其他 bot 照常可以用子代理。',
9416
9395
  routerPartOff: '只调度时部分关闭',
9417
9396
  routerAllowed: '只调度时也可用',
9418
9397
  routerAllowBack: '重新打开',
@@ -9436,7 +9415,7 @@ button.dshb-tline:hover{background:${C.hover}}
9436
9415
  setStallHint: '进行中的任务这么久没动静,先请它汇报;之后仍没动静就标为卡住。',
9437
9416
  setArchive: '任务完成多少小时后归档会话',
9438
9417
  usageAllTasks: '显示全部 {n} 个任务',
9439
- setArchiveHint: '在此之前,它所在话题或回复串里的新消息会让这个任务继续。',
9418
+ setArchiveHint: '在此之前,它所在讨论串里的新消息会让这个任务继续。',
9440
9419
  // 用量、记忆、话题、设置、模型来源
9441
9420
  settings: '设置',
9442
9421
  usage: '用量',
@@ -9653,6 +9632,79 @@ button.dshb-tline:hover{background:${C.hover}}
9653
9632
  return false;
9654
9633
  }
9655
9634
  };
9635
+ /** The central panel Harness shows: its id, null for a conversation, undefined when it cannot say. */
9636
+ const shownPanel = () => {
9637
+ try {
9638
+ const obs = service('layout')?.panelInfo;
9639
+ const v = typeof obs?.getSnapshot === 'function' ? obs.getSnapshot() : typeof obs?.get === 'function' ? obs.get() : obs?.value;
9640
+ return v && typeof v === 'object' && 'activePanelId' in v ? v.activePanelId : undefined;
9641
+ } catch {
9642
+ return undefined;
9643
+ }
9644
+ };
9645
+ /** Show the panel again, on the chat it showed. */
9646
+ const bringBack = (botId) => {
9647
+ if (botId) navigate(botId);
9648
+ return openPanel();
9649
+ };
9650
+ /**
9651
+ * A new topic archives the bot's last conversation, and when that is the conversation behind the
9652
+ * panel Harness closes the panel to show nothing (PLAN-0.10 §2.4). Closed within a moment of a
9653
+ * topic starting (from here, or one the Host started: the state's `rotatedAt`), it comes back.
9654
+ */
9655
+ const watchPanel = (layout) => {
9656
+ let obs;
9657
+ try {
9658
+ obs = layout?.panelInfo;
9659
+ } catch {
9660
+ obs = undefined;
9661
+ }
9662
+ if (!obs || typeof obs.subscribe !== 'function') return () => {};
9663
+ let last = shownPanel();
9664
+ const timers = new Set();
9665
+ const later = (fn, ms) => {
9666
+ const id = setTimeout(() => {
9667
+ timers.delete(id);
9668
+ fn();
9669
+ }, ms);
9670
+ timers.add(id);
9671
+ };
9672
+ const onChange = (v) => {
9673
+ const now = v && typeof v === 'object' && 'activePanelId' in v ? v.activePanelId : shownPanel();
9674
+ const was = last;
9675
+ last = now;
9676
+ if (was !== PANEL_ID || now !== null) return;
9677
+ const at = Date.now();
9678
+ if (at - (Number(store.rotatingAt) || 0) < ROTATE_WINDOW_MS) return void bringBack(store.lastChat);
9679
+ // The Host may have started the topic (a message after a quiet spell, a long conversation): ask it, twice at most.
9680
+ const check = (tries) =>
9681
+ Promise.resolve(refreshState()).then((st) => {
9682
+ const rotated = Number(st?.rotatedAt) || 0;
9683
+ if (rotated && Math.abs(rotated - (at + (Number(store.skew) || 0))) < ROTATE_WINDOW_MS) {
9684
+ if (shownPanel() === null) bringBack(store.lastChat);
9685
+ } else if (tries > 1) later(() => void check(tries - 1), 1200);
9686
+ });
9687
+ void check(2).catch(() => {});
9688
+ };
9689
+ let off;
9690
+ try {
9691
+ off = obs.subscribe(onChange);
9692
+ } catch {
9693
+ return () => {};
9694
+ }
9695
+ return () => {
9696
+ for (const id of timers) clearTimeout(id);
9697
+ try {
9698
+ if (typeof off === 'function') off();
9699
+ else off?.unsubscribe?.();
9700
+ } catch {
9701
+ // Gone with the layout.
9702
+ }
9703
+ };
9704
+ };
9705
+ // The layout service may come up after this client does.
9706
+ if (typeof ctx.inject === 'function') ctx.inject(['layout'], (scope) => scope.effect(() => watchPanel(scope.layout ?? service('layout')), 'bots: the panel stays open over a new topic'));
9707
+ else ctx.effect(() => watchPanel(service('layout')), 'bots: the panel stays open over a new topic');
9656
9708
  const openSession = (id) => {
9657
9709
  try {
9658
9710
  const ws = service('uiWorkspace');
@@ -9696,6 +9748,14 @@ button.dshb-tline:hover{background:${C.hover}}
9696
9748
  return openPanel();
9697
9749
  },
9698
9750
  openPanel,
9751
+ /** After a topic started from here: the panel was closed over it (now, or a moment later), so it comes back. */
9752
+ keepPanel: (botId) => {
9753
+ const again = () => {
9754
+ if (shownPanel() === null) bringBack(botId);
9755
+ };
9756
+ again();
9757
+ setTimeout(again, 1500);
9758
+ },
9699
9759
  sessionTitle: (id) => {
9700
9760
  try {
9701
9761
  const title = service('sessions')?.list?.getSnapshot?.()?.byId?.[id]?.displayTitle;