@kangyishuai/dsh-btw 0.1.1 → 0.2.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/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,8 +119,9 @@ 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;}",
@@ -175,6 +180,41 @@ window.__ModuleLoader__.load({
175
180
  return () => style.remove();
176
181
  }, "btw: styles");
177
182
 
183
+ /**
184
+ * 按钮(composer 工具行)与浮层(`shell.overlay`)是两个独立组件实例,
185
+ * 共享状态必须提升到 apply 作用域。
186
+ *
187
+ * 为什么浮层改注册到 `shell.overlay`:`conversation.input.overlay` 的 slot 文档写着
188
+ * "fixed overlays must portal to the document body because the docked composer contains them"。
189
+ * 放在 composer 里会被裁剪 —— 实测提示条跑到浮层下方 302px、位置还随对话流滚动漂移。
190
+ * `shell.overlay` 的语义是 "frame-wide floating layer, above every column and outside
191
+ * their scroll containers",换过去从根上解决,不必手写 portal。
192
+ */
193
+ const store = (() => {
194
+ /** @type {{ open: boolean, sessionId: string }} */
195
+ let state = { open: false, sessionId: "" };
196
+ /** @type {Set<() => void>} */
197
+ const listeners = new Set();
198
+ return {
199
+ get: () => state,
200
+ patch(/** @type {Partial<{ open: boolean, sessionId: string }>} */ next) {
201
+ state = { ...state, ...next };
202
+ for (const listener of listeners) listener();
203
+ },
204
+ subscribe(/** @type {() => void} */ listener) {
205
+ listeners.add(listener);
206
+ return () => listeners.delete(listener);
207
+ },
208
+ };
209
+ })();
210
+
211
+ /** 订阅 store 的极简 hook。 */
212
+ const useStore = () => {
213
+ const [, force] = React.useState(0);
214
+ React.useEffect(() => store.subscribe(() => force((/** @type {number} */ n) => n + 1)), []);
215
+ return store.get();
216
+ };
217
+
178
218
  /** 当前界面语言(转正草稿用)。取不到默认 zh。 */
