@kadaliao/dsh-bots 0.8.0 → 0.9.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
@@ -789,6 +789,33 @@ button.dshb-tline:hover{background:${C.hover}}
789
789
  .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
790
  .dshb-seg button:hover{color:${C.primary}}
791
791
  .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}}
792
+ .dshb-chatwrap{display:flex;flex:1;min-height:0;min-width:0;position:relative;container-type:inline-size}
793
+ .dshb-chatmain{display:flex;flex-direction:column;flex:1;min-width:0;min-height:0}
794
+ .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}
795
+ .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}}
796
+ .dshb-msg{position:relative;min-width:0}
797
+ .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}
798
+ .dshb-msg:hover .dshb-msg-act,.dshb-msg:focus-within .dshb-msg-act,.dshb-msg-act:focus-visible{opacity:1}
799
+ .dshb-msg-act:hover{color:${C.primary};background:${C.hover}}
800
+ .dshb-msg-actbox{position:absolute;top:0;right:0;z-index:1}
801
+ @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}}
814
+ .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
+ .dshb-threadhead{display:flex;align-items:center;gap:10px;padding:12px 12px 10px 16px;border-bottom:1px solid ${C.border1};min-width:0}
816
+ @container (max-width: 860px){.dshb-threadpane{position:absolute;inset:0;width:auto;z-index:6;border-left:none}}
817
+ @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)}}}
792
819
  @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
820
  @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
821
  @keyframes dshb-in{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}}
@@ -1319,14 +1346,19 @@ button.dshb-tline:hover{background:${C.hover}}
1319
1346
  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
1347
  }
1321
1348
 
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 }) {
1349
+ /**
1350
+ * 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}`).
1353
+ */
1354
+ function MessageList({ t, items, botId, empty, fold = null, onReply, onRetry, movedIn }) {
1324
1355
  const count = items.length;
1325
1356
  if (count === 0) return empty;
1326
1357
  const names = threadNamesOf(items);
1327
1358
  const rows = [];
1328
1359
  let lastDay = '';
1329
- items.forEach((m, i) => {
1360
+ const shown = fold ? fold.index.main : items;
1361
+ shown.forEach((m, i) => {
1330
1362
  const at = toMs(m.at);
1331
1363
  let day = '';
1332
1364
  try {
@@ -1359,10 +1391,16 @@ button.dshb-tline:hover{background:${C.hover}}
1359
1391
  else rows.push({ traffic: true, key: `g${m.id ?? i}`, items: [m] });
1360
1392
  return;
1361
1393
  }
1362
- const prev = items[i - 1];
1394
+ 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);
1363
1397
  // 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 }));
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
+ }
1366
1404
  });
1367
1405
  const level = botMessagesLevel();
1368
1406
  return h(
@@ -1371,6 +1409,115 @@ 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
+ /** 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) {
1419
+ const r = fold?.index?.roots.get(rootId);
1420
+ if (!r) return false;
1421
+ if (r.root?.movedTo) return true;
1422
+ return r.replies.length > 0 || topicTasks(fold, rootId).length > 0;
1423
+ }
1424
+
1425
+ /**
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.
1428
+ */
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;
1436
+ const mine = m.from === 'user';
1437
+ return h(
1438
+ 'div',
1439
+ { style: { display: 'flex', justifyContent: mine ? 'flex-end' : 'flex-start', paddingLeft: mine ? 0 : 40, margin: '3px 0 6px' } },
1440
+ 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
+ )
1499
+ : null,
1500
+ ),
1501
+ );
1502
+ }
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';
1508
+ 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
+ ),
1518
+ );
1519
+ }
1520
+
1374
1521
  /** A message between two bots (a delegation, a report, a DM), or a scheduled prompt: secondary traffic. */
1375
1522
  const isTraffic = (m) => m?.kind === 'system' || ((m?.kind === 'dm' || m?.kind === 'report') && m.from !== 'user' && m.to !== 'user');
1376
1523
  /** How much of what bots say to each other a chat shows (a team setting): 'line' | 'short' | 'full'. */
@@ -1496,7 +1643,41 @@ button.dshb-tline:hover{background:${C.hover}}
1496
1643
  );
1497
1644
  }
1498
1645
 
