pi-web-ui 0.90.0 → 0.90.1

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.
@@ -784,6 +784,26 @@ export function isInsideSessionsDir(agentDir, targetPath) {
784
784
  const sessionsRoot = resolve(agentDir, "sessions");
785
785
  return abs.startsWith(sessionsRoot + sep);
786
786
  }
787
+ /**
788
+ * 选一个断开的残留会话给新标签认领(纯函数):
789
+ * - 还有别的在线浏览器(非伪客户端且 live)→ 不认领(新标签是第二块屏,
790
+ * issue #10 的隔离必须保留,跑着的对话继续走 elsewhere 只读感知)。
791
+ * - 否则在断开 + 非伪 + 有内容的候选中按(streaming 多 → 最近活跃)取最优;
792
+ * 没有返回 null(调用方走正常新建流程)。
793
+ */
794
+ export function pickAdoptableOrphan(cands) {
795
+ if (cands.some((c) => !c.pseudo && c.live))
796
+ return null;
797
+ let best = null;
798
+ for (const c of cands) {
799
+ if (c.pseudo || c.live || !c.adoptable)
800
+ continue;
801
+ if (!best || c.streaming > best.streaming || (c.streaming === best.streaming && c.activity > best.activity)) {
802
+ best = c;
803
+ }
804
+ }
805
+ return best?.id ?? null;
806
+ }
787
807
  export class ClientSession {
788
808
  clientId;
789
809
  /** Set by AgentService.attach: reflects the SERVICE-wide quiesce flag
@@ -2103,6 +2123,11 @@ export class ClientSession {
2103
2123
  * TOOL_WATCHDOG_TIMEOUT_MS, abort the session instead of letting the
2104
2124
  * conversation hang forever (the SDK bash tool has no default timeout). */
2105
2125
  armToolWatchdog(conv, toolCallId) {
2126
+ this.rearmToolWatchdog(conv, toolCallId, TOOL_WATCHDOG_TIMEOUT_MS);
2127
+ }
2128
+ /** (重)布工具挂死看门狗:delayMs 后仍在跑则 abort 整轮。过户时用剩余时间重布
2129
+ * (已逾期的立即触发,语义不变). */
2130
+ rearmToolWatchdog(conv, toolCallId, delayMs) {
2106
2131
  const t = setTimeout(() => {
2107
2132
  conv.toolWatchdogs.delete(toolCallId);
2108
2133
  // The tool finished before the deadline — nothing to do.
@@ -2120,7 +2145,7 @@ export class ClientSession {
2120
2145
  // clears any goal / review loop. interruptRun adds a force-reset
2121
2146
  // fallback in case the model stream ignores the abort signal.
2122
2147
  void this.interruptRun(conv, "工具执行超时");
2123
- }, TOOL_WATCHDOG_TIMEOUT_MS);
2148
+ }, Math.max(0, delayMs));
2124
2149
  t.unref?.();
2125
2150
  conv.toolWatchdogs.set(toolCallId, t);
2126
2151
  }
@@ -3065,6 +3090,8 @@ export class ClientSession {
3065
3090
  }
3066
3091
  const id = `q-${++this.questionSeq}`;
3067
3092
  this.pendingQuestions.set(id, { resolve, questions, conversationId });
3093
+ // 运行列表的「?」角标靠 conversations 推送(问卷登记/解决不经过快照通道)。
3094
+ this.emitConversations();
3068
3095
  this.emit({
3069
3096
  type: "question_pending",
3070
3097
  id,
@@ -3073,14 +3100,20 @@ export class ClientSession {
3073
3100
  });
3074
3101
  }
3075
3102
  /** 前端回答模型提问(question_answer → 恢复 askUser 的 Promise)。id 需匹配
3076
- * pendingQuestions 中键;cancelled 或未匹配(例如用户早已切走)时按「取消」处理
3077
- * —— 把挂起的提问全部 reject,让模型知道用户离开了。 */
3103
+ * pendingQuestions 中键;未匹配(对方刚回答/取消、页面刷新重发)静默忽略。
3104
+ * 成功 resolve 后同步推 question_retracted + conversations:本页 live 对话框
3105
+ * 靠前者收起(跨页作答时源页就靠它),别处的「?」角标靠后者即时消失。
3106
+ * 返回是否真的恢复了一个挂起提问(跨页作答的送达回执用)。 */
3078
3107
  resolveQuestion(id, answers, cancelled) {
3079
3108
  const pending = this.pendingQuestions.get(id);
3080
- if (pending) {
3081
- this.pendingQuestions.delete(id);
3082
- pending.resolve(cancelled ? null : answers);
3083
- }
3109
+ if (!pending)
3110
+ return false;
3111
+ this.pendingQuestions.delete(id);
3112
+ pending.resolve(cancelled ? null : answers);
3113
+ this.emit({ type: "question_retracted", id });
3114
+ // 同上:角标消失也要即时推送(否则要等到 run 结束别处才知道问完了)。
3115
+ this.emitConversations();
3116
+ return true;
3084
3117
  }
3085
3118
  /** 快照侧的待答提问(UiState.pendingQuestion):只带当前对话的问卷——切回
3086
3119
  * 原对话会重推快照,对话框随之回来(重连/刷新/第二标签页的恢复通道)。 */
@@ -3106,6 +3139,18 @@ export class ClientSession {
3106
3139
  this.resolveQuestion(id, answers, cancelled);
3107
3140
  return Promise.resolve();
3108
3141
  }
