@spzxg/cli-ui 0.6.13 → 0.6.18

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.
Files changed (100) hide show
  1. package/CHANGELOG.md +108 -2
  2. package/README.md +140 -7
  3. package/dist/{cli-ui-embed-CXaGT9e4.js → cli-ui-embed-Dsw7A8BQ.js} +20333 -19872
  4. package/dist/{cli-ui-index-bMQJjEBW.js → cli-ui-index-CHFgaDHY.js} +2 -2
  5. package/dist/{cli-ui-jszip.min-D_w3a6AF.js → cli-ui-jszip.min-DDRprLiN.js} +1 -1
  6. package/dist/{cli-ui-jszip.min-AMeWMDT5.js → cli-ui-jszip.min-Dw9DMuD5.js} +2 -2
  7. package/dist/{cli-ui-xlsx-DMzew4IO.js → cli-ui-xlsx-BUG2_Azh.js} +1 -1
  8. package/dist/cli-ui.css +1 -1
  9. package/dist/cli-ui.js +1 -1
  10. package/package.json +1 -1
  11. package/src/board/BrowserPane.tsx +93 -30
  12. package/src/board/ChangesPane.tsx +86 -62
  13. package/src/board/CliBoard.tsx +65 -30
  14. package/src/board/FileViewer.tsx +49 -13
  15. package/src/board/context.ts +38 -7
  16. package/src/board/diffLines.ts +46 -0
  17. package/src/board/diffRefresh.ts +63 -0
  18. package/src/board/fileDiff.tsx +117 -0
  19. package/src/board/fileKind.ts +5 -3
  20. package/src/board/fileScope.ts +4 -2
  21. package/src/board/fileWatch.ts +59 -9
  22. package/src/board/linkage.ts +68 -0
  23. package/src/board/pathResolve.ts +108 -0
  24. package/src/board/useBoardUpload.tsx +7 -7
  25. package/src/board/workspace.ts +7 -1
  26. package/src/chat/CliChat.tsx +197 -216
  27. package/src/chat/Composer.tsx +10 -9
  28. package/src/chat/queueEdit.ts +27 -0
  29. package/src/components.tsx +2 -2
  30. package/src/core/blocks.ts +4 -1
  31. package/src/core/client.ts +86 -9
  32. package/src/core/config.ts +1 -1
  33. package/src/core/conversation.ts +23 -5
  34. package/src/core/documentUpload.ts +22 -5
  35. package/src/core/provider.tsx +14 -8
  36. package/src/core/store.ts +307 -63
  37. package/src/core/types.ts +49 -0
  38. package/src/elements.tsx +8 -5
  39. package/src/msglist/CliMsgList.tsx +30 -9
  40. package/src/operator/node/AgentConnect.tsx +28 -29
  41. package/src/operator/node/AppearancePanel.tsx +1 -1
  42. package/src/operator/node/BranchHistory.tsx +11 -7
  43. package/src/operator/node/BranchNavigator.tsx +1 -1
  44. package/src/operator/node/BrowserPane.tsx +7 -7
  45. package/src/operator/node/Chat.tsx +53 -272
  46. package/src/operator/node/CommandPalette.tsx +1 -1
  47. package/src/operator/node/Composer.tsx +13 -6
  48. package/src/operator/node/Layout.tsx +1 -1
  49. package/src/operator/node/Markdown.tsx +6 -36
  50. package/src/operator/node/Modal.tsx +1 -1
  51. package/src/operator/node/OnboardingWizard.tsx +11 -9
  52. package/src/operator/node/Orchestrator.tsx +18 -8
  53. package/src/operator/node/ProjectLanding.tsx +1 -1
  54. package/src/operator/node/ProjectsColumn.tsx +1 -1
  55. package/src/operator/node/ProviderAuth.tsx +16 -16
  56. package/src/operator/node/RunSwitch.tsx +1 -1
  57. package/src/operator/node/Services.tsx +1 -1
  58. package/src/operator/node/SessionRail.tsx +55 -19
  59. package/src/operator/node/SessionView.tsx +18 -16
  60. package/src/operator/node/SettingsView.tsx +1 -1
  61. package/src/operator/node/TaskBoard.tsx +1 -1
  62. package/src/operator/node/TaskChanges.tsx +83 -108
  63. package/src/operator/node/TaskHero.tsx +5 -5
  64. package/src/operator/node/TasksColumn.tsx +1 -1
  65. package/src/operator/node/Transcript.tsx +15 -250
  66. package/src/operator/node/Welcome.tsx +1 -1
  67. package/src/operator/node/WorktreePrune.tsx +1 -1
  68. package/src/operator/node/api.ts +17 -0
  69. package/src/operator/node/boardBackend.ts +4 -1
  70. package/src/operator/node/boardEvents.ts +17 -3
  71. package/src/operator/node/boardInteraction.ts +7 -4
  72. package/src/operator/node/boardState.ts +23 -14
  73. package/src/operator/node/composerDraft.ts +22 -0
  74. package/src/operator/node/fileLinks.ts +4 -38
  75. package/src/operator/node/format.ts +13 -104
  76. package/src/operator/node/github.tsx +14 -14
  77. package/src/operator/node/liveStream.ts +47 -6
  78. package/src/operator/node/modals.tsx +59 -22
  79. package/src/operator/node/recheckOnReturn.ts +28 -0
  80. package/src/operator/node/shared.tsx +10 -50
  81. package/src/operator/node/types.ts +9 -0
  82. package/src/operator/node/useOrchestrator.ts +9 -8
  83. package/src/operator/node/useRecaps.ts +15 -4
  84. package/src/operator/node/useTaskStream.ts +2 -2
  85. package/src/operator.base.css +9 -4
  86. package/src/operator.css +9 -4
  87. package/src/styles.css +22 -8
  88. package/src/ui/Markdown.tsx +42 -21
  89. package/src/ui/Popover.tsx +1 -1
  90. package/src/ui/QueuedMessages.tsx +58 -15
  91. package/src/ui/SubagentChat.tsx +42 -6
  92. package/src/ui/Transcript.tsx +19 -14
  93. package/src/ui/fileLinks.ts +6 -3
  94. package/src/ui/format.ts +27 -9
  95. package/src/ui/icons.tsx +2 -0
  96. package/src/ui/shared.tsx +11 -7
  97. package/src/ui/transcriptModel.ts +40 -9
  98. package/src/ui/useTranscriptWindow.ts +253 -0
  99. package/src/operator/node/icons.tsx +0 -88
  100. package/src/operator/node/transcriptModel.ts +0 -129
package/src/core/store.ts CHANGED
@@ -16,13 +16,16 @@ import { notifyCallback } from "./callbacks";
16
16
  import { CenterError, createCenterClient, firstLine, type CenterClient, type CenterClientOptions } from "./client";
17
17
  import { addTurnsIfAbsent, applyItems, applyOlderPage, applySnapshot, closedCallback, convEnded, convKey, emptyConv, isChatTask, NEW_TASK, parseConvKey, TERMINAL_JOB, TERMINAL_TURN, turnCallback, upsertTurns, type ConvState } from "./conversation";
18
18
  import { formatAnswersText } from "../ui/format";
19
+ import { KEEP_TRANSCRIPTS, trimToTail } from "../ui/transcriptModel";
19
20
  import { backgroundBlock, charCount, MAX_MESSAGE_CHARS, serializeBlock } from "./blocks";
