@kadaliao/dsh-bots 0.8.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). */
@@ -789,6 +793,30 @@ button.dshb-tline:hover{background:${C.hover}}
789
793
  .dshb-seg button{height:26px;padding:0 11px;border:none;border-radius:7px;background:transparent;color:${C.muted};font:inherit;font-size:${SMALL};font-weight:550;cursor:pointer;white-space:nowrap}
790
794
  .dshb-seg button:hover{color:${C.primary}}
791
795
  .dshb-seg button[data-active=true]{background:${C.layer1};color:${C.primary};box-shadow:0 1px 2px rgba(0,0,0,.12),0 0 0 1px ${C.border1}}
796
+ .dshb-chatwrap{display:flex;flex:1;min-height:0;min-width:0;position:relative;container-type:inline-size}
797
+ .dshb-chatmain{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0}
798
+ .dshb-composer{display:flex;flex-direction:column;gap:6px;padding:6px;border-radius:14px;border:1px solid ${C.border};background:${C.layer1};min-width:0}
799
+ .dshb-quote{display:flex;align-items:center;gap:6px;min-width:0;padding:5px 8px;border-radius:9px;background:${tint(C.label, 9)};border-left:3px solid ${C.label};font-size:${TINY}}
800
+ .dshb-msg{position:relative;min-width:0}
801
+ .dshb-msg-act{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border-radius:7px;border:1px solid ${C.border1};background:${C.base};color:${C.muted};font:inherit;font-size:${TINY};cursor:pointer;opacity:0;transition:opacity .12s;flex:none;white-space:nowrap}
802
+ .dshb-msg:hover .dshb-msg-act,.dshb-msg:focus-within .dshb-msg-act,.dshb-msg-act:focus-visible{opacity:1}
803
+ .dshb-msg-act:hover{color:${C.primary};background:${C.hover}}
804
+ .dshb-msg-actbox{position:absolute;top:0;right:0;z-index:1}
805
+ @media (hover:none){.dshb-msg-act{opacity:.65}}
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}}
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}}
817
+ .dshb-threadhead{display:flex;align-items:center;gap:10px;padding:12px 12px 10px 16px;border-bottom:1px solid ${C.border1};min-width:0}
818
+ @container (max-width: 860px){.dshb-threadpane{position:absolute;inset:0;width:auto;z-index:6;border-left:none}}
819
+ @media (max-width: 760px){.dshb-threadpane{position:absolute;inset:0;width:auto;z-index:6;border-left:none}}
792
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)}}}
793
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)}}
794
822
  @keyframes dshb-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
@@ -1319,14 +1347,19 @@ button.dshb-tline:hover{background:${C.hover}}
1319
1347
  return h('span', { style: { width: size, height: size, borderRadius: '50%', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', background: C.layer3, color: C.muted, flex: 'none' } }, glyph);
1320
1348
  }
1321
1349
 
1322
- /** A thread of one bot: the user's prompts right, the bot's replies left, DMs as cards. */
1323
- function MessageList({ t, items, botId, empty }) {
1350
+ /**
1351
+ * A thread of one bot: the user's prompts right, the bot's replies left, DMs as cards. With `fold`
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.
1354
+ */
1355
+ function MessageList({ t, items, botId, empty, fold = null, onReply, onRetry, movedIn, quoteOf, onQuote }) {
1324
1356
  const count = items.length;
1325
1357
  if (count === 0) return empty;
1326
1358
  const names = threadNamesOf(items);
1327
1359
  const rows = [];
1328
1360
  let lastDay = '';
1329
- items.forEach((m, i) => {
1361
+ const shown = (fold ? fold.index.main : items).filter((m) => !selfTalk(m));
1362
+ shown.forEach((m, i) => {
1330
1363
  const at = toMs(m.at);
1331
1364
  let day = '';
1332
1365
  try {
@@ -1359,10 +1392,15 @@ button.dshb-tline:hover{background:${C.hover}}
1359
1392
  else rows.push({ traffic: true, key: `g${m.id ?? i}`, items: [m] });
1360
1393
  return;
1361
1394
  }
1362
- const prev = items[i - 1];
1363
- // Answers to two chats of one turn keep their own headers (where each went), and so do two tasks.
1364
- const grouped = 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;
1365
- rows.push(h(MessageRow, { key: m.id ?? i, t, m, botId, grouped, names }));
1395
+ const prev = shown[i - 1];
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 }));
1366
1404
  });
1367
1405
  const level = botMessagesLevel();
1368
1406
  return h(
@@ -1371,8 +1409,63 @@ button.dshb-tline:hover{background:${C.hover}}
1371
1409
  rows.map((r) => (r && r.traffic ? h(BotTraffic, { key: r.key, t, items: r.items, level }) : r)),
1372
1410
  );
1373
1411
  }
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) {
1414
+ const r = fold?.index?.roots.get(rootId);
1415
+ if (!r) return false;
1416
+ const f = threadFacts(r);
1417
+ return f.running || (f.count > 0 && !r.together);
1418
+ }
1419
+
1420
+ /**
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.
1423
+ */
1424
+ function ThreadBar({ t, m, fold }) {
1425
+ const f = threadFacts(fold.index.roots.get(m.id));
1426
+ const mine = m.from === 'user';
1427
+ return h(
1428
+ 'div',
1429
+ { style: { display: 'flex', justifyContent: mine ? 'flex-end' : 'flex-start', paddingLeft: mine ? 0 : 40, margin: '3px 0 2px' } },
1430
+ h(
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'))
1437
+ : null,
1438
+ h('span', { style: { display: 'inline-flex', flex: 'none', opacity: 0.7 } }, Icon.arrow(10)),
1439
+ ),
1440
+ );
1441
+ }
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);
1449
+ return h(
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,
1462
+ );
1463
+ }
1464
+
1374
1465
  /** A message between two bots (a delegation, a report, a DM), or a scheduled prompt: secondary traffic. */
1375
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;
1376
1469
  /** How much of what bots say to each other a chat shows (a team setting): 'line' | 'short' | 'full'. */
1377
1470
  function botMessagesLevel() {
1378
1471
  const v = store.state?.display?.botMessages ?? store.settings?.settings?.display?.botMessages;
@@ -1496,7 +1589,41 @@ button.dshb-tline:hover{background:${C.hover}}
1496
1589
  );
