@spzxg/cli-ui 0.4.0 → 0.6.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.
@@ -16,7 +16,26 @@ export interface TextBlock {
16
16
  /** 显示名:文件名,粘贴的文字为「粘贴的文本」。 */
17
17
  name: string;
18
18
  text: string;
19
- kind: "file" | "paste";
19
+ kind: "file" | "paste" | "context" | "background";
20
+ }
21
+
22
+ /** 看板引用合成的块的名字(转录里按它认出来,显示成「看板上下文」卡片)。 */
23
+ export const BOARD_CONTEXT_NAME = "看板上下文";
24
+
25
+ /** 看板引用 → 发给智能体的块。 */
26
+ export function boardContextBlock(lines: string[]): TextBlock {
27
+ return { name: BOARD_CONTEXT_NAME, kind: "context", text: ["用户在右侧看板里引用了下面这些,供这条消息参考:", ...lines.map((l) => `- ${l}`)].join("\n") };
28
+ }
29
+
30
+ /** 补充背景合成的块的名字(转录里显示成「补充背景」卡片)。 */
31
+ export const BACKGROUND_NAME = "补充背景";
32
+
33
+ /** 补充背景(store.appendContext)→ 发给智能体的块。每条有标题时写成「【标题】」。 */
34
+ export function backgroundBlock(items: Array<{ title?: string; text: string }>): TextBlock {
35
+ // 内容里碰巧有附件分隔行时错开一个空格,免得把块提前截断。
36
+ const safe = (t: string) => t.replace(/^(----- 附件)/gm, " $1");
37
+ const body = items.map((i) => (i.title ? `【${i.title}】\n${safe(i.text)}` : safe(i.text))).join("\n\n");
38
+ return { name: BACKGROUND_NAME, kind: "background", text: `以下是补充的项目背景信息,请在这次及之后的工作中一并参考:\n\n${body}` };
20
39
  }
21
40
 
22
41
  /** 支持的文件:只有 TXT、Markdown、Word(.docx)。 */
@@ -63,7 +82,7 @@ export function splitMessage(content: string): MessagePart[] {
63
82
  if (!open || end === -1) { text.push(lines[i]); continue; }
64
83
  flush();
65
84
  const name = open[1];
66
- parts.push({ kind: "block", block: { name, text: lines.slice(i + 1, end).join("\n"), kind: name === PASTE_NAME ? "paste" : "file" } });
85
+ parts.push({ kind: "block", block: { name, text: lines.slice(i + 1, end).join("\n"), kind: name === PASTE_NAME ? "paste" : name === BOARD_CONTEXT_NAME ? "context" : name === BACKGROUND_NAME ? "background" : "file" } });
67
86
  i = end;
68
87
  }
69
88
  flush();
@@ -1,9 +1,10 @@
1
1
  import { createSseParser } from "./sse.js";
2
2
  import { NEW_TASK, parseConvKey } from "./conversation.js";
3
3
  import type {
4
- BoardInfo, BrowserMessage, BrowserStatus, CenterJob, CenterTask, CenterTurn, DiffResult, DirListing, FileInfo,
5
- BatchStreamSnapshot, NewConversationOptions, SendResult, StreamEnd, StreamItem, StreamSnapshot,
4
+ BoardInfo, BrowserMessage, BrowserStatus, CenterJob, CenterTask, CenterTurn, DiffResult, DirListing, FileInfo, Message,
5
+ BatchStreamSnapshot, BrowserFramesState, NewConversationOptions, SendResult, StreamEnd, StreamItem, StreamSnapshot,
6
6
  } from "./types.js";
7
+ import { decodeText } from "./textDecode.js";
7
8
 
8
9
  /**
9
10
  * center 服务(cli-task-center)对话任务接口的浏览器端客户端。组件的数据全部从这里来。
@@ -33,10 +34,19 @@ export interface CenterClientOptions {
33
34
  * (同源代理注入令牌);否则浏览器直接请求带不上请求头,看板改为先 fetch 再用 blob 地址显示。
34
35
  */
35
36
  directFileLinks?: boolean;
37
+ /**
38
+ * 普通请求(不含实时流、文件下载)多久没有响应就放弃,缺省 30 秒。代理或网络挂住时组件不会一直「读取中」,
39
+ * 而是报「请求超时」并按各自的规则重试。打开任务浏览器另给 150 秒(节点要先启动浏览器)。
40
+ */
41
+ requestTimeoutMs?: number;
36
42
  }
37
43
 
38
44
  /** 实时流超过这么久没有任何数据(center 每 20 秒一次心跳)就当连接已断。 */
39
45
  export const STREAM_SILENCE_MS = 45_000;
46
+ /** 读文件:这么久没回响应头(节点卡住、代理挂住)就放弃。 */
47
+ export const FILE_HEADER_TIMEOUT_MS = 30_000;
48
+ /** 读文件:传输中这么久一个字节都没收到就当断了(大文件慢慢传不算,只要还在动)。 */
49
+ export const FILE_STALL_MS = 60_000;
40
50
 