1499
- function MessageRow({ t, m, botId, grouped, names }) {
1646
+ /** "Reply" on a message, shown while the pointer is on it (always, faintly, without a pointer). */
1647
+ const ReplyAction = ({ t, m, onReply }) =>
1648
+ onReply && m?.id != null && !m.local
1649
+ ? h(
1650
+ 'button',
1651
+ {
1652
+ type: 'button',
1653
+ className: 'dshb-msg-act',
1654
+ 'data-dsh-bots-reply-to': m.id,
1655
+ title: t('replyAction'),
1656
+ onClick: (e) => {
1657
+ e?.stopPropagation?.();
1658
+ onReply(m);
1659
+ },
1660
+ },
1661
+ Icon.back(11),
1662
+ t('replyAction'),
1663
+ )
1664
+ : null;
1665
+ /** Under one of your messages: still waiting for the bot to take it, or not sent (with a way to send it again). */
1666
+ function SendState({ t, m, onRetry }) {
1667
+ if (m.failed) {
1668
+ return h(
1669
+ 'span',
1670
+ { 'data-dsh-bots-send-failed': m.id, style: { display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: TINY, color: C.error } },
1671
+ Icon.alert(11),
1672
+ t('msgFailed'),
1673
+ 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,
1674
+ );
1675
+ }
1676
+ if (m.pending) return h('span', { 'data-dsh-bots-pending': m.id, title: t('msgPendingHint'), style: { fontSize: TINY, color: C.faint } }, t('msgPending'));
1677
+ return null;
1678
+ }
1679
+
1680
+ function MessageRow({ t, m, botId, grouped, names, onReply, onRetry, moved = false }) {
1500
1681
  if (m.kind === 'topic') {
1501
1682
  const at = toMs(m.at);
1502
1683
  return h(
@@ -1521,20 +1702,28 @@ button.dshb-tline:hover{background:${C.hover}}
1521
1702
  const notice = messageNotice(m);
1522
1703
  if (between || m.kind === 'system') return h(BotTraffic, { t, items: [m], level: botMessagesLevel() });
1523
1704
  if (mine) {
1705
+ const state = m.pending || m.failed ? h(SendState, { t, m, onRetry }) : null;
1524
1706
  return h(
1525
1707
  '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
1708
+ { '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 } },
1709
+ grouped && !moved
1528
1710
  ? null
1529
1711
  : h(
1530
1712
  'span',
1531
- { style: { fontSize: TINY, color: C.faint, display: 'inline-flex', alignItems: 'center', gap: 6 } },
1713
+ { style: { fontSize: TINY, color: C.faint, display: 'inline-flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' } },
1714
+ moved ? h(Badge, { color: C.muted, 'data-dsh-bots-moved-in': m.id }, Icon.layers(10), t('movedIn')) : null,
1532
1715
  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
1716
  m.to !== botId && to.kind === 'bot' ? `${t('toName', { name: to.name })} · ${time}` : time,
1534
1717
  // A message from a chat that went straight to the task it follows up on.
1535
1718
  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
1719
  ),
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 })),
1720
+ h(
1721
+ 'div',
1722
+ { style: { display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 6, width: '100%', minWidth: 0 } },
1723
+ 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 })),
1725
+ ),
1726
+ state,
1538
1727
  h('div', { style: { width: 'min(480px, 78%)', display: 'flex', justifyContent: 'flex-end' } }, h(LinkCards, { t, text: m.text, align: 'flex-end' })),
1539
1728
  );
1540
1729
  }
@@ -1542,19 +1731,23 @@ button.dshb-tline:hover{background:${C.hover}}
1542
1731
  const place = m.via ? (isChatThread(m.thread) ? threadName(t, m.thread, names) : channelName(m.via, t)) : '';
1543
1732
  // With several chats in the turn, plain text reached none of them (bot_reply says where each answer goes).
1544
1733
  const choices = m.notSent === true && Array.isArray(m.choices) ? m.choices.filter(isChatThread) : [];
1734
+ // A teammate answering you itself, in this chat (the bot that did a task): its own face and name, the task.
1735
+ const worker = m.kind === 'reply' && m.from !== botId && from.kind === 'bot' && Boolean(ticketId);
1545
1736
  // A bot speaking to you reads like the main conversation: no box, full-strength text.