1497
1590
  }
1498
1591
 
1499
- function MessageRow({ t, m, botId, grouped, names }) {
1592
+ /** "Reply" on a message, shown while the pointer is on it (always, faintly, without a pointer). */
1593
+ const ReplyAction = ({ t, m, onReply }) =>
1594
+ onReply && m?.id != null && !m.local
1595
+ ? h(
1596
+ 'button',
1597
+ {
1598
+ type: 'button',
1599
+ className: 'dshb-msg-act',
1600
+ 'data-dsh-bots-reply-to': m.id,
1601
+ title: t('replyAction'),
1602
+ onClick: (e) => {
1603
+ e?.stopPropagation?.();
1604
+ onReply(m);
1605
+ },
1606
+ },
1607
+ Icon.back(11),
1608
+ t('replyAction'),
1609
+ )
1610
+ : null;
1611
+ /** Under one of your messages: still waiting for the bot to take it, or not sent (with a way to send it again). */
1612
+ function SendState({ t, m, onRetry }) {
1613
+ if (m.failed) {
1614
+ return h(
1615
+ 'span',
1616
+ { 'data-dsh-bots-send-failed': m.id, style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: TINY, color: C.error } },
1617
+ Icon.alert(11),
1618
+ t('msgFailed'),
1619
+ onRetry ? h('button', { type: 'button', className: 'dshb-link', 'data-dsh-bots-resend': m.id, onClick: () => onRetry(m), style: { fontSize: TINY, color: C.error, fontWeight: 600 } }, t('resend')) : null,
1620
+ );
1621
+ }
1622
+ if (m.pending) return h('span', { 'data-dsh-bots-pending': m.id, title: t('msgPendingHint'), style: { fontSize: TINY, color: C.faint } }, t('msgPending'));
1623
+ return null;
1624
+ }
1625
+
1626
+ function MessageRow({ t, m, botId, grouped, names, onReply, onRetry, moved = false, quote = null, onQuote }) {
1500
1627
  if (m.kind === 'topic') {
1501
1628
  const at = toMs(m.at);
1502
1629
  return h(
@@ -1521,20 +1648,33 @@ button.dshb-tline:hover{background:${C.hover}}
1521
1648
  const notice = messageNotice(m);
1522
1649
  if (between || m.kind === 'system') return h(BotTraffic, { t, items: [m], level: botMessagesLevel() });
1523
1650
  if (mine) {
1651
+ const state = m.pending || m.failed ? h(SendState, { t, m, onRetry }) : null;
1524
1652
  return h(
1525
1653
  'div',
1526
- { 'data-dsh-bots-msg': 'user', className: 'dshb-fade', style: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, marginTop: grouped ? 0 : 6 } },
1527
- grouped
1654
+ { 'data-dsh-bots-msg': 'user', 'data-dsh-bots-msg-id': m.id, 'data-local': m.local ? 'true' : undefined, className: 'dshb-msg dshb-fade', style: { display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 3, marginTop: grouped ? 0 : 6 } },
1655
+ grouped && !moved
1528
1656
  ? null
1529
1657
  : h(
1530
1658
  'span',
1531
- { style: { fontSize: TINY, color: C.faint, display: 'inline-flex', alignItems: 'center', gap: 6 } },
1659
+ { style: { fontSize: TINY, color: C.faint, display: 'inline-flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' } },
1660
+ moved ? h(Badge, { color: C.muted, 'data-dsh-bots-moved-in': m.id }, Icon.layers(10), t('movedIn')) : null,
1532
1661
  m.via ? h(Badge, { color: CHANNEL_COLORS[m.via] ?? C.muted, 'data-dsh-bots-via': m.via }, t('viaChannel', { app: channelName(m.via, t), who: str(m.who) || t('you') })) : null,
1533
1662
  m.to !== botId && to.kind === 'bot' ? `${t('toName', { name: to.name })} · ${time}` : time,
1534
1663
  // A message from a chat that went straight to the task it follows up on.
1535
1664
  ticketId ? h('button', { type: 'button', className: 'dshb-link', 'data-dsh-bots-report-task': ticketId, title: m.via ? t('followUpHint') : undefined, onClick: () => openTicket(ticketId), style: { fontSize: TINY } }, t(m.via ? 'followUpTask' : 'openTask')) : null,
1536
1665
  ),
1537
- h('div', { style: { maxWidth: '78%', padding: '8px 12px', borderRadius: '14px 14px 4px 14px', background: C.label, color: C.onLabel, fontSize: FONT } }, h(Clamp, { t, text: m.text, lines: 14, light: true })),
1666
+ h(
1667
+ 'div',
1668
+ { style: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6, width: '100%', minWidth: 0 } },
1669
+ h(ReplyAction, { t, m, onReply }),
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
+ ),
1676
+ ),
1677
+ state,
1538
1678
  h('div', { style: { width: 'min(480px, 78%)', display: 'flex', justifyContent: 'flex-end' } }, h(LinkCards, { t, text: m.text, align: 'flex-end' })),
1539
1679
  );
1540
1680
  }
@@ -1542,28 +1682,34 @@ button.dshb-tline:hover{background:${C.hover}}
1542
1682
  const place = m.via ? (isChatThread(m.thread) ? threadName(t, m.thread, names) : channelName(m.via, t)) : '';
1543
1683
  // With several chats in the turn, plain text reached none of them (bot_reply says where each answer goes).
1544
1684
  const choices = m.notSent === true && Array.isArray(m.choices) ? m.choices.filter(isChatThread) : [];
1685
+ // A teammate answering you itself, in this chat (the bot that did a task): its own face and name, the task.
1686
+ const worker = m.kind === 'reply' && m.from !== botId && from.kind === 'bot' && Boolean(ticketId);
1545
1687
  // A bot speaking to you reads like the main conversation: no box, full-strength text.