3142
+ /** 取某对话的等答复问卷原文(跨页作答的 peek 用;只读,不改变状态)。 */
3143
+ peekPendingQuestion(convId) {
3144
+ for (const [id, p] of this.pendingQuestions) {
3145
+ if (p.conversationId === convId)
3146
+ return { id, questions: p.questions };
3147
+ }
3148
+ return undefined;
3149
+ }
3150
+ /** 跨页作答:把别处问卷的原文推给本页弹框(回答经 answerElsewhereQuestion 回去)。 */
3151
+ pushElsewhereQuestion(owner, convId, q) {
3152
+ this.emit({ type: "elsewhere_question", owner, convId, id: q.id, questions: q.questions });
3153
+ }
3109
3154
  /** 关闭所有挂起提问(dispose 时清理):以「取消」解析,避免模型挂死。 */
3110
3155
  cancelPendingQuestions() {
3111
3156
  for (const [, p] of this.pendingQuestions) {
@@ -3174,6 +3219,20 @@ export class ClientSession {
3174
3219
  return { reason: `视觉桥转写失败:${err instanceof Error ? err.message : String(err)}` };
3175
3220
  }
3176
3221
  }
3222
+ /** 页调用超时计时器:到点按失败 resolve(晚到的 page_response 在
3223
+ * resolvePageCall 里找不到 id 会静默忽略)。过户重建时复用(计时重走). */
3224
+ armPageCallTimeout(id, resolve, timeoutMs) {
3225
+ return setTimeout(() => {
3226
+ // 到点:先删再 resolve——晚到的 page_response 在 resolvePageCall 里找
3227
+ // 找不到 id,会静默忽略(见那里的注释)。
3228
+ if (this.pendingPageCalls.delete(id)) {
3229
+ resolve({
3230
+ ok: false,
3231
+ error: `${Math.round(timeoutMs / 1000)} 秒内没有收到浏览器响应(timeout ${timeoutMs}ms)。请确认 pi-web-ui 页面已打开且 page-picker 扩展已启用。`,
3232
+ });
3233
+ }
3234
+ }, timeoutMs);
3235
+ }
3177
3236
  pageCall(req, sig, conversationId) {
3178
3237
  return new Promise((resolve) => {
3179
3238
  if (sig?.aborted || this.disposed) {
@@ -3190,18 +3249,9 @@ export class ClientSession {
3190
3249
  const id = `p-${++this.pageSeq}`;
3191
3250
  // 夹取与工具入口同一套规则(防手写脏值/其它调用方绕过 schema)。
3192
3251
  const timeoutMs = normalizePageCallTimeoutMs(req.timeoutMs);
3193
- const timer = setTimeout(() => {
3194
- // 到点:先删再 resolve——晚到的 page_response 在 resolvePageCall 里找
3195
- // 找不到 id,会静默忽略(见那里的注释)。
3196
- if (this.pendingPageCalls.delete(id)) {
3197
- resolve({
3198
- ok: false,
3199
- error: `${Math.round(timeoutMs / 1000)} 秒内没有收到浏览器响应(timeout ${timeoutMs}ms)。请确认 pi-web-ui 页面已打开且 page-picker 扩展已启用。`,
3200
- });
3201
- }
3202
- }, timeoutMs);
3252
+ const timer = this.armPageCallTimeout(id, resolve, timeoutMs);
3203
3253
  // 先登记再发:同步回包(同进程假客户端)也不能漏掉。
3204
- this.pendingPageCalls.set(id, { resolve, timer, conversationId });
3254
+ this.pendingPageCalls.set(id, { resolve, timer, conversationId, req, timeoutMs });
3205
3255
  this.emit({ type: "page_request", id, op: req.op, args: req.args, target: req.target, timeoutMs });
3206
3256
  });
3207
3257
  }
@@ -4019,7 +4069,8 @@ export class ClientSession {
4019
4069
  }
4020
4070
  return out;
4021
4071
  }
4022
- /** issue #145:本实例所有正在跑的对话摘要(elsewhere 列表的本机一半)。 */
4072
+ /** issue #145:本实例所有正在跑的对话摘要(elsewhere 列表的本机一半 +
4073
+ * 手动过户的目标定位:convId + 是否有等答复问卷)。 */
4023
4074
  streamingSummariesAll() {
4024
4075
  const out = [];
4025
4076
  for (const conv of this.convs.values()) {
@@ -4027,10 +4078,62 @@ export class ClientSession {
4027
4078
  continue;
4028
4079
  if (!this.conversationStreaming(conv))
4029
4080
  continue;
4030
- out.push({ title: conv.title, cwd: conv.cwd, isStreaming: true });
4081
+ out.push({
4082
+ title: conv.title,
4083
+ cwd: conv.cwd,
4084
+ isStreaming: true,
4085
+ convId: conv.id,
4086
+ hasQuestion: this.isWaitingOnUser(conv.id),
4087
+ });
4031
4088
  }
4032
4089
  return out;
4033
4090
  }
4091
+ /**
4092
+ * 浏览器重启认领用:本会话是否有值得新标签接管的内容。
4093
+ * 跑着的(主对话/子代理都算)、后台挂着的(listed)、有消息历史的都算;
4094
+ * 纯空白会话(刚建就关了标签)不算 —— 认领它与新建无异,不如走新建流程。
4095
+ * 零 token 冒烟测试的残留会话永远是空白的,因此认领逻辑不会改变它们的行为。
4096
+ */
4097
+ hasAdoptableContent() {
4098
+ for (const c of this.convs.values()) {
4099
+ try {
4100
+ if (c.session.isStreaming)
4101
+ return true;
4102
+ }
4103
+ catch {
4104
+ // 会话替换中 —— 按未跑处理
4105
+ }
4106
+ if (c.isSubagent)
4107
+ continue;
4108
+ if (c.listed)
4109
+ return true;
4110
+ try {
4111
+ if (c.session.getSessionStats().totalMessages > 0)
4112
+ return true;
4113
+ }
4114
+ catch {
4115
+ // 会话替换中 —— 按无消息处理
4116
+ }
4117
+ }
4118
+ return false;
4119
+ }
4120
+ /** 各对话最近活跃时间的最大值(认领时多个残留按此排序,新的优先)。 */
4121
+ latestActivity() {
4122
+ let at = 0;
4123
+ for (const c of this.convs.values()) {
4124
+ at = Math.max(at, c.lastActiveAt || 0, c.lastSdkEventAt || 0);
4125
+ }
4126
+ return at;
4127
+ }
4128
+ /** 被新标签认领后首帧即被告之(pendingNotices 随 attachSink 下发)。 */
4129
+ noteAdopted() {
4130
+ this.pendingNotices.push({
4131
+ type: "notice",
4132
+ level: "info",
4133
+ text: "已恢复你关闭浏览器前的工作会话(含运行中的对话),可直接继续查看与操作。",
4134
+ textEn: "Restored the workspace session from before the browser was closed, including its running conversations — pick up right where you left off.",
4135
+ });
4136
+ }
4034
4137
  /** issue #145:让其他客户端重推 conversations(elsewhere 刷新用;
4035
4138
  * 流式集合签名驱动,外层循环安全)。 */
4036
4139
  refreshExternalRunning() {
@@ -4863,6 +4966,133 @@ export class ClientSession {
4863
4966
  conv.unsubscribe = undefined;
4864
4967
  void conv.runtime.dispose().catch(() => { });
4865
4968
  }
4969
+ /** 过户用的对话摘要(AgentService 拼移动集合 + 容量检查用)。 */
4970
+ takeoverBriefs() {
4971
+ return [...this.convs.values()].map((c) => ({
4972
+ id: c.id,
4973
+ title: c.title,
4974
+ cwd: c.cwd,
4975
+ ...(c.parentId ? { parentId: c.parentId } : {}),
4976
+ isSubagent: c.isSubagent,
4977
+ }));
4978
+ }
4979
+ /**
4980
+ * 过户转出:把指定对话(含事件订阅/看门狗计时器/等答复问卷/页调用)从本会话摘除。
4981
+ * - 先修 active:active 被搬且还有剩余 → 切过去(优先主对话);active 被搬且掏空 →
4982
+ * 建空白兜底,建不出来(quiesce)则拒绝搬出(ok:false),绝不留悬空 active。
4983
+ * - 看门狗计时器清掉(toolStartTimes 保留,目标按剩余时间重布)。
4984
+ * - 只搬归属被搬对话的问卷/页调用(conversationId 对得上的;未记归属的留在源会话)。
4985
+ */
4986
+ async detachTakeoverConversations(ids) {
4987
+ const set = new Set(ids);
4988
+ const convs = [...this.convs.values()].filter((c) => set.has(c.id));
4989
+ if (convs.length === 0)
4990
+ return { ok: false, reason: "missing" };
4991
+ if (set.has(this.activeId)) {
4992
+ const remaining = [...this.convs.values()].find((c) => !set.has(c.id) && !c.isSubagent) ??
4993
+ [...this.convs.values()].find((c) => !set.has(c.id));
4994
+ if (remaining) {
4995
+ await this.switchConversation(remaining.id);
4996
+ }
4997
+ else if (!(await this.newChat())) {
4998
+ return { ok: false, reason: "empty" };
4999
+ }
5000
+ }
5001
+ for (const conv of convs) {
5002
+ this.convs.delete(conv.id);
5003
+ this.clearAllToolWatchdogs(conv);
5004
+ conv.unsubscribe?.();
5005
+ conv.unsubscribe = undefined;
5006
+ }
5007
+ const questions = [];
5008
+ for (const [qid, p] of this.pendingQuestions) {
5009
+ if (p.conversationId !== undefined && set.has(p.conversationId)) {
5010
+ this.pendingQuestions.delete(qid);
5011
+ questions.push({ resolve: p.resolve, questions: p.questions, conversationId: p.conversationId });
5012
+ // 源页面的对话框可能是即时通道弹出的(live),快照为 null 收不掉它 ——
5013
+ // 明确撤回,让源页面立即收起(目标页由转入方重推 question_pending)。
5014
+ this.emit({ type: "question_retracted", id: qid });
5015
+ }
5016
+ }
5017
+ const pageCalls = [];
5018
+ for (const [pid, p] of this.pendingPageCalls) {
5019
+ if (p.conversationId !== undefined && set.has(p.conversationId)) {
5020
+ this.pendingPageCalls.delete(pid);
5021
+ clearTimeout(p.timer);
5022
+ pageCalls.push({ resolve: p.resolve, req: p.req, timeoutMs: p.timeoutMs, conversationId: p.conversationId });
5023
+ }
5024
+ }
5025
+ this.emitConversations();
5026
+ this.flushSnapshot();
5027
+ return { ok: true, payload: { convs, questions, pageCalls } };
5028
+ }
5029
+ /**
5030
+ * 过户转入:把另一会话摘除的对话整体接过来,返回主对话的新 id。
5031
+ * - id 冲突(两边计数器都从 c1 开始,大概率撞上)→ 给搬入方分配新 id,move
5032
+ * 集合内的 parentId/问卷归属同步改写。模型手里旧 runId 的后续子代理工具调用
5033
+ * 会报 unknown(可经列表查新 id);定时唤醒的旧 id 同理回落无头执行。
5034
+ * - 事件订阅/终端投递/问卷/页调用全部重接到本会话并立即重推(问卷对话框在新
5035
+ * 页面直接弹出来)。看门狗按剩余时间重布(已逾期的立即触发)。
5036
+ */
5037
+ insertTakeoverConvs(payload) {
5038
+ const remap = new Map();
5039
+ for (const conv of payload.convs) {
5040
+ if (this.convs.has(conv.id)) {
5041
+ remap.set(conv.id, this.nextConversationId());
5042
+ }
5043
+ }
5044
+ const fix = (id) => remap.get(id) ?? id;
5045
+ let mainId = "";
5046
+ for (const conv of payload.convs) {
5047
+ conv.id = fix(conv.id);
5048
+ if (conv.parentId)
5049
+ conv.parentId = fix(conv.parentId);
5050
+ if (!conv.isSubagent && !mainId)
5051
+ mainId = conv.id;
5052
+ conv.lastActiveAt = Date.now();
5053
+ conv.terminals.rebindEmit((msg) => this.emitTerminal(conv.id, msg));
5054
+ conv.terminals.onAgentIdle = (terminalId, idleMs, title, lastLines) => this.notifyTerminalIdle(conv.id, terminalId, idleMs, title, lastLines);
5055
+ conv.unsubscribe?.();
5056
+ conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
5057
+ for (const [toolCallId, start] of conv.toolStartTimes) {
5058
+ if (!conv.toolWatchdogs.has(toolCallId)) {
5059
+ this.rearmToolWatchdog(conv, toolCallId, TOOL_WATCHDOG_TIMEOUT_MS - (Date.now() - start));
5060
+ }
5061
+ }
5062
+ this.convs.set(conv.id, conv);
5063
+ }
5064
+ if (!mainId)
5065
+ mainId = payload.convs[0]?.id ?? "";
5066
+ for (const q of payload.questions) {
5067
+ const nid = `q-${++this.questionSeq}`;
5068
+ this.pendingQuestions.set(nid, {
5069
+ resolve: q.resolve,
5070
+ questions: q.questions,
5071
+ conversationId: fix(q.conversationId),
5072
+ });
5073
+ this.emit({ type: "question_pending", id: nid, questions: q.questions });
5074
+ }
5075
+ for (const p of payload.pageCalls) {
5076
+ const nid = `p-${++this.pageSeq}`;
5077
+ const timer = this.armPageCallTimeout(nid, p.resolve, p.timeoutMs);
5078
+ this.pendingPageCalls.set(nid, {
5079
+ resolve: p.resolve,
5080
+ timer,
5081
+ conversationId: fix(p.conversationId),
5082
+ req: p.req,
5083
+ timeoutMs: p.timeoutMs,
5084
+ });
5085
+ this.emit({
5086
+ type: "page_request",
5087
+ id: nid,
5088
+ op: p.req.op,
5089
+ args: p.req.args,
5090
+ target: p.req.target,
5091
+ timeoutMs: p.timeoutMs,
5092
+ });
5093
+ }
5094
+ return mainId;
5095
+ }
4866
5096
  /** Switch the ACTIVE conversation without interrupting any other chat. */
4867
5097
  async switchConversation(id) {
4868
5098
  if (!this.convs.has(id) || id === this.activeId)
@@ -4998,14 +5228,17 @@ export class ClientSession {
4998
5228
  })(),
4999
5229
  // 子代理带 error 标记:左栏红点提示(普通对话不参与)。
5000
5230
  ...(conv.isSubagent ? this.subagentRunOutcome(conv) : {}),
5231
+ // 等答复的问卷:左栏「?」角标(主对话/子代理各自挂名下,切过去即可回答)。
5232
+ ...(this.isWaitingOnUser(conv.id) ? { hasQuestion: true } : {}),
5001
5233
  parentId: conv.parentId,
5002
5234
  });
5003
5235
  }
5004
- // issue #145:流式集合签名变化 → 通知其他客户端重推(左栏「另一处正在运行」近实时)
5236
+ // issue #145:流式集合签名变化 → 通知其他客户端重推(左栏「另一处正在运行」近实时)。
5237
+ // 签名含等问卷态(问卷挂起/解决不改变流式集合,不带它已打开的别处页面永远看不到 `?`)。
5005
5238
  try {
5006
5239
  const sig = JSON.stringify([...this.convs.values()]
5007
5240
  .filter((c) => this.conversationStreaming(c))
5008
- .map((c) => c.id)
5241
+ .map((c) => `${c.id}:${this.isWaitingOnUser(c.id) ? 1 : 0}`)
5009
5242
  .sort());
5010
5243
  if (sig !== this.lastRunningSig) {
5011
5244
  this.lastRunningSig = sig;
@@ -5025,8 +5258,8 @@ export class ClientSession {
5025
5258
  });
5026
5259
  }
5027
5260
  /** List persisted sessions for this client, newest first. */
5028
- /** issue #145:上次 emit 时本实例流式对话 id 集合签名。变化时经
5029
- * onRunningChanged 让其他客户端重推 conversations(elsewhere 近实时);
5261
+ /** issue #145:上次 emit 时本实例流式对话 id 集合签名(含等问卷态,见 emitConversations)。
5262
+ * 变化时经 onRunningChanged 让其他客户端重推 conversations(elsewhere 近实时);
5030
5263
  * 签名相等即停,天然防 ping-pong 循环。 */
5031
5264
  lastRunningSig = "";
5032
5265
  /** The client asked for the session list at least once (lazy loading) —
@@ -6489,8 +6722,10 @@ export class ClientSession {
6489
6722
  async dispose() {
6490
6723
  this.disposed = true;
6491
6724
  this.modelAdmin.dispose();
6725
+ // 关机路径:Windows 下跳过 pty.kill()(issue #215 ConPTY 死锁),只做
6726
+ // TerminateProcess + 状态清理,句柄由 OS 在进程退出时回收。
6492
6727
  for (const conv of this.convs.values())
6493
- conv.terminals.killAll();
6728
+ conv.terminals.killAll({ shutdown: true });
6494
6729
  if (this.snapshotTimer) {
6495
6730
  clearTimeout(this.snapshotTimer);
6496
6731
  this.snapshotTimer = null;
@@ -6676,14 +6911,15 @@ export class AgentService {
6676
6911
  }
6677
6912
  return out;
6678
6913
  }
6679
- /** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知用)。 */
6914
+ /** issue #145:别处所有正在跑的对话(左栏 elsewhere 只读感知 + 手动过户用)。
6915
+ * owner/convId 标识过户目标(手动过户入口);DSH 引擎不填(不可过户)。 */
6680
6916
  listExternalRunning(excludeClientId) {
6681
6917
  const out = [];
6682
6918
  for (const [clientId, cs] of this.clients) {
6683
6919
  if (clientId === excludeClientId)
6684
6920
  continue;
6685
6921
  for (const r of cs.streamingSummariesAll())
6686
- out.push(r);
6922
+ out.push({ ...r, owner: clientId });
6687
6923
  }
6688
6924
  return out;
6689
6925
  }
@@ -6894,6 +7130,216 @@ export class AgentService {
6894
7130
  service: toServiceInfo(launchOrigin()),
6895
7131
  };
6896
7132
  }
