@kangyishuai/dsh-btw 0.1.1 → 0.3.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/README.md CHANGED
@@ -49,8 +49,10 @@ Restart the DSH desktop app afterwards.
49
49
  /btw --scope recent <q> # hint the answer to focus (session | recent | selection)
50
50
  ```
51
51
 
52
- The overlay (button left of the composer) lists threads with cost badges, lets you follow up or
53
- promote one to a draft, and shows the scope badge.
52
+ The panel opens as a **centered dialog** from the「旁问」button left of the composer
53
+ (it lives in the frame-wide overlay layer, so it is not clipped by the composer).
54
+ It lists threads with cost badges, lets you follow up or promote one to a draft, and shows the
55
+ scope badge at the bottom. Use「+ 新旁问」to reveal the new-question input.
54
56
 
55
57
  ## Configuration
56
58
 
package/README.zh-CN.md CHANGED
@@ -52,7 +52,9 @@ dsh plugin --profile desktop add @kangyishuai/dsh-btw
52
52
  /btw --scope recent <问题> # 提示回答聚焦的范围(session | recent | selection)
53
53
  ```
54
54
 
55
- 浮层(输入框左侧按钮)列出各线程与成本徽章,可追问、可转正,并显示范围徽章。
55
+ 面板点输入框左侧的「旁问」按钮打开,以**居中弹窗**呈现(挂在 frame-wide 的 overlay 层,
56
+ 不会被输入框容器裁剪)。里面列出各线程与成本徽章,可追问、可转正,底部显示范围徽章;
57
+ 新建旁问要点标题栏的「+ 新旁问」。
56
58
 
57
59
  ## 配置
58
60
 