20
- import { cloneBoardView, reportBoardOwner, activateBoardOwner, selectedBoardOwner, mergeBoardHistory, rememberBoardFile } from "../board/context";
21
+ import { cloneBoardView, mergeBoardHistory, rememberBoardFile, withBoardPaths } from "../board/context";
22
+ import { createBoardOwners, createBoardSurfaces } from "../board/linkage";
21
23
  import { cloneWorkspaceChange, subscribeWorkspaceFiles, retryWorkspaceFiles, type WorkspaceWatchOptions } from "../board/fileWatch";
22
24
  import { retainFileScope } from "../board/fileScope";
23
25
  import type { WorkspaceChangeEvent, WorkspaceWatchStatus } from "./types";
24
26
  import { createWorkspace, type BoardView, type CliWorkspace } from "../board/workspace";
25
- import type { AskAnswers, AskQuestion, CenterJob, CenterTurn, ConversationClosedCallback, ConversationTurnCallback, NewConversationOptions } from "./types";
27
+ import type { AskAnswers, AskQuestion, BatchStreamTask, CenterJob, CenterTurn, ConversationClosedCallback, ConversationTurnCallback, NewConversationOptions, StreamItem, TaskAttemptEndPayload, TaskEndPayload } from "./types";
28
+ import { isBatchSnapshot } from "./types";
26
29
 