1546
1688
  return h(
1547
1689
  'div',
1548
- { 'data-dsh-bots-msg': m.kind || 'reply', className: 'dshb-fade', style: { display: 'flex', gap: 10, alignItems: 'flex-start', marginTop: grouped ? 4 : 12 } },
1690
+ { 'data-dsh-bots-msg': m.kind || 'reply', 'data-dsh-bots-msg-id': m.id, 'data-dsh-bots-worker': worker ? m.from : undefined, className: 'dshb-msg dshb-fade', style: { display: 'flex', gap: 10, alignItems: 'flex-start', marginTop: grouped ? 4 : 12 } },
1549
1691
  h('div', { style: { width: 30, flex: 'none' } }, grouped ? null : h(PartyAvatar, { p: from, size: 30 })),
1550
1692
  h(
1551
1693
  'div',
1552
1694
  { style: { display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0, flex: 1, maxWidth: 760 } },
1695
+ onReply ? h('div', { className: 'dshb-msg-actbox' }, h(ReplyAction, { t, m, onReply })) : null,
1553
1696
  grouped
1554
1697
  ? null
1555
1698
  : h(
1556
1699
  'div',
1557
- { style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: TINY } },
1700
+ { style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: TINY, flexWrap: 'wrap' } },
1701
+ moved ? h(Badge, { color: C.muted, 'data-dsh-bots-moved-in': m.id }, Icon.layers(10), t('movedIn')) : null,
1558
1702
  h('span', { style: { fontWeight: 700, fontSize: SMALL, color: C.primary } }, from.name),
1559
1703
  from.kind === 'bot' ? h('span', { style: { color: C.faint } }, `@${from.bot.handle}`) : null,
1560
1704
  m.to !== 'user' && to.kind === 'bot' && m.to !== botId ? h('span', { style: { color: C.faint } }, `→ ${to.name}`) : null,
1561
1705
  h('span', { style: { color: C.faint } }, time),
1562
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,
1563
- 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,
1564
1709
  notice ? h(StageChip, { t, stage: notice }) : null,
1565
1710
  ticketId ? h('button', { type: 'button', className: 'dshb-link', 'data-dsh-bots-report-task': ticketId, onClick: () => openTicket(ticketId), style: { fontSize: TINY } }, t('openTask')) : null,
1566
1711
  ),
1712
+ quote ? h(QuoteLine, { t, q: quote, onOpen: onQuote ? () => onQuote(m) : null }) : null,
1567
1713
  h('div', { className: 'dshb-reply', 'data-dsh-bots-reply-text': true }, h(Clamp, { t, text: m.text, lines: 24, variant: 'body' })),
1568
1714
  choices.length
1569
1715
  ? h(
@@ -1574,6 +1720,7 @@ button.dshb-tline:hover{background:${C.hover}}
1574
1720
  )
1575
1721
  : null,
1576
1722
  h(LinkCards, { t, text: m.text }),
1723
+ worker && !grouped ? h('div', { 'data-dsh-bots-worker-task': ticketId }, h(TaskCard, { t, id: ticketId, botId: m.from })) : null,
1577
1724
  ),
1578
1725
  );
1579
1726
  }
@@ -2104,33 +2251,161 @@ button.dshb-tline:hover{background:${C.hover}}
2104
2251
  return v;
2105
2252
  }
2106
2253
 
2107
- function useMessages(botId, active = true) {
2108
- const [items, setItems] = useState(null);
2254
+ /**
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.
2258
+ */
2259
+ function useMessages(botId, active = true, topic = '') {
2260
+ const [data, setData] = useState(null);
2109
2261
  const [failed, setFailed] = useState(false);
2110
2262
  const alive = useRef(true);
2111
2263
  useEffect(() => {
2112
2264
  alive.current = true;
2113
- setItems(null);
2265
+ setData(null);
2114
2266
  return () => {
2115
2267
  alive.current = false;
2116
2268
  };
2117
- }, [botId]);
2269
+ }, [botId, topic]);
2118
2270
  const load = () =>
2119
2271
  Promise.resolve()
2120
- .then(() => getJson(`messages?limit=200${botId ? `&bot=${encodeURIComponent(botId)}` : ''}`))
2272
+ .then(() => getJson(`messages?limit=${topic ? 500 : 200}${botId ? `&bot=${encodeURIComponent(botId)}` : ''}${topic ? `&topic=${encodeURIComponent(topic)}` : ''}`))
2121
2273
  .then((r) => {
2122
2274
  if (!alive.current) return;
2123
2275
  if (r && Array.isArray(r.items)) {
2124
2276
  setFailed(false);
2125
- setItems((prev) => (prev && prev.length === r.items.length && prev[prev.length - 1]?.id === r.items[r.items.length - 1]?.id ? prev : r.items));
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 }));
2126
2282
  } else setFailed(true);
2127
2283
  })
2128
2284
  .catch(() => {
2129
2285
  if (alive.current) setFailed(true);
2130
2286
  });
