mocode-ai 1.8.3 → 1.8.5
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 +1 -1
- package/README.zh-CN.md +2 -2
- package/dist/agent/work-discipline.js +18 -9
- package/dist/config/index.js +1 -1
- package/dist/repl/message-format.js +93 -3
- package/dist/skills/builtin-skills.js +1 -1
- package/dist/tools/builtins/ask-human.js +2 -1
- package/dist/ui/content.js +25 -22
- package/dist/ui/layout-internal/content-write.js +6 -6
- package/dist/ui/layout-internal/core.js +25 -0
- package/dist/ui/layout-internal/scroll.js +8 -0
- package/dist/ui/layout-internal/selection.js +2 -1
- package/dist/ui/layout-internal/state.js +2 -0
- package/dist/ui/markdown.js +218 -51
- package/dist/ui/render.js +110 -4
- package/dist/ui/theme.js +14 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -40,7 +40,7 @@ MoCode keeps code-level control light and leaves task strategy to the agent:
|
|
|
40
40
|
|
|
41
41
|
- **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
|
|
42
42
|
- **Bounded tool retries, explicit failures** — The runtime automatically retries only transient errors from tools explicitly marked `idempotent`, at most twice. `TIMEOUT`, permission denial, cancellation, and non-idempotent calls are not automatically retried. The resulting structured outcome is returned to the agent for any further recovery decision; see [Automatic retry](#automatic-retry-the-retryable-contract).
|
|
43
|
-
- **`ask_human` for user-owned decisions** — The agent
|
|
43
|
+
- **`ask_human` for user-owned decisions** — The agent must ask before any decision the user has not made (multiple reasonable approaches) and before key modifications (public APIs, schemas, dependencies, file moves/deletes, architecture, security, large or irreversible changes). Only trivial, repository-precedent details are decided alone.
|
|
44
44
|
- **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`) manage context pressure. Token estimation self-calibrates against provider usage.
|
|
45
45
|
|
|
46
46
|
## Architecture
|
package/README.zh-CN.md
CHANGED
|
@@ -92,14 +92,14 @@ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
|
|
|
92
92
|
|
|
93
93
|
- **建议式工作纪律** — system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
|
|
94
94
|
- **有界重试,明确报告失败** — runtime 仅对显式声明 `idempotent` 的工具瞬时错误自动重试,最多两次;`TIMEOUT`、权限拒绝、中断和非幂等调用不自动重试。最终结构化结果交给 agent,由其决定后续恢复方式,详见[自动重试](#自动重试retryable-契约)。
|
|
95
|
-
- **ask_human
|
|
95
|
+
- **ask_human 决策与关键修改先问** — 用户尚未做出的决策(存在多个合理方案)和关键修改(公共 API、schema、依赖、文件移动/删除、架构、安全、大范围或不可逆改动)必须先询问用户;只有符合仓库惯例的琐碎细节才由 agent 自行决定。
|
|
96
96
|
- **五区上下文控制 + token 自校准** — 独立旋钮管理上下文压力,token 估算根据真实 provider 用量校准。
|
|
97
97
|
|
|
98
98
|
## 为什么用 mocode
|
|
99
99
|
|
|
100
100
|
mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
|
|
101
101
|
|
|
102
|
-
- **自主多步推进** — 一次对话里连续多步:读代码、改代码、跑测试、根据报错再改……agent
|
|
102
|
+
- **自主多步推进** — 一次对话里连续多步:读代码、改代码、跑测试、根据报错再改……agent 自己决定下一步,中途不用你反复催。遇到决策点或关键修改会先调 `ask_human` 弹面板问你(阻塞到回应)。
|
|
103
103
|
- **能力感知并发** — 连续且声明支持并行的工具(如读文件、grep、glob、联网读取)可并发执行。按资源加锁的文件改动也可同时派发,由规范化资源锁协调冲突资源,而不是把所有写入全局串行化。进程类及未声明并行能力的工具保持各自的串行执行约束。
|
|
104
104
|
- **子 agent 分而治之** — 子任务拥有独立历史分支,工具权限不超过父 step 的能力上限;按并发上限分批运行,直接写入共享工作区并共用父级回滚轮次。主线接收最终摘要及执行元数据;没有每个 worker 独立的文件系统隔离或合并阶段。
|
|
105
105
|
- **计划 / 执行双模式** — `plan` 模式下探查并产出计划,不修改项目文件、不跑 shell 命令、不派生子 agent;内部会话和计划记录仍可持久化。`auto` 模式允许执行,但不是静态“全工具”模式:每个真实用户轮先由轻量 LLM router 选择最小充分工具簇,主模型需要时可在后续 step 追加能力。
|
|
@@ -32,20 +32,29 @@ const CORE_SECTION = `Use your judgment to choose the shortest reliable path fro
|
|
|
32
32
|
- Report honestly what you changed, what you checked, and anything left uncertain.
|
|
33
33
|
|
|
34
34
|
Never invent file paths, APIs, config keys, flags, or behavior. Distinguish repository evidence from assumptions.`;
|
|
35
|
-
/**
|
|
35
|
+
/**
|
|
36
|
+
* ASK-02: user decisions and key modifications are the user's call, not the agent's.
|
|
37
|
+
* The agent must call `ask_human` BEFORE acting; only trivial, reversible details may be decided alone.
|
|
38
|
+
*/
|
|
36
39
|
const ASK_WHITELIST_SECTION = `## When to ask instead of guess
|
|
37
40
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
41
|
+
The user owns every decision and every key change. NEVER decide these on your own: call \`ask_human\` FIRST, wait for the answer, then act. Asking is the default; acting alone is the exception.
|
|
42
|
+
|
|
43
|
+
Ask BEFORE acting when any of these applies:
|
|
44
|
+
1. A decision point: two or more reasonable approaches, designs, libraries, or behaviors exist and the user has not chosen one. Present the options with trade-offs and your recommendation; do not pick silently.
|
|
45
|
+
2. A key modification: changing public APIs, data formats, schemas, config semantics, or default behavior; adding, removing, or upgrading dependencies; renaming/moving/deleting files or modules; changing architecture or cross-module contracts; touching auth, permissions, security, or build/CI/release setup.
|
|
46
|
+
3. A broad or risky change: edits spanning many files, large refactors, anything hard to reverse, or any external side effect (push, deploy, network writes, data deletion/migration).
|
|
47
|
+
4. Scope growth: the work needs more than what the user asked for (extra features, unrelated fixes, behavior changes), or the request admits two or more materially different readings.
|
|
48
|
+
5. Evidence conflicts or gaps: repository evidence is missing, contradictory, or stale on something that changes the outcome.
|
|
49
|
+
6. A failed approach: the same approach failed twice and the next step is a different approach, tool, or tradeoff than the user agreed to.
|
|
50
|
+
|
|
51
|
+
For ambiguous or vague requests, load the \`brainstorming\` skill and clarify through a short dialogue (one question at a time) before starting work. For a key modification, state what will change, why, and the impact in \`question\`/\`context\`, offer a confirm / adjust / cancel style choice, and make no related edits until the user answers.
|
|
43
52
|
|
|
44
|
-
|
|
53
|
+
If the user cancels or answers "you decide", stop guessing: take the safest reversible option and state it. Do not repeat a question the user already answered.
|
|
45
54
|
|
|
46
|
-
|
|
55
|
+
Only these may be decided alone: naming and style that follow repository precedent, local implementation details inside an already-approved change, and read-only investigation. Disclose any assumption you made.
|
|
47
56
|
|
|
48
|
-
|
|
57
|
+
There is no per-turn cap on \`ask_human\`: ask as often as a decision genuinely requires, but batch related questions into one call instead of asking one trivial thing at a time. If \`ask_human\` is unavailable or no user can answer (non-interactive run), choose the safest reversible option, avoid the key modification if possible, and disclose it in the final reply.`;
|
|
49
58
|
/** Advisory guidance shared by main and sub-agents. */
|
|
50
59
|
export function buildWorkDisciplineSection(_modelFamily) {
|
|
51
60
|
return `${CORE_SECTION}\n\n${ASK_WHITELIST_SECTION}`;
|
package/dist/config/index.js
CHANGED
|
@@ -144,7 +144,7 @@ const DEFAULT_VOICE = `## Voice
|
|
|
144
144
|
- Give technical recommendations with brief trade-off reasoning when choices exist.
|
|
145
145
|
- Focus on useful information. Avoid unnecessary greetings, apologies, repetition, or filler.
|
|
146
146
|
- Match the user's style and language while staying task-focused.
|
|
147
|
-
- Disclose assumptions;
|
|
147
|
+
- Disclose assumptions; decisions and key modifications belong to the user, so ask first (see When to ask instead of guess).`;
|
|
148
148
|
/** 解析用户自定义声音:persona.md 文件优先(项目级 > 全局),其次 env MOCODE_PERSONA。无则返回 ''。 */
|
|
149
149
|
function readPersonaFile() {
|
|
150
150
|
const candidates = [
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
1
2
|
import { ui } from '../ui/theme.js';
|
|
3
|
+
import { renderFileChange, renderMultiFileChange } from '../ui/diff.js';
|
|
4
|
+
import { isToolErrorOutput } from '../tools/result.js';
|
|
5
|
+
import { jailResolve } from '../sandbox/index.js';
|
|
2
6
|
import * as layout from '../ui/layout.js';
|
|
3
7
|
import * as batch from '../ui/batch.js';
|
|
4
8
|
import { displayWidth, padEndDisplay, summarizeToolCall, summarizeToolResult } from '../ui/render.js';
|
|
@@ -25,6 +29,84 @@ export function formatUserMessage(lines, trailingBlank = true) {
|
|
|
25
29
|
})
|
|
26
30
|
.join('\n') + (trailingBlank ? '\n\n' : '\n'));
|
|
27
31
|
}
|
|
32
|
+
const toLf = (s) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
|
33
|
+
/** 回放用的行号定位:在**当前**文件里找 text 的唯一命中行(edit 已落盘,找新文本);找不到/不唯一退回 1。 */
|
|
34
|
+
function locateLine(filePath, text) {
|
|
35
|
+
if (!text)
|
|
36
|
+
return 1;
|
|
37
|
+
try {
|
|
38
|
+
const data = toLf(readFileSync(jailResolve(filePath), 'utf8'));
|
|
39
|
+
const needle = toLf(text);
|
|
40
|
+
const first = data.indexOf(needle);
|
|
41
|
+
if (first < 0 || data.indexOf(needle, first + needle.length) !== -1)
|
|
42
|
+
return 1;
|
|
43
|
+
return data.slice(0, first).split('\n').length;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return 1;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* 由历史里的工具参数重建 edit_file/write_file 的 diff 块(回放时自动展开用)。
|
|
51
|
+
* history 只存参数不存执行前快照,所以是尽力还原:
|
|
52
|
+
* - write_file 无旧内容 → 按 Create 展示全部为新增行;
|
|
53
|
+
* - edit_file 行号在当前文件里按新文本定位,定位不到退回相对行号 1;
|
|
54
|
+
* - 行号区间模式(无 old_string)、失败结果、参数非法 → 返回 null,退回单行摘要。
|
|
55
|
+
*/
|
|
56
|
+
export function buildReplayDiff(name, rawArgs, output) {
|
|
57
|
+
if (isToolErrorOutput(output))
|
|
58
|
+
return null;
|
|
59
|
+
let parsed;
|
|
60
|
+
try {
|
|
61
|
+
const v = JSON.parse(rawArgs);
|
|
62
|
+
if (!v || typeof v !== 'object')
|
|
63
|
+
return null;
|
|
64
|
+
parsed = v;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
const filePath = String(parsed.path ?? '');
|
|
70
|
+
if (!filePath)
|
|
71
|
+
return null;
|
|
72
|
+
if (name === 'write_file') {
|
|
73
|
+
if (typeof parsed.content !== 'string')
|
|
74
|
+
return null;
|
|
75
|
+
return renderFileChange({ path: filePath, kind: 'write', oldStr: null, newStr: parsed.content, startLine: 1 });
|
|
76
|
+
}
|
|
77
|
+
if (name !== 'edit_file')
|
|
78
|
+
return null;
|
|
79
|
+
if (Array.isArray(parsed.replacements) && parsed.replacements.length > 0) {
|
|
80
|
+
const hunks = [];
|
|
81
|
+
for (const item of parsed.replacements) {
|
|
82
|
+
const rec = item;
|
|
83
|
+
if (!rec || typeof rec.old_string !== 'string' || typeof rec.new_string !== 'string')
|
|
84
|
+
return null;
|
|
85
|
+
hunks.push({
|
|
86
|
+
oldStr: rec.old_string,
|
|
87
|
+
newStr: rec.new_string,
|
|
88
|
+
startLine: locateLine(filePath, rec.new_string),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return (renderMultiFileChange({ path: filePath, hunks }) ??
|
|
92
|
+
renderFileChange({
|
|
93
|
+
path: filePath,
|
|
94
|
+
kind: 'edit',
|
|
95
|
+
oldStr: hunks.map((h) => h.oldStr).join('\n'),
|
|
96
|
+
newStr: hunks.map((h) => h.newStr).join('\n'),
|
|
97
|
+
startLine: hunks[0].startLine,
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
if (typeof parsed.old_string !== 'string' || typeof parsed.new_string !== 'string')
|
|
101
|
+
return null;
|
|
102
|
+
return renderFileChange({
|
|
103
|
+
path: filePath,
|
|
104
|
+
kind: 'edit',
|
|
105
|
+
oldStr: parsed.old_string,
|
|
106
|
+
newStr: parsed.new_string,
|
|
107
|
+
startLine: locateLine(filePath, parsed.new_string),
|
|
108
|
+
});
|
|
109
|
+
}
|
|
28
110
|
/** 把任意消息 content 拍平成字符串(OpenAI 可能 string / null / 多模态数组)。 */
|
|
29
111
|
export function textOf(c) {
|
|
30
112
|
if (typeof c === 'string')
|
|
@@ -58,6 +140,7 @@ export function queryHistoryFromMessages(messages) {
|
|
|
58
140
|
*/
|
|
59
141
|
export function renderHistory(history) {
|
|
60
142
|
const idToEntry = new Map();
|
|
143
|
+
const idToArgs = new Map(); // tool_call id → 原始参数 JSON,供重建 mutation diff
|
|
61
144
|
// 普通工具可跨 assistant 步聚合;mutation 各自占一个 group,并切断前后普通工具。
|
|
62
145
|
let pendingBatches = [];
|
|
63
146
|
let normalBatch = null;
|
|
@@ -95,6 +178,9 @@ export function renderHistory(history) {
|
|
|
95
178
|
}
|
|
96
179
|
if (m.role === 'user') {
|
|
97
180
|
flushBatch(); // 上一轮 batch(若有)收尾
|
|
181
|
+
// 上一条 agent 正文 → 本条用户气泡:contentWriteMdOnce 会裁掉 markdown 尾部空行,
|
|
182
|
+
// 不归一的话气泡紧贴正文(实时对话由 REPL 循环顶部的 normalizeInputBoundary 保证恰好 1 条空行)。
|
|
183
|
+
layout.normalizeInputBoundary();
|
|
98
184
|
const lines = textOf(m.content).split('\n');
|
|
99
185
|
layout.contentWrite(formatUserMessage(lines));
|
|
100
186
|
const atts = messageAttachments.get(idx);
|
|
@@ -151,8 +237,10 @@ export function renderHistory(history) {
|
|
|
151
237
|
}
|
|
152
238
|
normalBatch.push(entry);
|
|
153
239
|
}
|
|
154
|
-
if (tc?.id)
|
|
240
|
+
if (tc?.id) {
|
|
155
241
|
idToEntry.set(tc.id, entry);
|
|
242
|
+
idToArgs.set(tc.id, args);
|
|
243
|
+
}
|
|
156
244
|
}
|
|
157
245
|
continue; // 跳过后续 tool 消息处理循环(由下一分支填 result)
|
|
158
246
|
}
|
|
@@ -165,9 +253,11 @@ export function renderHistory(history) {
|
|
|
165
253
|
const target = idToEntry.get(id);
|
|
166
254
|
const name = target?.name ?? '';
|
|
167
255
|
const output = textOf(m.content);
|
|
168
|
-
const preview = summarizeToolResult(name, output);
|
|
169
256
|
if (target) {
|
|
170
|
-
|
|
257
|
+
// mutation 成功:重建 diff 块,回放时自动展开(与实时一致);否则退回单行摘要。
|
|
258
|
+
const diff = batch.isMutationToolName(name) ? buildReplayDiff(name, idToArgs.get(id) ?? '', output) : null;
|
|
259
|
+
target.diffBlock = diff;
|
|
260
|
+
target.resultSummary = diff ? '' : summarizeToolResult(name, output);
|
|
171
261
|
target.fullOutput = output;
|
|
172
262
|
}
|
|
173
263
|
// 不直接写屏——等 flushBatch 时出单行摘要
|
|
@@ -72,7 +72,7 @@ const BRAINSTORM_BODY = `# Brainstorming(需求澄清)
|
|
|
72
72
|
|
|
73
73
|
## 边界
|
|
74
74
|
|
|
75
|
-
-
|
|
75
|
+
- ask_human 没有次数上限,但每个问题必须实质推进理解、相关问题合并提问;用户明确说「你决定」时,取最安全的可逆默认并说明。
|
|
76
76
|
- 用户取消:停止,不要按自己的猜测继续。
|
|
77
77
|
- 问题与方案用用户的语言。
|
|
78
78
|
- 澄清期间保持只读:不改文件、不跑有副作用的命令。
|
|
@@ -113,7 +113,8 @@ export const askHumanTool = {
|
|
|
113
113
|
'Ask the user a question and wait for their response.',
|
|
114
114
|
' CHOICES: pass 2-4 concrete options via `options`, each as { label, description? }; every non-empty option requires a non-empty `label`.',
|
|
115
115
|
' FREE-TEXT: pass `options: []` when the answer cannot be reduced to choices (e.g. "paste the error message").',
|
|
116
|
-
'
|
|
116
|
+
' MUST call BEFORE any decision the user has not made (multiple reasonable approaches) or any key modification (public API, schema, dependencies, file moves/deletes, architecture, security, large or irreversible changes); never decide these yourself.',
|
|
117
|
+
' Skip only for trivial details that follow repository precedent and are easily reversible.',
|
|
117
118
|
].join(' '),
|
|
118
119
|
parameters: {
|
|
119
120
|
type: 'object',
|
package/dist/ui/content.js
CHANGED
|
@@ -1,23 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 内容物理行缓冲(Phase 2 滚动回滚用)。
|
|
3
|
-
*
|
|
4
|
-
* 存折行后的物理行,每行自洽带色,供 layout.repaintViewport 单行直出、无需继承 SGR 状态。
|
|
5
|
-
* contentWrite 逐字符喂入(feedChar / feedSgr / breakRow);setLines 替换当前段(md 流式渲染用)。
|
|
6
|
-
* markdown 段额外保留未折行 source,终端列宽变化时可重新渲染对应物理行;普通行仍沿用原模型。
|
|
7
|
-
*
|
|
8
|
-
* **SGR 自洽模型**:每行存 `rowStartSgr + curRaw + \x1B[0m`:
|
|
9
|
-
* - rowStartSgr:本行起始时继承的活跃 SGR 前缀(来自上一行末状态);
|
|
10
|
-
* - curRaw:本行原始字节——可见字符 + 行内出现的 SGR 码(保留行内开合,如 `${dim}ab${reset}cd`);
|
|
11
|
-
* - 末尾 reset:使单行渲染不依赖后续。
|
|
12
|
-
* 这样行内 SGR 变化与跨行继承都正确——简单"前缀+可见文本"模型会丢行内开合的色。
|
|
13
|
-
*
|
|
14
|
-
* **当前行**:任何 feedChar/feedSgr/breakRow 后 hasCurrent=true;breakRow(\n/折行)提交本行并开新空行
|
|
15
|
-
* (hasCurrent 仍 true,代表光标所在的新空行)。这让 offset=0 的 viewport 重画与实时屏严格一致
|
|
16
|
-
* (含 \n 后的光标空行),避免回尾时内容错位。
|
|
17
|
-
*
|
|
18
|
-
* 主题(theme.ts)只用单参数 SGR 码,故 curSgr 状态机简单:遇 \x1B[0m / \x1B[m 清空,其余累加。
|
|
19
|
-
* 上限 20000 行防无限增长(超限丢头部,批量 trim)。
|
|
20
|
-
*/
|
|
21
1
|
const MAX_ROWS = 20000;
|
|
22
2
|
let rows = [];
|
|
23
3
|
let curSgr = ''; // 当前活跃 SGR 状态(行内演进;行末值 = 下行继承值)
|
|
@@ -165,7 +145,7 @@ export function beginSegment() {
|
|
|
165
145
|
* 行须各自自洽(行内 SGR 自带、行末 reset)——不经 feedChar/feedSgr,直接入 rows,
|
|
166
146
|
* 故 setLines 后 hasCurrent=false(snapshot 只返 rows;续写位由 layout 跟踪)。
|
|
167
147
|
*/
|
|
168
|
-
export function setLines(lines, source) {
|
|
148
|
+
export function setLines(lines, source, codeBlocks) {
|
|
169
149
|
if (segMark) {
|
|
170
150
|
rows.length = segMark.rowIdx;
|
|
171
151
|
}
|
|
@@ -179,6 +159,7 @@ export function setLines(lines, source) {
|
|
|
179
159
|
segment.rowCount = lines.length;
|
|
180
160
|
if (source !== undefined)
|
|
181
161
|
segment.source = source;
|
|
162
|
+
segment.codeBlocks = codeBlocks;
|
|
182
163
|
}
|
|
183
164
|
}
|
|
184
165
|
trimRows();
|
|
@@ -202,7 +183,9 @@ export function reflowMarkdown(cols, render) {
|
|
|
202
183
|
const start = Math.max(0, Math.min(rows.length, segment.start));
|
|
203
184
|
const oldCount = Math.max(0, Math.min(segment.rowCount, rows.length - start));
|
|
204
185
|
const oldLines = rows.slice(start, start + oldCount);
|
|
205
|
-
const
|
|
186
|
+
const rendered = render(segment.source, width);
|
|
187
|
+
const next = Array.isArray(rendered) ? rendered : rendered.lines;
|
|
188
|
+
segment.codeBlocks = Array.isArray(rendered) ? [] : rendered.codeBlocks;
|
|
206
189
|
rows.splice(start, oldCount, ...next);
|
|
207
190
|
const delta = next.length - oldCount;
|
|
208
191
|
segment.start = start;
|
|
@@ -308,6 +291,26 @@ export function lineAt(abs) {
|
|
|
308
291
|
const all = snapshot();
|
|
309
292
|
return abs >= 0 && abs < all.length ? all[abs] : null;
|
|
310
293
|
}
|
|
294
|
+
/** 命中某个代码块的复制按钮时返回其原文、header 绝对行与按钮显示列区间,否则 null。col 为 0-based 显示列。 */
|
|
295
|
+
export function codeBlockCopyAt(absLine, col) {
|
|
296
|
+
for (const segment of reflowSegments) {
|
|
297
|
+
const rel = absLine - segment.start;
|
|
298
|
+
for (const block of segment.codeBlocks ?? []) {
|
|
299
|
+
if (rel === block.headerLine &&
|
|
300
|
+
block.buttonColStart >= 0 &&
|
|
301
|
+
col >= block.buttonColStart &&
|
|
302
|
+
col < block.buttonColEnd) {
|
|
303
|
+
return {
|
|
304
|
+
code: block.code,
|
|
305
|
+
headerAbs: segment.start + block.headerLine,
|
|
306
|
+
colStart: block.buttonColStart,
|
|
307
|
+
colEnd: block.buttonColEnd,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
311
314
|
/** 等长替换一条已提交物理行,供运行中的工具 batch 原地刷新摘要。 */
|
|
312
315
|
export function replaceLine(abs, line) {
|
|
313
316
|
if (abs < 0 || abs >= rows.length)
|
|
@@ -5,7 +5,7 @@ import { charWidth, truncateAnsi, ansiDisplayWidth, remapWrappedPoint } from '..
|
|
|
5
5
|
import { ui } from '../theme.js';
|
|
6
6
|
import * as content from '../content.js';
|
|
7
7
|
import { reset as resetBatches, shiftBatchesAfter, shiftBatchesForReflow } from '../batch.js';
|
|
8
|
-
import {
|
|
8
|
+
import { renderMarkdownWithMeta } from '../markdown.js';
|
|
9
9
|
import { state } from './state.js';
|
|
10
10
|
import { esc, cup, getGeo, setRegion, runningCaretPos } from './screen.js';
|
|
11
11
|
import { viewportAbsStart, repaintViewport } from './scroll.js';
|
|
@@ -304,8 +304,8 @@ function renderMdSegment() {
|
|
|
304
304
|
// offset += delta(可负:setLines 重渲染可能缩行)冻住视图。md 段在尾,窗口在上方,冻结后不重叠。
|
|
305
305
|
const scrolled = state.scrollOffset > 0;
|
|
306
306
|
const totalBefore = scrolled ? content.totalRows() : 0;
|
|
307
|
-
const lines =
|
|
308
|
-
content.setLines(lines, state.mdBuf);
|
|
307
|
+
const { lines, codeBlocks } = renderMarkdownWithMeta(state.mdBuf, g.cols);
|
|
308
|
+
content.setLines(lines, state.mdBuf, codeBlocks);
|
|
309
309
|
state.mdRenderedLen = state.mdBuf.length;
|
|
310
310
|
const segRows = lines.length;
|
|
311
311
|
const available = g.contentBottom - state.segmentStartRow + 1;
|
|
@@ -410,8 +410,8 @@ export function contentWriteMdOnce(s) {
|
|
|
410
410
|
commitMd();
|
|
411
411
|
const g = getGeo();
|
|
412
412
|
content.beginSegment();
|
|
413
|
-
const lines =
|
|
414
|
-
content.setLines(lines, s);
|
|
413
|
+
const { lines, codeBlocks } = renderMarkdownWithMeta(s, g.cols);
|
|
414
|
+
content.setLines(lines, s, codeBlocks);
|
|
415
415
|
content.commitSegment();
|
|
416
416
|
// setLines 直接提交了全部 markdown 物理行;补回一个未提交的空当前行,保证满屏时
|
|
417
417
|
// 下一次 contentWrite 从正文下一行开始,而不是在 contentBottom 第 1 列覆盖正文末行。
|
|
@@ -821,7 +821,7 @@ export function reflowContentForResize(cols, colsChanged) {
|
|
|
821
821
|
const welcomeChange = reflowWelcomeBlockForResize(cols);
|
|
822
822
|
if (welcomeChange)
|
|
823
823
|
changes.push(welcomeChange);
|
|
824
|
-
changes.push(...content.reflowMarkdown(cols,
|
|
824
|
+
changes.push(...content.reflowMarkdown(cols, renderMarkdownWithMeta));
|
|
825
825
|
}
|
|
826
826
|
for (const change of changes) {
|
|
827
827
|
shiftBatchesForReflow(change.start, change.oldCount, change.newCount);
|
|
@@ -356,8 +356,33 @@ function handleMouseEvent(e) {
|
|
|
356
356
|
// 内容区纯点击(未拖动):若落在工具 batch 摘要行上 → 切换展开/折叠;
|
|
357
357
|
// 否则原行为:清选区。batch 反查通过 content lineAt + dynamic import(避免 layout↔batch 循环依赖)。
|
|
358
358
|
const absClick = state.selection.anchorLine; // 起止同行同列,取任一;未拖动时 line = anchor = end
|
|
359
|
+
const colClick = state.selection.anchorCol;
|
|
359
360
|
void (async () => {
|
|
360
361
|
try {
|
|
362
|
+
// 代码块复制按钮:命中 header 右侧「复制」即把代码原文写剪贴板(优先于选区/batch 展开)。
|
|
363
|
+
const copyHit = content.codeBlockCopyAt(absClick, colClick);
|
|
364
|
+
if (copyHit) {
|
|
365
|
+
state.selection = null;
|
|
366
|
+
copyToClipboard(copyHit.code);
|
|
367
|
+
// 按钮瞬时反白反馈 900ms(纯视觉覆盖,不改缓冲,不依赖剪贴板成败回执)。
|
|
368
|
+
const flash = {
|
|
369
|
+
absLine: copyHit.headerAbs,
|
|
370
|
+
colStart: copyHit.colStart,
|
|
371
|
+
colEnd: copyHit.colEnd,
|
|
372
|
+
until: Date.now() + 900,
|
|
373
|
+
};
|
|
374
|
+
state.copyFlash = flash;
|
|
375
|
+
repaintViewport();
|
|
376
|
+
setTimeout(() => {
|
|
377
|
+
// 连点时只清自己那次闪烁,不误清后一次。
|
|
378
|
+
if (state.copyFlash !== flash)
|
|
379
|
+
return;
|
|
380
|
+
state.copyFlash = null;
|
|
381
|
+
repaintViewport();
|
|
382
|
+
}, 900).unref?.();
|
|
383
|
+
repaint();
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
361
386
|
const m = await import('../batch.js');
|
|
362
387
|
const entry = m.findEntryByAbsLine(absClick);
|
|
363
388
|
if (entry) {
|
|
@@ -118,6 +118,14 @@ export function repaintViewport() {
|
|
|
118
118
|
line = highlightRange(line, colStart, colEnd);
|
|
119
119
|
}
|
|
120
120
|
}
|
|
121
|
+
// 代码块「复制」按钮点击反馈:超时则清除(纯视觉,不改缓冲)。复用选区反白样式。
|
|
122
|
+
if (state.copyFlash) {
|
|
123
|
+
if (Date.now() >= state.copyFlash.until)
|
|
124
|
+
state.copyFlash = null;
|
|
125
|
+
else if (state.copyFlash.absLine === absStart + r - 1) {
|
|
126
|
+
line = highlightRange(line, state.copyFlash.colStart, state.copyFlash.colEnd);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
121
129
|
p += cup(r, 1) + esc.clearLine + line;
|
|
122
130
|
}
|
|
123
131
|
// 光标:合并进同一 write(若拆成两次 stdout.write,行写完光标会暂留 contentRow/contentBottom,
|
|
@@ -70,7 +70,8 @@ export function extractSelectionText(sel) {
|
|
|
70
70
|
const lineW = displayWidth(plain);
|
|
71
71
|
const colStart = abs === sel.startLine ? sel.startCol : 0;
|
|
72
72
|
const colEnd = abs === sel.endLine ? sel.endCol : lineW;
|
|
73
|
-
|
|
73
|
+
// 去行尾空白:代码块整块铺底色时每行补满到列宽,不剥会把补位空格一起复制出去。
|
|
74
|
+
out.push(sliceByDisplayCol(plain, colStart, colEnd).trimEnd());
|
|
74
75
|
}
|
|
75
76
|
return out.join('\n');
|
|
76
77
|
}
|
|
@@ -106,4 +106,6 @@ export const state = {
|
|
|
106
106
|
/** 覆盖层自报的真光标位(1-based 屏坐标;null = 未报/光标不在可视区)。overlay 期间 drawStatusBar
|
|
107
107
|
* 照常刷底栏,但末尾 cup 回这里而非 runningCaretPos,防 80ms 心跳把弹窗光标拽到底栏输入框。 */
|
|
108
108
|
overlayCaret: null,
|
|
109
|
+
// ── 代码块「复制」按钮点击反馈(瞬时反白,不改缓冲;超时后随下次 repaintViewport 自然消失) ──
|
|
110
|
+
copyFlash: null,
|
|
109
111
|
};
|
package/dist/ui/markdown.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// clipAnsiLine 兜底,绝不溢出。颜色一律嵌入式 ANSI(ui.*)写进字符串。
|
|
14
14
|
import { getCliHighlight } from './cli-highlight-lazy.js';
|
|
15
15
|
import { ui, getThemeVersion } from './theme.js';
|
|
16
|
-
import {
|
|
16
|
+
import { graphemeAt, displayWidth, ansiDisplayWidth, stripAnsi } from './render.js';
|
|
17
17
|
const RESET = '\x1b[0m';
|
|
18
18
|
// theme 无 italic/strike,自备(TTY 感知:!isTTY 退化为空串,同 ui.* 契约)。
|
|
19
19
|
const ITALIC = ui.isTTY ? '\x1b[3m' : '';
|
|
@@ -34,13 +34,16 @@ function clipAnsiLine(str, width) {
|
|
|
34
34
|
out += parts[i];
|
|
35
35
|
continue;
|
|
36
36
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
37
|
+
const seg = parts[i];
|
|
38
|
+
for (let gi = 0; gi < seg.length;) {
|
|
39
|
+
const g = graphemeAt(seg, gi);
|
|
40
|
+
const ch = seg.slice(gi, g.end);
|
|
41
|
+
gi = g.end;
|
|
42
|
+
if (g.width > 0 && w + g.width > width) {
|
|
40
43
|
return out + RESET;
|
|
41
44
|
}
|
|
42
|
-
if (
|
|
43
|
-
w +=
|
|
45
|
+
if (g.width > 0)
|
|
46
|
+
w += g.width;
|
|
44
47
|
out += ch;
|
|
45
48
|
}
|
|
46
49
|
}
|
|
@@ -262,8 +265,11 @@ function wrapAnsiString(str, width) {
|
|
|
262
265
|
activeSgr += tok;
|
|
263
266
|
continue;
|
|
264
267
|
}
|
|
265
|
-
for (
|
|
266
|
-
const
|
|
268
|
+
for (let gi = 0; gi < tok.length;) {
|
|
269
|
+
const g = graphemeAt(tok, gi);
|
|
270
|
+
const ch = tok.slice(gi, g.end);
|
|
271
|
+
gi = g.end;
|
|
272
|
+
const cw = g.width;
|
|
267
273
|
if (cw <= 0) {
|
|
268
274
|
cur += ch;
|
|
269
275
|
continue;
|
|
@@ -311,9 +317,41 @@ function parseTableRow(line) {
|
|
|
311
317
|
let s = line.trim();
|
|
312
318
|
if (s.startsWith('|'))
|
|
313
319
|
s = s.slice(1);
|
|
314
|
-
|
|
320
|
+
// 末尾 | 只有在未被转义时才是边框(`a \|` 结尾的 \| 是单元格内容)
|
|
321
|
+
if (s.endsWith('|') && !s.endsWith('\\|'))
|
|
315
322
|
s = s.slice(0, -1);
|
|
316
|
-
|
|
323
|
+
// 按「未转义、且不在行内代码里」的 | 切分;\| 还原成 |(GFM 规则:转义管道符在代码里也生效)
|
|
324
|
+
const cells = [];
|
|
325
|
+
let cur = '';
|
|
326
|
+
let ticks = 0; // 当前打开的行内代码反引号数(0 = 不在代码里)
|
|
327
|
+
for (let k = 0; k < s.length; k++) {
|
|
328
|
+
const ch = s[k];
|
|
329
|
+
if (ch === '\\' && s[k + 1] === '|') {
|
|
330
|
+
cur += '|';
|
|
331
|
+
k++;
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
if (ch === '`') {
|
|
335
|
+
let run = 1;
|
|
336
|
+
while (s[k + run] === '`')
|
|
337
|
+
run++;
|
|
338
|
+
if (ticks === 0)
|
|
339
|
+
ticks = run;
|
|
340
|
+
else if (ticks === run)
|
|
341
|
+
ticks = 0;
|
|
342
|
+
cur += '`'.repeat(run);
|
|
343
|
+
k += run - 1;
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (ch === '|' && ticks === 0) {
|
|
347
|
+
cells.push(cur.trim());
|
|
348
|
+
cur = '';
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
cur += ch;
|
|
352
|
+
}
|
|
353
|
+
cells.push(cur.trim());
|
|
354
|
+
return cells;
|
|
317
355
|
}
|
|
318
356
|
/** 分隔行每 cell :?-+:? → 对齐(left 默认)。 */
|
|
319
357
|
function parseAlign(sep) {
|
|
@@ -324,6 +362,33 @@ function parseAlign(sep) {
|
|
|
324
362
|
return l && r ? 'center' : r ? 'right' : 'left';
|
|
325
363
|
});
|
|
326
364
|
}
|
|
365
|
+
/**
|
|
366
|
+
* 宽容匹配 GFM 表格:src[i] 为表头、src[i+1] 为分隔行。
|
|
367
|
+
* 分隔行本身带 |、每格只含 `-` 与 `:`、至少一格含 `-` 即可(模型常写出列数与表头不一致的分隔行、
|
|
368
|
+
* 漏写竖线的粘连格 `--:----:`、单列表格);列数以表头为准,缺的列按左对齐。
|
|
369
|
+
* 不带 | 的 `---`(hr / setext)与 `~ | ==` 等非法写法返回 null,仍走普通文本。
|
|
370
|
+
* 数据行读到空行或不含 | 的行为止。next 为表格后第一行的下标。
|
|
371
|
+
*/
|
|
372
|
+
function matchTable(src, i) {
|
|
373
|
+
if (i + 1 >= src.length || !src[i].includes('|') || !src[i + 1].includes('|'))
|
|
374
|
+
return null;
|
|
375
|
+
const header = parseTableRow(src[i]);
|
|
376
|
+
const sepCells = parseTableRow(src[i + 1]);
|
|
377
|
+
if (header.length < 1)
|
|
378
|
+
return null;
|
|
379
|
+
if (!sepCells.some((c) => c.includes('-')) || !sepCells.every((c) => /^[:-]+$/.test(c)))
|
|
380
|
+
return null;
|
|
381
|
+
const rows = [];
|
|
382
|
+
let j = i + 2;
|
|
383
|
+
while (j < src.length) {
|
|
384
|
+
const r = src[j];
|
|
385
|
+
if (r.trim() === '' || !r.includes('|'))
|
|
386
|
+
break;
|
|
387
|
+
rows.push(parseTableRow(r));
|
|
388
|
+
j++;
|
|
389
|
+
}
|
|
390
|
+
return { header, aligns: parseAlign(sepCells), rows, next: j };
|
|
391
|
+
}
|
|
327
392
|
/** ANSI 感知按可见宽度 pad(左/右/中),补空格;不截断(超宽原样返回,由 clipAnsiLine 兜底)。 */
|
|
328
393
|
function padAnsi(str, width, align) {
|
|
329
394
|
const w = ansiDisplayWidth(str);
|
|
@@ -406,10 +471,14 @@ const MEMO = new Map();
|
|
|
406
471
|
const MEMO_CAP = 16;
|
|
407
472
|
function renderMarkdownImpl(text, cols) {
|
|
408
473
|
const out = [];
|
|
409
|
-
const
|
|
474
|
+
const codeBlocks = [];
|
|
475
|
+
const src = text.split(/\r?\n/); // 兼容 CRLF:否则行尾 \r 让 fence 正则失配、整块不识别
|
|
410
476
|
let i = 0;
|
|
411
477
|
let inFence = false;
|
|
412
478
|
let fenceChar = '';
|
|
479
|
+
let fenceLen = 0; // 开栏围栏长度:闭合栏须 ≥ 此长度(CommonMark),4 反引号外层可安全包住 3 反引号示例
|
|
480
|
+
let fenceDepth = 0; // 同长度带语言标注的嵌套开栏深度(3 反引号外层包 ```ts 示例的常见写法)
|
|
481
|
+
let fenceIndent = 0; // 开栏缩进(列表项内的围栏):复制原文时按 CommonMark 剥掉这层缩进
|
|
413
482
|
let lang = '';
|
|
414
483
|
let codeBuf = [];
|
|
415
484
|
let para = [];
|
|
@@ -425,17 +494,61 @@ function renderMarkdownImpl(text, cols) {
|
|
|
425
494
|
para = [];
|
|
426
495
|
prevBlank = true;
|
|
427
496
|
};
|
|
497
|
+
// 代码块整块铺 codeBg 底色(header + 代码行补满到 cols),与正文区分出「可复制区」。
|
|
498
|
+
// 非 TTY(codeBg 为空串)退化为无底色、不补尾随空格。文本内的 reset 之后重开底色,防高亮 SGR 打断。
|
|
499
|
+
const paintCodeRow = (text) => {
|
|
500
|
+
const bg = ui.codeBg;
|
|
501
|
+
const body = clipAnsiLine(text, cols);
|
|
502
|
+
if (!bg)
|
|
503
|
+
return body;
|
|
504
|
+
const pad = Math.max(0, cols - ansiDisplayWidth(body));
|
|
505
|
+
return `${bg}${body.split(RESET).join(RESET + bg)}${' '.repeat(pad)}${RESET}`;
|
|
506
|
+
};
|
|
507
|
+
// header 行:左侧 dim 语言标签(始终保留这行以承载按钮),右端 accent 复制图标 ` ❐ `(两侧各留 1 格扩大点击面)。
|
|
508
|
+
// 窄窗放不下按钮时只画标签,buttonCol=-1 表示不可点。
|
|
509
|
+
const COPY_BTN = ' \u2750 ';
|
|
510
|
+
const buildHeader = (language) => {
|
|
511
|
+
const btnW = displayWidth(COPY_BTN);
|
|
512
|
+
const left = language ? ` ${ui.dim}${language}${ui.reset}` : ' ';
|
|
513
|
+
const leftW = 2 + displayWidth(language); // ' ' gutter + 语言名
|
|
514
|
+
const spaces = cols - leftW - btnW;
|
|
515
|
+
if (spaces < 0)
|
|
516
|
+
return { line: paintCodeRow(left), colStart: -1, colEnd: -1 };
|
|
517
|
+
const colStart = leftW + spaces;
|
|
518
|
+
return {
|
|
519
|
+
line: paintCodeRow(`${left}${' '.repeat(spaces)}${ui.accent}${COPY_BTN}${ui.reset}`),
|
|
520
|
+
colStart,
|
|
521
|
+
colEnd: colStart + btnW,
|
|
522
|
+
};
|
|
523
|
+
};
|
|
428
524
|
const flushCode = () => {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
const
|
|
525
|
+
const strip = fenceIndent > 0 ? new RegExp(`^[ \\t]{0,${fenceIndent}}`) : null;
|
|
526
|
+
const code = (strip ? codeBuf.map((l) => l.replace(strip, '')) : codeBuf).join('\n');
|
|
527
|
+
const headerLine = out.length;
|
|
528
|
+
const header = buildHeader(lang);
|
|
529
|
+
out.push(header.line);
|
|
530
|
+
const codeStartLine = out.length;
|
|
531
|
+
const highlighted = highlightCodeBlock(code, lang);
|
|
432
532
|
const codeW = Math.max(1, cols - 2);
|
|
433
533
|
for (const l of wrapAnsiString(highlighted, codeW)) {
|
|
434
|
-
out.push(
|
|
534
|
+
out.push(paintCodeRow(` ${l}`));
|
|
435
535
|
}
|
|
536
|
+
const codeEndLine = out.length - 1;
|
|
537
|
+
codeBlocks.push({
|
|
538
|
+
headerLine,
|
|
539
|
+
codeStartLine,
|
|
540
|
+
codeEndLine,
|
|
541
|
+
buttonColStart: header.colStart,
|
|
542
|
+
buttonColEnd: header.colEnd,
|
|
543
|
+
lang,
|
|
544
|
+
code,
|
|
545
|
+
});
|
|
436
546
|
out.push('');
|
|
437
547
|
inFence = false;
|
|
438
548
|
fenceChar = '';
|
|
549
|
+
fenceLen = 0;
|
|
550
|
+
fenceDepth = 0;
|
|
551
|
+
fenceIndent = 0;
|
|
439
552
|
lang = '';
|
|
440
553
|
codeBuf = [];
|
|
441
554
|
prevBlank = true;
|
|
@@ -446,7 +559,7 @@ function renderMarkdownImpl(text, cols) {
|
|
|
446
559
|
// 若不恢复,后续所有标题、列表和下一段代码都会被吞进首个代码块,最终显示成截图里的原始
|
|
447
560
|
// `##` / ```。只接受“独占一行、恰好两个同类字符”,避免误伤代码中的行内双反引号。
|
|
448
561
|
const shortClose = inFence ? line.match(/^\s*(`{2}|~{2})\s*$/) : null;
|
|
449
|
-
if (shortClose && shortClose[1][0] === fenceChar) {
|
|
562
|
+
if (shortClose && shortClose[1][0] === fenceChar && fenceDepth === 0) {
|
|
450
563
|
flushCode();
|
|
451
564
|
i++;
|
|
452
565
|
continue;
|
|
@@ -458,11 +571,25 @@ function renderMarkdownImpl(text, cols) {
|
|
|
458
571
|
flushPara();
|
|
459
572
|
inFence = true;
|
|
460
573
|
fenceChar = fm[2][0];
|
|
574
|
+
fenceLen = fm[2].length;
|
|
575
|
+
fenceDepth = 0;
|
|
576
|
+
fenceIndent = fm[1].length;
|
|
461
577
|
lang = fm[3].trim();
|
|
462
578
|
codeBuf = [];
|
|
463
579
|
}
|
|
464
|
-
else if (fm[2][0] === fenceChar) {
|
|
465
|
-
|
|
580
|
+
else if (fm[2][0] === fenceChar && fm[2].length >= fenceLen) {
|
|
581
|
+
if (fm[3].trim()) {
|
|
582
|
+
// 带语言标注的同类围栏不是闭合栏(CommonMark),按嵌套开栏计深度,其配对的裸栏不会提前截断外层块。
|
|
583
|
+
fenceDepth++;
|
|
584
|
+
codeBuf.push(line);
|
|
585
|
+
}
|
|
586
|
+
else if (fenceDepth > 0) {
|
|
587
|
+
fenceDepth--;
|
|
588
|
+
codeBuf.push(line);
|
|
589
|
+
}
|
|
590
|
+
else {
|
|
591
|
+
flushCode();
|
|
592
|
+
}
|
|
466
593
|
}
|
|
467
594
|
else {
|
|
468
595
|
codeBuf.push(line);
|
|
@@ -514,11 +641,33 @@ function renderMarkdownImpl(text, cols) {
|
|
|
514
641
|
flushPara();
|
|
515
642
|
const prefix = ` ${ui.dim}│${ui.reset} `;
|
|
516
643
|
const cont = ' '.repeat(ansiDisplayWidth(prefix));
|
|
517
|
-
|
|
518
|
-
|
|
644
|
+
// 收齐连续的引用行,去掉 > 前缀后再识别表格(否则引用块里的表格会逐行显示成竖线原文)
|
|
645
|
+
const inner = [];
|
|
646
|
+
let j = i;
|
|
647
|
+
while (j < src.length) {
|
|
648
|
+
const m = src[j].match(/^>\s?(.*)$/);
|
|
649
|
+
if (!m)
|
|
650
|
+
break;
|
|
651
|
+
inner.push(m[1]);
|
|
652
|
+
j++;
|
|
653
|
+
}
|
|
654
|
+
let k = 0;
|
|
655
|
+
while (k < inner.length) {
|
|
656
|
+
const t = matchTable(inner, k);
|
|
657
|
+
if (t) {
|
|
658
|
+
const tw = Math.max(1, cols - ansiDisplayWidth(prefix));
|
|
659
|
+
for (const l of renderTable(t.header, t.aligns, t.rows, tw))
|
|
660
|
+
out.push(clipAnsiLine(prefix + l, cols));
|
|
661
|
+
k = t.next;
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
for (const l of wrapWithPrefix(renderInline(inner[k]), prefix, cont, cols)) {
|
|
665
|
+
out.push(l);
|
|
666
|
+
}
|
|
667
|
+
k++;
|
|
519
668
|
}
|
|
520
669
|
prevBlank = false;
|
|
521
|
-
i
|
|
670
|
+
i = j;
|
|
522
671
|
continue;
|
|
523
672
|
}
|
|
524
673
|
// 无序列表 - * +
|
|
@@ -550,30 +699,30 @@ function renderMarkdownImpl(text, cols) {
|
|
|
550
699
|
i++;
|
|
551
700
|
continue;
|
|
552
701
|
}
|
|
553
|
-
// GFM 表格:表头
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
prevBlank = true;
|
|
574
|
-
continue;
|
|
575
|
-
}
|
|
702
|
+
// GFM 表格:表头 + 紧跟分隔行 → 收齐整块渲染(宽容匹配规则见 matchTable / renderTable)
|
|
703
|
+
const tbl = matchTable(src, i);
|
|
704
|
+
if (tbl) {
|
|
705
|
+
flushPara();
|
|
706
|
+
for (const l of renderTable(tbl.header, tbl.aligns, tbl.rows, cols))
|
|
707
|
+
out.push(l);
|
|
708
|
+
out.push('');
|
|
709
|
+
prevBlank = true;
|
|
710
|
+
i = tbl.next;
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
// 没有合法分隔行的竖线行(模型漏写分隔行 / 写法非法):保持逐行显示,
|
|
714
|
+
// 不能并进段落——段落会把多行 join 成一行,竖线文字糊成一团。
|
|
715
|
+
if (/^\s*\|/.test(line)) {
|
|
716
|
+
flushPara();
|
|
717
|
+
while (i < src.length && /^\s*\|/.test(src[i]) && !(i > 0 && matchTable(src, i))) {
|
|
718
|
+
const segs = renderInline(src[i].trim());
|
|
719
|
+
for (const l of wrapAnsiString(segsToAnsi(segs), cols))
|
|
720
|
+
out.push(clipAnsiLine(l, cols));
|
|
721
|
+
i++;
|
|
576
722
|
}
|
|
723
|
+
out.push('');
|
|
724
|
+
prevBlank = true;
|
|
725
|
+
continue;
|
|
577
726
|
}
|
|
578
727
|
// 段落:累积(连续非空非特殊行 join ' ' 后渲染)
|
|
579
728
|
para.push(line);
|
|
@@ -587,15 +736,29 @@ function renderMarkdownImpl(text, cols) {
|
|
|
587
736
|
// "\n\n" 与首段正文拆成不同 chunk;仅清洗首个正文 chunk 不够,因为 mdBuf
|
|
588
737
|
// 累积重渲染时这些换行仍会变成段首空行。这里最终兜底,正文段永不自带前导空行。
|
|
589
738
|
const isVisualBlank = (line) => stripAnsi(line).trim().length === 0;
|
|
590
|
-
|
|
739
|
+
let headShift = 0;
|
|
740
|
+
while (out.length > 0 && isVisualBlank(out[0])) {
|
|
591
741
|
out.shift();
|
|
742
|
+
headShift++;
|
|
743
|
+
}
|
|
592
744
|
// 末尾不留空行:agent onText 后接 onToolCall 的 contentWrite('\n') 会补 1 空行分隔正文与 ● 行;
|
|
593
745
|
// 若 md 末尾自带空行(段落/代码块后)则叠成 2 空行。裁掉末尾连续空行,让 onToolCall / 轮末
|
|
594
746
|
// contentWrite('\n') 恰好补 1 行(与改造前 raw 文本行为一致)。块间空行(flushPara/flushCode 中段
|
|
595
747
|
// push 的)不受影响——只裁末尾。
|
|
596
748
|
while (out.length > 0 && isVisualBlank(out[out.length - 1]))
|
|
597
749
|
out.pop();
|
|
598
|
-
|
|
750
|
+
// 前导空行被 shift:同步平移仍在输出区内的代码块相对行(被整体裁掉的块丢弃)。
|
|
751
|
+
const blocks = headShift
|
|
752
|
+
? codeBlocks
|
|
753
|
+
.map((b) => ({
|
|
754
|
+
...b,
|
|
755
|
+
headerLine: b.headerLine - headShift,
|
|
756
|
+
codeStartLine: b.codeStartLine - headShift,
|
|
757
|
+
codeEndLine: b.codeEndLine - headShift,
|
|
758
|
+
}))
|
|
759
|
+
.filter((b) => b.codeEndLine >= 0)
|
|
760
|
+
: codeBlocks;
|
|
761
|
+
return { lines: out, codeBlocks: blocks };
|
|
599
762
|
}
|
|
600
763
|
/**
|
|
601
764
|
* 把 markdown 文本渲染成 ANSI 物理行数组(每行 ansiDisplayWidth ≤ cols,自洽带色)。
|
|
@@ -603,20 +766,24 @@ function renderMarkdownImpl(text, cols) {
|
|
|
603
766
|
* 命中(MRU 提升),cols 变(resize)或切主题(themeVersion 变)则重算覆写。供 layout.contentWriteMd
|
|
604
767
|
* 每 chunk 调用(memo 使重复渲染命中缓存)。themeVersion 使 setTheme 后全量重绘不命中旧主题缓存行。
|
|
605
768
|
*/
|
|
606
|
-
export function
|
|
769
|
+
export function renderMarkdownWithMeta(text, cols) {
|
|
607
770
|
const hit = MEMO.get(text);
|
|
608
771
|
if (hit && hit.cols === cols && hit.themeVersion === getThemeVersion()) {
|
|
609
772
|
MEMO.delete(text);
|
|
610
773
|
MEMO.set(text, hit); // MRU 提升
|
|
611
|
-
return hit.lines;
|
|
774
|
+
return { lines: hit.lines, codeBlocks: hit.codeBlocks };
|
|
612
775
|
}
|
|
613
|
-
const lines = renderMarkdownImpl(text, cols);
|
|
776
|
+
const { lines, codeBlocks } = renderMarkdownImpl(text, cols);
|
|
614
777
|
if (MEMO.has(text))
|
|
615
778
|
MEMO.delete(text);
|
|
616
779
|
else if (MEMO.size >= MEMO_CAP)
|
|
617
780
|
MEMO.delete(MEMO.keys().next().value);
|
|
618
|
-
MEMO.set(text, { cols, lines, themeVersion: getThemeVersion() });
|
|
619
|
-
return lines;
|
|
781
|
+
MEMO.set(text, { cols, lines, codeBlocks, themeVersion: getThemeVersion() });
|
|
782
|
+
return { lines, codeBlocks };
|
|
783
|
+
}
|
|
784
|
+
/** 只取物理行(向后兼容 reflow / 测试);代码块定位信息见 renderMarkdownWithMeta。 */
|
|
785
|
+
export function renderMarkdown(text, cols) {
|
|
786
|
+
return renderMarkdownWithMeta(text, cols).lines;
|
|
620
787
|
}
|
|
621
788
|
// 供 check 脚本 / 单元验证用(不进 layout 运行时路径)。
|
|
622
789
|
export const __test = { clipAnsiLine, renderInline, wrapAnsiString, segsToAnsi };
|
package/dist/ui/render.js
CHANGED
|
@@ -60,14 +60,120 @@ export function charWidth(cp) {
|
|
|
60
60
|
return 2; // 表情
|
|
61
61
|
if (cp >= 0x20000 && cp <= 0x2fffd)
|
|
62
62
|
return 2; // CJK 扩展 B-F
|
|
63
|
-
if (cp
|
|
64
|
-
return 2; // ⚡
|
|
63
|
+
if (isWideBmpEmoji(cp))
|
|
64
|
+
return 2; // ⚡ ✅ ❌ ⭐ 等:终端按 emoji 2 格渲染,算 1 会与 chip 重叠产生残影、表格列错位
|
|
65
65
|
return 1;
|
|
66
66
|
}
|
|
67
|
+
/**
|
|
68
|
+
* BMP 内 East Asian Width = W 的 emoji(Emoji_Presentation=Yes,无需 VS16 就按 2 格画)。
|
|
69
|
+
* ✔ (U+2714) / ⚠ (U+26A0) 等文本呈现符号默认是窄的,不在此表。
|
|
70
|
+
* 补充平面(U+1F300+)已由上面的区间覆盖。
|
|
71
|
+
*/
|
|
72
|
+
const WIDE_BMP_EMOJI = [
|
|
73
|
+
[0x231a, 0x231b],
|
|
74
|
+
[0x23e9, 0x23ec],
|
|
75
|
+
[0x23f0, 0x23f0],
|
|
76
|
+
[0x23f3, 0x23f3],
|
|
77
|
+
[0x25fd, 0x25fe],
|
|
78
|
+
[0x2614, 0x2615],
|
|
79
|
+
[0x2648, 0x2653],
|
|
80
|
+
[0x267f, 0x267f],
|
|
81
|
+
[0x2693, 0x2693],
|
|
82
|
+
[0x26a1, 0x26a1],
|
|
83
|
+
[0x26aa, 0x26ab],
|
|
84
|
+
[0x26bd, 0x26be],
|
|
85
|
+
[0x26c4, 0x26c5],
|
|
86
|
+
[0x26ce, 0x26ce],
|
|
87
|
+
[0x26d4, 0x26d4],
|
|
88
|
+
[0x26ea, 0x26ea],
|
|
89
|
+
[0x26f2, 0x26f3],
|
|
90
|
+
[0x26f5, 0x26f5],
|
|
91
|
+
[0x26fa, 0x26fa],
|
|
92
|
+
[0x26fd, 0x26fd],
|
|
93
|
+
[0x2705, 0x2705],
|
|
94
|
+
[0x270a, 0x270b],
|
|
95
|
+
[0x2728, 0x2728],
|
|
96
|
+
[0x274c, 0x274c],
|
|
97
|
+
[0x274e, 0x274e],
|
|
98
|
+
[0x2753, 0x2755],
|
|
99
|
+
[0x2757, 0x2757],
|
|
100
|
+
[0x2795, 0x2797],
|
|
101
|
+
[0x27b0, 0x27b0],
|
|
102
|
+
[0x27bf, 0x27bf],
|
|
103
|
+
[0x2b1b, 0x2b1c],
|
|
104
|
+
[0x2b50, 0x2b50],
|
|
105
|
+
[0x2b55, 0x2b55],
|
|
106
|
+
];
|
|
107
|
+
function isWideBmpEmoji(cp) {
|
|
108
|
+
if (cp < 0x231a || cp > 0x2b55)
|
|
109
|
+
return false;
|
|
110
|
+
for (const [lo, hi] of WIDE_BMP_EMOJI) {
|
|
111
|
+
if (cp >= lo && cp <= hi)
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* 读 str 中 UTF-16 下标 i 处的一个「显示簇」,返回它占的终端列数与簇末下标(不含)。
|
|
118
|
+
* 终端会把下面几类码点序列合成一个字形,只画 emoji 的 2 格;逐码点累加宽度会算宽,表格边框就凹进去:
|
|
119
|
+
* - 区域旗帜:两个 Regional Indicator(🇨🇳)→ 2 格,而不是 2+2
|
|
120
|
+
* - ZWJ 序列:👨💻 / 👩👧 / ❤️🔥 → 以首个字符为准,ZWJ 后并入的 emoji 不再计宽
|
|
121
|
+
* - 肤色修饰符:👍🏽 → 并入前一字符
|
|
122
|
+
* - 后随 FE0F(VS16):⚠️ ✔️ ❤️ 默认文本呈现的窄符号切成 emoji 呈现 → 2 格;keycap(1️⃣)同为 2 格
|
|
123
|
+
* 组合符 / 控制符仍按 charWidth 算 0 宽。ZWJ 只与 U+2190 以上的符号 / emoji 合并,
|
|
124
|
+
* 避免把印地语等文字里的 ZWJ 误当 emoji 连接。
|
|
125
|
+
*/
|
|
126
|
+
export function graphemeAt(str, i) {
|
|
127
|
+
const cp = str.codePointAt(i) ?? 0;
|
|
128
|
+
let end = i + (cp > 0xffff ? 2 : 1);
|
|
129
|
+
if (cp >= 0x1f1e6 && cp <= 0x1f1ff) {
|
|
130
|
+
const next = str.codePointAt(end);
|
|
131
|
+
if (next !== undefined && next >= 0x1f1e6 && next <= 0x1f1ff)
|
|
132
|
+
end += 2;
|
|
133
|
+
return { width: 2, end };
|
|
134
|
+
}
|
|
135
|
+
let width = charWidth(cp);
|
|
136
|
+
for (;;) {
|
|
137
|
+
const n = str.codePointAt(end);
|
|
138
|
+
if (n === undefined)
|
|
139
|
+
break;
|
|
140
|
+
if (n === 0xfe0f) {
|
|
141
|
+
if (width === 1 && cp >= 0x80)
|
|
142
|
+
width = 2;
|
|
143
|
+
end += 1;
|
|
144
|
+
}
|
|
145
|
+
else if (n === 0xfe0e) {
|
|
146
|
+
end += 1;
|
|
147
|
+
}
|
|
148
|
+
else if (n === 0x20e3) {
|
|
149
|
+
if (width > 0)
|
|
150
|
+
width = 2;
|
|
151
|
+
end += 1;
|
|
152
|
+
}
|
|
153
|
+
else if (n >= 0x1f3fb && n <= 0x1f3ff && width > 0) {
|
|
154
|
+
end += 2;
|
|
155
|
+
}
|
|
156
|
+
else if (n === 0x200d) {
|
|
157
|
+
const m = str.codePointAt(end + 1);
|
|
158
|
+
if (m !== undefined && cp >= 0x2190 && m >= 0x2190)
|
|
159
|
+
end += 1 + (m > 0xffff ? 2 : 1);
|
|
160
|
+
else
|
|
161
|
+
end += 1;
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
break;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return { width, end };
|
|
168
|
+
}
|
|
67
169
|
export function displayWidth(str) {
|
|
68
170
|
let w = 0;
|
|
69
|
-
|
|
70
|
-
|
|
171
|
+
let i = 0;
|
|
172
|
+
while (i < str.length) {
|
|
173
|
+
const g = graphemeAt(str, i);
|
|
174
|
+
w += g.width;
|
|
175
|
+
i = g.end;
|
|
176
|
+
}
|
|
71
177
|
return w;
|
|
72
178
|
}
|
|
73
179
|
/**
|
package/dist/ui/theme.js
CHANGED
|
@@ -34,6 +34,7 @@ const DEFAULT = {
|
|
|
34
34
|
// diff 行底色:One Dark bg #282c34 上加 ~14% 亮度的对应色,够辨识但不刺眼
|
|
35
35
|
addBg: '\x1B[48;2;44;62;42m', // 偏暗绿(One Dark green(152,195,121)暗化)
|
|
36
36
|
delBg: '\x1B[48;2;62;38;42m', // 偏暗红(One Dark red(224,108,117)暗化)
|
|
37
|
+
codeBg: '\x1B[48;2;50;56;68m', // One Dark bg(40,44,52)上提亮一档的冷灰蓝;纯黑终端上同样可辨
|
|
37
38
|
};
|
|
38
39
|
/**
|
|
39
40
|
* 内建主题表。default=One Dark、light=Solarized Light、solarized=Solarized Dark、
|
|
@@ -60,6 +61,7 @@ const THEMES = {
|
|
|
60
61
|
// 比直接用 base1 更柔,跟深 fg(red/green)对比充足
|
|
61
62
|
addBg: '\x1B[48;2;220;235;205m',
|
|
62
63
|
delBg: '\x1B[48;2;245;218;215m',
|
|
64
|
+
codeBg: '\x1B[48;2;238;232;213m', // Solarized base2:浅米底上的代码块
|
|
63
65
|
},
|
|
64
66
|
solarized: {
|
|
65
67
|
red: '\x1B[38;2;220;50;47m',
|
|
@@ -77,6 +79,7 @@ const THEMES = {
|
|
|
77
79
|
// diff 行底色:Solarized Dark base03(0,43,54)上加对应色族暗 tint
|
|
78
80
|
addBg: '\x1B[48;2;20;50;38m',
|
|
79
81
|
delBg: '\x1B[48;2;55;30;30m',
|
|
82
|
+
codeBg: '\x1B[48;2;7;54;66m', // Solarized base02
|
|
80
83
|
},
|
|
81
84
|
gruvbox: {
|
|
82
85
|
red: '\x1B[38;2;251;73;52m',
|
|
@@ -94,6 +97,7 @@ const THEMES = {
|
|
|
94
97
|
// diff 行底色:Gruvbox dark bg(40,40,40)上贴暗 bg0_a 风格
|
|
95
98
|
addBg: '\x1B[48;2;40;55;30m',
|
|
96
99
|
delBg: '\x1B[48;2;70;35;30m',
|
|
100
|
+
codeBg: '\x1B[48;2;60;56;54m', // Gruvbox bg1
|
|
97
101
|
},
|
|
98
102
|
nord: {
|
|
99
103
|
red: '\x1B[38;2;191;97;106m',
|
|
@@ -111,6 +115,7 @@ const THEMES = {
|
|
|
111
115
|
// diff 行底色:Nord polar night(46,52,64)上贴对应色族暗 tint
|
|
112
116
|
addBg: '\x1B[48;2;46;66;52m',
|
|
113
117
|
delBg: '\x1B[48;2;72;46;52m',
|
|
118
|
+
codeBg: '\x1B[48;2;59;66;82m', // Nord polar night nord1
|
|
114
119
|
},
|
|
115
120
|
orange: {
|
|
116
121
|
// 秋季/南瓜橙:深暖底(#231c16 系)+ accent 主强调走橙色;yellow 槽也偏橙
|
|
@@ -131,6 +136,7 @@ const THEMES = {
|
|
|
131
136
|
// diff 行底色:暖深棕底上贴对应色族暗 tint,跟 fg 配对柔和可辨
|
|
132
137
|
addBg: '\x1B[48;2;55;70;35m',
|
|
133
138
|
delBg: '\x1B[48;2;78;42;32m',
|
|
139
|
+
codeBg: '\x1B[48;2;58;46;36m',
|
|
134
140
|
},
|
|
135
141
|
rose: {
|
|
136
142
|
// 玫红:深紫底 + accent 玫粉作主强调;magenta 槽与 accent 同源(主题色),
|
|
@@ -150,6 +156,7 @@ const THEMES = {
|
|
|
150
156
|
// diff 行底色:深紫底贴对应色族暗 tint,绿暗化偏橄榄、红暗化偏紫红
|
|
151
157
|
addBg: '\x1B[48;2;50;60;42m',
|
|
152
158
|
delBg: '\x1B[48;2;75;40;52m',
|
|
159
|
+
codeBg: '\x1B[48;2;56;42;54m',
|
|
153
160
|
},
|
|
154
161
|
emerald: {
|
|
155
162
|
// 翡翠绿:深绿底 + accent 翡翠绿作主强调;green 槽与 accent 同源(主题色),
|
|
@@ -169,6 +176,7 @@ const THEMES = {
|
|
|
169
176
|
// diff 行底色:深绿底贴对应色族暗 tint,绿暗化偏深绿、红暗化偏暗红
|
|
170
177
|
addBg: '\x1B[48;2;30;55;40m',
|
|
171
178
|
delBg: '\x1B[48;2;60;40;40m',
|
|
179
|
+
codeBg: '\x1B[48;2;34;56;50m',
|
|
172
180
|
},
|
|
173
181
|
amber: {
|
|
174
182
|
// 琥珀金黄:深棕底 + accent 琥珀金黄作主强调;yellow 槽与 accent 同源(主题色),
|
|
@@ -188,6 +196,7 @@ const THEMES = {
|
|
|
188
196
|
// diff 行底色:深棕底贴对应色族暗 tint,绿暗化偏橄榄、红暗化偏暗棕红
|
|
189
197
|
addBg: '\x1B[48;2;50;55;25m',
|
|
190
198
|
delBg: '\x1B[48;2;70;40;28m',
|
|
199
|
+
codeBg: '\x1B[48;2;60;48;32m',
|
|
191
200
|
},
|
|
192
201
|
lavender: {
|
|
193
202
|
// 薰衣草淡紫:深紫底 + accent 淡紫作主强调;magenta 槽与 accent 同源(主题色),
|
|
@@ -207,6 +216,7 @@ const THEMES = {
|
|
|
207
216
|
// diff 行底色:深紫底贴对应色族暗 tint,绿暗化偏冷绿、红暗化偏冷紫红
|
|
208
217
|
addBg: '\x1B[48;2;38;46;42m',
|
|
209
218
|
delBg: '\x1B[48;2;60;40;55m',
|
|
219
|
+
codeBg: '\x1B[48;2;50;44;70m',
|
|
210
220
|
},
|
|
211
221
|
sunset: {
|
|
212
222
|
// 日落珊瑚:深棕红底 + accent 珊瑚红作主强调;red 槽与 accent 同源(主题色);
|
|
@@ -226,6 +236,7 @@ const THEMES = {
|
|
|
226
236
|
// diff 行底色:深棕红底贴对应色族暗 tint,绿暗化偏橄榄、红暗化偏暗棕红
|
|
227
237
|
addBg: '\x1B[48;2;50;55;30m',
|
|
228
238
|
delBg: '\x1B[48;2;75;32;30m',
|
|
239
|
+
codeBg: '\x1B[48;2;62;42;40m',
|
|
229
240
|
},
|
|
230
241
|
};
|
|
231
242
|
let currentName = 'default';
|
|
@@ -320,4 +331,7 @@ export const ui = {
|
|
|
320
331
|
get delBg() {
|
|
321
332
|
return color('delBg');
|
|
322
333
|
},
|
|
334
|
+
get codeBg() {
|
|
335
|
+
return color('codeBg');
|
|
336
|
+
},
|
|
323
337
|
};
|