27
30
  export interface JobEntry {
28
31
  job: CenterJob | null;
@@ -100,6 +103,10 @@ export type CliEvent =
100
103
  | { type: "conversation_turn"; jobId: string; key: string; turn: CenterTurn; payload: ConversationTurnCallback }
101
104
  /** 对话结束(整个对话任务结束,或只关掉了这一个对话)。payload 与 center 回调 conversation_closed 的请求体同名同义。 */
102
105
  | { type: "conversation_closed"; jobId: string; key: string; reason: string | null; continuedBy: string | null; payload: ConversationClosedCallback }
106
+ /** 一次性任务(含续派)里一个子任务结束(初始历史终态不补报)。payload 字段与中枢一次性任务回调体 tasks[] 的一项同名。 */
107
+ | { type: "task_end"; jobId: string; key: string; task: BatchStreamTask; payload: TaskEndPayload }
108
+ /** 实际派发的执行批次结束;同一任务手动重试后可再次通知,旧服务缺标识时不发。 */
109
+ | { type: "task_attempt_end"; jobId: string; key: string; task: BatchStreamTask; payload: TaskAttemptEndPayload }
103
110
  /**
104
111
  * 新建了对话(新对话任务,或在对话任务里新开的对话),或旧对话结束后消息开了新对话(job_id 变了)。
105
112
  * taskId / key:新的那个对话;previousKey:之前的对话键(新建时是 null 或 "job#new")。
@@ -124,8 +131,19 @@ export type CliEvent =
124
131
  */
125
132
  | { type: "context"; key: string; pending: ContextItem[]; sent?: ContextItem[] };
126
133
 
127
- /** Public workspace metadata must not be shared between business listeners. */
134
+ /** Result consumers can annotate their own copy without changing later callbacks. */
135
+ export function cloneResultPayload<T extends ConversationTurnCallback | ConversationClosedCallback | TaskEndPayload | TaskAttemptEndPayload>(payload: T): T {
136
+ return payload.type === "conversation_turn" ? { ...payload, messages: payload.messages?.map(message => ({ ...message })) } : { ...payload };
137
+ }
138
+
139
+ /** Public event values must not be shared between business listeners or the store. */
128
140
  export function cloneWorkspaceEvent(event:CliEvent):CliEvent {
141
+ if(event.type==='conversation_turn')return {...event,turn:{...event.turn},payload:cloneResultPayload(event.payload)};
142
+ if(event.type==='conversation_closed')return {...event,payload:cloneResultPayload(event.payload)};
143
+ if(event.type==='task_end'||event.type==='task_attempt_end') {
144
+ const task={...event.task,...(event.task.queued?{queued:event.task.queued.map(item=>({...item}))}:{})};
145
+ return event.type==='task_end' ? {...event,task,payload:cloneResultPayload(event.payload)} : {...event,task,payload:cloneResultPayload(event.payload)};
146
+ }
129
147
  if(event.type==='files_changed')return cloneWorkspaceChange(event);
130
148
  if(event.type==='files_watch')return {...event};
131
149
  if(event.type==='board_ref')return {...event,refs:event.refs.map(ref=>({...ref}))};
@@ -172,7 +190,17 @@ export interface SendOptions {
172
190
  businessIdFor?: (text: string, kind: "create" | "message") => string;
173
191
  }
174
192
 
175
- const RECONNECT_MS = [1_000, 2_000, 5_000, 10_000, 20_000];
193
+ /**
194
+ * 断线后自动重连的退避(约 2 分钟内重试 7 次)。用完就停下(stream: "offline"),不再定时重试:
195
+ * 网络恢复、页面回到前台、窗口重新获得焦点、这个对话发出消息或调用 store.reconnect() 时再连。
196
+ */
197
+ const RECONNECT_MS = [1_000, 2_000, 5_000, 10_000, 20_000, 30_000, 60_000];
198
+ /**
199
+ * 断线后先悄悄重连,这么久之内重新连上(收到快照)就不提示,stream 保持原样(live / connecting);
200
+ * 超过仍没连上才变成 "reconnecting",界面显示「正在重连」。网关回收长连接、网络抖动、电脑休眠唤醒、
201
+ * 中枢重启时的一次断线大多几秒内就接上,期间漏掉的事件由重连后的快照补齐,不必打扰用户。
202
+ */
203
+ export const RECONNECT_NOTICE_MS = 15_000;
176
204
  /**
177
205
  * 退避时间上下浮动 ±30%:中枢重启时所有页面同时断开,不错开的话会在同一秒一起重连、一起拉快照,
178
206
  * 人多时把刚起来的中枢再压垮一次。
@@ -183,8 +211,18 @@ export const jitter = (ms: number) => Math.round(ms * (0.7 + Math.random() * 0.6
183
211
  * 很多人开着页面不看时,中枢和节点不用一直为他们推数据。
184
212
  */
185
213
  export const PARK_HIDDEN_MS = 5 * 60_000;
186
- /** 401 / 403:多半是宿主的登录会话过期了。宿主续上会话后要能自己恢复,所以慢慢重试,不永久放弃。 */
214
+ /**
215
+ * 没人看的对话(对话、看板都不看了)最多留这么多个的记录在内存里,每个离开时截到最新 SNAPSHOT_TAIL 条(往上翻过的更早消息丢掉,
216
+ * 再往上翻时重新取):来回切换最近看过的仍然立刻显示,更早的整个释放,再打开时从实时流重新读。
217
+ * 与节点适配(useTaskStream)同一条规则、同一组常量(ui/transcriptModel 的 KEEP_TRANSCRIPTS / trimToTail)。
218
+ */
219
+ export const IDLE_CONV_MAX = KEEP_TRANSCRIPTS;
220
+ /**
221
+ * 401 / 403:多半是宿主的登录会话过期了。隔 30 秒再试,最多 AUTH_RETRIES 次;之后停下等事件
222
+ * (宿主续上会话后切回页面、获得焦点或调用 store.reconnect() 即恢复),不无限重试。
223
+ */
187
224
  const AUTH_RETRY_MS = 30_000;
225
+ const AUTH_RETRIES = 3;
188
226
 
189
227
  // 全局只挂一份「网络恢复 / 切回页面」监听,转给当前有实时流的仓库。
190
228
  const reconnectors = new Set<() => void>();
@@ -206,6 +244,7 @@ function watchReconnect(fn: () => void, park: () => void) {
206
244
  if (listening || typeof window === "undefined") return;
207
245
  listening = true;
208
246
  window.addEventListener("online", fireReconnect);
247
+ window.addEventListener("focus", fireReconnect);
209
248
  document.addEventListener("visibilitychange", onVisible);
210
249
  }
211
250
  function unwatchReconnect(fn: () => void, park: () => void) {
@@ -214,6 +253,7 @@ function unwatchReconnect(fn: () => void, park: () => void) {
214
253
  if (!listening || reconnectors.size) return;
215
254
  listening = false;
216
255
  window.removeEventListener("online", fireReconnect);
256
+ window.removeEventListener("focus", fireReconnect);
217
257
  document.removeEventListener("visibilitychange", onVisible);
218
258
  }
219
259
  /** 测试用:当前登记着的仓库数。 */
@@ -236,6 +276,45 @@ export function createCliStore(options: CliStoreOptions = {}) {
236
276
  const eventListeners = new Set<(event: CliEvent) => void>();
237
277
  const settledTurns = new Set<string>();
238
278
  const watchedTurns = new Set<string>();
279
+ // 初始快照里的历史终态不补报;之后新增的任务即使首次出现就是终态,也发一次 task_end。
280
+ const watchedTasks = new Set<string>();
281
+ const historicalTasks = new Set<string>();
282
+ const endedTasks = new Set<string>();
283
+ const watchedExecutions = new Set<string>();
284
+ const endedExecutions = new Set<string>();
285
+ function noticeTaskAttempt(key: string, jobId: string, task: BatchStreamTask, initial: boolean) {
286
+ // A missing identity is an older service, not permission to infer a batch from attempt.
287
+ if (typeof task.execution_id !== "string" || !task.execution_id || typeof task.dispatched_at !== "string" || !task.dispatched_at || !Number.isFinite(Date.parse(task.dispatched_at))) return;
288
+ const execution = JSON.stringify([jobId, task.id, task.execution_id]);
289
+ if (!TERMINAL_JOB.has(task.status)) { watchedExecutions.add(execution); return; }
290
+ if (initial && !watchedExecutions.has(execution)) endedExecutions.add(execution);
291
+ if (endedExecutions.has(execution)) return;
292
+ endedExecutions.add(execution);
293
+ const payload: TaskAttemptEndPayload = {
294
+ type: "task_attempt_end", job_id: jobId, task_id: task.id, task_key: task.task_key ?? null, title: task.title, status: task.status,
295
+ attempts: task.attempt ?? 0, message: task.last_error ?? null, conversation: !!task.conversation,
296
+ continue_from_task_id: task.continue_from_task_id ?? null, occurred_at: new Date().toISOString(),
297
+ execution_id: task.execution_id, round: task.round ?? 0, dispatched_at: task.dispatched_at, ended_at: task.ended_at ?? null,
298
+ };
299
+ emit({ type: "task_attempt_end", jobId, key, task: { ...task }, payload });
300
+ }
301
+ function noticeTaskEnd(key: string, jobId: string, task: BatchStreamTask, initial: boolean) {
302
+ if (!TERMINAL_JOB.has(task.status)) { watchedTasks.add(task.id); historicalTasks.delete(task.id); return; }
303
+ if (initial && !watchedTasks.has(task.id)) historicalTasks.add(task.id);
304
+ if (historicalTasks.has(task.id) || endedTasks.has(task.id)) return;
305
+ endedTasks.add(task.id);
306
+ const payload: TaskEndPayload = {
307
+ type: "task_end", job_id: jobId, task_id: task.id, task_key: task.task_key ?? null, title: task.title, status: task.status,
308
+ attempts: task.attempt ?? 0, message: task.last_error ?? null, conversation: !!task.conversation,
309
+ continue_from_task_id: task.continue_from_task_id ?? null, occurred_at: new Date().toISOString(),
310
+ };
311
+ emit({ type: "task_end", jobId, key, task: { ...task }, payload });
312
+ }
313
+ function noticeBatchTask(key: string, jobId: string, task: BatchStreamTask | null | undefined, initial = false) {
314
+ if (!task || typeof task.id !== "string") return;
315
+ noticeTaskEnd(key, jobId, task, initial);
316
+ noticeTaskAttempt(key, jobId, task, initial);
317
+ }
239
318
  const closedJobs = new Set<string>();
240
319
  const seenOpen = new Set<string>();
241
320
  let hostIds = false;
@@ -254,12 +333,24 @@ export function createCliStore(options: CliStoreOptions = {}) {
254
333
  try{while(eventQueue.length){const next=eventQueue.shift()!;for(const fn of next.listeners)notifyCallback(fn,cloneWorkspaceEvent(next.event));}}
255
334
  finally{dispatching=false;}
256
335
  };
336
+ const transitions: Array<{ key: string; prev: ConvState; next: ConvState }> = [];
337
+ let notifyingTransitions = false;
257
338
  const patchConv = (key: string, fn: (conv: ConvState) => ConvState) => {
258
339
  const prev = state.convs[key] ?? emptyConv(key);
259
340
  const next = fn(prev);
260
341
  if (next !== prev) {
261
- noticeTransitions(key, prev, next);
342
+ transitions.push({ key, prev, next });
262
343
  set({ convs: { ...state.convs, [key]: next } });
344
+ // Commit before notifying hosts. A callback can synchronously reconnect
345
+ // and apply a newer snapshot; never write this older state over it.
346
+ if (notifyingTransitions) return;
347
+ notifyingTransitions = true;
348
+ try {
349
+ while (transitions.length) {
350
+ const transition = transitions.shift()!;
351
+ noticeTransitions(transition.key, transition.prev, transition.next);
352
+ }
353
+ } finally { notifyingTransitions = false; }
263
354
  }
264
355
  };
265
356
  const patchJob = (jobId: string, patch: Partial<JobEntry>) => {
@@ -274,7 +365,7 @@ export function createCliStore(options: CliStoreOptions = {}) {
274
365
  const before = new Map(prev.turns.map((turn) => [turn.turn_id, turn.status]));
275
366
  // 有轮次开始执行 / 新排队:列表卡片的「运行中」「排队中」也要跟上,不等下一次轮询。
276
367
  if (next.turns.some((turn) => before.get(turn.turn_id) !== turn.status && !TERMINAL_TURN.has(turn.status))) void refreshJob(jobId);
277
- // 本页看着还没结束过的轮次才发结果(打开页面时就已结束的历史轮次不发)。
368
+ // 记下已提交或见过的未结束轮次:首次快照也应为这些轮次补报结果。
278
369
  for (const turn of next.turns) if (!TERMINAL_TURN.has(turn.status)) watchedTurns.add(turn.turn_id);
279
370
  // 按 seq 顺序发,与 center 投递 callback 的顺序一致:前面还有没结束的轮次,后面结束了的先等着
280
371
  // (例如第 2 条排队消息被撤回时第 1 轮还在跑,要等第 1 轮结束后先发 1、再发 2)。
@@ -283,7 +374,7 @@ export function createCliStore(options: CliStoreOptions = {}) {
283
374
  if (settledTurns.has(turn.turn_id)) continue;
284
375
  settledTurns.add(turn.turn_id);
285
376
  // 被合并进别的轮次的消息不单独发(center 也不单独投递),结果在那一轮的 messages 里。
286
- if (!watchedTurns.has(turn.turn_id) || turn.status === "merged") continue;
377
+ if (turn.status === "merged") continue;
287
378
  const continuedFrom = state.jobs[jobId]?.job?.conversation?.continued_from_job_id ?? null;
288
379
  emit({ type: "conversation_turn", jobId, key, turn, payload: turnCallback(next, turn, continuedFrom) });
289
380
  void refreshJob(jobId, true);
@@ -343,11 +434,14 @@ export function createCliStore(options: CliStoreOptions = {}) {
343
434
  }
344
435
 
345
436
  const refreshAgain = new Set<string>();
437
+ /** 每个对话任务拉过几次详情(成功或失败都算):列表排队期间别处拉过了就不再重复。 */
438
+ const fetches = new Map<string, number>();
346
439
  async function refreshJob(jobId: string, force = false) {
347
440
  const entry = state.jobs[jobId];
348
441
  // 正在拉:拉完再补一次,免得错过这期间的变化(例如轮次刚从排队变成执行中)。
349
442
  if (entry?.loading) { refreshAgain.add(jobId); return; }
350
443
  if (!force && entry && Date.now() - entry.fetchedAt < JOB_REFRESH_GAP_MS) return;
444
+ fetches.set(jobId, (fetches.get(jobId) ?? 0) + 1);
351
445
  patchJob(jobId, { loading: true });
352
446
  try {
353
447
  const job = await client.getJob(jobId);
@@ -358,8 +452,11 @@ export function createCliStore(options: CliStoreOptions = {}) {
358
452
  firstInput = first?.turns[0]?.input ?? "";
359
453
  }
360
454
  patchJob(jobId, { job, firstInput, loading: false, error: null, fetchedAt: Date.now() });
361
- // 新数据里已包含实时用量,清零累计(这个对话任务里的每个对话)。
362
- for (const conv of Object.values(state.convs)) if (conv.jobId === jobId) patchConv(conv.key, (c) => ({ ...c, liveUsage: { fresh: 0, cacheRead: 0 } }));
455
+ // 新数据里已包含实时用量,清零累计(这个对话任务里的每个对话)。已经是 0 的不动:不然每次刷新都换一个对话对象,
456
+ // 看着它的对话组件会把整份消息重算、重画一遍。
457
+ for (const conv of Object.values(state.convs)) {
458
+ if (conv.jobId === jobId && (conv.liveUsage.fresh || conv.liveUsage.cacheRead)) patchConv(conv.key, (c) => ({ ...c, liveUsage: { fresh: 0, cacheRead: 0 } }));
459
+ }
363
460
  } catch (error) {
364
461
  patchJob(jobId, { loading: false, error: error instanceof Error ? error.message : String(error), fetchedAt: Date.now() });
365
462
  // 本地记住的对话在 center 已经不存在(被删、换了环境):从列表里拿掉。宿主给的 jobIds 不动,由宿主决定。
@@ -372,6 +469,38 @@ export function createCliStore(options: CliStoreOptions = {}) {
372
469
  if (refreshAgain.delete(jobId)) void refreshJob(jobId, true);
373
470
  }
374
471
 
472
+ /** 只要拿到详情就行(打开对话、列表补拉):已经在拉的不再排一次「拉完再补」。 */
473
+ function loadJob(jobId: string, force = false) {
474
+ if (state.jobs[jobId]?.loading) return Promise.resolve();
475
+ return refreshJob(jobId, force);
476
+ }
477
+
478
+ // 列表的后台拉取(首次加载、刷新、补拉新加进来的)共用一个并发上限 LIST_CONCURRENCY;
479
+ // 同一个任务排着或正在拉时不再排第二次。打开对话、发消息这类用户在等的不走这里。
480
+ const listQueue = new Map<string, Promise<void>>();
481
+ let listActive = 0;
482
+ const listWaiting: Array<() => void> = [];
483
+ function queueListJob(jobId: string, force: boolean): Promise<void> {
484
+ const queued = listQueue.get(jobId);
485
+ if (queued) return queued;
486
+ const seen = fetches.get(jobId) ?? 0;
487
+ const run = (async () => {
488
+ if (listActive >= LIST_CONCURRENCY) await new Promise<void>((resolve) => listWaiting.push(resolve));
489
+ listActive += 1;
490
+ try {
491
+ // 排队期间别处已经开始拉了(打开了这个对话、轮次变化):不再重复。
492
+ if ((fetches.get(jobId) ?? 0) !== seen) return;
493
+ await loadJob(jobId, force);
494
+ } finally {
495
+ listActive -= 1;
496
+ listWaiting.shift()?.();
497
+ }
498
+ })();
499
+ listQueue.set(jobId, run);
500
+ void run.finally(() => { if (listQueue.get(jobId) === run) listQueue.delete(jobId); });
501
+ return run;
502
+ }
503
+
375
504
  /**
376
505
  * 刷新列表。缺省只刷还没结束的对话(结束了的不会再变,轮询不必每次都拉);all = true 全部重拉(首次加载、手动刷新)。
377
506
  */
@@ -382,16 +511,33 @@ export function createCliStore(options: CliStoreOptions = {}) {
382
511
  const status = state.jobs[id]?.job?.status;
383
512
  return !status || !TERMINAL_JOB.has(status);
384
513
  });
385
- await runLimited(ids, LIST_CONCURRENCY, (id) => refreshJob(id, true));
514
+ await Promise.all(ids.map((id) => queueListJob(id, true)));
386
515
  set({ listLoading: false });
387
516
  } catch (error) {
388
517
  set({ listLoading: false, listError: error instanceof Error ? error.message : String(error) });
389
518
  }
390
519
  }
391
520
 
521
+ /** 列表里还没有数据的对话任务(宿主新给的、别的组件新建的):排进列表的后台拉取(列表组件用)。 */
522
+ function loadMissingJobs() {
523
+ for (const id of state.jobIds) if (!state.jobs[id]) void queueListJob(id, false);
524
+ }
525
+
392
526
  // ── 实时流(引用计数 + 断线重连) ─────────────────────
393
527
 
394
- const streams = new Map<string, { refs: number; stop: (() => void) | null; timer: ReturnType<typeof setTimeout> | null; attempt: number; parked?: boolean }>();
528
+ // synced:这个流已经收到过快照;之后的快照是断线重连后的补齐。
529
+ type StreamEntry = {
530
+ refs: number; stop: (() => void) | null; timer: ReturnType<typeof setTimeout> | null; attempt: number; parked?: boolean; synced?: boolean;
531
+ /** 这次断线从什么时候开始(还没恢复);恢复 = 新连接收到快照或数据。 */
532
+ droppedAt?: number;
533
+ /** 到 RECONNECT_NOTICE_MS 还没恢复时把状态改成 reconnecting 的定时器。 */
534
+ notice?: ReturnType<typeof setTimeout> | null;
535
+ lastError?: string | null;
536
+ };
537
+ const streams = new Map<string, StreamEntry>();
538
+ const clearNotice = (entry: StreamEntry) => { if (entry.notice) { clearTimeout(entry.notice); entry.notice = null; } };
539
+ /** 不再算「断线中」:恢复了,或者转成了别的明确状态(停下、结束、出错、页面停放)。 */
540
+ const settleDrop = (entry: StreamEntry) => { clearNotice(entry); entry.droppedAt = undefined; entry.lastError = null; };
395
541
 
396
542
  function connect(key: string) {
397
543
  const entry = streams.get(key);
@@ -402,6 +548,9 @@ export function createCliStore(options: CliStoreOptions = {}) {
402
548
  if (streams.get(key) !== entry || entry.refs <= 0) return;
403
549
  const { jobId, taskId } = parseConvKey(key);
404
550
  let ended = false, retired = false, snapshotReceived = false;
551
+ // 这条连接上节点回合结束时查过文件、当时的工具执行次数(ConvState.edits);中枢随后把这一轮标成结束时据此去重。
552
+ let roundEndEdits: number | null = null;
553
+ let endReason: string | null = null;
405
554
  let cleanup: (() => void) | null = null;
406
555
  const owns = () => streams.get(key) === entry && entry.refs > 0 && entry.stop === retire;
407
556
  const active = () => !retired && owns();
@@ -413,68 +562,126 @@ export function createCliStore(options: CliStoreOptions = {}) {
413
562
  const dispose = cleanup; cleanup = null;
414
563
  notifyCallback(dispose ?? undefined, undefined);
415
564
  };
565
+ // 新连接真正送来了数据:断线算恢复,退避次数重新计。只连上响应头就又断的不算,
566
+ // 否则「连上即断」会把重试次数一直清零、变成无限重连。
567
+ const recovered = () => { entry.attempt = 0; settleDrop(entry); };
568
+ // 断线:先悄悄重连;到 RECONNECT_NOTICE_MS 还没恢复才显示「正在重连」(见 RECONNECT_NOTICE_MS)。
569
+ const noteDrop = (current: StreamEntry, error: CenterError | null) => {
570
+ current.lastError = error?.message ?? null;
571
+ current.droppedAt ??= Date.now();
572
+ const show = () => patchConv(key, (conv) => ({ ...conv, stream: "reconnecting", streamError: current.lastError ?? null }));
573
+ const waited = Date.now() - current.droppedAt;
574
+ if (waited >= RECONNECT_NOTICE_MS) { clearNotice(current); show(); return; }
575
+ if (current.notice) return;
576
+ current.notice = setTimeout(() => {
577
+ current.notice = null;
578
+ if (streams.get(key) !== current || current.refs <= 0 || current.parked || current.droppedAt === undefined) return;
579
+ show();
580
+ }, RECONNECT_NOTICE_MS - waited);
581
+ };
582
+ // 重试用完:停下等事件(见 RECONNECT_MS),对话照常可以看、可以发消息。
583
+ const goOffline = (current: NonNullable<ReturnType<typeof streams.get>>, error: CenterError | null) => {
584
+ settleDrop(current);
585
+ current.parked = true;
586
+ patchConv(key, (conv) => ({ ...conv, stream: "offline", streamError: error?.message ?? null }));
587
+ emit({ type: "error", jobId: key, error: error ?? new CenterError("实时连接已中断", "NETWORK", 0) });
588
+ };
416
589
  const close = (error: CenterError | null) => {
417
590
  if (!active()) return;
418
591
  retire();
419
592
  const current = streams.get(key);
420
593
  if (current !== entry || current.refs <= 0 || current.stop) return;
421
- // 对话结束(end)不再连;中枢停机(server_shutdown)稍后重连。
422
- if (ended && state.convs[key]?.endReason !== "server_shutdown") return;
594
+ // 对话结束(end)不再连;中枢停机(server_shutdown)按断线处理,稍后重连。
595
+ if (ended && endReason !== "server_shutdown") return;
423
596
  // 404:对话不存在,重连也没用。
424
597
  if (error && error.status === 404) {
598
+ settleDrop(current);
425
599
  patchConv(key, (conv) => ({ ...conv, stream: "error", streamError: error.message }));
426
600
  emit({ type: "error", jobId: key, error });
427
601
  return;
428
602
  }
429
- // 401 / 403:多半是宿主的登录会话过期。报出来(宿主可以据此续会话),之后每 30 秒再试,会话续上了自己恢复。
603
+ // 401 / 403:多半是宿主的登录会话过期。报出来(宿主可以据此续会话),之后隔 30 秒再试几次,会话续上了自己恢复。
430
604
  if (error && (error.status === 401 || error.status === 403)) {
431
- patchConv(key, (conv) => ({ ...conv, stream: "error", streamError: error.message }));
605
+ settleDrop(current);
432
606
  if (current.attempt === 0) emit({ type: "error", jobId: key, error });
607
+ if (current.attempt >= AUTH_RETRIES) { goOffline(current, error); return; }
608
+ patchConv(key, (conv) => ({ ...conv, stream: "error", streamError: error.message }));
433
609
  current.attempt += 1;
434
610
  current.timer = setTimeout(() => { current.timer = null; connect(key); }, jitter(AUTH_RETRY_MS));
435
611
  return;
436
612
  }
437
- const delay = RECONNECT_MS[Math.min(current.attempt, RECONNECT_MS.length - 1)];
613
+ if (current.attempt >= RECONNECT_MS.length) { goOffline(current, error); return; }
614
+ const delay = RECONNECT_MS[current.attempt];
438
615
  current.attempt += 1;
439
- patchConv(key, (conv) => ({ ...conv, stream: "reconnecting", streamError: error?.message ?? null }));
616
+ noteDrop(current, error);
440
617
  current.timer = setTimeout(() => { current.timer = null; connect(key); }, jitter(delay));
441
618
  };
442
619
  entry.stop = retire;
443
- patchConv(key, (conv) => ({ ...conv, stream: entry.attempt ? "reconnecting" : "connecting", streamError: null }));
620
+ // 断线后的重连尝试不改状态(悄悄进行,或已经在显示「正在重连」);只有首次连接显示 connecting。
621
+ if (entry.droppedAt === undefined) patchConv(key, (conv) => ({ ...conv, stream: "connecting", streamError: null }));
444
622
  if (!active()) return;
445
623
  try {
446
624
  cleanup = client.stream(jobId, {
447
- onOpen: () => { if (!active()) return; entry.attempt = 0; patchConv(key, (conv) => ({ ...conv, stream: "live", streamError: null })); },
625
+ onOpen: () => { if (!active()) return; clearNotice(entry); patchConv(key, (conv) => ({ ...conv, stream: "live", streamError: null })); },
448
626
  onSnapshot: (snapshot) => {
449
627
  if (!active()) return;
450
- patchConv(key, (conv) => applySnapshot(conv, snapshot));
628
+ // 重连后的快照:断线期间可能有轮次结束,算一次收尾(首次连上不算,看板挂上时自己会读)。
629
+ const catchUp = !snapshotReceived && !!entry.synced;
630
+ const initial = !entry.synced;
631
+ entry.synced = true;
632
+ recovered();
633
+ // Only the first snapshot's unobserved terminal turns are history.
634
+ // New terminal turns in later events/snapshots still need one result.
635
+ if (initial && !isBatchSnapshot(snapshot)) for (const turn of Array.isArray(snapshot.turns) ? snapshot.turns : []) {
636
+ if (TERMINAL_TURN.has(turn.status) && !watchedTurns.has(turn.turn_id)) settledTurns.add(turn.turn_id);
637
+ }
638
+ patchConv(key, (conv) => { const next = applySnapshot(conv, snapshot); return catchUp ? { ...next, settled: next.settled + 1 } : next; });
639
+ // 一次性任务:快照里的子任务(重连后补上断线期间结束的)。
640
+ if (isBatchSnapshot(snapshot)) for (const task of [...(Array.isArray(snapshot.tasks) ? snapshot.tasks : []), ...(snapshot.task ? [snapshot.task] : [])]) noticeBatchTask(key, jobId, task, initial);
451
641
  // Each connection catches up once, including rounds completed while disconnected.
452
642
  if (!snapshotReceived) { snapshotReceived = true; refreshFiles(); }
453
643
  },
454
644
  onChunk: (items) => {
455
645
  if (!active()) return;
646
+ recovered();
456
647
  let refresh = false;
457
648
  patchConv(key, (conv) => {
458
649
  let next = conv;
650
+ let settled = false;
459
651
  for (const item of items) {
460
652
  const previous = next;
461
653
  next = applyItems(next, [item]);
462
654
  // applyItems also rejects events from another batch task's node session.
463
655
  if (next === previous) continue;
464
656
  // Observe every event: end + next user in one chunk can leave running=true.
465
- if (item.type === "node" && item.event.type === "turn_end" || item.type === "transcript") refresh = true;
657
+ if (item.type === "transcript") { refresh = true; roundEndEdits = null; }
658
+ // 节点上一个回合结束就查文件(中枢的这一轮可能还没结束:节点接着跑下一回合)。
659
+ if (item.type === "node" && item.event.type === "turn_end") { refresh = true; roundEndEdits = next.edits; }
660
+ // 有轮次的对话以中枢把这一轮标成结束为准(节点已停、轮末保存已做);没有轮次的看节点 turn_end。
661
+ if (item.type === "node" && item.event.type === "turn_end" && !next.turns.length) settled = true;
466
662
  if (item.type === "turn" && item.turn.status !== "merged" && TERMINAL_TURN.has(item.turn.status)
467
- && !TERMINAL_TURN.has(previous.turns.find((turn) => turn.turn_id === item.turn.turn_id)?.status ?? "")) refresh = true;
663
+ && !TERMINAL_TURN.has(previous.turns.find((turn) => turn.turn_id === item.turn.turn_id)?.status ?? "")) {
664
+ settled = true;
665
+ // 节点回合结束时已经查过、之后再没有工具执行完:文件不会变,不再查第二次。
666
+ if (roundEndEdits !== next.edits) refresh = true;
667
+ roundEndEdits = null;
668
+ }
468
669
  }
469
- return next;
670
+ return settled ? { ...next, settled: next.settled + 1 } : next;
470
671
  });
471
672
  if (refresh) refreshFiles();
673
+ // 一次性任务里子任务的状态变化:包括已经不在看的那些(跟着最新的子任务时,旧的结束也要报)。
674
+ if (state.convs[key]?.batch) for (const item of items as StreamItem[]) if (item.type === "task") noticeBatchTask(key, jobId, item.task as BatchStreamTask);
472
675
  },
473
676
  onEnd: (end) => {
474
677
  if (!active() || ended) return;
475
678
  ended = true;
679
+ endReason = end.reason;
680
+ // 中枢停机:连接随后会断,按断线悄悄重连,不显示成「已结束」。
681
+ if (end.reason === "server_shutdown") return;
682
+ settleDrop(entry);
476
683
  const continuedBy = taskId ? (end.continued_by_job_id && end.continued_by_task_id ? convKey(end.continued_by_job_id, end.continued_by_task_id) : null) : end.continued_by_job_id ?? null;
477
- patchConv(key, (conv) => ({ ...conv, stream: "ended", endReason: end.reason, continuedBy, nodeRunning: false }));
684
+ patchConv(key, (conv) => ({ ...conv, stream: "ended", endReason: end.reason, continuedBy, nodeRunning: false, settled: conv.settled + 1 }));
478
685
  refreshFiles();
479
686
  void refreshJob(jobId, true);
480
687
  },
@@ -494,7 +701,7 @@ export function createCliStore(options: CliStoreOptions = {}) {
494
701
  // 只在有实时流时登记到全局(见 watchReconnect):组件卸载、流都关了就撤掉,宿主单页应用里反复挂载组件不会越积越多。
495
702
  function reconnectNow() {
496
703
  for (const [jobId, entry] of streams) {
497
- if (entry.parked && entry.refs > 0) { entry.parked = false; entry.attempt = 0; connect(jobId); continue; }
704
+ if (entry.parked && entry.refs > 0) { entry.parked = false; entry.attempt = 0; settleDrop(entry); connect(jobId); continue; }
498
705
  if (!entry.timer) continue;
499
706
  clearTimeout(entry.timer);
500
707
  entry.timer = null;
@@ -502,12 +709,28 @@ export function createCliStore(options: CliStoreOptions = {}) {
502
709
  connect(jobId);
503
710
  }
504
711
  }
712
+ /** 手动重连:给了对话键只连这一个,否则所有停下的 / 正在退避等待的都立刻再连(重试次数重新计)。 */
713
+ /**
714
+ * 立刻重连。缺省只接上停下的(offline、页面停放)或正在等重连的;force:连着的也断开重连一次,
715
+ * 让中枢重新补发快照(例如会话记录一直没读到时的「重新读取」)。
716
+ */
717
+ function reconnect(key?: string, options: { force?: boolean } = {}) {
718
+ if (!key) { reconnectNow(); return; }
719
+ const entry = streams.get(key);
720
+ if (!entry || entry.refs <= 0 || (!options.force && !entry.parked && !entry.timer)) return;
721
+ if (entry.timer) { clearTimeout(entry.timer); entry.timer = null; }
722
+ entry.parked = false; entry.attempt = 0;
723
+ if (options.force) { settleDrop(entry); patchConv(key, (conv) => ({ ...conv, transcriptError: null })); }
724
+ // connect 会先关掉还连着的那条(包括已经收到 end 的)。
725
+ connect(key);
726
+ }
505
727
  // 页面在后台太久:停掉实时流(主动停止不算断线,不会触发重连),切回来由 reconnectNow 接上。
506
728
  function parkAll() {
507
729
  for (const entry of streams.values()) {
508
730
  // 只停连着的和正在等重连的;对话已结束、不再连的不动。
509
731
  if (entry.refs <= 0 || (!entry.stop && !entry.timer)) continue;
510
732
  if (entry.timer) { clearTimeout(entry.timer); entry.timer = null; }
733
+ settleDrop(entry);
511
734
  entry.stop?.();
512
735
  entry.stop = null;
513
736
  entry.parked = true;
@@ -522,7 +745,7 @@ export function createCliStore(options: CliStoreOptions = {}) {
522
745
  function open(key: string): () => void {
523
746
  const { jobId, taskId } = parseConvKey(key);
524
747
  if (taskId === NEW_TASK) {
525
- void refreshJob(jobId);
748
+ void loadJob(jobId);
526
749
  return () => undefined;
527
750
  }
528
751
  let entry = streams.get(key);
@@ -533,7 +756,9 @@ export function createCliStore(options: CliStoreOptions = {}) {
533
756
  }
534
757
  entry.refs += 1;
535
758
  if (entry.refs === 1) {
536
- void refreshJob(jobId);
759
+ markActive(key);
760
+ // 列表正在拉这个任务(页面刚打开时常见):用它的结果,不再排一次「拉完再补」。
761
+ void loadJob(jobId);
537
762
  connect(key);
538
763
  }
539
764
  const owned = entry;
@@ -549,12 +774,38 @@ export function createCliStore(options: CliStoreOptions = {}) {
549
774
  // acquire a new lease for the same task.
550
775
  streams.delete(key);
551
776
  if (current.timer) { clearTimeout(current.timer); current.timer = null; }
777
+ settleDrop(current);
552
778
  syncLive();
553
779
  current.stop?.();
554
- if (!streams.has(key)) patchConv(key, (conv) => ({ ...conv, stream: conv.stream === "ended" ? "ended" : "idle" }));
780
+ if (!streams.has(key)) {
781
+ patchConv(key, (conv) => ({ ...conv, stream: conv.stream === "ended" ? "ended" : "idle" }));
782
+ markIdle(key);
783
+ }
555
784
  };
556
785
  }
557
786
 
787
+ // 没人看的对话按最近不看的先后排着(最早不看的在前),超过 IDLE_CONV_MAX 个就释放最早的那些的记录。
788
+ const idleConvs: string[] = [];
789
+ function markIdle(key: string) {
790
+ markActive(key);
791
+ idleConvs.push(key);
792
+ // 离开的对话截回快照大小:往上翻过很远的对话在后台不留几千条消息。
793
+ patchConv(key, (conv) => {
794
+ const trimmed = trimToTail(conv.msgs, conv.older);
795
+ return trimmed.msgs === conv.msgs ? conv : { ...conv, msgs: trimmed.msgs, older: trimmed.older };
796
+ });
797
+ if (idleConvs.length <= IDLE_CONV_MAX) return;
798
+ const drop = idleConvs.splice(0, idleConvs.length - IDLE_CONV_MAX).filter((k) => !streams.has(k) && state.convs[k]);
799
+ if (!drop.length) return;
800
+ const convs = { ...state.convs };
801
+ for (const k of drop) delete convs[k];
802
+ set({ convs });
803
+ }
804
+ function markActive(key: string) {
805
+ const at = idleConvs.indexOf(key);
806
+ if (at >= 0) idleConvs.splice(at, 1);
807
+ }
808
+
558
809
  // ── 发消息 / 新建 / 撤回 / 结束 ───────────────────────
559
810
 
560
811
  /**
@@ -591,6 +842,8 @@ export function createCliStore(options: CliStoreOptions = {}) {
591
842
  try {
592
843
  const target = await sendWithText(key, text, overrides);
593
844
  if (ctx.length) emit({ type: "context", key: target, pending: state.context[ck] ?? [], sent: ctx });
845
+ // 实时流因重试用完停下了:消息已发出,马上再连,回复才能实时显示。
846
+ reconnect(target);
594
847
  return target;
595
848
  } catch (error) {
596
849
  if (ctx.length) {
@@ -682,7 +935,7 @@ export function createCliStore(options: CliStoreOptions = {}) {
682
935
  * 卡片先在本地标成已答(Operator 同样是先乐观更新)。
683
936
  */
684
937
  /** fallback = false:只交给正在等的回合,不改发消息(一次性任务不能发消息);没有在等的回合时报错。 */
685
- async function answerAsk(key: string, askId: string, questions: AskQuestion[], answers: AskAnswers, overrides: SendOptions & { fallback?: boolean } = {}): Promise<string> {
938
+ async function answerAsk(key: string, askId: string, questions: AskQuestion[], answers: AskAnswers, overrides: SendOptions & { fallback?: boolean; fallbackSend?: (text: string) => Promise<string> } = {}): Promise<string> {
686
939
  // 与 Operator 的 answerQuestion 同一流程:先乐观标成已答 → 交给正在等的回合 → 没有在等的回合就当普通回复发出。
687
940
  patchConv(key, (conv) => ({ ...conv, localAnswers: { ...conv.localAnswers, [askId]: answers } }));
688
941
  try {
@@ -691,7 +944,8 @@ export function createCliStore(options: CliStoreOptions = {}) {
691
944
  if (resolved) return key;
692
945
  }
693
946
  if (overrides.fallback === false) throw new CenterError("这个提问已经没有在等回答了(回合已经结束)", "ASK_EXPIRED", 0);
694
- return await send(key, formatAnswersText(questions, answers), overrides);
947
+ const formatted = formatAnswersText(questions, answers);
948
+ return await (overrides.fallbackSend ? overrides.fallbackSend(formatted) : send(key, formatted, overrides));
695
949
  } catch (error) {
696
950
  // 没发出去:卡片恢复成可回答。
697
951
  patchConv(key, (conv) => {
@@ -741,7 +995,8 @@ export function createCliStore(options: CliStoreOptions = {}) {
741
995
  * 同一个对话同一时刻只取一页。返回取到没有。
742
996
  */
743
997
  const loadingOlder = new Set<string>();
744
- async function loadOlder(key: string): Promise<boolean> {
998
+ /** beforeApply:这一页接上去之前调用(界面趁这时量下第一行的位置,接上后视图不跳)。 */
999
+ async function loadOlder(key: string, opts: { beforeApply?: () => void } = {}): Promise<boolean> {
745
1000
  const conv = state.convs[key];
746
1001
  // 节点会话:一次性任务是正在看的那个对话,对话任务是流里这个对话的远端任务。
747
1002
  const remote = conv ? conv.remoteTaskId ?? conv.task?.remote_task_id ?? null : null;
@@ -751,6 +1006,9 @@ export function createCliStore(options: CliStoreOptions = {}) {
751
1006
  try {
752
1007
  const page = await client.history(key, remote, first.id, 200);
753
1008
  // 取的过程中换了节点会话(重建、续派切过去):这一页作废。
1009
+ const current = state.convs[key];
1010
+ if (!current || (current.remoteTaskId ?? current.task?.remote_task_id ?? null) !== remote || current.msgs[0]?.id !== first.id) return false;
1011
+ notifyCallback(opts.beforeApply, undefined);
754
1012
  patchConv(key, (c) => ((c.remoteTaskId ?? c.task?.remote_task_id ?? null) === remote && c.msgs[0]?.id === first.id ? applyOlderPage(c, page.messages ?? [], page.older) : c));
755
1013
  return true;
756
1014
  } catch (error) {
@@ -762,7 +1020,9 @@ export function createCliStore(options: CliStoreOptions = {}) {
762
1020
  }
763
1021
 
764
1022
  // 同一个仓库里登记的看板(cli-board)。后登记的优先(例如弹出的看板盖在常驻的上面)。
765
- const surfaces: { surface: BoardSurface; owner?: string; inline?: boolean; priority?: () => number }[] = [];
1023
+ // 「在看板里打开」的接收方和各看板报告的样子:规则与节点适配共用(board/linkage)。
1024
+ const surfaces = createBoardSurfaces<{ jobId: string; target: OpenTarget }>();
1025
+ const boardOwners = createBoardOwners();
766
1026
  const visibleLists = new Set<string>();
767
1027
  function reportListPresence(owner: string, visible: boolean) {
768
1028
  if (visible) visibleLists.add(owner); else visibleLists.delete(owner);
@@ -827,7 +1087,6 @@ export function createCliStore(options: CliStoreOptions = {}) {
827
1087
  */
828
1088
  // 每个看板各自报告(按 owner 记),生效的是最近报告、还开着的那个;一个看板撤掉只撤它自己的。
829
1089
  const viewSources = new Map<string, Map<string, BoardRef>>();
830
- const boardSources = new Map<string, Map<string, BoardView>>();
831
1090
  /** 记下 owner 的报告,返回现在生效的那个(最近报告的)。 */
832
1091
  function latestReport<T>(sources: Map<string, Map<string, T>>, key: string, owner: string, value: T | null): T | null {
833
1092
  const m = sources.get(key) ?? new Map<string, T>();
@@ -860,16 +1119,13 @@ export function createCliStore(options: CliStoreOptions = {}) {
860
1119
  if(contextChanged&&state.boardContext[key]===retained)emit({type:"board_context",jobId:key,view:cloneBoardView(retained!)});
861
1120
  }
862
1121
  function reportBoard(key:string,view:BoardView|null,owner="default") {
863
- const sources=boardSources.get(key)??new Map<string,BoardView>();
1122
+ if(view)view=withBoardPaths(view,key);
864
1123
  let history=state.boardContext[key]?.history??[];
865
- if(view){history=mergeBoardHistory(history,sources.get(owner),view);reportBoardOwner(sources,owner,cloneBoardView(view));}
866
- else sources.delete(owner);
867
- if(sources.size)boardSources.set(key,sources);else boardSources.delete(key);
868
- const top=selectedBoardOwner(sources)?.[1]??null;applyBoardSelection(key,top,history);
1124
+ if(view)history=mergeBoardHistory(history,boardOwners.previous(key,owner),view);
1125
+ const top=boardOwners.report(key,owner,view?cloneBoardView(view):null);applyBoardSelection(key,top,history);
869
1126
  }
870
1127
  function activateBoard(key:string,owner:string) {
871
- const sources=boardSources.get(key);if(!sources)return;
872
- const top=activateBoardOwner(sources,owner)?.[1];if(!top)return;
1128
+ const top=boardOwners.activate(key,owner);if(!top)return;
873
1129
  const file=top.current??(top.file?{path:top.file,sourceId:key}:null);
874
1130
  const history=file?rememberBoardFile(state.boardContext[key]?.history??[],file):state.boardContext[key]?.history??[];
875
1131
  applyBoardSelection(key,top,history);
@@ -877,13 +1133,15 @@ export function createCliStore(options: CliStoreOptions = {}) {
877
1133
  const fileSubscriptions = new Map<string,{listeners:Set<{change?:(event:WorkspaceChangeEvent)=>void;status?:WorkspaceWatchOptions['onStatus']}>;stop:()=>void;status?:WorkspaceWatchStatus}>();
878
1134
  function watchWorkspace(key:string,listener?:(event:WorkspaceChangeEvent)=>void,options:WorkspaceWatchOptions={}) {
879
1135
  if(!client.board) throw new Error("当前后端不支持工作区文件订阅");
880
- const releaseScope=options.paths?.length||options.dirs?.length?retainFileScope(client.board,key,{paths:[...options.paths??[]],dirs:[...options.dirs??[]]}):()=>{};
1136
+ const releaseScope=options.paths?.length||options.dirs?.length?retainFileScope(client.board,key,{paths:[...options.paths??[]],dirs:[...options.dirs??[]],...(options.dirEntries?{entries:[...options.dirs??[]]}:{})}):()=>{};
881
1137
  const item={change:listener,status:options.onStatus};let subscription=fileSubscriptions.get(key);
882
1138
  if(!subscription){
883
1139
  subscription={listeners:new Set([item]),stop:()=>{}};fileSubscriptions.set(key,subscription);const owned=subscription;
884
1140
  owned.stop=subscribeWorkspaceFiles(client.board,key,event=>{emit(event);for(const next of [...owned.listeners])notifyCallback(next.change,cloneWorkspaceChange(event));},{intervalMs:options.intervalMs,onStatus:status=>{owned.status=status;emit(status);for(const next of [...owned.listeners])notifyCallback(next.status,{...status});}});
885
1141
  }else{subscription.listeners.add(item);if(subscription.status)notifyCallback(item.status,{...subscription.status});retryWorkspaceFiles(client.board,key);}
886
- const owned=subscription;let active=true;return()=>{if(!active)return;active=false;owned.listeners.delete(item);if(!owned.listeners.size){if(fileSubscriptions.get(key)===owned)fileSubscriptions.delete(key);owned.stop();}releaseScope();};
1142
+ // 订阅文件变化时跟着这个对话的实时流(和对话、看板共用一条):每轮结束才会去查文件。只订阅不显示对话的业务方也能及时收到。
1143
+ const releaseStream=parseConvKey(key).taskId===NEW_TASK?()=>{}:open(key);
1144
+ const owned=subscription;let active=true;return()=>{if(!active)return;active=false;owned.listeners.delete(item);if(!owned.listeners.size){if(fileSubscriptions.get(key)===owned)fileSubscriptions.delete(key);owned.stop();}releaseScope();releaseStream();};
887
1145
  }
888
1146
 
889
1147
  // ── 补充背景:业务方随时追加,随下一条消息发给智能体 ────────
@@ -948,14 +1206,7 @@ export function createCliStore(options: CliStoreOptions = {}) {
948
1206
  }
949
1207
 
950
1208
  function openInBoard(jobId: string, target: OpenTarget, preferredInlineOwner?: string): boolean {
951
- let handled = false;
952
- const available = [...surfaces].reverse().filter(item => !preferredInlineOwner || !item.inline || item.owner === preferredInlineOwner)
953
- .sort((a, b) => (b.priority?.() ?? 2) - (a.priority?.() ?? 2));
954
- for (const { surface } of available) {
955
- try { handled = surface(jobId, { ...target }); }
956
- catch (error) { console.error("[@spzxg/cli-ui] board surface callback failed", error); }
957
- if (handled) break;
958
- }
1209
+ const handled = surfaces.open({ jobId, target }, (item) => !preferredInlineOwner || !item.inline || item.owner === preferredInlineOwner);
959
1210
  emit({ type: "open", jobId, target, handled });
960
1211
  return handled;
961
1212
  }
@@ -969,9 +1220,8 @@ export function createCliStore(options: CliStoreOptions = {}) {
969
1220
  openInBoard,
970
1221
  /** 看板登记自己;返回注销函数。 */
971
1222
  registerBoard(surface: BoardSurface, options: { owner?: string; inline?: boolean; priority?: () => number } = {}) {
972
- const entry = { surface, ...options };
973
- surfaces.push(entry);
974
- return () => { const i = surfaces.indexOf(entry); if (i >= 0) surfaces.splice(i, 1); };
1223
+ // 每个接收方拿到自己的一份 target,改了也不影响下一个。
1224
+ return surfaces.register(({ jobId, target }) => surface(jobId, { ...target }), options);
975
1225
  },
976
1226
  subscribe(fn: () => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
977
1227
  on(fn: (event: CliEvent) => void) { eventListeners.add(fn); return () => { eventListeners.delete(fn); }; },
@@ -981,6 +1231,8 @@ export function createCliStore(options: CliStoreOptions = {}) {
981
1231
  emit({ type: "select", jobId });
982
1232
  },
983
1233
  setJobIds, addJob, removeJob, replaceJob, refreshJob, refreshAll,
1234
+ /** 列表组件用:补拉列表里还没有数据的对话任务。 */
1235
+ loadMissingJobs,
984
1236
  addRef, removeRef, takeRefs, restoreRefs,
985
1237
  setViewing, dismissViewing, takeViewing, restoreViewing,
986
1238
  /** 看板报告自己的样子(看板组件用)。 */
@@ -989,21 +1241,13 @@ export function createCliStore(options: CliStoreOptions = {}) {
989
1241
  appendContext, removeContext, pendingContext,
990
1242
  /** 工作区文件接口(不显示看板也能用):列文件、读文件、下载、打包。不传 = 当前选中的对话。 */
991
1243
  workspace, watchWorkspace,
992
- open, send, answerAsk, cancelTurn, close, loadOlder,
1244
+ open, send, answerAsk, cancelTurn, close, loadOlder, reconnect,
993
1245
  };
994
1246
  }
995
1247
 
996
1248
  export type CliStore = ReturnType<typeof createCliStore>;
997
1249
 
998
1250
 
999
- async function runLimited<T>(items: T[], limit: number, fn: (item: T) => Promise<unknown>) {
1000
- let index = 0;
1001
- const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
1002
- while (index < items.length) await fn(items[index++]);
1003
- });
1004
- await Promise.all(workers);
1005
- }
1006
-
1007
1251
  const REF_MAX = 20;
1008
1252
  const REF_TEXT_MAX = 4_000;
1009
1253