@kangyishuai/dsh-btw 0.3.0 → 0.5.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,53 @@ 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: "追问",
59
+ followSend: "追问",
60
+ followCancel: "取消追问",
61
+ followInputLabel: "追问该线程",
62
+ thinking: "思考中",
63
+ threadCount: "{count} 个线程",
64
+ resizeHint: "拖动右侧栏分隔条可调宽度;⌥⌘B 收起侧栏",
47
65
  turns: "轮",
48
66
  promote: "转正",
49
67
  promoted: "已插入输入框草稿(未发送)",
50
68
  promoteBlocked: "输入框已有内容,先清空再转正",
51
69
  promoteFailed: "生成转正草稿失败",
52
- sending: "正在等待答案…(通常 20–40 秒)",
70
+ sending: "正在等待答案…",
71
+ streaming: "正在生成回答",
72
+ waitHint: "通常 20–40 秒",
53
73
  sentPending: "命令已提交,答案稍后出现在对话里",
54
74
  expandAnswer: "展开全文",
55
75
  collapseAnswer: "收起",
56
- newQuestion: "+ 新旁问",
57
76
  submitHint: "提交时会以 /btw 命令写入对话",
77
+ newQuestionLabel: "新旁问",
58
78
  scopeAny: "范围:不限",
59
79
  scopeSession: "范围:整个会话",
60
80
  scopeRecent: "范围:最近几轮",