7133
+ /** 插件/调度伪客户端:sink 常驻(fire-and-forget 的空函数),不能按浏览器存活判断。 */
7134
+ static isPseudoClientId(id) {
7135
+ return id.startsWith("plugin:") || id.startsWith("scheduler:");
7136
+ }
7137
+ /**
7138
+ * 浏览器重启认领:给 fresh clientId 找一个可接管的断开残留会话(返回旧 id)。
7139
+ * 有别的在线浏览器时返回 null(issue #10 隔离优先)。
7140
+ * 全同步:attach 里的认领段不含 await,并发的新标签后到者看到 sinkCount>0,
7141
+ * 不会抢走同一个残留。
7142
+ */
7143
+ findAdoptableOrphan(excludeClientId) {
7144
+ const cands = [];
7145
+ for (const [id, cs] of this.clients) {
7146
+ if (id === excludeClientId)
7147
+ continue;
7148
+ const pseudo = AgentService.isPseudoClientId(id);
7149
+ let live = false;
7150
+ let streaming = 0;
7151
+ let adoptable = false;
7152
+ let activity = 0;
7153
+ try {
7154
+ live = cs.sinkCount() > 0;
7155
+ }
7156
+ catch {
7157
+ live = false;
7158
+ }
7159
+ if (!pseudo && !live) {
7160
+ try {
7161
+ streaming = cs.activeConversations();
7162
+ }
7163
+ catch {
7164
+ streaming = 0;
7165
+ }
7166
+ try {
7167
+ adoptable = cs.hasAdoptableContent();
7168
+ }
7169
+ catch {
7170
+ adoptable = false;
7171
+ }
7172
+ try {
7173
+ activity = cs.latestActivity();
7174
+ }
7175
+ catch {
7176
+ activity = 0;
7177
+ }
7178
+ }
7179
+ cands.push({ id, live, pseudo, streaming, adoptable, activity });
7180
+ }
7181
+ const picked = pickAdoptableOrphan(cands);
7182
+ if (!picked)
7183
+ return null;
7184
+ const cs = this.clients.get(picked);
7185
+ return cs ? { oldId: picked, cs } : null;
7186
+ }
7187
+ /**
7188
+ * 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表 / 跨端 steer)。
7189
+ * attach 尾部与认领分支共用 —— 认领换了 map 键,必须在首帧推送(attachSink)
7190
+ * 前就按新 id 重接,否则 self-exclusion 失效:把自己当成“另一处”(elsewhere
7191
+ * 误报 + prompt/switch 自拦)。尾部会再调一次,幂等。
7192
+ */
7193
+ wireClient(cs, clientId) {
7194
+ cs.findSessionOwner = (targetPath) => this.findSessionOwner(targetPath, clientId);
7195
+ cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
7196
+ cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
7197
+ cs.listExternalRunning = () => this.listExternalRunning(clientId);
7198
+ cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
7199
+ cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
7200
+ cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
7201
+ cs.schedulerStore = this.schedulerStore;
7202
+ }
7203
+ /**
7204
+ * 手动过户(take_over_conversation):把 owner 会话的某主对话(含子代理后代、
7205
+ * 等答复问卷/页调用)整体搬到 target 会话并切过去。搬的是 runtime 本体不是
7206
+ * 副本,单 writer 不变 —— 从在线标签页手里接管也是安全的;源会话修好 active
7207
+ * 并推全量刷新,双方都收到去向通知。quiesce 排空期也放行(重连既有工作)。
7208
+ */
7209
+ async takeOverConversation(targetId, ownerId, convId) {
7210
+ const target = this.clients.get(targetId);
7211
+ if (!target)
7212
+ return;
7213
+ const fail = (text, textEn) => {
7214
+ target.sendNotice({ type: "notice", level: "warning", text, textEn });
7215
+ };
7216
+ if (!ownerId || !convId) {
7217
+ fail("过户目标不明确(缺 owner/id),请重试", "Takeover target unclear (missing owner/id), please retry.");
7218
+ return;
7219
+ }
7220
+ if (ownerId === targetId) {
7221
+ // 自己的对话 → 退化为普通切换。
7222
+ try {
7223
+ await target.switchConversation(convId);
7224
+ }
7225
+ catch {
7226
+ /* switch 内部已用 notice 报错 */
7227
+ }
7228
+ return;
7229
+ }
7230
+ if (AgentService.isPseudoClientId(ownerId)) {
7231
+ fail("定时任务/插件会话不支持过户", "Scheduler/plugin sessions cannot be taken over.");
7232
+ return;
7233
+ }
7234
+ const source = this.clients.get(ownerId);
7235
+ if (!source) {
7236
+ fail("对方会话已不存在,可从历史对话里直接打开", "The source session is gone; reopen it from History instead.");
7237
+ target.refreshExternalRunning();
7238
+ return;
7239
+ }
7240
+ const briefs = source.takeoverBriefs();
7241
+ const main = briefs.find((b) => b.id === convId);
7242
+ if (!main) {
7243
+ fail("对方已经没有这条对话(刚结束或被关闭),左栏稍后自动刷新", "That conversation is gone on the other side; the list refreshes shortly.");
7244
+ target.refreshExternalRunning();
7245
+ return;
7246
+ }
7247
+ if (main.isSubagent) {
7248
+ fail("只能过户主对话(子代理随主对话一起搬)", "Only main conversations can be taken over (subagents move with their parent).");
7249
+ return;
7250
+ }
7251
+ const moveIds = [convId, ...collectSubagentDescendantIds(briefs, convId)];
7252
+ const moveSet = new Set(moveIds);
7253
+ // 容量:与 switchSession 同口径(目标项目非子代理 8 个)。
7254
+ const movedMains = briefs.filter((b) => moveSet.has(b.id) && !b.isSubagent).length;
7255
+ const openInProject = target.takeoverBriefs().filter((b) => b.cwd === main.cwd && !b.isSubagent).length + movedMains;
7256
+ if (openInProject > MAX_OPEN_CONVERSATIONS) {
7257
+ fail(`目标项目运行的对话已达上限(${MAX_OPEN_CONVERSATIONS} 个),请先打开某个对话并离开(不继续对话)以移出列表`, `This project already has the max open conversations (${MAX_OPEN_CONVERSATIONS}). Open one and leave it (without continuing) to remove it from the list.`);
7258
+ return;
7259
+ }
7260
+ try {
7261
+ const detached = await source.detachTakeoverConversations(moveIds);
7262
+ if (!detached.ok) {
7263
+ fail(detached.reason === "empty"
7264
+ ? "对方会话只剩这一条对话且服务排空中,稍后再试"
7265
+ : "对方已经没有这条对话(刚结束或被关闭),左栏稍后自动刷新", detached.reason === "empty"
7266
+ ? "The source session only has this conversation and the server is draining; try later."
7267
+ : "That conversation is gone on the other side; the list refreshes shortly.");
7268
+ if (detached.reason === "missing")
7269
+ target.refreshExternalRunning();
7270
+ return;
7271
+ }
7272
+ const newMainId = target.insertTakeoverConvs(detached.payload);
7273
+ // 源会话修好 active(detach 内部已处理)→ 推全量刷新 + 告知去向;
7274
+ // 无 sink 时 emit 即丢,无需判断。
7275
+ source.sendNotice({
7276
+ type: "notice",
7277
+ level: "info",
7278
+ text: `「${main.title}」已过户到另一处接管,本页不再持有它。`,
7279
+ textEn: `"${main.title}" was taken over by another page and is no longer held here.`,
7280
+ });
7281
+ target.sendNotice({
7282
+ type: "notice",
7283
+ level: "info",
7284
+ text: `已将「${main.title}」过户到当前页面,可直接继续查看与操作。`,
7285
+ textEn: `"${main.title}" was moved to this page — pick up right where it left off.`,
7286
+ });
7287
+ await target.switchConversation(newMainId);
7288
+ }
7289
+ catch (err) {
7290
+ fail(`过户失败:${err.message}`, `Takeover failed: ${err.message}`);
7291
+ }
7292
+ }
7293
+ /**
7294
+ * 跨页作答预告(peek_elsewhere_question):把 owner 会话里某对话的等答复问卷
7295
+ * 原文取回 target 页展示。只读,不搬迁对话;问卷已不在则直说(并刷新左栏)。
7296
+ */
7297
+ async peekElsewhereQuestion(targetId, ownerId, convId) {
7298
+ const target = this.clients.get(targetId);
7299
+ if (!target)
7300
+ return;
7301
+ const fail = (text, textEn) => {
7302
+ target.sendNotice({ type: "notice", level: "warning", text, textEn });
7303
+ };
7304
+ if (!ownerId || !convId) {
7305
+ fail("问卷目标不明确(缺 owner/id),请重试", "Question target unclear (missing owner/id), please retry.");
7306
+ return;
7307
+ }
7308
+ if (ownerId === targetId)
7309
+ return; // 自己的问卷走本地通道,不需要预告
7310
+ if (AgentService.isPseudoClientId(ownerId)) {
7311
+ fail("定时任务/插件会话的问卷不支持跨页作答", "Scheduler/plugin session questions cannot be answered cross-page.");
7312
+ return;
7313
+ }
7314
+ const source = this.clients.get(ownerId);
7315
+ const q = source?.peekPendingQuestion(convId);
7316
+ if (!q) {
7317
+ fail("那张问卷已不在(对方刚回答/取消或对话已结束)", "That question is gone (just answered/cancelled there, or the run ended).");
7318
+ target.refreshExternalRunning();
7319
+ return;
7320
+ }
7321
+ target.pushElsewhereQuestion(ownerId, convId, q);
7322
+ }
7323
+ /**
7324
+ * 跨页作答(question_answer 带 owner):把本页提交的答案送到持有方会话。
7325
+ * 问卷已不在(对方刚回答/取消)则明确告知,答案不吞不丢两不沾 —— 没送出就是没送出。
7326
+ */
7327
+ async answerElsewhereQuestion(targetId, ownerId, id, answers, cancelled) {
7328
+ const target = this.clients.get(targetId);
7329
+ if (!target)
7330
+ return;
7331
+ const source = this.clients.get(ownerId);
7332
+ const ok = source ? source.resolveQuestion(id, answers, cancelled) : false;
7333
+ if (!ok) {
7334
+ target.sendNotice({
7335
+ type: "notice",
7336
+ level: "warning",
7337
+ text: "那张问卷已不在(对方刚回答/取消或对话已结束),你的回答没有送出",
7338
+ textEn: "That question is gone (just answered/cancelled there, or the run ended) — your answer was not delivered.",
7339
+ });
7340
+ target.refreshExternalRunning();
7341
+ }
7342
+ }
6897
7343
  /** Get or create the session for a client, racing attach calls safely. */
