@kangyishuai/dsh-btw 0.3.0 → 0.4.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
@@ -1,12 +1,15 @@
1
1
  // @ts-check
2
2
  // client 半:classic script,以 window.__ModuleLoader__.load 注册 factory,不能 import / JSX。
3
3
  //
4
- // 职责(v0.2b):
5
- // A. 输入框左侧一个「旁问」按钮,点开浮层。
6
- // B. 浮层里列出本会话最近的旁问(Typert Remote `btw/history`),带成本徽章。
7
- // C. 浮层里可以直接发问:把 `/btw <问题>` 塞进 composer 再提交。
4
+ // 职责(v0.4):
5
+ // A. 输入框左侧一个「旁问」按钮,点开**右侧贴边抽屉**(不居中、不遮挡主对话)。
6
+ // B. 抽屉里按聊天顺序(旧→新、最新在底部,自动滚到底)列出本会话的旁问线程,
7
+ // 每条线程展开全部轮次,答案按 **Markdown** 渲染。
8
+ // C. 正在跑的旁问**流式**显示(host 在 `llm/stream` 上缓冲子会话文本,`btw/live` 轮询)。
9
+ // D. 直接发问 / 追问:把 `/btw <问题>` 塞进 composer 再提交。
8
10
  // **必须借 composer 提交**——真实 Agent 只能在命令调用上下文里拿到
9
11
  // (`ctx.agents.get()` 返回 undefined,见公开仓库 docs/adr/0016)。
12
+ // E. 一键转正:host 生成 Markdown 源码草稿,只插进输入框、绝不发送。
10
13
  //
11
14
  // 宿主调用走 ctx.connection.rpc.call("/api", "btw/<method>", { args: { request } })——
12
15
  // 无构建插件没有 typert 客户端产物(见 docs/runtime/0.2.2-rc.1.md §7)。