179
219
  const langOf = () => {
180
220
  try {
@@ -309,10 +349,44 @@ window.__ModuleLoader__.load({
309
349
  return "ok";
310
350
  };
311
351
 
352
+ /**
353
+ * composer 工具行里的「旁问」按钮。
354
+ *
355
+ * 它同时负责把当前 sessionId 写进 store —— 浮层注册在 root scope 的
356
+ * `shell.overlay` 上,拿不到 session props,只能由按钮转交。
357
+ */
358
+ function BtwTrigger(/** @type {any} */ props) {
359
+ const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
360
+ const shared = useStore();
361
+ React.useEffect(() => {
362
+ if (shared.sessionId !== sessionId) store.patch({ sessionId });
363
+ }, [sessionId, shared.sessionId]);
364
+ return h(
365
+ "button",
366
+ {
367
+ type: "button",
368
+ className: "dsh-btw-btn",
369
+ "data-btw-toggle": "true",
370
+ title: t("button"),
371
+ onClick: () => store.patch({ open: !store.get().open }),
372
+ },
373
+ t("button"),
374
+ );
375
+ }
376
+
312
377
  /** 浮层:只读列表 + 浮层内发问。 */
313
378
  function BtwPanel(/** @type {any} */ props) {
314
- const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
315
- const [open, setOpen] = React.useState(false);
379
+ void props;
380
+ const shared = useStore();
381
+ const open = shared.open;
382
+ const sessionId = shared.sessionId;
383
+ const setOpen = (/** @type {boolean | ((prev: boolean) => boolean)} */ next) =>
384
+ store.patch({
385
+ open:
386
+ typeof next === "function"
387
+ ? /** @type {(prev: boolean) => boolean} */ (next)(store.get().open)
388
+ : next,
389
+ });
316
390
  const [threads, setThreads] = React.useState(/** @type {any[] | null} */ (null));
317
391
  const [failed, setFailed] = React.useState(false);
318
392
  const [activeId, setActiveId] = React.useState("");
@@ -324,6 +398,9 @@ window.__ModuleLoader__.load({
324
398
  const [expandedAnswers, setExpandedAnswers] = React.useState(
325
399
  /** @type {Record<string, boolean>} */ ({}),
326
400
  );
401
+ // 新建旁问的输入框默认收起:实测同时出现「线程内追问框 + 底部新建框」时,
402
+ // 用户分不清哪个是哪个(两个输入框视觉几乎一样)。
403
+ const [showNew, setShowNew] = React.useState(false);
327
404
  const aliveRef = React.useRef(true);
328
405
 
329
406
  React.useEffect(
@@ -473,19 +550,8 @@ window.__ModuleLoader__.load({
473
550
  setNotice(t("promoted"));
474
551
  };
475
552
 
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
- );
487
-
488
- if (!open) return h("span", { "data-btw-root": "true" }, button);
553
+ // 浮层不画按钮:按钮由 BtwTrigger 注册在 composer 工具行里。
554
+ if (!open) return null;
489
555
 
490
556
  const renderThread = (/** @type {any} */ thread, /** @type {number} */ index) => {
491
557
  const expanded = activeId === thread.threadId;
@@ -512,7 +578,8 @@ window.__ModuleLoader__.load({
512
578
  (() => {
513
579
  // 长答案默认折叠 6 行:实测一条 3000+ 字答案会把浮层撑满,
514
580
  // 用户只能看到答案中部、找不到成本与按钮。
515
- const answerText = String(thread.answer ?? "");
581
+ // 优先用 host 清理过的纯文本(保留代码块);没有就回退原文。
582
+ const answerText = String(thread.answerPlain ?? thread.answer ?? "");
516
583
  const key = String(thread.threadId ?? "");
517
584
  const isOpen = expandedAnswers[key] === true;
518
585
  const needsClamp = answerText.length > 400;
@@ -624,7 +691,6 @@ window.__ModuleLoader__.load({
624
691
  return h(
625
692
  "span",
626
693
  { "data-btw-root": "true" },
627
- button,
628
694
  h(
629
695
  "div",
630
696
  { className: "dsh-btw-panel", "data-btw-overlay": "true", role: "dialog" },
@@ -632,6 +698,16 @@ window.__ModuleLoader__.load({
632
698
  "div",
633
699
  { className: "dsh-btw-head" },
634
700
  h("span", null, t("title")),
701
+ h(
702
+ "button",
703
+ {
704
+ type: "button",
705
+ className: "dsh-btw-btn",
706
+ "data-btw-new": "true",
707
+ onClick: () => setShowNew((/** @type {boolean} */ v) => !v),
708
+ },
709
+ showNew ? t("collapse") : t("newQuestion"),
710
+ ),
635
711
  h(
636
712
  "button",
637
713
  {
@@ -662,37 +738,39 @@ window.__ModuleLoader__.load({
662
738
  { className: "dsh-btw-err", "data-btw-error": "history_unavailable" },
663
739
  `${t("failed")} — ${lastRpcError}`,
664
740
  )
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
- ),
741
+ : h("div", { className: "dsh-btw-scroll", "data-btw-list": "true" }, body),
742
+ showNew
743
+ ? h(
744
+ "div",
745
+ { className: "dsh-btw-row", "data-btw-newline": "true" },
746
+ h("textarea", {
747
+ className: "dsh-btw-input",
748
+ "data-btw-input": "true",
749
+ placeholder: t("placeholder"),
750
+ value: activeId === "" ? question : "",
751
+ rows: 2,
752
+ onChange: (/** @type {any} */ event) =>
753
+ setQuestion(String(event?.target?.value ?? "")),
754
+ onKeyDown: (/** @type {any} */ event) => {
755
+ if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
756
+ event.preventDefault();
757
+ void submit("");
758
+ }
759
+ },
760
+ }),
761
+ h(
762
+ "button",
763
+ {
764
+ type: "button",
765
+ className: "dsh-btw-btn",
766
+ "data-btw-send": "true",
767
+ disabled: busy || question.trim() === "",
768
+ onClick: () => void submit(""),
769
+ },
770
+ t("send"),
771
+ ),
772
+ )
773
+ : null,
696
774
  h(
697
775
  "div",
698
776
  { className: "dsh-btw-row" },
@@ -711,6 +789,7 @@ window.__ModuleLoader__.load({
711
789
  h("option", { value: "selection" }, t("scopeSelection")),
712
790
  ),
713
791
  ),
792
+ h("div", { className: "dsh-btw-meta", "data-btw-hint": "true" }, t("submitHint")),
714
793
  badge === ""
715
794
  ? null
716
795
  : h("div", { className: "dsh-btw-meta", "data-btw-badge": "true" }, badge),
@@ -874,7 +953,14 @@ window.__ModuleLoader__.load({
874
953
  ctx.slots.inject("conversation.input.left", () =>
875
954
  ctx.slots.register(
876
955
  { name: "conversation.input.left", id: "btw-toggle", order: 40, locale: NS },
877
- (/** @type {any} */ props) => h(BtwPanel, props),
956
+ (/** @type {any} */ props) => h(BtwTrigger, props),
957
+ ),
958
+ );
959
+
960
+ // 浮层挂在 shell.overlay(frame-wide,所有列之上、滚动容器之外),不受 composer 裁剪。
961
+ ctx.slots.inject("shell.overlay", () =>
962
+ ctx.slots.register({ name: "shell.overlay", id: "btw-panel", order: 60, locale: NS }, () =>
963
+ h(BtwPanel, null),
878
964
  ),
879
965
  );
880
966
  };
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
  /**
@@ -120,7 +123,40 @@ export function renderPromoteDraft(record, options = {}) {
120
123
  * @param {string} text
121
124
  * @returns {string}
122
125
  */
123
- export function stripMarkdown(text) {
126
+ /**
127
+ * 去掉常见 Markdown 标记,让文本适合直接阅读/放进输入框。
128
+ *
129
+ * @param {string} text
130
+ * @param {{ keepCode?: boolean }} [options] keepCode 默认 true:``` 围栏内的内容原样保留
131
+ * (代码缩进有意义,清掉会毁掉可读性)。
132
+ * @returns {string}
133
+ */
134
+ export function stripMarkdown(text, options = {}) {
135
+ const raw = String(text ?? "");
136
+ if (options.keepCode === false) return stripAllMarkdown(raw);
137
+ // 先把围栏块抽出占位,避免下面的标记清理破坏代码内容。
138
+ /** @type {string[]} */
139
+ const fences = [];
140
+ const parked = raw.replace(
141
+ /```[a-zA-Z0-9_-]*\n([\s\S]*?)```/gu,
142
+ (/** @type {string} */ _m, /** @type {string} */ body) => {
143
+ fences.push(body.replace(/\n+$/u, ""));
144
+ return `@@BTWFENCE${fences.length - 1}@@`;
145
+ },
146
+ );
147
+ const cleaned = stripAllMarkdown(parked).replace(
148
+ /@@BTWFENCE(\d+)@@/gu,
149
+ (/** @type {string} */ _m, /** @type {string} */ i) => `\n${fences[Number(i)] ?? ""}\n`,
150
+ );
151
+ return cleaned.replace(/\n{3,}/gu, "\n\n").trim();
152
+ }
153
+
154
+ /**
155
+ * 纯标记清理(条目级,不含代码块保护)。
156
+ * @param {string} text
157
+ * @returns {string}
158
+ */
159
+ function stripAllMarkdown(text) {
124
160
  return (
125
161
  String(text ?? "")
126
162
  .replace(/^\s{0,3}#{1,6}\s+/gmu, "") // 标题井号
@@ -190,7 +226,7 @@ export function parseThreadFlag(raw) {
190
226
  /**
191
227
  * 线程列表(给浮层展示):按最后一条时间倒序,每项带条数与首问。
192
228
  * @param {any[]} records
193
- * @returns {{ threadId: string, turns: number, question: string, answer: string, lastId: string, cost: any, ms: number, at: number }[]}
229
+ * @returns {{ threadId: string, turns: number, question: string, answer: string, answerPlain: string, lastId: string, cost: any, ms: number, at: number }[]}
194
230
  */
195
231
  export function listThreads(records) {
196
232
  return groupThreads(records)
@@ -199,6 +235,9 @@ export function listThreads(records) {
199
235
  turns: thread.items.length,
200
236
  question: String(thread.items[0]?.question ?? ""),
201
237
  answer: String(thread.last?.answer ?? ""),
238
+ // 展示用:去掉 Markdown 噪音但保留代码块(列表里显示原文的话,用户看到的是
239
+ // `**粗体**`、`|表|格|`、`|---|`,实测被抱怨「为什么给我一堆井号和竖线」)。
240
+ answerPlain: stripMarkdown(String(thread.last?.answer ?? "")),
202
241
  lastId: String(thread.last?.id ?? ""),
203
242
  cost: thread.last?.cost ?? null,
204
243
  ms: Number(thread.last?.ms ?? 0),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangyishuai/dsh-btw",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Read-only side questions that do not interrupt the main task",
5
5
  "keywords": [
6
6
  "dsh",