pi-hub-server 0.8.0 → 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.
@@ -1,38 +1,67 @@
1
1
  /**
2
- * 会话锁 —— 优先用 `pi-session-lock` 插件的唯一实现,找不到就降级到内置最小实现。
2
+ * 会话锁 —— hub 自带一份实现;`pi-session-lock` 插件是**用户显式安装才有的互通增强**,不是依赖。
3
3
  *
4
- * 加载期**不再 throw**:全新机器上 `pi-hub doctor` / `pi-hub serve` 必须能起来
5
- * (开箱即用是硬指标;旧实现 `throw new Error("pi-session-lock core not found")` 让
6
- * 所有子命令连 import 都过不去)。降级不等于静默:`lockSource` 由 serve banner、
7
- * `pi-hub doctor` 与 `/v1/health` 打出来,`corePath` 指到实际加载的那份,`lockReason`
8
- * 给出降级的**一行原因**。
4
+ * 三种状态(`lockSource`):
5
+ * plugin —— 装了插件且能消费(`CORE_API_VERSION` 匹配 + 7 个函数齐):
6
+ * hub 与桌面 pi / 其它装了插件的进程**共用同一份锁**。
7
+ * fallback —— **默认状态**:没装插件,用 `session-lock-fallback.mjs`。
8
+ * hub 自己(多会话、多端)的互斥照常;只是不与桌面 pi 共享锁。
9
+ * error —— 配置错误:`PI_HUB_SESSION_LOCK_CORE` 指到的不是文件。绝不静默回退(见下)。
9
10
  *
10
- * 解析顺序(显式优先,其次各处常见安装位置):
11
- * 1. `PI_HUB_SESSION_LOCK_CORE`(显式指定,gate 用它验证 plugin/降级两条分支)
12
- * 2. 自身 node_modules —— `require.resolve`,覆盖 `npm i -g pi-session-lock`(全局时是本包的
13
- * 嵌套依赖)与仓内 `npm i pi-session-lock` 两种装法
11
+ * 两种正常模式落盘协议**完全相同**(`lock-protocol.mjs`),所以「装没装插件」只影响互通面,
12
+ * 不影响互斥面 —— 这也是本模块不再把 fallback 说成「降级/异常」的原因。
13
+ *
14
+ * 加载期不 throw:开箱即用是硬指标(全新机器上 `pi-hub doctor` / `serve` / `status` / `-h`
15
+ * 都必须能起来)。没装插件**不刷屏**(本模块被所有子命令 import),原因与「要不要装」的提示
16
+ * 由 `pi-hub doctor`、`serve` banner 与 `/v1/health.sessionLockInfo` 打出来。
17
+ *
18
+ * 唯一例外是**显式配置错误**:设了 `PI_HUB_SESSION_LOCK_CORE` 却指到不存在的文件/目录时,
19
+ * 用户点名的就是那一份,静默换用内置实现等于「你以为在共享锁,其实没有」。此时:
20
+ * - `explicitPointerError` 给出**一行**原因(`/v1/health.sessionLockInfo.explicitPointerError` 也报);
21
+ * - `serve` 在监听前打这一行并以非 0 退出;`doctor` 打这一行并以非 0 退出;
22
+ * - `claim`/`peek`/`release`/… 被调用时抛同一条错误(绝不静默回退)。
23
+ * 但**仍然不在 import 期 throw** —— 本模块被所有子命令共享,import-time throw 会把与锁无关的
24
+ * `pi-hub token` / `-h` / `status` 一起打死(`test/no-plugin.mjs` 钉住这条不变量)。
25
+ *
26
+ * 自动发现顺序(显式优先,其次各处**文档化**的安装位置;每条都带理由,形状由闸门钉死):
27
+ * 1. `PI_HUB_SESSION_LOCK_CORE`(显式指定;指坏了就是上面的 error 状态,不会落到 2-4)
28
+ * 2. 本包依赖解析(`npm i pi-session-lock` 落在本包 node_modules)
14
29
  * 3. 兄弟全局目录 `<prefix>/lib/node_modules/pi-session-lock/core.mjs`(两个包各自全局装)
15
- * 4. `~/pi-plugins/pi-session-lock/core.mjs`(插件仓直接 clone 的装法)
16
- * 5. `~/.pi/agent/npm/node_modules/pi-session-lock/core.mjs`(pi 自己的 npm 布局)
30
+ * 4. `~/.pi/agent/npm/node_modules/pi-session-lock/core.mjs`(pi 自己的 npm 布局)
17
31
  *
18
32
  * 兼容口径:插件 0.6.0 起把 `CORE_API_VERSION` 冻结为对外契约(`core.mjs:35` /
19
33
  * README「冻结面」:不匹配就自己降级,不要猜算法)。所以这里**先验版本再验函数**:
20
- * 版本缺失或不等于 `SUPPORTED_CORE_API` 一律降级,不拿半残的实现去抢锁。
34
+ * 版本缺失或不等于 `SUPPORTED_CORE_API` 一律不用插件,不拿半残的实现去抢锁。
21
35
  */
22
36
  import fs from "node:fs";
23
37
  import path from "node:path";
24
38
  import { createRequire } from "node:module";