1546
1737
  return h(
1547
1738
  'div',
1548
- { 'data-dsh-bots-msg': m.kind || 'reply', className: 'dshb-fade', style: { display: 'flex', gap: 10, alignItems: 'flex-start', marginTop: grouped ? 4 : 12 } },
1739
+ { '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
1740
  h('div', { style: { width: 30, flex: 'none' } }, grouped ? null : h(PartyAvatar, { p: from, size: 30 })),
1550
1741
  h(
1551
1742
  'div',
1552
1743
  { style: { display: 'flex', flexDirection: 'column', gap: 4, minWidth: 0, flex: 1, maxWidth: 760 } },
1744
+ onReply ? h('div', { className: 'dshb-msg-actbox' }, h(ReplyAction, { t, m, onReply })) : null,
1553
1745
  grouped
1554
1746
  ? null
1555
1747
  : h(
1556
1748
  'div',
1557
- { style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: TINY } },
1749
+ { style: { display: 'flex', alignItems: 'baseline', gap: 6, fontSize: TINY, flexWrap: 'wrap' } },
1750
+ moved ? h(Badge, { color: C.muted, 'data-dsh-bots-moved-in': m.id }, Icon.layers(10), t('movedIn')) : null,
1558
1751
  h('span', { style: { fontWeight: 700, fontSize: SMALL, color: C.primary } }, from.name),
1559
1752
  from.kind === 'bot' ? h('span', { style: { color: C.faint } }, `@${from.bot.handle}`) : null,
1560
1753
  m.to !== 'user' && to.kind === 'bot' && m.to !== botId ? h('span', { style: { color: C.faint } }, `→ ${to.name}`) : null,
@@ -1574,6 +1767,7 @@ button.dshb-tline:hover{background:${C.hover}}
1574
1767
  )
1575
1768
  : null,
1576
1769
  h(LinkCards, { t, text: m.text }),
1770
+ worker && !grouped ? h('div', { 'data-dsh-bots-worker-task': ticketId }, h(TaskCard, { t, id: ticketId, botId: m.from })) : null,
1577
1771
  ),
1578
1772
  );
1579
1773
  }
@@ -2104,32 +2298,137 @@ button.dshb-tline:hover{background:${C.hover}}
2104
2298
  return v;
2105
2299
  }
2106
2300
 
2107
- function useMessages(botId, active = true) {
2108
- const [items, setItems] = useState(null);
2301
+ /**
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.
2304
+ */
2305
+ function useMessages(botId, active = true, topic = '') {
2306
+ const [data, setData] = useState(null);
2109
2307
  const [failed, setFailed] = useState(false);
2110
2308
  const alive = useRef(true);
2111
2309
  useEffect(() => {
2112
2310
  alive.current = true;
2113
- setItems(null);
2311
+ setData(null);
2114
2312
  return () => {
2115
2313
  alive.current = false;
2116
2314
  };
2117
- }, [botId]);
2315
+ }, [botId, topic]);
2118
2316
  const load = () =>
2119
2317
  Promise.resolve()
2120
- .then(() => getJson(`messages?limit=200${botId ? `&bot=${encodeURIComponent(botId)}` : ''}`))
2318
+ .then(() => getJson(`messages?limit=${topic ? 500 : 200}${botId ? `&bot=${encodeURIComponent(botId)}` : ''}${topic ? `&topic=${encodeURIComponent(topic)}` : ''}`))
2121
2319
  .then((r) => {
2122
2320
  if (!alive.current) return;
2123
2321
  if (r && Array.isArray(r.items)) {
2124
2322
  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));
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 }));
2126
2327
  } else setFailed(true);
2127
2328
  })
2128
2329
  .catch(() => {
2129
2330
  if (alive.current) setFailed(true);
2130
2331
  });
