@spzxg/cli-ui 0.6.13 → 0.6.17

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 +100 -2
  2. package/README.md +131 -7
  3. package/dist/{cli-ui-embed-CXaGT9e4.js → cli-ui-embed-REq-GvM7.js} +20350 -19892
  4. package/dist/{cli-ui-index-bMQJjEBW.js → cli-ui-index-p_XTnmsN.js} +2 -2
  5. package/dist/{cli-ui-jszip.min-D_w3a6AF.js → cli-ui-jszip.min-0mqaiYeK.js} +1 -1
  6. package/dist/{cli-ui-jszip.min-AMeWMDT5.js → cli-ui-jszip.min-CJa9yrKW.js} +2 -2
  7. package/dist/{cli-ui-xlsx-DMzew4IO.js → cli-ui-xlsx-BPL7P3mE.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 +62 -27
  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 +36 -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/types.ts CHANGED
@@ -251,6 +251,8 @@ export type StreamItem =
251
251
  /** remote_task_id:一次性任务的流里才有(大任务里可能同时有几个节点对话)。 */
252
252
  /** older:快照只有最新一段时,更早还有几条(往上翻时经 history 分页取)。旧版中枢没有 = 全量。 */
253
253
  | { type: "transcript"; remote_task_id?: string; messages: Message[] | null; pending: PendingMessage[] | null; running: boolean | null; older?: number }
254
+ /** 中枢读不到这个对话的记录(执行节点暂时连不上、读超时),会继续重试;旧版中枢没有。 */
255
+ | { type: "transcript_unavailable"; remote_task_id?: string; error: string }
254
256
  | { type: "node"; remote_task_id?: string; event: NodeEvent }
255
257
  | { type: "turn"; turn: CenterTurn }
256
258
  | { type: "job"; job: { id: string; status: JobStatus; closed_reason?: string | null; node_id: string | null } }
@@ -279,6 +281,11 @@ export interface BatchStreamTask extends AwaitingInputState {
279
281
  status: string;
280
282
  round: number;
281
283
  attempt: number;
284
+ /** 实际派发执行批次的稳定标识;旧版中枢或从未派发的任务没有。 */
285
+ execution_id?: string;
286
+ dispatched_at?: string | null;
287
+ /** 中枢记录的本次结束时间;同次收尾可能更新,不作为批次标识。 */
288
+ ended_at?: string | null;
282
289
  remote_task_id: string | null;
283
290
  continue_from_task_id: string | null;
284
291
  last_error: string | null;
@@ -381,6 +388,42 @@ export interface ConversationClosedCallback {
381
388
 
382
389
  export type ConversationCallback = ConversationTurnCallback | ConversationClosedCallback;
383
390
 
391
+ /**
392
+ * 一次性任务(含续派)里一个子任务结束一次(成功 / 失败 / 取消):type = "task_end",onTaskEnd 收到的载荷。
393
+ * 字段与中枢一次性任务回调体 tasks[] 的一项同名(task_id、task_key、title、status、attempts、message)。
394
+ * 初始快照中已结束的历史子任务不发;连接后新增快任务也通知,断线期间结束的重连后补报。
395
+ */
396
+ export interface TaskEndPayload {
397
+ type: "task_end";
398
+ job_id: string;
399
+ task_id: string;
400
+ task_key: string | null;
401
+ title: string;
402
+ /** succeeded / failed / cancelled。 */
403
+ status: string;
404
+ attempts: number;
405
+ /** 失败 / 取消原因(中枢原文)。 */
406
+ message: string | null;
407
+ /** 续派时 mode=conversation 的对话式子任务(可以接着聊)。 */
408
+ conversation: boolean;
409
+ /** 接着它聊出来的子任务指回的那条。 */
410
+ continue_from_task_id: string | null;
411
+ occurred_at: string;
412
+ }
413
+
414
+ /**
415
+ * 实际派发的执行批次进入成功 / 失败 / 取消时的可选通知。
416
+ * 按 job_id + task_id + execution_id 去重;不补首次历史,不推测旧服务缺少的标识。
417
+ * 内部自动重派的 queued 状态、未派发的取消不触发此通知;原 task_end 规则不变。
418
+ */
419
+ export interface TaskAttemptEndPayload extends Omit<TaskEndPayload, "type"> {
420
+ type: "task_attempt_end";
421
+ execution_id: string;
422
+ round: number;
423
+ dispatched_at: string;
424
+ ended_at: string | null;
425
+ }
426
+
384
427
  /** 一轮结束时 onTurnEnd 收到的载荷(字段与 center 的 conversation_turn 回调体一致)。 */
385
428
  export type TurnEndPayload = ConversationTurnCallback;
386
429
  /** 对话结束时 onConversationEnd 收到的载荷(字段与 center 的 conversation_closed 回调体一致)。 */
@@ -395,6 +438,8 @@ export interface BoardInfo {
395
438
  detail?: string;
396
439
  task_id?: string;
397
440
  remote_task_id?: string;
441
+ /** 节点确认的当前任务工作目录;旧服务端可省略,不由客户端猜测。 */
442
+ workspaceRoot?: string;
398
443
  node?: { id: string; health: string };
399
444
  files: boolean;
400
445
  /** 节点开了浏览器功能。null = 这次没探测出来(节点慢 / 暂时连不上),照常显示浏览器页签。 */
@@ -432,6 +477,10 @@ export interface DiffResult {
432
477
  alreadyMerged?: boolean;
433
478
  /** 因为总量上限没带 diff 的文件数。 */
434
479
  patchesOmitted?: number;
480
+ /** 渐进式改动(?summary=1):只有文件列表和增删行数,patch 为空,点开时用 diffFile 取。 */
481
+ summary?: boolean;
482
+ /** 渐进式摘要的内容修订,包含增删行数相同的未提交变化(需配套节点)。 */
483
+ revision?: string;
435
484
  error?: string;
436
485
  /** 有的节点只给一整段 unified diff。 */
437
486
  diff?: string;
package/src/elements.tsx CHANGED
@@ -22,7 +22,8 @@
22
22
  * config(界面配置 JSON)、new-conversation(新建对话参数 JSON:title / businessId / workspace / callback / agent …)。
23
23
  * 界面配置也可以直接赋对象:document.querySelector("cli-chat").config = { header: { export: false } }。
24
24
  * 事件(全在浏览器里从实时流算出,和 center 的 callback.url 无关):
25
- * cli-turn-end(一轮结束)、cli-conversation-end(对话结束),detail 字段与 center 回调体一致;
25
+ * cli-turn-end(一轮结束)、cli-conversation-end(对话结束)、cli-task-end(一次性任务里一个子任务结束);
26
+ * cli-task-attempt-end(一次已派发执行批次结束),detail 含执行批次身份;
26
27
  * cli-event(全部事件:select / conversation_turn / conversation_closed / job_change / open / error);
27
28
  * cli-callback 是旧名字,等同于前两个合在一起,保留兼容。
28
29
  * 渲染在 light DOM 里(不用 Shadow DOM),样式靠页面引入 styles.css,作用域都在 .cli-ui 内。
@@ -254,6 +255,8 @@ abstract class CliElement extends Base {
254
255
  },
255
256
  onTurnEnd: (payload: unknown) => this.dispatchEvent(new CustomEvent("cli-turn-end", { detail: payload, bubbles: true })),
256
257
  onConversationEnd: (payload: unknown) => this.dispatchEvent(new CustomEvent("cli-conversation-end", { detail: payload, bubbles: true })),
258
+ onTaskEnd: (payload: unknown) => this.dispatchEvent(new CustomEvent("cli-task-end", { detail: payload, bubbles: true })),
259
+ onTaskAttemptEnd: (payload: unknown) => this.dispatchEvent(new CustomEvent("cli-task-attempt-end", { detail: payload, bubbles: true })),
257
260
  onCallback: (payload: unknown) => this.dispatchEvent(new CustomEvent("cli-callback", { detail: payload, bubbles: true })),
258
261
  style: { height: "100%" },
259
262
  config: this.config as never,
@@ -277,7 +280,7 @@ class CliMsgListElement extends CliElement {
277
280
  protected element() {
278
281
  const context = this.getAttribute("context");
279
282
  // 结果事件只由 <cli-chat> 发:同一个 group 里列表和对话共用一个仓库,两边都发的话 document 上会收到两遍。
280
- const { onTurnEnd: _a, onConversationEnd: _b, onCallback: _c, ...common } = this.common();
283
+ const { onTurnEnd: _a, onConversationEnd: _b, onTaskEnd: _d, onTaskAttemptEnd: _e, onCallback: _c, ...common } = this.common();
281
284
  return <CliMsgList {...common} {...(context !== null ? { context } : {})} />;
282
285
  }
283
286
  }
@@ -298,7 +301,7 @@ class CliBoardElement extends CliElement {
298
301
  const availableTabs = this.getAttribute("available-tabs")?.split(",").map(t=>t.trim()).filter(Boolean) as BoardTab[] | undefined;
299
302
  const defaultTab = (this.getAttribute("default-tab") as BoardTab | null) ?? undefined;
300
303
  // 结果事件只由 <cli-chat> 发(同上);看板只发 cli-event。
301
- const { onTurnEnd: _a, onConversationEnd: _b, onCallback: _c, title: _t, color: _k, config: _g, ...common } = this.common();
304
+ const { onTurnEnd: _a, onConversationEnd: _b, onTaskEnd: _d, onTaskAttemptEnd: _e, onCallback: _c, title: _t, color: _k, config: _g, ...common } = this.common();
302
305
  const taskId = this.getAttribute("task-id");
303
306
  return <CliBoard {...common} {...(jobId !== null ? { jobId: jobId || null } : {})} {...(taskId ? { taskId } : {})} tabs={this.hasAttribute("tabs") ? tabs ?? [] : undefined} availableTabs={availableTabs} defaultTab={defaultTab} readOnly={this.hasAttribute("read-only")}
304
307
  // 同一个 group 里有对话:看板里「引用到对话」带进那个对话的下一条消息;no-quote 关掉。
@@ -310,7 +313,7 @@ class CliBoardElement extends CliElement {
310
313
  class CliFilePreviewElement extends CliElement {
311
314
  protected element() {
312
315
  const jobId = this.getAttribute("job-id");
313
- const { onTurnEnd: _a, onConversationEnd: _b, onCallback: _c, title: _t, color: _k, config: _g, ...common } = this.common();
316
+ const { onTurnEnd: _a, onConversationEnd: _b, onTaskEnd: _d, onTaskAttemptEnd: _e, onCallback: _c, title: _t, color: _k, config: _g, ...common } = this.common();
314
317
  return <CliFilePreview {...common} {...(jobId !== null ? { jobId: jobId || null } : {})} path={this.getAttribute("path") ?? ""} />;
315
318
  }
316
319
  }
@@ -318,7 +321,7 @@ class CliFilePreviewElement extends CliElement {
318
321
  class CliBrowserElement extends CliElement {
319
322
  protected element() {
320
323
  const jobId = this.getAttribute("job-id");
321
- const { onTurnEnd: _a, onConversationEnd: _b, onCallback: _c, title: _t, color: _k, config: _g, ...common } = this.common();
324
+ const { onTurnEnd: _a, onConversationEnd: _b, onTaskEnd: _d, onTaskAttemptEnd: _e, onCallback: _c, title: _t, color: _k, config: _g, ...common } = this.common();
322
325
  return <CliBrowserView {...common} {...(jobId !== null ? { jobId: jobId || null } : {})} readOnly={this.hasAttribute("read-only")} />;
323
326
  }
324
327
  }
@@ -40,7 +40,10 @@ export interface CliMsgListProps extends CliStoreOptions, ResultHandlers {
40
40
  context?: string;
41
41
  onEditContext?: () => void;
42
42
  onCollapse?: () => void;
43
- /** 刷新列表的间隔,缺省 10 秒;0 = 不轮询(正在看的对话仍然实时)。 */
43
+ /**
44
+ * @deprecated 0.6.14 起列表不再定时轮询,此参数仅保留兼容、不再安排定时请求。
45
+ * 打开着的对话由实时流驱动;其余未结束的对话在页面回到前台、窗口重新获得焦点、网络恢复时重新拉取,也可用 store.refreshAll()。
46
+ */
44
47
  pollMs?: number;
45
48
  theme?: "light" | "dark";
46
49
  className?: string;
@@ -279,8 +282,11 @@ function Group({ label, cards, selected, onSelect, show, rows, firstTask, onNewI
279
282
  );
280
283
  }
281
284
 
282
- function MsgListInner({ jobIds, selectedId, onSelect, onNew, title = "对话", color = "#b8613f", context, onEditContext, onCollapse, pollMs = 10_000, config, theme = "light", className, style, width, onEvent, onTurnEnd, onConversationEnd, onCallback, inProvider }: CliMsgListProps & { inProvider: boolean }) {
283
- useComponentEvents(onEvent, { onTurnEnd, onConversationEnd, onCallback }, inProvider);
285
+ /** 回到前台 / 获得焦点 / 网络恢复时重新拉列表,相邻这么久以内只拉一次。 */
286
+ const LIST_REFRESH_GAP_MS = 5_000;
287
+
288
+ function MsgListInner({ jobIds, selectedId, onSelect, onNew, title = "对话", color = "#b8613f", context, onEditContext, onCollapse, config, theme = "light", className, style, width, onEvent, onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, inProvider }: CliMsgListProps & { inProvider: boolean }) {
289
+ useComponentEvents(onEvent, { onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange }, inProvider);
284
290
  const configKey = JSON.stringify(config ?? {});
285
291
  const cfg = useMemo(() => resolveMsgListConfig(config), [configKey]); // eslint-disable-line react-hooks/exhaustive-deps
286
292
  const h = cfg.header;
@@ -317,14 +323,29 @@ function MsgListInner({ jobIds, selectedId, onSelect, onNew, title = "对话", c
317
323
  void store.refreshAll({ all: true }).finally(() => setDiscovered(true));
318
324
  }, [store]); // eslint-disable-line react-hooks/exhaustive-deps
319
325
 
326
+ // 不定时轮询:打开着的对话由实时流更新卡片(store 的 noticeTransitions);其余未结束的,
327
+ // 在页面回到前台、窗口重新获得焦点、网络恢复时重新拉一遍(相邻 5 秒内的合并为一次)。
320
328
  useEffect(() => {
321
- if (!pollMs) return;
322
- const timer = setInterval(() => { if (document.visibilityState !== "hidden") void store.refreshAll(); }, pollMs);
323
- return () => clearInterval(timer);
324
- }, [store, pollMs]);
329
+ let last = Date.now();
330
+ const refresh = () => {
331
+ if (document.visibilityState === "hidden" || Date.now() - last < LIST_REFRESH_GAP_MS) return;
332
+ last = Date.now();
333
+ void store.refreshAll();
334
+ };
335
+ const onVisibility = () => { if (document.visibilityState === "visible") refresh(); };
336
+ document.addEventListener("visibilitychange", onVisibility);
337
+ window.addEventListener("focus", refresh);
338
+ window.addEventListener("online", refresh);
339
+ return () => {
340
+ document.removeEventListener("visibilitychange", onVisibility);
341
+ window.removeEventListener("focus", refresh);
342
+ window.removeEventListener("online", refresh);
343
+ };
344
+ }, [store]);
325
345
 
326
- // 新加进来的对话(别的组件新建的 / 接续出来的)还没数据:补拉一次。
327
- useEffect(() => { for (const id of ids) if (!jobs[id]) void store.refreshJob(id); }, [ids, jobs, store]);
346
+ // 新加进来的对话(宿主后给的、别的组件新建的 / 接续出来的)还没数据:补拉一次。
347
+ // 和首次加载、刷新共用列表的并发上限;已经在排、在拉的不重复。
348
+ useEffect(() => { store.loadMissingJobs(); }, [ids, store]);
328
349
 
329
350
  const cards = useMemo(() => ids.map((id) => cardView(id, jobs[id])), [ids, jobs]);
330
351
  const q = query.trim().toLowerCase();
@@ -1,13 +1,14 @@
1
1
  "use client";
2
2
 
3
3
  import { useCallback, useEffect, useRef, useState } from "react";
4
- import { Icon } from "./icons";
4
+ import { Icon } from "../../ui/icons";
5
5
  import { jget, jsend } from "./api";
6
6
  import { Modal } from "./Modal";
7
7
  import { AUTH_BANNER_HINT } from "./protocol/authFailure";
8
8
  import { isOptInAgent } from "./protocol/agents/optIn";
9
9
  import { ProviderAuthPanel } from "./ProviderAuth";
10
10
  import type { AgentInfo, AgentInfoT, AgentsResponseT, AgentLoginT, ClaudeVerifyT } from "./types";
11
+ import { useRecheckOnReturn } from "./recheckOnReturn";
11
12
 
12
13
  const NUDGE_DISMISSED = "orch_agent_nudge_dismissed";
13
14
 
@@ -246,7 +247,8 @@ function BedrockConnect({ agent, onConnected, compatible = false }: { agent: Age
246
247
  // setting, or a device-code `aws sso login` for the SSO profile) and surfaces
247
248
  // the device URL + one-time code here. Clicking through lands on the IdP
248
249
  // (silent if that session is still live) then the AWS approval page; nothing is
249
- // pasted back — the command exits on approval and the poll flips to success.
250
+ // pasted back — the command exits on approval; coming back to this tab (or 检查状态)
251
+ // re-reads the login and flips it to success.
250
252
  function BedrockRefresh({ agent, onConnected }: { agent: AgentInfoT; onConnected?: () => void }) {
251
253
  const [login, setLogin] = useState<AgentLoginT | null>(null);
252
254
  const [busy, setBusy] = useState(false);
@@ -282,17 +284,15 @@ function BedrockRefresh({ agent, onConnected }: { agent: AgentInfoT; onConnected
282
284
  }
283
285
  };
284
286
 
285
- // Poll while the CLI waits for the browser-side approval.
286
- useEffect(() => {
287
- if (!login || (login.status !== "starting" && login.status !== "awaiting")) return;
288
- const t = setInterval(() => {
289
- jget<AgentLoginT>(base).then((l) => {
290
- setLogin(l);
291
- if (l.status === "success") succeed();
292
- }).catch(() => {});
293
- }, 1800);
294
- return () => clearInterval(t);
295
- }, [login, base, succeed]);
287
+ // Re-check while the CLI waits for the browser-side approval — whenever the user
288
+ // comes back to this tab, or presses 检查状态 (useRecheckOnReturn; no polling).
289
+ const checkLogin = () => {
290
+ jget<AgentLoginT>(base).then((l) => {
291
+ setLogin(l);
292
+ if (l.status === "success") succeed();
293
+ }).catch(() => {});
294
+ };
295
+ useRecheckOnReturn(!!login && (login.status === "starting" || login.status === "awaiting"), checkLogin);
296
296
 
297
297
  if (login?.status === "success") {
298
298
  return (
@@ -325,14 +325,14 @@ function BedrockRefresh({ agent, onConnected }: { agent: AgentInfoT; onConnected
325
325
  2. 如果页面要求输入验证码,请输入{login.code ? ":" : "页面上显示的验证码。"}
326
326
  </div>
327
327
  {login.code && <div className="ctx-mono" style={{ fontSize: 20, letterSpacing: 2, margin: "8px 0 2px", fontWeight: 600 }}>{login.code}</div>}
328
- <div className="wiz-verify" style={{ marginTop: 10 }}><span className="wiz-spin" /> <span>等待你在浏览器中确认…</span></div>
328
+ <div className="wiz-verify" style={{ marginTop: 10 }}><span className="wiz-spin" /> <span>等待你在浏览器中确认…回到这个页面时会自动检查。</span> <button className="linkbtn" onClick={checkLogin}>检查状态</button></div>
329
329
  <LogToggle log={login.log} show={showLog} setShow={setShowLog} />
330
330
  </div>
331
331
  );
332
332
  }
333
333
 
334
334
  if (login?.status === "starting") {
335
- return <div className="wiz-verify" style={{ marginTop: 12 }}><span className="wiz-spin" /> <span>正在启动 AWS 刷新…获取登录链接。</span></div>;
335
+ return <div className="wiz-verify" style={{ marginTop: 12 }}><span className="wiz-spin" /> <span>正在启动 AWS 刷新…获取登录链接。</span> <button className="linkbtn" onClick={checkLogin}>检查状态</button></div>;
336
336
  }
337
337
 
338
338
  // idle — the refresh CTA under the verify button
@@ -427,18 +427,16 @@ function SubscriptionConnect({ agent, onConnected, compact }: { agent: AgentInfo
427
427
  }
428
428
  };
429
429
 
430
- // Poll while the CLI waits for the user to authorize / exchange the code.
431
- useEffect(() => {
432
- if (checkingAuth || (existingAuth?.authenticated && !chooseLogin)) return;
433
- if (!login || (login.status !== "starting" && login.status !== "awaiting" && login.status !== "submitting")) return;
434
- const t = setInterval(() => {
435
- jget<AgentLoginT>(base).then((l) => {
436
- setLogin(l);
437
- if (l.status === "success") succeed();
438
- }).catch(() => {});
439
- }, 1800);
440
- return () => clearInterval(t);
441
- }, [login, base, succeed, checkingAuth, existingAuth, chooseLogin]);
430
+ // Re-check while the CLI waits for the user to authorize / exchange the code —
431
+ // whenever the user comes back to this tab, or presses 检查状态 (no polling).
432
+ const checkLogin = () => {
433
+ jget<AgentLoginT>(base).then((l) => {
434
+ setLogin(l);
435
+ if (l.status === "success") succeed();
436
+ }).catch(() => {});
437
+ };
438
+ useRecheckOnReturn(!checkingAuth && !(existingAuth?.authenticated && !chooseLogin) && !!login
439
+ && (login.status === "starting" || login.status === "awaiting" || login.status === "submitting"), checkLogin);
442
440
 
443
441
  const submitCode = async () => {
444
442
  if (!code.trim()) return;
@@ -516,6 +514,7 @@ function SubscriptionConnect({ agent, onConnected, compact }: { agent: AgentInfo
516
514
  {login.status === "submitting" || busy ? "验证中…" : "提交"}
517
515
  </button>
518
516
  </div>
517
+ {login.status === "submitting" && <div className="hlp" style={{ marginTop: 6 }}>正在验证授权码… <button className="linkbtn" onClick={checkLogin}>检查状态</button></div>}
519
518
  </>
520
519
  ) : (
521
520
  <>
@@ -523,7 +522,7 @@ function SubscriptionConnect({ agent, onConnected, compact }: { agent: AgentInfo
523
522
  2. 出现提示时,输入这个一次性验证码{login.code ? "" : "(显示在登录页上)"}:
524
523
  </div>
525
524
  {login.code && <div className="ctx-mono" style={{ fontSize: 20, letterSpacing: 2, margin: "8px 0 2px", fontWeight: 600 }}>{login.code}</div>}
526
- <div className="wiz-verify" style={{ marginTop: 10 }}><span className="wiz-spin" /> <span>等待你在浏览器中完成授权…</span></div>
525
+ <div className="wiz-verify" style={{ marginTop: 10 }}><span className="wiz-spin" /> <span>等待你在浏览器中完成授权…回到这个页面时会自动检查。</span> <button className="linkbtn" onClick={checkLogin}>检查状态</button></div>
527
526
  </>
528
527
  )}
529
528
  <LogToggle log={login.log} show={showLog} setShow={setShowLog} />
@@ -532,7 +531,7 @@ function SubscriptionConnect({ agent, onConnected, compact }: { agent: AgentInfo
532
531
  }
533
532
 
534
533
  if (login?.status === "starting") {
535
- return <div className="wiz-verify"><span className="wiz-spin" /> <span>正在启动登录…准备授权链接。</span></div>;
534
+ return <div className="wiz-verify"><span className="wiz-spin" /> <span>正在启动登录…准备授权链接。</span> <button className="linkbtn" onClick={checkLogin}>检查状态</button></div>;
536
535
  }
537
536
 
538
537
  // idle — initial CTA
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
 
3
- import { Icon } from "./icons";
3
+ import { Icon } from "../../ui/icons";
4
4
  import type { Appearance } from "./types";
5
5
 
6
6
  export function AppearancePanel({ appearance, setAppearance, onClose }: { appearance: Appearance; setAppearance: (k: keyof Appearance, v: string) => void; onClose: () => void }) {
@@ -7,13 +7,14 @@ import { BranchNavigator } from "./BranchNavigator";
7
7
  import { branchAncestry, messagesAtFork, type BranchStep } from "./branchFlow";
8
8
  import { agentLabel } from "./agents";
9
9
  import { jget } from "./api";
10
+ import { documentRequest } from "../../core/documentUpload";
10
11
  import { ErrNote, LoadNote } from "./shared";
11
12
  import type { AgentsBundle, Msg, TaskRow } from "./types";
12
13
 
13
- type History = { messages?: Msg[]; error?: string };
14
+ type History = { messages?: Msg[]; error?: string; workspaceRoot?: string };
14
15
  // Reusing a common prefix keeps branch switches immediate. Keys include the
15
16
  // source version; failures are retryable and never become permanent cache hits.
16
- const cache = new Map<string, Msg[]>();
17
+ const cache = new Map<string, { messages: Msg[]; workspaceRoot?: string }>();
17
18
  const keyFor = (source: TaskRow) => `${source.id}:${source.updated_at}`;
18
19
 
19
20
  export function useBranchHistory(task: TaskRow, tasks: TaskRow[]) {
@@ -27,12 +28,15 @@ export function useBranchHistory(task: TaskRow, tasks: TaskRow[]) {
27
28
  if (!source || cache.has(keyFor(source))) continue;
28
29
  const key = keyFor(source);
29
30
  setLoaded((prev) => ({ ...prev, [key]: {} }));
30
- void jget<TaskRow & { messages: (Msg & { created_at?: number })[] }>(`/api/tasks/${source.id}`).then((data) => {
31
+ const root = documentRequest<{ workspaceRoot?: string }>(fetch, `/api/tasks/${encodeURIComponent(source.id)}/file-sync/capabilities`, { signal: AbortSignal.timeout(5_000) }).catch(() => null);
32
+ void jget<TaskRow & { messages: (Msg & { created_at?: number })[] }>(`/api/tasks/${source.id}`).then(async (data) => {
31
33
  if (data.project_id !== task.project_id) throw new Error("来源会话不属于当前项目。");
32
34
  const messages = data.messages.map((m) => ({ ...m, ts: m.created_at ?? m.ts }));
33
- cache.set(key, messages);
35
+ const capabilities = await root;
36
+ const history = { messages, ...(typeof capabilities?.workspaceRoot === "string" ? { workspaceRoot: capabilities.workspaceRoot } : {}) };
37
+ cache.set(key, history);
34
38
  while (cache.size > 24) cache.delete(cache.keys().next().value!);
35
- if (!dead) setLoaded((prev) => ({ ...prev, [key]: { messages } }));
39
+ if (!dead) setLoaded((prev) => ({ ...prev, [key]: history }));
36
40
  }).catch((error: unknown) => {
37
41
  if (!dead) setLoaded((prev) => ({ ...prev, [key]: { error: error instanceof Error ? error.message : "来源会话加载失败" } }));
38
42
  });
@@ -42,7 +46,7 @@ export function useBranchHistory(task: TaskRow, tasks: TaskRow[]) {
42
46
  // array identity from the selected task's live stream.
43
47
  // eslint-disable-next-line react-hooks/exhaustive-deps
44
48
  }, [signature, retry]);
45
- const entries = steps.map((step) => ({ ...step, history: step.source ? { ...loaded[keyFor(step.source)], ...(cache.has(keyFor(step.source)) ? { messages: cache.get(keyFor(step.source)) } : {}) } : {} }));
49
+ const entries = steps.map((step) => ({ ...step, history: step.source ? { ...loaded[keyFor(step.source)], ...cache.get(keyFor(step.source)) } : {} }));
46
50
  return { entries, ready: entries.every(({ source, history }) => !source || !!history.messages || !!history.error), retry: () => setRetry((n) => n + 1) };
47
51
  }
48
52
 
@@ -59,7 +63,7 @@ export function BranchHistory({ entries, tasks, agents, onSelect, onQuote, onRet
59
63
  : <FileLinkContext.Provider value={{taskId:source.id}}>{buildSessions(messagesAtFork(history.messages, child)).map((session, si) => <div key={session.n}>
60
64
  {si > 0 && session.summaryBefore && <SessionBreak summary={session.summaryBefore} />}
61
65
  <div className="session-label"><span className="ln" />第 {session.n} 次会话 · 派生前<span className="ln" /></div>
62
- {session.messages.map((m, mi) => <MessageView key={m.id} m={m} initial={mi === 0 && m.role === "user"} hideWho={m.role === "assistant" && ["assistant", "tool"].includes(session.messages[mi - 1]?.role)} agent={source.agent} agentLabel={agentLabel(agents, source.agent)} readOnly onQuote={(msg, selected) => onQuote(msg, source, selected)} />)}
66
+ {session.messages.map((m, mi) => <MessageView key={m.id} m={m} initial={mi === 0 && m.role === "user"} hideWho={m.role === "assistant" && ["assistant", "tool"].includes(session.messages[mi - 1]?.role)} agent={source.agent} agentLabel={agentLabel(agents, source.agent)} readOnly attachmentScope={{taskId:source.id,workspaceRoot:history.workspaceRoot}} onQuote={(msg, selected) => onQuote(msg, source, selected)} />)}
63
67
  </div>)}</FileLinkContext.Provider>}
64
68
  </section>
65
69
  <BranchNavigator sourceId={child.parent_task_id!} projectId={child.project_id} tasks={tasks} selected={child} onSelect={onSelect} />
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { useEffect, useRef } from "react";
3
- import { Icon } from "./icons";
3
+ import { Icon } from "../../ui/icons";
4
4
  import { SLABEL, type TaskRow } from "./types";
5
5
  import { branchOptions } from "./branchFlow";
6
6
 
@@ -1,6 +1,6 @@
1
1
  "use client";
2
2
  import { useMemo, useState } from "react";
3
- import { Icon } from "./icons";
3
+ import { Icon } from "../../ui/icons";
4
4
  import { BrowserPane as BrowserSurface } from "../../board/BrowserPane";
5
5
  import { createOperatorBoardBackend } from "./boardBackend";
6
6
  import type { BrowserStatus } from "../../core/types";
@@ -102,8 +102,8 @@ function LoginProfiles() {
102
102
  );
103
103
  }
104
104
 
105
- export function BrowserPane({ taskId, popup=false, onQuote, onQuoteText, onPage }: {
106
- taskId:string; popup?:boolean; onQuote?:(page:{url:string;title:string})=>void;
105
+ export function BrowserPane({ taskId, popup=false, readOnly=false, onQuote, onQuoteText, onPage }: {
106
+ taskId:string; popup?:boolean; readOnly?:boolean; onQuote?:(page:{url:string;title:string})=>void;
107
107
  onQuoteText?:(text:string,page:{url:string;title:string})=>void;
108
108
  onPage?:(page:{url:string;title:string}|null)=>void;
109
109
  }) {
@@ -111,15 +111,15 @@ export function BrowserPane({ taskId, popup=false, onQuote, onQuoteText, onPage
111
111
  const [busy,setBusy]=useState(false);
112
112
  const [error,setError]=useState<string|null>(null);
113
113
  const localAction=async(status:BrowserStatus,update:(status:BrowserStatus)=>void)=>{
114
- if(busy)return;setBusy(true);setError(null);
114
+ if(readOnly||busy)return;setBusy(true);setError(null);
115
115
  try{
116
116
  const response=await fetch(`/api/tasks/${encodeURIComponent(taskId)}/browser`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({action:status.shownLocally?'park':'show'})});
117
117
  const result=await response.json();if(!response.ok)throw new Error(result.error||`操作失败(${response.status})`);if(result.state)update(result);
118
118
  }catch(error){setError(error instanceof Error?error.message:String(error));}finally{setBusy(false);}
119
119
  };
120
- return <BrowserSurface key={taskId} backend={backend} jobId={taskId} className={popup?'bp-popup':undefined} onQuote={onQuote} onQuoteText={onQuoteText} onPage={onPage}
121
- footer={!popup?<LoginProfiles/>:undefined} extension={(status,update)=><>
122
- {status.state==='running'&&<div className="bp-row">
120
+ return <BrowserSurface readOnly={readOnly} key={taskId} backend={backend} jobId={taskId} className={popup?'bp-popup':undefined} onQuote={onQuote} onQuoteText={onQuoteText} onPage={onPage}
121
+ footer={!popup&&!readOnly?<LoginProfiles/>:undefined} extension={(status,update)=><>
122
+ {!readOnly&&status.state==='running'&&<div className="bp-row">
123
123
  {!popup&&<button className="btn btn-line btn-sm" onClick={()=>window.open(`/browser/${encodeURIComponent(taskId)}`,`browser-${taskId}`,'width=1320,height=960')}>{Icon.external()} 弹出窗口</button>}
124
124
  <button className="btn btn-ghost btn-sm" disabled={busy} onClick={()=>void localAction(status,update)}>{status.shownLocally?'收起节点上的窗口':'在节点屏幕上显示'}</button>
125
125
  </div>}