2131
- usePoll(() => (active ? load() : undefined), CHAT_POLL_MS, [botId, active]);
2132
- return { items, failed, reload: load };
2287
+ usePoll(() => (active ? load() : undefined), CHAT_POLL_MS, [botId, active, topic]);
2288
+ return { items: data ? data.items : null, threads: data ? data.threads : {}, failed, reload: load };
2289
+ }
2290
+
2291
+ // --- threads (PLAN-0.10): a reply to a message, talked over beside the chat --------------------
2292
+
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);
2297
+ /** Markdown as a line of plain text, for a preview: no emphasis marks, headings, list markers or link targets. */
2298
+ const plainPreview = (text) =>
2299
+ str(text)
2300
+ .replace(/```[\s\S]*?```/g, ' ')
2301
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
2302
+ .replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d+[.)]\s+)/gm, '')
2303
+ .replace(/(\*\*|__|~~|`)/g, '')
2304
+ .replace(/(^|[\s(])[*_](\S[^*_]*?)[*_](?=[\s).,!?:;,。!?:;]|$)/g, '$1$2')
2305
+ .replace(/\s+/g, ' ')
2306
+ .trim();
2307
+ /** A short excerpt of a message for a quote or a label. */
2308
+ const excerpt = (text, n = 48) => {
2309
+ const line = plainPreview(str(text).split('\n').find((l) => plainPreview(l) !== '') ?? '');
2310
+ return [...line].length > n ? `${[...line].slice(0, n - 1).join('').trimEnd()}…` : line;
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
+ };
2317
+ /**
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.
2321
+ */
2322
+ function threadIndex(items, threads = {}) {
2323
+ const byId = new Map();
2324
+ for (const m of items) if (m && m.id != null) byId.set(m.id, m);
2325
+ const roots = new Map();
2326
+ const rootOf = (id) => {
2327
+ let r = roots.get(id);
2328
+ if (!r) {
2329
+ r = { root: byId.get(id), replies: [], summary: summaryOf(threads, id) };
2330
+ roots.set(id, r);
2331
+ }
2332
+ return r;
2333
+ };
2334
+ const main = [];
2335
+ for (const m of items) {
2336
+ if (!m) continue;
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;
2343
+ }
2344
+ if (summaryOf(threads, m.id)) rootOf(m.id);
2345
+ }
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
+ }
2360
+ return { byId, roots, main };
2361
+ }
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 };
2133
2377
  }
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
+ }
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;
2396
+ }
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);
2407
+ }
2408
+
2134
2409
 
2135
2410
  /** A first chat: the bot's bio and three opening messages to start from. */
2136
2411
  function ChatEmpty({ t, bot, onPick }) {
@@ -2321,17 +2596,79 @@ button.dshb-tline:hover{background:${C.hover}}
2321
2596
  return list.length ? h('div', { 'data-dsh-bots-asks': list.length, className: 'dshb-scroll', style: { maxHeight: '45vh' } }, list.map((a) => h(AskCard, { key: a.id, t, ask: a, env, onAnswered }))) : null;
2322
2597
  };
2323
2598
 
2599
+ /** A chat's messages with the ones being sent from here (`local`) that the Host has not listed yet. */
2600
+ function mergeLocal(items, local) {
2601
+ if (!Array.isArray(items)) return items;
2602
+ if (!local.length) return items;
2603
+ const ids = new Set(items.map((m) => m?.id));
2604
+ const extra = local.filter((m) => !ids.has(m.id));
2605
+ return extra.length ? [...items, ...extra] : items;
2606
+ }
2607
+ /** The line above a composer naming the message a reply answers, with a way to drop it. */
2608
+ function QuoteBar({ t, m, onCancel, attr = 'data-dsh-bots-quote' }) {
2609
+ const who = party(t, m.from);
2610
+ return h(
2611
+ 'div',
2612
+ { [attr]: m.id, className: 'dshb-quote' },
2613
+ h('span', { style: { color: C.label, display: 'inline-flex', flex: 'none' } }, Icon.back(12)),
2614
+ h('span', { style: { fontWeight: 600, flex: 'none' } }, t('replyingTo', { name: who.name })),
2615
+ h('span', { style: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: C.muted } }, excerpt(m.text, 80)),
2616
+ h('button', { type: 'button', className: 'dshb-link', [`${attr}-cancel`]: m.id, title: t('cancelReply'), 'aria-label': t('cancelReply'), onClick: onCancel, style: { display: 'inline-flex', color: C.muted, flex: 'none' } }, Icon.close(12)),
2617
+ );
2618
+ }
2619
+
2324
2620
  function ChatTab({ t, bot, env, toast }) {
2325
- const { items, failed, reload } = useMessages(bot.id);
2621
+ const { items: listed, threads, failed, reload } = useMessages(bot.id);
2326
2622
  const [text, setText] = useState('');
2327
- const [sending, setSending] = useState(false);
2623
+ // Messages sent from here: shown at once (queued), then the Host's own copy; a failed one stays to be sent again.
2624
+ const [local, setLocal] = useState([]);
2625
+ // The thread open beside the chat; the message the next one replies to (quoted above the composer).
2626
+ const [open, setOpen] = useState('');
2627
+ const [quote, setQuote] = useState(null);
2628
+ const input = useRef(null);
2328
2629
  // The quick poll may know before the state does that it started or stopped.
2329
2630
  const live = liveBot(bot);
2330
2631
  const running = live.status === 'running' || Boolean(live.activity);
2331
- const thread = useStickToBottom(`${items?.length ?? 0}:${items?.[items.length - 1]?.id ?? ''}:${running}`);
2632
+ const items = mergeLocal(listed, local);
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));
2641
+ }
2642
+ }
2643
+ const lastMain = index.main[index.main.length - 1];
2644
+ const thread = useStickToBottom(`${index.main.length}:${lastMain?.id ?? ''}:${running}:${answering}:${Boolean(ownWork)}`);
2332
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)));
2653
+ };
2654
+ useEffect(() => dropListed(listed), [listed]);
2655
+ const openThread = (id) => {
2656
+ if (id) setOpen(id);
2657
+ };
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);
2661
+ try {
2662
+ input.current?.focus?.();
2663
+ } catch {
2664
+ // Focus is a nicety.
2665
+ }
2666
+ };
2667
+
2333
2668
  const startTopic = () => {
2334
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();
2335
2672
  postJson('topic/new', { id: bot.id })
2336
2673
  .then((r) => {
2337
2674
  if (r?.ok) {
@@ -2340,84 +2677,294 @@ button.dshb-tline:hover{background:${C.hover}}
2340
2677
  void refreshState();
2341
2678
  } else toast(r?.reason || t('actionFailed'), 'error');
2342
2679
  })
2343
- .finally(() => setTopicBusy(false));
2680
+ .finally(() => {
2681
+ setTopicBusy(false);
2682
+ env.keepPanel?.(bot.id);
2683
+ });
2684
+ };
2685
+ /**
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).
2689
+ */
2690
+ const sendText = (body, replyTo = '', again = '', root = '') => {
2691
+ const id = again || `local-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
2692
+ const target = replyTo ? index.byId.get(replyTo) : null;
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 } : {}) };
2697
+ setLocal((list) => [...list.filter((m) => m.id !== id), row]);
2698
+ return postJson('send', { to: bot.id, text: body, ...(replyTo ? { replyTo } : {}) }).then((r) => {
2699
+ if (r?.ok) {
2700
+ const msg = r.message && typeof r.message === 'object' && r.message.id != null ? r.message : null;
2701
+ setLocal((list) => list.flatMap((m) => (m.id !== id ? [m] : msg ? [{ ...msg, pending: msg.pending ?? true, chat: msg.chat ?? bot.id }] : [])));
2702
+ void reload();
2703
+ void refreshState();
2704
+ return { ok: true, topic: msg ? str(msg.topic) || topic : topic };
2705
+ }
2706
+ setLocal((list) => list.map((m) => (m.id === id ? { ...m, pending: false, failed: true } : m)));
2707
+ toast(r?.reason || t('sendFailed'), 'error');
2708
+ return { ok: false, topic };
2709
+ });
2710
+ };
2711
+ const retry = (m) => {
2712
+ if (!m?.local) return;
2713
+ const root = threadOfMsg(m);
2714
+ void sendText(str(m.text), root ? str(m.replyTo) || root : '', m.id, root);
2344
2715
  };