2131
- usePoll(() => (active ? load() : undefined), CHAT_POLL_MS, [botId, active]);
2132
- return { items, failed, reload: load };
2332
+ usePoll(() => (active ? load() : undefined), CHAT_POLL_MS, [botId, active, topic]);
2333
+ return { items: data ? data.items : null, topics: data ? data.topics : {}, failed, reload: load };
2334
+ }
2335
+
2336
+ // --- panel topics (PLAN-0.9): every top-level message is a topic's root ---------------------
2337
+
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. */
2343
+ /** Markdown as a line of plain text, for a preview: no emphasis marks, headings, list markers or link targets. */
2344
+ const plainPreview = (text) =>
2345
+ str(text)
2346
+ .replace(/```[\s\S]*?```/g, ' ')
2347
+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
2348
+ .replace(/^\s{0,3}(?:#{1,6}\s+|>\s?|[-*+]\s+|\d+[.)]\s+)/gm, '')
2349
+ .replace(/(\*\*|__|~~|`)/g, '')
2350
+ .replace(/(^|[\s(])[*_](\S[^*_]*?)[*_](?=[\s).,!?:;,。!?:;]|$)/g, '$1$2')
2351
+ .replace(/\s+/g, ' ')
2352
+ .trim();
2353
+ const excerpt = (text, n = 48) => {
2354
+ const line = plainPreview(str(text).split('\n').find((l) => plainPreview(l) !== '') ?? '');
2355
+ return [...line].length > n ? `${[...line].slice(0, n - 1).join('').trimEnd()}…` : line;
2356
+ };
2357
+ /**
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.
2361
+ */
2362
+ function topicIndex(items) {
2363
+ const byId = new Map();
2364
+ for (const m of items) if (m && m.id != null) byId.set(m.id, m);
2365
+ const roots = new Map();
2366
+ const rootOf = (id) => {
2367
+ let r = roots.get(id);
2368
+ if (!r) {
2369
+ r = { root: byId.get(id), replies: [], lastAt: toMs(byId.get(id)?.at) || 0, last: null, botAt: 0 };
2370
+ roots.set(id, r);
2371
+ }
2372
+ return r;
2373
+ };
2374
+ const main = [];
2375
+ for (const m of items) {
2376
+ if (!m) continue;
2377
+ const own = str(m.topic);
2378
+ if (own && own === m.id) {
2379
+ rootOf(m.id);
2380
+ main.push(m);
2381
+ }
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);
2395
+ }
2396
+ for (const r of roots.values()) r.replies.sort((a, b) => (toMs(a.at) || 0) - (toMs(b.at) || 0));
2397
+ return { byId, roots, main };
2398
+ }
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
+ }
2407
+ }
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;
2420
+ }
2421
+ }
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
+ }
2133
2432
  }
2134
2433
 
2135
2434
  /** A first chat: the bot's bio and three opening messages to start from. */
@@ -2321,15 +2620,137 @@ button.dshb-tline:hover{background:${C.hover}}
2321
2620
  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
2621
  };
2323
2622
 
2623
+ /** A chat's messages with the ones being sent from here (`local`) that the Host has not listed yet. */
2624
+ function mergeLocal(items, local) {
2625
+ if (!Array.isArray(items)) return items;
2626
+ if (!local.length) return items;
2627
+ const ids = new Set(items.map((m) => m?.id));
2628
+ const extra = local.filter((m) => !ids.has(m.id));
2629
+ return extra.length ? [...items, ...extra] : items;
2630
+ }
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
+ /** The line above a composer naming the message a reply answers, with a way to drop it. */
2646
+ function QuoteBar({ t, m, onCancel, attr = 'data-dsh-bots-quote' }) {
2647
+ const who = party(t, m.from);
2648
+ return h(
2649
+ 'div',
2650
+ { [attr]: m.id, className: 'dshb-quote' },
2651
+ h('span', { style: { color: C.label, display: 'inline-flex', flex: 'none' } }, Icon.back(12)),
2652
+ h('span', { style: { fontWeight: 600, flex: 'none' } }, t('replyingTo', { name: who.name })),
2653
+ h('span', { style: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: C.muted } }, excerpt(m.text, 80)),
2654
+ 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)),
2655
+ );
2656
+ }
2657
+
2324
2658
  function ChatTab({ t, bot, env, toast }) {
2325
- const { items, failed, reload } = useMessages(bot.id);
2659
+ const { items: listed, topics, failed, reload } = useMessages(bot.id);
2326
2660
  const [text, setText] = useState('');
2327
- const [sending, setSending] = useState(false);
2661
+ // Messages sent from here: shown at once (queued), then the Host's own copy; a failed one stays to be sent again.
2662
+ 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);
2665
+ 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);
2328
2672
  // The quick poll may know before the state does that it started or stopped.
2329
2673
  const live = liveBot(bot);
2330
2674
  const running = live.status === 'running' || Boolean(live.activity);
2331
- const thread = useStickToBottom(`${items?.length ?? 0}:${items?.[items.length - 1]?.id ?? ''}:${running}`);
2675
+ 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}`);
2332
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);
2711
+ }
2712
+ }
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
+ }
2722
+ };
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);
2735
+ };
2736
+ const hidden = offscreen ? offscreen.split(',').filter((id) => unread.has(id)) : [];
2737
+ const pointAt = (id) => {
2738
+ try {
2739
+ const el = thread.box.current?.querySelector?.(`[data-dsh-bots-topic-bar="${String(id).replace(/["\\]/g, '\\$&')}"]`);
2740
+ el?.scrollIntoView?.({ block: 'center', behavior: 'smooth' });
2741
+ } catch {
2742
+ // Scrolling is a nicety.
2743
+ }
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
+ };
2753
+
2333
2754
  const startTopic = () => {
2334
2755
  setTopicBusy(true);
2335
2756
  postJson('topic/new', { id: bot.id })
@@ -2342,82 +2763,254 @@ button.dshb-tline:hover{background:${C.hover}}
2342
2763
  })