@@ -25,36 +28,47 @@ window.__ModuleLoader__.load({
25
28
  /** setDraft 走异步更新:轮询草稿落定(与 next-step 同参数)。 */
26
29
  const DRAFT_POLL_TRIES = 15;
27
30
  const DRAFT_POLL_INTERVAL_MS = 20;
28
- /** 浮层列出的线程条数上限。 */
31
+ /** 抽屉列出的线程条数上限(host 还会按 perSessionRecords 再夹一次)。 */
29
32
  const LIMITS_CLIENT_THREADS = 20;
30
- /** 提交后轮询历史,等新记录出现;按实测 /btw 耗时(32–40s)给足 120s 窗口。 */
33
+ /** 提交后轮询历史,等新记录出现;按实测 /btw 耗时(20–40s)给足 120s 窗口。 */
31
34
  const REFRESH_MAX_MS = 120_000;
32
- const REFRESH_INTERVAL_MS = 1500;
35
+ const REFRESH_INTERVAL_MS = 1200;
36
+ /** 流式轮询间隔:有 run 时密一点,空闲时慢一点(只读一个内存快照,很便宜)。 */
37
+ const LIVE_ACTIVE_MS = 350;
38
+ const LIVE_IDLE_MS = 1000;
39
+ /** 空闲时每 N 次 live 轮询才刷一次线程列表(约 4s)。 */
40
+ const LIVE_IDLE_REFRESH_EVERY = 4;
33
41
 
34
42
  const zh = {
35
43
  button: "旁问",
36
- title: "最近的旁问",
44
+ title: "旁问",
45
+ subtitle: "最近的旁问",
37
46
  placeholder: "提一个只读旁问…",
38
47
  send: "提问",
39
48
  empty: "本会话还没有旁问。在下面提一个,或直接用 /btw <问题>。",
40
49
  close: "关闭",
41
- cost: "新增 {newTokens} · 命中缓存 {cachedTokens} · {ms}ms",
50
+ collapse: "收起为侧边条",
51
+ collapseShort: "收起",
52
+ expand: "展开旁问",
53
+ cost: "新增 {newTokens} · 命中缓存 {cachedTokens} · {ms}",
42
54
  failed: "读取旁问历史失败",
43
55
  sent: "已提交,答案会出现在对话里",
44
56
  followUp: "追问",
45
- collapse: "收起",
46
57
  followPlaceholder: "在这个线程里追问…",
58
+ followUpLabel: "追问",
47
59
  turns: "轮",
48
60
  promote: "转正",
49
61
  promoted: "已插入输入框草稿(未发送)",
50
62
  promoteBlocked: "输入框已有内容,先清空再转正",
51
63
  promoteFailed: "生成转正草稿失败",
52
- sending: "正在等待答案…(通常 20–40 秒)",
64
+ sending: "正在等待答案…",
65
+ streaming: "正在生成回答",
66
+ waitHint: "通常 20–40 秒",
53
67
  sentPending: "命令已提交,答案稍后出现在对话里",
54
68
  expandAnswer: "展开全文",
55
69
  collapseAnswer: "收起",
56
- newQuestion: "+ 新旁问",
57
70
  submitHint: "提交时会以 /btw 命令写入对话",
71
+ newQuestionLabel: "新旁问",
58
72
  scopeAny: "范围:不限",
59
73
  scopeSession: "范围:整个会话",
60
74
  scopeRecent: "范围:最近几轮",
@@ -74,28 +88,34 @@ window.__ModuleLoader__.load({
74
88
  };
75
89
  const en = {
76
90
  button: "btw",
77
- title: "Recent side questions",
91
+ title: "Side questions",
92
+ subtitle: "Recent side questions",
78
93
  placeholder: "Ask a read-only side question…",
79
94
  send: "Ask",
80
95
  empty: "No side question yet. Ask one below, or use /btw <question>.",
81
96
  close: "Close",
82
- cost: "new {newTokens} · cached {cachedTokens} · {ms}ms",
97
+ collapse: "Collapse to side rail",
98
+ collapseShort: "Collapse",
99
+ expand: "Expand side questions",
100
+ cost: "new {newTokens} · cached {cachedTokens} · {ms}",
83
101
  failed: "Could not read side-question history",
84
102
  sent: "Submitted; the answer appears in the conversation",
85
103
  followUp: "Follow up",
86
- collapse: "Collapse",
87
104
  followPlaceholder: "Ask a follow-up in this thread…",
105
+ followUpLabel: "Follow-up",
88
106
  turns: "turns",
89
107
  promote: "Promote",
90
108
  promoted: "Inserted into the composer as a draft (not sent)",
91
109
  promoteBlocked: "Composer already has content; clear it before promoting",
92
110
  promoteFailed: "Could not create the promotion draft",
93
- sending: "Waiting for the answer… (usually 20–40s)",
111
+ sending: "Waiting for the answer…",
112
+ streaming: "Generating the answer",
113
+ waitHint: "usually 20–40s",
94
114
  sentPending: "Command submitted; the answer will appear in the conversation",
95
115
  expandAnswer: "Show all",
96
116
  collapseAnswer: "Collapse",
97
- newQuestion: "+ New question",
98
117
  submitHint: "Submitting writes a /btw command into the conversation",
118
+ newQuestionLabel: "New side question",
99
119
  scopeAny: "Scope: any",
100
120
  scopeSession: "Scope: whole session",
101
121
  scopeRecent: "Scope: recent turns",
@@ -116,29 +136,80 @@ window.__ModuleLoader__.load({
116
136
  };
117
137
 
118
138
  const CSS = [
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;}",
139
+ // ---- 通用按钮 --------------------------------------------------------
140
+ ".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;white-space:nowrap;}",
120
141
  ".dsh-btw-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.16));color:var(--dsw-alias-label-primary,CanvasText);}",
121
142
  ".dsh-btw-btn:disabled{opacity:.5;cursor:default;}",
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;}",
125
- ".dsh-btw-item{padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
126
- ".dsh-btw-q{color:var(--dsw-alias-label-secondary,GrayText);}",
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;}",
130
- ".dsh-btw-a.is-clamped{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:6;line-clamp:6;overflow:hidden;}",
131
- ".dsh-btw-meta{margin-top:2px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:11px;}",
132
- ".dsh-btw-dim{color:var(--dsw-alias-label-tertiary,GrayText);padding:6px 0;}",
133
- ".dsh-btw-err{color:var(--dsw-alias-state-error-primary,#d9534f);padding:6px 0;}",
134
- ".dsh-btw-row{display:flex;gap:6px;margin-top:8px;}",
135
- ".dsh-btw-status{position:sticky;top:-10px;z-index:2;display:flex;align-items:center;gap:6px;margin:0 0 8px;padding:5px 8px;border-radius:var(--dsw-radius-sm,6px);background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,Canvas));color:var(--dsw-alias-label-secondary,GrayText);font-size:12px;box-shadow:0 1px 0 var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
143
+ ".dsh-btw-btn.is-primary{background:var(--dsw-alias-button-primary-fill,#4f7cff);border-color:transparent;color:var(--dsw-alias-label-on-color,#fff);}",
144
+ ".dsh-btw-btn.is-primary:hover{background:var(--dsw-alias-button-primary-hover,#4f7cff);color:var(--dsw-alias-label-on-color,#fff);}",
145
+ // ---- 右侧抽屉 --------------------------------------------------------
146
+ // 贴右边、避开顶部会话头和底部 composer。注意:DSH 的对话区是整宽的,
147
+ // 抽屉仍会盖住主对话右侧约 400px(比居中弹窗好,但不是「完全不遮挡」);
148
+ // 完全不遮挡需要 DSH 原生右侧边栏(打开时主对话变窄)。
149
+ ".dsh-btw-panel{position:fixed;right:12px;top:72px;bottom:140px;width:min(400px,calc(100vw - 24px));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:10px 12px;font-size:12px;line-height:1.55;box-shadow:0 18px 48px rgba(0,0,0,.38);}",
150
+ "@media (max-width:760px){.dsh-btw-panel{top:56px;bottom:150px;width:calc(100vw - 24px);}}",
151
+ // 原生右侧栏 tab:填满 pane,不再 fixed / 不再自带卡片外壳(由右侧栏提供)。
152
+ ".dsh-btw-panel.is-tab{position:static;inset:auto;width:100%;max-width:820px;margin:0 auto;height:100%;min-height:0;max-height:none;border:none;border-radius:0;box-shadow:none;padding:12px 14px;background:transparent;}",
153
+ ".dsh-btw-rail{position:fixed;right:0;top:50%;transform:translateY(-50%);z-index:2147482000;display:flex;flex-direction:row;align-items:center;gap:6px;padding:9px 12px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));border-right:none;border-radius:10px 0 0 10px;background:var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,Canvas));color:var(--dsw-alias-label-secondary,GrayText);font-size:12px;cursor:pointer;box-shadow:-2px 0 10px rgba(0,0,0,.22);}",
154
+ ".dsh-btw-rail:hover{color:var(--dsw-alias-label-primary,CanvasText);background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,Canvas));}",
155
+ ".dsh-btw-rail-count{font-size:10px;opacity:.75;font-variant-numeric:tabular-nums;}",
156
+ // ---- 头部 / 状态 ------------------------------------------------------
157
+ ".dsh-btw-head{display:flex;align-items:center;gap:6px;margin-bottom:8px;font-weight:600;flex:none;}",
158
+ ".dsh-btw-head-title{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}",
159
+ ".dsh-btw-grow{flex:1 1 auto;}",
160
+ ".dsh-btw-status{display:flex;align-items:center;gap:6px;margin:0 0 8px;padding:5px 8px;border-radius:var(--dsw-radius-sm,6px);background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,Canvas));color:var(--dsw-alias-label-secondary,GrayText);font-size:11.5px;box-shadow:0 1px 0 var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
136
161
  ".dsh-btw-status.is-busy{color:var(--dsw-alias-label-primary,CanvasText);}",
137
162
  ".dsh-btw-spinner{display:inline-block;animation:dsh-btw-spin 1s linear infinite;}",
138
163
  "@keyframes dsh-btw-spin{from{transform:rotate(0)}to{transform:rotate(360deg)}}",
164
+ // ---- 列表 ------------------------------------------------------------
165
+ ".dsh-btw-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding-right:2px;scrollbar-gutter:stable;}",
166
+ ".dsh-btw-thread{padding:8px 0;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
167
+ ".dsh-btw-thread:first-child{border-top:none;padding-top:2px;}",
168
+ ".dsh-btw-turn{margin-top:6px;}",
169
+ ".dsh-btw-turn:first-child{margin-top:0;}",
170
+ ".dsh-btw-q{display:block;padding:5px 8px;border-radius:8px;background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,Canvas));color:var(--dsw-alias-label-primary,CanvasText);white-space:pre-wrap;word-break:break-word;font-size:12px;}",
171
+ ".dsh-btw-q-label{display:block;margin-bottom:2px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:10.5px;letter-spacing:.5px;}",
172
+ ".dsh-btw-a{margin-top:4px;word-break:break-word;}",
173
+ ".dsh-btw-meta{margin-top:3px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:11px;font-variant-numeric:tabular-nums;}",
174
+ ".dsh-btw-dim{color:var(--dsw-alias-label-tertiary,GrayText);padding:6px 0;}",
175
+ ".dsh-btw-err{color:var(--dsw-alias-state-error-primary,#d9534f);padding:6px 0;word-break:break-word;}",
176
+ ".dsh-btw-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-top:8px;}",
177
+ // ---- Markdown --------------------------------------------------------
178
+ ".dsh-btw-md{overflow-wrap:anywhere;}",
179
+ ".dsh-btw-md p{margin:0 0 6px;}",
180
+ ".dsh-btw-md p:last-child{margin-bottom:0;}",
181
+ ".dsh-btw-md h1,.dsh-btw-md h2,.dsh-btw-md h3,.dsh-btw-md h4,.dsh-btw-md h5,.dsh-btw-md h6{margin:10px 0 5px;font-weight:600;line-height:1.35;}",
182
+ ".dsh-btw-md h1{font-size:15px;}",
183
+ ".dsh-btw-md h2{font-size:14px;}",
184
+ ".dsh-btw-md h3{font-size:13px;}",
185
+ ".dsh-btw-md h4,.dsh-btw-md h5,.dsh-btw-md h6{font-size:12.5px;}",
186
+ ".dsh-btw-md ul,.dsh-btw-md ol{margin:4px 0 6px;padding-left:20px;}",
187
+ ".dsh-btw-md li{margin:2px 0;}",
188
+ ".dsh-btw-md blockquote{margin:6px 0;padding:2px 0 2px 10px;border-left:2px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));color:var(--dsw-alias-label-secondary,GrayText);}",
189
+ ".dsh-btw-md code{padding:1px 4px;border-radius:4px;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;}",
190
+ ".dsh-btw-codeblock{margin:6px 0;}",
191
+ ".dsh-btw-codeblock-lang{color:var(--dsw-alias-label-tertiary,GrayText);font-size:10.5px;margin-bottom:2px;}",
192
+ ".dsh-btw-md pre{margin: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;}",
193
+ ".dsh-btw-md pre code{padding:0;border:none;background:transparent;font-size:inherit;white-space:pre;}",
194
+ ".dsh-btw-tablewrap{max-width:100%;overflow-x:auto;margin:6px 0;}",
195
+ ".dsh-btw-md table{border-collapse:collapse;font-size:11.5px;}",
196
+ ".dsh-btw-md th,.dsh-btw-md td{border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));padding:4px 7px;text-align:left;vertical-align:top;}",
197
+ ".dsh-btw-md th{background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,Canvas));font-weight:600;}",
198
+ ".dsh-btw-md hr{border:none;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));margin:8px 0;}",
199
+ ".dsh-btw-md a,.dsh-btw-link{color:var(--dsw-alias-brand-primary,#4f7cff);text-decoration:underline;word-break:break-all;}",
200
+ ".dsh-btw-md strong{font-weight:600;}",
201
+ ".dsh-btw-md del{opacity:.65;}",
202
+ ".dsh-btw-caret{display:inline-block;width:6px;height:1em;margin-left:2px;vertical-align:-2px;background:currentColor;animation:dsh-btw-blink 1s steps(1) infinite;}",
203
+ "@keyframes dsh-btw-blink{50%{opacity:0}}",
204
+ ".dsh-btw-a.is-clamped .dsh-btw-md{position:relative;max-height:320px;overflow:hidden;}",
205
+ '.dsh-btw-a.is-clamped .dsh-btw-md::after{content:"";position:absolute;left:0;right:0;bottom:0;height:56px;background:linear-gradient(transparent,var(--dsw-alias-bg-layer-2,var(--dsw-alias-bg-base,Canvas)));pointer-events:none;}',
206
+ // ---- composer --------------------------------------------------------
207
+ ".dsh-btw-composer{flex:none;display:flex;flex-direction:column;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
208
+ ".dsh-btw-composer-label{color:var(--dsw-alias-label-tertiary,GrayText);font-size:10.5px;letter-spacing:.5px;}",
209
+ ".dsh-btw-select{flex:1 1 auto;min-width:0;height:28px;padding:0 6px;border-radius:var(--dsw-radius-sm,6px);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));background:var(--dsw-alias-bg-base,Canvas);color:var(--dsw-alias-label-primary,CanvasText);font:inherit;font-size:11.5px;}",
210
+ ".dsh-btw-input{flex:1 1 auto;min-width:0;resize:vertical;min-height:48px;padding:6px 8px;border-radius:var(--dsw-radius-sm,6px);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));background:var(--dsw-alias-bg-base,Canvas);color:var(--dsw-alias-label-primary,CanvasText);font:inherit;}",
139
211
  ".dsh-btw-setrow{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:6px 0;}",
140
212
  ".dsh-btw-setlabel{min-width:0;color:var(--dsw-alias-label-secondary,GrayText);}",
141
- ".dsh-btw-input{flex:1 1 auto;min-width:0;resize:vertical;min-height:52px;padding:6px 8px;border-radius:var(--dsw-radius-sm,6px);border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.35));background:var(--dsw-alias-bg-base,Canvas);color:var(--dsw-alias-label-primary,CanvasText);font:inherit;}",
142
213
  ].join("");
143
214
 
144
215
  /** @param {any} ctx @param {string} name */
@@ -162,6 +233,247 @@ window.__ModuleLoader__.load({
162
233
  );
163
234
  }
164
235
 
236
+ // ---- 自适应格式化(与 lib/format.js 行为等价;client 是 classic script,无法 import)--
237
+ const TOKEN_UNITS = [
238
+ { scale: 1e3, suffix: "K" },
239
+ { scale: 1e6, suffix: "M" },
240
+ { scale: 1e9, suffix: "B" },
241
+ { scale: 1e12, suffix: "T" },
242
+ ];
243
+ /** @param {number} value */
244
+ const oneDecimal = (value) => (Math.round(value * 10) / 10).toFixed(1).replace(/\.0+$/u, "");
245
+ /** @param {number} value */
246
+ const scaledText = (value) => (value < 100 ? oneDecimal(value) : String(Math.round(value)));
247
+
248
+ /** @param {unknown} value */
249
+ function formatTokens(value) {
250
+ const number = Math.max(0, Math.round(Number(value) || 0));
251
+ if (number < 1000) return String(number);
252
+ let index = 0;
253
+ for (let i = 0; i < TOKEN_UNITS.length; i += 1) {
254
+ if (number >= TOKEN_UNITS[i].scale) index = i;
255
+ }
256
+ let unit = TOKEN_UNITS[index];
257
+ let scaled = number / unit.scale;
258
+ if (index < TOKEN_UNITS.length - 1 && scaled >= 999.5) {
259
+ index += 1;
260
+ unit = TOKEN_UNITS[index];
261
+ scaled = number / unit.scale;
262
+ }
263
+ return `${scaledText(scaled)}${unit.suffix}`;
264
+ }
265
+
266
+ /** @param {unknown} value */
267
+ function formatDuration(value) {
268
+ const ms = Math.max(0, Math.round(Number(value) || 0));
269
+ if (ms < 1000) return `${ms}ms`;
270
+ const seconds = ms / 1000;
271
+ if (seconds < 59.95) return `${scaledText(seconds)}s`;
272
+ const minutes = seconds / 60;
273
+ if (minutes < 59.95) return `${scaledText(minutes)}m`;
274
+ return `${scaledText(minutes / 60)}h`;
275
+ }
276
+
277
+ // ---- Markdown:host 已解析成 JSON 树,这里只做元素映射 --------------------
278
+ /** @param {any[]} runs @param {string} prefix @returns {any[]} */
279
+ function renderInlines(runs, prefix) {
280
+ /** @type {any[]} */
281
+ const out = [];
282
+ const list = Array.isArray(runs) ? runs : [];
283
+ for (let index = 0; index < list.length; index += 1) {
284
+ const run = list[index];
285
+ const key = `${prefix}i${index}`;
286
+ if (run?.type === "code") {
287
+ out.push(h("code", { key, className: "dsh-btw-inline-code" }, String(run.text ?? "")));
288
+ continue;
289
+ }
290
+ if (run?.type === "strong" || run?.type === "em" || run?.type === "del") {
291
+ const tag = run.type === "strong" ? "strong" : run.type === "em" ? "em" : "del";
292
+ out.push(h(tag, { key }, ...renderInlines(run.children, key)));
293
+ continue;
294
+ }
295
+ if (run?.type === "link") {
296
+ const href = String(run.href ?? "");
297
+ if (!/^(https?:\/\/|mailto:)/iu.test(href)) {
298
+ out.push(h(React.Fragment, { key }, ...renderInlines(run.children, key)));
299
+ } else {
300
+ out.push(
301
+ h(
302
+ "a",
303
+ {
304
+ key,
305
+ className: "dsh-btw-link",
306
+ href,
307
+ target: "_blank",
308
+ rel: "noreferrer noopener",
309
+ "data-btw-link": "true",
310
+ },
311
+ ...renderInlines(run.children, key),
312
+ ),
313
+ );
314
+ }
315
+ continue;
316
+ }
317
+ // 普通文本:段内换行保留成 <br>(模型答案里常靠单换行分行)。
318
+ const text = String(run?.text ?? "");
319
+ const pieces = text.split("\n");
320
+ for (let pieceIndex = 0; pieceIndex < pieces.length; pieceIndex += 1) {
321
+ if (pieceIndex > 0) out.push(h("br", { key: `${key}b${pieceIndex}` }));
322
+ if (pieces[pieceIndex] !== "")
323
+ out.push(h(React.Fragment, { key: `${key}t${pieceIndex}` }, pieces[pieceIndex]));
324
+ }
325
+ }
326
+ return out;
327
+ }
328
+
329
+ /**
330
+ * @param {any[]} blocks
331
+ * @param {boolean} streaming
332
+ * @param {string} [prefix]
333
+ * @returns {any[]}
334
+ */
335
+ function renderBlocks(blocks, streaming, prefix = "b") {
336
+ /** @type {any[]} */
337
+ const out = [];
338
+ const list = Array.isArray(blocks) ? blocks : [];
339
+ for (let index = 0; index < list.length; index += 1) {
340
+ const block = list[index];
341
+ const key = `${prefix}${index}`;
342
+ switch (block?.type) {
343
+ case "heading": {
344
+ const level = Math.min(6, Math.max(1, Number(block.level) || 2));
345
+ out.push(h(`h${level}`, { key }, ...renderInlines(block.inlines, `${key}i`)));
346
+ break;
347
+ }
348
+ case "paragraph":
349
+ out.push(h("p", { key }, ...renderInlines(block.inlines, `${key}i`)));
350
+ break;
351
+ case "code":
352
+ out.push(
353
+ h(
354
+ "div",
355
+ { key, className: "dsh-btw-codeblock", "data-btw-code": "true" },
356
+ block.lang
357
+ ? h("div", { className: "dsh-btw-codeblock-lang" }, String(block.lang))
358
+ : null,
359
+ h("pre", null, h("code", null, String(block.code ?? ""))),
360
+ ),
361
+ );
362
+ break;
363
+ case "list": {
364
+ const items = Array.isArray(block.items) ? block.items : [];
365
+ out.push(
366
+ h(
367
+ block.ordered ? "ol" : "ul",
368
+ { key, start: block.ordered ? Number(block.start) || 1 : undefined },
369
+ ...items.map((/** @type {any} */ item, /** @type {number} */ itemIndex) =>
370
+ h(
371
+ "li",
372
+ { key: `${key}-${itemIndex}` },
373
+ ...renderInlines(item?.inlines, `${key}-${itemIndex}i`),
374
+ ),
375
+ ),
376
+ ),
377
+ );
378
+ break;
379
+ }
380
+ case "quote":
381
+ out.push(h("blockquote", { key }, ...renderBlocks(block.blocks, streaming, `${key}q`)));
382
+ break;
383
+ case "table": {
384
+ const align = Array.isArray(block.align) ? block.align : [];
385
+ const header = Array.isArray(block.header) ? block.header : [];
386
+ const rows = Array.isArray(block.rows) ? block.rows : [];
387
+ out.push(
388
+ h(
389
+ "div",
390
+ { key, className: "dsh-btw-tablewrap" },
391
+ h(
392
+ "table",
393
+ null,
394
+ h(
395
+ "thead",
396
+ null,
397
+ h(
398
+ "tr",
399
+ { key: `${key}h` },
400
+ ...header.map((/** @type {any} */ cell, /** @type {number} */ cellIndex) =>
401
+ h(
402
+ "th",
403
+ { key: `${key}h${cellIndex}`, style: cellStyle(align[cellIndex]) },
404
+ ...renderInlines(cell, `${key}h${cellIndex}i`),
405
+ ),
406
+ ),
407
+ ),
408
+ ),
409
+ h(
410
+ "tbody",
411
+ null,
412
+ ...rows.map((/** @type {any} */ row, /** @type {number} */ rowIndex) =>
413
+ h(
414
+ "tr",
415
+ { key: `${key}r${rowIndex}` },
416
+ ...(Array.isArray(row) ? row : []).map((cell, cellIndex) =>
417
+ h(
418
+ "td",
419
+ {
420
+ key: `${key}r${rowIndex}c${cellIndex}`,
421
+ style: cellStyle(align[cellIndex]),
422
+ },
423
+ ...renderInlines(cell, `${key}r${rowIndex}c${cellIndex}i`),
424
+ ),
425
+ ),
426
+ ),
427
+ ),
428
+ ),
429
+ ),
430
+ ),
431
+ );
432
+ break;
433
+ }
434
+ case "hr":
435
+ out.push(h("hr", { key }));
436
+ break;
437
+ default: {
438
+ const text = String(block?.text ?? "");
439
+ if (text !== "") out.push(h("p", { key }, text));
440
+ }
441
+ }
442
+ }
443
+ if (streaming)
444
+ out.push(h("span", { key: "caret", className: "dsh-btw-caret", "aria-hidden": "true" }));
445
+ return out;
446
+ }
447
+
448
+ /** @param {any} align */
449
+ function cellStyle(align) {
450
+ return align === "center"
451
+ ? { textAlign: "center" }
452
+ : align === "right"
453
+ ? { textAlign: "right" }
454
+ : undefined;
455
+ }
456
+
457
+ /**
458
+ * 一条答案的 Markdown 容器;超长时折叠,点「展开全文」再放开。
459
+ * @param {any} props
460
+ */
461
+ function MarkdownBody(props) {
462
+ const { blocks, streaming, clamped } = props;
463
+ return h(
464
+ "div",
465
+ {
466
+ className: `dsh-btw-a${clamped ? " is-clamped" : ""}`,
467
+ "data-btw-answer": "true",
468
+ "data-btw-md": "true",
469
+ },
470
+ h("div", { className: "dsh-btw-md" }, ...renderBlocks(blocks, streaming === true)),
471
+ );
472
+ }
473
+
474
+ /** 一次 RPC 失败原因(诊断用,渲染进 data-btw-error)。 */
475
+ let lastRpcError = "";
476
+
165
477
  exports.inject = ["slots", "locale", "connection", "sessions"];
166
478
  /** @param {any} ctx */
167
479
  exports.apply = function apply(ctx) {
@@ -183,23 +495,23 @@ window.__ModuleLoader__.load({
183
495
  }, "btw: styles");
184
496
 
185
497
  /**
186
- * 按钮(composer 工具行)与浮层(`shell.overlay`)是两个独立组件实例,
498
+ * 按钮(composer 工具行)与抽屉(`shell.overlay`)是两个独立组件实例,
187
499
  * 共享状态必须提升到 apply 作用域。
188
500
  *
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。
501
+ * 为什么抽屉仍挂 `shell.overlay`:`conversation.input.overlay` 在 composer 内部,
502
+ * 会被裁剪;`shell.overlay` 是 frame-wide 浮层,定位从根上可靠,且不改变布局
503
+ * (不会像右侧边栏那样把主对话挤窄)。
194
504
  */
195
505
  const store = (() => {
196
- /** @type {{ open: boolean, sessionId: string }} */
197
- let state = { open: false, sessionId: "" };
506
+ /** @type {{ open: boolean, collapsed: boolean, sessionId: string }} */
507
+ let state = { open: false, collapsed: false, sessionId: "" };
198
508
  /** @type {Set<() => void>} */
199
509
  const listeners = new Set();
200
510
  return {
201
511
  get: () => state,
202
- patch(/** @type {Partial<{ open: boolean, sessionId: string }>} */ next) {
512
+ patch(
513
+ /** @type {Partial<{ open: boolean, collapsed: boolean, sessionId: string }>} */ next,
514
+ ) {
203
515
  state = { ...state, ...next };
204
516
  for (const listener of listeners) listener();
205
517
  },
@@ -210,6 +522,12 @@ window.__ModuleLoader__.load({
210
522
  };
211
523
  })();
212
524
 
525
+ /**
526
+ * 原生右侧栏是否可用:注册成功后才走 tab 形态,否则回退到浮层抽屉。
527
+ * 这样同一份 client 能同时兼容「右侧栏服务在」与「只有 shell.overlay」的宿主。
528
+ */
529
+ let tabReady = false;
530
+
213
531
  /** 订阅 store 的极简 hook。 */
214
532
  const useStore = () => {
215
533
  const [, force] = React.useState(0);
@@ -229,9 +547,6 @@ window.__ModuleLoader__.load({
229
547
  return "zh";
230
548
  };
231
549
 
232
- /** 最近一次 RPC 失败原因(诊断用,渲染进 data-btw-error)。 */
233
- let lastRpcError = "";
234
-
235
550
  /** Typert Remote 调用;解 { ok, value } 信封,失败返回 undefined。 */
236
551
  const callRemote = (/** @type {string} */ method, /** @type {any} */ request) => {
237
552
  const connection = serviceOf(ctx, "connection");
@@ -354,8 +669,9 @@ window.__ModuleLoader__.load({
354
669
  /**
355
670
  * composer 工具行里的「旁问」按钮。
356
671
  *
357
- * 它同时负责把当前 sessionId 写进 store —— 浮层注册在 root scope 的
358
- * `shell.overlay` 上,拿不到 session props,只能由按钮转交。
672
+ * 首选打开 DSH 原生右侧栏的「旁问」tab(不遮挡主对话);宿主没有右侧栏
673
+ * 服务时回退到 `shell.overlay` 浮层抽屉。回退形态拿不到 session props,
674
+ * 所以按钮同时负责把 sessionId 写进 store。
359
675
  */
360
676
  function BtwTrigger(/** @type {any} */ props) {
361
677
  const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
@@ -363,6 +679,37 @@ window.__ModuleLoader__.load({
363
679
  React.useEffect(() => {
364
680
  if (shared.sessionId !== sessionId) store.patch({ sessionId });
365
681
  }, [sessionId, shared.sessionId]);
682
+ /** 首选形态:在 DSH 原生右侧栏打开「旁问」tab(不遮挡主对话)。 */
683
+ const openSidebarTab = () => {
684
+ if (!tabReady) return false;
685
+ const sidebarRight = serviceOf(ctx, "sidebarRight");
686
+ if (!sidebarRight || typeof sidebarRight.openTab !== "function") return false;
687
+ try {
688
+ // 侧栏已被收起时,openTab 只会 focus 已存在的 tab、不会展开栏,
689
+ // 所以先显式展开(track=true、非 fullscreen),再打开/聚焦 tab。
690
+ const layout = serviceOf(ctx, "layout");
691
+ if (layout && typeof layout.openRightbar === "function") {
692
+ try {
693
+ layout.openRightbar(true, false);
694
+ } catch {
695
+ /* 展开失败不阻塞打开 */
696
+ }
697
+ }
698
+ sidebarRight.openTab("btw");
699
+ // 若之前用过回退抽屉,打开 tab 时把它收掉,避免两套面板同时在场。
700
+ store.patch({ open: false, collapsed: false });
701
+ return true;
702
+ } catch {
703
+ return false;
704
+ }
705
+ };
706
+ const toggle = () => {
707
+ if (openSidebarTab()) return;
708
+ const current = store.get();
709
+ if (!current.open) store.patch({ open: true, collapsed: false });
710
+ else if (current.collapsed) store.patch({ collapsed: false });
711
+ else store.patch({ open: false });
712
+ };
366
713
  return h(
367
714
  "button",
368
715
  {
@@ -370,29 +717,28 @@ window.__ModuleLoader__.load({
370
717
  className: "dsh-btw-btn",
371
718
  "data-btw-toggle": "true",
372
719
  title: t("button"),
373
- onClick: () => store.patch({ open: !store.get().open }),
720
+ onClick: toggle,
374
721
  },
375
722
  t("button"),
376
723
  );
377
724
  }
378
725
 
379
- /** 浮层:只读列表 + 浮层内发问。 */
380
- function BtwPanel(/** @type {any} */ props) {
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
- });
726
+ /**
727
+ * 面板主体:原生右侧栏 tab 与回退抽屉共用。
728
+ * @param {any} props `{ sessionId, mode: 'tab'|'drawer', onCollapse, onClose }`
729
+ */
730
+ function BtwBody(/** @type {any} */ props) {
731
+ const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
732
+ const mode = props?.mode === "tab" ? "tab" : "drawer";
733
+ const onCollapse = typeof props?.onCollapse === "function" ? props.onCollapse : () => {};
734
+ const onClose = typeof props?.onClose === "function" ? props.onClose : onCollapse;
735
+ const visible = props?.visible !== false;
392
736
  const [threads, setThreads] = React.useState(/** @type {any[] | null} */ (null));
737
+ const [liveRuns, setLiveRuns] = React.useState(/** @type {any[]} */ ([]));
393
738
  const [failed, setFailed] = React.useState(false);
394
739
  const [activeId, setActiveId] = React.useState("");
395
740
  const [question, setQuestion] = React.useState("");
741
+ const [followQuestion, setFollowQuestion] = React.useState("");
396
742
  const [busy, setBusy] = React.useState(false);
397
743
  const [notice, setNotice] = React.useState("");
398
744
  const [badge, setBadge] = React.useState("");
@@ -400,10 +746,10 @@ window.__ModuleLoader__.load({
400
746
  const [expandedAnswers, setExpandedAnswers] = React.useState(
401
747
  /** @type {Record<string, boolean>} */ ({}),
402
748
  );
403
- // 新建旁问的输入框默认收起:实测同时出现「线程内追问框 + 底部新建框」时,
404
- // 用户分不清哪个是哪个(两个输入框视觉几乎一样)。
405
- const [showNew, setShowNew] = React.useState(false);
406
749
  const aliveRef = React.useRef(true);
750
+ const liveRef = React.useRef(/** @type {any[]} */ ([]));
751
+ const scrollRef = React.useRef(/** @type {any} */ (null));
752
+ const pinnedRef = React.useRef(true);
407
753
 
408
754
  React.useEffect(
409
755
  () => () => {
@@ -412,13 +758,24 @@ window.__ModuleLoader__.load({
412
758
  [],
413
759
  );
414
760
 
761
+ // 切会话:清空上一会话的列表与流式现场。
762
+ React.useEffect(() => {
763
+ setThreads(null);
764
+ setLiveRuns([]);
765
+ liveRef.current = [];
766
+ setActiveId("");
767
+ setFollowQuestion("");
768
+ setNotice("");
769
+ pinnedRef.current = true;
770
+ }, [sessionId]);
771
+
415
772
  /**
416
- * 拉线程列表。返回数组(成功)或 null(失败)——
417
- * 调用方需要区分「线程数增加」(新问题)与「某线程轮数增加」(追问)。
773
+ * 拉线程列表。quiet = 后台轮询:失败不把界面打红。
774
+ * @param {boolean} [quiet]
418
775
  * @returns {Promise<any[] | null>}
419
776
  */
420
- const load = React.useCallback(
421
- () =>
777
+ const loadThreads = React.useCallback(
778
+ (quiet = false) =>
422
779
  callRemote("threads", { sessionId, limit: LIMITS_CLIENT_THREADS }).then((value) => {
423
780
  if (!aliveRef.current) return null;
424
781
  if (Array.isArray(/** @type {any} */ (value))) {
@@ -426,15 +783,16 @@ window.__ModuleLoader__.load({
426
783
  setFailed(false);
427
784
  return /** @type {any[]} */ (value);
428
785
  }
429
- setThreads([]);
430
- setFailed(true);
786
+ if (!quiet) {
787
+ setThreads([]);
788
+ setFailed(true);
789
+ }
431
790
  return null;
432
791
  }),
433
792
  [sessionId],
434
793
  );
435
794
 
436
795
  React.useEffect(() => {
437
- if (!open) return undefined;
438
796
  const scopeLabel =
439
797
  scope === ""
440
798
  ? ""
@@ -449,36 +807,100 @@ window.__ModuleLoader__.load({
449
807
  if (!aliveRef.current) return;
450
808
  if (value && typeof value.badge === "string") setBadge(value.badge);
451
809
  });
452
- }, [open, sessionId, scope]);
810
+ }, [sessionId, scope]);
811
+
812
+ // 面板挂载(tab 打开 / 抽屉展开)时先读一次历史。
813
+ React.useEffect(() => {
814
+ void loadThreads();
815
+ }, [loadThreads]);
816
+
817
+ // 流式与后台刷新:面板打开期间常驻。有 run 时 350ms 一次、空闲 1s 一次;
818
+ // 空闲时每 4 次才刷一次线程列表,避免无谓 RPC。
819
+ React.useEffect(() => {
820
+ if (sessionId === "" || !visible) return undefined;
821
+ let cancelled = false;
822
+ /** @type {any} */
823
+ let timer;
824
+ let ticks = 0;
825
+ const tick = async () => {
826
+ if (cancelled) return;
827
+ /** @type {any[]} */
828
+ let runs = [];
829
+ try {
830
+ const value = await callRemote("live", { sessionId });
831
+ if (Array.isArray(value?.runs)) runs = value.runs;
832
+ } catch {
833
+ runs = [];
834
+ }
835
+ if (cancelled) return;
836
+ const hadLive = liveRef.current.length > 0;
837
+ const hasLive = runs.length > 0;
838
+ liveRef.current = runs;
839
+ // 空闲轮询(无 run)不重复 set 空数组,省掉每秒一次无意义的重渲染。
840
+ if (hasLive || hadLive) setLiveRuns(runs);
841
+ // 只在 live 结束后刷一次历史(run 进行中 threads 不会变,少传大 payload)。
842
+ if (hadLive && !hasLive) void loadThreads(true);
843
+ else if (!hasLive && ticks % LIVE_IDLE_REFRESH_EVERY === 0) void loadThreads(true);
844
+ ticks += 1;
845
+ if (!cancelled)
846
+ timer = setTimeout(tick, runs.length > 0 ? LIVE_ACTIVE_MS : LIVE_IDLE_MS);
847
+ };
848
+ timer = setTimeout(tick, 200);
849
+ return () => {
850
+ cancelled = true;
851
+ clearTimeout(timer);
852
+ };
853
+ }, [sessionId, visible, loadThreads]);
453
854
 
855
+ // Esc 只用于回退抽屉;原生 tab 里 Esc 属于宿主,不抢。
454
856
  React.useEffect(() => {
455
- if (!open) return undefined;
456
- void load();
857
+ if (mode !== "drawer") return undefined;
457
858
  const onKey = (/** @type {any} */ event) => {
458
- if (event?.key === "Escape") setOpen(false);
859
+ if (event?.key === "Escape") onClose();
459
860
  };
460
861
  document.addEventListener("keydown", onKey);
461
862
  return () => document.removeEventListener("keydown", onKey);
462
- }, [open, load]);
863
+ }, [mode, onClose]);
864
+
865
+ // 自动滚到底:只有用户本来就在底部时才跟随(向上翻历史时不抢滚动条)。
866
+ const onScroll = () => {
867
+ const el = scrollRef.current;
868
+ if (!el) return;
869
+ pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
870
+ };
871
+ React.useEffect(() => {
872
+ const el = scrollRef.current;
873
+ if (!el || !pinnedRef.current) return;
874
+ el.scrollTop = el.scrollHeight;
875
+ }, [threads, liveRuns]);
876
+
877
+ const metaTextOf = (/** @type {any} */ cost, /** @type {number} */ ms) => {
878
+ if (cost && typeof cost === "object") {
879
+ return fmt(t("cost"), {
880
+ newTokens: formatTokens(cost.inputTokens),
881
+ cachedTokens: formatTokens(cost.cacheReadTokens),
882
+ ms: formatDuration(ms),
883
+ });
884
+ }
885
+ return ms > 0 ? formatDuration(ms) : "";
886
+ };
463
887
 
464
888
  /**
465
- * 发问:新线程走 `/btw <q>`;追问走 `/btw --thread <id> <q>`。
466
- *
467
- * 2026-11-17 修复(实测用户反馈「点了没反应、按钮永久卡死」):
468
- * 1. 旧实现轮询 20×1.5s=30s,而真实 /btw 耗时 32–40s,永远等不到 → 改为按
469
- * 实际耗时给足窗口(REFRESH_MAX_MS),并保留「线程数增加即提前结束」。
470
- * 2. poll 的 `.then()` 没有 `.catch()`,一次 RPC 失败就断链,
471
- * `setBusy(false)` 永不执行 → 改用 try/finally 兜底,任何路径都恢复按钮。
889
+ * 发问 / 追问:新线程走 `/btw <q>`;追问走 `/btw --thread <id> <q>`,
890
+ * 并在提交前把参数登记到 host(这样 composer 里只出现裸 `/btw`)。
891
+ * @param {string} threadId
472
892
  */
473
- const submit = async (/** @type {string} */ threadId) => {
474
- const text = question.trim();
893
+ const submit = async (threadId) => {
894
+ const text = (threadId === "" ? question : followQuestion).trim();
475
895
  if (text === "" || busy) return;
476
896
  setBusy(true);
477
897
  setNotice(t("sending"));
478
898
  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,
899
+ // 用「最近一条记录的时间」判断完成,而不是线程数:
900
+ // 线程数受 20 条上限约束,满额时新问题不会让数量增加,旧逻辑会白等到 120s。
901
+ const beforeAt = beforeThreads.reduce(
902
+ (latest, /** @type {any} */ entry) => Math.max(latest, Number(entry?.at ?? 0)),
903
+ 0,
482
904
  );
483
905
  const flags = [
484
906
  threadId === "" ? "" : `--thread ${threadId}`,
@@ -488,9 +910,6 @@ window.__ModuleLoader__.load({
488
910
  .join(" ");
489
911
  let line = flags === "" ? `/btw ${text}` : `/btw ${flags} ${text}`;
490
912
  if (threadId !== "") {
491
- // 追问:先把参数交给 host 暂存,再提交**裸 `/btw`** ——
492
- // 否则 `--thread t_xxx <问题>` 会整段出现在用户输入框里(实测被抱怨
493
- // 「为什么给我一堆乱码」)。host 侧处理裸命令时先查这个队列。
494
913
  const queued = await callRemote("queueFollowUp", {
495
914
  sessionId,
496
915
  threadId,
@@ -505,9 +924,13 @@ window.__ModuleLoader__.load({
505
924
  setNotice(t("sendFailed"));
506
925
  return;
507
926
  }
508
- setQuestion("");
927
+ if (threadId === "") setQuestion("");
928
+ else {
929
+ setFollowQuestion("");
930
+ setActiveId("");
931
+ }
509
932
  setNotice(t("sent"));
510
- // 轮询到「线程数增加」为止,最长 REFRESH_MAX_MS;单次失败不中断。
933
+ // 轮询到「线程数增加 / 轮数增加」为止,最长 REFRESH_MAX_MS;单次失败不中断。
511
934
  const deadline = Date.now() + REFRESH_MAX_MS;
512
935
  let refreshed = false;
513
936
  while (Date.now() < deadline && aliveRef.current) {
@@ -516,39 +939,28 @@ window.__ModuleLoader__.load({
516
939
  /** @type {any[] | null} */
517
940
  let next = null;
518
941
  try {
519
- next = await load();
942
+ next = await loadThreads(true);
520
943
  } catch {
521
- next = null; // 单次失败继续轮询,不静默卡死
944
+ next = null;
522
945
  }
523
946
  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
- }
947
+ if (next.some((/** @type {any} */ entry) => Number(entry?.at ?? 0) > beforeAt)) {
948
+ refreshed = true;
949
+ break;
538
950
  }
539
951
  }
540
952
  setNotice(refreshed ? "" : t("sentPending"));
541
953
  } finally {
542
- // 无论如何都要放开按钮:卡死的按钮是实测最劝退的问题。
543
954
  if (aliveRef.current) setBusy(false);
544
955
  }
545
956
  };
546
957
 
547
958
  /**
548
- * 一键转正:取 host 生成的四节草稿,**只插进 composer,不发送**。
959
+ * 一键转正:取 host 生成的 Markdown 草稿,**只插进 composer,不发送**。
549
960
  * 输入框已有内容时拒绝,避免覆盖用户正在写的东西。
961
+ * @param {any} thread
550
962
  */
551
- const promote = async (/** @type {any} */ thread) => {
963
+ const promote = async (thread) => {
552
964
  if (busy) return;
553
965
  setBusy(true);
554
966
  setNotice("");
@@ -586,320 +998,301 @@ window.__ModuleLoader__.load({
586
998
  setNotice(t("promoted"));
587
999
  };
588
1000
 
589
- // 浮层不画按钮:按钮由 BtwTrigger 注册在 composer 工具行里。
590
- if (!open) return null;
1001
+ // 折叠按钮:展开/收起单条长答案。
1002
+ const toggleAnswer = (/** @type {string} */ key) =>
1003
+ setExpandedAnswers((/** @type {any} */ previous) => ({
1004
+ ...previous,
1005
+ [key]: !previous[key],
1006
+ }));
591
1007
 
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
- };
641
-
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
- };
677
-
678
- const renderThread = (/** @type {any} */ thread, /** @type {number} */ index) => {
679
- const expanded = activeId === thread.threadId;
1008
+ /** @param {any} thread @param {number} index */
1009
+ const renderThread = (thread, index) => {
1010
+ const threadId = String(thread?.threadId ?? "");
1011
+ const items = Array.isArray(thread?.items) ? thread.items : [];
1012
+ const expanded = activeId === threadId;
680
1013
  return h(
681
1014
  "div",
682
1015
  {
683
- className: "dsh-btw-item",
684
- key: thread.threadId ?? String(index),
1016
+ className: "dsh-btw-thread",
1017
+ key: threadId === "" ? String(index) : threadId,
685
1018
  "data-btw-thread": "true",
686
- "data-btw-thread-id": String(thread.threadId ?? ""),
1019
+ "data-btw-thread-id": threadId,
687
1020
  },
688
- h(
689
- "div",
690
- { className: "dsh-btw-q" },
691
- `/btw ${String(thread.question ?? "")}`,
692
- Number(thread.turns) > 1
693
- ? h(
694
- "span",
695
- { className: "dsh-btw-meta" },
696
- ` · ${String(thread.turns)} ${t("turns")}`,
697
- )
698
- : null,
699
- ),
700
- (() => {
701
- // 长答案默认折叠 6 行:实测一条 3000+ 字答案会把浮层撑满,
702
- // 用户只能看到答案中部、找不到成本与按钮。
703
- // 优先用 host 清理过的纯文本(保留代码块);没有就回退原文。
704
- const answerText = String(thread.answerPlain ?? thread.answer ?? "");
705
- const key = String(thread.threadId ?? "");
706
- const isOpen = expandedAnswers[key] === true;
707
- const needsClamp = answerText.length > 400;
1021
+ ...items.map((/** @type {any} */ item, /** @type {number} */ itemIndex) => {
1022
+ const itemKey = `${threadId}:${String(item?.id ?? itemIndex)}`;
1023
+ const isLast = itemIndex === items.length - 1;
1024
+ const clamped = expandedAnswers[itemKey] !== true && Number(item?.chars ?? 0) > 400;
708
1025
  return h(
709
- React.Fragment,
710
- null,
711
- h(
712
- "div",
713
- {
714
- className: `dsh-btw-a${needsClamp && !isOpen ? " is-clamped" : ""}`,
715
- "data-btw-answer": "true",
716
- },
717
- renderAnswerBody(thread, answerText),
718
- ),
719
- needsClamp
1026
+ "div",
1027
+ { className: "dsh-btw-turn", key: itemKey, "data-btw-turn": "true" },
1028
+ String(item?.question ?? "") === ""
1029
+ ? null
1030
+ : h(
1031
+ "div",
1032
+ { className: "dsh-btw-q", "data-btw-question": "true" },
1033
+ itemIndex === 0
1034
+ ? null
1035
+ : h("span", { className: "dsh-btw-q-label" }, t("followUpLabel")),
1036
+ String(item.question),
1037
+ ),
1038
+ h(MarkdownBody, { blocks: item?.blocks, streaming: false, clamped }),
1039
+ clamped
720
1040
  ? h(
721
1041
  "button",
722
1042
  {
723
1043
  type: "button",
724
1044
  className: "dsh-btw-btn",
725
1045
  "data-btw-expand": "true",
726
- onClick: () =>
727
- setExpandedAnswers((/** @type {any} */ prev) => ({
728
- ...prev,
729
- [key]: !isOpen,
730
- })),
1046
+ onClick: () => toggleAnswer(itemKey),
731
1047
  },
732
- isOpen ? t("collapseAnswer") : t("expandAnswer"),
1048
+ t("expandAnswer"),
1049
+ )
1050
+ : null,
1051
+ (() => {
1052
+ const meta = metaTextOf(item?.cost, Number(item?.ms ?? 0));
1053
+ return meta === ""
1054
+ ? null
1055
+ : h("div", { className: "dsh-btw-meta", "data-btw-meta": "true" }, meta);
1056
+ })(),
1057
+ isLast
1058
+ ? h(
1059
+ "div",
1060
+ { className: "dsh-btw-row" },
1061
+ h(
1062
+ "button",
1063
+ {
1064
+ type: "button",
1065
+ className: "dsh-btw-btn",
1066
+ "data-btw-followup": "true",
1067
+ onClick: () => {
1068
+ setActiveId(expanded ? "" : threadId);
1069
+ setFollowQuestion("");
1070
+ },
1071
+ },
1072
+ expanded ? t("collapseAnswer") : t("followUp"),
1073
+ ),
1074
+ h(
1075
+ "button",
1076
+ {
1077
+ type: "button",
1078
+ className: "dsh-btw-btn",
1079
+ "data-btw-promote": "true",
1080
+ disabled: busy,
1081
+ onClick: () => void promote(thread),
1082
+ },
1083
+ t("promote"),
1084
+ ),
1085
+ )
1086
+ : null,
1087
+ expanded && isLast
1088
+ ? h(
1089
+ "div",
1090
+ { className: "dsh-btw-row", "data-btw-thread-input": "true" },
1091
+ h("textarea", {
1092
+ className: "dsh-btw-input",
1093
+ "data-btw-input": "true",
1094
+ placeholder: t("followPlaceholder"),
1095
+ value: followQuestion,
1096
+ rows: 2,
1097
+ onChange: (/** @type {any} */ event) =>
1098
+ setFollowQuestion(String(event?.target?.value ?? "")),
1099
+ onKeyDown: (/** @type {any} */ event) => {
1100
+ if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
1101
+ event.preventDefault();
1102
+ void submit(threadId);
1103
+ }
1104
+ },
1105
+ }),
1106
+ h(
1107
+ "button",
1108
+ {
1109
+ type: "button",
1110
+ className: "dsh-btw-btn",
1111
+ "data-btw-send": "true",
1112
+ disabled: busy || followQuestion.trim() === "",
1113
+ onClick: () => void submit(threadId),
1114
+ },
1115
+ t("send"),
1116
+ ),
733
1117
  )
734
1118
  : null,
735
1119
  );
1120
+ }),
1121
+ );
1122
+ };
1123
+
1124
+ /** 流式卡片:固定追加在列表最底部(最新一条),结束后由真实线程替换。 */
1125
+ const renderLive = (/** @type {any} */ run) => {
1126
+ const questionText = String(run?.question ?? "");
1127
+ const isFollowUp = (Array.isArray(threads) ? threads : []).some(
1128
+ (/** @type {any} */ thread) => thread?.threadId === run?.threadId,
1129
+ );
1130
+ return h(
1131
+ "div",
1132
+ {
1133
+ className: "dsh-btw-thread dsh-btw-live",
1134
+ key: `live:${String(run?.threadId ?? "")}`,
1135
+ "data-btw-live": "true",
1136
+ "data-btw-thread-id": String(run?.threadId ?? ""),
1137
+ },
1138
+ questionText === ""
1139
+ ? null
1140
+ : h(
1141
+ "div",
1142
+ { className: "dsh-btw-q", "data-btw-question": "true" },
1143
+ isFollowUp
1144
+ ? h("span", { className: "dsh-btw-q-label" }, t("followUpLabel"))
1145
+ : null,
1146
+ questionText,
1147
+ ),
1148
+ (() => {
1149
+ const blocks = Array.isArray(run?.blocks) ? run.blocks : [];
1150
+ return blocks.length === 0
1151
+ ? h("div", { className: "dsh-btw-dim", "data-btw-stream-text": "true" }, "…")
1152
+ : h(
1153
+ "div",
1154
+ {
1155
+ className: "dsh-btw-a",
1156
+ "data-btw-stream-text": "true",
1157
+ "data-btw-md": "true",
1158
+ },
1159
+ h("div", { className: "dsh-btw-md" }, ...renderBlocks(blocks, true)),
1160
+ );
736
1161
  })(),
737
1162
  h(
738
1163
  "div",
739
- { className: "dsh-btw-meta", "data-btw-meta": "true" },
740
- fmt(t("cost"), {
741
- newTokens: String(thread.cost?.inputTokens ?? 0),
742
- cachedTokens: String(thread.cost?.cacheReadTokens ?? 0),
743
- ms: String(thread.ms ?? 0),
744
- }),
1164
+ { className: "dsh-btw-meta", "data-btw-elapsed": "true" },
1165
+ `${t("streaming")} · ${formatDuration(run?.ms)}`,
745
1166
  ),
746
- h(
747
- "div",
748
- { className: "dsh-btw-row" },
749
- h(
750
- "button",
751
- {
752
- type: "button",
753
- className: "dsh-btw-btn",
754
- "data-btw-followup": "true",
755
- onClick: () => setActiveId(expanded ? "" : String(thread.threadId ?? "")),
756
- },
757
- expanded ? t("collapse") : t("followUp"),
758
- ),
759
- h(
760
- "button",
761
- {
762
- type: "button",
763
- className: "dsh-btw-btn",
764
- "data-btw-promote": "true",
765
- disabled: busy,
766
- onClick: () => void promote(thread),
767
- },
768
- t("promote"),
769
- ),
770
- ),
771
- expanded
772
- ? h(
773
- "div",
774
- { className: "dsh-btw-row", "data-btw-thread-input": "true" },
775
- h("textarea", {
776
- className: "dsh-btw-input",
777
- "data-btw-input": "true",
778
- placeholder: t("followPlaceholder"),
779
- value: question,
780
- rows: 2,
781
- onChange: (/** @type {any} */ event) =>
782
- setQuestion(String(event?.target?.value ?? "")),
783
- onKeyDown: (/** @type {any} */ event) => {
784
- if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
785
- event.preventDefault();
786
- void submit(String(thread.threadId ?? ""));
787
- }
788
- },
789
- }),
790
- h(
791
- "button",
792
- {
793
- type: "button",
794
- className: "dsh-btw-btn",
795
- "data-btw-send": "true",
796
- disabled: busy || question.trim() === "",
797
- onClick: () => void submit(String(thread.threadId ?? "")),
798
- },
799
- t("send"),
800
- ),
801
- )
802
- : null,
803
1167
  );
804
1168
  };
805
1169
 
806
- const body =
807
- threads === null
1170
+ const known = threads ?? [];
1171
+ const list =
1172
+ threads === null && liveRuns.length === 0
808
1173
  ? h("div", { className: "dsh-btw-dim" }, "…")
809
- : threads.length === 0
1174
+ : known.length === 0 && liveRuns.length === 0
810
1175
  ? h("div", { className: "dsh-btw-dim", "data-btw-empty": "true" }, t("empty"))
811
- : threads.map(renderThread);
1176
+ : [
1177
+ ...known.map(renderThread),
1178
+ ...liveRuns.map((/** @type {any} */ run) => renderLive(run)),
1179
+ ];
1180
+
1181
+ // 有 live 卡片时不显示状态条:卡片里已经有「正在生成回答 · 12s」,不需要重复。
1182
+ const statusBusy = busy;
1183
+ const statusText = busy ? `${t("sending")}(${t("waitHint")})` : notice;
1184
+ const statusVisible = liveRuns.length === 0 && (statusBusy || notice !== "");
812
1185
 
813
1186
  return h(
814
- "span",
815
- { "data-btw-root": "true" },
1187
+ "div",
1188
+ {
1189
+ className: `dsh-btw-panel${mode === "tab" ? " is-tab" : ""}`,
1190
+ "data-btw-panel": "true",
1191
+ ...(mode === "tab"
1192
+ ? { "data-btw-tab": "true" }
1193
+ : { "data-btw-overlay": "true", "data-btw-drawer": "true" }),
1194
+ role: mode === "tab" ? "region" : "dialog",
1195
+ "aria-label": t("title"),
1196
+ },
816
1197
  h(
817
1198
  "div",
818
- { className: "dsh-btw-panel", "data-btw-overlay": "true", role: "dialog" },
1199
+ { className: "dsh-btw-head" },
1200
+ h("span", { className: "dsh-btw-head-title" }, t("subtitle")),
1201
+ threads !== null && threads.length > 0
1202
+ ? h(
1203
+ "span",
1204
+ { className: "dsh-btw-dim", "data-btw-count": "true" },
1205
+ String(threads.length),
1206
+ )
1207
+ : null,
1208
+ mode === "tab"
1209
+ ? null
1210
+ : h(
1211
+ "button",
1212
+ {
1213
+ type: "button",
1214
+ className: "dsh-btw-btn",
1215
+ "data-btw-collapse": "true",
1216
+ title: t("collapse"),
1217
+ onClick: () => onCollapse(),
1218
+ },
1219
+ t("collapseShort"),
1220
+ ),
819
1221
  h(
820
- "div",
821
- { className: "dsh-btw-head" },
822
- h("span", null, t("title")),
823
- h(
824
- "button",
1222
+ "button",
1223
+ {
1224
+ type: "button",
1225
+ className: "dsh-btw-btn",
1226
+ "data-btw-close": "true",
1227
+ onClick: () => onClose(),
1228
+ },
1229
+ t("close"),
1230
+ ),
1231
+ ),
1232
+ statusVisible
1233
+ ? h(
1234
+ "div",
825
1235
  {
826
- type: "button",
827
- className: "dsh-btw-btn",
828
- "data-btw-new": "true",
829
- onClick: () => setShowNew((/** @type {boolean} */ v) => !v),
1236
+ className: `dsh-btw-status${statusBusy ? " is-busy" : ""}`,
1237
+ "data-btw-notice": "true",
830
1238
  },
831
- showNew ? t("collapse") : t("newQuestion"),
1239
+ statusBusy ? h("span", { className: "dsh-btw-spinner" }, "⟳") : null,
1240
+ h("span", null, statusText),
1241
+ )
1242
+ : null,
1243
+ failed
1244
+ ? h(
1245
+ "div",
1246
+ { className: "dsh-btw-err", "data-btw-error": "history_unavailable" },
1247
+ `${t("failed")} — ${lastRpcError}`,
1248
+ )
1249
+ : h(
1250
+ "div",
1251
+ {
1252
+ className: "dsh-btw-scroll",
1253
+ "data-btw-list": "true",
1254
+ ref: scrollRef,
1255
+ onScroll,
1256
+ },
1257
+ ...(Array.isArray(list) ? list : [list]),
832
1258
  ),
1259
+ h(
1260
+ "div",
1261
+ { className: "dsh-btw-composer" },
1262
+ h("span", { className: "dsh-btw-composer-label" }, t("newQuestionLabel")),
1263
+ h("textarea", {
1264
+ className: "dsh-btw-input",
1265
+ "data-btw-input": "true",
1266
+ placeholder: t("placeholder"),
1267
+ value: question,
1268
+ rows: 2,
1269
+ onChange: (/** @type {any} */ event) =>
1270
+ setQuestion(String(event?.target?.value ?? "")),
1271
+ onKeyDown: (/** @type {any} */ event) => {
1272
+ if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
1273
+ event.preventDefault();
1274
+ void submit("");
1275
+ }
1276
+ },
1277
+ }),
1278
+ h(
1279
+ "div",
1280
+ { className: "dsh-btw-row" },
833
1281
  h(
834
1282
  "button",
835
1283
  {
836
1284
  type: "button",
837
- className: "dsh-btw-btn",
838
- "data-btw-close": "true",
839
- onClick: () => setOpen(false),
1285
+ className: "dsh-btw-btn is-primary",
1286
+ "data-btw-send": "true",
1287
+ disabled: busy || question.trim() === "",
1288
+ onClick: () => void submit(""),
840
1289
  },
841
- t("close"),
1290
+ t("send"),
842
1291
  ),
843
- ),
844
- // 提示条固定在**头部正下方**:旧实现放在浮层最底部,列表一长就被推到
845
- // 滚动区外(实测浮层底 616px、提示在 918px),用户提交后完全看不到反馈。
846
- notice === "" && !busy
847
- ? null
848
- : h(
849
- "div",
850
- {
851
- className: `dsh-btw-status${busy ? " is-busy" : ""}`,
852
- "data-btw-notice": "true",
853
- },
854
- busy ? h("span", { className: "dsh-btw-spinner" }, "⟳") : null,
855
- h("span", null, busy ? t("sending") : notice),
856
- ),
857
- failed
858
- ? h(
859
- "div",
860
- { className: "dsh-btw-err", "data-btw-error": "history_unavailable" },
861
- `${t("failed")} — ${lastRpcError}`,
862
- )
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,
896
- h(
897
- "div",
898
- { className: "dsh-btw-row" },
899
1292
  h(
900
1293
  "select",
901
1294
  {
902
- className: "dsh-btw-input",
1295
+ className: "dsh-btw-select",
903
1296
  "data-btw-scope": "true",
904
1297
  value: scope,
905
1298
  onChange: (/** @type {any} */ event) =>
@@ -919,6 +1312,76 @@ window.__ModuleLoader__.load({
919
1312
  );
920
1313
  }
921
1314
 
1315
+ /** 回退形态:`shell.overlay` 里的右侧抽屉(宿主没有右侧栏服务时)。 */
1316
+ function BtwDrawer(/** @type {any} */ props) {
1317
+ void props;
1318
+ const shared = useStore();
1319
+ if (!shared.open) return null;
1320
+ if (shared.collapsed) {
1321
+ return h(
1322
+ "button",
1323
+ {
1324
+ type: "button",
1325
+ className: "dsh-btw-rail",
1326
+ "data-btw-rail": "true",
1327
+ title: t("expand"),
1328
+ "aria-label": t("expand"),
1329
+ onClick: () => store.patch({ collapsed: false }),
1330
+ },
1331
+ h("span", null, t("button")),
1332
+ );
1333
+ }
1334
+ return h(BtwBody, {
1335
+ sessionId: shared.sessionId,
1336
+ mode: "drawer",
1337
+ onCollapse: () => store.patch({ collapsed: true }),
1338
+ onClose: () => store.patch({ open: false }),
1339
+ });
1340
+ }
1341
+
1342
+ /**
1343
+ * 首选形态:DSH 原生右侧栏里的「旁问」tab。
1344
+ * 收起 = 关闭 tab(再点输入框旁的「旁问」按钮打开)。
1345
+ */
1346
+ function BtwTab(/** @type {any} */ props) {
1347
+ const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
1348
+ const useTabInfo =
1349
+ typeof props?.useTabInfo === "function" ? props.useTabInfo : () => undefined;
1350
+ const info = useTabInfo();
1351
+ const closeTab = () => {
1352
+ try {
1353
+ const actions = info?.tab?.actions;
1354
+ if (typeof actions?.close === "function") {
1355
+ actions.close();
1356
+ return;
1357
+ }
1358
+ } catch {
1359
+ /* 退到 closeIn */
1360
+ }
1361
+ try {
1362
+ const sidebarRight = serviceOf(ctx, "sidebarRight");
1363
+ const tabId = info?.tab?.id;
1364
+ if (
1365
+ sidebarRight !== undefined &&
1366
+ typeof sidebarRight.closeIn === "function" &&
1367
+ tabId !== undefined
1368
+ ) {
1369
+ sidebarRight.closeIn(sessionId, tabId);
1370
+ }
1371
+ } catch {
1372
+ /* 关不上也保持可见 */
1373
+ }
1374
+ };
1375
+ // 收起整栏交给宿主右上角的收起按钮/快捷键;这里只负责关闭 tab。
1376
+ return h(BtwBody, {
1377
+ sessionId,
1378
+ mode: "tab",
1379
+ onCollapse: closeTab,
1380
+ onClose: closeTab,
1381
+ visible: info?.tab?.visible !== false,
1382
+ });
1383
+ }
1384
+
922
1385
  /** 设置分节(约定 §7.2:首屏 ≤3 行、可直改、无改动时禁用保存)。 */
923
1386
  function BtwSettings(/** @type {any} */ props) {
924
1387
  const api = props?.api;
@@ -1079,10 +1542,42 @@ window.__ModuleLoader__.load({
1079
1542
  ),
1080
1543
  );
1081
1544
 
1082
- // 浮层挂在 shell.overlay(frame-wide,所有列之上、滚动容器之外),不受 composer 裁剪。
1545
+ // 首选:DSH 原生右侧栏 tab(打开时主对话变窄但不被遮挡)。
1546
+ if (typeof ctx.inject === "function") {
1547
+ ctx.inject(["sidebarRightTabs"], (/** @type {any} */ scope) => {
1548
+ const tabs = scope?.sidebarRightTabs;
1549
+ ctx.effect(() => {
1550
+ if (!tabs || typeof tabs.register !== "function") return undefined;
1551
+ try {
1552
+ const dispose = tabs.register({
1553
+ id: PLUGIN_ID,
1554
+ kind: "btw",
1555
+ title: () => t("title"),
1556
+ priority: "extension",
1557
+ });
1558
+ tabReady = true;
1559
+ return () => {
1560
+ tabReady = false;
1561
+ dispose();
1562
+ };
1563
+ } catch {
1564
+ // 注册失败就保持 tabReady=false,按钮自动回退到浮层抽屉。
1565
+ return undefined;
1566
+ }
1567
+ }, "btw: sidebar tab type");
1568
+ });
1569
+ }
1570
+ ctx.slots.inject("sidebar.right.pane.tab", () =>
1571
+ ctx.slots.register(
1572
+ { name: "sidebar.right.pane.tab", key: PLUGIN_ID, locale: NS },
1573
+ (/** @type {any} */ slotProps) => h(BtwTab, slotProps),
1574
+ ),
1575
+ );
1576
+
1577
+ // 回退:右侧浮层抽屉,挂在 shell.overlay(frame-wide,不受 composer 裁剪)。
1083
1578
  ctx.slots.inject("shell.overlay", () =>
1084
1579
  ctx.slots.register({ name: "shell.overlay", id: "btw-panel", order: 60, locale: NS }, () =>
1085
- h(BtwPanel, null),
1580
+ h(BtwDrawer, null),
1086
1581
  ),
1087
1582
  );
1088
1583
  };