25
39
  import { fileURLToPath, pathToFileURL } from "node:url";
26
40
  import { HOME } from "./config.mjs";
41
+ import { REQUIRED_CORE_EXPORTS, SUPPORTED_CORE_API, lockCoreCandidates } from "./lock-protocol.mjs";
27
42
  import * as fallbackLock from "./session-lock-fallback.mjs";
28
43
 
29
44
  const HERE = path.dirname(fileURLToPath(import.meta.url));
30
45
 
31
- /** hub 能消费的 core API 版本;插件 README「冻结面」要求消费方不匹配就降级。 */
32
- const SUPPORTED_CORE_API = 1;
46
+ /** 插件必须给出的函数与可消费版本:常量表在 `lock-protocol.mjs`(与 fallback 同源)。 */
47
+ const REQUIRED = REQUIRED_CORE_EXPORTS;
33
48
 
34
- /** 插件必须给出的函数(= 本模块导出的全部读写面);缺一个就当没装(降级要显式,不能半残着跑)。 */
35
- const REQUIRED = ["identity", "lockDirFor", "peek", "claim", "release", "classify", "readOwner"];
49
+ /**
50
+ * 显式指针的**配置错误**(一行原因);没有设/指到了文件时为 null。
51
+ *
52
+ * 这是「用户说要用哪份插件」与「hub 到底用了哪份」之间唯一允许失败的地方:
53
+ * 指坏了就报错,不猜下一个候选(猜中了别的安装 = 用户被骗)。
54
+ */
55
+ export const explicitPointerError = (() => {
56
+ const pointer = process.env.PI_HUB_SESSION_LOCK_CORE;
57
+ if (!pointer) return null;
58
+ try {
59
+ if (fs.statSync(pointer).isFile()) return null;
60
+ } catch {
61
+ /* 不存在:下面统一报错 */
62
+ }
63
+ return `PI_HUB_SESSION_LOCK_CORE 指到的不是一个文件:${pointer}(不会静默回退到内置锁;改对路径,或清掉这个环境变量)`;
64
+ })();
36
65
 