package/lib/client.js CHANGED
@@ -53,6 +53,8 @@ window.__ModuleLoader__.load({
53
53
  sentPending: "命令已提交,答案稍后出现在对话里",
54
54
  expandAnswer: "展开全文",
55
55
  collapseAnswer: "收起",
56
+ newQuestion: "+ 新旁问",
57
+ submitHint: "提交时会以 /btw 命令写入对话",
56
58
  scopeAny: "范围:不限",
57
59
  scopeSession: "范围:整个会话",
58
60
  scopeRecent: "范围:最近几轮",
@@ -92,6 +94,8 @@ window.__ModuleLoader__.load({
92
94
  sentPending: "Command submitted; the answer will appear in the conversation",
93
95
  expandAnswer: "Show all",
94
96
  collapseAnswer: "Collapse",
97
+ newQuestion: "+ New question",
98
+ submitHint: "Submitting writes a /btw command into the conversation",
95
99
  scopeAny: "Scope: any",
96
100
  scopeSession: "Scope: whole session",
97
101
  scopeRecent: "Scope: recent turns",
@@ -115,11 +119,14 @@ window.__ModuleLoader__.load({
115
119
  ".dsh-btw-btn{height:24px;padding:0 8px;border-radius:var(--dsw-radius-sm,6px);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));background:transparent;color:var(--dsw-alias-label-secondary,GrayText);font-size:12px;cursor:pointer;}",
116
120
  ".dsh-btw-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.16));color:var(--dsw-alias-label-primary,CanvasText);}",
117
121
  ".dsh-btw-btn:disabled{opacity:.5;cursor:default;}",
118
- ".dsh-btw-panel{position:absolute;left:0;right:0;bottom:100%;margin-bottom:6px;max-height:46vh;overflow:auto;z-index:30;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,Canvas));color:var(--dsw-alias-label-primary,CanvasText);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));border-radius:10px;padding:10px 12px;font-size:12px;line-height:1.55;box-shadow:0 12px 32px rgba(0,0,0,.28);}",
119
- ".dsh-btw-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;font-weight:600;}",
122
+ ".dsh-btw-panel{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);width:min(720px,94vw);max-height:min(74vh,680px);display:flex;flex-direction:column;min-height:0;z-index:2147482000;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,Canvas));color:var(--dsw-alias-label-primary,CanvasText);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));border-radius:12px;padding:12px 14px;font-size:12px;line-height:1.55;box-shadow:0 18px 48px rgba(0,0,0,.38);}",
123
+ ".dsh-btw-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px;font-weight:600;flex:none;}",
124
+ ".dsh-btw-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain;}",
120
125
  ".dsh-btw-item{padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
121
126
  ".dsh-btw-q{color:var(--dsw-alias-label-secondary,GrayText);}",
122
127
  ".dsh-btw-a{white-space:pre-wrap;word-break:break-word;margin-top:2px;}",
128
+ ".dsh-btw-code{margin:6px 0;padding:8px 10px;border-radius:6px;background:var(--dsw-alias-bg-base,Canvas);border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));font-family:var(--ds-font-family-code,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:11.5px;line-height:1.5;white-space:pre;overflow-x:auto;}",
129
+ ".dsh-btw-link{color:var(--dsw-alias-brand-primary,#4f7cff);text-decoration:underline;word-break:break-all;}",
123
130
  ".dsh-btw-a.is-clamped{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:6;line-clamp:6;overflow:hidden;}",
124
131
  ".dsh-btw-meta{margin-top:2px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:11px;}",
125
132
  ".dsh-btw-dim{color:var(--dsw-alias-label-tertiary,GrayText);padding:6px 0;}",
@@ -175,6 +182,41 @@ window.__ModuleLoader__.load({
175
182
  return () => style.remove();
176
183
  }, "btw: styles");
177
184
 
185
+ /**
186
+ * 按钮(composer 工具行)与浮层(`shell.overlay`)是两个独立组件实例,
187
+ * 共享状态必须提升到 apply 作用域。
188
+ *
189
+ * 为什么浮层改注册到 `shell.overlay`:`conversation.input.overlay` 的 slot 文档写着
190
+ * "fixed overlays must portal to the document body because the docked composer contains them"。
191
+ * 放在 composer 里会被裁剪 —— 实测提示条跑到浮层下方 302px、位置还随对话流滚动漂移。
192
+ * `shell.overlay` 的语义是 "frame-wide floating layer, above every column and outside
193
+ * their scroll containers",换过去从根上解决,不必手写 portal。
194
+ */
195
+ const store = (() => {
196
+ /** @type {{ open: boolean, sessionId: string }} */
197
+ let state = { open: false, sessionId: "" };
198
+ /** @type {Set<() => void>} */
199
+ const listeners = new Set();
200
+ return {
201
+ get: () => state,
202
+ patch(/** @type {Partial<{ open: boolean, sessionId: string }>} */ next) {
203
+ state = { ...state, ...next };
204
+ for (const listener of listeners) listener();
205
+ },
206
+ subscribe(/** @type {() => void} */ listener) {
207
+ listeners.add(listener);
208
+ return () => listeners.delete(listener);
209
+ },
210
+ };
211
+ })();
212
+
213
+ /** 订阅 store 的极简 hook。 */
214
+ const useStore = () => {
215
+ const [, force] = React.useState(0);
216
+ React.useEffect(() => store.subscribe(() => force((/** @type {number} */ n) => n + 1)), []);
217
+ return store.get();
218
+ };
219
+
178
220
  /** 当前界面语言(转正草稿用)。取不到默认 zh。 */
179
221
  const langOf = () => {
180
222
  try {
@@ -309,10 +351,44 @@ window.__ModuleLoader__.load({
309
351
  return "ok";
310
352
  };
311
353
 
354
+ /**
355
+ * composer 工具行里的「旁问」按钮。
356
+ *
357
+ * 它同时负责把当前 sessionId 写进 store —— 浮层注册在 root scope 的
358
+ * `shell.overlay` 上,拿不到 session props,只能由按钮转交。
359
+ */
360
+ function BtwTrigger(/** @type {any} */ props) {
361
+ const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
362
+ const shared = useStore();
363
+ React.useEffect(() => {
364
+ if (shared.sessionId !== sessionId) store.patch({ sessionId });
365
+ }, [sessionId, shared.sessionId]);
366
+ return h(
367
+ "button",
368
+ {
369
+ type: "button",
370
+ className: "dsh-btw-btn",
371
+ "data-btw-toggle": "true",
372
+ title: t("button"),
373
+ onClick: () => store.patch({ open: !store.get().open }),
374
+ },
375
+ t("button"),
376
+ );
377
+ }
378
+
312
379
  /** 浮层:只读列表 + 浮层内发问。 */
313
380
  function BtwPanel(/** @type {any} */ props) {
314
- const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
315
- const [open, setOpen] = React.useState(false);
381
+ void props;
382
+ const shared = useStore();
383
+ const open = shared.open;
384
+ const sessionId = shared.sessionId;
385
+ const setOpen = (/** @type {boolean | ((prev: boolean) => boolean)} */ next) =>
386
+ store.patch({
387
+ open:
388
+ typeof next === "function"
389
+ ? /** @type {(prev: boolean) => boolean} */ (next)(store.get().open)
390
+ : next,
391
+ });
316
392
  const [threads, setThreads] = React.useState(/** @type {any[] | null} */ (null));
317
393
  const [failed, setFailed] = React.useState(false);
318
394
  const [activeId, setActiveId] = React.useState("");
@@ -324,6 +400,9 @@ window.__ModuleLoader__.load({
324
400
  const [expandedAnswers, setExpandedAnswers] = React.useState(
325
401
  /** @type {Record<string, boolean>} */ ({}),
326
402
  );
403
+ // 新建旁问的输入框默认收起:实测同时出现「线程内追问框 + 底部新建框」时,
404
+ // 用户分不清哪个是哪个(两个输入框视觉几乎一样)。
405
+ const [showNew, setShowNew] = React.useState(false);
327
406
  const aliveRef = React.useRef(true);
328
407
 
329
408
  React.useEffect(
@@ -333,18 +412,23 @@ window.__ModuleLoader__.load({
333
412
  [],
334
413
  );
335
414
 
415
+ /**
416
+ * 拉线程列表。返回数组(成功)或 null(失败)——
417
+ * 调用方需要区分「线程数增加」(新问题)与「某线程轮数增加」(追问)。
418
+ * @returns {Promise<any[] | null>}
419
+ */
336
420
  const load = React.useCallback(
337
421
  () =>
338
422
  callRemote("threads", { sessionId, limit: LIMITS_CLIENT_THREADS }).then((value) => {
339
- if (!aliveRef.current) return 0;
423
+ if (!aliveRef.current) return null;
340
424
  if (Array.isArray(/** @type {any} */ (value))) {
341
425
  setThreads(value);
342
426
  setFailed(false);
343
- return value.length;
427
+ return /** @type {any[]} */ (value);
344
428
  }
345
429
  setThreads([]);
346
430
  setFailed(true);
347
- return 0;
431
+ return null;
348
432
  }),
349
433
  [sessionId],
350
434
  );
@@ -391,14 +475,30 @@ window.__ModuleLoader__.load({
391
475
  if (text === "" || busy) return;
392
476
  setBusy(true);
393
477
  setNotice(t("sending"));
394
- const before = Array.isArray(threads) ? threads.length : 0;
478
+ const beforeThreads = Array.isArray(threads) ? threads : [];
479
+ const beforeCount = beforeThreads.length;
480
+ const beforeTurns = Number(
481
+ beforeThreads.find((/** @type {any} */ t) => t?.threadId === threadId)?.turns ?? 0,
482
+ );
395
483
  const flags = [
396
484
  threadId === "" ? "" : `--thread ${threadId}`,
397
485
  scope === "" ? "" : `--scope ${scope}`,
398
486
  ]
399
487
  .filter(Boolean)
400
488
  .join(" ");
401
- const line = flags === "" ? `/btw ${text}` : `/btw ${flags} ${text}`;
489
+ let line = flags === "" ? `/btw ${text}` : `/btw ${flags} ${text}`;
490
+ if (threadId !== "") {
491
+ // 追问:先把参数交给 host 暂存,再提交**裸 `/btw`** ——
492
+ // 否则 `--thread t_xxx <问题>` 会整段出现在用户输入框里(实测被抱怨
493
+ // 「为什么给我一堆乱码」)。host 侧处理裸命令时先查这个队列。
494
+ const queued = await callRemote("queueFollowUp", {
495
+ sessionId,
496
+ threadId,
497
+ question: text,
498
+ scope,
499
+ }).catch(() => undefined);
500
+ if (queued?.ok === true) line = "/btw";
501
+ }
402
502
  try {
403
503
  const result = await sendText(sessionId, line);
404
504
  if (result !== "ok") {
@@ -413,15 +513,28 @@ window.__ModuleLoader__.load({
413
513
  while (Date.now() < deadline && aliveRef.current) {
414
514
  await new Promise((resolve) => setTimeout(resolve, REFRESH_INTERVAL_MS));
415
515
  if (!aliveRef.current) break;
416
- let count = before;
516
+ /** @type {any[] | null} */
517
+ let next = null;
417
518
  try {
418
- count = await load();
519
+ next = await load();
419
520
  } catch {
420
- count = before; // 单次失败继续轮询,不静默卡死
521
+ next = null; // 单次失败继续轮询,不静默卡死
421
522
  }
422
- if (count > before) {
423
- refreshed = true;
424
- break;
523
+ if (next === null) continue;
524
+ if (threadId === "") {
525
+ // 新问题 → 线程数应增加
526
+ if (next.length > beforeCount) {
527
+ refreshed = true;
528
+ break;
529
+ }
530
+ } else {
531
+ // 追问 → **线程数不变**,要看目标线程的轮数是否增加。
532
+ // (曾经只判线程数,导致追问永远等不到,按钮卡到 120s 超时。)
533
+ const target = next.find((/** @type {any} */ t) => t?.threadId === threadId);
534
+ if (Number(target?.turns ?? 0) > beforeTurns) {
535
+ refreshed = true;
536
+ break;
537
+ }
425
538
  }
426
539
  }
427
540
  setNotice(refreshed ? "" : t("sentPending"));
@@ -473,19 +586,94 @@ window.__ModuleLoader__.load({
473
586
  setNotice(t("promoted"));
474
587
  };
475
588
 
476
- const button = h(
477
- "button",
478
- {
479
- type: "button",
480
- className: "dsh-btw-btn",
481
- "data-btw-toggle": "true",
482
- title: t("button"),
483
- onClick: () => setOpen((/** @type {boolean} */ value) => !value),
484
- },
485
- t("button"),
486
- );
589
+ // 浮层不画按钮:按钮由 BtwTrigger 注册在 composer 工具行里。
590
+ if (!open) return null;
591
+
592
+ /**
593
+ * 把 host 切好的段映射成元素:
594
+ * - `code` → 等宽 `<pre>`(不再把 ``` 显示给用户)
595
+ * - `link` → 可点 `<a>`(之前 URL 是死文本)
596
+ * - `text` → 原样
597
+ * 没有 segments(老数据 / 字段缺失)时回退纯文本。
598
+ * @param {any} thread
599
+ * @param {string} fallback
600
+ * @returns {any}
601
+ */
602
+ /**
603
+ * 回退解析:host 还没重启(或拿到老数据)时,client 自己从原始答案里切段。
604
+ *
605
+ * 为什么两处都做:`answerSegments` 是 host 侧字段,改完必须重启 DSH 才生效;
606
+ * client 改动刷新页面即可。为了让新渲染立刻可用,这里保留一份**行为等价**的
607
+ * 极简实现(切 ``` 围栏 + 认 http(s) URL)。host 版本优先 —— 它被单测覆盖。
608
+ * @param {string} text
609
+ * @returns {any[]}
610
+ */
611
+ const parseSegmentsLocal = (/** @type {string} */ text) => {
612
+ const raw = String(text ?? "");
613
+ /** @type {any[]} */
614
+ const out = [];
615
+ const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu;
616
+ let last = 0;
617
+ for (;;) {
618
+ const m = fenceRe.exec(raw);
619
+ if (m === null) break;
620
+ if (m.index > last) out.push({ kind: "text", text: raw.slice(last, m.index) });
621
+ out.push({ kind: "code", lang: m[1] ?? "", text: (m[2] ?? "").replace(/\n+$/u, "") });
622
+ last = m.index + m[0].length;
623
+ }
624
+ const tail = raw.slice(last);
625
+ const urlRe = /https?:\/\/[^\s<>()\u3000-\u303f\uff00-\uffef]+/gu;
626
+ let cursor = 0;
627
+ for (;;) {
628
+ const u = urlRe.exec(tail);
629
+ if (u === null) break;
630
+ const rawUrl = u[0];
631
+ const trimmed = rawUrl.replace(/[.,;:!?]+$/u, "");
632
+ if (u.index > cursor) out.push({ kind: "text", text: tail.slice(cursor, u.index) });
633
+ if (trimmed !== "") out.push({ kind: "link", text: trimmed, href: trimmed });
634
+ const rest = rawUrl.slice(trimmed.length);
635
+ if (rest !== "") out.push({ kind: "text", text: rest });
636
+ cursor = u.index + rawUrl.length;
637
+ }
638
+ if (cursor < tail.length) out.push({ kind: "text", text: tail.slice(cursor) });
639
+ return out;
640
+ };
487
641
 
488
- if (!open) return h("span", { "data-btw-root": "true" }, button);
642
+ const renderAnswerBody = (/** @type {any} */ thread, /** @type {string} */ _fallback) => {
643
+ const fromHost = Array.isArray(thread?.answerSegments) ? thread.answerSegments : null;
644
+ // host 字段缺失时退回本地解析(老数据 / host 未重启)。
645
+ const fromLocal =
646
+ fromHost === null && typeof thread?.answer === "string"
647
+ ? parseSegmentsLocal(thread.answer)
648
+ : null;
649
+ const segments = fromHost ?? fromLocal;
650
+ return segments.map((/** @type {any} */ seg, /** @type {number} */ i) => {
651
+ if (seg?.kind === "code") {
652
+ return h(
653
+ "pre",
654
+ { className: "dsh-btw-code", key: `c${i}`, "data-btw-code": "true" },
655
+ String(seg.text ?? ""),
656
+ );
657
+ }
658
+ if (seg?.kind === "link") {
659
+ const href = String(seg.href ?? "");
660
+ if (!/^https?:\/\//iu.test(href)) return String(seg.text ?? "");
661
+ return h(
662
+ "a",
663
+ {
664
+ key: `l${i}`,
665
+ className: "dsh-btw-link",
666
+ href,
667
+ target: "_blank",
668
+ rel: "noreferrer noopener",
669
+ "data-btw-link": "true",
670
+ },
671
+ String(seg.text ?? href),
672
+ );
673
+ }
674
+ return String(seg?.text ?? "");
675
+ });
676
+ };
489
677
 
490
678
  const renderThread = (/** @type {any} */ thread, /** @type {number} */ index) => {
491
679
  const expanded = activeId === thread.threadId;
@@ -512,7 +700,8 @@ window.__ModuleLoader__.load({
512
700
  (() => {
513
701
  // 长答案默认折叠 6 行:实测一条 3000+ 字答案会把浮层撑满,
514
702
  // 用户只能看到答案中部、找不到成本与按钮。
515
- const answerText = String(thread.answer ?? "");
703
+ // 优先用 host 清理过的纯文本(保留代码块);没有就回退原文。
704
+ const answerText = String(thread.answerPlain ?? thread.answer ?? "");
516
705
  const key = String(thread.threadId ?? "");
517
706
  const isOpen = expandedAnswers[key] === true;
518
707
  const needsClamp = answerText.length > 400;
@@ -525,7 +714,7 @@ window.__ModuleLoader__.load({
525
714
  className: `dsh-btw-a${needsClamp && !isOpen ? " is-clamped" : ""}`,
526
715
  "data-btw-answer": "true",
527
716
  },
528
- answerText,
717
+ renderAnswerBody(thread, answerText),
529
718
  ),
530
719
  needsClamp
531
720
  ? h(
@@ -624,7 +813,6 @@ window.__ModuleLoader__.load({
624
813
  return h(
625
814
  "span",
626
815
  { "data-btw-root": "true" },
627
- button,
628
816
  h(
629
817
  "div",
630
818
  { className: "dsh-btw-panel", "data-btw-overlay": "true", role: "dialog" },
@@ -632,6 +820,16 @@ window.__ModuleLoader__.load({
632
820
  "div",
633
821
  { className: "dsh-btw-head" },
634
822
  h("span", null, t("title")),
823
+ h(
824
+ "button",
825
+ {
826
+ type: "button",
827
+ className: "dsh-btw-btn",
828
+ "data-btw-new": "true",
829
+ onClick: () => setShowNew((/** @type {boolean} */ v) => !v),
830
+ },
831
+ showNew ? t("collapse") : t("newQuestion"),
832
+ ),
635
833
  h(
636
834
  "button",
637
835
  {
@@ -662,37 +860,39 @@ window.__ModuleLoader__.load({
662
860
  { className: "dsh-btw-err", "data-btw-error": "history_unavailable" },
663
861
  `${t("failed")} — ${lastRpcError}`,
664
862
  )
665
- : body,
666
- h(
667
- "div",
668
- { className: "dsh-btw-row", "data-btw-newline": "true" },
669
- h("textarea", {
670
- className: "dsh-btw-input",
671
- "data-btw-input": "true",
672
- placeholder: t("placeholder"),
673
- value: activeId === "" ? question : "",
674
- rows: 2,
675
- onChange: (/** @type {any} */ event) =>
676
- setQuestion(String(event?.target?.value ?? "")),
677
- onKeyDown: (/** @type {any} */ event) => {
678
- if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
679
- event.preventDefault();
680
- void submit("");
681
- }
682
- },
683
- }),
684
- h(
685
- "button",
686
- {
687
- type: "button",
688
- className: "dsh-btw-btn",
689
- "data-btw-send": "true",
690
- disabled: busy || question.trim() === "",
691
- onClick: () => void submit(""),
692
- },
693
- t("send"),
694
- ),
695
- ),
863
+ : h("div", { className: "dsh-btw-scroll", "data-btw-list": "true" }, body),
864
+ showNew
865
+ ? h(
866
+ "div",
867
+ { className: "dsh-btw-row", "data-btw-newline": "true" },
868
+ h("textarea", {
869
+ className: "dsh-btw-input",
870
+ "data-btw-input": "true",
871
+ placeholder: t("placeholder"),
872
+ value: activeId === "" ? question : "",
873
+ rows: 2,
874
+ onChange: (/** @type {any} */ event) =>
875
+ setQuestion(String(event?.target?.value ?? "")),
876
+ onKeyDown: (/** @type {any} */ event) => {
877
+ if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
878
+ event.preventDefault();
879
+ void submit("");
880
+ }
881
+ },
882
+ }),
883
+ h(
884
+ "button",
885
+ {
886
+ type: "button",
887
+ className: "dsh-btw-btn",
888
+ "data-btw-send": "true",
889
+ disabled: busy || question.trim() === "",
890
+ onClick: () => void submit(""),
891
+ },
892
+ t("send"),
893
+ ),
894
+ )
895
+ : null,
696
896
  h(
697
897
  "div",
698
898
  { className: "dsh-btw-row" },
@@ -711,6 +911,7 @@ window.__ModuleLoader__.load({
711
911
  h("option", { value: "selection" }, t("scopeSelection")),
712
912
  ),
713
913
  ),
914
+ h("div", { className: "dsh-btw-meta", "data-btw-hint": "true" }, t("submitHint")),
714
915
  badge === ""
715
916
  ? null
716
917
  : h("div", { className: "dsh-btw-meta", "data-btw-badge": "true" }, badge),
@@ -874,7 +1075,14 @@ window.__ModuleLoader__.load({
874
1075
  ctx.slots.inject("conversation.input.left", () =>
875
1076
  ctx.slots.register(
876
1077
  { name: "conversation.input.left", id: "btw-toggle", order: 40, locale: NS },
877
- (/** @type {any} */ props) => h(BtwPanel, props),
1078
+ (/** @type {any} */ props) => h(BtwTrigger, props),
1079
+ ),
1080
+ );
1081
+
1082
+ // 浮层挂在 shell.overlay(frame-wide,所有列之上、滚动容器之外),不受 composer 裁剪。
1083
+ ctx.slots.inject("shell.overlay", () =>
1084
+ ctx.slots.register({ name: "shell.overlay", id: "btw-panel", order: 60, locale: NS }, () =>
1085
+ h(BtwPanel, null),
878
1086
  ),
879
1087
  );
880
1088
  };
@@ -0,0 +1,64 @@
1
+ // @ts-check
2
+ // 「追问待处理队列」:浮层想发起追问,但只能借 composer 提交一条命令
3
+ // (client 没有 commands 服务,真实 Agent 只能从命令上下文取 —— 见 ADR 0016)。
4
+ //
5
+ // 直接写 `/btw --thread t_xxx <问题>` 会把内部参数暴露在用户输入框里(实测被抱怨)。
6
+ // 改成:client 先把 {threadId, question, scope} 交给 host 暂存,再提交**裸 `/btw`**;
7
+ // host 处理命令时先查队列,取到就当追问处理,取不到才走「重开上一条」的老语义。
8
+ //
9
+ // 纯逻辑、不 import 宿主包,便于单测。
10
+
11
+ /**
12
+ * @typedef {{ threadId: string, question: string, scope: string, at: number }} PendingFollowUp
13
+ */
14
+
15
+ /**
16
+ * 建一个按 sessionId 分槽的待处理队列。
17
+ *
18
+ * 单槽而非数组:同一个会话在任意时刻只会有一次「即将提交的追问」,
19
+ * 覆盖旧值比排队更符合实际(用户连点两次时后一次生效)。
20
+ * @param {{ ttlMs?: number, now?: () => number }} [options]
21
+ */
22
+ export function createFollowUpQueue(options = {}) {
23
+ const ttlMs = Number(options.ttlMs) || 60_000;
24
+ const now = options.now ?? Date.now;
25
+ /** @type {Map<string, PendingFollowUp>} */
26
+ const slots = new Map();
27
+ return {
28
+ /**
29
+ * 登记一次待处理的追问。
30
+ * @param {string} sessionId
31
+ * @param {{ threadId: string, question: string, scope?: string }} input
32
+ * @returns {void}
33
+ */
34
+ push(sessionId, input) {
35
+ const threadId = String(input?.threadId ?? "");
36
+ const question = String(input?.question ?? "");
37
+ if (sessionId === "" || threadId === "" || question === "") return;
38
+ slots.set(sessionId, {
39
+ threadId,
40
+ question,
41
+ scope: String(input?.scope ?? ""),
42
+ at: now(),
43
+ });
44
+ },
45
+
46
+ /**
47
+ * 取出并清空(一次性)。过期的视为不存在。
48
+ * @param {string} sessionId
49
+ * @returns {PendingFollowUp | undefined}
50
+ */
51
+ take(sessionId) {
52
+ const item = slots.get(sessionId);
53
+ if (item === undefined) return undefined;
54
+ slots.delete(sessionId);
55
+ if (now() - item.at > ttlMs) return undefined;
56
+ return item;
57
+ },
58
+
59
+ /** 诊断用。 */
60
+ size() {
61
+ return slots.size;
62
+ },
63
+ };
64
+ }
package/lib/service.js CHANGED
@@ -5,6 +5,7 @@
5
5
  import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
6
6
  import { renderBadge } from "./badge.js";
7
7
  import { parseAllowedTools } from "./config.js";
8
+ import { createFollowUpQueue } from "./followup-queue.js";
8
9
  import { appendRecord, lastRecord, listRecent } from "./history.js";
9
10
  import { clip, LIMITS } from "./limits.js";
10
11
  import { format, loadMessages, pickLanguage } from "./messages.js";
@@ -75,6 +76,8 @@ export class BtwService extends TypertRemoteService {
75
76
  this.allowedTools = this.configAllowedTools;
76
77
  this.language = pickLanguage(this.config?.language);
77
78
  this.usageBySession = observeUsage(ctx);
79
+ // 浮层追问借 composer 提交裸 `/btw`,真实参数从这里取(见 followup-queue.js)。
80
+ this.followUps = createFollowUpQueue({});
78
81
  /** @type {Record<string, string>} */
79
82
  this.messages = FALLBACK;
80
83
  // locale 加载(不阻塞激活)
@@ -131,9 +134,20 @@ export class BtwService extends TypertRemoteService {
131
134
  const file = historyFile(this.dataRoot, agent?.id ?? "");
132
135
  // 追问用 `/btw --thread <id> <问题>` 标记线程(见 threads.js 的 parseThreadFlag 说明)。
133
136
  const parsed = parseCommandArgs(String(invocation?.rawInput ?? ""));
134
- const threadId = parsed.threadId;
135
- const scope = parsed.scope;
136
- const question = clip(parsed.question, LIMITS.questionChars);
137
+ let threadId = parsed.threadId;
138
+ let scope = parsed.scope;
139
+ let rawQuestion = parsed.question;
140
+ // 裸 `/btw`(无参数)时先看有没有浮层登记的追问:
141
+ // 有就当追问处理,没有才走「重开上一条」的老语义。
142
+ if (threadId === "" && rawQuestion === "") {
143
+ const queued = this.followUps.take(String(agent?.id ?? ""));
144
+ if (queued !== undefined) {
145
+ threadId = queued.threadId;
146
+ scope = queued.scope;
147
+ rawQuestion = queued.question;
148
+ }
149
+ }
150
+ const question = clip(rawQuestion, LIMITS.questionChars);
137
151
 
138
152
  if (question.text === "") {
139
153
  const previous = await lastRecord(file).catch(() => undefined);
@@ -303,6 +317,22 @@ export class BtwService extends TypertRemoteService {
303
317
  return lastRecord(historyFile(this.dataRoot, String(input.sessionId ?? "")));
304
318
  }
305
319
 
320
+ /**
321
+ * 登记一次待处理的追问。client 在提交裸 `/btw` **之前**调用,
322
+ * 这样命令文本里不必出现 `--thread t_xxx`。
323
+ * @param {{ sessionId?: string, threadId?: string, question?: string, scope?: string } | undefined} request
324
+ * @returns {Promise<{ ok: boolean, size: number }>}
325
+ */
326
+ async queueFollowUp(request) {
327
+ const input = request ?? {};
328
+ this.followUps.push(String(input.sessionId ?? ""), {
329
+ threadId: String(input.threadId ?? ""),
330
+ question: String(input.question ?? ""),
331
+ scope: String(input.scope ?? ""),
332
+ });
333
+ return { ok: true, size: this.followUps.size() };
334
+ }
335
+
306
336
  /**
307
337
  * 读当前设置(client 设置面板用)。
308
338
  * @param {undefined} request 参数必须存在且是单一标识符(网关 SRC 校验)。
@@ -359,6 +389,7 @@ export class BtwService extends TypertRemoteService {
359
389
  declareRemote(BtwService, "history");
360
390
  declareRemote(BtwService, "last");
361
391
  declareRemote(BtwService, "stats");
392
+ declareRemote(BtwService, "queueFollowUp");
362
393
  declareRemote(BtwService, "threads");
363
394
  declareRemote(BtwService, "promote");
364
395
  declareRemote(BtwService, "settings");
package/lib/threads.js CHANGED
@@ -18,10 +18,13 @@ export const PROMOTE_SECTIONS = [
18
18
  * @returns {string}
19
19
  */
20
20
  export function newThreadId(now = Date.now(), rand = Math.random) {
21
- const suffix = Math.floor(rand() * 36 ** 4)
21
+ // 短 id:浮层发问要走 composer,命令文本(`/btw --thread <id> ...`)会短暂出现在
22
+ // 用户输入框里,id 越短越不刺眼。实测 16 字符的 `t_mwkfmjk1_qrb3` 太显眼。
23
+ // 单机单会话内冲突概率可忽略(时间 36 进制 + 2 位随机)。
24
+ const suffix = Math.floor(rand() * 36 ** 2)
22
25
  .toString(36)
23
- .padStart(4, "0");
24
- return `t_${now.toString(36)}_${suffix}`;
26
+ .padStart(2, "0");
27
+ return `t_${now.toString(36)}${suffix}`;
25
28
  }
26
29
 
27
30
  /**
@@ -111,16 +114,48 @@ export function renderPromoteDraft(record, options = {}) {
111
114
  }
112
115
 
113
116
  /**
114
- * 去掉常见 Markdown 标记,让文本适合直接放进输入框。
117
+ * 去掉常见 Markdown 标记,让文本适合直接阅读/放进输入框。
115
118
  *
116
- * 为什么必须做:实测用户点「转正」后,输入框里塞进来的是 `## 我问了什么`、
117
- * `**每个 PR 上实际出现的检查是 8 个**`、`|---|` 这类源码,用户原话是
118
- * 「为什么给我一堆井号和竖线?」。我们没有 Markdown 渲染器(ADR 0001 不引入构建),
119
- * 所以草稿必须自己变成纯文本。
120
119
  * @param {string} text
120
+ * @param {{ keepCode?: boolean, keepFence?: boolean }} [options]
121
+ * - keepCode 默认 true:``` 围栏内的内容原样保留(代码缩进有意义)
122
+ * - keepFence 默认 false:true 时保留 ``` 围栏标记,供 client 识别代码块边界
121
123
  * @returns {string}
122
124
  */
123
- export function stripMarkdown(text) {
125
+ export function stripMarkdown(text, options = {}) {
126
+ const raw = String(text ?? "");
127
+ if (options.keepCode === false) return stripAllMarkdown(raw);
128
+ const keepFence = options.keepFence === true;
129
+ // 先把围栏块抽出占位,避免下面的标记清理破坏代码内容。
130
+ /** @type {{ lang: string, body: string }[]} */
131
+ const fences = [];
132
+ const parked = raw.replace(
133
+ /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu,
134
+ (/** @type {string} */ _m, /** @type {string} */ lang, /** @type {string} */ body) => {
135
+ const fence = body.replace(/\n+$/u, "");
136
+ fences.push({ lang, body: fence });
137
+ return `@@BTWFENCE${fences.length - 1}@@`;
138
+ },
139
+ );
140
+ const cleaned = stripAllMarkdown(parked).replace(
141
+ /@@BTWFENCE(\d+)@@/gu,
142
+ (/** @type {string} */ _m, /** @type {string} */ i) => {
143
+ const fence = fences[Number(i)];
144
+ if (fence === undefined) return "";
145
+ // keepFence 时保留 ``` 标记:client 靠它识别代码块边界,渲染成 <pre> 后
146
+ // 再把标记本身隐藏掉。默认关,转正草稿等纯文本场景不需要它。
147
+ return keepFence ? `\n\`\`\`${fence.lang}\n${fence.body}\n\`\`\`\n` : `\n${fence.body}\n`;
148
+ },
149
+ );
150
+ return cleaned.replace(/\n{3,}/gu, "\n\n").trim();
151
+ }
152
+
153
+ /**
154
+ * 纯标记清理(条目级,不含代码块保护)。
155
+ * @param {string} text
156
+ * @returns {string}
157
+ */
158
+ function stripAllMarkdown(text) {
124
159
  return (
125
160
  String(text ?? "")
126
161
  .replace(/^\s{0,3}#{1,6}\s+/gmu, "") // 标题井号
@@ -190,7 +225,7 @@ export function parseThreadFlag(raw) {
190
225
  /**
191
226
  * 线程列表(给浮层展示):按最后一条时间倒序,每项带条数与首问。
192
227
  * @param {any[]} records
193
- * @returns {{ threadId: string, turns: number, question: string, answer: string, lastId: string, cost: any, ms: number, at: number }[]}
228
+ * @returns {{ threadId: string, turns: number, question: string, answer: string, answerPlain: string, answerSegments: AnswerSegment[], lastId: string, cost: any, ms: number, at: number }[]}
194
229
  */
195
230
  export function listThreads(records) {
196
231
  return groupThreads(records)
@@ -199,6 +234,14 @@ export function listThreads(records) {
199
234
  turns: thread.items.length,
200
235
  question: String(thread.items[0]?.question ?? ""),
201
236
  answer: String(thread.last?.answer ?? ""),
237
+ // 展示用:去掉 Markdown 噪音但保留代码块(列表里显示原文的话,用户看到的是
238
+ // `**粗体**`、`|表|格|`、`|---|`,实测被抱怨「为什么给我一堆井号和竖线」)。
239
+ answerPlain: stripMarkdown(String(thread.last?.answer ?? "")),
240
+ // 渲染用:切好的段(代码块 / 链接 / 文本)。解析只在这里做一份,
241
+ // client 只负责把 kind 映射成元素(classic script 无法 import 这个模块)。
242
+ answerSegments: parseRichSegments(
243
+ stripMarkdown(String(thread.last?.answer ?? ""), { keepFence: true }),
244
+ ),
202
245
  lastId: String(thread.last?.id ?? ""),
203
246
  cost: thread.last?.cost ?? null,
204
247
  ms: Number(thread.last?.ms ?? 0),
@@ -238,3 +281,67 @@ export function parseCommandArgs(raw) {
238
281
  }
239
282
  return { threadId, scope, question: rest.trim() };
240
283
  }
284
+
285
+ /**
286
+ * @typedef {{ kind: "text", text: string }} TextSegment
287
+ * @typedef {{ kind: "code", lang: string, text: string }} CodeSegment
288
+ * @typedef {{ kind: "link", text: string, href: string }} LinkSegment
289
+ * @typedef {TextSegment | CodeSegment | LinkSegment} AnswerSegment
290
+ */
291
+
292
+ /**
293
+ * 把答案文本切成渲染段:代码块 / 链接 / 普通文本。
294
+ *
295
+ * 为什么需要它:`answerPlain` 保留了 ``` 围栏(`keepFence`),client 才能识别代码块边界,
296
+ * 把代码渲染成等宽 `<pre>` 而**不显示** ``` 本身;普通文本里的 URL 变成可点链接
297
+ * (之前答案里的链接是死文本)。
298
+ *
299
+ * 刻意**不做**完整 Markdown 渲染(表格/标题/粗体):仓库不引入构建步骤(ADR 0001),
300
+ * 手写完整渲染器的成本与风险远大于收益。粗体/表格已由 stripMarkdown 变成可读标点。
301
+ * @param {string} text
302
+ * @returns {AnswerSegment[]}
303
+ */
304
+ export function parseRichSegments(text) {
305
+ const raw = String(text ?? "");
306
+ /** @type {AnswerSegment[]} */
307
+ const out = [];
308
+ // 1) 先按围栏切出代码块
309
+ const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu;
310
+ let last = 0;
311
+ for (;;) {
312
+ const match = fenceRe.exec(raw);
313
+ if (match === null) break;
314
+ if (match.index > last) out.push(...splitLinks(raw.slice(last, match.index)));
315
+ out.push({ kind: "code", lang: match[1] ?? "", text: (match[2] ?? "").replace(/\n+$/u, "") });
316
+ last = match.index + match[0].length;
317
+ }
318
+ if (last < raw.length) out.push(...splitLinks(raw.slice(last)));
319
+ return out.length > 0 ? out : [{ kind: "text", text: raw }];
320
+ }
321
+
322
+ /**
323
+ * 把一段普通文本按 URL 切成 text/link 段。
324
+ * @param {string} text
325
+ * @returns {AnswerSegment[]}
326
+ */
327
+ function splitLinks(text) {
328
+ /** @type {AnswerSegment[]} */
329
+ const out = [];
330
+ // 只认 http(s);末尾的标点(。,;:!?)】」)不属于 URL。
331
+ const urlRe = /https?:\/\/[^\s<>()\u3000-\u303f\uff00-\uffef]+/gu;
332
+ let last = 0;
333
+ for (;;) {
334
+ const match = urlRe.exec(text);
335
+ if (match === null) break;
336
+ const raw = match[0];
337
+ const trimmed = raw.replace(/[.,;:!?]+$/u, "");
338
+ if (match.index > last) out.push({ kind: "text", text: text.slice(last, match.index) });
339
+ if (trimmed !== "") out.push({ kind: "link", text: trimmed, href: trimmed });
340
+ const rest = raw.slice(trimmed.length);
341
+ if (rest !== "") out.push({ kind: "text", text: rest });
342
+ last = match.index + raw.length;
343
+ }
344
+ if (last < text.length) out.push({ kind: "text", text: text.slice(last) });
345
+ if (out.length === 0 && text !== "") out.push({ kind: "text", text });
346
+ return out;
347
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-btw",
3
- "version": "0.1.1",
3
+ "version": "0.3.0",
4
4
  "description": "Read-only side questions that do not interrupt the main task",
5
5
  "keywords": [
6
6
  "dsh",