41
51
  export class CenterError extends Error {
42
52
  constructor(message: string, readonly code: string, readonly status: number, readonly detail?: unknown) {
@@ -63,6 +73,8 @@ const ERROR_TEXT: Record<string, string> = {
63
73
  too_many_viewers: "同时观看这个浏览器的人太多,请稍后再试",
64
74
  viewer_not_found: "画面连接已断开,正在重连",
65
75
  viewer_not_ready: "画面连接还没就绪,正在重连",
76
+ link_expired: "文件链接已失效,请刷新",
77
+ task_not_found: "这个子任务不在对应的任务里",
66
78
  };
67
79
 
68
80
  /**
@@ -77,6 +89,11 @@ export interface ConversationBackend {
77
89
  /** taskId:只要对话任务里这一个对话的轮次。 */
78
90
  listTurns(jobId: string, query?: { afterSeq?: number; limit?: number; taskId?: string }): Promise<{ job_id: string; turns: CenterTurn[] }>;
79
91
  listTasks(): Promise<{ tasks: CenterTask[] }>;
92
+ /**
93
+ * 更早的节点转录(往上翻):remote 是流里给的节点会话,before 是手里最早那条消息的 id。
94
+ * 返回这一页(旧的在前)和再往前还剩几条。旧版中枢没有这个接口(实时流也就给的是全量,用不到)。
95
+ */
96
+ history?(jobId: string, remote: string, before: string, limit?: number): Promise<{ messages: Message[]; older: number }>;
80
97
  createConversation(firstMessage: string, opts?: NewConversationOptions & { businessId?: string }): Promise<{ id: string; job_id: string; status: string; task_ids?: string[]; turn: CenterTurn }>;
81
98
  /** taskId:发给对话任务里的哪个对话,不给 = 第一个。 */
82
99
  sendMessage(jobId: string, text: string, opts?: { businessId?: string; timeoutSeconds?: number; taskId?: string }): Promise<SendResult>;
@@ -94,11 +111,15 @@ export interface ConversationBackend {
94
111
  /** taskId:看对话任务里的哪个对话,不给 = 第一个。 */
95
112
  stream(jobId: string, handlers: StreamHandlers, intervalMs?: number, taskId?: string | null): () => void;
96
113
  /**
97
- * 把回答直接交给正停在提问上的回合(Operator 的 POST /api/tasks/:id/answer)。
98
- * resolved=false 表示没有在等的回合,调用方改用「下一条消息」发回答。center 不提供:它在 Agent 提问时已经结束那一轮。
114
+ * 把回答直接交给正停在提问上的回合(中枢 POST /api/jobs/:id/answer → 节点 /answer)。
115
+ * resolved=false 表示没有在等的回合:对话任务改用「下一条消息」发回答(中枢在 Agent 提问时已经结束那一轮);
116
+ * 一次性任务的子任务提问时回合开着等,答案直接交过去。
99
117
  */
100
118
  answerAsk?(jobId: string, askId: string, answers: string[][]): Promise<{ resolved: boolean }>;
101
- /** 提交浏览器输入卡片(Operator 的 POST /api/tasks/:id/input),返回错误文案或 null。center 不提供。 */
119
+ /**
120
+ * 提交浏览器输入卡片(验证码、账号、密码、选项;中枢 POST /api/jobs/:id/input → 节点 /input),返回错误文案或 null。
121
+ * 密码只交给节点上的浏览器脚本,不进模型、不进转录、中枢不落库。
122
+ */
102
123
  submitInput?(jobId: string, inputId: string, values: string[]): Promise<string | null>;
103
124
  /** 浏览器交接后交还给 AI(Operator 的 POST /api/tasks/:id/browser),返回错误文案或 null。center 不提供。 */
104
125
  handback?(jobId: string): Promise<string | null>;
@@ -118,9 +139,23 @@ export interface BoardBackend {
118
139
  stat(jobId: string, path?: string): Promise<DirListing | FileInfo>;
119
140
  /** 文件地址(给 <img> / <iframe> / 下载链接用)。相对路径用路径式地址,HTML 里的相对资源能跟着解析。 */
120
141
  fileUrl(jobId: string, path: string, opts?: { download?: boolean }): string;
121
- /** 读文本(最多 maxBytes,超过的截断)。 */
122
- readText(jobId: string, path: string, maxBytes?: number): Promise<{ text: string; truncated: boolean; size: number; contentType: string }>;
123
- readBuffer(jobId: string, path: string): Promise<ArrayBuffer>;
142
+ /**
143
+ * 浏览器能直接打开的文件地址前缀(…/files/raw,后面接相对路径或 ?path=):directLinks 时就是 fileUrl 的前缀;
144
+ * 否则向中枢换一个短期令牌放进路径(<img> / <iframe> / 下载都不需要请求头,大文件流式下载、不进浏览器内存),
145
+ * 快过期时自动换新的。中枢不支持时返回 null(看板退回先 fetch 再显示)。
146
+ */
147
+ fileLinkBase?(jobId: string): Promise<string | null>;
148
+ /**
149
+ * 读文本(最多 maxBytes,超过的截断)。只向中枢要这一段(Range),超大文件不整个传过来。
150
+ * tail = 读末尾那一段(超大日志);节点不支持只读一段时退回开头(返回的 tail 为 false)。
151
+ * 不是 UTF-8 的(GBK 导出的 CSV 之类)按 GB18030 解,encoding 说明按什么解的。
152
+ */
153
+ readText(jobId: string, path: string, maxBytes?: number, opts?: { tail?: boolean }): Promise<TextChunk>;
154
+ /**
155
+ * 读整个文件。signal 取消(打包下载点了取消);onBytes 报已收到的字节数(大文件显示进度)。
156
+ * 弱网:FILE_HEADER_TIMEOUT_MS 内没回响应头、或传输中 FILE_STALL_MS 没收到数据,按网络错误(NETWORK)失败。
157
+ */
158
+ readBuffer(jobId: string, path: string, opts?: { signal?: AbortSignal; onBytes?: (bytes: number) => void }): Promise<ArrayBuffer>;
124
159
  diff(jobId: string): Promise<DiffResult>;
125
160
  browserStatus(jobId: string): Promise<BrowserStatus>;
126
161
  browserAction(jobId: string, action: "open" | "close" | "takeover" | "handback"): Promise<BrowserStatus>;
@@ -129,6 +164,44 @@ export interface BoardBackend {
129
164
  /** 浏览器实时画面;onViewer 给出发输入要用的 viewer id。 */
130
165
  browserFrames(jobId: string, handlers: { onViewer: (viewer: string) => void; onMessage: (message: BrowserMessage) => void; onEnd?: (end: { reason: string; detail?: string }) => void; onClose?: (error: CenterError | null) => void }): () => void;
131
166
  browserInput(jobId: string, viewer: string, events: Array<Record<string, unknown>>): Promise<void>;
167
+ /**
168
+ * 浏览器的一条实时连接(状态 + 画面 + 弹窗 + 复制出的文字,见中枢 board-live.ts)。新版中枢才有:
169
+ * 旧版中枢回 404(路由不存在,error 为 "Not Found"),组件退回 browserEvents + browserFrames 两条。
170
+ */
171
+ browserLive?(jobId: string, handlers: BrowserLiveHandlers): () => void;
172
+ }
173
+
174
+ export interface TextChunk {
175
+ text: string;
176
+ /** 只读到了一部分。 */
177
+ truncated: boolean;
178
+ /** 文件总大小。 */
179
+ size: number;
180
+ contentType: string;
181
+ /** 读的是末尾那一段。 */
182
+ tail?: boolean;
183
+ encoding?: string;
184
+ }
185
+
186
+ export interface BrowserLiveHandlers {
187
+ /** 这条连接的 viewer id;ready = 输入能送到节点(画面连接已建好)。 */
188
+ onViewer: (viewer: string, ready: boolean) => void;
189
+ onStatus: (status: BrowserStatus) => void;
190
+ onMessage: (message: BrowserMessage) => void;
191
+ onFrames?: (state: BrowserFramesState) => void;
192
+ /** 不会再有数据(节点拒绝、中枢停机)。 */
193
+ onEnd?: (end: { reason: string; status?: number; detail?: string }) => void;
194
+ onClose?: (error: CenterError | null) => void;
195
+ }
196
+
197
+ /** 旧版中枢没有这个接口:Fastify 的「路由不存在」404(和「任务不存在」的 not_found 区分开)。 */
198
+ export const isMissingRoute = (error: CenterError | null | undefined) => !!error && error.status === 404 && error.code === "Not Found";
199
+
200
+ /** 由 fileLinkBase 给的前缀拼出文件地址。 */
201
+ export function fileUrlFromBase(linkBase: string, path: string, download = false) {
202
+ const clean = path.replace(/^\.\//, "");
203
+ if (clean.startsWith("/") || clean.startsWith("~") || /^[a-z]:[\\/]/i.test(clean)) return `${linkBase}?path=${encodeURIComponent(clean)}${download ? "&download=1" : ""}`;
204
+ return `${linkBase}/${clean.split("/").filter(Boolean).map(encodeURIComponent).join("/")}${download ? "?download=1" : ""}`;
132
205
  }
133
206
 
134
207
  export function createCenterClient(options: CenterClientOptions = {}): ConversationBackend {
@@ -142,18 +215,38 @@ export function createCenterClient(options: CenterClientOptions = {}): Conversat
142
215
  return result;
143
216
  }
144
217
 
145
- async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
218
+ // 同一时刻对同一地址的 GET 只发一次,后来的共用结果:列表、对话、看板经常同时要同一份数据(同一个任务的详情、看板概况、目录),
219
+ // 浏览器对一个域名的连接有限,重复请求会把真正要紧的(点开文件、发消息)挤到后面排队。
220
+ const inflight = new Map<string, Promise<unknown>>();
221
+ function request<T>(path: string, init: RequestInit = {}, timeoutMs = options.requestTimeoutMs ?? 30_000): Promise<T> {
222
+ if ((init.method ?? "GET") !== "GET" || init.body) return send<T>(path, init, timeoutMs);
223
+ const shared = inflight.get(path);
224
+ if (shared) return shared as Promise<T>;
225
+ const p = send<T>(path, init, timeoutMs).finally(() => inflight.delete(path));
226
+ inflight.set(path, p);
227
+ return p;
228
+ }
229
+ async function send<T>(path: string, init: RequestInit, timeoutMs: number): Promise<T> {
146
230
  let response: Response;
231
+ const ctl = new AbortController();
232
+ let timedOut = false;
233
+ const timer = setTimeout(() => { timedOut = true; ctl.abort(); }, timeoutMs);
147
234
  try {
148
235
  response = await doFetch(`${base}${path}`, {
149
236
  ...init,
237
+ signal: ctl.signal,
150
238
  headers: headers(init.body ? { "Content-Type": "application/json" } : {}),
151
239
  });
152
240
  } catch (error) {
241
+ clearTimeout(timer);
242
+ if (timedOut) throw new CenterError(`任务中心 ${Math.round(timeoutMs / 1000)} 秒没有响应,请稍后重试`, "NETWORK", 0);
153
243
  throw new CenterError(`连不上任务中心:${error instanceof Error ? error.message : String(error)}`, "NETWORK", 0);
154
244
  }
155
- const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
245
+ // 响应体也算在时限里(代理把响应头发了、正文却挂住)。
246
+ const body = (await response.json().catch(() => null).finally(() => clearTimeout(timer))) as Record<string, unknown> | null;
156
247
  if (!response.ok) {
248
+ // 413:消息 / 请求体超过中枢上限(中枢回的是 Fastify 的英文说明)。
249
+ if (response.status === 413) throw new CenterError("内容太大,超过任务中心单次请求的上限,请删减或分几条发送", "payload_too_large", 413, body);
157
250
  const code = typeof body?.error === "string" ? body.error : `HTTP_${response.status}`;
158
251
  const detail = typeof body?.detail === "string" ? body.detail : undefined;
159
252
  throw new CenterError(ERROR_TEXT[code] ?? detail ?? `任务中心返回错误(HTTP ${response.status})`, code, response.status, body);
@@ -177,6 +270,26 @@ export function createCenterClient(options: CenterClientOptions = {}): Conversat
177
270
  },
178
271
  /** 列表用:本产品线全部子任务(对话任务每个对话一条),用来发现对话。 */
179
272
  listTasks: () => request<{ tasks: CenterTask[] }>("/api/tasks"),
273
+ async answerAsk(jobId: string, askId: string, answers: string[][]) {
274
+ try {
275
+ return await request<{ resolved: boolean }>(boardPath(jobId, "answer"), { method: "POST", body: JSON.stringify({ ask_id: askId, answers }) });
276
+ } catch (error) {
277
+ // 旧版中枢没有这个接口:当作没有在等的回合(对话任务照旧走下一条消息)。
278
+ if (error instanceof CenterError && isMissingRoute(error)) return { resolved: false };
279
+ throw error;
280
+ }
281
+ },
282
+ async submitInput(jobId: string, inputId: string, values: string[]) {
283
+ try {
284
+ await request(boardPath(jobId, "input"), { method: "POST", body: JSON.stringify({ input_id: inputId, values }) });
285
+ return null;
286
+ } catch (error) {
287
+ if (error instanceof CenterError && isMissingRoute(error)) return "当前任务中心版本不支持在这里填写,请升级任务中心";
288
+ return error instanceof Error ? error.message : String(error);
289
+ }
290
+ },
291
+ history: (jobId: string, remote: string, before: string, limit = 200) =>
292
+ request<{ messages: Message[]; older: number }>(`/api/jobs/${id(parseConvKey(jobId).jobId)}/history?remote=${id(remote)}&before=${id(before)}&limit=${limit}`),
180
293
  createConversation: (firstMessage: string, opts: NewConversationOptions & { businessId?: string } = {}) => {
181
294
  const title = (opts.title || firstLine(firstMessage)).slice(0, 120);
182
295
  return post<{ id: string; job_id: string; status: string; task_ids?: string[]; turn: CenterTurn }>("/api/jobs", {
@@ -387,58 +500,154 @@ function createBoardClient(
387
500
  base: string,
388
501
  headers: (extra?: Record<string, string>) => Record<string, string>,
389
502
  doFetch: typeof fetch,
390
- request: <T>(path: string, init?: RequestInit) => Promise<T>,
503
+ request: <T>(path: string, init?: RequestInit, timeoutMs?: number) => Promise<T>,
391
504
  directLinks: boolean,
392
505
  ): BoardBackend {
393
- const fileFetch = async (jobId: string, path: string) => {
506
+ /**
507
+ * 取文件:响应头限时 FILE_HEADER_TIMEOUT_MS;body() 边读边看门(FILE_STALL_MS 没数据就断),
508
+ * limit 读够就停(大文件只要开头)。外面给的 signal 取消时一并中止。
509
+ */
510
+ const fileFetch = async (jobId: string, path: string, extra: Record<string, string> = {}, signal?: AbortSignal) => {
511
+ const name = path.split("/").pop() || path;
512
+ const aborted = () => new DOMException("已取消", "AbortError");
513
+ if (signal?.aborted) throw aborted();
514
+ const ctl = new AbortController();
515
+ const cancel = () => ctl.abort();
516
+ signal?.addEventListener("abort", cancel, { once: true });
517
+ let timedOut = false;
518
+ const timer = setTimeout(() => { timedOut = true; ctl.abort(); }, FILE_HEADER_TIMEOUT_MS);
519
+ const release = () => { clearTimeout(timer); signal?.removeEventListener("abort", cancel); };
394
520
  let response: Response;
395
521
  try {
396
- response = await doFetch(boardFileUrl(base, jobId, path), { headers: headers() });
522
+ // 和中止赛跑:宿主自定义的 fetch 不一定理会 signal,取消 / 超时也要马上生效。
523
+ const stopped = new Promise<never>((_r, reject) => {
524
+ if (ctl.signal.aborted) reject(new DOMException("aborted", "AbortError"));
525
+ ctl.signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true });
526
+ });
527
+ response = await Promise.race([doFetch(boardFileUrl(base, jobId, path), { headers: headers(extra), signal: ctl.signal }), stopped]);
397
528
  } catch (error) {
529
+ release();
530
+ if (signal?.aborted) throw aborted();
531
+ if (timedOut) throw new CenterError(`读取「${name}」${FILE_HEADER_TIMEOUT_MS / 1000} 秒没有响应(执行节点忙或网络慢),请稍后重试`, "NETWORK", 0);
398
532
  throw new CenterError(`连不上任务中心:${error instanceof Error ? error.message : String(error)}`, "NETWORK", 0);
399
533
  }
400
- if (!response.ok) {
534
+ clearTimeout(timer);
535
+ if (!response.ok && response.status !== 416) {
536
+ release();
401
537
  const body = (await response.json().catch(() => null)) as { error?: string; detail?: string } | null;
402
- throw new CenterError(body?.detail ?? ERROR_TEXT[body?.error ?? ""] ?? body?.error ?? `读取失败(HTTP ${response.status})`, body?.error ?? `HTTP_${response.status}`, response.status);
538
+ const fallback = response.status === 404 ? "文件不存在(可能已被任务删除或改名)" : body?.error ?? `读取失败(HTTP ${response.status})`;
539
+ throw new CenterError(body?.detail ?? ERROR_TEXT[body?.error ?? ""] ?? fallback, body?.error ?? `HTTP_${response.status}`, response.status);
403
540
  }
404
- return response;
405
- };
406
- return {
407
- directLinks,
408
- info: (jobId) => request<BoardInfo>(boardPath(jobId, "board")),
409
- stat: (jobId, path = ".") => request<DirListing | FileInfo>(boardPath(jobId, "files", `path=${encodeURIComponent(path)}`)),
410
- fileUrl: (jobId, path, opts = {}) => boardFileUrl(base, jobId, path, opts.download),
411
- async readText(jobId, path, maxBytes = 512 * 1024) {
412
- const response = await fileFetch(jobId, path);
413
- const contentType = response.headers.get("content-type") ?? "";
414
- const size = Number(response.headers.get("content-length") ?? 0);
415
- // 只读前 maxBytes:大文件不整个拉进浏览器。
541
+ const stallError = () => new CenterError(`读取「${name}」时 ${FILE_STALL_MS / 1000} 秒没有收到数据,传输已中断,请重试`, "NETWORK", 0);
542
+ /** 读响应体:limit 读够就停;onBytes 报进度;FILE_STALL_MS 没数据当断线。 */
543
+ const body = async (opts: { limit?: number; onBytes?: (bytes: number) => void } = {}): Promise<Uint8Array<ArrayBuffer>> => {
544
+ // 空文件要「前 N 字节」:节点回 416,就是空的。
545
+ if (response.status === 416) { release(); return new Uint8Array(0); }
416
546
  const reader = response.body?.getReader();
417
- if (!reader) return { text: await response.text(), truncated: false, size, contentType };
547
+ if (!reader) {
548
+ try { return new Uint8Array(await response.arrayBuffer()); } finally { release(); }
549
+ }
418
550
  const chunks: Uint8Array[] = [];
419
551
  let got = 0;
420
- let truncated = false;
421
- for (;;) {
422
- const { done, value } = await reader.read();
423
- if (done) break;
424
- chunks.push(value);
425
- got += value.length;
426
- if (got >= maxBytes) { truncated = true; await reader.cancel().catch(() => undefined); break; }
552
+ let stalled = false;
553
+ let stall: ReturnType<typeof setTimeout> | undefined;
554
+ const arm = () => {
555
+ clearTimeout(stall);
556
+ stall = setTimeout(() => { stalled = true; ctl.abort(); void reader.cancel().catch(() => undefined); }, FILE_STALL_MS);
557
+ };
558
+ try {
559
+ arm();
560
+ for (;;) {
561
+ const { done, value } = await reader.read();
562
+ if (stalled) throw stallError();
563
+ if (done) break;
564
+ arm();
565
+ chunks.push(value);
566
+ got += value.length;
567
+ opts.onBytes?.(got);
568
+ if (opts.limit !== undefined && got >= opts.limit) { await reader.cancel().catch(() => undefined); break; }
569
+ }
570
+ } catch (error) {
571
+ if (signal?.aborted) throw aborted();
572
+ if (stalled) throw stallError();
573
+ if (error instanceof CenterError) throw error;
574
+ throw new CenterError(`读取「${name}」中断:${error instanceof Error ? error.message : String(error)}`, "NETWORK", 0);
575
+ } finally {
576
+ clearTimeout(stall);
577
+ release();
427
578
  }
428
- const all = new Uint8Array(Math.min(got, maxBytes));
579
+ if (signal?.aborted) throw aborted();
580
+ const size = opts.limit !== undefined ? Math.min(got, opts.limit) : got;
581
+ const all = new Uint8Array(size);
429
582
  let offset = 0;
430
583
  for (const chunk of chunks) {
431
- const take = Math.min(chunk.length, all.length - offset);
584
+ const take = Math.min(chunk.length, size - offset);
432
585
  all.set(chunk.subarray(0, take), offset);
433
586
  offset += take;
434
- if (offset >= all.length) break;
587
+ if (offset >= size) break;
435
588
  }
436
- return { text: new TextDecoder().decode(all), truncated, size: size || got, contentType };
589
+ return all;
590
+ };
591
+ return { response, body };
592
+ };
593
+ // 文件链接令牌:按对话键缓存,离过期不到 5 分钟就换新的;同一时刻只换一次。
594
+ const links = new Map<string, { base: string; until: number }>();
595
+ const minting = new Map<string, Promise<string | null>>();
596
+ let linksUnsupported = false;
597
+ const LINK_REFRESH_MS = 5 * 60_000;
598
+ return {
599
+ directLinks,
600
+ info: (jobId) => request<BoardInfo>(boardPath(jobId, "board")),
601
+ stat: (jobId, path = ".") => request<DirListing | FileInfo>(boardPath(jobId, "files", `path=${encodeURIComponent(path)}`)),
602
+ fileUrl: (jobId, path, opts = {}) => boardFileUrl(base, jobId, path, opts.download),
603
+ async fileLinkBase(jobId) {
604
+ const { job, task } = boardTarget(jobId);
605
+ if (directLinks) return `${base}/api/jobs/${job}${task ? `/tasks/${task}` : ""}/files/raw`;
606
+ if (linksUnsupported) return null;
607
+ const cached = links.get(jobId);
608
+ if (cached && cached.until - Date.now() > LINK_REFRESH_MS) return cached.base;
609
+ const running = minting.get(jobId);
610
+ if (running) return running;
611
+ const work = request<{ base?: unknown; expires_at?: string }>(boardPath(jobId, "files/token"), { method: "POST", body: "{}" }).then((r) => {
612
+ if (typeof r?.base !== "string") { linksUnsupported = true; return null; }
613
+ const linkBase = `${base}${r.base}`;
614
+ links.set(jobId, { base: linkBase, until: Date.parse(r.expires_at ?? "") || Date.now() + 30 * 60_000 });
615
+ return linkBase;
616
+ }, (error: unknown) => {
617
+ if (error instanceof CenterError && isMissingRoute(error)) { linksUnsupported = true; return null; }
618
+ throw error;
619
+ }).finally(() => minting.delete(jobId));
620
+ minting.set(jobId, work);
621
+ return work;
622
+ },
623
+ async readText(jobId, path, maxBytes = 512 * 1024, opts = {}) {
624
+ // 只要需要的那一段:开头 maxBytes,或者末尾 maxBytes(超大日志)。不支持 Range 的节点回整个文件(200),下面边读边截。
625
+ const { response, body } = await fileFetch(jobId, path, { Range: opts.tail ? `bytes=-${maxBytes}` : `bytes=0-${maxBytes - 1}` });
626
+ const contentType = response.headers.get("content-type") ?? "text/plain";
627
+ if (response.status === 416) { await body(); return { text: "", truncated: false, size: 0, contentType }; }
628
+ const total = /\/(\d+)\s*$/.exec(response.headers.get("content-range") ?? "")?.[1];
629
+ const length = Number(response.headers.get("content-length") ?? 0);
630
+ if (response.status === 206) {
631
+ // 节点给的一段可能比要的长(不严格按 Range):也只留 maxBytes。
632
+ const bytes = await body({ limit: maxBytes });
633
+ const size = total ? Number(total) : bytes.length;
634
+ const start = Number(/bytes (\d+)-/.exec(response.headers.get("content-range") ?? "")?.[1] ?? 0);
635
+ const { text, encoding } = decodeText(bytes, { fromMiddle: start > 0 });
636
+ return { text, truncated: bytes.length < size, size, contentType, tail: start > 0, encoding };
637
+ }
638
+ // 不支持 Range(回 200 整个文件):只读前 maxBytes,大文件不整个拉进浏览器。
639
+ const all = await body({ limit: maxBytes });
640
+ const truncated = all.length >= maxBytes && (!length || length > maxBytes);
641
+ const { text, encoding } = decodeText(all);
642
+ return { text, truncated, size: length || all.length, contentType, encoding };
643
+ },
644
+ async readBuffer(jobId, path, opts = {}) {
645
+ const { body } = await fileFetch(jobId, path, {}, opts.signal);
646
+ return (await body({ onBytes: opts.onBytes })).buffer;
437
647
  },
438
- readBuffer: async (jobId, path) => (await fileFetch(jobId, path)).arrayBuffer(),
439
648
  diff: (jobId) => request<DiffResult>(boardPath(jobId, "diff")),
440
649
  browserStatus: (jobId) => request<BrowserStatus>(boardPath(jobId, "browser")),
441
- browserAction: (jobId, action) => request<BrowserStatus>(boardPath(jobId, "browser"), { method: "POST", body: JSON.stringify({ action }) }),
650
+ browserAction: (jobId, action) => request<BrowserStatus>(boardPath(jobId, "browser"), { method: "POST", body: JSON.stringify({ action }) }, 150_000),
442
651
  browserEvents: (jobId, handlers) => openSse(doFetch, `${base}${boardPath(jobId, "browser/events")}`, headers(), (event, data) => {
443
652
  if (event === "status") handlers.onStatus(data as BrowserStatus);
444
653
  }, handlers.onClose),
@@ -450,5 +659,13 @@ function createBoardClient(
450
659
  async browserInput(jobId, viewer, events) {
451
660
  await request(boardPath(jobId, "browser/input"), { method: "POST", body: JSON.stringify({ viewer, events }) });
452
661
  },
662
+ browserLive: (jobId, h) => openSse(doFetch, `${base}${boardPath(jobId, "browser/live")}`, headers(), (event, data) => {
663
+ const d = data as Record<string, unknown>;
664
+ if (event === "viewer") h.onViewer(String(d.viewer), d.ready === true);
665
+ else if (event === "status") h.onStatus(data as BrowserStatus);
666
+ else if (event === "message") h.onMessage(data as BrowserMessage);
667
+ else if (event === "frames") h.onFrames?.(data as BrowserFramesState);
668
+ else if (event === "end") h.onEnd?.(data as { reason: string; status?: number; detail?: string });
669
+ }, h.onClose),
453
670
  };
454
671
  }
@@ -7,7 +7,7 @@
7
7
  * 界面以节点转录为主;转录还没有(没派发、节点连不上)时用轮次的 input / reply 兜底。
8
8
  */
9
9
  import { isBatchSnapshot, type AskAnswers, type AskQuestion, type BatchStreamSnapshot, type BatchStreamTask, type CenterTurn, type ConversationClosedCallback, type ConversationTurnCallback, type JobStatus, type Message, type Msg, type NodeEvent, type StreamItem, type StreamSnapshot, type StreamTask, type ToolData, type TurnUsage } from "./types.js";
10
- import { indexFromEnd, mergeSnapshot, toolDataOf } from "../ui/transcriptModel.js";
10
+ import { indexFromEnd, mergeSnapshot, prependOlder, toolDataOf } from "../ui/transcriptModel.js";
11
11
  import { formatAnswersText } from "../ui/format.js";
12
12
 
13
13
  export const TERMINAL_TURN = new Set(["succeeded", "failed", "cancelled", "merged"]);
@@ -68,6 +68,8 @@ export interface ConvState {
68
68
  /** 节点转录(Operator 消息)。 */
69
69
  msgs: Msg[];
70
70
  hasTranscript: boolean;
71
+ /** 节点转录里比 msgs 更早、还没取的条数(实时流只给最新一段;往上翻时 store.loadOlder 分页取)。 */
72
+ older: number;
71
73
  nodeRunning: boolean;
72
74
  resolvedModel: string | null;
73
75
  /** 上次刷新任务详情之后,实时流里累计的用量(usage 事件)。 */
@@ -89,7 +91,7 @@ export interface ConvState {
89
91
  }
90
92
 
91
93
  export const emptyConv = (key: string): ConvState => ({
92
- key, ...parseConvKey(key), job: null, task: null, turns: [], msgs: [], hasTranscript: false, nodeRunning: false, resolvedModel: null,
94
+ key, ...parseConvKey(key), job: null, task: null, turns: [], msgs: [], hasTranscript: false, older: 0, nodeRunning: false, resolvedModel: null,
93
95
  liveUsage: { fresh: 0, cacheRead: 0 }, stream: "idle", streamError: null, endReason: null, continuedBy: null, localAnswers: {},
94
96
  batch: false, batchTask: null, remoteTaskId: null,
95
97
  });
@@ -152,7 +154,7 @@ function focusBatchTask(conv: ConvState, task: BatchStreamTask | null): ConvStat
152
154
  const batchTask = task ? { ...kept, ...task } : null;
153
155
  return {
154
156
  ...conv, batch: true, batchTask, task: batchTask ? batchStreamTask(batchTask) : null, remoteTaskId: remote,
155
- ...(sameRemote ? {} : { msgs: [], hasTranscript: false, nodeRunning: false }),
157
+ ...(sameRemote ? {} : { msgs: [], hasTranscript: false, older: 0, nodeRunning: false }),
156
158
  };
157
159
  }
158
160
 
@@ -175,7 +177,7 @@ function applyBatchTask(conv: ConvState, task: BatchStreamTask): ConvState {
175
177
  }
176
178
 
177
179
  // 缺字段时兜底:generation 缺省 1(按它分会话,缺了会把顺序排乱);时间缺就不显示。
178
- const toMsg = (m: Message): Msg => ({ id: m.id, role: m.role, content: m.content, generation: typeof m.generation === "number" ? m.generation : 1, ...(typeof m.created_at === "number" ? { ts: m.created_at } : {}) });
180
+ export const toMsg = (m: Message): Msg => ({ id: m.id, role: m.role, content: m.content, generation: typeof m.generation === "number" ? m.generation : 1, ...(typeof m.created_at === "number" ? { ts: m.created_at } : {}) });
179
181
 
180
182
  export function applyItems(conv: ConvState, items: StreamItem[]): ConvState {
181
183
  let next = conv;
@@ -185,7 +187,8 @@ export function applyItems(conv: ConvState, items: StreamItem[]): ConvState {
185
187
  if (item.type === "transcript") {
186
188
  // 节点转录全量(连上 / 重连节点时各一次):整体替换,没变的消息保留对象引用。
187
189
  const messages = Array.isArray(item.messages) ? item.messages.map(toMsg) : [];
188
- next = { ...next, msgs: mergeSnapshot(next.msgs, messages), hasTranscript: true, nodeRunning: item.running === true };
190
+ const merged = mergeSnapshot(next.msgs, messages, typeof item.older === "number" ? item.older : 0);
191
+ next = { ...next, msgs: merged.msgs, older: merged.older, hasTranscript: true, nodeRunning: item.running === true };
189
192
  } else if (item.type === "node") {
190
193
  next = applyNodeEvent(next, item.event);
191
194
  } else if (item.type === "turn") {
@@ -285,6 +288,11 @@ export function applyNodeEvent(conv: ConvState, ev: NodeEvent): ConvState {
285
288
  }
286
289
  }
287
290
 
291
+ /** 往上翻取到的一页更早的节点消息(旧的在前)。older:再往前还剩几条。 */
292
+ export function applyOlderPage(conv: ConvState, page: Message[], older: number): ConvState {
293
+ return { ...conv, msgs: prependOlder(conv.msgs, page.map(toMsg)), older: Math.max(0, older) };
294
+ }
295
+
288
296
  /** 这个对话结束了:整个对话任务结束,或者只是这一个对话被关闭。 */
289
297
  export const convEnded = (conv: Pick<ConvState, "job" | "task">) => !!conv.task?.closed || (!!conv.job && TERMINAL_JOB.has(conv.job.status));
290
298
 
@@ -312,7 +320,8 @@ export function viewMessages(conv: ConvState): Msg[] {
312
320
  // 转录里的第一条用户消息、内容又不是开出会话那一轮的原文,就是它;措辞以后变了也认得出。
313
321
  // 之后的消息里再出现这句固定语句(例如会话被重启),按原文匹配。
314
322
  const openerText = opener ? opener.sent_input ?? opener.input : null;
315
- let replaced = false;
323
+ // 更早的消息还没取(older > 0)时,手里的第一条用户消息不是会话的开场:不按位置认。
324
+ let replaced = conv.older > 0;
316
325
  for (const m of conv.msgs) {
317
326
  const firstUser = !replaced && m.role === "user";
318
327
  if (firstUser) replaced = true;
@@ -378,7 +387,8 @@ function batchViewMessages(conv: ConvState): Msg[] {
378
387
  const out: Msg[] = [];
379
388
  const task = conv.batchTask;
380
389
  const opener = task?.opener_prompt ?? null;
381
- const firstUserId = conv.msgs.find((m) => m.role === "user")?.id;
390
+ // 更早的消息还没取时,手里的第一条用户消息不是开场语句。
391
+ const firstUserId = conv.older > 0 ? undefined : conv.msgs.find((m) => m.role === "user")?.id;
382
392
  for (let i = 0; i < conv.msgs.length; i++) {
383
393
  const m = conv.msgs[i];
384
394
  if (m.role === "user" && m.content.includes(CONFIRM_MARK)) {