@each1024/pi-mini-mode 2.0.9 → 2.0.10
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 +9 -6
- package/README.zh-CN.md +6 -8
- package/extensions/footer-status.ts +46 -1189
- package/lib/agent-render.ts +203 -0
- package/lib/agent-state.ts +199 -0
- package/lib/agent-view.ts +5 -519
- package/lib/agent-widgets.ts +129 -0
- package/lib/footer-line.ts +206 -0
- package/lib/input-editor-paths.ts +79 -0
- package/lib/input-editor.ts +184 -0
- package/lib/input-enhancements-types.ts +49 -0
- package/lib/input-enhancements.ts +15 -797
- package/lib/input-hover-preview.ts +122 -0
- package/lib/input-image-graphics.ts +34 -0
- package/lib/input-image-paths.ts +120 -0
- package/lib/input-inline-images.ts +114 -0
- package/lib/input-skill-completion.ts +132 -0
- package/lib/minimal-output.ts +379 -0
- package/lib/minimal-turns.ts +203 -0
- package/lib/settings-web.ts +9 -2
- package/lib/settings.html +5 -4
- package/lib/settings.ts +153 -0
- package/lib/thinking-preview.ts +30 -19
- package/lib/thinking-stream.ts +89 -0
- package/lib/transcript-adapter.ts +15 -501
- package/lib/transcript-cards.ts +67 -0
- package/lib/transcript-notice-render.ts +211 -0
- package/lib/transcript-notices.ts +238 -0
- package/lib/usage.ts +137 -0
- package/package.json +4 -2
package/lib/settings.html
CHANGED
|
@@ -10,12 +10,12 @@
|
|
|
10
10
|
.preview-mode input[type=number]{font:inherit;color:var(--foreground);background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);padding:8px;width:6em;height:44px}.preview-mode input:disabled{opacity:.5}
|
|
11
11
|
|
|
12
12
|
/* Editorial headings; controls and status data retain readable system fonts. */
|
|
13
|
-
body{background:light-dark(#f6f3ed,#141614)}main{max-width:1160px;padding:32px 32px 88px}header{align-items:flex-start;border-bottom:1px solid var(--border);padding-bottom:36px}h1{font:italic 400 clamp(2.625rem,5vw,3.625rem)/1.06 "Didot","Bodoni 72","Songti SC","STSong",serif;letter-spacing:.02em}.subtitle{font:normal 1.625rem/1.4 "Didot","Bodoni 72","Songti SC","STSong",serif;color:var(--accent);margin:16px 0 0}h2{font:normal 2rem/1.25 "Didot","Bodoni 72","Songti SC","STSong",serif;letter-spacing:0;text-transform:none;color:var(--foreground);margin:0 0 16px}section{margin:0;padding-top:24px}.feature-head h3{font:normal 1.625rem/1.25 "Didot","Bodoni 72","Songti SC","STSong",serif}.feature{padding:20px}.feature:first-child{border-top:3px solid var(--accent)}.feature-body,.feature-points{line-height:1.7}#preview{background:var(--surface);border:1px solid var(--border);padding:16px 24px;height:80px;margin-bottom:12px}.grid label{min-height:44px}@media(max-width:760px){main{padding:20px 16px 64px}header{padding-bottom:20px}.features{grid-template-columns:1fr}h2{font-size:1.75rem}.subtitle{font-size:1.375rem}}
|
|
13
|
+
body{background:light-dark(#f6f3ed,#141614)}main{max-width:1160px;padding:32px 32px 88px}header{align-items:flex-start;border-bottom:1px solid var(--border);padding-bottom:36px}.title-block{flex:1 1 420px;min-width:0}h1{font:italic 400 clamp(2.625rem,5vw,3.625rem)/1.06 "Didot","Bodoni 72","Songti SC","STSong",serif;letter-spacing:.02em}.subtitle-row{display:flex;align-items:baseline;justify-content:space-between;gap:16px;flex-wrap:wrap}.subtitle{font:normal 1.625rem/1.4 "Didot","Bodoni 72","Songti SC","STSong",serif;color:var(--accent);margin:16px 0 0}.version{margin:16px 0 0;color:var(--muted);font:var(--text-sm)/1.4 ui-sans-serif,system-ui,sans-serif;letter-spacing:.04em;white-space:nowrap}h2{font:normal 2rem/1.25 "Didot","Bodoni 72","Songti SC","STSong",serif;letter-spacing:0;text-transform:none;color:var(--foreground);margin:0 0 16px}section{margin:0;padding-top:24px}.feature-head h3{font:normal 1.625rem/1.25 "Didot","Bodoni 72","Songti SC","STSong",serif}.feature{padding:20px}.feature:first-child{border-top:3px solid var(--accent)}.feature-body,.feature-points{line-height:1.7}#preview{background:var(--surface);border:1px solid var(--border);padding:16px 24px;height:80px;margin-bottom:12px}.grid label{min-height:44px}@media(max-width:760px){main{padding:20px 16px 64px}header{padding-bottom:20px}.features{grid-template-columns:1fr}h2{font-size:1.75rem}.subtitle{font-size:1.375rem}}
|
|
14
14
|
</style>
|
|
15
15
|
<main>
|
|
16
16
|
<div id="statusbar" role="status" aria-live="polite"><span id="status"></span><button type="button" id="retry" hidden></button></div>
|
|
17
17
|
<header>
|
|
18
|
-
<div><h1 id="title"></h1><p class="subtitle" id="subtitle"></p></div>
|
|
18
|
+
<div class="title-block"><h1 id="title"></h1><div class="subtitle-row"><p class="subtitle" id="subtitle"></p><p class="version" id="version"></p></div></div>
|
|
19
19
|
<nav>
|
|
20
20
|
<button type="button" id="lang-en" aria-pressed="false">EN</button>
|
|
21
21
|
<button type="button" id="lang-zh" aria-pressed="false">中文</button>
|
|
@@ -31,7 +31,7 @@ body{background:light-dark(#f6f3ed,#141614)}main{max-width:1160px;padding:32px 3
|
|
|
31
31
|
<section><h2 id="featuresHeading"></h2><div class="features" id="features"></div></section>
|
|
32
32
|
</main>
|
|
33
33
|
<script>
|
|
34
|
-
const $=id=>document.getElementById(id),token=location.hash.slice(1);
|
|
34
|
+
const $=id=>document.getElementById(id),token=location.hash.slice(1),VERSION=document.documentElement.dataset.version||'';
|
|
35
35
|
history.replaceState(null,'',location.pathname);
|
|
36
36
|
const I18N={
|
|
37
37
|
title:{zh:'Pi Mini Mode',en:'Pi Mini Mode'},
|
|
@@ -46,7 +46,7 @@ const I18N={
|
|
|
46
46
|
recordLimitHint:{zh:'默认 6 条。子代理始终显示,每个占一条;剩余额度显示最新执行记录。子代理超过上限时,仅显示全部子代理。',en:'Defaults to 6. Every subagent stays visible and uses one record; remaining slots show the latest execution records. When subagents exceed the limit, only their rows remain.'},
|
|
47
47
|
featureList:{
|
|
48
48
|
zh:[
|
|
49
|
-
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'在全屏模式下,把思考、工具与技能记录收进一棵可折叠过程树,保留完整回复。',points:['长用户消息显示前四行,点击展开全文','
|
|
49
|
+
{id:'minimal',setting:'pi-mini-mode-minimal-show',title:'极简输出',body:'在全屏模式下,把思考、工具与技能记录收进一棵可折叠过程树,保留完整回复。',points:['长用户消息显示前四行,点击展开全文','子代理始终显示,可展开活动记录与输出','Ctrl+O 展开或收起过程树,新问题默认收起','最终 Markdown 流畅呈现,失败与中断明确标记']},
|
|
50
50
|
{id:'input-enhancements',setting:'pi-mini-mode-input-enhancements',title:'输入增强',body:'让输入框和消息里的图片、技能与文件路径直接可用。',points:['图片默认以内联卡片陈列于输入框上方,亦可切换光标悬停','图片路径收纳为 [image1] 标签,提交时保留原图','空白后输入 / 就地搜索技能并插入光标处','点击图片标签或文件路径,用系统默认应用打开'],hint:'Ctrl+V 粘贴图片(Windows/WSL 使用 Alt+V)'},
|
|
51
51
|
{id:'themes',title:'明暗主题',body:'主题让 Markdown、代码高亮、表格与 Mermaid 图表跟随明暗切换。',points:['用户消息使用主题用户背景色,与正文区分','不支持、不完整或过宽的图表保留源文本'],hint:'回到 Pi,输入 /settings → Theme,选择 cc-dark / cc-light'}
|
|
52
52
|
],
|
|
@@ -114,6 +114,7 @@ function applyLang(){
|
|
|
114
114
|
document.documentElement.lang=lang==='zh'?'zh-CN':'en';
|
|
115
115
|
document.title=t('documentTitle');
|
|
116
116
|
for(const id of ['title','subtitle','featuresHeading','fieldsHeading','dragHint']) $(id).textContent=t(id);
|
|
117
|
+
$('version').textContent=VERSION?`v${VERSION}`:'';
|
|
117
118
|
$('reset').textContent=t('reset');$('retry').textContent=t('retry');
|
|
118
119
|
$('lang-zh').setAttribute('aria-pressed',String(lang==='zh'));
|
|
119
120
|
$('lang-en').setAttribute('aria-pressed',String(lang==='en'));
|
package/lib/settings.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import type { SettingItem } from "@earendil-works/pi-tui";
|
|
3
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
|
|
7
|
+
export const SETTINGS_FILE_NAME = "pi-mini-mode.json";
|
|
8
|
+
|
|
9
|
+
export interface MiniLensSettings {
|
|
10
|
+
"pi-mini-mode-model-show": boolean;
|
|
11
|
+
"pi-mini-mode-thinking-show": boolean;
|
|
12
|
+
"pi-mini-mode-project-branch-show": boolean;
|
|
13
|
+
"pi-mini-mode-branch-show": boolean;
|
|
14
|
+
"pi-mini-mode-ch-show": boolean;
|
|
15
|
+
"pi-mini-mode-session-tokens-show": boolean;
|
|
16
|
+
"pi-mini-mode-cache-tokens-show": boolean;
|
|
17
|
+
"pi-mini-mode-cache-miss-show": boolean;
|
|
18
|
+
"pi-mini-mode-cost-show": boolean;
|
|
19
|
+
"pi-mini-mode-mcp-show": boolean;
|
|
20
|
+
"pi-mini-mode-context-show": boolean;
|
|
21
|
+
"pi-mini-mode-context-dots-show": boolean;
|
|
22
|
+
"pi-mini-mode-context-percent-show": boolean;
|
|
23
|
+
"pi-mini-mode-speed-show": boolean;
|
|
24
|
+
"pi-mini-mode-speed-unit-show": boolean;
|
|
25
|
+
"pi-mini-mode-minimal-show": boolean;
|
|
26
|
+
"pi-mini-mode-minimal-record-limit": number;
|
|
27
|
+
"pi-mini-mode-input-enhancements": boolean;
|
|
28
|
+
"pi-mini-mode-image-preview": "hover" | "inline";
|
|
29
|
+
onboardingCompleted: boolean;
|
|
30
|
+
footerOrder?: string[];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const DEFAULT_SETTINGS: Readonly<MiniLensSettings> = {
|
|
34
|
+
"pi-mini-mode-model-show": true,
|
|
35
|
+
"pi-mini-mode-thinking-show": true,
|
|
36
|
+
"pi-mini-mode-project-branch-show": true,
|
|
37
|
+
"pi-mini-mode-branch-show": false,
|
|
38
|
+
"pi-mini-mode-ch-show": true,
|
|
39
|
+
"pi-mini-mode-session-tokens-show": true,
|
|
40
|
+
"pi-mini-mode-cache-tokens-show": false,
|
|
41
|
+
"pi-mini-mode-cache-miss-show": true,
|
|
42
|
+
"pi-mini-mode-cost-show": true,
|
|
43
|
+
"pi-mini-mode-mcp-show": false,
|
|
44
|
+
"pi-mini-mode-context-show": true,
|
|
45
|
+
"pi-mini-mode-context-dots-show": true,
|
|
46
|
+
"pi-mini-mode-context-percent-show": true,
|
|
47
|
+
"pi-mini-mode-speed-show": true,
|
|
48
|
+
"pi-mini-mode-speed-unit-show": true,
|
|
49
|
+
"pi-mini-mode-minimal-show": true,
|
|
50
|
+
"pi-mini-mode-minimal-record-limit": 6,
|
|
51
|
+
"pi-mini-mode-input-enhancements": true,
|
|
52
|
+
"pi-mini-mode-image-preview": "inline",
|
|
53
|
+
onboardingCompleted: false,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export const SETTING_IDS = Object.keys(DEFAULT_SETTINGS) as Array<Exclude<keyof MiniLensSettings, "footerOrder">>;
|
|
57
|
+
export const FOOTER_FIELDS = ["project-branch", "model", "thinking", "branch", "session-tokens", "cache-tokens", "cache-miss", "ch", "cost", "mcp", "context", "context-percent", "speed"] as const;
|
|
58
|
+
export const FOOTER_STYLE_OPTIONS = ["context-dots", "speed-unit"] as const;
|
|
59
|
+
|
|
60
|
+
export const COPY = {
|
|
61
|
+
preview: "预览(示例数据)", minimal: "极简输出",
|
|
62
|
+
model: "显示模型", thinking: "显示思考等级", total: "显示会话总 token", cached: "显示会话缓存 token", miss: "显示缓存 miss", totalLabel: "Total", cachedLabel: "Cached", cacheHitLabel: "CH", cacheHit: "显示缓存命中率 (CH)", price: "显示会话价格", mcp: "显示已启用 MCP 服务器", context: "显示上下文 token 与进度条", dots: "↳ 使用点阵进度条", percent: "显示上下文百分比", speed: "显示最近生成速度", speedUnit: "↳ 显示 tok/s 单位", inputEnhancements: "输入增强",
|
|
63
|
+
totalDescription: "Total:当前会话分支上的全部 token,含工具上报的 LLM 用量。", cachedDescription: "Cached:累计 cache-read + cache-write token(包含在 Total 中)。", cacheHitDescription: "CH(cache hit):cache-read / (input + cache-read)。Cache write 不计入此比率。",
|
|
64
|
+
enableMinimalDescription: "开启统一折叠思考、工具和技能过程;关闭恢复 Pi 默认会话历史。",
|
|
65
|
+
inputEnhancementsDescription: "原生 Ctrl+V 粘贴图片(Windows/WSL:Alt+V);图片显示为 [image1] 标签,默认在输入框上方显示内联卡片(可切换光标悬停模式)。空白后 / 选择技能并在光标处插入。Cmd+点击带下划线的图片标签或消息文件路径,用系统默认应用打开;预览及点击需终端支持。关闭仅恢复原生行为。",
|
|
66
|
+
tuiRequired: "/pi-mini-mode-settings 需要 TUI 模式", saveFailed: "无法保存 Pi Mini Mode 设置", onboarding: "默认开启输入增强和极简输出;极简输出需要全屏模式。仅显示分支、缓存 token 和 MCP 服务数默认关闭。选择「打开浏览器设置」可调整字段、预览方式和功能开关;推荐配置会保存主题和全屏模式。以后可用 /pi-mini-mode-settings 修改。", keepDefaults: "保留默认", configureNow: "打开浏览器设置", applyRecommended: "应用推荐配置", chooseTheme: "选择主题(主题立即应用;全屏模式需重启 Pi)", themeSaved: "已保存主题和全屏模式。请重启 Pi 以启用全屏;项目设置或命令行参数可能覆盖全局设置。", themeSaveFailed: "无法保存推荐的 Pi 主题和全屏模式;未完成首次配置。", themeApplyFailed: "推荐设置已保存,但当前主题未能立即应用;请重启 Pi。",
|
|
67
|
+
} as const;
|
|
68
|
+
|
|
69
|
+
export const RECOMMENDED_THEMES = ["cc-dark", "cc-light"] as const;
|
|
70
|
+
export type RecommendedTheme = typeof RECOMMENDED_THEMES[number];
|
|
71
|
+
|
|
72
|
+
export function settingsPath(agentDir = process.env.PI_MINI_MODE_AGENT_DIR ?? join(homedir(), CONFIG_DIR_NAME, "agent")): string {
|
|
73
|
+
return join(agentDir, SETTINGS_FILE_NAME);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function isBoolean(value: unknown): value is boolean {
|
|
77
|
+
return typeof value === "boolean";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function isRecordLimit(value: unknown): value is number {
|
|
81
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function parseSettings(value: unknown): MiniLensSettings {
|
|
85
|
+
const candidate = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
|
86
|
+
const settings = { ...DEFAULT_SETTINGS };
|
|
87
|
+
for (const id of SETTING_IDS) {
|
|
88
|
+
if (id === "pi-mini-mode-image-preview") {
|
|
89
|
+
if (candidate[id] === "hover" || candidate[id] === "inline") settings[id] = candidate[id];
|
|
90
|
+
} else if (id === "pi-mini-mode-minimal-record-limit") {
|
|
91
|
+
if (isRecordLimit(candidate[id])) settings[id] = candidate[id];
|
|
92
|
+
} else if (isBoolean(candidate[id])) settings[id] = candidate[id];
|
|
93
|
+
}
|
|
94
|
+
if (Array.isArray(candidate.footerOrder)) {
|
|
95
|
+
settings.footerOrder = [...new Set(candidate.footerOrder.filter((id): id is typeof FOOTER_FIELDS[number] =>
|
|
96
|
+
typeof id === "string" && (FOOTER_FIELDS as readonly string[]).includes(id)))];
|
|
97
|
+
for (const id of FOOTER_FIELDS) if (!settings.footerOrder.includes(id)) settings.footerOrder.push(id);
|
|
98
|
+
}
|
|
99
|
+
if (settings["pi-mini-mode-branch-show"]) settings["pi-mini-mode-project-branch-show"] = false;
|
|
100
|
+
return settings;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Rewrite missing defaults, retired switches, and normalized footer order once on load. */
|
|
104
|
+
export function settingsNeedBackfill(raw: unknown, parsed: MiniLensSettings): boolean {
|
|
105
|
+
if (!raw || typeof raw !== "object") return true;
|
|
106
|
+
const candidate = raw as Record<string, unknown>;
|
|
107
|
+
for (const id of SETTING_IDS) {
|
|
108
|
+
if (!Object.hasOwn(candidate, id)) return true;
|
|
109
|
+
}
|
|
110
|
+
if (LEGACY_MINIMAL_SETTING_IDS.some(id => Object.hasOwn(candidate, id))) return true;
|
|
111
|
+
if (!Array.isArray(candidate.footerOrder)) return false;
|
|
112
|
+
return JSON.stringify(candidate.footerOrder) !== JSON.stringify(parsed.footerOrder);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function loadSettings(path = settingsPath()): Promise<{ settings: MiniLensSettings; exists: boolean; backfilled: boolean }> {
|
|
116
|
+
try {
|
|
117
|
+
const raw: unknown = JSON.parse(await readFile(path, "utf8"));
|
|
118
|
+
const settings = parseSettings(raw);
|
|
119
|
+
return { settings, exists: true, backfilled: settingsNeedBackfill(raw, settings) };
|
|
120
|
+
} catch {
|
|
121
|
+
return { settings: { ...DEFAULT_SETTINGS }, exists: false, backfilled: false };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export async function saveSettings(settings: MiniLensSettings, path = settingsPath()): Promise<void> {
|
|
126
|
+
await mkdir(dirname(path), { recursive: true });
|
|
127
|
+
const temporaryPath = `${path}.tmp`;
|
|
128
|
+
await writeFile(temporaryPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8");
|
|
129
|
+
await rename(temporaryPath, path);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export const LEGACY_MINIMAL_SETTING_IDS = [
|
|
133
|
+
"pi-mini-mode-minimal-thinking-show", "pi-mini-mode-minimal-tools-show", "pi-mini-mode-minimal-output-show",
|
|
134
|
+
"pi-mini-mode-minimal-skills-show", "pi-mini-mode-agent-usage-show", "pi-mini-mode-agent-shortcut-show",
|
|
135
|
+
] as const;
|
|
136
|
+
|
|
137
|
+
export function isLegacyMinimalSetting(id: string): boolean {
|
|
138
|
+
return (LEGACY_MINIMAL_SETTING_IDS as readonly string[]).includes(id);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function settingsItems(settings: MiniLensSettings): SettingItem[] {
|
|
142
|
+
const values = ["on", "off"];
|
|
143
|
+
const labels: Record<Exclude<keyof MiniLensSettings, "onboardingCompleted" | "footerOrder" | "pi-mini-mode-image-preview" | "pi-mini-mode-minimal-record-limit">, string> = {
|
|
144
|
+
"pi-mini-mode-project-branch-show": "显示项目名称和分支(互斥)",
|
|
145
|
+
"pi-mini-mode-branch-show": "仅显示分支(思考等级后,互斥)",
|
|
146
|
+
"pi-mini-mode-model-show": COPY.model, "pi-mini-mode-thinking-show": COPY.thinking, "pi-mini-mode-session-tokens-show": COPY.total, "pi-mini-mode-cache-tokens-show": COPY.cached, "pi-mini-mode-cache-miss-show": COPY.miss, "pi-mini-mode-ch-show": COPY.cacheHit, "pi-mini-mode-cost-show": COPY.price, "pi-mini-mode-mcp-show": COPY.mcp, "pi-mini-mode-context-show": COPY.context, "pi-mini-mode-context-dots-show": COPY.dots, "pi-mini-mode-context-percent-show": COPY.percent, "pi-mini-mode-speed-show": COPY.speed, "pi-mini-mode-speed-unit-show": COPY.speedUnit, "pi-mini-mode-minimal-show": COPY.minimal, "pi-mini-mode-input-enhancements": COPY.inputEnhancements,
|
|
147
|
+
};
|
|
148
|
+
return (Object.keys(labels) as Array<keyof typeof labels>).map((id) => ({
|
|
149
|
+
id, label: labels[id],
|
|
150
|
+
description: id === "pi-mini-mode-minimal-show" ? COPY.enableMinimalDescription : id === "pi-mini-mode-input-enhancements" ? COPY.inputEnhancementsDescription : id === "pi-mini-mode-session-tokens-show" ? COPY.totalDescription : id === "pi-mini-mode-cache-tokens-show" ? COPY.cachedDescription : id === "pi-mini-mode-ch-show" ? COPY.cacheHitDescription : undefined,
|
|
151
|
+
currentValue: settings[id] ? values[0] : values[1], values,
|
|
152
|
+
}));
|
|
153
|
+
}
|
package/lib/thinking-preview.ts
CHANGED
|
@@ -5,31 +5,42 @@ const sentences = new Intl.Segmenter(undefined, { granularity: "sentence" });
|
|
|
5
5
|
const words = new Intl.Segmenter(undefined, { granularity: "word" });
|
|
6
6
|
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
7
7
|
|
|
8
|
-
/**
|
|
9
|
-
export function thinkingPreview(source: string, columns: number, maxRows = 1): string {
|
|
10
|
-
if (columns <= 0) return "";
|
|
8
|
+
/** Live previews follow coherent sentences; completed previews retain the beginning. */
|
|
9
|
+
export function thinkingPreview(source: string, columns: number, maxRows = 1, live = false): string {
|
|
10
|
+
if (columns <= 0 || maxRows <= 0) return "";
|
|
11
11
|
const paragraphs = stripVTControlCharacters(source).replace(/[\x00-\x08\x0b-\x1f\x7f]/g, " ")
|
|
12
12
|
.split(/\n+/).map(line => line.replace(/\s+/g, " ").trim()).filter(Boolean);
|
|
13
|
-
const
|
|
14
|
-
if (!
|
|
15
|
-
const parts = [...sentences.segment(paragraph)].map(part => part.segment.trim()).filter(Boolean);
|
|
16
|
-
let latest = parts.at(-1) ?? paragraph;
|
|
17
|
-
if (visibleWidth(latest) < 12 && parts.length > 1) latest = `${parts.at(-2)} ${latest}`;
|
|
13
|
+
const full = paragraphs.join(" ");
|
|
14
|
+
if (!full) return "";
|
|
18
15
|
const fits = (text: string) => visibleWidth(text) <= columns * maxRows && new Text(text, 0, 0).render(columns).length <= maxRows;
|
|
19
|
-
if (fits(
|
|
16
|
+
if (fits(full)) return full;
|
|
17
|
+
let excerpt = full;
|
|
18
|
+
if (live) {
|
|
19
|
+
const parts = paragraphs.flatMap(paragraph => [...sentences.segment(paragraph)].map(part => part.segment.trim()).filter(Boolean));
|
|
20
|
+
excerpt = parts.at(-1) ?? full;
|
|
21
|
+
// Keep context across paragraph boundaries while the next sentence is incomplete.
|
|
22
|
+
if (visibleWidth(excerpt) < 12 && parts.length > 1) excerpt = `${parts.at(-2)} ${excerpt}`;
|
|
23
|
+
const marked = excerpt === full ? excerpt : `…${excerpt}`;
|
|
24
|
+
if (fits(marked)) return marked;
|
|
25
|
+
}
|
|
20
26
|
|
|
21
|
-
//
|
|
22
|
-
let
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
27
|
+
// Only live thinking follows the tail. Tools and completed thinking retain the head.
|
|
28
|
+
let result = "";
|
|
29
|
+
const marked = (text: string) => live ? `…${text.trimStart()}` : `${text.trimEnd()}…`;
|
|
30
|
+
const segments = [...words.segment(excerpt)];
|
|
31
|
+
for (const { segment } of live ? segments.reverse() : segments) {
|
|
32
|
+
const candidate = live ? segment + result : result + segment;
|
|
33
|
+
if (!fits(marked(candidate))) break;
|
|
34
|
+
result = candidate;
|
|
26
35
|
}
|
|
27
|
-
if (!
|
|
36
|
+
if (!result.trim()) {
|
|
28
37
|
// An oversized word/path still respects emoji and combining-character boundaries.
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
38
|
+
const characters = [...graphemes.segment(excerpt)];
|
|
39
|
+
for (const { segment } of live ? characters.reverse() : characters) {
|
|
40
|
+
const candidate = live ? segment + result : result + segment;
|
|
41
|
+
if (!fits(marked(candidate))) break;
|
|
42
|
+
result = candidate;
|
|
32
43
|
}
|
|
33
44
|
}
|
|
34
|
-
return
|
|
45
|
+
return result.trim() ? marked(result) : "…";
|
|
35
46
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { ensureThinkingClock, freezeOpenThinkingClocks, freezeThinkingClock, thinkingText, type MinimalTurn, type ThinkingOutcome } from "./minimal-turns.ts";
|
|
2
|
+
|
|
3
|
+
type ThinkingEvent = { type: string; contentIndex?: number; content?: string; partial?: { timestamp?: number } };
|
|
4
|
+
|
|
5
|
+
/** One assistant message owns its block indices; each start owns a fresh process row. */
|
|
6
|
+
export function createThinkingStream() {
|
|
7
|
+
const indices = new Map<number, number>();
|
|
8
|
+
const ended = new Set<number>();
|
|
9
|
+
let owner: MinimalTurn | undefined;
|
|
10
|
+
let closed = true;
|
|
11
|
+
let messageTimestamp: number | undefined;
|
|
12
|
+
let finalized = false;
|
|
13
|
+
const matchesMessage = (timestamp?: number) => messageTimestamp === undefined || timestamp === undefined || timestamp === messageTimestamp;
|
|
14
|
+
const write = (turn: MinimalTurn, content: Array<Record<string, unknown>>, event?: ThinkingEvent) => {
|
|
15
|
+
for (const [block, item] of content.entries()) {
|
|
16
|
+
if (item?.type !== "thinking") continue;
|
|
17
|
+
const terminal = event?.type === "thinking_end" && event.contentIndex === block ? thinkingText({ thinking: event.content }) : "";
|
|
18
|
+
const body = terminal || thinkingText(item);
|
|
19
|
+
let index = indices.get(block);
|
|
20
|
+
if (index === undefined) {
|
|
21
|
+
index = turn.process.length;
|
|
22
|
+
indices.set(block, index);
|
|
23
|
+
turn.process.push(`thinking ${body}`);
|
|
24
|
+
} else if (body) turn.process[index] = `thinking ${body}`;
|
|
25
|
+
// A terminal empty snapshot must not erase already streamed, readable text.
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
reset() { indices.clear(); ended.clear(); owner = undefined; closed = true; messageTimestamp = undefined; finalized = false; },
|
|
30
|
+
start(turn: MinimalTurn, timestamp?: number) {
|
|
31
|
+
freezeOpenThinkingClocks(owner);
|
|
32
|
+
indices.clear(); ended.clear(); owner = turn; closed = false;
|
|
33
|
+
messageTimestamp = timestamp; finalized = false;
|
|
34
|
+
turn.thinking = undefined;
|
|
35
|
+
},
|
|
36
|
+
update(turn: MinimalTurn, content: Array<Record<string, unknown>>, event: ThinkingEvent) {
|
|
37
|
+
if (closed || turn !== owner || !matchesMessage(event.partial?.timestamp)) return false;
|
|
38
|
+
const block = event.contentIndex;
|
|
39
|
+
if (event.type === "thinking_delta" && block !== undefined && ended.has(block)) return false;
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
if (event.type === "thinking_start" && block !== undefined) {
|
|
42
|
+
freezeOpenThinkingClocks(turn);
|
|
43
|
+
for (const previous of indices.keys()) ended.add(previous);
|
|
44
|
+
indices.delete(block);
|
|
45
|
+
ended.delete(block);
|
|
46
|
+
}
|
|
47
|
+
write(turn, content, event);
|
|
48
|
+
if ((event.type === "thinking_start" || event.type === "thinking_delta") && block !== undefined) {
|
|
49
|
+
const index = indices.get(block);
|
|
50
|
+
if (index !== undefined) {
|
|
51
|
+
for (const [previous, previousIndex] of indices) if (previous !== block) {
|
|
52
|
+
ended.add(previous);
|
|
53
|
+
freezeThinkingClock(turn, previousIndex);
|
|
54
|
+
}
|
|
55
|
+
ensureThinkingClock(turn, index, now).lastUpdatedAt = now;
|
|
56
|
+
turn.thinking = index;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (event.type === "thinking_end" && event.contentIndex !== undefined) ended.add(event.contentIndex);
|
|
60
|
+
if (/^(text|toolcall)_/.test(event.type)) for (const block of indices.keys()) ended.add(block);
|
|
61
|
+
for (const [block, index] of indices) if (ended.has(block)) {
|
|
62
|
+
freezeThinkingClock(turn, index);
|
|
63
|
+
if (turn.thinking === index) turn.thinking = undefined;
|
|
64
|
+
}
|
|
65
|
+
return true;
|
|
66
|
+
},
|
|
67
|
+
finish(turn: MinimalTurn, content: Array<Record<string, unknown>>, outcome: ThinkingOutcome = "done", timestamp?: number) {
|
|
68
|
+
if (turn !== owner || finalized || !matchesMessage(timestamp)) return false;
|
|
69
|
+
const active = turn.thinking;
|
|
70
|
+
write(turn, content);
|
|
71
|
+
freezeOpenThinkingClocks(turn, Date.now(), outcome);
|
|
72
|
+
// A failed terminal frame can omit the partial content altogether.
|
|
73
|
+
const failed = active ?? (content.length === 0 || content.at(-1)?.type === "thinking" ? [...indices.values()].at(-1) : undefined);
|
|
74
|
+
if (outcome !== "done" && failed !== undefined) (turn.thinkingOutcomes ??= [])[failed] = outcome;
|
|
75
|
+
turn.thinking = undefined;
|
|
76
|
+
turn.awaitingResponse = false;
|
|
77
|
+
closed = true; finalized = true;
|
|
78
|
+
return true;
|
|
79
|
+
},
|
|
80
|
+
stop(turn: MinimalTurn | undefined, outcome: ThinkingOutcome = "done") {
|
|
81
|
+
if (turn) {
|
|
82
|
+
freezeOpenThinkingClocks(turn, Date.now(), outcome);
|
|
83
|
+
turn.thinking = undefined;
|
|
84
|
+
turn.awaitingResponse = false;
|
|
85
|
+
}
|
|
86
|
+
if (turn === owner) closed = true;
|
|
87
|
+
},
|
|
88
|
+
};
|
|
89
|
+
}
|