37
66
  function resolveInstalled() {
38
67
  const require = createRequire(import.meta.url);
@@ -47,15 +76,9 @@ function resolveInstalled() {
47
76
  return null;
48
77
  }
49
78
 
79
+ /** 自动发现候选(`lock-protocol.mjs` 里带每条的理由;**不扫作者本机的仓目录布局**)。 */
50
80
  function candidates() {
51
- return [
52
- process.env.PI_HUB_SESSION_LOCK_CORE,
53
- resolveInstalled(),
54
- path.join(HERE, "..", "node_modules", "pi-session-lock", "core.mjs"),
55
- path.join(HERE, "..", "..", "pi-session-lock", "core.mjs"),
56
- path.join(HOME, "pi-plugins", "pi-session-lock", "core.mjs"),
57
- path.join(HOME, ".pi", "agent", "npm", "node_modules", "pi-session-lock", "core.mjs"),
58
- ].filter(Boolean);
81
+ return lockCoreCandidates({ here: HERE, home: HOME, resolved: resolveInstalled() }).map((c) => c.file);
59
82
  }
60
83
 
61
84
  function exists(p) {
@@ -66,7 +89,8 @@ function exists(p) {
66
89
  }
67
90
  }
68
91
 
69
- const foundPath = candidates().find(exists) ?? null;
92
+ /** 显式指针失效时**不做任何自动发现**:用户点名的那一份不在,别处的安装不算数。 */
93
+ const foundPath = explicitPointerError ? null : candidates().find(exists) ?? null;
70
94
 
71
95
  /** 插件版本:与 core.mjs 同目录的 package.json(找不到就是 null,上报时按 unknown 处理)。 */
72
96
  function readPluginVersion(coreFilePath) {
@@ -78,49 +102,74 @@ function readPluginVersion(coreFilePath) {
78
102
  }
79
103
  }
80
104
 
81
- /** 降级的**一行原因**(plugin 分支为 null);banner / doctor / /v1/health 都打它。 */
82
- let degradeReason = null;
105
+ /** 没用插件时的**一行中性原因**(plugin 分支为 null);banner / doctor / /v1/health 都打它。 */
106
+ let unusedReason = null;
83
107
 
84
- function degrade(reason) {
85
- degradeReason = reason;
86
- console.error(`pi-session-lock 降级到内置实现:${reason}`);
108
+ /**
109
+ * 记下「为什么没用插件」。
110
+ *
111
+ * `loud` 只给「装了但用不了」用:那说明用户以为生效了、其实没有,值得打一行。
112
+ * 「没装」是**默认状态**,不打(本模块被所有子命令 import,刷屏等于把正常状态说成故障)。
113
+ */
114
+ function withoutPlugin(reason, { loud = true } = {}) {
115
+ unusedReason = reason;
116
+ if (loud) console.error(`会话锁:没有用上 pi-session-lock 插件 —— ${reason}`);
87
117
  return null;
88
118
  }
89
119
 
90
120
  async function loadPlugin() {
91
- if (!foundPath) return degrade("没有找到 pi-session-lock 的 core.mjs");
121
+ if (!foundPath) return withoutPlugin("没有找到 pi-session-lock 插件(默认用内置锁)", { loud: false });
92
122
  let mod;
93
123
  try {
94
124
  mod = await import(pathToFileURL(foundPath).href);
95
125
  } catch (err) {
96
- return degrade(`${foundPath} 加载失败:${err.message}`);
126
+ return withoutPlugin(`${foundPath} 加载失败:${err.message}`);
97
127
  }
98
128
  const api = mod.CORE_API_VERSION;
99
129
  if (typeof api !== "number") {
100
- return degrade(`${foundPath} 缺少 CORE_API_VERSION(hub 支持 ${SUPPORTED_CORE_API})`);
130
+ return withoutPlugin(`${foundPath} 缺少 CORE_API_VERSION(hub 支持 ${SUPPORTED_CORE_API})`);
101
131
  }
102
132
  if (api !== SUPPORTED_CORE_API) {
103
- return degrade(`${foundPath} 的 CORE_API_VERSION=${api} 与 hub 支持的 ${SUPPORTED_CORE_API} 不兼容`);
133
+ return withoutPlugin(`${foundPath} 的 CORE_API_VERSION=${api} 与 hub 支持的 ${SUPPORTED_CORE_API} 不兼容`);
104
134
  }
105
135
  const missing = REQUIRED.filter((name) => typeof mod[name] !== "function");
106
- if (missing.length) return degrade(`${foundPath} 缺少 ${missing.join(", ")}`);
136
+ if (missing.length) return withoutPlugin(`${foundPath} 缺少 ${missing.join(", ")}`);
107
137
  return mod;
108
138
  }
109
139
 
140
+ /**
141
+ * 显式指针坏掉时的替身:每个锁操作都抛同一行错误。
142
+ * 用内置实现顶上就是「静默回退」——用户以为在和桌面 pi 共享锁,其实没有。
143
+ */
144
+ function refusingImplementation() {
145
+ const refused = {};
146
+ for (const name of REQUIRED) {
147
+ refused[name] = () => {
148
+ throw new Error(`会话锁不可用:${explicitPointerError}`);
149
+ };
150
+ }
151
+ return refused;
152
+ }
153
+
110
154
  const plugin = await loadPlugin();
111
- const impl = plugin ?? fallbackLock;
155
+ const impl = explicitPointerError ? refusingImplementation() : plugin ?? fallbackLock;
112
156
 
113
- /** 实际使用的锁实现来源:"plugin" | "fallback"(serve banner / doctor / /v1/health 都打它)。 */
114
- export const lockSource = plugin ? "plugin" : "fallback";
115
- /** 插件 core.mjs 的绝对路径;降级时为 null(内置实现的路径就是本仓 src/session-lock-fallback.mjs)。 */
157
+ /** 实际使用的锁来源:"plugin" | "fallback" | "error"(serve banner / doctor / /v1/health 都打它)。 */
158
+ export const lockSource = explicitPointerError ? "error" : plugin ? "plugin" : "fallback";
159
+ /** 插件 core.mjs 的绝对路径;没用插件时为 null(内置实现的路径就是本仓 src/session-lock-fallback.mjs)。 */
116
160
  export const corePath = plugin ? foundPath : null;
117
- /** 插件 package.json 的 version;降级时 null(内置实现没有版本)。 */
161
+ /** 插件 package.json 的 version;没用插件时 null(内置实现没有版本)。 */
118
162
  export const pluginVersion = plugin ? readPluginVersion(foundPath) : null;
119
- /** 插件冻结的 core API 版本;降级时 null(`/v1/health` 用 null 而不是报错)。 */
163
+ /** 插件冻结的 core API 版本;没用插件时 null(`/v1/health` 用 null 而不是报错)。 */
120
164
  export const coreApiVersion = plugin ? plugin.CORE_API_VERSION : null;
121
- /** 降级原因(一行);plugin 分支为 null。 */
122
- export const lockReason = plugin ? null : degradeReason;
123
- /** hub 支持并可消费的 core API 版本(上报用;插件版本不等于它时降级)。 */
165
+ /** 没用插件的原因(一行);plugin 分支为 null。显式指针失效时就是那条配置错误。 */
166
+ export const lockReason = plugin ? null : explicitPointerError ?? unusedReason;
167
+ /** 一行「要不要装插件」的可操作提示;plugin 与「显式指针配错」两种情况下为 null(后者看 explicitPointerError)。 */
168
+ export const lockHint =
169
+ plugin || explicitPointerError
170
+ ? null
171
+ : "内置锁照常工作(hub 内多端互斥不变);要与桌面 pi 共用同一份锁:npm i -g pi-session-lock,或 PI_HUB_SESSION_LOCK_CORE=/abs/path/core.mjs";
172
+ /** hub 支持并可消费的 core API 版本(上报用;插件版本不等于它时不用插件)。 */
124
173
  export const supportedCoreApi = SUPPORTED_CORE_API;
125
174
 
126
175
  export const identity = impl.identity;
@@ -130,6 +179,8 @@ export const claim = impl.claim;
130
179
  export const release = impl.release;
131
180
  export const classify = impl.classify;
132
181
  export const readOwner = impl.readOwner;
133
- /** 判活能力(plugin 若没导出就报 plugin,doctor 只用来提示平台差异)。 */
182
+ /** 判活能力(插件若没导出就报 plugin,doctor 只用来提示平台差异)。 */
134
183
  export const capabilities =
135
- typeof impl.capabilities === "function" ? impl.capabilities : () => ({ platform: process.platform, note: null });
184
+ typeof impl.capabilities === "function"
185
+ ? impl.capabilities
186
+ : () => ({ platform: process.platform, note: explicitPointerError });
@@ -3,7 +3,13 @@ import path from "node:path";
3
3
  import { SESSIONS_DIR } from "./config.mjs";
4
4
 
5
5
  const HEAD_BYTES = 64 * 1024;
6
+ /** 判定 `lastStatus` 只读文件尾部这么多字节:一轮的收尾记录一定在最后,无需整文件扫描。 */
7
+ const TAIL_BYTES = 64 * 1024;
8
+ /** 尾窗口里没有完整 message 行时(最后一条记录本身 >64KB)重试一次的窗口。 */
9
+ const TAIL_RETRY_BYTES = 1024 * 1024;
6
10
  const CACHE_TTL_MS = 3000;
11
+ /** 会话列表 `preview` 的截断长度:客户端把它当未命名会话的标题,160 字够一眼认出。 */
12
+ export const PREVIEW_MAX = 160;
7
13
 
8
14
  /** @type {{at:number, entries:any[]}} */
9
15
  let cache = { at: 0, entries: [] };
@@ -49,19 +55,92 @@ function parseHead(text) {
49
55
  .filter((b) => b?.type === "text")
50
56
  .map((b) => b.text)
51
57
  .join("\n");
52
- if (text) meta.preview = text.slice(0, 160);
58
+ if (text) meta.preview = text.slice(0, PREVIEW_MAX);
53
59
  if (meta.name && meta.id) break;
54
60
  }
55
61
  }
56
62
  return meta;
57
63
  }