2345
2716
  const send = () => {
2346
2717
  const body = text.trim();
2347
- if (!body || sending) return;
2348
- setSending(true);
2718
+ if (!body) return;
2719
+ const to = quote?.id ?? '';
2720
+ setText('');
2721
+ setQuote(null);
2349
2722
  thread.stick();
2350
- postJson('send', { to: bot.id, text: body })
2351
- .then((r) => {
2352
- if (r?.ok) {
2353
- setText('');
2354
- thread.stick();
2355
- void reload();
2356
- void refreshState();
2357
- } else toast(r?.reason || t('sendFailed'), 'error');
2358
- })
2359
- .finally(() => setSending(false));
2723
+ void sendText(body, to).then(() => thread.stick());
2360
2724
  };
2361
2725
  // A pasted link previews above the composer, as it will in the thread.
2362
2726
  const previewUrl = linksIn(useDebounced(text, 400))[0] ?? '';
2727
+ const fold = { index, onOpen: openThread };
2363
2728
  return h(
2364
2729
  'div',
2365
- { style: { display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 } },
2730
+ { className: 'dshb-chatwrap', 'data-dsh-bots-chat': bot.id, 'data-thread-open': open || undefined },
2366
2731
  h(
2367
2732
  'div',
2368
- { className: 'dshb-scroll', 'data-dsh-bots-thread': bot.id, ref: thread.box, onScroll: thread.onScroll, style: { flex: 1, padding: '6px 24px' } },
2733
+ { className: 'dshb-chatmain' },
2369
2734
  h(
2370
2735
  'div',
2371
- { ref: thread.content },
2372
- items === null
2373
- ? h('div', { style: { padding: 24, color: C.faint, fontSize: SMALL, textAlign: 'center' } }, failed ? t('unavailable') : t('loading'))
2374
- : h(MessageList, {
2375
- t,
2376
- items,
2377
- botId: bot.id,
2378
- empty: h(ChatEmpty, { t, bot, onPick: setText }),
2379
- }),
2380
- running ? h('div', { style: { maxWidth: 880, margin: '0 auto' } }, h(WorkingRow, { t, bot, a: live.activity, attr: bot.id })) : null,
2736
+ {
2737
+ className: 'dshb-scroll',
2738
+ 'data-dsh-bots-thread': bot.id,
2739
+ ref: thread.box,
2740
+ onScroll: thread.onScroll,
2741
+ style: { flex: 1, padding: '6px 24px' },
2742
+ },
2743
+ h(
2744
+ 'div',
2745
+ { ref: thread.content },
2746
+ items === null
2747
+ ? h('div', { style: { padding: 24, color: C.faint, fontSize: SMALL, textAlign: 'center' } }, failed ? t('unavailable') : t('loading'))
2748
+ : h(MessageList, {
2749
+ t,
2750
+ items,
2751
+ botId: bot.id,
2752
+ fold,
2753
+ onReply: replyTo,
2754
+ onRetry: retry,
2755
+ quoteOf: (m, prev) => chatQuote(m, prev, index),
2756
+ onQuote: (m) => openThread(threadOfMsg(m) || m.id),
2757
+ empty: h(ChatEmpty, { t, bot, onPick: setText }),
2758
+ }),
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,
2760
+ ),
2761
+ ),
2762
+ h(
2763
+ 'div',
2764
+ { style: { padding: '10px 24px 16px', borderTop: `1px solid ${C.border1}`, background: C.base, position: 'relative' } },
2765
+ h(
2766
+ 'div',
2767
+ { style: { maxWidth: 880, margin: '0 auto' } },
2768
+ // Questions of its own conversation; a task's wait in the task.
2769
+ h(AskCards, { t, sessionId: bot.sessionId, env, onAnswered: () => void reload() }),
2770
+ previewUrl ? h('div', { 'data-dsh-bots-composer-preview': previewUrl, style: { marginBottom: 8, maxHeight: 260, overflow: 'auto' } }, h(LinkCard, { t, url: previewUrl })) : null,
2771
+ h(
2772
+ 'div',
2773
+ { className: 'dshb-composer' },
2774
+ quote ? h(QuoteBar, { t, m: quote, onCancel: () => setQuote(null) }) : null,
2775
+ h(
2776
+ 'div',
2777
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 8 } },
2778
+ h('textarea', {
2779
+ 'data-dsh-bots-composer': true,
2780
+ ref: input,
2781
+ value: text,
2782
+ rows: Math.min(8, Math.max(1, text.split('\n').length)),
2783
+ placeholder: t('composer', { handle: bot.handle }),
2784
+ onChange: (e) => setText(e.target.value),
2785
+ onKeyDown: (e) => {
2786
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
2787
+ e.preventDefault();
2788
+ send();
2789
+ } else if (e.key === 'Escape' && quote) {
2790
+ e.stopPropagation?.();
2791
+ setQuote(null);
2792
+ }
2793
+ },
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' },
2795
+ }),
2796
+ h(Btn, { kind: 'primary', icon: Icon.send(15), title: t('send'), disabled: !text.trim(), onClick: send, style: { borderRadius: 10, width: 34, height: 34 } }),
2797
+ ),
2798
+ ),
2799
+ h(
2800
+ 'div',
2801
+ { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 7, fontSize: TINY, color: C.faint, flexWrap: 'wrap' } },
2802
+ h('span', null, t('composerHint')),
2803
+ h('span', { style: { flex: 1 } }),
2804
+ bot.topic ? h('span', { 'data-dsh-bots-topic': true, title: t('topicNow', { when: fmtAgo(t, bot.topic.startedAt), n: bot.topic.tasks, ctx: fmtNum(bot.topic.context) }) }, t('topicShort', { n: bot.topic.tasks, ctx: fmtNum(bot.topic.context) })) : null,
2805
+ h('button', { type: 'button', className: 'dshb-link', title: t('newTopicHint'), disabled: running || topicBusy || !bot.sessionId, onClick: startTopic, 'data-dsh-bots-new-topic': 'chat', style: { fontSize: TINY, display: 'inline-flex', alignItems: 'center', gap: 4, opacity: running || !bot.sessionId ? 0.5 : 1 } }, Icon.plus(11), t('newTopic')),
2806
+ env.canOpen() ? h('span', { style: { color: C.faint } }, '·') : null,
2807
+ env.canOpen() ? h('button', { type: 'button', className: 'dshb-link', style: { fontSize: TINY, display: 'inline-flex', alignItems: 'center', gap: 4 }, onClick: () => env.openBot(bot) }, Icon.open(11), t('fullTranscript')) : null,
2808
+ ),
2809
+ ),
2381
2810
  ),