@@ -71,31 +91,45 @@ window.__ModuleLoader__.load({
71
91
  "settings.failed": "保存失败",
72
92
  "settings.mode": "模式",
73
93
  "settings.readOnly": "只读",
94
+ "settings.echo": "主对话显示完整答案",
95
+ "settings.echoHint": "关闭后只在旁问面板展示,/btw 命令只回一行提示。",
74
96
  };
75
97
  const en = {
76
98
  button: "btw",
77
- title: "Recent side questions",
99
+ title: "Side questions",
100
+ subtitle: "Recent side questions",
78
101
  placeholder: "Ask a read-only side question…",
79
102
  send: "Ask",
80
103
  empty: "No side question yet. Ask one below, or use /btw <question>.",
81
104
  close: "Close",
82
- cost: "new {newTokens} · cached {cachedTokens} · {ms}ms",
105
+ collapse: "Collapse to side rail",
106
+ collapseShort: "Collapse",
107
+ expand: "Expand side questions",
108
+ cost: "new {newTokens} · cached {cachedTokens} · {ms}",
83
109
  failed: "Could not read side-question history",
84
110
  sent: "Submitted; the answer appears in the conversation",
85
111
  followUp: "Follow up",
86
- collapse: "Collapse",
87
112
  followPlaceholder: "Ask a follow-up in this thread…",
113
+ followUpLabel: "Follow-up",
114
+ followSend: "Follow up",
115
+ followCancel: "Cancel follow-up",
116
+ followInputLabel: "Follow up in this thread",
117
+ thinking: "Thinking",
118
+ threadCount: "{count} threads",
119
+ resizeHint: "Drag the sidebar divider to resize; ⌥⌘B collapses the sidebar",
88
120
  turns: "turns",
89
121
  promote: "Promote",
90
122
  promoted: "Inserted into the composer as a draft (not sent)",
91
123
  promoteBlocked: "Composer already has content; clear it before promoting",
92
124
  promoteFailed: "Could not create the promotion draft",
93
- sending: "Waiting for the answer… (usually 20–40s)",
125
+ sending: "Waiting for the answer…",
126
+ streaming: "Generating the answer",
127
+ waitHint: "usually 20–40s",
94
128
  sentPending: "Command submitted; the answer will appear in the conversation",
95
129
  expandAnswer: "Show all",
96
130
  collapseAnswer: "Collapse",
97
- newQuestion: "+ New question",
98
131
  submitHint: "Submitting writes a /btw command into the conversation",
132
+ newQuestionLabel: "New side question",
99
133
  scopeAny: "Scope: any",
100
134
  scopeSession: "Scope: whole session",
101
135
  scopeRecent: "Scope: recent turns",
@@ -113,32 +147,86 @@ window.__ModuleLoader__.load({
113
147
  "settings.failed": "Save failed",
114
148
  "settings.mode": "Mode",
115
149
  "settings.readOnly": "read-only",
150
+ "settings.echo": "Show full answer in the conversation",
151
+ "settings.echoHint":
152
+ "When off, the answer is only in the side-question panel; /btw returns one line.",
116
153
  };
117
154
 
118
155
  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;}",
156
+ // ---- 通用按钮 --------------------------------------------------------
157
+ ".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
158
  ".dsh-btw-btn:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(128,128,128,.16));color:var(--dsw-alias-label-primary,CanvasText);}",
121
159
  ".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));}",
160
+ ".dsh-btw-btn.is-primary{background:var(--dsw-alias-button-primary-fill,#4f7cff);border-color:transparent;color:var(--dsw-alias-label-on-color,#fff);}",
161
+ ".dsh-btw-btn.is-primary:hover{background:var(--dsw-alias-button-primary-hover,#4f7cff);color:var(--dsw-alias-label-on-color,#fff);}",
162
+ // ---- 右侧抽屉 --------------------------------------------------------
163
+ // 贴右边、避开顶部会话头和底部 composer。注意:DSH 的对话区是整宽的,
164
+ // 抽屉仍会盖住主对话右侧约 400px(比居中弹窗好,但不是「完全不遮挡」);
165
+ // 完全不遮挡需要 DSH 原生右侧边栏(打开时主对话变窄)。
166
+ ".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);}",
167
+ "@media (max-width:760px){.dsh-btw-panel{top:56px;bottom:150px;width:calc(100vw - 24px);}}",
168
+ // 原生右侧栏 tab:填满 pane,不再 fixed / 不再自带卡片外壳(由右侧栏提供)。
169
+ ".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;}",
170
+ ".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);}",
171
+ ".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));}",
172
+ ".dsh-btw-rail-count{font-size:10px;opacity:.75;font-variant-numeric:tabular-nums;}",
173
+ // ---- 头部 / 状态 ------------------------------------------------------
174
+ ".dsh-btw-head{display:flex;align-items:center;gap:6px;margin-bottom:8px;font-weight:600;flex:none;}",
175
+ ".dsh-btw-head-title{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}",
176
+ ".dsh-btw-grow{flex:1 1 auto;}",
177
+ ".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
178
  ".dsh-btw-status.is-busy{color:var(--dsw-alias-label-primary,CanvasText);}",
137
179
  ".dsh-btw-spinner{display:inline-block;animation:dsh-btw-spin 1s linear infinite;}",
138
180
  "@keyframes dsh-btw-spin{from{transform:rotate(0)}to{transform:rotate(360deg)}}",
181
+ // ---- 列表 ------------------------------------------------------------
182
+ ".dsh-btw-scroll{flex:1 1 auto;min-height:0;overflow-y:auto;overscroll-behavior:contain;padding-right:2px;scrollbar-gutter:stable;}",
183
+ ".dsh-btw-thread{padding:8px 0;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
184
+ ".dsh-btw-thread:first-child{border-top:none;padding-top:2px;}",
185
+ ".dsh-btw-turn{margin-top:6px;}",
186
+ ".dsh-btw-turn:first-child{margin-top:0;}",
187
+ ".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;}",
188
+ ".dsh-btw-q-label{display:block;margin-bottom:2px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:10.5px;letter-spacing:.5px;}",
189
+ ".dsh-btw-a{margin-top:4px;word-break:break-word;}",
190
+ ".dsh-btw-meta{margin-top:3px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:11px;font-variant-numeric:tabular-nums;}",
191
+ ".dsh-btw-dim{color:var(--dsw-alias-label-tertiary,GrayText);padding:6px 0;}",
192
+ ".dsh-btw-err{color:var(--dsw-alias-state-error-primary,#d9534f);padding:6px 0;word-break:break-word;}",
193
+ ".dsh-btw-row{display:flex;flex-wrap:wrap;align-items:center;gap:6px;margin-top:8px;}",
194
+ // ---- Markdown --------------------------------------------------------
195
+ ".dsh-btw-md{overflow-wrap:anywhere;}",
196
+ ".dsh-btw-md p{margin:0 0 6px;}",
197
+ ".dsh-btw-md p:last-child{margin-bottom:0;}",
198
+ ".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;}",
199
+ ".dsh-btw-md h1{font-size:15px;}",
200
+ ".dsh-btw-md h2{font-size:14px;}",
201
+ ".dsh-btw-md h3{font-size:13px;}",
202
+ ".dsh-btw-md h4,.dsh-btw-md h5,.dsh-btw-md h6{font-size:12.5px;}",
203
+ ".dsh-btw-md ul,.dsh-btw-md ol{margin:4px 0 6px;padding-left:20px;}",
204
+ ".dsh-btw-md li{margin:2px 0;}",
205
+ ".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);}",
206
+ ".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;}",
207
+ ".dsh-btw-codeblock{margin:6px 0;}",
208
+ ".dsh-btw-codeblock-lang{color:var(--dsw-alias-label-tertiary,GrayText);font-size:10.5px;margin-bottom:2px;}",
209
+ ".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;}",
210
+ ".dsh-btw-md pre code{padding:0;border:none;background:transparent;font-size:inherit;white-space:pre;}",
211
+ ".dsh-btw-tablewrap{max-width:100%;overflow-x:auto;margin:6px 0;}",
212
+ ".dsh-btw-md table{border-collapse:collapse;font-size:11.5px;}",
213
+ ".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;}",
214
+ ".dsh-btw-md th{background:var(--dsw-alias-bg-layer-3,var(--dsw-alias-bg-layer-2,Canvas));font-weight:600;}",
215
+ ".dsh-btw-md hr{border:none;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));margin:8px 0;}",
216
+ ".dsh-btw-md a,.dsh-btw-link{color:var(--dsw-alias-brand-primary,#4f7cff);text-decoration:underline;word-break:break-all;}",
217
+ ".dsh-btw-md strong{font-weight:600;}",
218
+ ".dsh-btw-md del{opacity:.65;}",
219
+ ".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;}",
220
+ "@keyframes dsh-btw-blink{50%{opacity:0}}",
221
+ ".dsh-btw-a.is-clamped .dsh-btw-md{position:relative;max-height:320px;overflow:hidden;}",
222
+ '.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;}',
223
+ // ---- composer --------------------------------------------------------
224
+ ".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));}",
225
+ ".dsh-btw-composer-label{color:var(--dsw-alias-label-tertiary,GrayText);font-size:10.5px;letter-spacing:.5px;}",
226
+ ".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;}",
227
+ ".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
228
  ".dsh-btw-setrow{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin:6px 0;}",
140
229
  ".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
230
  ].join("");
143
231
 
144
232
  /** @param {any} ctx @param {string} name */
@@ -162,6 +250,250 @@ window.__ModuleLoader__.load({
162
250
  );
163
251
  }
164
252
 
253
+ // ---- 自适应格式化(与 lib/format.js 行为等价;client 是 classic script,无法 import)--
254
+ const TOKEN_UNITS = [
255
+ { scale: 1e3, suffix: "K" },
256
+ { scale: 1e6, suffix: "M" },
257
+ { scale: 1e9, suffix: "B" },
258
+ { scale: 1e12, suffix: "T" },
259
+ ];
260
+ /** @param {number} value */
261
+ const oneDecimal = (value) => (Math.round(value * 10) / 10).toFixed(1).replace(/\.0+$/u, "");
262
+ /** @param {number} value */
263
+ const scaledText = (value) => (value < 100 ? oneDecimal(value) : String(Math.round(value)));
264
+
265
+ /** @param {unknown} value */
266
+ function formatTokens(value) {
267
+ const number = Math.max(0, Math.round(Number(value) || 0));
268
+ if (number < 1000) return String(number);
269
+ let index = 0;
270
+ for (let i = 0; i < TOKEN_UNITS.length; i += 1) {
271
+ if (number >= TOKEN_UNITS[i].scale) index = i;
272
+ }
273
+ let unit = TOKEN_UNITS[index];
274
+ let scaled = number / unit.scale;
275
+ if (index < TOKEN_UNITS.length - 1 && scaled >= 999.5) {
276
+ index += 1;
277
+ unit = TOKEN_UNITS[index];
278
+ scaled = number / unit.scale;
279
+ }
280
+ return `${scaledText(scaled)}${unit.suffix}`;
281
+ }
282
+
283
+ /** @param {unknown} value */
284
+ function formatDuration(value) {
285
+ const ms = Math.max(0, Math.round(Number(value) || 0));
286
+ if (ms < 1000) return `${ms}ms`;
287
+ const seconds = ms / 1000;
288
+ if (seconds < 59.95) return `${scaledText(seconds)}s`;
289
+ const minutes = seconds / 60;
290
+ if (minutes < 59.95) return `${scaledText(minutes)}m`;
291
+ return `${scaledText(minutes / 60)}h`;
292
+ }
293
+
294
+ // ---- Markdown:host 已解析成 JSON 树,这里只做元素映射 --------------------
295
+ /** @param {any[]} runs @param {string} prefix @returns {any[]} */
296
+ function renderInlines(runs, prefix) {
297
+ /** @type {any[]} */
298
+ const out = [];
299
+ const list = Array.isArray(runs) ? runs : [];
300
+ for (let index = 0; index < list.length; index += 1) {
301
+ const run = list[index];
302
+ const key = `${prefix}i${index}`;
303
+ if (run?.type === "code") {
304
+ out.push(h("code", { key, className: "dsh-btw-inline-code" }, String(run.text ?? "")));
305
+ continue;
306
+ }
307
+ if (run?.type === "strong" || run?.type === "em" || run?.type === "del") {
308
+ const tag = run.type === "strong" ? "strong" : run.type === "em" ? "em" : "del";
309
+ out.push(h(tag, { key }, ...renderInlines(run.children, key)));
310
+ continue;
311
+ }
312
+ if (run?.type === "link") {
313
+ const href = String(run.href ?? "");
314
+ if (!/^(https?:\/\/|mailto:)/iu.test(href)) {
315
+ out.push(h(React.Fragment, { key }, ...renderInlines(run.children, key)));
316
+ } else {
317
+ out.push(
318
+ h(
319
+ "a",
320
+ {
321
+ key,
322
+ className: "dsh-btw-link",
323
+ href,
324
+ target: "_blank",
325
+ rel: "noreferrer noopener",
326
+ "data-btw-link": "true",
327
+ },
328
+ ...renderInlines(run.children, key),
329
+ ),
330
+ );
331
+ }
332
+ continue;
333
+ }
334
+ // 普通文本:段内换行保留成 <br>(模型答案里常靠单换行分行)。
335
+ const text = String(run?.text ?? "");
336
+ const pieces = text.split("\n");
337
+ for (let pieceIndex = 0; pieceIndex < pieces.length; pieceIndex += 1) {
338
+ if (pieceIndex > 0) out.push(h("br", { key: `${key}b${pieceIndex}` }));
339
+ if (pieces[pieceIndex] !== "")
340
+ out.push(h(React.Fragment, { key: `${key}t${pieceIndex}` }, pieces[pieceIndex]));
341
+ }
342
+ }
343
+ return out;
344
+ }
345
+
346
+ /**
347
+ * @param {any[]} blocks
348
+ * @param {boolean} streaming
349
+ * @param {string} [prefix]
350
+ * @returns {any[]}
351
+ */
352
+ function renderBlocks(blocks, streaming, prefix = "b") {
353
+ /** @type {any[]} */
354
+ const out = [];
355
+ const list = Array.isArray(blocks) ? blocks : [];
356
+ for (let index = 0; index < list.length; index += 1) {
357
+ const block = list[index];
358
+ const key = `${prefix}${index}`;
359
+ switch (block?.type) {
360
+ case "heading": {
361
+ const level = Math.min(6, Math.max(1, Number(block.level) || 2));
362
+ out.push(h(`h${level}`, { key }, ...renderInlines(block.inlines, `${key}i`)));
363
+ break;
364
+ }
365
+ case "paragraph":
366
+ out.push(h("p", { key }, ...renderInlines(block.inlines, `${key}i`)));
367
+ break;
368
+ case "code":
369
+ out.push(
370
+ h(
371
+ "div",
372
+ { key, className: "dsh-btw-codeblock", "data-btw-code": "true" },
373
+ block.lang
374
+ ? h("div", { className: "dsh-btw-codeblock-lang" }, String(block.lang))
375
+ : null,
376
+ h("pre", null, h("code", null, String(block.code ?? ""))),
377
+ ),
378
+ );
379
+ break;
380
+ case "list": {
381
+ const items = Array.isArray(block.items) ? block.items : [];
382
+ out.push(
383
+ h(
384
+ block.ordered ? "ol" : "ul",
385
+ { key, start: block.ordered ? Number(block.start) || 1 : undefined },
386
+ ...items.map((/** @type {any} */ item, /** @type {number} */ itemIndex) =>
387
+ h(
388
+ "li",
389
+ { key: `${key}-${itemIndex}` },
390
+ ...renderInlines(item?.inlines, `${key}-${itemIndex}i`),
391
+ ),
392
+ ),
393
+ ),
394
+ );
395
+ break;
396
+ }
397
+ case "quote":
398
+ out.push(h("blockquote", { key }, ...renderBlocks(block.blocks, streaming, `${key}q`)));
399
+ break;
400
+ case "table": {
401
+ const align = Array.isArray(block.align) ? block.align : [];
402
+ const header = Array.isArray(block.header) ? block.header : [];
403
+ const rows = Array.isArray(block.rows) ? block.rows : [];
404
+ out.push(
405
+ h(
406
+ "div",
407
+ { key, className: "dsh-btw-tablewrap" },
408
+ h(
409
+ "table",
410
+ null,
411
+ h(
412
+ "thead",
413
+ null,
414
+ h(
415
+ "tr",
416
+ { key: `${key}h` },
417
+ ...header.map((/** @type {any} */ cell, /** @type {number} */ cellIndex) =>
418
+ h(
419
+ "th",
420
+ { key: `${key}h${cellIndex}`, style: cellStyle(align[cellIndex]) },
421
+ ...renderInlines(cell, `${key}h${cellIndex}i`),
422
+ ),
423
+ ),
424
+ ),
425
+ ),
426
+ h(
427
+ "tbody",
428
+ null,
429
+ ...rows.map((/** @type {any} */ row, /** @type {number} */ rowIndex) =>
430
+ h(
431
+ "tr",
432
+ { key: `${key}r${rowIndex}` },
433
+ ...(Array.isArray(row) ? row : []).map((cell, cellIndex) =>
434
+ h(
435
+ "td",
436
+ {
437
+ key: `${key}r${rowIndex}c${cellIndex}`,
438
+ style: cellStyle(align[cellIndex]),
439
+ },
440
+ ...renderInlines(cell, `${key}r${rowIndex}c${cellIndex}i`),
441
+ ),
442
+ ),
443
+ ),
444
+ ),
445
+ ),
446
+ ),
447
+ ),
448
+ );
449
+ break;
450
+ }
451
+ case "hr":
452
+ out.push(h("hr", { key }));
453
+ break;
454
+ default: {
455
+ const text = String(block?.text ?? "");
456
+ if (text !== "") out.push(h("p", { key }, text));
457
+ }
458
+ }
459
+ }
460
+ if (streaming)
461
+ out.push(h("span", { key: "caret", className: "dsh-btw-caret", "aria-hidden": "true" }));
462
+ return out;
463
+ }
464
+
465
+ /** @param {any} align */
466
+ function cellStyle(align) {
467
+ return align === "center"
468
+ ? { textAlign: "center" }
469
+ : align === "right"
470
+ ? { textAlign: "right" }
471
+ : undefined;
472
+ }
473
+
474
+ /**
475
+ * 一条答案的 Markdown 容器;超长时折叠,点「展开全文」再放开。
476
+ * @param {any} props
477
+ */
478
+ function MarkdownBody(props) {
479
+ const { blocks, streaming, clamped, answerId } = props;
480
+ return h(
481
+ "div",
482
+ {
483
+ className: `dsh-btw-a${clamped ? " is-clamped" : ""}`,
484
+ "data-btw-answer": "true",
485
+ "data-btw-md": "true",
486
+ ...(typeof answerId === "string" && answerId !== ""
487
+ ? { "data-btw-answer-id": answerId }
488
+ : {}),
489
+ },
490
+ h("div", { className: "dsh-btw-md" }, ...renderBlocks(blocks, streaming === true)),
491
+ );
492
+ }
493
+
494
+ /** 一次 RPC 失败原因(诊断用,渲染进 data-btw-error)。 */
495
+ let lastRpcError = "";
496
+
165
497
  exports.inject = ["slots", "locale", "connection", "sessions"];
166
498
  /** @param {any} ctx */
167
499
  exports.apply = function apply(ctx) {
@@ -183,23 +515,23 @@ window.__ModuleLoader__.load({
183
515
  }, "btw: styles");
184
516
 
185
517
  /**
186
- * 按钮(composer 工具行)与浮层(`shell.overlay`)是两个独立组件实例,
518
+ * 按钮(composer 工具行)与抽屉(`shell.overlay`)是两个独立组件实例,
187
519
  * 共享状态必须提升到 apply 作用域。
188
520
  *
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。
521
+ * 为什么抽屉仍挂 `shell.overlay`:`conversation.input.overlay` 在 composer 内部,
522
+ * 会被裁剪;`shell.overlay` 是 frame-wide 浮层,定位从根上可靠,且不改变布局
523
+ * (不会像右侧边栏那样把主对话挤窄)。
194
524
  */
195
525
  const store = (() => {
196
- /** @type {{ open: boolean, sessionId: string }} */
197
- let state = { open: false, sessionId: "" };
526
+ /** @type {{ open: boolean, collapsed: boolean, sessionId: string }} */
527
+ let state = { open: false, collapsed: false, sessionId: "" };
198
528
  /** @type {Set<() => void>} */
199
529
  const listeners = new Set();
200
530
  return {
201
531
  get: () => state,
202
- patch(/** @type {Partial<{ open: boolean, sessionId: string }>} */ next) {
532
+ patch(
533
+ /** @type {Partial<{ open: boolean, collapsed: boolean, sessionId: string }>} */ next,
534
+ ) {
203
535
  state = { ...state, ...next };
204
536
  for (const listener of listeners) listener();
205
537
  },
@@ -210,6 +542,12 @@ window.__ModuleLoader__.load({
210
542
  };
211
543
  })();
212
544
 
545
+ /**
546
+ * 原生右侧栏是否可用:注册成功后才走 tab 形态,否则回退到浮层抽屉。
547
+ * 这样同一份 client 能同时兼容「右侧栏服务在」与「只有 shell.overlay」的宿主。
548
+ */
549
+ let tabReady = false;
550
+
213
551
  /** 订阅 store 的极简 hook。 */
214
552
  const useStore = () => {
215
553
  const [, force] = React.useState(0);
@@ -229,9 +567,6 @@ window.__ModuleLoader__.load({
229
567
  return "zh";
230
568
  };
231
569
 
232
- /** 最近一次 RPC 失败原因(诊断用,渲染进 data-btw-error)。 */
233
- let lastRpcError = "";
234
-
235
570
  /** Typert Remote 调用;解 { ok, value } 信封,失败返回 undefined。 */
236
571
  const callRemote = (/** @type {string} */ method, /** @type {any} */ request) => {
237
572
  const connection = serviceOf(ctx, "connection");
@@ -354,8 +689,9 @@ window.__ModuleLoader__.load({
354
689
  /**
355
690
  * composer 工具行里的「旁问」按钮。
356
691
  *
357
- * 它同时负责把当前 sessionId 写进 store —— 浮层注册在 root scope 的
358
- * `shell.overlay` 上,拿不到 session props,只能由按钮转交。
692
+ * 首选打开 DSH 原生右侧栏的「旁问」tab(不遮挡主对话);宿主没有右侧栏
693
+ * 服务时回退到 `shell.overlay` 浮层抽屉。回退形态拿不到 session props,
694
+ * 所以按钮同时负责把 sessionId 写进 store。
359
695
  */
360
696
  function BtwTrigger(/** @type {any} */ props) {
361
697
  const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
@@ -363,6 +699,37 @@ window.__ModuleLoader__.load({
363
699
  React.useEffect(() => {
364
700
  if (shared.sessionId !== sessionId) store.patch({ sessionId });
365
701
  }, [sessionId, shared.sessionId]);
702
+ /** 首选形态:在 DSH 原生右侧栏打开「旁问」tab(不遮挡主对话)。 */
703
+ const openSidebarTab = () => {
704
+ if (!tabReady) return false;
705
+ const sidebarRight = serviceOf(ctx, "sidebarRight");
706
+ if (!sidebarRight || typeof sidebarRight.openTab !== "function") return false;
707
+ try {
708
+ // 侧栏已被收起时,openTab 只会 focus 已存在的 tab、不会展开栏,
709
+ // 所以先显式展开(track=true、非 fullscreen),再打开/聚焦 tab。
710
+ const layout = serviceOf(ctx, "layout");
711
+ if (layout && typeof layout.openRightbar === "function") {
712
+ try {
713
+ layout.openRightbar(true, false);
714
+ } catch {
715
+ /* 展开失败不阻塞打开 */
716
+ }
717
+ }
718
+ sidebarRight.openTab("btw");
719
+ // 若之前用过回退抽屉,打开 tab 时把它收掉,避免两套面板同时在场。
720
+ store.patch({ open: false, collapsed: false });
721
+ return true;
722
+ } catch {
723
+ return false;
724
+ }
725
+ };
726
+ const toggle = () => {
727
+ if (openSidebarTab()) return;
728
+ const current = store.get();
729
+ if (!current.open) store.patch({ open: true, collapsed: false });
730
+ else if (current.collapsed) store.patch({ collapsed: false });
731
+ else store.patch({ open: false });
732
+ };
366
733
  return h(
367
734
  "button",
368
735
  {
@@ -370,29 +737,28 @@ window.__ModuleLoader__.load({
370
737
  className: "dsh-btw-btn",
371
738
  "data-btw-toggle": "true",
372
739
  title: t("button"),
373
- onClick: () => store.patch({ open: !store.get().open }),
740
+ onClick: toggle,
374
741
  },
375
742
  t("button"),
376
743
  );
377
744
  }
378
745
 
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
- });
746
+ /**
747
+ * 面板主体:原生右侧栏 tab 与回退抽屉共用。
748
+ * @param {any} props `{ sessionId, mode: 'tab'|'drawer', onCollapse, onClose }`
749
+ */
750
+ function BtwBody(/** @type {any} */ props) {
751
+ const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
752
+ const mode = props?.mode === "tab" ? "tab" : "drawer";
753
+ const onCollapse = typeof props?.onCollapse === "function" ? props.onCollapse : () => {};
754
+ const onClose = typeof props?.onClose === "function" ? props.onClose : onCollapse;
755
+ const visible = props?.visible !== false;
392
756
  const [threads, setThreads] = React.useState(/** @type {any[] | null} */ (null));
757
+ const [liveRuns, setLiveRuns] = React.useState(/** @type {any[]} */ ([]));
393
758
  const [failed, setFailed] = React.useState(false);
394
759
  const [activeId, setActiveId] = React.useState("");
395
760
  const [question, setQuestion] = React.useState("");
761
+ const [followQuestion, setFollowQuestion] = React.useState("");
396
762
  const [busy, setBusy] = React.useState(false);
397
763
  const [notice, setNotice] = React.useState("");
398
764
  const [badge, setBadge] = React.useState("");
@@ -400,10 +766,11 @@ window.__ModuleLoader__.load({
400
766
  const [expandedAnswers, setExpandedAnswers] = React.useState(
401
767
  /** @type {Record<string, boolean>} */ ({}),
402
768
  );
403
- // 新建旁问的输入框默认收起:实测同时出现「线程内追问框 + 底部新建框」时,
404
- // 用户分不清哪个是哪个(两个输入框视觉几乎一样)。
405
- const [showNew, setShowNew] = React.useState(false);
406
769
  const aliveRef = React.useRef(true);
770
+ const liveRef = React.useRef(/** @type {any[]} */ ([]));
771
+ const scrollRef = React.useRef(/** @type {any} */ (null));
772
+ const pinnedRef = React.useRef(true);
773
+ const questionRef = React.useRef(/** @type {any} */ (null));
407
774
 
408
775
  React.useEffect(
409
776
  () => () => {
@@ -412,13 +779,37 @@ window.__ModuleLoader__.load({
412
779
  [],
413
780
  );
414
781
 
782
+ // 切会话:清空上一会话的列表与流式现场。
783
+ React.useEffect(() => {
784
+ setThreads(null);
785
+ setLiveRuns([]);
786
+ liveRef.current = [];
787
+ setActiveId("");
788
+ setFollowQuestion("");
789
+ setNotice("");
790
+ pinnedRef.current = true;
791
+ }, [sessionId]);
792
+
793
+ // 面板可见且没开追问输入时,自动聚焦「新旁问」输入框,省一次点击。
794
+ React.useEffect(() => {
795
+ if (!visible || sessionId === "" || activeId !== "") return undefined;
796
+ const timer = setTimeout(() => {
797
+ try {
798
+ questionRef.current?.focus();
799
+ } catch {
800
+ /* 忽略焦点失败 */
801
+ }
802
+ }, 0);
803
+ return () => clearTimeout(timer);
804
+ }, [visible, sessionId, activeId]);
805
+
415
806
  /**
416
- * 拉线程列表。返回数组(成功)或 null(失败)——
417
- * 调用方需要区分「线程数增加」(新问题)与「某线程轮数增加」(追问)。
807
+ * 拉线程列表。quiet = 后台轮询:失败不把界面打红。
808
+ * @param {boolean} [quiet]
418
809
  * @returns {Promise<any[] | null>}
419
810
  */
420
- const load = React.useCallback(
421
- () =>
811
+ const loadThreads = React.useCallback(
812
+ (quiet = false) =>
422
813
  callRemote("threads", { sessionId, limit: LIMITS_CLIENT_THREADS }).then((value) => {
423
814
  if (!aliveRef.current) return null;
424
815
  if (Array.isArray(/** @type {any} */ (value))) {
@@ -426,15 +817,17 @@ window.__ModuleLoader__.load({
426
817
  setFailed(false);
427
818
  return /** @type {any[]} */ (value);
428
819
  }
429
- setThreads([]);
430
- setFailed(true);
820
+ if (!quiet) {
821
+ setThreads([]);
822
+ setFailed(true);
823
+ }
431
824
  return null;
432
825
  }),
433
826
  [sessionId],
434
827
  );
435
828
 
436
- React.useEffect(() => {
437
- if (!open) return undefined;
829
+ /** 重新拉徽章(记录数/范围)。提交完成、live 结束、切范围时都要刷新,避免计数落后。 */
830
+ const refreshBadge = React.useCallback(() => {
438
831
  const scopeLabel =
439
832
  scope === ""
440
833
  ? ""
@@ -445,40 +838,119 @@ window.__ModuleLoader__.load({
445
838
  ? "scopeRecent"
446
839
  : "scopeSelection",
447
840
  ).replace(/^范围:|^Scope:\s*/i, "");
448
- callRemote("stats", { sessionId, scope: scopeLabel, lang: langOf() }).then((value) => {
449
- if (!aliveRef.current) return;
450
- if (value && typeof value.badge === "string") setBadge(value.badge);
451
- });
452
- }, [open, sessionId, scope]);
841
+ return callRemote("stats", { sessionId, scope: scopeLabel, lang: langOf() }).then(
842
+ (/** @type {any} */ value) => {
843
+ if (!aliveRef.current) return;
844
+ if (value && typeof value.badge === "string") setBadge(value.badge);
845
+ },
846
+ );
847
+ }, [sessionId, scope, t]);
848
+
849
+ React.useEffect(() => {
850
+ void refreshBadge();
851
+ }, [refreshBadge]);
852
+
853
+ // 面板挂载(tab 打开 / 抽屉展开)时先读一次历史。
854
+ React.useEffect(() => {
855
+ void loadThreads();
856
+ }, [loadThreads]);
453
857
 
858
+ // 流式与后台刷新:面板打开期间常驻。有 run 时 350ms 一次、空闲 1s 一次;
859
+ // 空闲时每 4 次才刷一次线程列表,避免无谓 RPC。
860
+ React.useEffect(() => {
861
+ if (sessionId === "" || !visible) return undefined;
862
+ let cancelled = false;
863
+ /** @type {any} */
864
+ let timer;
865
+ let ticks = 0;
866
+ const tick = async () => {
867
+ if (cancelled) return;
868
+ /** @type {any[]} */
869
+ let runs = [];
870
+ try {
871
+ const value = await callRemote("live", { sessionId });
872
+ if (Array.isArray(value?.runs)) runs = value.runs;
873
+ } catch {
874
+ runs = [];
875
+ }
876
+ if (cancelled) return;
877
+ const hadLive = liveRef.current.length > 0;
878
+ const hasLive = runs.length > 0;
879
+ liveRef.current = runs;
880
+ // 空闲轮询(无 run)不重复 set 空数组,省掉每秒一次无意义的重渲染。
881
+ if (hasLive || hadLive) setLiveRuns(runs);
882
+ // 只在 live 结束后刷一次历史(run 进行中 threads 不会变,少传大 payload)。
883
+ if (hadLive && !hasLive) {
884
+ void loadThreads(true);
885
+ void refreshBadge();
886
+ } else if (!hasLive && ticks % LIVE_IDLE_REFRESH_EVERY === 0) void loadThreads(true);
887
+ ticks += 1;
888
+ if (!cancelled)
889
+ timer = setTimeout(tick, runs.length > 0 ? LIVE_ACTIVE_MS : LIVE_IDLE_MS);
890
+ };
891
+ timer = setTimeout(tick, 200);
892
+ return () => {
893
+ cancelled = true;
894
+ clearTimeout(timer);
895
+ };
896
+ }, [sessionId, visible, loadThreads, refreshBadge]);
897
+
898
+ // Esc 关闭面板(tab 与回退抽屉同一手感)。用捕获阶段先于宿主/菜单处理,
899
+ // 否则宿主会把 Esc preventDefault 掉,面板永远收不到。
454
900
  React.useEffect(() => {
455
- if (!open) return undefined;
456
- void load();
457
901
  const onKey = (/** @type {any} */ event) => {
458
- if (event?.key === "Escape") setOpen(false);
902
+ if (event?.key !== "Escape") return;
903
+ // 只在焦点位于面板内时才关闭:设置对话框/斜杠菜单的 Esc 归它们自己,
904
+ // 不会因为面板开着而被一起关掉。
905
+ const inPanel =
906
+ typeof event?.target?.closest === "function" &&
907
+ event.target.closest("[data-btw-panel]") !== null;
908
+ if (!inPanel) return;
909
+ onClose();
459
910
  };
460
- document.addEventListener("keydown", onKey);
461
- return () => document.removeEventListener("keydown", onKey);
462
- }, [open, load]);
911
+ document.addEventListener("keydown", onKey, true);
912
+ return () => document.removeEventListener("keydown", onKey, true);
913
+ }, [onClose]);
914
+
915
+ // 自动滚到底:只有用户本来就在底部时才跟随(向上翻历史时不抢滚动条)。
916
+ const onScroll = () => {
917
+ const el = scrollRef.current;
918
+ if (!el) return;
919
+ pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
920
+ };
921
+ React.useEffect(() => {
922
+ const el = scrollRef.current;
923
+ if (!el || !pinnedRef.current) return;
924
+ el.scrollTop = el.scrollHeight;
925
+ }, [threads, liveRuns]);
926
+
927
+ const metaTextOf = (/** @type {any} */ cost, /** @type {number} */ ms) => {
928
+ if (cost && typeof cost === "object") {
929
+ return fmt(t("cost"), {
930
+ newTokens: formatTokens(cost.inputTokens),
931
+ cachedTokens: formatTokens(cost.cacheReadTokens),
932
+ ms: formatDuration(ms),
933
+ });
934
+ }
935
+ return ms > 0 ? formatDuration(ms) : "";
936
+ };
463
937
 
464
938
  /**
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 兜底,任何路径都恢复按钮。
939
+ * 发问 / 追问:新线程走 `/btw <q>`;追问走 `/btw --thread <id> <q>`,
940
+ * 并在提交前把参数登记到 host(这样 composer 里只出现裸 `/btw`)。
941
+ * @param {string} threadId
472
942
  */
473
- const submit = async (/** @type {string} */ threadId) => {
474
- const text = question.trim();
943
+ const submit = async (threadId) => {
944
+ const text = (threadId === "" ? question : followQuestion).trim();
475
945
  if (text === "" || busy) return;
476
946
  setBusy(true);
477
947
  setNotice(t("sending"));
478
948
  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,
949
+ // 用「最近一条记录的时间」判断完成,而不是线程数:
950
+ // 线程数受 20 条上限约束,满额时新问题不会让数量增加,旧逻辑会白等到 120s。
951
+ const beforeAt = beforeThreads.reduce(
952
+ (latest, /** @type {any} */ entry) => Math.max(latest, Number(entry?.at ?? 0)),
953
+ 0,
482
954
  );
483
955
  const flags = [
484
956
  threadId === "" ? "" : `--thread ${threadId}`,
@@ -488,9 +960,6 @@ window.__ModuleLoader__.load({
488
960
  .join(" ");
489
961
  let line = flags === "" ? `/btw ${text}` : `/btw ${flags} ${text}`;
490
962
  if (threadId !== "") {
491
- // 追问:先把参数交给 host 暂存,再提交**裸 `/btw`** ——
492
- // 否则 `--thread t_xxx <问题>` 会整段出现在用户输入框里(实测被抱怨
493
- // 「为什么给我一堆乱码」)。host 侧处理裸命令时先查这个队列。
494
963
  const queued = await callRemote("queueFollowUp", {
495
964
  sessionId,
496
965
  threadId,
@@ -505,9 +974,13 @@ window.__ModuleLoader__.load({
505
974
  setNotice(t("sendFailed"));
506
975
  return;
507
976
  }
508
- setQuestion("");
977
+ if (threadId === "") setQuestion("");
978
+ else {
979
+ setFollowQuestion("");
980
+ setActiveId("");
981
+ }
509
982
  setNotice(t("sent"));
510
- // 轮询到「线程数增加」为止,最长 REFRESH_MAX_MS;单次失败不中断。
983
+ // 轮询到「线程数增加 / 轮数增加」为止,最长 REFRESH_MAX_MS;单次失败不中断。
511
984
  const deadline = Date.now() + REFRESH_MAX_MS;
512
985
  let refreshed = false;
513
986
  while (Date.now() < deadline && aliveRef.current) {
@@ -516,39 +989,29 @@ window.__ModuleLoader__.load({
516
989
  /** @type {any[] | null} */
517
990
  let next = null;
518
991
  try {
519
- next = await load();
992
+ next = await loadThreads(true);
520
993
  } catch {
521
- next = null; // 单次失败继续轮询,不静默卡死
994
+ next = null;
522
995
  }
523
996
  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
- }
997
+ if (next.some((/** @type {any} */ entry) => Number(entry?.at ?? 0) > beforeAt)) {
998
+ refreshed = true;
999
+ break;
538
1000
  }
539
1001
  }
1002
+ void refreshBadge();
540
1003
  setNotice(refreshed ? "" : t("sentPending"));
541
1004
  } finally {
542
- // 无论如何都要放开按钮:卡死的按钮是实测最劝退的问题。
543
1005
  if (aliveRef.current) setBusy(false);
544
1006
  }
545
1007
  };
546
1008
 
547
1009
  /**
548
- * 一键转正:取 host 生成的四节草稿,**只插进 composer,不发送**。
1010
+ * 一键转正:取 host 生成的 Markdown 草稿,**只插进 composer,不发送**。
549
1011
  * 输入框已有内容时拒绝,避免覆盖用户正在写的东西。
1012
+ * @param {any} thread
550
1013
  */
551
- const promote = async (/** @type {any} */ thread) => {
1014
+ const promote = async (thread) => {
552
1015
  if (busy) return;
553
1016
  setBusy(true);
554
1017
  setNotice("");
@@ -567,7 +1030,8 @@ window.__ModuleLoader__.load({
567
1030
  }
568
1031
  const result = await callRemote("promote", {
569
1032
  sessionId,
570
- recordId: String(thread?.lastId ?? ""),
1033
+ // 线程级转正:host 用首问 + 最后一轮答案组四节草稿。
1034
+ threadId: String(thread?.threadId ?? ""),
571
1035
  lang: langOf(),
572
1036
  });
573
1037
  if (result?.ok !== true || typeof result?.text !== "string") {
@@ -586,345 +1050,446 @@ window.__ModuleLoader__.load({
586
1050
  setNotice(t("promoted"));
587
1051
  };
588
1052
 
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;
1053
+ // 折叠按钮:展开/收起单条长答案。展开后保持被点答案的视口位置,避免列表跳回顶部。
1054
+ const answerAnchorRef = React.useRef(/** @type {any} */ (null));
1055
+ const toggleAnswer = (/** @type {string} */ key) => {
1056
+ const list = scrollRef.current;
1057
+ /** @type {any} */
1058
+ const el =
1059
+ list === null || list === undefined
1060
+ ? null
1061
+ : list.querySelector(`[data-btw-answer-id="${key}"]`);
1062
+ answerAnchorRef.current = {
1063
+ key,
1064
+ top: el === null || el === undefined ? null : el.getBoundingClientRect().top,
1065
+ };
1066
+ setExpandedAnswers((/** @type {any} */ previous) => ({
1067
+ ...previous,
1068
+ [key]: !previous[key],
1069
+ }));
640
1070
  };
1071
+ React.useLayoutEffect(() => {
1072
+ const pending = answerAnchorRef.current;
1073
+ if (pending === null || pending === undefined) return;
1074
+ answerAnchorRef.current = null;
1075
+ const list = scrollRef.current;
1076
+ if (list === null || list === undefined || pending.top === null) return;
1077
+ const el = list.querySelector(`[data-btw-answer-id="${pending.key}"]`);
1078
+ if (el === null || el === undefined) return;
1079
+ list.scrollTop += el.getBoundingClientRect().top - pending.top;
1080
+ }, [expandedAnswers]);
641
1081
 
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
- };
1082
+ /** 范围档位选择器:底部「新旁问」和线程内追问共用同一个 scope 状态。 */
1083
+ const renderScopeSelect = (/** @type {string} */ key) =>
1084
+ h(
1085
+ "select",
1086
+ {
1087
+ key,
1088
+ className: "dsh-btw-select",
1089
+ "data-btw-scope": "true",
1090
+ value: scope,
1091
+ onChange: (/** @type {any} */ event) => setScope(String(event?.target?.value ?? "")),
1092
+ },
1093
+ h("option", { value: "" }, t("scopeAny")),
1094
+ h("option", { value: "session" }, t("scopeSession")),
1095
+ h("option", { value: "recent" }, t("scopeRecent")),
1096
+ h("option", { value: "selection" }, t("scopeSelection")),
1097
+ );
677
1098
 
678
- const renderThread = (/** @type {any} */ thread, /** @type {number} */ index) => {
679
- const expanded = activeId === thread.threadId;
1099
+ /** @param {any} thread @param {number} index */
1100
+ const renderThread = (thread, index) => {
1101
+ const threadId = String(thread?.threadId ?? "");
1102
+ const items = Array.isArray(thread?.items) ? thread.items : [];
1103
+ const expanded = activeId === threadId;
680
1104
  return h(
681
1105
  "div",
682
1106
  {
683
- className: "dsh-btw-item",
684
- key: thread.threadId ?? String(index),
1107
+ className: "dsh-btw-thread",
1108
+ key: threadId === "" ? String(index) : threadId,
685
1109
  "data-btw-thread": "true",
686
- "data-btw-thread-id": String(thread.threadId ?? ""),
1110
+ "data-btw-thread-id": threadId,
687
1111
  },
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;
1112
+ ...items.map((/** @type {any} */ item, /** @type {number} */ itemIndex) => {
1113
+ const itemKey = `${threadId}:${String(item?.id ?? itemIndex)}`;
1114
+ const isLast = itemIndex === items.length - 1;
1115
+ const clamped = expandedAnswers[itemKey] !== true && Number(item?.chars ?? 0) > 400;
708
1116
  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
1117
+ "div",
1118
+ { className: "dsh-btw-turn", key: itemKey, "data-btw-turn": "true" },
1119
+ String(item?.question ?? "") === ""
1120
+ ? null
1121
+ : h(
1122
+ "div",
1123
+ { className: "dsh-btw-q", "data-btw-question": "true" },
1124
+ itemIndex === 0
1125
+ ? null
1126
+ : h("span", { className: "dsh-btw-q-label" }, t("followUpLabel")),
1127
+ String(item.question),
1128
+ ),
1129
+ h(MarkdownBody, {
1130
+ blocks: item?.blocks,
1131
+ streaming: false,
1132
+ clamped,
1133
+ answerId: itemKey,
1134
+ }),
1135
+ clamped
720
1136
  ? h(
721
1137
  "button",
722
1138
  {
723
1139
  type: "button",
724
1140
  className: "dsh-btw-btn",
725
1141
  "data-btw-expand": "true",
726
- onClick: () =>
727
- setExpandedAnswers((/** @type {any} */ prev) => ({
728
- ...prev,
729
- [key]: !isOpen,
730
- })),
1142
+ onClick: () => toggleAnswer(itemKey),
731
1143
  },
732
- isOpen ? t("collapseAnswer") : t("expandAnswer"),
1144
+ t("expandAnswer"),
1145
+ )
1146
+ : null,
1147
+ (() => {
1148
+ const meta = metaTextOf(item?.cost, Number(item?.ms ?? 0));
1149
+ return meta === ""
1150
+ ? null
1151
+ : h("div", { className: "dsh-btw-meta", "data-btw-meta": "true" }, meta);
1152
+ })(),
1153
+ isLast
1154
+ ? h(
1155
+ "div",
1156
+ { className: "dsh-btw-row" },
1157
+ h(
1158
+ "button",
1159
+ {
1160
+ type: "button",
1161
+ className: "dsh-btw-btn",
1162
+ "data-btw-followup": "true",
1163
+ onClick: () => {
1164
+ setActiveId(expanded ? "" : threadId);
1165
+ setFollowQuestion("");
1166
+ },
1167
+ },
1168
+ expanded ? t("followCancel") : t("followUp"),
1169
+ ),
1170
+ h(
1171
+ "button",
1172
+ {
1173
+ type: "button",
1174
+ className: "dsh-btw-btn",
1175
+ "data-btw-promote": "true",
1176
+ disabled: busy,
1177
+ onClick: () => void promote(thread),
1178
+ },
1179
+ t("promote"),
1180
+ ),
1181
+ )
1182
+ : null,
1183
+ expanded && isLast
1184
+ ? h(
1185
+ "div",
1186
+ { className: "dsh-btw-composer", "data-btw-thread-input": "true" },
1187
+ h("span", { className: "dsh-btw-composer-label" }, t("followInputLabel")),
1188
+ h("textarea", {
1189
+ className: "dsh-btw-input",
1190
+ "data-btw-input": "true",
1191
+ placeholder: t("followPlaceholder"),
1192
+ value: followQuestion,
1193
+ rows: 2,
1194
+ onChange: (/** @type {any} */ event) =>
1195
+ setFollowQuestion(String(event?.target?.value ?? "")),
1196
+ onKeyDown: (/** @type {any} */ event) => {
1197
+ if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
1198
+ event.preventDefault();
1199
+ void submit(threadId);
1200
+ }
1201
+ },
1202
+ }),
1203
+ h(
1204
+ "div",
1205
+ { className: "dsh-btw-row" },
1206
+ h(
1207
+ "button",
1208
+ {
1209
+ type: "button",
1210
+ className: "dsh-btw-btn",
1211
+ "data-btw-send": "true",
1212
+ disabled: busy || followQuestion.trim() === "",
1213
+ onClick: () => void submit(threadId),
1214
+ },
1215
+ t("followSend"),
1216
+ ),
1217
+ renderScopeSelect("follow-scope"),
1218
+ ),
733
1219
  )
734
1220
  : null,
735
1221
  );
1222
+ }),
1223
+ );
1224
+ };
1225
+
1226
+ /** 流式卡片:固定追加在列表最底部(最新一条),结束后由真实线程替换。 */
1227
+ const renderLive = (/** @type {any} */ run) => {
1228
+ const questionText = String(run?.question ?? "");
1229
+ const isFollowUp = (Array.isArray(threads) ? threads : []).some(
1230
+ (/** @type {any} */ thread) => thread?.threadId === run?.threadId,
1231
+ );
1232
+ return h(
1233
+ "div",
1234
+ {
1235
+ className: "dsh-btw-thread dsh-btw-live",
1236
+ key: `live:${String(run?.threadId ?? "")}`,
1237
+ "data-btw-live": "true",
1238
+ "data-btw-thread-id": String(run?.threadId ?? ""),
1239
+ },
1240
+ questionText === ""
1241
+ ? null
1242
+ : h(
1243
+ "div",
1244
+ { className: "dsh-btw-q", "data-btw-question": "true" },
1245
+ isFollowUp
1246
+ ? h("span", { className: "dsh-btw-q-label" }, t("followUpLabel"))
1247
+ : null,
1248
+ questionText,
1249
+ ),
1250
+ (() => {
1251
+ const blocks = Array.isArray(run?.blocks) ? run.blocks : [];
1252
+ return blocks.length === 0
1253
+ ? h("div", { className: "dsh-btw-dim", "data-btw-stream-text": "true" }, "…")
1254
+ : h(
1255
+ "div",
1256
+ {
1257
+ className: "dsh-btw-a",
1258
+ "data-btw-stream-text": "true",
1259
+ "data-btw-md": "true",
1260
+ },
1261
+ h("div", { className: "dsh-btw-md" }, ...renderBlocks(blocks, true)),
1262
+ );
736
1263
  })(),
737
1264
  h(
738
1265
  "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
- }),
1266
+ { className: "dsh-btw-meta", "data-btw-elapsed": "true" },
1267
+ `${
1268
+ Array.isArray(run?.blocks) && run.blocks.length > 0 ? t("streaming") : t("thinking")
1269
+ } · ${formatDuration(run?.ms)}`,
745
1270
  ),
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
1271
  );
804
1272
  };
805
1273
 
806
- const body =
807
- threads === null
1274
+ const known = threads ?? [];
1275
+ const list =
1276
+ threads === null && liveRuns.length === 0
808
1277
  ? h("div", { className: "dsh-btw-dim" }, "…")
809
- : threads.length === 0
1278
+ : known.length === 0 && liveRuns.length === 0
810
1279
  ? h("div", { className: "dsh-btw-dim", "data-btw-empty": "true" }, t("empty"))
811
- : threads.map(renderThread);
1280
+ : [
1281
+ ...known.map(renderThread),
1282
+ ...liveRuns.map((/** @type {any} */ run) => renderLive(run)),
1283
+ ];
1284
+
1285
+ // 有 live 卡片时不显示状态条:卡片里已经有「正在生成回答 · 12s」,不需要重复。
1286
+ const statusBusy = busy;
1287
+ const statusText = busy ? `${t("sending")}(${t("waitHint")})` : notice;
1288
+ const statusVisible = liveRuns.length === 0 && (statusBusy || notice !== "");
812
1289
 
813
1290
  return h(
814
- "span",
815
- { "data-btw-root": "true" },
1291
+ "div",
1292
+ {
1293
+ className: `dsh-btw-panel${mode === "tab" ? " is-tab" : ""}`,
1294
+ "data-btw-panel": "true",
1295
+ ...(mode === "tab"
1296
+ ? { "data-btw-tab": "true" }
1297
+ : { "data-btw-overlay": "true", "data-btw-drawer": "true" }),
1298
+ role: mode === "tab" ? "region" : "dialog",
1299
+ "aria-label": t("title"),
1300
+ },
816
1301
  h(
817
1302
  "div",
818
- { className: "dsh-btw-panel", "data-btw-overlay": "true", role: "dialog" },
1303
+ { className: "dsh-btw-head" },
1304
+ h("span", { className: "dsh-btw-head-title" }, t("subtitle")),
1305
+ threads !== null && threads.length > 0
1306
+ ? h(
1307
+ "span",
1308
+ { className: "dsh-btw-dim", "data-btw-count": "true" },
1309
+ fmt(t("threadCount"), { count: threads.length }),
1310
+ )
1311
+ : null,
1312
+ mode === "tab"
1313
+ ? null
1314
+ : h(
1315
+ "button",
1316
+ {
1317
+ type: "button",
1318
+ className: "dsh-btw-btn",
1319
+ "data-btw-collapse": "true",
1320
+ title: t("collapse"),
1321
+ onClick: () => onCollapse(),
1322
+ },
1323
+ t("collapseShort"),
1324
+ ),
819
1325
  h(
820
- "div",
821
- { className: "dsh-btw-head" },
822
- h("span", null, t("title")),
823
- h(
824
- "button",
1326
+ "button",
1327
+ {
1328
+ type: "button",
1329
+ className: "dsh-btw-btn",
1330
+ "data-btw-close": "true",
1331
+ onClick: () => onClose(),
1332
+ },
1333
+ t("close"),
1334
+ ),
1335
+ ),
1336
+ statusVisible
1337
+ ? h(
1338
+ "div",
825
1339
  {
826
- type: "button",
827
- className: "dsh-btw-btn",
828
- "data-btw-new": "true",
829
- onClick: () => setShowNew((/** @type {boolean} */ v) => !v),
1340
+ className: `dsh-btw-status${statusBusy ? " is-busy" : ""}`,
1341
+ "data-btw-notice": "true",
830
1342
  },
831
- showNew ? t("collapse") : t("newQuestion"),
832
- ),
833
- h(
834
- "button",
1343
+ statusBusy ? h("span", { className: "dsh-btw-spinner" }, "⟳") : null,
1344
+ h("span", null, statusText),
1345
+ )
1346
+ : null,
1347
+ failed
1348
+ ? h(
1349
+ "div",
1350
+ { className: "dsh-btw-err", "data-btw-error": "history_unavailable" },
1351
+ `${t("failed")} — ${lastRpcError}`,
1352
+ )
1353
+ : h(
1354
+ "div",
835
1355
  {
836
- type: "button",
837
- className: "dsh-btw-btn",
838
- "data-btw-close": "true",
839
- onClick: () => setOpen(false),
1356
+ className: "dsh-btw-scroll",
1357
+ "data-btw-list": "true",
1358
+ ref: scrollRef,
1359
+ onScroll,
840
1360
  },
841
- t("close"),
1361
+ ...(Array.isArray(list) ? list : [list]),
842
1362
  ),
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",
1363
+ activeId === ""
1364
+ ? h(
1365
+ "div",
1366
+ { className: "dsh-btw-composer" },
1367
+ h("span", { className: "dsh-btw-composer-label" }, t("newQuestionLabel")),
1368
+ h("textarea", {
1369
+ className: "dsh-btw-input",
1370
+ "data-btw-input": "true",
1371
+ placeholder: t("placeholder"),
1372
+ value: question,
1373
+ rows: 2,
1374
+ ref: questionRef,
1375
+ onChange: (/** @type {any} */ event) =>
1376
+ setQuestion(String(event?.target?.value ?? "")),
1377
+ onKeyDown: (/** @type {any} */ event) => {
1378
+ if (event?.key === "Enter" && (event.metaKey || event.ctrlKey)) {
1379
+ event.preventDefault();
1380
+ void submit("");
1381
+ }
853
1382
  },
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(
1383
+ }),
1384
+ h(
866
1385
  "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
- }),
1386
+ { className: "dsh-btw-row" },
883
1387
  h(
884
1388
  "button",
885
1389
  {
886
1390
  type: "button",
887
- className: "dsh-btw-btn",
1391
+ className: "dsh-btw-btn is-primary",
888
1392
  "data-btw-send": "true",
889
1393
  disabled: busy || question.trim() === "",
890
1394
  onClick: () => void submit(""),
891
1395
  },
892
1396
  t("send"),
893
1397
  ),
894
- )
895
- : null,
896
- h(
897
- "div",
898
- { className: "dsh-btw-row" },
899
- h(
900
- "select",
901
- {
902
- className: "dsh-btw-input",
903
- "data-btw-scope": "true",
904
- value: scope,
905
- onChange: (/** @type {any} */ event) =>
906
- setScope(String(event?.target?.value ?? "")),
907
- },
908
- h("option", { value: "" }, t("scopeAny")),
909
- h("option", { value: "session" }, t("scopeSession")),
910
- h("option", { value: "recent" }, t("scopeRecent")),
911
- h("option", { value: "selection" }, t("scopeSelection")),
912
- ),
913
- ),
914
- h("div", { className: "dsh-btw-meta", "data-btw-hint": "true" }, t("submitHint")),
915
- badge === ""
916
- ? null
917
- : h("div", { className: "dsh-btw-meta", "data-btw-badge": "true" }, badge),
918
- ),
1398
+ renderScopeSelect("new-scope"),
1399
+ ),
1400
+ )
1401
+ : null,
1402
+ h("div", { className: "dsh-btw-meta", "data-btw-hint": "true" }, t("submitHint")),
1403
+ mode === "tab"
1404
+ ? h(
1405
+ "div",
1406
+ { className: "dsh-btw-meta", "data-btw-resize-hint": "true" },
1407
+ t("resizeHint"),
1408
+ )
1409
+ : null,
1410
+ badge === ""
1411
+ ? null
1412
+ : h("div", { className: "dsh-btw-meta", "data-btw-badge": "true" }, badge),
919
1413
  );
920
1414
  }
921
1415
 
1416
+ /** 回退形态:`shell.overlay` 里的右侧抽屉(宿主没有右侧栏服务时)。 */
1417
+ function BtwDrawer(/** @type {any} */ props) {
1418
+ void props;
1419
+ const shared = useStore();
1420
+ if (!shared.open) return null;
1421
+ if (shared.collapsed) {
1422
+ return h(
1423
+ "button",
1424
+ {
1425
+ type: "button",
1426
+ className: "dsh-btw-rail",
1427
+ "data-btw-rail": "true",
1428
+ title: t("expand"),
1429
+ "aria-label": t("expand"),
1430
+ onClick: () => store.patch({ collapsed: false }),
1431
+ },
1432
+ h("span", null, t("button")),
1433
+ );
1434
+ }
1435
+ return h(BtwBody, {
1436
+ sessionId: shared.sessionId,
1437
+ mode: "drawer",
1438
+ onCollapse: () => store.patch({ collapsed: true }),
1439
+ onClose: () => store.patch({ open: false }),
1440
+ });
1441
+ }
1442
+
1443
+ /**
1444
+ * 首选形态:DSH 原生右侧栏里的「旁问」tab。
1445
+ * 收起 = 关闭 tab(再点输入框旁的「旁问」按钮打开)。
1446
+ */
1447
+ function BtwTab(/** @type {any} */ props) {
1448
+ const sessionId = typeof props?.sessionId === "string" ? props.sessionId : "";
1449
+ const useTabInfo =
1450
+ typeof props?.useTabInfo === "function" ? props.useTabInfo : () => undefined;
1451
+ const info = useTabInfo();
1452
+ const closeTab = () => {
1453
+ try {
1454
+ const actions = info?.tab?.actions;
1455
+ if (typeof actions?.close === "function") {
1456
+ actions.close();
1457
+ return;
1458
+ }
1459
+ } catch {
1460
+ /* 退到 closeIn */
1461
+ }
1462
+ try {
1463
+ const sidebarRight = serviceOf(ctx, "sidebarRight");
1464
+ const tabId = info?.tab?.id;
1465
+ if (
1466
+ sidebarRight !== undefined &&
1467
+ typeof sidebarRight.closeIn === "function" &&
1468
+ tabId !== undefined
1469
+ ) {
1470
+ sidebarRight.closeIn(sessionId, tabId);
1471
+ }
1472
+ } catch {
1473
+ /* 关不上也保持可见 */
1474
+ }
1475
+ };
1476
+ // 收起整栏交给宿主右上角的收起按钮/快捷键;这里只负责关闭 tab。
1477
+ return h(BtwBody, {
1478
+ sessionId,
1479
+ mode: "tab",
1480
+ onCollapse: closeTab,
1481
+ onClose: closeTab,
1482
+ visible: info?.tab?.visible !== false,
1483
+ });
1484
+ }
1485
+
922
1486
  /** 设置分节(约定 §7.2:首屏 ≤3 行、可直改、无改动时禁用保存)。 */
923
1487
  function BtwSettings(/** @type {any} */ props) {
924
1488
  const api = props?.api;
925
1489
  const [loaded, setLoaded] = React.useState(/** @type {any} */ (null));
926
1490
  const [tools, setTools] = React.useState("");
927
1491
  const [limit, setLimit] = React.useState("");
1492
+ const [echo, setEcho] = React.useState(true);
928
1493
  const [saving, setSaving] = React.useState(false);
929
1494
  const [notice, setNotice] = React.useState("");
930
1495
  const [expanded, setExpanded] = React.useState(false);
@@ -934,6 +1499,7 @@ window.__ModuleLoader__.load({
934
1499
  setLoaded(value);
935
1500
  setTools(Array.isArray(value.allowedTools) ? value.allowedTools.join(", ") : "");
936
1501
  setLimit(String(value.historyLimit ?? ""));
1502
+ setEcho(value.echoAnswer !== false);
937
1503
  }, []);
938
1504
 
939
1505
  React.useEffect(() => {
@@ -945,7 +1511,8 @@ window.__ModuleLoader__.load({
945
1511
  const dirty =
946
1512
  loaded !== null &&
947
1513
  (tools !== (loaded.allowedTools ?? []).join(", ") ||
948
- limit !== String(loaded.historyLimit ?? ""));
1514
+ limit !== String(loaded.historyLimit ?? "") ||
1515
+ echo !== (loaded.echoAnswer !== false));
949
1516
 
950
1517
  const save = async () => {
951
1518
  const call =
@@ -954,7 +1521,7 @@ window.__ModuleLoader__.load({
954
1521
  setSaving(true);
955
1522
  setNotice("");
956
1523
  const next = await Promise.resolve(
957
- call({ allowedTools: tools, historyLimit: Number(limit) }),
1524
+ call({ allowedTools: tools, historyLimit: Number(limit), echoAnswer: echo }),
958
1525
  ).catch(() => undefined);
959
1526
  setSaving(false);
960
1527
  if (next && typeof next === "object") {
@@ -994,6 +1561,16 @@ window.__ModuleLoader__.load({
994
1561
  ? t("settings.readOnly")
995
1562
  : `${loaded.allowedTools.length}`,
996
1563
  ),
1564
+ h("span", { className: "dsh-btw-grow" }),
1565
+ h("input", {
1566
+ type: "checkbox",
1567
+ "data-btw-setting-echo": "true",
1568
+ "aria-label": t("settings.echo"),
1569
+ title: t("settings.echoHint"),
1570
+ checked: echo,
1571
+ onChange: (/** @type {any} */ event) => setEcho(event?.target?.checked === true),
1572
+ }),
1573
+ h("span", { className: "dsh-btw-setlabel" }, t("settings.echo")),
997
1574
  ),
998
1575
  row(
999
1576
  t("settings.tools"),
@@ -1079,10 +1656,42 @@ window.__ModuleLoader__.load({
1079
1656
  ),
1080
1657
  );
1081
1658
 
1082
- // 浮层挂在 shell.overlay(frame-wide,所有列之上、滚动容器之外),不受 composer 裁剪。
1659
+ // 首选:DSH 原生右侧栏 tab(打开时主对话变窄但不被遮挡)。
1660
+ if (typeof ctx.inject === "function") {
1661
+ ctx.inject(["sidebarRightTabs"], (/** @type {any} */ scope) => {
1662
+ const tabs = scope?.sidebarRightTabs;
1663
+ ctx.effect(() => {
1664
+ if (!tabs || typeof tabs.register !== "function") return undefined;
1665
+ try {
1666
+ const dispose = tabs.register({
1667
+ id: PLUGIN_ID,
1668
+ kind: "btw",
1669
+ title: () => t("title"),
1670
+ priority: "extension",
1671
+ });
1672
+ tabReady = true;
1673
+ return () => {
1674
+ tabReady = false;
1675
+ dispose();
1676
+ };
1677
+ } catch {
1678
+ // 注册失败就保持 tabReady=false,按钮自动回退到浮层抽屉。
1679
+ return undefined;
1680
+ }
1681
+ }, "btw: sidebar tab type");
1682
+ });
1683
+ }
1684
+ ctx.slots.inject("sidebar.right.pane.tab", () =>
1685
+ ctx.slots.register(
1686
+ { name: "sidebar.right.pane.tab", key: PLUGIN_ID, locale: NS },
1687
+ (/** @type {any} */ slotProps) => h(BtwTab, slotProps),
1688
+ ),
1689
+ );
1690
+
1691
+ // 回退:右侧浮层抽屉,挂在 shell.overlay(frame-wide,不受 composer 裁剪)。
1083
1692
  ctx.slots.inject("shell.overlay", () =>
1084
1693
  ctx.slots.register({ name: "shell.overlay", id: "btw-panel", order: 60, locale: NS }, () =>
1085
- h(BtwPanel, null),
1694
+ h(BtwDrawer, null),
1086
1695
  ),
1087
1696
  );
1088
1697
  };