pi-hub-server 0.4.2 → 0.9.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/web/model.js ADDED
@@ -0,0 +1,342 @@
1
+ // 网页端的纯数据层:历史消息 → 渲染项、工具卡状态文案、时长格式。
2
+ // 不碰 DOM,所以能在 node 里直接 import 单测(`test/web-model.mjs`);渲染与事件处理留在 app.js。
3
+ "use strict";
4
+
5
+ /** 毫秒 → 人读时长(`320ms` / `2.4s` / `1m05s`),历史回放与流式同一套口径。 */
6
+ export function formatDuration(ms) {
7
+ if (ms === null || ms === undefined || ms === "") return "";
8
+ const v = Number(ms);
9
+ if (!Number.isFinite(v) || v < 0) return "";
10
+ if (v < 1000) return `${Math.round(v)}ms`;
11
+ if (v < 60_000) return `${(v / 1000).toFixed(1)}s`;
12
+ const minutes = Math.floor(v / 60_000);
13
+ const seconds = Math.round((v % 60_000) / 1000);
14
+ return `${minutes}m${String(seconds).padStart(2, "0")}s`;
15
+ }
16
+
17
+ /**
18
+ * 推理强度的中文标签(`off` → 关 …)。`#thinking-select` 的 option **value 仍是原始 level**,
19
+ * 只换 label,否则 `POST /v1/sessions/:id/thinking` 会收到中文串。
20
+ */
21
+ const THINKING_LEVEL_LABELS = {
22
+ off: "关",
23
+ minimal: "极简",
24
+ low: "低",
25
+ medium: "中",
26
+ high: "高",
27
+ xhigh: "极高",
28
+ max: "最大",
29
+ };
30
+
31
+ export function thinkingLevelLabel(level) {
32
+ const raw = String(level ?? "");
33
+ return THINKING_LEVEL_LABELS[raw.trim().toLowerCase()] ?? raw;
34
+ }
35
+
36
+ /** 工具卡右侧状态文案:耗时一律带上(只有「完成」看不出这条命令跑了多久)。 */
37
+ export function toolStateText(tool, now = Date.now()) {
38
+ const took = formatDuration(tool.durationMs);
39
+ if (tool.isError) return took ? `失败 · ${took}` : "失败";
40
+ if (tool.state === "done") return took ? `完成 · ${took}` : "完成";
41
+ if (tool.state === "running") {
42
+ const elapsed = tool.startedAt ? formatDuration(now - tool.startedAt) : "";
43
+ return elapsed ? `运行中… ${elapsed}` : "运行中…";
44
+ }
45
+ return "排队中";
46
+ }
47
+
48
+ /**
49
+ * 会话标题:`name` → `cwd` 的目录名 → 短 id(8 字符)。
50
+ * 以前直接拿 `sessionId` 当标题,顶栏整行就是一条 UUID(用户截图实测);完整值放 title 属性。
51
+ */
52
+ export function sessionTitle(session, fallbackId = "") {
53
+ const name = String(session?.name ?? "").trim();
54
+ if (name) return name;
55
+ const cwd = String(session?.cwd ?? "").replace(/[/\\]+$/, "");
56
+ const base = cwd.split(/[/\\]/).pop()?.trim();
57
+ if (base) return base;
58
+ const id = String(session?.sessionId ?? fallbackId ?? "");
59
+ return id ? id.slice(0, 8) : "pi hub";
60
+ }
61
+
62
+ /**
63
+ * token 数 → `1.60M` / `160.0k` / `980`(脚注与历史回放同一套口径)。
64
+ * M 两位是安卓 `Stats.kt` 的口径(`1.00M / 28.39M`):同一会话换端看数字不能变。
65
+ */
66
+ export function formatTokens(n) {
67
+ const v = Number(n) || 0;
68
+ if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(2)}M`;
69
+ if (v >= 1000) return `${(v / 1000).toFixed(1)}k`;
70
+ return String(v);
71
+ }
72
+
73
+ /**
74
+ * 底部用量脚注:同一条信息只出现一次,合成一行(W1-b)。
75
+ * 宽屏 `上下文 16% · 160.0k/1.00M · 速率 100.3 tok/s · 缓存命中 98.2% · $1.235`;
76
+ * 窄屏(<420px,CSS 切)只留 `16% · $1.23`。
77
+ * 四舍五入口径对齐安卓(速率/命中率 1 位、M 两位、成本 3 位),字段名对齐「速率 / 缓存命中」。
78
+ * 字段缺失就整段不画,不编数字;`tokensPerSecond`/`cacheHitRate` 为 null 一律跳过。
79
+ */
80
+ export function usageLines(stats, usage) {
81
+ const parts = [];
82
+ const narrow = [];
83
+ const ctx = stats?.contextUsage ?? null;
84
+ if (ctx && Number.isFinite(ctx.percent)) {
85
+ const pct = `${Math.round(ctx.percent)}%`;
86
+ parts.push(`上下文 ${pct}`);
87
+ narrow.push(pct);
88
+ if (Number.isFinite(ctx.tokens)) {
89
+ const window = Number.isFinite(ctx.contextWindow) ? `/${formatTokens(ctx.contextWindow)}` : "";
90
+ parts.push(`${formatTokens(ctx.tokens)}${window}`);
91
+ }
92
+ } else if (usage?.totalTokens) {
93
+ parts.push(`本机累计 ${formatTokens(usage.totalTokens)} tokens`);
94
+ }
95
+ const rate = stats?.tokensPerSecond;
96
+ if (typeof rate === "number" && Number.isFinite(rate) && rate > 0) parts.push(`速率 ${rate.toFixed(1)} tok/s`);
97
+ const hit = stats?.cacheHitRate;
98
+ if (typeof hit === "number" && Number.isFinite(hit)) parts.push(`缓存命中 ${(hit * 100).toFixed(1)}%`);
99
+ const cost = stats?.cost ?? usage?.cost ?? null;
100
+ if (typeof cost === "number" && cost > 0) {
101
+ parts.push(`$${cost.toFixed(3)}`);
102
+ narrow.push(`$${cost.toFixed(2)}`);
103
+ }
104
+ return { full: parts.join(" · "), narrow: narrow.join(" · ") };
105
+ }
106
+
107
+ /** 参数文本:单键 `command` 直接给命令本体,其余按 JSON 缩进(bash 展开后第一眼就是命令)。 */
108
+ export function toolInputText(tool) {
109
+ const args = tool.args;
110
+ if (args === undefined || args === null) return "";
111
+ if (typeof args === "string") return args;
112
+ if (typeof args === "object") {
113
+ const keys = Object.keys(args);
114
+ if (keys.length === 1 && typeof args.command === "string") return args.command;
115
+ try {
116
+ return JSON.stringify(args, null, 2);
117
+ } catch {
118
+ return String(args);
119
+ }
120
+ }
121
+ return String(args);
122
+ }
123
+
124
+ /** option value 里的模型 id:`provider/id` 取最后一个 `/` 之后(provider 本身带点,不能按第一个切)。 */
125
+ export function modelIdPart(value) {
126
+ const s = String(value ?? "");
127
+ const slash = s.lastIndexOf("/");
128
+ return slash === -1 ? s : s.slice(slash + 1);
129
+ }
130
+
131
+ /**
132
+ * 会话模型 → 候选 option value。
133
+ * `/v1/sessions` 的历史行给的是裸 id(`ustc-dsf`,来自 `model_change.modelId`),
134
+ * live 快照给 `{provider,id}` 对象;而 `#model-select` 的 value 是 `provider/id`。
135
+ * 所以裸 id 只能靠 id 部分匹配,这里把两种形态拉平成候选列表(精确值在前)。
136
+ */
137
+ export function modelValueCandidates(model) {
138
+ if (model && typeof model === "object") {
139
+ const out = [];
140
+ if (model.provider && model.id) out.push(`${model.provider}/${model.id}`);
141
+ if (model.id) out.push(String(model.id));
142
+ return out;
143
+ }
144
+ const raw = String(model ?? "");
145
+ return raw ? [raw] : [];
146
+ }
147
+
148
+ /**
149
+ * 在 option value 列表里挑出会话模型对应的那个:先精确匹配,再按 id 部分匹配。
150
+ * 都匹配不上返回 null —— 调用方据此画「当前模型不在列表」的项,而不是停在「模型…」占位。
151
+ */
152
+ export function matchModelValue(values, model) {
153
+ const candidates = modelValueCandidates(model);
154
+ if (!candidates.length) return null;
155
+ const list = [...(values ?? [])];
156
+ for (const candidate of candidates) if (list.includes(candidate)) return candidate;
157
+ const wanted = candidates.map(modelIdPart);
158
+ for (const value of list) if (wanted.includes(modelIdPart(value))) return value;
159
+ return null;
160
+ }
161
+
162
+ /**
163
+ * 历史消息 → 客户端渲染项。
164
+ * `toolResult` 是独立消息行,必须按 `toolCallId` 并回对应工具卡片;丢弃它的话重开会话后
165
+ * 卡片只有「完成」,展开看不到输出、也没有耗时(R4 网页实测)。
166
+ * @param {Array<any>} messages `/history` 返回的 messages
167
+ */
168
+ export function historyToItems(messages) {
169
+ const items = [];
170
+ const byCallId = new Map();
171
+ for (const m of messages ?? []) {
172
+ if (m.role === "user") {
173
+ items.push({ role: "user", text: m.text ?? "", ts: m.ts });
174
+ continue;
175
+ }
176
+ if (m.role === "toolResult" || m.role === "tool") {
177
+ const tool = byCallId.get(m.toolCallId);
178
+ if (!tool) continue;
179
+ tool.state = "done";
180
+ tool.isError = m.isError === true;
181
+ if (m.durationMs !== undefined && m.durationMs !== null) tool.durationMs = m.durationMs;
182
+ if (m.toolName) tool.name = m.toolName;
183
+ if (m.text) tool.preview = m.text;
184
+ continue;
185
+ }
186
+ if (m.role !== "assistant") continue;
187
+ const toolMap = new Map();
188
+ const order = [];
189
+ for (const call of m.toolCalls ?? []) {
190
+ if (!call?.id) continue;
191
+ const tool = {
192
+ id: call.id,
193
+ name: call.name ?? "tool",
194
+ args: call.args,
195
+ state: "done",
196
+ preview: null,
197
+ isError: false,
198
+ durationMs: null,
199
+ };
200
+ toolMap.set(call.id, tool);
201
+ byCallId.set(call.id, tool);
202
+ order.push(call.id);
203
+ }
204
+ items.push({
205
+ role: "assistant",
206
+ text: m.text ?? "",
207
+ thinking: m.thinking ?? "",
208
+ tools: toolMap,
209
+ toolOrder: order,
210
+ streaming: false,
211
+ usage: m.usage ?? null,
212
+ model: m.model ?? null,
213
+ durationMs: m.durationMs ?? null,
214
+ stopReason: m.stopReason ?? null,
215
+ ts: m.ts,
216
+ el: null,
217
+ refs: null,
218
+ });
219
+ }
220
+ return items;
221
+ }
222
+
223
+ /**
224
+ * 锚定菜单的落点(F1):菜单必须从**被点的那一个按钮**旁长出,且永不出窗口。
225
+ * 顺序:左窄栏(图标栏)里右缘对齐会溢出左边 ⇒ 从按钮右侧长出;否则优先下方,
226
+ * 下方放不下就上翻,仍放不下就夹在视口内(clamp)。
227
+ * 纯函数,交给 `test/web-model.mjs` 用假矩形验算;实际测量在 app.js 的 openMenuAt()。
228
+ * @param {{left:number,right:number,top:number,bottom:number}} anchorRect
229
+ * @param {{width:number,height:number}} menuSize
230
+ * @param {{width:number,height:number}} viewport
231
+ * @param {number} [gap] 菜单与按钮之间的缝(px)
232
+ * @returns {{left:number,top:number,placement:"right"|"below"|"above"|"clamped"}}
233
+ */
234
+ export function menuPlacement(anchorRect, menuSize, viewport, gap = 10) {
235
+ const EDGE = 4;
236
+ const { right: ar, top: at, bottom: ab } = anchorRect;
237
+ const mw = menuSize.width;
238
+ const mh = menuSize.height;
239
+ const vw = viewport.width;
240
+ const vh = viewport.height;
241
+ const clamp = (v, max) => Math.max(EDGE, Math.min(Math.round(v), Math.round(max)));
242
+ const alignRight = ar - mw;
243
+ // 56px 图标栏:按钮右缘对齐会把菜单推到窗口左边界外,改从按钮右侧长出来
244
+ if (alignRight < EDGE && vw - ar >= mw + gap + EDGE) {
245
+ return { left: ar + gap, top: clamp(at, vh - mh - EDGE), placement: "right" };
246
+ }
247
+ const left = clamp(alignRight, vw - mw - EDGE);
248
+ if (ab + gap + mh <= vh - EDGE) return { left, top: ab + gap, placement: "below" };
249
+ if (at - gap - mh >= EDGE) return { left, top: at - gap - mh, placement: "above" };
250
+ return { left, top: clamp(ab + gap, vh - mh - EDGE), placement: "clamped" };
251
+ }
252
+
253
+ /**
254
+ * 主机 home 的最佳猜测(对齐安卓 `guessHome`):只认 `/home/<user>`、`/Users/<user>`、`/root`。
255
+ * 猜不到返回 null,路径展示退化为原样 —— 网页拿不到服务端 home,只能从 cwd 里认。
256
+ */
257
+ export function guessHome(paths) {
258
+ const re = /^(\/home\/[^/]+|\/Users\/[^/]+|\/root)(\/|$)/;
259
+ for (const path of paths ?? []) {
260
+ const hit = re.exec(String(path ?? "").trim());
261
+ if (hit) return hit[1];
262
+ }
263
+ return null;
264
+ }
265
+
266
+ /** 路径的 `~` 缩写(`/home/me/x` + home=/home/me → `~/x`)。 */
267
+ function shortenHome(path, home) {
268
+ const p = String(path ?? "").trim().replace(/[/\\]+$/, "");
269
+ const h = String(home ?? "").trim().replace(/[/\\]+$/, "");
270
+ if (!p) return "";
271
+ if (!h) return p;
272
+ if (p === h) return "~";
273
+ if (p.startsWith(`${h}/`)) return `~${p.slice(h.length)}`;
274
+ return p;
275
+ }
276
+
277
+ /**
278
+ * 窄屏路径标签(对齐安卓 `pathDisplayLabel`):`~` 缩写后只留末两段(`~/…/foo/bar`)。
279
+ * 末两段以内原样返回,保证「看得出是哪一层」。
280
+ */
281
+ export function displayPathLabel(path, home) {
282
+ const raw = String(path ?? "").trim();
283
+ if (!raw) return "";
284
+ if (raw === "/") return "/";
285
+ const shortened = shortenHome(raw, home) || "/";
286
+ if (shortened === "~" || shortened === "/") return shortened;
287
+ const homeBased = shortened.startsWith("~/");
288
+ const body = shortened.replace(/^~\//, "").replace(/^\//, "");
289
+ const segs = body.split("/").filter(Boolean);
290
+ if (segs.length <= 2) return shortened;
291
+ const prefix = homeBased ? "~/" : shortened.startsWith("/") ? "/" : "";
292
+ return `${prefix}…/${segs.slice(-2).join("/")}`;
293
+ }
294
+
295
+ /**
296
+ * 会话组头的两段文案(对齐安卓「名称 + ~ 缩写路径」):
297
+ * 名称 = cwd 末段,路径 = displayPathLabel;路径与名称相同时不重复画。
298
+ */
299
+ export function workspaceHeader(cwd, home) {
300
+ const raw = String(cwd ?? "").trim();
301
+ if (!raw) return { name: "(未知工作区)", path: "" };
302
+ const trimmed = raw.replace(/[/\\]+$/, "");
303
+ const name = trimmed.split(/[/\\]/).pop()?.trim() || raw;
304
+ const path = displayPathLabel(raw, home);
305
+ return { name, path: path === name ? "" : path };
306
+ }
307
+
308
+ /** 工作区分组折叠态存成 JSON 数组(按 cwd 记,含「未分类」组用的那句占位 cwd)。 */
309
+ export function parseCollapsedGroups(raw) {
310
+ try {
311
+ const parsed = JSON.parse(raw ?? "[]");
312
+ return Array.isArray(parsed) ? parsed.filter((v) => typeof v === "string") : [];
313
+ } catch {
314
+ // 坏数据当作没折叠过,不能因为一条 localStorage 就让抽屉渲染不出来
315
+ return [];
316
+ }
317
+ }
318
+
319
+ /** 翻转某个 cwd 的折叠态,返回新数组(不改入参)。 */
320
+ export function toggleCollapsedGroup(list, cwd) {
321
+ const current = [...(list ?? [])];
322
+ return current.includes(cwd) ? current.filter((value) => value !== cwd) : [...current, cwd];
323
+ }
324
+
325
+ /** 折叠态分组头右侧的会话数(展开态不显示:列表本身就是答案)。 */
326
+ export function groupCollapsedText(count) {
327
+ return `${Number(count) || 0} 个会话`;
328
+ }
329
+
330
+ /**
331
+ * 会话用的模型:优先 `/state` 的会话快照,其次历史里最后一条带 model 的 assistant 消息。
332
+ * `starting` 的新会话 live 快照常常还没有 model(F4 用户截图),没有它就只能停在占位;
333
+ * 都拿不到返回 null —— 调用方据此显示「默认」而不是空占位。
334
+ */
335
+ export function pickSessionModel(sessionModel, items) {
336
+ if (modelValueCandidates(sessionModel).length) return sessionModel;
337
+ for (let i = (items?.length ?? 0) - 1; i >= 0; i -= 1) {
338
+ const model = items[i]?.model;
339
+ if (modelValueCandidates(model).length) return model;
340
+ }
341
+ return null;
342
+ }