pi-session-lock 0.3.1 → 0.5.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,56 +1,119 @@
1
1
  /**
2
2
  * session-lock(pi 侧适配层)—— 逻辑全在 ../core.mjs,与进程外调用方共用一份实现。
3
+ * 只读跟随的解析/渲染/信箱投递在 ../follow.mjs。
3
4
  *
4
5
  * 这里只做:把 pi 的 extension 钩子接到 core 的 claim/peek/release 上。
5
- * 策略保持原样:不阻止启动、只拦人的动作(input / user_bash)、能证明冲突才拦、
6
- * 说不清就 fail-open、/session-lock 可查、/session-lock-release 只回收已证死的锁。
7
6
  *
8
- * paseo 兼容(2026-12-04 实测):
9
- * paseo daemon 给每个 agent 常驻一个 pi 子进程(`input` 走 source=rpc,空闲时进程也活着),
10
- * 所以「session_start 就认领」会让空转的 paseo agent 永久占住会话,TUI 里 /resume 直接报
11
- * 「另一个活进程正在用这个会话」。改成**按轮持锁**:
12
- * session_start 不认领 → input / agent_start 认领 → agent_settled 立刻释放。
13
- * 锁只在真正写盘的窗口内存在,空闲的 paseo agent 什么都不占。
7
+ * 策略(2026-12-05 起「削弱语义」):
8
+ * - 默认 PI_SESSION_LOCK_CONFLICT=ask:发现别的活进程持锁时弹窗询问发起方,二选一:
9
+ * 「Fork 新会话」→ ctx.fork 复制当前分支(history 完整,header 记 parentSession);
10
+ * 「只读跟随」 → 不持锁/不写盘,输入经 pi-mailbox 转给对方(TUI 里打开跟随窗口)。
11
+ * - 没人能回答(自动化托管会话 / print / json)→ 退回 fork 流程:写 yield-request,
12
+ * 等 PI_SESSION_LOCK_GRACE_MS,对方空闲就让锁接管原会话,否则自动 fork。
13
+ * - PI_SESSION_LOCK_CONFLICT=fork 跳过询问直接走 fork 流程;=follow 直接只读跟随;
14
+ * =block 恢复老的「直接拦输入」语义。
14
15
  *
15
- * 反方向(TUI 窗口空转持锁、paseo 要接着聊):要锁的一方写 yield-request.json,
16
- * 持有者空闲时看到一个活着且未过期的请求就让锁;paseo 侧被拦下的那条消息会在
17
- * 拿到锁之后重放(60 秒窗口),做到「手机上发一句,桌面上那个窗口自动让位」。
16
+ * paseo 兼容(2026-12-04 实测):paseo daemon 给每个 agent 常驻一个 pi 子进程
17
+ * (`input` 走 source=rpc,空闲时进程也活着),所以 paseo 托管进程按轮持锁
18
+ * (session_start 不认领 → input/agent_start 认领 → agent_settled 释放),
19
+ * 空闲时看到让锁请求就 release;**paseo 侧不自动 fork**(daemon 按会话 id 管理 agent,
20
+ * 换文件会破坏它的映射),仍是「请求让锁 + 60s 内重放」。
21
+ *
22
+ * 只读跟随(/session-lock-follow):渲染对方会话的当前分支,不持锁、不写盘;
23
+ * 在这个界面里输入的话经 pi-mailbox 投给持有者进程(等同对方窗口里敲一句)。
18
24
  */
19
25
  import fs from "node:fs";
26
+ import path from "node:path";
20
27
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
28
+ import { SessionManager } from "@earendil-works/pi-coding-agent";
29
+ import {
30
+ Editor,
31
+ Key,
32
+ matchesKey,
33
+ truncateToWidth,
34
+ visibleWidth,
35
+ wrapTextWithAnsi,
36
+ type EditorTheme,
37
+ } from "@earendil-works/pi-tui";
21
38
  import {
22
39
  claim,
23
40
  classify,
24
41
  clearYieldRequest,
42
+ describeActivity,
43
+ describeOwner,
25
44
  enabled,
26
45
  lockDirFor,
27
46
  paseoManaged,
47
+ peek,
28
48
  readOwner,
49
+ readPresence,
29
50
  readYieldRequest,
30
51
  release,
31
52
  requestYield,
32
53
  } from "../core.mjs";
54
+ import { activeBranch, readSessionDelta, sendToMailbox, transcriptLines } from "../follow.mjs";
33
55
 
34
56
  const PASEO = paseoManaged();
35
57
  const PASEO_SOURCE = PASEO?.label ?? "pi-session-lock";
36
- const YIELD_POLL_MS = 15_000; // 持锁方多久看一次让锁请求
37
- const YIELD_RETRY_MS = 3_000; // 请求方多久重试一次认领
38
- const REPLAY_WINDOW_MS = 60_000; // 重试多久还没拿到锁就放弃并提示重发
58
+ const YIELD_POLL_MS = Number(process.env.PI_SESSION_LOCK_YIELD_POLL_MS ?? 5000); // 持锁方多久看一次让锁请求(≈ grace 的一半,空闲时通常能先让出)
59
+ const YIELD_RETRY_MS = 3_000; // paseo 请求方多久重试一次认领
60
+ const REPLAY_WINDOW_MS = 60_000; // paseo 重试多久还没拿到锁就放弃并提示重发
39
61
  const DEBUG = process.env.PI_SESSION_LOCK_DEBUG === "1"; // 兼容排障用:事件流水落一个文件
40
62
  const DEBUG_LOG = process.env.PI_SESSION_LOCK_DEBUG_LOG ?? "/tmp/pi-session-lock-debug.log";
41
63
 
64
+ /**
65
+ * 冲突策略:
66
+ * ask(默认)—— 弹窗让发起方二选一:Fork 新会话 / 只读跟随(输入经 pi-mailbox 转给对方)
67
+ * fork —— 不弹窗,等对方让锁,超时自动 fork
68
+ * follow —— 不弹窗,直接只读跟随(输入都转给对方)
69
+ * block —— 老语义:直接拦输入
70
+ */
71
+ type Policy = "ask" | "fork" | "follow" | "block";
72
+ const POLICY: Policy = (() => {
73
+ const raw = (process.env.PI_SESSION_LOCK_CONFLICT ?? "ask").toLowerCase();
74
+ return raw === "fork" || raw === "follow" || raw === "block" ? raw : "ask";
75
+ })();
76
+ /** 询问弹窗自身多久没回答就当作「取消」(TUI 会显示倒计时,RPC 端由 pi 兜底)。 */
77
+ const ASK_TIMEOUT_MS = Number(process.env.PI_SESSION_LOCK_ASK_TIMEOUT_MS ?? 120_000);
78
+ /** 自动化托管会话(pi-auto / boot-*)没人回答弹窗,直接走 fork。 */
79
+ const AUTOMATION = Boolean(
80
+ process.env.PI_AUTO_SESSION_ID || process.env.PI_BOOT_SESSION_ID || process.env.PI_GUARD_DIR || process.env.PI_RUN_DIR,
81
+ );
82
+ /** 请求让锁后最多等多久再决定 fork。 */
83
+ const GRACE_MS = Number(process.env.PI_SESSION_LOCK_GRACE_MS ?? 6000);
84
+ const WAIT_POLL_MS = 1200;
85
+ /** 自动 fork 的兜底:命令没被派发/一直没返回时,多久后解除 forking 标志。 */
86
+ const FORK_WATCHDOG_MS = 15_000;
87
+ const FOLLOW_LINES = Math.max(6, Number(process.env.PI_SESSION_LOCK_FOLLOW_LINES ?? 22));
88
+ const FORK_COMMAND = "/session-lock-fork --auto";
89
+
42
90
  type Held = { dir: string | null; conflict: string | null; unknown: string | null };