2382
2811
  ),
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,
2828
+ );
2829
+ }
2830
+
2831
+ /**
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.
2836
+ */
2837
+ function ThreadPane({ t, bot, rootId, base, local, onClose, onSend, onRetry, onSeen, onListed }) {
2838
+ const { items, threads, reload } = useMessages(bot.id, true, rootId);
2839
+ const [text, setText] = useState('');
2840
+ const [quote, setQuote] = useState(null);
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) ?? [];
2846
+ const root = list.find((m) => m?.id === rootId) ?? base.byId.get(rootId) ?? null;
2847
+ const seenIds = new Set();
2848
+ const replies = list
2849
+ .filter((m) => inThread(m, rootId) && !seenIds.has(m.id) && seenIds.add(m.id))
2850
+ .sort((a, b) => (toMs(a.at) || 0) - (toMs(b.at) || 0));
2851
+ const summary = Array.isArray(items) ? summaryOf(threads, rootId) : known?.summary ?? null;
2852
+ const facts = threadFacts({ summary, replies: [] });
2853
+ const stick = useStickToBottom(`${replies.length}:${replies[replies.length - 1]?.id ?? ''}`);
2854
+ useEffect(() => {
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]);
2867
+ const send = () => {
2868
+ const body = text.trim();
2869
+ if (!body) return;
2870
+ const replyTo = quote?.id ?? rootId;
2871
+ setText('');
2872
+ setQuote(null);
2873
+ stick.stick();
2874
+ void onSend(body, replyTo, '', rootId).then(() => {
2875
+ stick.stick();
2876
+ void reload();
2877
+ });
2878
+ };
2879
+ const count = replies.filter((m) => !isTraffic(m)).length;
2880
+ const pick = (m) => setQuote(m.id === rootId ? null : m);
2881
+ return h(
2882
+ 'aside',
2883
+ {
2884
+ className: 'dshb-threadpane dshb-fade',
2885
+ 'data-dsh-bots-thread-pane': rootId,
2886
+ onKeyDown: (e) => {
2887
+ if (e.key === 'Escape' && !quote) onClose();
2888
+ },
2889
+ },
2383
2890
  h(
2384
2891
  'div',
2385
- { style: { padding: '10px 24px 16px', borderTop: `1px solid ${C.border1}`, background: C.base } },
2892
+ { className: 'dshb-threadhead' },
2893
+ h('span', { style: { color: C.label, display: 'inline-flex', flex: 'none' } }, Icon.chat(15)),
2386
2894
  h(
2387
2895
  'div',
2388
- { style: { maxWidth: 880, margin: '0 auto' } },
2389
- // Questions of its own conversation; a task's wait in the task.
2390
- h(AskCards, { t, sessionId: bot.sessionId, env, onAnswered: () => void reload() }),
2391
- previewUrl ? h('div', { 'data-dsh-bots-composer-preview': previewUrl, style: { marginBottom: 8, maxHeight: 260, overflow: 'auto' } }, h(LinkCard, { t, url: previewUrl })) : null,
2896
+ { style: { display: 'flex', flexDirection: 'column', minWidth: 0, flex: 1 } },
2897
+ h('span', { style: { fontWeight: 700, fontSize: SMALL } }, t('threadPaneTitle')),
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) : ''),
2899
+ ),
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)),
2901
+ ),
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,
2903
+ h(
2904
+ 'div',
2905
+ { className: 'dshb-scroll', 'data-dsh-bots-thread-body': rootId, ref: stick.box, onScroll: stick.onScroll, style: { flex: 1, padding: '4px 16px 12px' } },
2392
2906
  h(
2393
2907
  'div',
2394
- { style: { display: 'flex', alignItems: 'flex-end', gap: 8, padding: 6, borderRadius: 14, border: `1px solid ${C.border}`, background: C.layer1 } },
2395
- h('textarea', {
2396
- 'data-dsh-bots-composer': true,
2397
- value: text,
2398
- rows: Math.min(8, Math.max(1, text.split('\n').length)),
2399
- placeholder: t('composer', { handle: bot.handle }),
2400
- onChange: (e) => setText(e.target.value),
2401
- onKeyDown: (e) => {
2402
- if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
2403
- e.preventDefault();
2404
- send();
2405
- }
2406
- },
2407
- style: { flex: 1, 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' },
2408
- }),
2409
- h(Btn, { kind: 'primary', icon: Icon.send(15), title: t('send'), disabled: !text.trim() || sending, onClick: send, style: { borderRadius: 10, width: 34, height: 34 } }),
2908
+ { ref: stick.content },
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
2918
+ ? h(MessageList, {
2919
+ t,
2920
+ items: replies,
2921
+ botId: bot.id,
2922
+ onReply: pick,
2923
+ onRetry,
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
+ },
2933
+ empty: null,
2934
+ })
2935
+ : null,
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,
2410
2937
  ),