2343
2764
  .finally(() => setTopicBusy(false));
2344
2765
  };
2766
+ /**
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}`.
2769
+ */
2770
+ const sendText = (body, replyTo = '', again = '', topicHint = '') => {
2771
+ const id = again || `local-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
2772
+ 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 } : {}) };
2776
+ setLocal((list) => [...list.filter((m) => m.id !== id), row]);
2777
+ return postJson('send', { to: bot.id, text: body, ...(replyTo ? { replyTo } : {}) }).then((r) => {
2778
+ if (r?.ok) {
2779
+ const msg = r.message && typeof r.message === 'object' && r.message.id != null ? r.message : null;
2780
+ setLocal((list) => list.flatMap((m) => (m.id !== id ? [m] : msg ? [{ ...msg, pending: msg.pending ?? true, chat: msg.chat ?? bot.id }] : [])));
2781
+ void reload();
2782
+ void refreshState();
2783
+ return { ok: true, topic: msg ? topicOfMsg(msg) || topic : topic };
2784
+ }
2785
+ setLocal((list) => list.map((m) => (m.id === id ? { ...m, pending: false, failed: true } : m)));
2786
+ toast(r?.reason || t('sendFailed'), 'error');
2787
+ return { ok: false, topic };
2788
+ });
2789
+ };
2790
+ const retry = (m) => {
2791
+ if (!m?.local) return;
2792
+ void sendText(str(m.text), str(m.replyTo), m.id, m.replyTo ? str(m.topic) : '');
2793
+ };
2345
2794
  const send = () => {
2346
2795
  const body = text.trim();
2347
- if (!body || sending) return;
2348
- setSending(true);
2349
- 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));
2796
+ if (!body) return;
2797
+ const replyTo = quote?.id ?? '';
2798
+ setText('');
2799
+ 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
+ });
2360
2806
  };
2361
2807
  // A pasted link previews above the composer, as it will in the thread.
2362
2808
  const previewUrl = linksIn(useDebounced(text, 400))[0] ?? '';
2809
+ const fold = { index, topics, onOpen: openTopic, unread, flash };
2363
2810
  return h(
2364
2811
  'div',
2365
- { style: { display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 } },
2812
+ { className: 'dshb-chatwrap', 'data-dsh-bots-chat': bot.id, 'data-topic-open': open || undefined },
2366
2813
  h(
2367
2814
  'div',
2368
- { className: 'dshb-scroll', 'data-dsh-bots-thread': bot.id, ref: thread.box, onScroll: thread.onScroll, style: { flex: 1, padding: '6px 24px' } },
2815
+ { className: 'dshb-chatmain' },
2369
2816
  h(
2370
2817
  '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,
2818
+ {
2819
+ className: 'dshb-scroll',
2820
+ 'data-dsh-bots-thread': bot.id,
2821
+ ref: thread.box,
2822
+ onScroll: (e) => {
2823
+ thread.onScroll(e);
2824
+ if (unreadIds.length) measureSoon();
2825
+ },
2826
+ style: { flex: 1, padding: '6px 24px' },
2827
+ },
2828
+ h(
2829
+ 'div',
2830
+ { ref: thread.content },
2831
+ items === null
2832
+ ? h('div', { style: { padding: 24, color: C.faint, fontSize: SMALL, textAlign: 'center' } }, failed ? t('unavailable') : t('loading'))
2833
+ : h(MessageList, {
2834
+ t,
2835
+ items,
2836
+ botId: bot.id,
2837
+ fold,
2838
+ onReply: (m) => setQuote(m),
2839
+ onRetry: retry,
2840
+ empty: h(ChatEmpty, { t, bot, onPick: setText }),
2841
+ }),
2842
+ running ? h('div', { style: { maxWidth: 880, margin: '0 auto' } }, h(WorkingRow, { t, bot, a: live.activity, attr: bot.id })) : null,
2843
+ ),
2844
+ ),
2845
+ h(
2846
+ 'div',
2847
+ { 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
+ h(
2862
+ 'div',
2863
+ { style: { maxWidth: 880, margin: '0 auto' } },
2864
+ // Questions of its own conversation; a task's wait in the task.
2865
+ h(AskCards, { t, sessionId: bot.sessionId, env, onAnswered: () => void reload() }),
2866
+ previewUrl ? h('div', { 'data-dsh-bots-composer-preview': previewUrl, style: { marginBottom: 8, maxHeight: 260, overflow: 'auto' } }, h(LinkCard, { t, url: previewUrl })) : null,
2867
+ h(
2868
+ 'div',
2869
+ { className: 'dshb-composer' },
2870
+ quote ? h(QuoteBar, { t, m: quote, onCancel: () => setQuote(null) }) : null,
2871
+ h(
2872
+ 'div',
2873
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 8 } },
2874
+ h('textarea', {
2875
+ 'data-dsh-bots-composer': true,
2876
+ value: text,
2877
+ rows: Math.min(8, Math.max(1, text.split('\n').length)),
2878
+ placeholder: quote ? t('topicComposer') : t('composer', { handle: bot.handle }),
2879
+ onChange: (e) => setText(e.target.value),
2880
+ onKeyDown: (e) => {
2881
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
2882
+ e.preventDefault();
2883
+ send();
2884
+ } else if (e.key === 'Escape' && quote) setQuote(null);
2885
+ },
2886
+ 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
+ }),
2888
+ h(Btn, { kind: 'primary', icon: Icon.send(15), title: t('send'), disabled: !text.trim(), onClick: send, style: { borderRadius: 10, width: 34, height: 34 } }),
2889
+ ),
2890
+ ),
2891
+ h(
2892
+ 'div',
2893
+ { style: { display: 'flex', alignItems: 'center', gap: 6, marginTop: 7, fontSize: TINY, color: C.faint, flexWrap: 'wrap' } },
2894
+ h('span', null, t('composerHint')),
2895
+ h('span', { style: { flex: 1 } }),
2896
+ 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,
2897
+ 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')),
2898
+ env.canOpen() ? h('span', { style: { color: C.faint } }, '·') : null,
2899
+ 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,
2900
+ ),
2901
+ ),
2381
2902
  ),
2382
2903
  ),
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,
2906
+ );
2907
+ }
2908
+
2909
+ /**
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.
2913
+ */
2914
+ function ThreadPane({ t, bot, rootId, base, baseTopics, local, onClose, onSend, onRetry, onSeen }) {
2915
+ const { items, topics } = useMessages(bot.id, true, rootId);
2916
+ const [text, setText] = useState('');
2917
+ 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) ?? [];
2920
+ const root = list.find((m) => m?.id === rootId) ?? base.byId.get(rootId) ?? null;
2921
+ const seenIds = new Set();
2922
+ const replies = list
2923
+ .filter((m) => inTopic(m, rootId) && !seenIds.has(m.id) && seenIds.add(m.id))
2924
+ .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);
2928
+ const stick = useStickToBottom(`${replies.length}:${replies[replies.length - 1]?.id ?? ''}`);
2929
+ // Open means read: what arrives while it is open is read too.
2930
+ useEffect(() => {
2931
+ onSeen?.(rootId, lastAt);
2932
+ }, [rootId, lastAt]);
2933
+ const send = () => {
2934
+ const body = text.trim();
2935
+ if (!body) return;
2936
+ const replyTo = quote?.id ?? rootId;
2937
+ setText('');
2938
+ setQuote(null);
2939
+ stick.stick();
2940
+ void onSend(body, replyTo, '', rootId).then(() => stick.stick());
2941
+ };
2942
+ const count = replies.filter((m) => !isTraffic(m)).length;
2943
+ return h(
2944
+ 'aside',
2945
+ {
2946
+ className: 'dshb-threadpane dshb-fade',
2947
+ 'data-dsh-bots-thread-pane': rootId,
2948
+ onKeyDown: (e) => {
2949
+ if (e.key === 'Escape' && !quote) onClose();
2950
+ },
2951
+ },
2383
2952
  h(
2384
2953
  'div',
2385
- { style: { padding: '10px 24px 16px', borderTop: `1px solid ${C.border1}`, background: C.base } },
2954
+ { className: 'dshb-threadhead' },
2955
+ h('span', { style: { color: C.label, display: 'inline-flex', flex: 'none' } }, Icon.chat(15)),
2386
2956
  h(
2387
2957
  '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,
2958
+ { style: { display: 'flex', flexDirection: 'column', minWidth: 0, flex: 1 } },
2959
+ h('span', { style: { fontWeight: 700, fontSize: SMALL } }, t('topicTitle')),
2960
+ 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
+ ),
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)),
2963
+ ),
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,
2965
+ h(
2966
+ 'div',
2967
+ { className: 'dshb-scroll', 'data-dsh-bots-thread-body': rootId, ref: stick.box, onScroll: stick.onScroll, style: { flex: 1, padding: '4px 16px 12px' } },
2392
2968
  h(
2393
2969
  '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 } }),
2970
+ { ref: stick.content },
2971
+ shown.length
2972
+ ? h(MessageList, {
2973
+ t,
2974
+ items: shown,
2975
+ botId: bot.id,
2976
+ onReply: (m) => setQuote(m.id === rootId ? null : m),
2977
+ onRetry,
2978
+ movedIn: (m) => m.movedTo === rootId && m.id !== rootId,
2979
+ empty: null,
2980
+ })
2981
+ : 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')),
2410
2983
  ),
2984
+ ),
2985
+ h(
2986
+ 'div',
2987
+ { style: { padding: '8px 12px 12px', borderTop: `1px solid ${C.border1}` } },
2411
2988
  h(
2412
2989
  '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
- ),
2990
+ { className: 'dshb-composer' },
2991
+ quote ? h(QuoteBar, { t, m: quote, onCancel: () => setQuote(null), attr: 'data-dsh-bots-thread-quote' }) : null,
2992
+ h(
2993
+ 'div',
2994
+ { style: { display: 'flex', alignItems: 'flex-end', gap: 8 } },
2995
+ h('textarea', {
2996
+ 'data-dsh-bots-thread-composer': rootId,
2997
+ value: text,
2998
+ rows: Math.min(6, Math.max(1, text.split('\n').length)),
2999
+ placeholder: t('topicComposer'),
3000
+ onChange: (e) => setText(e.target.value),
3001
+ onKeyDown: (e) => {
3002
+ if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.nativeEvent?.isComposing) {
3003
+ e.preventDefault();
3004
+ send();
3005
+ } else if (e.key === 'Escape' && quote) {
3006
+ e.stopPropagation?.();
3007
+ setQuote(null);
3008
+ }
3009
+ },
3010
+ 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' },
3011
+ }),
3012
+ 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 } }),
3013
+ ),
2421
3014
  ),
2422
3015
  ),
2423
3016
  );
@@ -7323,6 +7916,27 @@ button.dshb-tline:hover{background:${C.hover}}
7323
7916
  act_tool: 'Using {detail}',
7324
7917
  composer: 'Message @{handle}',
7325
7918
  composerHint: 'Enter to send · Shift+Enter for a new line',
7919
+ replyAction: 'Reply',
7920
+ replyingTo: 'Replying to {name}',
7921
+ 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',
7936
+ msgPending: 'Queued',
7937
+ msgPendingHint: 'Delivered; the bot takes it as soon as it finishes its current step.',
7938
+ msgFailed: 'Not sent',
7939
+ resend: 'Send again',
7326
7940
  fullTranscript: 'Full transcript in its conversation',
7327
7941
  send: 'Send',
7328
7942
  sendFailed: 'Could not send the message.',
@@ -8200,6 +8814,27 @@ button.dshb-tline:hover{background:${C.hover}}
8200
8814
  act_tool: '使用 {detail}',
8201
8815
  composer: '给 @{handle} 发消息',
8202
8816
  composerHint: 'Enter 发送 · Shift+Enter 换行',
8817
+ replyAction: '回复',
8818
+ replyingTo: '回复 {name}',
8819
+ 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} 个话题有新回复',
8834
+ msgPending: '排队中',
8835
+ msgPendingHint: '已送达,bot 做完手头这一步就会看到。',
8836
+ msgFailed: '发送失败',
8837
+ resend: '重发',
8203
8838
  fullTranscript: '完整记录在它的会话里',
8204
8839
  send: '发送',
8205
8840
  sendFailed: '消息没有发出去。',