91
+ type Queued = { text: string; images: unknown[]; deadline: number };
92
+ type SendUser = (content: unknown) => void;
43
93
 
44
94
  export default function sessionLock(pi: ExtensionAPI) {
45
95
  let held: Held = { dir: null, conflict: null, unknown: null };
46
96
  let sessionFile: string | null = null;
47
97
  let lastCtx: ExtensionContext | null = null;
48
98
  let replaying = false;
49
- let pending: { text: string; images: unknown[]; deadline: number } | null = null;
99
+ let queued: Queued[] = [];
50
100
  let yieldTimer: ReturnType<typeof setInterval> | null = null;
51
101
  let retryTimer: ReturnType<typeof setInterval> | null = null;
102
+ let waitTimer: ReturnType<typeof setInterval> | null = null;
103
+ let waitDeadline = 0;
104
+ let forking = false;
105
+ let forkAttempts = 0;
106
+ let forkGuard: ReturnType<typeof setTimeout> | null = null;
107
+ /** 发起方在弹窗里做的选择(每个会话记一次)。 */
108
+ let choice: "fork" | "follow" | null = null;
109
+ /** 只读跟随态:本窗口不写会话,输入经 pi-mailbox 转给对方。 */
110
+ let spectating = false;
111
+ let asking = false;
112
+ let generation = 0;
113
+ let warnedExtensionDrop = false;
52
114
 
53
- const warn = (ctx: ExtensionContext, message: string, level: "info" | "warning" | "error") => {
115
+ const warn = (ctx: ExtensionContext | null, message: string, level: "info" | "warning" | "error") => {
116
+ if (!ctx) return;
54
117
  try {
55
118
  ctx.ui.notify(message, level);
56
119
  } catch {
@@ -63,7 +126,7 @@ export default function sessionLock(pi: ExtensionAPI) {
63
126
  try {
64
127
  fs.appendFileSync(
65
128
  DEBUG_LOG,
66
- `${new Date().toISOString()} pid=${process.pid} paseo=${PASEO_SOURCE} held=${held.dir ? "dir" : held.conflict ? "conflict" : "-"} file=${sessionFile ?? "null"} ${tag} ${detail}\n`,
129
+ `${new Date().toISOString()} pid=${process.pid} paseo=${PASEO_SOURCE} policy=${POLICY} held=${held.dir ? "dir" : held.conflict ? "conflict" : "-"} file=${sessionFile ?? "null"} ${tag} ${detail}\n`,
67
130
  );
68
131
  } catch {
69
132
  /* 排障日志不是关键路径 */
@@ -95,11 +158,39 @@ export default function sessionLock(pi: ExtensionAPI) {
95
158
  retryTimer = null;
96
159
  };
97
160
 
161
+ const stopWait = () => {
162
+ if (waitTimer) clearInterval(waitTimer);
163
+ waitTimer = null;
164
+ };
165
+
166
+ const contentFor = (item: Queued): unknown =>
167
+ item.images.length ? [{ type: "text", text: item.text }, ...item.images] : item.text;
168
+
169
+ /** 把等待期间拦下的消息按到达顺序重放出去(此时已经拿到/换到了可写的会话)。 */
170
+ const flushQueued = (send: SendUser): number => {
171
+ const now = Date.now();
172
+ const items = queued.splice(0).filter((item) => item.deadline > now);
173
+ if (!items.length) return 0;
174
+ replaying = true;
175
+ try {
176
+ for (const item of items) {
177
+ try {
178
+ send(contentFor(item));
179
+ } catch {
180
+ /* 单条失败不影响后续 */
181
+ }
182
+ }
183
+ } finally {
184
+ replaying = false;
185
+ }
186
+ return items.length;
187
+ };
188
+
98
189
  /** paseo 被拦下的消息:反复重试认领,拿到锁就重放这条消息。 */
99
190
  const startReplay = () => {
100
191
  if (retryTimer) return;
101
192
  retryTimer = setInterval(() => {
102
- if (!pending) return stopRetry();
193
+ if (!queued.length) return stopRetry();
103
194
  if (!sessionFile || !lastCtx) return;
104
195
  held = take(sessionFile);
105
196
  dbg("retry", `owned=${Boolean(held.dir && !held.conflict)}`);
@@ -108,23 +199,15 @@ export default function sessionLock(pi: ExtensionAPI) {
108
199
  if (held.dir) requestYield(held.dir, { source: PASEO_SOURCE, sessionFile });
109
200
  } else if (held.dir) {
110
201
  clearYieldRequest(held.dir);
111
- const { text, images } = pending;
112
- pending = null;
202
+ const sent = flushQueued((content) => pi.sendUserMessage(content as never));
113
203
  stopRetry();
114
- replaying = true;
115
- const content = images.length ? [{ type: "text", text }, ...images] : text;
116
- Promise.resolve()
117
- .then(() => pi.sendUserMessage(content as never /* 文本或 text+image 数组 */))
118
- .catch(() => {})
119
- .finally(() => {
120
- replaying = false;
121
- });
204
+ if (sent > 0) warn(lastCtx, `🔒 已拿到会话锁,重放了 ${sent} 条被拦下的消息。`, "info");
122
205
  return;
123
206
  }
124
- if (Date.now() > (pending?.deadline ?? 0)) {
125
- pending = null;
207
+ if (Date.now() > (queued[0]?.deadline ?? 0)) {
208
+ queued = [];
126
209
  stopRetry();
127
- if (lastCtx) warn(lastCtx, "🔒 等锁超时,这条消息没送达:先在占用方收尾,或关掉那个进程后重发。", "error");
210
+ warn(lastCtx, "🔒 等锁超时,这条消息没送达:先在占用方收尾,或关掉那个进程后重发。", "error");
128
211
  }
129
212
  }, YIELD_RETRY_MS);
130
213
  retryTimer.unref?.();
@@ -147,28 +230,314 @@ export default function sessionLock(pi: ExtensionAPI) {
147
230
  const dir = held.dir;
148
231
  release(dir);
149
232
  held = { dir: null, conflict: null, unknown: null };
150
- warn(lastCtx, `🔒 会话已让给 ${request.source ?? "另一个进程"}(pid ${request.pid}):本窗口再输入会重新认领,对方占着就会被拦。`, "info");
233
+ warn(
234
+ lastCtx,
235
+ `🔒 会话已让给 ${request.source ?? "另一个进程"}(pid ${request.pid}):本窗口再输入会重新认领,对方占着就会被拦或被 fork。`,
236
+ "info",
237
+ );
238
+ };
239
+
240
+ /**
241
+ * 自动 fork:不能从事件 ctx 直接调 fork(只有命令 ctx 有),
242
+ * 所以用 sendUserMessage 派发扩展命令 —— prompt() 在 input 钩子之前处理扩展命令,
243
+ * 不会反过来触发本插件的输入拦截。
244
+ */
245
+ const autoFork = (reason: string) => {
246
+ if (forking) return;
247
+ if (forkAttempts >= 2) {
248
+ warn(lastCtx, "🔒 已经 fork 过一次仍然冲突:本窗口的输入会被拦,请用 /clone 另存一份。", "error");
249
+ return;
250
+ }
251
+ forking = true;
252
+ forkAttempts += 1;
253
+ dbg("auto_fork", reason);
254
+ try {
255
+ pi.sendUserMessage(FORK_COMMAND, { expandPromptTemplates: true });
256
+ } catch (error) {
257
+ forking = false;
258
+ warn(lastCtx, `🔀 自动 fork 没有派发成功(${String(error)}):退回为拦输入。`, "error");
259
+ return;
260
+ }
261
+ if (forkGuard) clearTimeout(forkGuard);
262
+ forkGuard = setTimeout(() => {
263
+ forkGuard = null;
264
+ if (!forking) return;
265
+ forking = false;
266
+ warn(lastCtx, "🔀 fork 命令没有在预期时间内完成:本窗口输入仍会被拦,请手动 /session-lock-fork 或 /clone。", "error");
267
+ }, FORK_WATCHDOG_MS);
268
+ forkGuard.unref?.();
269
+ };
270
+
271
+ /** fork 只在有交互 UI 的模式里有意义(print/json 没有会话替换流程)。 */
272
+ const forkCapable = (ctx: ExtensionContext): boolean => ctx.mode === "tui" || ctx.mode === "rpc";
273
+
274
+ /** 能不能弹窗问人:有 UI、不是自动化会话。 */
275
+ const askable = (ctx: ExtensionContext): boolean => ctx.hasUI && forkCapable(ctx) && !AUTOMATION;
276
+
277
+ const currentOwner = () => (sessionFile ? peek(sessionFile).owner ?? null : null);
278
+ const ownerPidNow = (): number | null => {
279
+ const pid = currentOwner()?.pid;
280
+ return typeof pid === "number" ? pid : null;
281
+ };
282
+
283
+ /** 把等待期间拦下的消息经 pi-mailbox 转给持有者(只读跟随的输入通道)。 */
284
+ const forwardQueuedToMailbox = (ctx: ExtensionContext | null): { sent: number; failed: number } => {
285
+ const now = Date.now();
286
+ const items = queued.splice(0).filter((item) => item.deadline > now);
287
+ const pid = ownerPidNow();
288
+ let sent = 0;
289
+ let failed = 0;
290
+ let droppedImages = 0;
291
+ for (const item of items) {
292
+ if (item.images.length) droppedImages += 1;
293
+ if (!pid) {
294
+ failed += 1;
295
+ continue;
296
+ }
297
+ const result = sendToMailbox({ pid, text: item.text, from: "session-lock-follow" });
298
+ if (result.ok) sent += 1;
299
+ else failed += 1;
300
+ }
301
+ if (droppedImages) warn(ctx, `🔭 ${droppedImages} 条消息带图片:pi-mailbox 只收文本,图片没有转过去。`, "warning");
302
+ return { sent, failed };
303
+ };
304
+
305
+ /** 进入只读跟随态:不持锁、不写会话;输入全部走 pi-mailbox。 */
306
+ const enterSpectator = async (ctx: ExtensionContext, openViewer: boolean): Promise<void> => {
307
+ spectating = true;
308
+ choice = "follow";
309
+ stopWait();
310
+ clearYieldRequest(held.dir); // 不打算接管了,别让原持有者白白放锁
311
+ const pid = ownerPidNow();
312
+ const { sent, failed } = forwardQueuedToMailbox(ctx);
313
+ const parts = [`🔭 只读跟随:本窗口不写入该会话`];
314
+ if (pid) parts.push(`输入会经 pi-mailbox 转给 pid ${pid}`);
315
+ if (sent) parts.push(`已转输 ${sent} 条`);
316
+ if (failed) parts.push(`${failed} 条没转出去(对方没有 mailbox 名册?)`);
317
+ parts.push("要改成 fork 新会话:/session-lock-fork");
318
+ warn(ctx, parts.join(";"), "info");
319
+ if (openViewer && sessionFile && ctx.mode === "tui") {
320
+ try {
321
+ await openFollowScreen(ctx, sessionFile);
322
+ } catch (error) {
323
+ dbg("follow_screen_error", String(error));
324
+ }
325
+ }
326
+ };
327
+
328
+ /** 询问发起方:Fork 新会话,还是只读跟随(输入经 pi-mailbox 转给对方)。 */
329
+ const askConflictChoice = (ctx: ExtensionContext, origin: "start" | "input"): void => {
330
+ if (asking || choice) return;
331
+ const gen = generation;
332
+ asking = true;
333
+ const delay = origin === "start" ? 600 : 0;
334
+ setTimeout(async () => {
335
+ const fail = (message: string, level: "info" | "warning" | "error") => {
336
+ asking = false;
337
+ warn(lastCtx, message, level);
338
+ };
339
+ if (gen !== generation || !sessionFile) return fail("会话已更换,放弃这次询问。", "info");
340
+ const glance = peek(sessionFile);
341
+ if (glance.state !== "live") {
342
+ // 对方已经走了:直接接管原会话,不用问了
343
+ asking = false;
344
+ claimNow(ctx);
345
+ if (held.dir && !held.conflict) {
346
+ warn(ctx, "🔒 占用方已经退出:直接接管原会话继续。", "info");
347
+ flushQueued((content) => pi.sendUserMessage(content as never));
348
+ } else {
349
+ warn(ctx, `🔒 占用方已退出,但认领没成功:${held.unknown ?? "未知原因"}`, "warning");
350
+ }
351
+ return;
352
+ }
353
+
354
+ const pid = typeof glance.owner?.pid === "number" ? glance.owner.pid : null;
355
+ const mailboxReady = pid != null && Boolean(readPresence(pid));
356
+ const followLabel = mailboxReady
357
+ ? "只读跟随:不写会话,输入经 pi-mailbox 转给对方"
358
+ : "只读跟随:对方没有 mailbox 名册(只能看,不能转输)";
359
+ const forkLabel = "Fork 一份新会话继续(历史完整保留)";
360
+ let picked: string | undefined;
361
+ try {
362
+ picked = await ctx.ui.select(
363
+ `会话正被 ${describeOwner(glance.owner)} 使用(${describeActivity(glance.owner).label}):怎么继续?`,
364
+ [forkLabel, followLabel, "取消:先不动(本窗口保持不写)"],
365
+ { timeout: ASK_TIMEOUT_MS },
366
+ );
367
+ } catch (error) {
368
+ asking = false;
369
+ warn(ctx, `🔒 询问弹窗不可用(${String(error)}):退回为拦输入,可用 /session-lock-fork。`, "error");
370
+ return;
371
+ }
372
+ asking = false;
373
+ if (gen !== generation) return;
374
+
375
+ if (!picked) {
376
+ warn(lastCtx, "🔒 没选(超时/取消):本窗口不写对方会话,再输入会重新询问。", "warning");
377
+ return;
378
+ }
379
+ if (picked.startsWith("Fork")) {
380
+ choice = "fork";
381
+ warn(lastCtx, "🔀 已选择 fork:正在复制当前会话(历史完整保留)…", "info");
382
+ // 不能在 input 钩子里同步 fork(prompt preflight 占着),放到下一个 tick
383
+ setTimeout(() => autoFork("user-choice"), 0);
384
+ return;
385
+ }
386
+ if (picked.startsWith("只读跟随")) {
387
+ void enterSpectator(ctx, true);
388
+ return;
389
+ }
390
+ // 取消
391
+ queued = [];
392
+ warn(lastCtx, "🔒 已取消:本窗口不会写入对方会话(输入仍会被拦/询问)。", "info");
393
+ }, delay)?.unref?.();
394
+ };
395
+
396
+ /** 冲突处理:按策略问人 / 等让锁 / 自动 fork / 直接拦。 */
397
+ const onConflict = (ctx: ExtensionContext, origin: "start" | "input" = "start") => {
398
+ if (POLICY === "block" || !forkCapable(ctx)) {
399
+ warn(ctx, `🔒 ${held.conflict}。已拦输入:先退出那个进程,或 /clone 一份新的再继续。`, "error");
400
+ return;
401
+ }
402
+ if (POLICY === "follow") {
403
+ void enterSpectator(ctx, origin === "input");
404
+ return;
405
+ }
406
+ if (POLICY === "ask" && askable(ctx)) {
407
+ warn(
408
+ ctx,
409
+ `🔒 ${held.conflict}。请选择怎么继续:Fork 新会话(历史完整)/ 只读跟随(输入转给对方,不写会话)。`,
410
+ "warning",
411
+ );
412
+ askConflictChoice(ctx, origin);
413
+ return;
414
+ }
415
+ if (!held.dir) {
416
+ // 说不清锁目录(owner.json 残缺等):别硬来
417
+ warn(ctx, `🔒 ${held.conflict}:无法请求让锁,输入先被拦。`, "error");
418
+ return;
419
+ }
420
+ requestYield(held.dir, { source: PASEO_SOURCE, sessionFile });
421
+ warn(
422
+ ctx,
423
+ `🔒 ${held.conflict}。已请求对方让锁,等待 ${Math.round(GRACE_MS / 1000)}s:对方空闲就接管原会话,仍在跑就自动 fork 一份(历史完整保留)。只看不写可用 pi-session-follow。`,
424
+ "warning",
425
+ );
426
+ startWait(ctx);
427
+ };
428
+
429
+ /** 轮询等待让锁;超时后按策略 fork / 放行。 */
430
+ const startWait = (ctx: ExtensionContext) => {
431
+ if (waitTimer || !sessionFile || !held.dir) return;
432
+ waitDeadline = Date.now() + GRACE_MS;
433
+ const dir = held.dir;
434
+ dbg("wait_start", `dir=${dir}`);
435
+ waitTimer = setInterval(() => {
436
+ if (!sessionFile || !lastCtx) return stopWait();
437
+ const result = claim(sessionFile, { source: PASEO_SOURCE });
438
+ if (result.ok || result.state === "off") {
439
+ held = { dir: result.dir ?? dir, conflict: null, unknown: null };
440
+ if (held.dir) clearYieldRequest(held.dir);
441
+ stopWait();
442
+ warn(lastCtx, "🔒 对方已让出会话:现在由本窗口继续。", "info");
443
+ const sent = flushQueued((content) => pi.sendUserMessage(content as never));
444
+ if (sent) warn(lastCtx, `🔒 已重放 ${sent} 条等待中的消息。`, "info");
445
+ return;
446
+ }
447
+ if (result.state === "unknown") {
448
+ held = { dir: result.dir ?? dir, conflict: null, unknown: result.reason };
449
+ }
450
+ if (Date.now() < waitDeadline) return;
451
+ stopWait();
452
+ if (result.state === "conflict") {
453
+ const activity = describeActivity(result.owner);
454
+ dbg("wait_timeout", `${result.reason} / ${activity.label}`);
455
+ warn(
456
+ lastCtx,
457
+ `🔀 会话仍被 ${describeOwner(result.owner)} 占用(${activity.label}):自动 fork 一份新会话继续,历史完整保留。`,
458
+ "warning",
459
+ );
460
+ autoFork(`still-live:${activity.label}`);
461
+ } else {
462
+ warn(lastCtx, `🔒 会话锁无法判定(${result.reason}):本会话继续可用,并发保护未生效。`, "warning");
463
+ }
464
+ }, WAIT_POLL_MS);
465
+ waitTimer.unref?.();
151
466
  };
152
467
 
153
468
  pi.on("session_start", (event, ctx) => {
154
469
  lastCtx = ctx;
155
470
  sessionFile = ctx.sessionManager.getSessionFile() ?? null;
156
471
  held = { dir: null, conflict: null, unknown: null };
472
+ stopWait();
473
+ stopRetry();
474
+ queued = [];
475
+ choice = null;
476
+ spectating = false;
477
+ asking = false;
478
+ warnedExtensionDrop = false;
479
+ generation += 1;
157
480
  dbg("session_start", `reason=${event.reason}`);
158
481
  if (!enabled() || !sessionFile) return;
482
+
483
+ if (event.reason === "fork") {
484
+ // fork 出来的新文件:认领它,并告诉用户刚刚发生了什么
485
+ claimNow(ctx);
486
+ if (held.unknown) warn(ctx, `🔒 会话锁无法判定(${held.unknown}):本会话仍可用,但并发保护未生效。`, "warning");
487
+ warn(ctx, "🔀 已 fork 到新会话(原会话历史完整保留)。原会话继续由对方使用;被拦下的消息(如果有)已重放到这里。", "info");
488
+ if (!yieldTimer) {
489
+ yieldTimer = setInterval(pollYield, YIELD_POLL_MS);
490
+ yieldTimer.unref?.();
491
+ }
492
+ return;
493
+ }
494
+
159
495
  if (PASEO) return; // paseo 托管:按轮持锁,空闲不占(见文件头)
496
+
160
497
  claimNow(ctx);
161
- if (held.conflict) warn(ctx, `🔒 ${held.conflict}。已拦输入:先退出那个进程,或 /clone 一份新的再继续。`, "error");
498
+ if (held.conflict) onConflict(ctx, "start");
162
499
  else if (held.unknown) warn(ctx, `🔒 会话锁无法判定(${held.unknown}):本会话仍可用,但并发保护未生效。`, "warning");
163
- yieldTimer = setInterval(pollYield, YIELD_POLL_MS);
164
- yieldTimer.unref?.();
500
+ if (!yieldTimer) {
501
+ yieldTimer = setInterval(pollYield, YIELD_POLL_MS);
502
+ yieldTimer.unref?.();
503
+ }
165
504
  });
166
505
 
167
506
  // 只拦人的输入(TUI 打字 / RPC / 手机端 / steer 都经这里)。扩展命令在 input 之前处理,故 /session-lock 仍可用。
168
507
  pi.on("input", (event, ctx) => {
169
508
  lastCtx = ctx;
170
509
  if (!enabled() || replaying) return;
171
- dbg("input", `source=${event.source}`);
510
+ dbg("input", `source=${event.source}${spectating ? " spectator" : ""}`);
511
+
512
+ // 只读跟随态:不写会话,把这句话经 pi-mailbox 转给对方。
513
+ if (spectating) {
514
+ if (event.source === "extension") {
515
+ // 自动化续轮/子代理结果这类消息不往对方会话里塞(那不是「用户插话」),只提示一次
516
+ if (!warnedExtensionDrop) {
517
+ warnedExtensionDrop = true;
518
+ warn(ctx, "🔭 只读跟随中:扩展消息不会转给对方(只转发人打的字)。", "warning");
519
+ }
520
+ dbg("spectator_drop_extension", event.text.slice(0, 60));
521
+ return { action: "handled" };
522
+ }
523
+ if (event.images?.length) warn(ctx, "🔭 图片不会转发(pi-mailbox 只收文本)。", "warning");
524
+ const pid = ownerPidNow();
525
+ const sent = pid ? sendToMailbox({ pid, text: event.text, from: "session-lock-follow" }) : { ok: false, reason: "没有持有者" };
526
+ if (sent.ok) {
527
+ warn(ctx, `🔭 已转给对方(pid ${pid}):本窗口没有写入该会话。`, "info");
528
+ return { action: "handled" };
529
+ }
530
+ // 对方走了:试试接管原会话,接着正常跑
531
+ claimNow(ctx);
532
+ if (held.dir && !held.conflict) {
533
+ spectating = false;
534
+ choice = null;
535
+ warn(ctx, `🔭 对方已经不在了(${sent.reason}):已接管原会话,这条消息按本地输入继续。`, "info");
536
+ return; // 让 pi 继续处理这条输入
537
+ }
538
+ warn(ctx, `🔭 没能转输:${sent.reason}。本窗口保持只读(/session-lock-fork 可另起一份)。`, "error");
539
+ return { action: "handled" };
540
+ }
172
541
  // 空闲时没持锁(paseo 按轮持锁 / 自己刚才让过锁),或者上次判冲突而对方可能已经走了:
173
542
  // 现在真的要写了,重新认领一次(对方还活着就还是 conflict)。
174
543
  if (!held.dir || held.conflict) {
@@ -177,21 +546,43 @@ export default function sessionLock(pi: ExtensionAPI) {
177
546
  }
178
547
  if (!held.conflict) return;
179
548
 
180
- if (PASEO && held.dir) {
181
- // paseo 侧:请求对方让锁,并把这条消息挂起,拿到锁后重放
549
+ if (PASEO) {
550
+ // paseo 侧:请求对方让锁,并把这条消息挂起,拿到锁后重放(不 fork,daemon 按会话 id 管理)
551
+ if (!held.dir) {
552
+ warn(ctx, `🔒 输入已拦:${held.conflict}`, "error");
553
+ return { action: "handled" };
554
+ }
182
555
  requestYield(held.dir, { source: PASEO_SOURCE, sessionFile });
183
- pending = { text: event.text, images: event.images ?? [], deadline: Date.now() + REPLAY_WINDOW_MS };
556
+ queued.push({ text: event.text, images: event.images ?? [], deadline: Date.now() + REPLAY_WINDOW_MS });
184
557
  startReplay();
185
558
  warn(ctx, `🔒 输入已拦:${held.conflict}。已请求对方让锁,拿到后自动重放这条消息(60 秒内)。`, "error");
186
- } else {
559
+ return { action: "handled" };
560
+ }
561
+
562
+ if (POLICY === "block" || !forkCapable(ctx)) {
187
563
  warn(ctx, `🔒 输入已拦:${held.conflict}`, "error");
564
+ return { action: "handled" };
188
565
  }
566
+
567
+ // 削弱语义:先挂起这条消息,再按策略决定(询问 / 等让锁 / 直接跟随)
568
+ queued.push({ text: event.text, images: event.images ?? [], deadline: Date.now() + ASK_TIMEOUT_MS + GRACE_MS });
569
+ onConflict(ctx, "input");
189
570
  return { action: "handled" };
190
571
  });
191
572
 
192
573
  // paseo 侧的兜底:非 input 触发的 run(定时续轮、extension 发消息)也要先拿到锁
193
574
  pi.on("agent_start", (_event, ctx) => {
194
575
  lastCtx = ctx;
576
+ if (spectating) {
577
+ // 只读跟随态绝不让本窗口真正跑起来(否则就会写会话)
578
+ warn(ctx, "🔭 只读跟随中:已拦下本地运行(输入应转给对方)。", "warning");
579
+ try {
580
+ ctx.abort();
581
+ } catch {
582
+ /* ignore */
583
+ }
584
+ return;
585
+ }
195
586
  if (!enabled() || !PASEO || (held.dir && !held.conflict)) return;
196
587
  claimNow(ctx);
197
588
  if (!held.conflict) return;
@@ -213,6 +604,17 @@ export default function sessionLock(pi: ExtensionAPI) {
213
604
  });
214
605
 
215
606
  pi.on("user_bash", (_event, ctx) => {
607
+ if (spectating) {
608
+ warn(ctx, "🔭 只读跟随中:本窗口不执行用户 bash。", "error");
609
+ return {
610
+ result: {
611
+ output: "blocked: read-only follow (this window does not write the session)",
612
+ exitCode: 1,
613
+ cancelled: false,
614
+ truncated: false,
615
+ },
616
+ };
617
+ }
216
618
  if (!held.conflict) return;
217
619
  warn(ctx, "🔒 会话被另一进程占用,用户 bash 已拦。", "error");
218
620
  return {
@@ -225,44 +627,48 @@ export default function sessionLock(pi: ExtensionAPI) {
225
627
  };
226
628
  });
227
629
 
228
- // 切到别人的会话前先看一眼(不让 /resume 撞上活进程)。拿不到就放行。
630
+ // 切到别人的会话前先看一眼。削弱语义下不再直接取消 resume:
631
+ // 允许进去,session_start(reason=resume)会照常请求让锁、必要时自动 fork。
229
632
  pi.on("session_before_switch", (event, ctx) => {
230
633
  if (!enabled() || event.reason !== "resume" || !event.targetSessionFile) return;
231
- const probe = claim(event.targetSessionFile);
232
- if (probe.ok && probe.dir && probe.dir !== held.dir) {
233
- // 只是探测:别把目标会话的锁留着(当前会话的锁不动)
234
- release(probe.dir);
235
- return;
236
- }
237
- if (probe.state === "conflict") {
238
- warn(ctx, `🔒 不能 resume:${probe.warning ?? probe.reason}`, "error");
634
+ const probe = peek(event.targetSessionFile);
635
+ if (probe.state !== "live") return;
636
+ if (POLICY === "block" || !forkCapable(ctx)) {
637
+ warn(ctx, `🔒 不能 resume:${probe.reason}`, "error");
239
638
  return { cancel: true };
240
639
  }
640
+ warn(ctx, `🔒 目标会话正被另一个活进程使用(${probe.reason}):进入后会先请求让锁,必要时自动 fork。`, "warning");
241
641
  });
242
642
 
243
643
  pi.on("session_shutdown", () => {
244
644
  stopRetry();
645
+ stopWait();
646
+ if (forkGuard) clearTimeout(forkGuard);
647
+ forkGuard = null;
245
648
  if (yieldTimer) clearInterval(yieldTimer);
246
649
  yieldTimer = null;
247
- pending = null;
650
+ queued = [];
248
651
  release(held.dir);
249
652
  held = { dir: null, conflict: null, unknown: null };
250
653
  });
251
654
 
655
+ const statusText = (file: string | null): string => {
656
+ if (!file) return "no session file (ephemeral session)";
657
+ if (!enabled()) return `disabled (PI_SESSION_LOCK=off)\n${lockDirFor(file)}`;
658
+ if (spectating)
659
+ return `follow: 只读跟随(不持锁、不写会话),输入经 pi-mailbox 转给 pid ${ownerPidNow() ?? "?"}\npolicy=${POLICY} choice=${choice}\n${lockDirFor(file)}`;
660
+ if (held.conflict)
661
+ return `conflict: ${held.conflict}\npolicy=${POLICY} grace=${GRACE_MS}ms waiting=${Boolean(waitTimer)} asking=${asking} choice=${choice ?? "-"}\n${held.dir}`;
662
+ if (held.unknown) return `unknown: ${held.unknown}\n${held.dir}`;
663
+ if (held.dir) return `owned by this process (pid ${process.pid})\n${held.dir}`;
664
+ if (PASEO) return `paseo-managed (${PASEO.label}): 空闲不持锁,输入时认领\n${lockDirFor(file)}`;
665
+ return "no lock (ephemeral session)";
666
+ };
667
+
252
668
  pi.registerCommand("session-lock", {
253
669
  description: "查看当前会话锁状态",
254
670
  handler: async (_args, ctx) => {
255
- const file = ctx.sessionManager.getSessionFile();
256
- const describe = () => {
257
- if (!file) return "no session file (ephemeral session)";
258
- if (!enabled()) return `disabled (PI_SESSION_LOCK=off)\n${lockDirFor(file)}`;
259
- if (held.conflict) return `conflict: ${held.conflict}\n${held.dir}`;
260
- if (held.unknown) return `unknown: ${held.unknown}\n${held.dir}`;
261
- if (held.dir) return `owned by this process (pid ${process.pid})\n${held.dir}`;
262
- if (PASEO) return `paseo-managed (${PASEO.label}): 空闲不持锁,输入时认领\n${lockDirFor(file)}`;
263
- return "no lock (ephemeral session)";
264
- };
265
- warn(ctx, `🔒 ${describe()}`, held.conflict ? "error" : "info");
671
+ warn(ctx, `🔒 ${statusText(ctx.sessionManager.getSessionFile() ?? null)}`, held.conflict ? "error" : "info");
266
672
  },
267
673
  });
268
674
 
@@ -284,4 +690,329 @@ export default function sessionLock(pi: ExtensionAPI) {
284
690
  warn(ctx, `🔒 已回收并重新认领:${held.dir}`, "info");
285
691
  },
286
692
  });
693
+
694
+ // 手动/自动共用的 fork 命令:从当前 leaf 复制一份新会话(history 完整保留)。
695
+ pi.registerCommand("session-lock-fork", {
696
+ description: "把当前会话 fork 成一份新会话继续(原会话留给占用它的进程),并重放被拦下的消息",
697
+ handler: async (args, ctx) => {
698
+ const auto = /\B--auto\b/.test(` ${args} `);
699
+ const file = ctx.sessionManager.getSessionFile();
700
+ if (!enabled() || !file) {
701
+ if (auto) forking = false;
702
+ return warn(ctx, "🔀 没有可 fork 的会话文件。", "warning");
703
+ }
704
+ const selfOwned = peek(file).state === "self";
705
+ if (selfOwned && !queued.length && !/\B--force\b/.test(` ${args} `)) {
706
+ if (auto) forking = false;
707
+ return warn(ctx, "🔒 本进程已持有这个会话,不需要 fork(想复制一份用 /clone)。", "info");
708
+ }
709
+ const leafId = ctx.sessionManager.getLeafId();
710
+ if (!leafId) {
711
+ if (auto) forking = false;
712
+ return warn(ctx, "🔀 会话还没有任何条目,无法 fork。", "error");
713
+ }
714
+
715
+ const now = Date.now();
716
+ const carry = queued.splice(0).filter((item) => item.deadline > now);
717
+ dbg("fork", `auto=${auto} leaf=${leafId} carry=${carry.length}`);
718
+
719
+ let ok = false;
720
+ try {
721
+ const result = await ctx.fork(leafId, {
722
+ position: "at",
723
+ withSession: async (fresh) => {
724
+ for (const item of carry) {
725
+ try {
726
+ await fresh.sendUserMessage(contentFor(item) as never, { deliverAs: "followUp" });
727
+ } catch {
728
+ /* 单条失败不影响 fork 本身 */
729
+ }
730
+ }
731
+ if (carry.length) {
732
+ try {
733
+ fresh.ui.notify(`🔀 已把 ${carry.length} 条被拦下的消息重放到新会话。`, "info");
734
+ } catch {
735
+ /* notify 不是关键路径 */
736
+ }
737
+ }
738
+ },
739
+ });
740
+ ok = !result.cancelled;
741
+ if (result.cancelled) {
742
+ queued = [...carry, ...queued];
743
+ warn(ctx, "🔀 fork 已取消:本窗口仍在原会话上(冲突时输入会被拦)。", "warning");
744
+ }
745
+ } catch (error) {
746
+ queued = [...carry, ...queued];
747
+ warn(ctx, `🔀 fork 失败:${String(error)}。退回为拦输入,可以用 /clone 手动复制。`, "error");
748
+ } finally {
749
+ if (auto) forking = false;
750
+ // fork 之后不再要原会话了:把让锁请求撤掉,否则原持有者空闲时会把锁也放掉,
751
+ // 原会话就出现一个「谁都能抢」的空窗(它其实还在被人用)。
752
+ clearYieldRequest(lockDirFor(file));
753
+ }
754
+ if (!ok) dbg("fork_failed", `auto=${auto}`);
755
+ },
756
+ });
757
+
758
+ pi.registerCommand("session-lock-follow", {
759
+ description: "只读跟随另一个进程在用的会话(不持锁、不写盘;输入经 pi-mailbox 转给对方)",
760
+ handler: async (args, ctx) => {
761
+ if (ctx.mode !== "tui") {
762
+ return warn(ctx, "🔭 只读跟随需要 TUI 模式(rpc/print 下没有自定义界面)。", "error");
763
+ }
764
+ const target = await resolveFollowTarget(args.trim(), ctx);
765
+ if (!target) return warn(ctx, `🔭 找不到要跟随的会话:${args.trim() || "(当前会话)"}`, "error");
766
+ if (!fs.existsSync(target)) return warn(ctx, `🔭 会话文件不存在:${target}`, "error");
767
+
768
+ const probe = peek(target);
769
+ if (probe.state === "self") {
770
+ return warn(ctx, "🔭 当前进程就是该会话的持有者,不需要只读跟随。", "info");
771
+ }
772
+ // 跟随的就是本窗口正在用的、被别人占着的会话:顺手进入跟随态(之后输入都转给对方),
773
+ // 否则关掉跟随窗口后每次输入还会再弹一次询问。
774
+ const isCurrent = (() => {
775
+ if (!sessionFile) return false;
776
+ try {
777
+ return fs.realpathSync(target) === fs.realpathSync(sessionFile);
778
+ } catch {
779
+ return false;
780
+ }
781
+ })();
782
+ if (isCurrent && probe.state === "live") {
783
+ await enterSpectator(ctx, true);
784
+ return;
785
+ }
786
+ await openFollowScreen(ctx, target);
787
+ warn(ctx, `🔭 已退出只读跟随:${path.basename(target)}(没有写入对方会话)。`, "info");
788
+ },
789
+ });
790
+
791
+ // ---- 只读跟随 -------------------------------------------------------------
792
+
793
+ async function resolveFollowTarget(arg: string, ctx: ExtensionContext): Promise<string | null> {
794
+ if (!arg) return ctx.sessionManager.getSessionFile() ?? null;
795
+ const looksLikePath = arg.includes("/") || arg.endsWith(".jsonl") || arg.startsWith("~");
796
+ if (looksLikePath) {
797
+ const expanded = arg.startsWith("~") ? path.join(process.env.HOME ?? "", arg.slice(1)) : arg;
798
+ try {
799
+ return fs.realpathSync(path.resolve(ctx.cwd, expanded));
800
+ } catch {
801
+ return path.resolve(ctx.cwd, expanded);
802
+ }
803
+ }
804
+ try {
805
+ const infos = await SessionManager.listAll();
806
+ const exact = infos.find((info) => info.id === arg);
807
+ if (exact) return exact.path;
808
+ const prefix = infos.filter((info) => info.id.startsWith(arg));
809
+ if (prefix.length === 1) return prefix[0].path;
810
+ } catch {
811
+ /* 列表失败就只认路径 */
812
+ }
813
+ return null;
814
+ }
815
+
816
+ async function openFollowScreen(ctx: ExtensionContext, target: string): Promise<void> {
817
+ const followed = path.basename(target);
818
+ let stream = { entries: [] as unknown[], size: 0, ino: 0, mtimeMs: 0, reset: true };
819
+ try {
820
+ stream = readSessionDelta(target, stream);
821
+ } catch {
822
+ /* 读不到就先空着 */
823
+ }
824
+
825
+ await ctx.ui.custom<void>((tui, theme, _keys, done) => {
826
+ const editorTheme: EditorTheme = {
827
+ borderColor: (s: string) => theme.fg("accent", s),
828
+ selectList: {
829
+ selectedPrefix: (t: string) => theme.fg("accent", t),
830
+ selectedText: (t: string) => theme.fg("accent", t),
831
+ description: (t: string) => theme.fg("muted", t),
832
+ scrollInfo: (t: string) => theme.fg("dim", t),
833
+ noMatch: (t: string) => theme.fg("warning", t),
834
+ },
835
+ };
836
+ const editor = new Editor(tui, editorTheme);
837
+
838
+ const initial = peek(target);
839
+ let ownerPid: number | null = initial.owner?.pid ?? null;
840
+ let activity = initial.owner ? describeActivity(initial.owner) : null;
841
+ let branch = activeBranch(stream.entries);
842
+ let scrollBack = 0;
843
+ let status = ownerPid
844
+ ? `跟随 pid ${ownerPid}(${activity?.label ?? "?"})`
845
+ : "当前没有活进程持锁(可能已关闭)";
846
+ let cached: { width: number; revision: number; lines: string[] } | null = null;
847
+ let revision = 0;
848
+ let closed = false;
849
+
850
+ const invalidate = () => {
851
+ cached = null;
852
+ };
853
+ const refresh = () => {
854
+ const previousSize = stream.size;
855
+ const next = readSessionDelta(target, stream);
856
+ stream = next;
857
+ if (next.reset || next.size !== previousSize) {
858
+ branch = activeBranch(next.entries);
859
+ revision += 1;
860
+ invalidate();
861
+ tui.requestRender();
862
+ }
863
+ const glance = peek(target);
864
+ const pid = glance.owner?.pid ?? null;
865
+ if (pid !== ownerPid) {
866
+ ownerPid = pid;
867
+ activity = glance.owner ? describeActivity(glance.owner) : null;
868
+ status = ownerPid
869
+ ? `跟随 pid ${ownerPid}(${activity?.label ?? "?"})`
870
+ : "当前没有活进程持锁(可能已关闭)";
871
+ invalidate();
872
+ tui.requestRender();
873
+ }
874
+ };
875
+ const ticker = setInterval(refresh, 1000);
876
+ ticker.unref?.();
877
+ const stop = () => {
878
+ if (closed) return;
879
+ closed = true;
880
+ clearInterval(ticker);
881
+ };
882
+ const finish = () => {
883
+ stop();
884
+ done();
885
+ };
886
+
887
+ editor.onSubmit = (value: string) => {
888
+ const text = value.trim();
889
+ editor.setText("");
890
+ invalidate();
891
+ if (!text) {
892
+ tui.requestRender();
893
+ return;
894
+ }
895
+ if (text === "/quit" || text === "/q" || text === "!q") {
896
+ finish();
897
+ return;
898
+ }
899
+ if (!ownerPid) {
900
+ status = "✗ 没有持有者:不能转输(本窗口只读)";
901
+ } else {
902
+ const sent = sendToMailbox({ pid: ownerPid, text, from: "session-follow" });
903
+ status = sent.ok ? `✓ ${clock()} 已转给 pid ${ownerPid}` : `✗ ${sent.reason}`;
904
+ }
905
+ invalidate();
906
+ tui.requestRender();
907
+ };
908
+
909
+ const styleOf = (style: string) => {
910
+ switch (style) {
911
+ case "user":
912
+ return { color: "accent", prefix: "❯ " };
913
+ case "assistant":
914
+ return { color: "text", prefix: " " };
915
+ case "tool":
916
+ return { color: "muted", prefix: " " };
917
+ case "result":
918
+ return { color: "dim", prefix: " " };
919
+ case "meta":
920
+ return { color: "warning", prefix: " " };
921
+ default:
922
+ return { color: "muted", prefix: " " };
923
+ }
924
+ };
925
+
926
+ const transcript = (width: number): string[] => {
927
+ if (cached && cached.width === width && cached.revision === revision) return cached.lines;
928
+ const out: string[] = [];
929
+ for (const item of transcriptLines(branch, { maxEntries: 300 })) {
930
+ const { color, prefix } = styleOf(item.style);
931
+ const prefixWidth = visibleWidth(prefix);
932
+ const bodyWidth = Math.max(1, width - prefixWidth);
933
+ item.text.split("\n").forEach((raw, index) => {
934
+ const wrapped = wrapTextWithAnsi(raw, bodyWidth);
935
+ wrapped.forEach((line, wrappedIndex) => {
936
+ const lead = index === 0 && wrappedIndex === 0 ? prefix : " ".repeat(prefixWidth);
937
+ out.push(truncateToWidth(`${lead}${theme.fg(color, line)}`, width));
938
+ });
939
+ });
940
+ }
941
+ cached = { width, revision, lines: out };
942
+ return out;
943
+ };
944
+
945
+ const render = (width: number): string[] => {
946
+ const w = Math.max(1, width);
947
+ const lines: string[] = [];
948
+ lines.push(theme.fg("accent", "─".repeat(w)));
949
+ lines.push(
950
+ truncateToWidth(
951
+ `${theme.fg("accent", theme.bold("🔭 只读跟随"))} ${theme.fg("text", followed)} ${theme.fg("dim", "· 不持锁 / 不写盘")}`,
952
+ w,
953
+ ),
954
+ );
955
+ lines.push(truncateToWidth(theme.fg("muted", status), w));
956
+ lines.push(theme.fg("dim", "─".repeat(w)));
957
+
958
+ const body = transcript(w);
959
+ const total = body.length;
960
+ const maxScroll = Math.max(0, total - FOLLOW_LINES);
961
+ if (scrollBack > maxScroll) scrollBack = maxScroll;
962
+ const end = Math.max(0, total - scrollBack);
963
+ const start = Math.max(0, end - FOLLOW_LINES);
964
+ const view = body.slice(start, end);
965
+ for (let i = view.length; i < FOLLOW_LINES; i += 1) lines.push("");
966
+ lines.push(...view);
967
+
968
+ lines.push(theme.fg("dim", "─".repeat(w)));
969
+ const inputLines = editor.render(Math.max(1, w - 2));
970
+ for (const line of inputLines) lines.push(` ${line}`);
971
+ const hint = ownerPid
972
+ ? "Enter 转发给对方 • PgUp/PgDn 翻看 • Esc 退出(只读,不写对方会话)"
973
+ : "当前无人持有:只能看 • PgUp/PgDn 翻看 • Esc 退出";
974
+ lines.push(truncateToWidth(theme.fg("dim", hint), w));
975
+ return lines;
976
+ };
977
+
978
+ const handleInput = (data: string) => {
979
+ if (matchesKey(data, Key.escape) || matchesKey(data, Key.ctrl("c"))) {
980
+ finish();
981
+ return;
982
+ }
983
+ if (matchesKey(data, Key.pageUp)) {
984
+ scrollBack += Math.max(1, Math.floor(FOLLOW_LINES / 2));
985
+ invalidate();
986
+ tui.requestRender();
987
+ return;
988
+ }
989
+ if (matchesKey(data, Key.pageDown)) {
990
+ scrollBack = Math.max(0, scrollBack - Math.max(1, Math.floor(FOLLOW_LINES / 2)));
991
+ invalidate();
992
+ tui.requestRender();
993
+ return;
994
+ }
995
+ if (matchesKey(data, Key.end)) {
996
+ scrollBack = 0;
997
+ invalidate();
998
+ tui.requestRender();
999
+ return;
1000
+ }
1001
+ editor.handleInput(data);
1002
+ invalidate();
1003
+ tui.requestRender();
1004
+ };
1005
+
1006
+ return {
1007
+ render,
1008
+ handleInput,
1009
+ invalidate,
1010
+ };
1011
+ });
1012
+ }
1013
+ }
1014
+
1015
+ function clock(): string {
1016
+ const now = new Date();
1017
+ return `${String(now.getHours()).padStart(2, "0")}:${String(now.getMinutes()).padStart(2, "0")}:${String(now.getSeconds()).padStart(2, "0")}`;
287
1018
  }