58
64
 
65
+ function readTail(file, size, window = TAIL_BYTES) {
66
+ const start = Math.max(0, size - window);
67
+ const length = size - start;
68
+ if (length <= 0) return { text: "", truncated: false };
69
+ const fd = fs.openSync(file, "r");
70
+ try {
71
+ const buf = Buffer.alloc(length);
72
+ const n = fs.readSync(fd, buf, 0, length, start);
73
+ return { text: buf.subarray(0, n).toString("utf8"), truncated: start > 0 };
74
+ } finally {
75
+ fs.closeSync(fd);
76
+ }
77
+ }
78
+
79
+ /** assistant 消息是否以工具调用收尾(本轮还没收口:工具结果或下一轮还没落盘)。 */
80
+ function hasToolCall(content) {
81
+ if (!Array.isArray(content)) return false;
82
+ return content.some((b) => b?.type === "toolCall");
83
+ }
84
+
85
+ /**
86
+ * 一条 `type=message` 记录对应的会话状态(`running` 只能由 live 状态给出,见 `mergedSessions`)。
87
+ * @param {any} message 会话文件里的 `message` 字段
88
+ * @returns {"done"|"aborted"|"error"}
89
+ */
90
+ function statusOfMessage(message) {
91
+ const role = message?.role;
92
+ if (role === "assistant") {
93
+ const stop = message.stopReason;
94
+ if (stop === "error") return "error";
95
+ if (stop === "aborted") return "aborted";
96
+ // stopReason=toolUse 或带 toolCall 块:这一轮在等工具结果,没有收尾记录 ⇒ 进程被杀了。
97
+ if (stop === "toolUse" || hasToolCall(message.content)) return "error";
98
+ // end_turn / stop / max_tokens 等正常结束
99
+ return "done";
100
+ }
101
+ if (role === "toolResult") return "error"; // 工具跑完但助手没回话:中途退出
102
+ if (role === "user") return "error"; // 用户发完就断了,这一轮没开始/没收尾
103
+ return "done";
104
+ }
105
+
106
+ /**
107
+ * 从文件尾部判定 `lastStatus`:取最后一条完整的 `type=message` 记录。
108
+ * 坏行/半行(并发写入被截断)跳过;空会话(没有 message)⇒ `done`。
109
+ * 截断窗口里一条完整 message 都没找到(最后一条记录本身超过窗口)⇒ `null`,调用方换大窗口重试。
110
+ * @param {{text:string, truncated:boolean}} tail `readTail` 的结果
111
+ * @returns {"done"|"aborted"|"error"|null}
112
+ */
113
+ function parseTailStatus(tail) {
114
+ const lines = tail.text.split("\n");
115
+ // 尾部 64KB 从行中间切进来时,第一行必然不完整,丢掉(与 readHistory 丢弃半行同口径)。
116
+ if (tail.truncated) lines.shift();
117
+ for (let i = lines.length - 1; i >= 0; i--) {
118
+ const line = lines[i].trim();
119
+ if (!line) continue;
120
+ let rec;
121
+ try {
122
+ rec = JSON.parse(line);
123
+ } catch {
124
+ continue;
125
+ }
126
+ if (rec?.type !== "message" || !rec.message) continue;
127
+ return statusOfMessage(rec.message);
128
+ }
129
+ // 窗口被截断却一行 message 都没解析出来(最后一条记录 >窗口):不知道就说不知道,
130
+ // 别把 aborted/error 画成 done(R2 用 100KB 尾记录复现过)。
131
+ return tail.truncated ? null : "done";
132
+ }
133
+
59
134
  function readFileMeta(file, stat) {
60
135
  const cached = fileCache.get(file);
61
136
  if (cached && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) return cached.meta;
62
- let meta = { id: null, cwd: null, name: null, createdAt: null, preview: null, model: null };
137
+ let meta = { id: null, cwd: null, name: null, createdAt: null, preview: null, model: null, lastStatus: "done" };
63
138
  try {
64
139
  meta = parseHead(readHead(file));
140
+ // 先 64KB,未命中再 1MB;两次都没有完整 message 行才退回 done(空会话/超长单条记录)。
141
+ meta.lastStatus = parseTailStatus(readTail(file, stat.size, TAIL_BYTES))
142
+ ?? parseTailStatus(readTail(file, stat.size, TAIL_RETRY_BYTES))
143
+ ?? "done";
65
144
  } catch {
66
145
  // 忽略损坏/被并发重写的文件
67
146
  }
@@ -69,9 +148,46 @@ function readFileMeta(file, stat) {
69
148
  return meta;
70
149
  }
71
150
 
151
+ /**
152
+ * 单个会话文件里首条用户消息的文本(截断 `PREVIEW_MAX`);文件不存在/坏行/还没有用户消息 → null。
153
+ * 续会话(resume)时 `LiveSession` 用它补 `firstUserText`:pi 不会重放首条用户消息。
154
+ * @param {string} file
155
+ * @returns {string|null}
156
+ */
157
+ export function readFilePreview(file) {
158
+ try {
159
+ return parseHead(readHead(file)).preview ?? null;
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * 会话列表行的唯一排序口径:`updatedAt` 降序,同 timestamp 用 `id` 升序兜底。
167
+ * 稳定且确定:两个 hub 请求之间同 timestamp 的行不会互换位置(客户端列表不会抖)。
168
+ * 原地排序并返回同一个数组(调用方持有 rows 的所有权)。
169
+ * @template {{id:string, updatedAt?:string|null}} T
170
+ * @param {T[]} rows
171
+ * @returns {T[]}
172
+ */
173
+ export function sortSessionRows(rows) {
174
+ const at = (row) => {
175
+ const ms = Date.parse(row?.updatedAt ?? "");
176
+ return Number.isFinite(ms) ? ms : Number.NEGATIVE_INFINITY;
177
+ };
178
+ return rows.sort((a, b) => {
179
+ const diff = at(b) - at(a);
180
+ if (diff) return diff;
181
+ if (a.id === b.id) return 0;
182
+ return a.id < b.id ? -1 : 1;
183
+ });
184
+ }
185
+
72
186
  /**
73
187
  * 列出会话库里的一级会话文件(不追 subagent 嵌套目录)。
74
- * @param {{limit?:number}} [opts]
188
+ * 每行带 `lastStatus`(`running|done|aborted|error`):这里只能从文件尾部判出后三种,
189
+ * `running` 由 `mergedSessions` 拿 live 状态补;缓存键仍是 mtime+size(同一文件不改不动)。
190
+ * @param {{limit?:number, force?:boolean}} [opts]
75
191
  */
76
192
  export function listSessions(opts = {}) {
77
193
  const limit = opts.limit ?? 200;
@@ -112,6 +228,8 @@ export function listSessions(opts = {}) {
112
228
  preview: meta.preview,
113
229
  model: meta.model,
114
230
  createdAt: meta.createdAt,
231
+ // 行尾三态图标(进行中/完成未读/异常退出)只有 live 行能判「进行中」,磁盘行看文件尾部。
232
+ lastStatus: meta.lastStatus ?? "done",
115
233
  updatedAt: new Date(stat.mtimeMs).toISOString(),
116
234
  updatedAtMs: stat.mtimeMs,
117
235
  file,
@@ -120,7 +238,7 @@ export function listSessions(opts = {}) {
120
238
  });
121
239
  }
122
240
  }
123
- entries.sort((a, b) => b.updatedAtMs - a.updatedAtMs);
241
+ sortSessionRows(entries);
124
242
  cache = { at: now, entries };
125
243
  return entries.slice(0, limit);
126
244
  }
package/src/static.mjs CHANGED
@@ -41,6 +41,8 @@ const EXACT_ROUTES = new Map([
41
41
  ["/app.js", "app.js"],
42
42
  ["/markdown.js", "markdown.js"],
43
43
  ["/model.js", "model.js"],
44
+ // 网页端的纯逻辑(贴底判定 / 草稿键)单独成模块,app.js import 它,node 单测也 import 它
45
+ ["/compose.js", "compose.js"],
44
46
  ["/style.css", "style.css"],
45
47
  // 教程页(pi-hub tutorial 的网页版):静态、免鉴权、不含令牌,可以直接发给手机看。
46
48
  ["/tutorial.html", "tutorial.html"],
package/web/app.js CHANGED
@@ -3,6 +3,7 @@
3
3
  "use strict";
4
4
 
5
5
  import { renderMarkdown } from "./markdown.js";
6
+ import { draftKeyOf, draftStorageKey, isPinned } from "./compose.js";
6
7
  import {
7
8
  formatDuration,
8
9
  formatTokens,
@@ -71,6 +72,10 @@ const state = {
71
72
  usage: null,
72
73
  search: "",
73
74
  pinned: true,
75
+ /** 上一次 scroll 事件的 scrollTop:用来区分「用户主动上滑」和「内容变长」。 */
76
+ lastScrollTop: 0,
77
+ /** 输入框当前对应的草稿键(会话 id / `n:<cwd>`):切会话时换副本,发送成功后清掉。 */
78
+ draftKey: "",
74
79
  /** 桌面侧栏折叠态(跨刷新保持);窄屏忽略。 */
75
80
  sidebarCollapsed: false,
76
81
  /** 抽屉里已折叠的工作区 cwd 列表(跨刷新保持)。 */
@@ -93,6 +98,50 @@ function store(key, value) {
93
98
  return null;
94
99
  }
95
100
 
101
+ function unstore(key) {
102
+ try {
103
+ localStorage.removeItem(key);
104
+ } catch {
105
+ // 同上:删不掉就当没存过
106
+ }
107
+ }
108
+
109
+ // ---------- 输入框草稿(F7:按会话/窗口隔离) ----------
110
+ // 键由 compose.draftKeyOf 决定:会话=会话 id,还没建会话的新窗口=`n:<cwd>`。
111
+ // 隐私模式(localStorage 抛异常)下 store/unstore 静默失败 ⇒ 退化成「刷新即丢」,不是错误。
112
+
113
+ function saveDraft(key, text) {
114
+ if (!key) return;
115
+ if (text) store(draftStorageKey(key), text);
116
+ else unstore(draftStorageKey(key));
117
+ }
118
+
119
+ function loadDraft(key) {
120
+ return (key && store(draftStorageKey(key))) || "";
121
+ }
122
+
123
+ /**
124
+ * 换草稿副本:先把当前键的输入落盘,再从 localStorage 载入新键。
125
+ * 切会话 / 开新会话窗口都走这里,所以旧会话的字不会串到新会话里。
126
+ */
127
+ function switchDraft(nextKey) {
128
+ const input = $("prompt");
129
+ const previous = state.draftKey;
130
+ const text = input.value;
131
+ if (previous && previous !== nextKey) saveDraft(previous, text);
132
+ state.draftKey = nextKey;
133
+ let next = loadDraft(nextKey);
134
+ // 同一份新会话缓冲的“搬家”:还没选工作区(`n:`)时先打的字,选好 cwd 后要跟着进 `n:<cwd>`,
135
+ // 否则用户「先打字、再点仓库组的 +」时会整段字看着没了。会话 ↔ 窗口之间从不搬。
136
+ if (!next && text && previous === draftKeyOf(null, "") && nextKey.startsWith("n:")) {
137
+ next = text;
138
+ saveDraft(nextKey, text);
139
+ }
140
+ if (input.value !== next) input.value = next;
141
+ hideSlash();
142
+ autosize();
143
+ }
144
+
96
145
  class ApiError extends Error {
97
146
  constructor(status, code, message) {
98
147
  super(message || `HTTP ${status}`);
@@ -439,6 +488,7 @@ function appendItemEl(item) {
439
488
  const el = buildItemEl(item);
440
489
  box.append(el);
441
490
  patchItem(item);
491
+ // 新消息只在贴底时跟随(F8);用户上滑后在读上文,位置必须原地不动
442
492
  if (state.pinned) scrollToBottom();
443
493
  }
444
494
 
@@ -501,13 +551,17 @@ function renderMessages() {
501
551
  patchItem(item);
502
552
  }
503
553
  box.append(frag);
554
+ // 整屏重画只在开会话/载入历史时发生(F8 的「用户主动进入」),这里强制贴底;
555
+ // 流式追加绝不能走这条路(否则上滑阅读会被冲刷)
504
556
  scrollToBottom();
505
557
  }
506
558
 
507
559
  function scrollToBottom() {
508
560
  const box = $("messages");
509
561
  box.scrollTop = box.scrollHeight;
562
+ // 程序化滚底后 scroll 事件会异步回来复核一次,这里先把状态置上,避免在回包前被当成“已上滑”
510
563
  state.pinned = true;
564
+ state.lastScrollTop = box.scrollTop;
511
565
  $("btn-jump").hidden = true;
512
566
  }
513
567
 
@@ -935,6 +989,7 @@ function handleEvent(ev) {
935
989
  if (ev.thinking !== undefined) item.thinking = ev.thinking;
936
990
  item.streaming = false;
937
991
  patchItem(item);
992
+ if (state.pinned) scrollToBottom();
938
993
  break;
939
994
  }
940
995
  case "turn_end": {
@@ -1003,9 +1058,14 @@ function handleEvent(ev) {
1003
1058
  }
1004
1059
  }
1005
1060
 
1061
+ /**
1062
+ * 执行态 UI(F9):发送键**始终**可见可点(agent 跑着也能发 = 服务端排队 follow-up),
1063
+ * 额外多出停止键。两键并存,不是以前那样 `hidden = busy` 互斥替换。
1064
+ * 一律只改 `hidden`,不碰 `state.stream`/正在流的消息。
1065
+ */
1006
1066
  function setStreamingUi(busy) {
1007
1067
  state.streaming = busy;
1008
- $("btn-send").hidden = busy;
1068
+ $("btn-send").hidden = false;
1009
1069
  $("btn-stop").hidden = !busy;
1010
1070
  }
1011
1071
 
@@ -1177,6 +1237,9 @@ async function send() {
1177
1237
  const input = $("prompt");
1178
1238
  const text = input.value.trim();
1179
1239
  if (!text && !state.images.length && !state.docs.length) return;
1240
+ // 发送成功后要清的草稿键:ensureSession 新建会话时 state.draftKey 会换成新会话 id,
1241
+ // 所以这里先把「写字时那个键」记下来,两边都清。
1242
+ const sentDraftKey = state.draftKey;
1180
1243
  let finalText = text;
1181
1244
  for (const doc of state.docs) {
1182
1245
  finalText += `${finalText ? "\n\n" : ""}[附件] ${doc.path}`;
@@ -1185,19 +1248,29 @@ async function send() {
1185
1248
  try {
1186
1249
  const id = await ensureSession();
1187
1250
  input.value = "";
1251
+ saveDraft(sentDraftKey, "");
1252
+ saveDraft(state.draftKey, "");
1188
1253
  hideSlash();
1189
1254
  autosize();
1190
1255
  state.images = [];
1191
1256
  state.docs = [];
1192
1257
  renderAttachments();
1258
+ // 用户自己发言 = 唯一无条件跟随的时机(F8):强制贴底并滚到底,焦点回输入框(F7)
1193
1259
  state.pinned = true;
1260
+ scrollToBottom();
1261
+ input.focus();
1194
1262
  const body = { text: finalText };
1195
1263
  if (images.length) body.images = images;
1264
+ // F9:执行中发送必须显式声明排队语义(服务端 readStreamingBehavior 只认 steer/followUp),
1265
+ // 不传就会被 pi 以 409 prompt_rejected 拒掉(W-VERIFY 实测)。
1266
+ if (state.streaming) body.streamingBehavior = "followUp";
1196
1267
  const data = await api(`/v1/sessions/${id}/prompt`, { method: "POST", body });
1268
+ // 执行中发送(F9):服务端自行排队 follow-up,UI 只提示一句,不改 streaming 也不清流
1197
1269
  if (data?.disposition === "queued") toast("已排队(正在生成)");
1198
1270
  setStreamingUi(true);
1199
1271
  } catch (err) {
1200
1272
  input.value = text;
1273
+ saveDraft(state.draftKey, text);
1201
1274
  toast(`发送失败:${err.message}`);
1202
1275
  }
1203
1276
  }
@@ -1265,6 +1338,8 @@ function selectSessionModel(select, model) {
1265
1338
 
1266
1339
  async function openSession(id) {
1267
1340
  state.sessionId = id;
1341
+ // 草稿换成这条会话的副本(F7):先把上一个键的输入落盘,再载入这里(新建的会话是空草稿)
1342
+ switchDraft(draftKeyOf(id, null));
1268
1343
  state.items = [];
1269
1344
  state.streaming = false;
1270
1345
  state.stats = null;
@@ -1485,6 +1560,7 @@ async function forkSession({ item = null, clone = false } = {}) {
1485
1560
  // 非 clone 时服务端回传被分叉的那条 user 文本:回填输入框方便改完重问
1486
1561
  if (!clone && data.text) {
1487
1562
  $("prompt").value = data.text;
1563
+ saveDraft(state.draftKey, data.text);
1488
1564
  autosize();
1489
1565
  $("prompt").focus();
1490
1566
  }
@@ -1653,6 +1729,8 @@ function openNewSession(cwd) {
1653
1729
  } else showDrawer();
1654
1730
  loadSessions().catch(() => {});
1655
1731
  setNewSessionOpen(true, cwd);
1732
+ // 新会话窗口有自己的草稿副本(F7):按表单里实际生效的 cwd 取键(`n:<cwd>`,空 cwd 也有一份)
1733
+ switchDraft(draftKeyOf(null, $("new-cwd").value.trim()));
1656
1734
  }
1657
1735
 
1658
1736
  function showLogin(message) {
@@ -1862,6 +1940,8 @@ function wire() {
1862
1940
  $("prompt").addEventListener("input", () => {
1863
1941
  autosize();
1864
1942
  updateSlash();
1943
+ // 边打边存:切会话/刷新都不丢(F7);隐私模式下 saveDraft 静默失败
1944
+ saveDraft(state.draftKey, $("prompt").value);
1865
1945
  });
1866
1946
  $("prompt").addEventListener("blur", hideSlash);
1867
1947
  $("prompt").addEventListener("keydown", (event) => {
@@ -1920,9 +2000,15 @@ function wire() {
1920
2000
  });
1921
2001
  $("messages").addEventListener("scroll", () => {
1922
2002
  const box = $("messages");
1923
- const atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 60;
1924
- state.pinned = atBottom;
1925
- $("btn-jump").hidden = atBottom;
2003
+ // 贴底判定走 compose.isPinned(阈值 32,可 node 单测)。
2004
+ // F8 修复(W-VERIFY):流式 append 会让 scrollHeight 变长而 scrollTop 不动,
2005
+ // 此刻 gap>32 不等于「用户上滑」——只有 scrollTop 真的变小才失跟,否则保持原状态。
2006
+ const top = box.scrollTop;
2007
+ const prev = state.lastScrollTop;
2008
+ if (isPinned(box)) state.pinned = true;
2009
+ else if (top < prev - 2) state.pinned = false;
2010
+ state.lastScrollTop = top;
2011
+ $("btn-jump").hidden = state.pinned;
1926
2012
  });
1927
2013
  $("btn-jump").addEventListener("click", scrollToBottom);
1928
2014
  $("messages").addEventListener("click", async (event) => {
@@ -2004,6 +2090,8 @@ async function boot() {
2004
2090
  state.collapsedGroups = parseCollapsedGroups(store(STORE_KEYS.collapsedGroups));
2005
2091
  wire();
2006
2092
  autosize();
2093
+ // 首屏草稿(F7):还没开会话时用「上次工作区」的新会话键;记住的会话在 openSession 里换副本
2094
+ switchDraft(draftKeyOf(null, store(STORE_KEYS.cwd) ?? ""));
2007
2095
  // 首帧定屏:两屏在 HTML 里都带 hidden,若等 /v1/web/session 往返结束才显示,
2008
2096
  // 首次访问会先看到一片纯背景色(这就是「第一次进来闪一下」)。
2009
2097
  // 这里同步按上次登录态先画一屏骨架,拿到真实结果再纠正。
@@ -2023,7 +2111,7 @@ async function boot() {
2023
2111
  return;
2024
2112
  }
2025
2113
  markAuthed(false);
2026
- // `pi-hub web-login` 打印的链接带 #code=XXXX-XXXX:直接兑换成 cookie,不要求手输。
2114
+ // `pi-hub web` 打印的链接带 #code=XXXX-XXXX:直接兑换成 cookie,不要求手输。
2027
2115
  const hash = new URLSearchParams(location.hash.replace(/^#/, ""));
2028
2116
  const code = hash.get("code");
2029
2117
  if (code) {
package/web/compose.js ADDED
@@ -0,0 +1,39 @@
1
+ // 网页端的纯逻辑(无 DOM、无 localStorage、无网络):node 直接单测,见 test/web-compose.mjs。
2
+ // app.js 只负责把 DOM 量出来的数喂进来、把键写进 localStorage;判定与拼键都留在这里。
3
+ "use strict";
4
+
5
+ /** 「贴底」阈值(px):与安卓端 `offset < 32px` 同一量级。差半屏不算贴底,否则上滑也会被拽回来。 */
6
+ export const PIN_BOTTOM_THRESHOLD = 32;
7
+
8
+ /**
9
+ * 是否「贴底」——只有它为真时,流式/新消息才允许自动滚到底。
10
+ * `metrics` 可以是 `{scrollHeight, scrollTop, clientHeight}`,也可以直接传滚动容器元素(同名字段)。
11
+ * 量不到(null / 字段缺失)按 0 算 ⇒ 贴底,等价于「没有视口就谈不上偏离」。
12
+ * @param {{scrollHeight?: number, scrollTop?: number, clientHeight?: number}|null} metrics
13
+ * @returns {boolean}
14
+ */
15
+ export function isPinned(metrics) {
16
+ const { scrollHeight = 0, scrollTop = 0, clientHeight = 0 } = metrics ?? {};
17
+ return scrollHeight - scrollTop - clientHeight < PIN_BOTTOM_THRESHOLD;
18
+ }
19
+
20
+ /** 草稿在 localStorage 里的键前缀:一条会话/一个窗口一条记录。 */
21
+ export const DRAFT_STORAGE_PREFIX = "pihub.draft.";
22
+
23
+ /**
24
+ * 草稿键:会话里=会话 id;还没建会话的新开窗口=`n:<cwd>`。
25
+ * 所以同一 cwd 的新窗口共用一份草稿、不同 cwd 各自独立;cwd 为空(空项目/空会话)也有
26
+ * `n:` 这一份兜底草稿,不会因为「还没工作区」就不留字。
27
+ * @param {string|null|undefined} sessionId
28
+ * @param {string|null|undefined} cwd
29
+ * @returns {string}
30
+ */
31
+ export function draftKeyOf(sessionId, cwd) {
32
+ if (sessionId) return String(sessionId);
33
+ return `n:${cwd ?? ""}`;
34
+ }
35
+
36
+ /** 草稿键 → localStorage 键(集中在这里,测试可以直接断言不会串键)。 */
37
+ export function draftStorageKey(key) {
38
+ return `${DRAFT_STORAGE_PREFIX}${key}`;
39
+ }