@kangyishuai/dsh-btw 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/README.zh-CN.md +3 -1
- package/lib/client.js +134 -12
- package/lib/followup-queue.js +64 -0
- package/lib/service.js +34 -3
- package/lib/threads.js +86 -18
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -49,8 +49,10 @@ Restart the DSH desktop app afterwards.
|
|
|
49
49
|
/btw --scope recent <q> # hint the answer to focus (session | recent | selection)
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
The
|
|
53
|
-
|
|
52
|
+
The panel opens as a **centered dialog** from the「旁问」button left of the composer
|
|
53
|
+
(it lives in the frame-wide overlay layer, so it is not clipped by the composer).
|
|
54
|
+
It lists threads with cost badges, lets you follow up or promote one to a draft, and shows the
|
|
55
|
+
scope badge at the bottom. Use「+ 新旁问」to reveal the new-question input.
|
|
54
56
|
|
|
55
57
|
## Configuration
|
|
56
58
|
|
package/README.zh-CN.md
CHANGED
|
@@ -52,7 +52,9 @@ dsh plugin --profile desktop add @kangyishuai/dsh-btw
|
|
|
52
52
|
/btw --scope recent <问题> # 提示回答聚焦的范围(session | recent | selection)
|
|
53
53
|
```
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
面板点输入框左侧的「旁问」按钮打开,以**居中弹窗**呈现(挂在 frame-wide 的 overlay 层,
|
|
56
|
+
不会被输入框容器裁剪)。里面列出各线程与成本徽章,可追问、可转正,底部显示范围徽章;
|
|
57
|
+
新建旁问要点标题栏的「+ 新旁问」。
|
|
56
58
|
|
|
57
59
|
## 配置
|
|
58
60
|
|
package/lib/client.js
CHANGED
|
@@ -125,6 +125,8 @@ window.__ModuleLoader__.load({
|
|
|
125
125
|
".dsh-btw-item{padding:6px 0;border-top:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.2));}",
|
|
126
126
|
".dsh-btw-q{color:var(--dsw-alias-label-secondary,GrayText);}",
|
|
127
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;}",
|
|
128
130
|
".dsh-btw-a.is-clamped{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:6;line-clamp:6;overflow:hidden;}",
|
|
129
131
|
".dsh-btw-meta{margin-top:2px;color:var(--dsw-alias-label-tertiary,GrayText);font-size:11px;}",
|
|
130
132
|
".dsh-btw-dim{color:var(--dsw-alias-label-tertiary,GrayText);padding:6px 0;}",
|
|
@@ -410,18 +412,23 @@ window.__ModuleLoader__.load({
|
|
|
410
412
|
[],
|
|
411
413
|
);
|
|
412
414
|
|
|
415
|
+
/**
|
|
416
|
+
* 拉线程列表。返回数组(成功)或 null(失败)——
|
|
417
|
+
* 调用方需要区分「线程数增加」(新问题)与「某线程轮数增加」(追问)。
|
|
418
|
+
* @returns {Promise<any[] | null>}
|
|
419
|
+
*/
|
|
413
420
|
const load = React.useCallback(
|
|
414
421
|
() =>
|
|
415
422
|
callRemote("threads", { sessionId, limit: LIMITS_CLIENT_THREADS }).then((value) => {
|
|
416
|
-
if (!aliveRef.current) return
|
|
423
|
+
if (!aliveRef.current) return null;
|
|
417
424
|
if (Array.isArray(/** @type {any} */ (value))) {
|
|
418
425
|
setThreads(value);
|
|
419
426
|
setFailed(false);
|
|
420
|
-
return value
|
|
427
|
+
return /** @type {any[]} */ (value);
|
|
421
428
|
}
|
|
422
429
|
setThreads([]);
|
|
423
430
|
setFailed(true);
|
|
424
|
-
return
|
|
431
|
+
return null;
|
|
425
432
|
}),
|
|
426
433
|
[sessionId],
|
|
427
434
|
);
|
|
@@ -468,14 +475,30 @@ window.__ModuleLoader__.load({
|
|
|
468
475
|
if (text === "" || busy) return;
|
|
469
476
|
setBusy(true);
|
|
470
477
|
setNotice(t("sending"));
|
|
471
|
-
const
|
|
478
|
+
const beforeThreads = Array.isArray(threads) ? threads : [];
|
|
479
|
+
const beforeCount = beforeThreads.length;
|
|
480
|
+
const beforeTurns = Number(
|
|
481
|
+
beforeThreads.find((/** @type {any} */ t) => t?.threadId === threadId)?.turns ?? 0,
|
|
482
|
+
);
|
|
472
483
|
const flags = [
|
|
473
484
|
threadId === "" ? "" : `--thread ${threadId}`,
|
|
474
485
|
scope === "" ? "" : `--scope ${scope}`,
|
|
475
486
|
]
|
|
476
487
|
.filter(Boolean)
|
|
477
488
|
.join(" ");
|
|
478
|
-
|
|
489
|
+
let line = flags === "" ? `/btw ${text}` : `/btw ${flags} ${text}`;
|
|
490
|
+
if (threadId !== "") {
|
|
491
|
+
// 追问:先把参数交给 host 暂存,再提交**裸 `/btw`** ——
|
|
492
|
+
// 否则 `--thread t_xxx <问题>` 会整段出现在用户输入框里(实测被抱怨
|
|
493
|
+
// 「为什么给我一堆乱码」)。host 侧处理裸命令时先查这个队列。
|
|
494
|
+
const queued = await callRemote("queueFollowUp", {
|
|
495
|
+
sessionId,
|
|
496
|
+
threadId,
|
|
497
|
+
question: text,
|
|
498
|
+
scope,
|
|
499
|
+
}).catch(() => undefined);
|
|
500
|
+
if (queued?.ok === true) line = "/btw";
|
|
501
|
+
}
|
|
479
502
|
try {
|
|
480
503
|
const result = await sendText(sessionId, line);
|
|
481
504
|
if (result !== "ok") {
|
|
@@ -490,15 +513,28 @@ window.__ModuleLoader__.load({
|
|
|
490
513
|
while (Date.now() < deadline && aliveRef.current) {
|
|
491
514
|
await new Promise((resolve) => setTimeout(resolve, REFRESH_INTERVAL_MS));
|
|
492
515
|
if (!aliveRef.current) break;
|
|
493
|
-
|
|
516
|
+
/** @type {any[] | null} */
|
|
517
|
+
let next = null;
|
|
494
518
|
try {
|
|
495
|
-
|
|
519
|
+
next = await load();
|
|
496
520
|
} catch {
|
|
497
|
-
|
|
521
|
+
next = null; // 单次失败继续轮询,不静默卡死
|
|
498
522
|
}
|
|
499
|
-
if (
|
|
500
|
-
|
|
501
|
-
|
|
523
|
+
if (next === null) continue;
|
|
524
|
+
if (threadId === "") {
|
|
525
|
+
// 新问题 → 线程数应增加
|
|
526
|
+
if (next.length > beforeCount) {
|
|
527
|
+
refreshed = true;
|
|
528
|
+
break;
|
|
529
|
+
}
|
|
530
|
+
} else {
|
|
531
|
+
// 追问 → **线程数不变**,要看目标线程的轮数是否增加。
|
|
532
|
+
// (曾经只判线程数,导致追问永远等不到,按钮卡到 120s 超时。)
|
|
533
|
+
const target = next.find((/** @type {any} */ t) => t?.threadId === threadId);
|
|
534
|
+
if (Number(target?.turns ?? 0) > beforeTurns) {
|
|
535
|
+
refreshed = true;
|
|
536
|
+
break;
|
|
537
|
+
}
|
|
502
538
|
}
|
|
503
539
|
}
|
|
504
540
|
setNotice(refreshed ? "" : t("sentPending"));
|
|
@@ -553,6 +589,92 @@ window.__ModuleLoader__.load({
|
|
|
553
589
|
// 浮层不画按钮:按钮由 BtwTrigger 注册在 composer 工具行里。
|
|
554
590
|
if (!open) return null;
|
|
555
591
|
|
|
592
|
+
/**
|
|
593
|
+
* 把 host 切好的段映射成元素:
|
|
594
|
+
* - `code` → 等宽 `<pre>`(不再把 ``` 显示给用户)
|
|
595
|
+
* - `link` → 可点 `<a>`(之前 URL 是死文本)
|
|
596
|
+
* - `text` → 原样
|
|
597
|
+
* 没有 segments(老数据 / 字段缺失)时回退纯文本。
|
|
598
|
+
* @param {any} thread
|
|
599
|
+
* @param {string} fallback
|
|
600
|
+
* @returns {any}
|
|
601
|
+
*/
|
|
602
|
+
/**
|
|
603
|
+
* 回退解析:host 还没重启(或拿到老数据)时,client 自己从原始答案里切段。
|
|
604
|
+
*
|
|
605
|
+
* 为什么两处都做:`answerSegments` 是 host 侧字段,改完必须重启 DSH 才生效;
|
|
606
|
+
* client 改动刷新页面即可。为了让新渲染立刻可用,这里保留一份**行为等价**的
|
|
607
|
+
* 极简实现(切 ``` 围栏 + 认 http(s) URL)。host 版本优先 —— 它被单测覆盖。
|
|
608
|
+
* @param {string} text
|
|
609
|
+
* @returns {any[]}
|
|
610
|
+
*/
|
|
611
|
+
const parseSegmentsLocal = (/** @type {string} */ text) => {
|
|
612
|
+
const raw = String(text ?? "");
|
|
613
|
+
/** @type {any[]} */
|
|
614
|
+
const out = [];
|
|
615
|
+
const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu;
|
|
616
|
+
let last = 0;
|
|
617
|
+
for (;;) {
|
|
618
|
+
const m = fenceRe.exec(raw);
|
|
619
|
+
if (m === null) break;
|
|
620
|
+
if (m.index > last) out.push({ kind: "text", text: raw.slice(last, m.index) });
|
|
621
|
+
out.push({ kind: "code", lang: m[1] ?? "", text: (m[2] ?? "").replace(/\n+$/u, "") });
|
|
622
|
+
last = m.index + m[0].length;
|
|
623
|
+
}
|
|
624
|
+
const tail = raw.slice(last);
|
|
625
|
+
const urlRe = /https?:\/\/[^\s<>()\u3000-\u303f\uff00-\uffef]+/gu;
|
|
626
|
+
let cursor = 0;
|
|
627
|
+
for (;;) {
|
|
628
|
+
const u = urlRe.exec(tail);
|
|
629
|
+
if (u === null) break;
|
|
630
|
+
const rawUrl = u[0];
|
|
631
|
+
const trimmed = rawUrl.replace(/[.,;:!?]+$/u, "");
|
|
632
|
+
if (u.index > cursor) out.push({ kind: "text", text: tail.slice(cursor, u.index) });
|
|
633
|
+
if (trimmed !== "") out.push({ kind: "link", text: trimmed, href: trimmed });
|
|
634
|
+
const rest = rawUrl.slice(trimmed.length);
|
|
635
|
+
if (rest !== "") out.push({ kind: "text", text: rest });
|
|
636
|
+
cursor = u.index + rawUrl.length;
|
|
637
|
+
}
|
|
638
|
+
if (cursor < tail.length) out.push({ kind: "text", text: tail.slice(cursor) });
|
|
639
|
+
return out;
|
|
640
|
+
};
|
|
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
|
+
|
|
556
678
|
const renderThread = (/** @type {any} */ thread, /** @type {number} */ index) => {
|
|
557
679
|
const expanded = activeId === thread.threadId;
|
|
558
680
|
return h(
|
|
@@ -592,7 +714,7 @@ window.__ModuleLoader__.load({
|
|
|
592
714
|
className: `dsh-btw-a${needsClamp && !isOpen ? " is-clamped" : ""}`,
|
|
593
715
|
"data-btw-answer": "true",
|
|
594
716
|
},
|
|
595
|
-
answerText,
|
|
717
|
+
renderAnswerBody(thread, answerText),
|
|
596
718
|
),
|
|
597
719
|
needsClamp
|
|
598
720
|
? h(
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 「追问待处理队列」:浮层想发起追问,但只能借 composer 提交一条命令
|
|
3
|
+
// (client 没有 commands 服务,真实 Agent 只能从命令上下文取 —— 见 ADR 0016)。
|
|
4
|
+
//
|
|
5
|
+
// 直接写 `/btw --thread t_xxx <问题>` 会把内部参数暴露在用户输入框里(实测被抱怨)。
|
|
6
|
+
// 改成:client 先把 {threadId, question, scope} 交给 host 暂存,再提交**裸 `/btw`**;
|
|
7
|
+
// host 处理命令时先查队列,取到就当追问处理,取不到才走「重开上一条」的老语义。
|
|
8
|
+
//
|
|
9
|
+
// 纯逻辑、不 import 宿主包,便于单测。
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* @typedef {{ threadId: string, question: string, scope: string, at: number }} PendingFollowUp
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 建一个按 sessionId 分槽的待处理队列。
|
|
17
|
+
*
|
|
18
|
+
* 单槽而非数组:同一个会话在任意时刻只会有一次「即将提交的追问」,
|
|
19
|
+
* 覆盖旧值比排队更符合实际(用户连点两次时后一次生效)。
|
|
20
|
+
* @param {{ ttlMs?: number, now?: () => number }} [options]
|
|
21
|
+
*/
|
|
22
|
+
export function createFollowUpQueue(options = {}) {
|
|
23
|
+
const ttlMs = Number(options.ttlMs) || 60_000;
|
|
24
|
+
const now = options.now ?? Date.now;
|
|
25
|
+
/** @type {Map<string, PendingFollowUp>} */
|
|
26
|
+
const slots = new Map();
|
|
27
|
+
return {
|
|
28
|
+
/**
|
|
29
|
+
* 登记一次待处理的追问。
|
|
30
|
+
* @param {string} sessionId
|
|
31
|
+
* @param {{ threadId: string, question: string, scope?: string }} input
|
|
32
|
+
* @returns {void}
|
|
33
|
+
*/
|
|
34
|
+
push(sessionId, input) {
|
|
35
|
+
const threadId = String(input?.threadId ?? "");
|
|
36
|
+
const question = String(input?.question ?? "");
|
|
37
|
+
if (sessionId === "" || threadId === "" || question === "") return;
|
|
38
|
+
slots.set(sessionId, {
|
|
39
|
+
threadId,
|
|
40
|
+
question,
|
|
41
|
+
scope: String(input?.scope ?? ""),
|
|
42
|
+
at: now(),
|
|
43
|
+
});
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 取出并清空(一次性)。过期的视为不存在。
|
|
48
|
+
* @param {string} sessionId
|
|
49
|
+
* @returns {PendingFollowUp | undefined}
|
|
50
|
+
*/
|
|
51
|
+
take(sessionId) {
|
|
52
|
+
const item = slots.get(sessionId);
|
|
53
|
+
if (item === undefined) return undefined;
|
|
54
|
+
slots.delete(sessionId);
|
|
55
|
+
if (now() - item.at > ttlMs) return undefined;
|
|
56
|
+
return item;
|
|
57
|
+
},
|
|
58
|
+
|
|
59
|
+
/** 诊断用。 */
|
|
60
|
+
size() {
|
|
61
|
+
return slots.size;
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
package/lib/service.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
6
6
|
import { renderBadge } from "./badge.js";
|
|
7
7
|
import { parseAllowedTools } from "./config.js";
|
|
8
|
+
import { createFollowUpQueue } from "./followup-queue.js";
|
|
8
9
|
import { appendRecord, lastRecord, listRecent } from "./history.js";
|
|
9
10
|
import { clip, LIMITS } from "./limits.js";
|
|
10
11
|
import { format, loadMessages, pickLanguage } from "./messages.js";
|
|
@@ -75,6 +76,8 @@ export class BtwService extends TypertRemoteService {
|
|
|
75
76
|
this.allowedTools = this.configAllowedTools;
|
|
76
77
|
this.language = pickLanguage(this.config?.language);
|
|
77
78
|
this.usageBySession = observeUsage(ctx);
|
|
79
|
+
// 浮层追问借 composer 提交裸 `/btw`,真实参数从这里取(见 followup-queue.js)。
|
|
80
|
+
this.followUps = createFollowUpQueue({});
|
|
78
81
|
/** @type {Record<string, string>} */
|
|
79
82
|
this.messages = FALLBACK;
|
|
80
83
|
// locale 加载(不阻塞激活)
|
|
@@ -131,9 +134,20 @@ export class BtwService extends TypertRemoteService {
|
|
|
131
134
|
const file = historyFile(this.dataRoot, agent?.id ?? "");
|
|
132
135
|
// 追问用 `/btw --thread <id> <问题>` 标记线程(见 threads.js 的 parseThreadFlag 说明)。
|
|
133
136
|
const parsed = parseCommandArgs(String(invocation?.rawInput ?? ""));
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
+
let threadId = parsed.threadId;
|
|
138
|
+
let scope = parsed.scope;
|
|
139
|
+
let rawQuestion = parsed.question;
|
|
140
|
+
// 裸 `/btw`(无参数)时先看有没有浮层登记的追问:
|
|
141
|
+
// 有就当追问处理,没有才走「重开上一条」的老语义。
|
|
142
|
+
if (threadId === "" && rawQuestion === "") {
|
|
143
|
+
const queued = this.followUps.take(String(agent?.id ?? ""));
|
|
144
|
+
if (queued !== undefined) {
|
|
145
|
+
threadId = queued.threadId;
|
|
146
|
+
scope = queued.scope;
|
|
147
|
+
rawQuestion = queued.question;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const question = clip(rawQuestion, LIMITS.questionChars);
|
|
137
151
|
|
|
138
152
|
if (question.text === "") {
|
|
139
153
|
const previous = await lastRecord(file).catch(() => undefined);
|
|
@@ -303,6 +317,22 @@ export class BtwService extends TypertRemoteService {
|
|
|
303
317
|
return lastRecord(historyFile(this.dataRoot, String(input.sessionId ?? "")));
|
|
304
318
|
}
|
|
305
319
|
|
|
320
|
+
/**
|
|
321
|
+
* 登记一次待处理的追问。client 在提交裸 `/btw` **之前**调用,
|
|
322
|
+
* 这样命令文本里不必出现 `--thread t_xxx`。
|
|
323
|
+
* @param {{ sessionId?: string, threadId?: string, question?: string, scope?: string } | undefined} request
|
|
324
|
+
* @returns {Promise<{ ok: boolean, size: number }>}
|
|
325
|
+
*/
|
|
326
|
+
async queueFollowUp(request) {
|
|
327
|
+
const input = request ?? {};
|
|
328
|
+
this.followUps.push(String(input.sessionId ?? ""), {
|
|
329
|
+
threadId: String(input.threadId ?? ""),
|
|
330
|
+
question: String(input.question ?? ""),
|
|
331
|
+
scope: String(input.scope ?? ""),
|
|
332
|
+
});
|
|
333
|
+
return { ok: true, size: this.followUps.size() };
|
|
334
|
+
}
|
|
335
|
+
|
|
306
336
|
/**
|
|
307
337
|
* 读当前设置(client 设置面板用)。
|
|
308
338
|
* @param {undefined} request 参数必须存在且是单一标识符(网关 SRC 校验)。
|
|
@@ -359,6 +389,7 @@ export class BtwService extends TypertRemoteService {
|
|
|
359
389
|
declareRemote(BtwService, "history");
|
|
360
390
|
declareRemote(BtwService, "last");
|
|
361
391
|
declareRemote(BtwService, "stats");
|
|
392
|
+
declareRemote(BtwService, "queueFollowUp");
|
|
362
393
|
declareRemote(BtwService, "threads");
|
|
363
394
|
declareRemote(BtwService, "promote");
|
|
364
395
|
declareRemote(BtwService, "settings");
|
package/lib/threads.js
CHANGED
|
@@ -113,40 +113,39 @@ export function renderPromoteDraft(record, options = {}) {
|
|
|
113
113
|
return text.length > maxChars ? `${text.slice(0, maxChars - 1)}…` : text;
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
-
/**
|
|
117
|
-
* 去掉常见 Markdown 标记,让文本适合直接放进输入框。
|
|
118
|
-
*
|
|
119
|
-
* 为什么必须做:实测用户点「转正」后,输入框里塞进来的是 `## 我问了什么`、
|
|
120
|
-
* `**每个 PR 上实际出现的检查是 8 个**`、`|---|` 这类源码,用户原话是
|
|
121
|
-
* 「为什么给我一堆井号和竖线?」。我们没有 Markdown 渲染器(ADR 0001 不引入构建),
|
|
122
|
-
* 所以草稿必须自己变成纯文本。
|
|
123
|
-
* @param {string} text
|
|
124
|
-
* @returns {string}
|
|
125
|
-
*/
|
|
126
116
|
/**
|
|
127
117
|
* 去掉常见 Markdown 标记,让文本适合直接阅读/放进输入框。
|
|
128
118
|
*
|
|
129
119
|
* @param {string} text
|
|
130
|
-
* @param {{ keepCode?: boolean }} [options]
|
|
131
|
-
*
|
|
120
|
+
* @param {{ keepCode?: boolean, keepFence?: boolean }} [options]
|
|
121
|
+
* - keepCode 默认 true:``` 围栏内的内容原样保留(代码缩进有意义)
|
|
122
|
+
* - keepFence 默认 false:true 时保留 ``` 围栏标记,供 client 识别代码块边界
|
|
132
123
|
* @returns {string}
|
|
133
124
|
*/
|
|
134
125
|
export function stripMarkdown(text, options = {}) {
|
|
135
126
|
const raw = String(text ?? "");
|
|
136
127
|
if (options.keepCode === false) return stripAllMarkdown(raw);
|
|
128
|
+
const keepFence = options.keepFence === true;
|
|
137
129
|
// 先把围栏块抽出占位,避免下面的标记清理破坏代码内容。
|
|
138
|
-
/** @type {string[]} */
|
|
130
|
+
/** @type {{ lang: string, body: string }[]} */
|
|
139
131
|
const fences = [];
|
|
140
132
|
const parked = raw.replace(
|
|
141
|
-
/```[a-zA-Z0-9_-]
|
|
142
|
-
(/** @type {string} */ _m, /** @type {string} */ body) => {
|
|
143
|
-
|
|
133
|
+
/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu,
|
|
134
|
+
(/** @type {string} */ _m, /** @type {string} */ lang, /** @type {string} */ body) => {
|
|
135
|
+
const fence = body.replace(/\n+$/u, "");
|
|
136
|
+
fences.push({ lang, body: fence });
|
|
144
137
|
return `@@BTWFENCE${fences.length - 1}@@`;
|
|
145
138
|
},
|
|
146
139
|
);
|
|
147
140
|
const cleaned = stripAllMarkdown(parked).replace(
|
|
148
141
|
/@@BTWFENCE(\d+)@@/gu,
|
|
149
|
-
(/** @type {string} */ _m, /** @type {string} */ i) =>
|
|
142
|
+
(/** @type {string} */ _m, /** @type {string} */ i) => {
|
|
143
|
+
const fence = fences[Number(i)];
|
|
144
|
+
if (fence === undefined) return "";
|
|
145
|
+
// keepFence 时保留 ``` 标记:client 靠它识别代码块边界,渲染成 <pre> 后
|
|
146
|
+
// 再把标记本身隐藏掉。默认关,转正草稿等纯文本场景不需要它。
|
|
147
|
+
return keepFence ? `\n\`\`\`${fence.lang}\n${fence.body}\n\`\`\`\n` : `\n${fence.body}\n`;
|
|
148
|
+
},
|
|
150
149
|
);
|
|
151
150
|
return cleaned.replace(/\n{3,}/gu, "\n\n").trim();
|
|
152
151
|
}
|
|
@@ -226,7 +225,7 @@ export function parseThreadFlag(raw) {
|
|
|
226
225
|
/**
|
|
227
226
|
* 线程列表(给浮层展示):按最后一条时间倒序,每项带条数与首问。
|
|
228
227
|
* @param {any[]} records
|
|
229
|
-
* @returns {{ threadId: string, turns: number, question: string, answer: string, answerPlain: string, lastId: string, cost: any, ms: number, at: number }[]}
|
|
228
|
+
* @returns {{ threadId: string, turns: number, question: string, answer: string, answerPlain: string, answerSegments: AnswerSegment[], lastId: string, cost: any, ms: number, at: number }[]}
|
|
230
229
|
*/
|
|
231
230
|
export function listThreads(records) {
|
|
232
231
|
return groupThreads(records)
|
|
@@ -238,6 +237,11 @@ export function listThreads(records) {
|
|
|
238
237
|
// 展示用:去掉 Markdown 噪音但保留代码块(列表里显示原文的话,用户看到的是
|
|
239
238
|
// `**粗体**`、`|表|格|`、`|---|`,实测被抱怨「为什么给我一堆井号和竖线」)。
|
|
240
239
|
answerPlain: stripMarkdown(String(thread.last?.answer ?? "")),
|
|
240
|
+
// 渲染用:切好的段(代码块 / 链接 / 文本)。解析只在这里做一份,
|
|
241
|
+
// client 只负责把 kind 映射成元素(classic script 无法 import 这个模块)。
|
|
242
|
+
answerSegments: parseRichSegments(
|
|
243
|
+
stripMarkdown(String(thread.last?.answer ?? ""), { keepFence: true }),
|
|
244
|
+
),
|
|
241
245
|
lastId: String(thread.last?.id ?? ""),
|
|
242
246
|
cost: thread.last?.cost ?? null,
|
|
243
247
|
ms: Number(thread.last?.ms ?? 0),
|
|
@@ -277,3 +281,67 @@ export function parseCommandArgs(raw) {
|
|
|
277
281
|
}
|
|
278
282
|
return { threadId, scope, question: rest.trim() };
|
|
279
283
|
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* @typedef {{ kind: "text", text: string }} TextSegment
|
|
287
|
+
* @typedef {{ kind: "code", lang: string, text: string }} CodeSegment
|
|
288
|
+
* @typedef {{ kind: "link", text: string, href: string }} LinkSegment
|
|
289
|
+
* @typedef {TextSegment | CodeSegment | LinkSegment} AnswerSegment
|
|
290
|
+
*/
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 把答案文本切成渲染段:代码块 / 链接 / 普通文本。
|
|
294
|
+
*
|
|
295
|
+
* 为什么需要它:`answerPlain` 保留了 ``` 围栏(`keepFence`),client 才能识别代码块边界,
|
|
296
|
+
* 把代码渲染成等宽 `<pre>` 而**不显示** ``` 本身;普通文本里的 URL 变成可点链接
|
|
297
|
+
* (之前答案里的链接是死文本)。
|
|
298
|
+
*
|
|
299
|
+
* 刻意**不做**完整 Markdown 渲染(表格/标题/粗体):仓库不引入构建步骤(ADR 0001),
|
|
300
|
+
* 手写完整渲染器的成本与风险远大于收益。粗体/表格已由 stripMarkdown 变成可读标点。
|
|
301
|
+
* @param {string} text
|
|
302
|
+
* @returns {AnswerSegment[]}
|
|
303
|
+
*/
|
|
304
|
+
export function parseRichSegments(text) {
|
|
305
|
+
const raw = String(text ?? "");
|
|
306
|
+
/** @type {AnswerSegment[]} */
|
|
307
|
+
const out = [];
|
|
308
|
+
// 1) 先按围栏切出代码块
|
|
309
|
+
const fenceRe = /```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/gu;
|
|
310
|
+
let last = 0;
|
|
311
|
+
for (;;) {
|
|
312
|
+
const match = fenceRe.exec(raw);
|
|
313
|
+
if (match === null) break;
|
|
314
|
+
if (match.index > last) out.push(...splitLinks(raw.slice(last, match.index)));
|
|
315
|
+
out.push({ kind: "code", lang: match[1] ?? "", text: (match[2] ?? "").replace(/\n+$/u, "") });
|
|
316
|
+
last = match.index + match[0].length;
|
|
317
|
+
}
|
|
318
|
+
if (last < raw.length) out.push(...splitLinks(raw.slice(last)));
|
|
319
|
+
return out.length > 0 ? out : [{ kind: "text", text: raw }];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* 把一段普通文本按 URL 切成 text/link 段。
|
|
324
|
+
* @param {string} text
|
|
325
|
+
* @returns {AnswerSegment[]}
|
|
326
|
+
*/
|
|
327
|
+
function splitLinks(text) {
|
|
328
|
+
/** @type {AnswerSegment[]} */
|
|
329
|
+
const out = [];
|
|
330
|
+
// 只认 http(s);末尾的标点(。,;:!?)】」)不属于 URL。
|
|
331
|
+
const urlRe = /https?:\/\/[^\s<>()\u3000-\u303f\uff00-\uffef]+/gu;
|
|
332
|
+
let last = 0;
|
|
333
|
+
for (;;) {
|
|
334
|
+
const match = urlRe.exec(text);
|
|
335
|
+
if (match === null) break;
|
|
336
|
+
const raw = match[0];
|
|
337
|
+
const trimmed = raw.replace(/[.,;:!?]+$/u, "");
|
|
338
|
+
if (match.index > last) out.push({ kind: "text", text: text.slice(last, match.index) });
|
|
339
|
+
if (trimmed !== "") out.push({ kind: "link", text: trimmed, href: trimmed });
|
|
340
|
+
const rest = raw.slice(trimmed.length);
|
|
341
|
+
if (rest !== "") out.push({ kind: "text", text: rest });
|
|
342
|
+
last = match.index + raw.length;
|
|
343
|
+
}
|
|
344
|
+
if (last < text.length) out.push({ kind: "text", text: text.slice(last) });
|
|
345
|
+
if (out.length === 0 && text !== "") out.push({ kind: "text", text });
|
|
346
|
+
return out;
|
|
347
|
+
}
|