2938
+ ),
2939
+ h(
2940
+ 'div',
2941
+ { style: { padding: '8px 12px 12px', borderTop: `1px solid ${C.border1}` } },
2411
2942
  h(
2412
2943
  'div',
2413
- { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 7, fontSize: TINY, color: C.faint } },
2414
- h('span', null, t('composerHint')),
2415
- h('span', { style: { flex: 1 } }),
2416
- bot.topic ? h('span', { 'data-dsh-bots-topic': true, title: t('topicNow', { when: fmtAgo(t, bot.topic.startedAt), n: bot.topic.tasks, ctx: fmtNum(bot.topic.context) }) }, t('topicShort', { n: bot.topic.tasks, ctx: fmtNum(bot.topic.context) })) : null,
2417
- h('button', { type: 'button', className: 'dshb-link', title: t('newTopicHint'), disabled: running || topicBusy || !bot.sessionId, onClick: startTopic, 'data-dsh-bots-new-topic': 'chat', style: { fontSize: TINY, display: 'inline-flex', alignItems: 'center', gap: 4, opacity: running || !bot.sessionId ? 0.5 : 1 } }, Icon.plus(11), t('newTopic')),
2418
- env.canOpen() ? h('span', { style: { color: C.faint } }, '·') : null,
2419
- env.canOpen() ? h('button', { type: 'button', className: 'dshb-link', style: { fontSize: TINY, display: 'inline-flex', alignItems: 'center', gap: 4 }, onClick: () => env.openBot(bot) }, Icon.open(11), t('fullTranscript')) : null,
2420
- ),
2944
+ { className: 'dshb-composer' },
2945
+ quote ? h(QuoteBar, { t, m: quote, onCancel: () => setQuote(null), attr: 'data-dsh-bots-thread-quote' }) : null,
2946
+ h(
2947
+ 'div',
2948
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 8 } },
2949
+ h('textarea', {
2950
+ 'data-dsh-bots-thread-composer': rootId,
2951
+ value: text,
2952
+ rows: Math.min(6, Math.max(1, text.split('\n').length)),
2953
+ placeholder: t('threadComposer'),
2954
+ onChange: (e) => setText(e.target.value),
2955
+ onKeyDown: (e) => {
2956
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
2957
+ e.preventDefault();
2958
+ send();
2959
+ } else if (e.key === 'Escape' && quote) {
2960
+ e.stopPropagation?.();
2961
+ setQuote(null);
2962
+ }
2963
+ },
2964
+ style: { flex: 1, minWidth: 0, minHeight: 30, maxHeight: 160, resize: 'none', border: 'none', outline: 'none', background: 'transparent', color: C.primary, font: 'inherit', fontSize: FONT, lineHeight: 1.5, padding: '5px 8px' },
2965
+ }),
2966
+ h(Btn, { kind: 'primary', icon: Icon.send(14), title: t('send'), disabled: !text.trim(), onClick: send, 'data-dsh-bots-thread-send': rootId, style: { borderRadius: 9, width: 32, height: 32 } }),
2967
+ ),
2421
2968
  ),
2422
2969
  ),
2423
2970
  );
@@ -3092,6 +3639,20 @@ button.dshb-tline:hover{background:${C.hover}}
3092
3639
  }
3093
3640
 
3094
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
+ }
3095
3656
  function RouterNoticeBanner({ t, onOpenDispatcher, onDismiss }) {
3096
3657
  return h(
3097
3658
  'div',
@@ -3467,6 +4028,8 @@ button.dshb-tline:hover{background:${C.hover}}
3467
4028
  const isPrimary = bot.role === 'primary' || bot.id === store.state?.primaryId;
3468
4029
  const routing = isPrimary && routerActiveOf();
3469
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) : []);
3470
4033
  const routerAllow = new Set(draft.routerAllow);
3471
4034
  const routerBlocked = (names) => names.filter((x) => routerDeny.has(x) && !routerAllow.has(x));
3472
4035
  const inEffect = routing ? new Set([...draft.deny, ...routerBlocked([...routerDeny])]) : denied;
@@ -3557,9 +4120,10 @@ button.dshb-tline:hover{background:${C.hover}}
3557
4120
  'div',
3558
4121
  { 'data-dsh-bots-abilities': true, style: { display: 'flex', flexDirection: 'column', border: `1px solid ${C.border1}`, borderRadius: 12, overflow: 'hidden', background: C.layer1 } },
3559
4122
  abilities.map((ab, i) => {
3560
- 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);
3561
4125
  const warn = ab.risky && on;
3562
- const gated = ab.available.filter((x) => routerDeny.has(x));
4126
+ const gated = teamOff ? [] : ab.available.filter((x) => routerDeny.has(x));
3563
4127
  const blocked = routerBlocked(gated);
3564
4128
  const whole = gated.length > 0 && gated.length === ab.available.length;
3565
4129
  return h(
@@ -3574,6 +4138,7 @@ button.dshb-tline:hover{background:${C.hover}}
3574
4138
  { style: { display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' } },
3575
4139
  h('span', { style: { fontWeight: 600, color: on ? C.primary : C.muted } }, pick(ab.name, lang)),
3576
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,
3577
4142
  gated.length
3578
4143
  ? blocked.length
3579
4144
  ? h(Badge, { color: C.muted, title: blocked.join(', '), 'data-dsh-bots-router-off': ab.id }, t(whole ? 'routerOff' : 'routerPartOff'))
@@ -3586,7 +4151,7 @@ button.dshb-tline:hover{background:${C.hover}}
3586
4151
  h('span', { style: { fontSize: TINY, color: C.muted } }, pick(ab.description, lang)),
3587
4152
  ),
3588
4153
  h('span', { className: 'dshb-mono', title: ab.available.join(', '), style: { fontSize: 11, color: C.faint, flex: 'none' } }, t('nTools', { n: ab.available.length })),
3589
- 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 }),
3590
4155
  );
3591
4156
  }),
3592
4157
  ),
@@ -5303,7 +5868,7 @@ button.dshb-tline:hover{background:${C.hover}}
5303
5868
  else if (tab === 'skills') body = h(SkillsTab, { key: bot.id, t, bot, toast, catalog, setTab, env });
5304
5869
  else if (tab === 'schedules') body = h(SchedulesTab, { key: bot.id, t, bot, toast, catalog });
5305
5870
  else if (tab === 'apps') body = h(AppsTab, { key: bot.id, t, bot, toast, catalog });
5306
- 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 });
5307
5872
  else body = h(ChatTab, { key: bot.id, t, bot, env, toast });
5308
5873
  return h(
5309
5874
  'div',
@@ -5945,13 +6510,16 @@ button.dshb-tline:hover{background:${C.hover}}
5945
6510
  }
5946
6511
  const memModelText = (t, m) => (m ? `${m.provider} · ${m.model}` : t('botsOwnModel'));
5947
6512
 