6898
7344
  async attach(clientId, send) {
6899
7345
  let cs = this.clients.get(clientId);
@@ -6903,67 +7349,83 @@ export class AgentService {
6903
7349
  cs = await inflight;
6904
7350
  }
6905
7351
  else {
6906
- // Restore this client's last-used workspace when it still exists;
6907
- // Admission gate: while quiesced, only clients with an EXISTING
6908
- // session may attach (they can watch their runs drain); brand-new
6909
- // clients are refused — index.ts closes their socket (4403) and the
6910
- // browser reconnect loop retries after admission reopens.
6911
- if (this.quiesced) {
6912
- throw new QuiesceRejectedError("新连接被拒绝,请等服务器恢复后重试");
7352
+ // 浏览器重启认领(clientId 存 sessionStorage,关浏览器即失;服务端残留
7353
+ // ClientSession 的运行中对话否则永远卡在“另一处”只读,连看都看不了):
7354
+ // 无其他在线浏览器时,把最近断开的残留会话整体过户给这个新 id
7355
+ // (只换 map 键,不搬 runtime:对话/终端/订阅/cwd 原样保留,
7356
+ // 流式增量经尾部 attachSink 直接推给新 socket)。
7357
+ // 有其他在线标签时不认领(issue #10 隔离优先);quiesce 排空期也放行
7358
+ // (这是重连既有工作,不是新工作)。本段无 await,并发 attach 原子。
7359
+ const orphan = this.findAdoptableOrphan(clientId);
7360
+ if (orphan) {
7361
+ this.clients.delete(orphan.oldId);
7362
+ this.clients.set(clientId, orphan.cs);
7363
+ cs = orphan.cs;
7364
+ // 先按新 id 重接(首帧 attachSink 的 elsewhere/self-exclusion 依赖它)。
7365
+ this.wireClient(cs, clientId);
7366
+ cs.noteAdopted();
7367
+ // 服务重启前记在旧 id 名下的中断记录搬到新 id 名下,尾部
7368
+ // resumeInterrupted 按新 id 消费(只认领一次,不重复恢复)。
7369
+ const inter = this.stateStore.takeInterrupted(orphan.oldId);
7370
+ if (inter?.length)
7371
+ this.stateStore.saveInterrupted(clientId, inter);
6913
7372
  }
6914
- // otherwise fall back to the server's configured default cwd.
6915
- let cwd = this.cwd;
6916
- const saved = this.stateStore.get(clientId);
6917
- if (saved.lastCwd && saved.lastCwd !== this.cwd) {
6918
- try {
6919
- if (statSync(saved.lastCwd).isDirectory())
6920
- cwd = saved.lastCwd;
6921
- }
6922
- catch {
6923
- // gone (unmounted drive / deleted) — fall back to the default
7373
+ else {
7374
+ // Restore this client's last-used workspace when it still exists;
7375
+ // Admission gate: while quiesced, only clients with an EXISTING
7376
+ // session may attach (they can watch their runs drain); brand-new
7377
+ // clients are refused — index.ts closes their socket (4403) and the
7378
+ // browser reconnect loop retries after admission reopens.
7379
+ if (this.quiesced) {
7380
+ throw new QuiesceRejectedError("新连接被拒绝,请等服务器恢复后重试");
6924
7381
  }
6925
- }
6926
- // Sessions use the SDK default per-project dir — no per-client dir.
6927
- // issue #145:新标签页默认恢复项目最近的会话 —— 若那条在别处跑着,
6928
- // 建之前就决定空白(第二个 writer 根本不会被打开,也无需事后拆 runtime)。
6929
- // 先做无 I/O 的便宜判断,无人在跑时不扫目录。
6930
- let createOpts;
6931
- if (this.hasStreamingElsewhere(clientId)) {
6932
- try {
6933
- const infos = await SessionManager.list(cwd, piSessionsRoot());
6934
- const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
6935
- const owner = recent ? this.findSessionOwner(recent, clientId) : null;
6936
- if (owner?.isStreaming)
6937
- createOpts = { blank: true, blankTitle: owner.title };
7382
+ // otherwise fall back to the server's configured default cwd.
7383
+ let cwd = this.cwd;
7384
+ const saved = this.stateStore.get(clientId);
7385
+ if (saved.lastCwd && saved.lastCwd !== this.cwd) {
7386
+ try {
7387
+ if (statSync(saved.lastCwd).isDirectory())
7388
+ cwd = saved.lastCwd;
7389
+ }
7390
+ catch {
7391
+ // gone (unmounted drive / deleted) — fall back to the default
7392
+ }
6938
7393
  }
6939
- catch {
6940
- // 列表失败不挡正常恢复
7394
+ // Sessions use the SDK default per-project dir — no per-client dir.
7395
+ // issue #145:新标签页默认恢复项目最近的会话 —— 若那条在别处跑着,
7396
+ // 建之前就决定空白(第二个 writer 根本不会被打开,也无需事后拆 runtime)。
7397
+ // 先做无 I/O 的便宜判断,无人在跑时不扫目录。
7398
+ let createOpts;
7399
+ if (this.hasStreamingElsewhere(clientId)) {
7400
+ try {
7401
+ const infos = await SessionManager.list(cwd, piSessionsRoot());
7402
+ const recent = infos[0]?.path ? resolve(infos[0].path) : undefined;
7403
+ const owner = recent ? this.findSessionOwner(recent, clientId) : null;
7404
+ if (owner?.isStreaming)
7405
+ createOpts = { blank: true, blankTitle: owner.title };
7406
+ }
7407
+ catch {
7408
+ // 列表失败不挡正常恢复
7409
+ }
6941
7410
  }
6942
- }
6943
- const creating = ClientSession.create(clientId, cwd, this.stateStore, createOpts).finally(() => {
6944
- this.pending.delete(clientId);
6945
- });
6946
- this.pending.set(clientId, creating);
6947
- cs = await creating;
6948
- this.clients.set(clientId, cs);
6949
- // issue #145 接线提前:首帧 elsewhere 依赖它。
6950
- cs.findSessionOwner = (targetPath) => this.findSessionOwner(targetPath, clientId);
6951
- cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
6952
- cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
6953
- cs.listExternalRunning = () => this.listExternalRunning(clientId);
6954
- cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
6955
- cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
6956
- cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
6957
- cs.schedulerStore = this.schedulerStore;
6958
- // Make sure the restored/default workspace appears in the project list.
6959
- this.stateStore.remember(clientId, cwd);
6960
- if (cwd !== this.cwd) {
6961
- send({
6962
- type: "notice",
6963
- level: "info",
6964
- text: `已恢复上次的工作目录:${cwd}`,
6965
- textEn: `Restored the last working directory: ${cwd}`,
7411
+ const creating = ClientSession.create(clientId, cwd, this.stateStore, createOpts).finally(() => {
7412
+ this.pending.delete(clientId);
6966
7413
  });
7414
+ this.pending.set(clientId, creating);
7415
+ cs = await creating;
7416
+ this.clients.set(clientId, cs);
7417
+ // issue #145 接线提前:首帧 elsewhere 依赖它。
7418
+ this.wireClient(cs, clientId);
7419
+ // Make sure the restored/default workspace appears in the project list.
7420
+ this.stateStore.remember(clientId, cwd);
7421
+ if (cwd !== this.cwd) {
7422
+ send({
7423
+ type: "notice",
7424
+ level: "info",
7425
+ text: `已恢复上次的工作目录:${cwd}`,
7426
+ textEn: `Restored the last working directory: ${cwd}`,
7427
+ });
7428
+ }
6967
7429
  }
6968
7430
  }
6969
7431
  }
@@ -6984,13 +7446,7 @@ export class AgentService {
6984
7446
  cs.pluginStopBgTask = this.pluginStopBgTask;
6985
7447
  cs.isQuiesced = () => this.quiesced;
6986
7448
  // issue #145 跨客户端感知接线(同会话查重 / 同项目并行 / elsewhere 列表)。
6987
- cs.findSessionOwner = (targetPath) => this.findSessionOwner(targetPath, clientId);
6988
- cs.hasStreamingElsewhere = () => this.hasStreamingElsewhere(clientId);
6989
- cs.listProjectRunners = (cwd) => this.listProjectRunners(cwd, clientId);
6990
- cs.listExternalRunning = () => this.listExternalRunning(clientId);
6991
- cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
6992
- cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
6993
- cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
7449
+ this.wireClient(cs, clientId);
6994
7450
  // 插件宿主工作区跟随:初次接入也同步一次(恢复的 lastCwd 可能≠服务启动目录),
6995
7451
  // notifyCwd 幂等去重;此后 set_cwd 成功时由 cs.onCwdChanged 继续驱动。
6996
7452
  cs.onCwdChanged = (abs, roots) => this.onClientCwdChanged?.(abs, roots);