5948
- function MemoryTab({ t, bot, toast, onSettings }) {
6513
+ function MemoryTab({ t, bot, env, toast, onSettings }) {
5949
6514
  const { data, reload } = useJson(`memory?bot=${encodeURIComponent(bot.id)}`, 15_000);
5950
6515
  const [busy, setBusy] = useState(false);
5951
6516
  const name = bot.name || `@${bot.handle}`;
5952
6517
  const topic = data?.topic;
5953
6518
  const startTopic = () => {
5954
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;
5955
6523
  postJson('topic/new', { id: bot.id })
5956
6524
  .then((r) => {
5957
6525
  if (r?.ok) {
@@ -5960,7 +6528,10 @@ button.dshb-tline:hover{background:${C.hover}}
5960
6528
  void refreshState();
5961
6529
  } else toast(r?.reason || t('actionFailed'), 'error');
5962
6530
  })
5963
- .finally(() => setBusy(false));
6531
+ .finally(() => {
6532
+ setBusy(false);
6533
+ env?.keepPanel?.(bot.id);
6534
+ });
5964
6535
  };
5965
6536
  return h(
5966
6537
  'div',
@@ -6927,6 +7498,7 @@ button.dshb-tline:hover{background:${C.hover}}
6927
7498
  h(
6928
7499
  'div',
6929
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,
6930
7502
  !noticeGone && routerNotice.pending(s.state)
6931
7503
  ? h(RouterNoticeBanner, {
6932
7504
  t,
@@ -7323,6 +7895,25 @@ button.dshb-tline:hover{background:${C.hover}}
7323
7895
  act_tool: 'Using {detail}',
7324
7896
  composer: 'Message @{handle}',
7325
7897
  composerHint: 'Enter to send · Shift+Enter for a new line',
7898
+ replyAction: 'Reply',
7899
+ replyingTo: 'Replying to {name}',
7900
+ cancelReply: 'Cancel the reply',
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.',
7913
+ msgPending: 'Queued',
7914
+ msgPendingHint: 'Delivered; the bot takes it as soon as it finishes its current step.',
7915
+ msgFailed: 'Not sent',
7916
+ resend: 'Send again',
7326
7917
  fullTranscript: 'Full transcript in its conversation',
7327
7918
  send: 'Send',
7328
7919
  sendFailed: 'Could not send the message.',
@@ -7912,6 +8503,8 @@ button.dshb-tline:hover{background:${C.hover}}
7912
8503
  routerWaiting: 'Router mode starts once the team has another bot; until then {name} does the work itself.',
7913
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.',
7914
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.',
7915
8508
  routerPartOff: 'Partly off in Router mode',
7916
8509
  routerAllowed: 'On in Router mode',
7917
8510
  routerAllowBack: 'Turn back on',
@@ -8200,6 +8793,25 @@ button.dshb-tline:hover{background:${C.hover}}
8200
8793
  act_tool: '使用 {detail}',
8201
8794
  composer: '给 @{handle} 发消息',
8202
8795
  composerHint: 'Enter 发送 · Shift+Enter 换行',
8796
+ replyAction: '回复',
8797
+ replyingTo: '回复 {name}',
8798
+ cancelReply: '取消回复',
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 后生效。',
8811
+ msgPending: '排队中',
8812
+ msgPendingHint: '已送达,bot 做完手头这一步就会看到。',
8813
+ msgFailed: '发送失败',
8814
+ resend: '重发',
8203
8815
  fullTranscript: '完整记录在它的会话里',
8204
8816
  send: '发送',
8205
8817
  sendFailed: '消息没有发出去。',
@@ -8673,7 +9285,7 @@ button.dshb-tline:hover{background:${C.hover}}
8673
9285
  channelPrivate: '只有配对过的人能找到团队,其他人一律忽略(每天最多回一句“这是私人 Bot”)。在群里,只有 @ 它或回复它时才会回答。',
8674
9286
  viaChannel: '{app} · {who}',
8675
9287
  sentToChannel: '也已发到 {app}',
8676
- threadPart: '话题',
9288
+ threadPart: '讨论串',
8677
9289
  threadTopic: '话题',
8678
9290
  notSent: '未发出',
8679
9291
  notSentChats: '没有发到任何聊天:这一轮涉及多个聊天({chats})。',
@@ -8778,6 +9390,8 @@ button.dshb-tline:hover{background:${C.hover}}
8778
9390
  routerWaiting: '团队里再有一个 Bot 后才开始只调度,在此之前 {name} 自己动手。',
8779
9391
  abilitiesRouterHint: '{name} 能用 Harness 内置工具做哪些事。只调度时它不执行命令、不写文件、不用子代理、不作图也不做 Office 文档;确实需要时可以在下面逐项打开。',
8780
9392
  routerOff: '只调度时关闭',
9393
+ teamOff: '调度员不用',
9394
+ teamOffHint: '调度员把要并行的活交给队友,面板里能看到他们各自的任务;其他 bot 照常可以用子代理。',
8781
9395
  routerPartOff: '只调度时部分关闭',
8782
9396
  routerAllowed: '只调度时也可用',
8783
9397
  routerAllowBack: '重新打开',
@@ -8801,7 +9415,7 @@ button.dshb-tline:hover{background:${C.hover}}
8801
9415
  setStallHint: '进行中的任务这么久没动静,先请它汇报;之后仍没动静就标为卡住。',
8802
9416
  setArchive: '任务完成多少小时后归档会话',
8803
9417
  usageAllTasks: '显示全部 {n} 个任务',
8804
- setArchiveHint: '在此之前,它所在话题或回复串里的新消息会让这个任务继续。',
9418
+ setArchiveHint: '在此之前,它所在讨论串里的新消息会让这个任务继续。',
8805
9419
  // 用量、记忆、话题、设置、模型来源
8806
9420
  settings: '设置',
8807
9421
  usage: '用量',
@@ -9018,6 +9632,79 @@ button.dshb-tline:hover{background:${C.hover}}
9018
9632
  return false;
9019
9633
  }
9020
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');
9021
9708
  const openSession = (id) => {
9022
9709
  try {
9023
9710
  const ws = service('uiWorkspace');
@@ -9061,6 +9748,14 @@ button.dshb-tline:hover{background:${C.hover}}
9061
9748
  return openPanel();
9062
9749
  },
9063
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
+ },
9064
9759
  sessionTitle: (id) => {
9065
9760
  try {
9066
9761
  const title = service('sessions')?.list?.getSnapshot?.()?.byId?.[id]?.displayTitle;