@spzxg/cli-ui 0.6.12 → 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 (106) hide show
  1. package/CHANGELOG.md +111 -2
  2. package/README.md +131 -7
  3. package/dist/{cli-ui-embed-B0HDalUb.js → cli-ui-embed-REq-GvM7.js} +20751 -20260
  4. package/dist/{cli-ui-index-B0juE2Jq.js → cli-ui-index-p_XTnmsN.js} +2 -2
  5. package/dist/{cli-ui-jszip.min-BBS0YWg7.js → cli-ui-jszip.min-0mqaiYeK.js} +1 -1
  6. package/dist/{cli-ui-jszip.min-CSeehR5Z.js → cli-ui-jszip.min-CJa9yrKW.js} +2 -2
  7. package/dist/{cli-ui-xlsx-Bk3fo5jQ.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 +64 -30
  14. package/src/board/FileViewer.tsx +52 -16
  15. package/src/board/FilesPane.tsx +1 -1
  16. package/src/board/context.ts +38 -7
  17. package/src/board/diffLines.ts +46 -0
  18. package/src/board/diffRefresh.ts +63 -0
  19. package/src/board/fileDiff.tsx +117 -0
  20. package/src/board/fileKind.ts +5 -3
  21. package/src/board/fileScope.ts +9 -4
  22. package/src/board/fileSync.ts +12 -4
  23. package/src/board/fileSyncProcessor.ts +4 -3
  24. package/src/board/fileSyncTransport.ts +2 -2
  25. package/src/board/fileWatch.ts +94 -28
  26. package/src/board/linkage.ts +68 -0
  27. package/src/board/pathResolve.ts +108 -0
  28. package/src/board/useBoardUpload.tsx +7 -7
  29. package/src/board/workspace.ts +7 -1
  30. package/src/chat/CliChat.tsx +197 -216
  31. package/src/chat/Composer.tsx +10 -9
  32. package/src/chat/queueEdit.ts +27 -0
  33. package/src/components.tsx +2 -2
  34. package/src/core/blocks.ts +4 -1
  35. package/src/core/client.ts +86 -9
  36. package/src/core/config.ts +1 -1
  37. package/src/core/conversation.ts +23 -5
  38. package/src/core/documentUpload.ts +22 -5
  39. package/src/core/identity.ts +2 -14
  40. package/src/core/provider.tsx +14 -8
  41. package/src/core/sha256.ts +21 -0
  42. package/src/core/store.ts +307 -63
  43. package/src/core/types.ts +49 -0
  44. package/src/elements.tsx +8 -5
  45. package/src/msglist/CliMsgList.tsx +30 -9
  46. package/src/operator/node/AgentConnect.tsx +28 -29
  47. package/src/operator/node/AppearancePanel.tsx +1 -1
  48. package/src/operator/node/BranchHistory.tsx +11 -7
  49. package/src/operator/node/BranchNavigator.tsx +1 -1
  50. package/src/operator/node/BrowserPane.tsx +7 -7
  51. package/src/operator/node/Chat.tsx +53 -272
  52. package/src/operator/node/CommandPalette.tsx +1 -1
  53. package/src/operator/node/Composer.tsx +13 -6
  54. package/src/operator/node/Layout.tsx +4 -2
  55. package/src/operator/node/Markdown.tsx +6 -36
  56. package/src/operator/node/Modal.tsx +1 -1
  57. package/src/operator/node/OnboardingWizard.tsx +11 -9
  58. package/src/operator/node/Orchestrator.tsx +18 -8
  59. package/src/operator/node/ProjectLanding.tsx +1 -1
  60. package/src/operator/node/ProjectsColumn.tsx +1 -1
  61. package/src/operator/node/ProviderAuth.tsx +16 -16
  62. package/src/operator/node/RunSwitch.tsx +1 -1
  63. package/src/operator/node/Services.tsx +1 -1
  64. package/src/operator/node/SessionRail.tsx +57 -21
  65. package/src/operator/node/SessionView.tsx +18 -16
  66. package/src/operator/node/SettingsView.tsx +1 -1
  67. package/src/operator/node/TaskBoard.tsx +1 -1
  68. package/src/operator/node/TaskChanges.tsx +83 -108
  69. package/src/operator/node/TaskHero.tsx +5 -5
  70. package/src/operator/node/TasksColumn.tsx +1 -1
  71. package/src/operator/node/Transcript.tsx +15 -250
  72. package/src/operator/node/Welcome.tsx +1 -1
  73. package/src/operator/node/WorktreePrune.tsx +1 -1
  74. package/src/operator/node/api.ts +17 -0
  75. package/src/operator/node/boardBackend.ts +4 -1
  76. package/src/operator/node/boardEvents.ts +17 -3
  77. package/src/operator/node/boardInteraction.ts +7 -4
  78. package/src/operator/node/boardState.ts +23 -14
  79. package/src/operator/node/composerDraft.ts +22 -0
  80. package/src/operator/node/fileLinks.ts +4 -38
  81. package/src/operator/node/format.ts +13 -104
  82. package/src/operator/node/github.tsx +14 -14
  83. package/src/operator/node/liveStream.ts +47 -6
  84. package/src/operator/node/modals.tsx +59 -22
  85. package/src/operator/node/recheckOnReturn.ts +28 -0
  86. package/src/operator/node/shared.tsx +10 -50
  87. package/src/operator/node/types.ts +9 -0
  88. package/src/operator/node/useOrchestrator.ts +9 -8
  89. package/src/operator/node/useRecaps.ts +15 -4
  90. package/src/operator/node/useTaskStream.ts +2 -2
  91. package/src/operator.base.css +13 -2
  92. package/src/operator.css +13 -2
  93. package/src/styles.css +22 -8
  94. package/src/ui/Markdown.tsx +36 -21
  95. package/src/ui/Popover.tsx +1 -1
  96. package/src/ui/QueuedMessages.tsx +58 -15
  97. package/src/ui/SubagentChat.tsx +42 -6
  98. package/src/ui/Transcript.tsx +19 -14
  99. package/src/ui/fileLinks.ts +6 -3
  100. package/src/ui/format.ts +27 -9
  101. package/src/ui/icons.tsx +2 -0
  102. package/src/ui/shared.tsx +11 -7
  103. package/src/ui/transcriptModel.ts +40 -9
  104. package/src/ui/useTranscriptWindow.ts +253 -0
  105. package/src/operator/node/icons.tsx +0 -88
  106. package/src/operator/node/transcriptModel.ts +0 -129
@@ -1,4 +1,4 @@
1
- import { retryWorkspaceFiles } from "./fileWatch";
1
+ import { notifyWorkspaceFileCreated, retryWorkspaceFiles } from "./fileWatch";
2
2
  import { retainFileScope } from "./fileScope";
3
3
  // cli-board:右侧看板。界面取自 Operator 的会话右栏(SessionRail):文件 / 改动 / 浏览器三个页签。
4
4
  // 数据经 center 的 /api/jobs/:id/board、files、diff、browser 转发自执行节点(浏览器不直连节点)。
@@ -9,25 +9,27 @@ import { retainFileScope } from "./fileScope";
9
9
  //
10
10
  // 同步:每轮实时输出结束、恢复页面或手动刷新时检查打开的文件,只读取缺失变化块;没有周期轮询。
11
11
  // 和 cli-chat 放在同一个 Provider 里时,对话里点本地文件 / 「查看浏览器」会在这里打开(store.openInBoard)。
12
- import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
12
+ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
13
13
  import { createPortal } from "react-dom";
14
14
  import { CliErrorBoundary } from "../ui/ErrorBoundary";
15
15
  import type { BoardRef, CliEvent, CliStore, CliStoreOptions, OpenTarget } from "../core/store";
16
16
  import { useCliState, useCliStore, useCliStoreContext, useComponentEvents, withOwnProvider } from "../core/provider";
17
- import { convKey, parseConvKey, isRunning } from "../core/conversation";
17
+ import { convKey, parseConvKey, isRunning, TERMINAL_JOB } from "../core/conversation";
18
18
  import type { BoardInfo, FileEntry } from "../core/types";
19
19
  import { Icon } from "../ui/icons";
20
20
  import { FileViewer, type FileAction } from "./FileViewer";
21
21
  import { FilesPane } from "./FilesPane";
22
22
  import { ChangesPane } from "./ChangesPane";
23
23
  import { BrowserPane } from "./BrowserPane";
24
- import { rememberBoardFile } from "./context";
24
+ import { rememberBoardFile, withBoardPaths } from "./context";
25
+ import { workspaceFileDirectory } from "../core/documentUpload";
25
26
  import type { BoardFile } from "./workspace";
26
27
  import type { WorkspaceHandlers } from "../core/provider";
27
28
  import { useBoardPanels } from "./panels";
28
29
  import { PanelControls, PanelTab, type InlineBoardLayout } from "./PanelControls";
29
30
  import { useBoardVisibility } from "./useBoardVisibility";
30
31
  import { useBoardUpload } from "./useBoardUpload";
32
+ import { pathHints, resolveMissingPath } from "./pathResolve";
31
33
 
32
34
  export type BoardTab = "files" | "changes" | "browser";
33
35
 
@@ -101,7 +103,7 @@ export interface CliBoardProps extends CliStoreOptions, WorkspaceHandlers {
101
103
  * 缺省和 quoteToChat 一样。
102
104
  */
103
105
  autoQuoteOpenFile?: boolean;
104
- /** 给了就在页签栏右侧显示「隐藏面板」按钮。 */
106
+ /** 保留旧宿主兼容;看板不再显示内置收起按钮。 */
105
107
  onCollapse?: () => void;
106
108
  /**
107
109
  * 收起状态:只显示一条窄栏(点一下展开)。收起时仍然接对话里的打开请求——接到就记下要打开的东西并调 onExpand,
@@ -118,14 +120,15 @@ export interface CliBoardProps extends CliStoreOptions, WorkspaceHandlers {
118
120
  store?: CliStore;
119
121
  }
120
122
 
121
- export function CliBoard(props: CliBoardProps) {
123
+ // memo:嵌在对话里的看板不随对话的每次重画(流式输出时每来一块一次)重画,只在参数变了时才重画。
124
+ export const CliBoard = memo(function CliBoard(props: CliBoardProps) {
122
125
  const ctx = useCliStoreContext();
123
126
  return <CliErrorBoundary component="cli-board" theme={props.theme}>{withOwnProvider(props, <BoardInner {...props} inProvider={!!ctx} />, !!ctx)}</CliErrorBoundary>;
124
- }
127
+ });
125
128
 
126
- interface OpenFile { name?: string; reloadKey?:number; path: string; size?: number; mtime?: number; version: number }
129
+ interface OpenFile { name?: string; reloadKey?:number; path: string; size?: number; mtime?: number; version: number; /** 由对话里写的这个相对路径补全来的。 */ resolvedFrom?: string }
127
130
 
128
- function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs, defaultTab, readOnly, fileActions, acceptOpen = true, quoteToChat, autoQuoteOpenFile, extraTabs, onCollapse, collapsed, onExpand, onNavigate, onEvent, onFilesChange, onFilesWatch, onBoardContextChange, watchFiles = true, fileWatchIntervalMs, theme = "light", className, style, inProvider, inlineLayout, inlineOwner, visible: visibilityOverride, onQuoteToChat }: CliBoardProps & { inProvider: boolean }) {
131
+ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs, defaultTab, readOnly, fileActions, acceptOpen = true, quoteToChat, autoQuoteOpenFile, extraTabs, collapsed, onExpand, onNavigate, onEvent, onFilesChange, onFilesWatch, onBoardContextChange, watchFiles = true, fileWatchIntervalMs, theme = "light", className, style, inProvider, inlineLayout, inlineOwner, visible: visibilityOverride, onQuoteToChat }: CliBoardProps & { inProvider: boolean }) {
129
132
  useComponentEvents(onEvent, {onFilesChange,onFilesWatch,onBoardContextChange}, inProvider);
130
133
  const store = useCliStore();
131
134
  const backend = store.client.board;
@@ -143,6 +146,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
143
146
 
144
147
  const storageId = jobId && store.draftScope ? `${store.draftScope}:${jobId}` : jobId;
145
148
  const [info, setInfo] = useState<BoardInfo | null>(null);
149
+ const workspaceRootRef=useRef(info?.workspaceRoot);workspaceRootRef.current=info?.workspaceRoot;
146
150
  const [infoError, setInfoError] = useState<string | null>(null);
147
151
  // 页签:内置的(文件列表 / 改动 / 浏览器)、打开的文件(file:<路径>,可以开多个、可以关)、宿主加的。
148
152
  const [tab, setTab] = useState<string>(defaultTab ?? tabs?.[0] ?? "files");
@@ -153,10 +157,12 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
153
157
  const [tick, setTick] = useState(0);
154
158
 
155
159
  // 换了对话:回到初始状态。
160
+ // 对话里写的相对路径 → 补全后确实存在的路径(这个对话里再点同一个链接直接打开补全后的)。
161
+ const aliases = useRef(new Map<string, string>());
156
162
  const lastJob = useRef(jobId);
157
163
  if (lastJob.current !== jobId) {
158
164
  lastJob.current = jobId;
159
- setInfo(null); setInfoError(null); setDir(""); setFiles([]); setHistory([]);
165
+ setInfo(null); setInfoError(null); setDir(""); setFiles([]); setHistory([]); aliases.current.clear();
160
166
  setTab(defaultTab ?? tabs?.[0] ?? "files");
161
167
  }
162
168
  // 恢复上次开着的文件页签(存在 sessionStorage):挂上之后、绘制之前做——服务端渲染和首次渲染一致,不会对不上。
@@ -166,12 +172,18 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
166
172
 
167
173
  // 实时流:看板单独用时也要知道任务在不在跑(同一对话只连一次)。
168
174
  useEffect(() => (jobId ? store.open(jobId) : undefined), [store, jobId]);
169
- const conv = useCliState((s) => (jobId ? s.convs[jobId] : undefined));
170
- const running = conv ? isRunning(conv) : false;
171
- // 进展签名:轮次状态 + 看的子任务(一次性任务没有轮次:续派开出新子任务、派发到节点、换了节点对话都要重查看板概况)+ 转录条数。变了就刷新(节流)。
172
- const statusKey = conv
173
- ? `${conv.turns.map((t) => `${t.turn_id}:${t.status}`).join(",")}|${conv.job?.status ?? ""}|${conv.task?.id ?? ""}:${conv.task?.status ?? ""}:${conv.remoteTaskId ?? conv.task?.remote_task_id ?? ""}`
174
- : "";
175
+ // 只订阅看板用得到的几个值(不是整个对话):智能体流式输出时对话每来一块都会变,看板不跟着重画。
176
+ const running = useCliState((s) => { const conv = jobId ? s.convs[jobId] : undefined; return conv ? isRunning(conv) : false; });
177
+ // 看板概况(派发到哪个节点、节点上的会话、有没有文件 / 浏览器)只在这些变了时重查:派发到节点(节点、开始执行过没有)、
178
+ // 任务结束、看的子任务或它在节点上的会话换了(续派、重建)。每一轮的排队 → 执行 → 结束不影响概况,不重查。
179
+ const statusKey = useCliState((s) => {
180
+ const conv = jobId ? s.convs[jobId] : undefined;
181
+ if (!conv) return "";
182
+ const started = conv.turns.some((t) => !!t.started_at || t.status === "running" || t.status === "dispatching") || !!conv.batchTask?.remote_task_id;
183
+ return `${conv.job?.node_id ?? ""}|${started}|${TERMINAL_JOB.has(conv.job?.status ?? "")}|${conv.task?.id ?? ""}:${conv.remoteTaskId ?? conv.task?.remote_task_id ?? ""}`;
184
+ });
185
+ const settled = useCliState((s) => (jobId ? s.convs[jobId]?.settled ?? 0 : 0));
186
+ const edits = useCliState((s) => (jobId ? s.convs[jobId]?.edits ?? 0 : 0));
175
187
  const bump = useCallback(() => setTick((n) => n + 1), []);
176
188
  const [manual, setManual] = useState(0);
177
189
  const refreshAll = useCallback(() => {
@@ -190,7 +202,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
190
202
  let alive = true;
191
203
  void backend.info(jobId).then((i) => {
192
204
  if (!alive) return;
193
- setInfo((old) => (old && old.dispatched === i.dispatched && old.remote_task_id === i.remote_task_id && old.files === i.files && old.browser === i.browser && old.node?.health === i.node?.health ? old : i));
205
+ setInfo((old) => (old && old.dispatched === i.dispatched && old.remote_task_id === i.remote_task_id && old.workspaceRoot === i.workspaceRoot && old.files === i.files && old.browser === i.browser && old.node?.health === i.node?.health ? old : i));
194
206
  setInfoError(null);
195
207
  }, (e: unknown) => { if (alive) setInfoError(e instanceof Error ? e.message : String(e)); });
196
208
  return () => { alive = false; };
@@ -220,6 +232,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
220
232
  const shownTabs = [...panels.open, ...(builtinTabs.includes("files") ? files.map(f => fileTabId(f.path)) : [])];
221
233
  const activeTab = shownTabs.includes(tab) ? tab : shownTabs[0] ?? "";
222
234
  const file = activeTab.startsWith(FILE_TAB) ? files.find((f) => fileTabId(f.path) === activeTab) ?? null : null;
235
+ useEffect(()=>{if(file){const parent=workspaceFileDirectory(file.path,info?.workspaceRoot);if(parent!==undefined)setDir(parent);}},[file?.path,info?.workspaceRoot]);
223
236
  useEffect(()=>{if(file&&jobId)setHistory(previous=>{const next=rememberBoardFile(previous,{path:file.path,sourceId:jobId});return JSON.stringify(next)===JSON.stringify(previous)?previous:next;});},[file?.path,jobId]);
224
237
  const tabLabel = (t: string) => TAB_LABEL[t as BoardTab] ?? (t.startsWith(FILE_TAB) ? files.find(file => file.path === t.slice(FILE_TAB.length))?.name || t.slice(FILE_TAB.length).split("/").pop() || t : undefined) ?? extraTabs?.find((x) => x.id === t)?.label ?? t;
225
238
  // 页签多了横向滚动:当前页签总是滚到看得见的地方(新开的文件页签在最后,窄看板里容易被挤出去)。
@@ -284,7 +297,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
284
297
  }, [store, jobId, owner, visible, isInline, availableTabs?.join(","), readOnly]); // eslint-disable-line react-hooks/exhaustive-deps
285
298
  useIsoLayoutEffect(() => () => { if (jobId && !isInline) store.reportBoardPresence(jobId, owner, null); }, [store, jobId, owner, isInline]);
286
299
  useEffect(() => {
287
- if (!jobId || !autoView) return;
300
+ if (!jobId) return;
288
301
  store.setViewing(jobId, viewingPath
289
302
  ? { id: `file:${viewingPath}`, kind: "file", label: viewingPath.split("/").pop() || viewingPath, text: `用户当前在看板里打开着工作区文件 ${viewingPath}` }
290
303
  : viewingPage
@@ -319,12 +332,14 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
319
332
  activeRef.current = activeTab;
320
333
  /** 打开文件:已经开着就切过去(并重读),否则新开一个页签;超过 MAX_FILE_TABS 关掉最早的(不关正在看的)。 */
321
334
  const openPath = useCallback((path: string, entry?: Partial<FileEntry>) => {
322
- const clean = path.replace(/^\.\//, "").replace(/\/+$/, "");
323
- if (!clean) return;
335
+ const requested = path.replace(/^\.\//, "").replace(/\/+$/, "");
336
+ if (!requested) return;
337
+ const clean = aliases.current.get(requested) ?? requested;
338
+ const resolvedFrom = clean !== requested ? requested : undefined;
324
339
  setFiles((list) => {
325
340
  const have = list.find((f) => f.path === clean);
326
341
  if (have) return list.map((f) => (f.path === clean ? { ...f, name: entry?.name ?? f.name, size: entry?.size ?? f.size, mtime: entry?.mtime ?? f.mtime, version: f.version + 1 } : f));
327
- const next = [...list, { path: clean, name: entry?.name, size: entry?.size, mtime: entry?.mtime, version: 0 }];
342
+ const next = [...list, { path: clean, name: entry?.name, size: entry?.size, mtime: entry?.mtime, version: 0, ...(resolvedFrom ? { resolvedFrom } : {}) }];
328
343
  while (next.length > MAX_FILE_TABS) {
329
344
  const i = next.findIndex((f) => fileTabId(f.path) !== activeRef.current && f.path !== clean);
330
345
  next.splice(i >= 0 ? i : 0, 1);
@@ -332,16 +347,35 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
332
347
  return next;
333
348
  });
334
349
  setTab(fileTabId(clean));
335
- const parent = clean.includes("/") && !clean.startsWith("/") ? clean.split("/").slice(0, -1).join("/") : "";
336
- setDir(parent);
350
+ setDir(previous=>workspaceFileDirectory(clean,workspaceRootRef.current)??previous);
351
+ }, []);
352
+ /** 打不开的相对路径换成补全后的:原来的页签原地换成新路径(已经开着就切过去),以后再点同一个链接直接打开它。 */
353
+ const replacePath = useCallback((from: string, to: string) => {
354
+ aliases.current.set(from, to);
355
+ setFiles((list) => {
356
+ const old = list.find((f) => f.path === from);
357
+ const resolvedFrom = old?.resolvedFrom ?? from;
358
+ if (list.some((f) => f.path === to)) return list.filter((f) => f.path !== from).map((f) => (f.path === to ? { ...f, resolvedFrom: f.resolvedFrom ?? resolvedFrom } : f));
359
+ return list.map((f) => (f.path === from ? { path: to, version: 0, resolvedFrom } : f));
360
+ });
361
+ setTab(fileTabId(to));
362
+ setDir(previous=>workspaceFileDirectory(to,workspaceRootRef.current)??previous);
337
363
  }, []);
364
+ const historyRef = useRef(history); historyRef.current = history;
365
+ const resolveMissing = useCallback((path: string, signal: AbortSignal) => {
366
+ if (!backend || !jobId) return Promise.resolve([]);
367
+ const conv = store.getState().convs[jobId];
368
+ const seen = [...(store.getState().boardContext[jobId]?.history ?? []), ...historyRef.current].map((f) => f.path);
369
+ return resolveMissingPath(backend, jobId, path, pathHints(conv?.msgs ?? [], seen), signal);
370
+ }, [backend, jobId, store]);
338
371
  const uploadToWorkspace = useMemo(() => !readOnly && jobId && backend?.uploadFile
339
372
  ? (file: File, options: import("../core/documentUpload").DocumentUploadOptions) => backend.uploadFile!(jobId, file, options)
340
373
  : undefined, [backend, jobId, readOnly]);
341
374
  const upload = useBoardUpload(jobId, uploadToWorkspace, receipt => {
342
375
  openPath(receipt.path!, { name: receipt.name, size: receipt.size });
376
+ if (backend && jobId && receipt.path) notifyWorkspaceFileCreated(backend, jobId, receipt.path);
343
377
  setTick(value => value + 1);
344
- });
378
+ }, dir || ".");
345
379
  /** 关文件页签:关的是正在看的,就切到它旁边的文件页签,没有了回文件列表。 */
346
380
  const closeFile = useCallback((path: string) => {
347
381
  setFiles((list) => {
@@ -389,8 +423,8 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
389
423
  useEffect(() => {
390
424
  if (!jobId || restoreNeeded) return;
391
425
  const currentFile = isInline && !visible ? null : file;
392
- store.reportBoard(jobId, { tab: activeTab, dir, file: currentFile?.path ?? null, files: files.map(file=>file.path), current:file?{path:file.path,sourceId:jobId}:null,opened:files.map(file=>({path:file.path,sourceId:jobId})),history,browser:activeTab==="browser"?browserPage:null,visible,autoContext:autoQuoteOpenFile??canQuote }, owner);
393
- }, [store, jobId, activeTab, dir, file?.path, openPaths, history, browserPage, visible, autoQuoteOpenFile, canQuote, owner, restoreNeeded]);
426
+ store.reportBoard(jobId, withBoardPaths({ tab: activeTab, dir, directorySourceId: jobId, workspaceRoot: info?.workspaceRoot, remoteTaskId: info?.remote_task_id ?? undefined, file: currentFile?.path ?? null, files: files.map(file=>file.path), current:file?{path:file.path,sourceId:jobId}:null,opened:files.map(file=>({path:file.path,sourceId:jobId})),history,browser:activeTab==="browser"?browserPage:null,visible,autoContext:autoQuoteOpenFile??canQuote }, jobId), owner);
427
+ }, [store, jobId, activeTab, dir, file?.path, openPaths, history, browserPage, visible, autoQuoteOpenFile, canQuote, owner, restoreNeeded, info?.workspaceRoot, info?.remote_task_id]);
394
428
  useEffect(() => () => { if (jobId) store.reportBoard(jobId, null, owner); }, [store, jobId, owner]);
395
429
 
396
430
  const body = () => {
@@ -400,7 +434,7 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
400
434
  if (!info) return <div className="tc-note">{infoError ? <>读取看板失败:{infoError} <button className="cli-fv-btn" onClick={refreshAll}>重试</button></> : "读取中…"}</div>;
401
435
  if (!info.dispatched) return <div className="tc-note">任务还没开始执行({info.detail ?? "等待分配执行节点"})。开始后这里会显示工作区文件。</div>;
402
436
  if (!visible) return null;
403
- if (activeTab === "changes") return <ChangesPane key={jobId} backend={backend} jobId={jobId} refreshKey={tick} onOpen={(p) => openPath(p)} />;
437
+ if (activeTab === "changes") return <ChangesPane key={jobId} backend={backend} jobId={jobId} refreshKey={tick} settled={settled + manual} edits={edits} onOpen={(p) => openPath(p)} />;
404
438
  if (activeTab === "browser") {
405
439
  if (!visible) return null;
406
440
  return <BrowserPane key={`${jobId}:${info.remote_task_id}`} backend={backend} jobId={jobId} readOnly={readOnly}
@@ -428,7 +462,8 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
428
462
  actions={allFileActions}
429
463
  onOpenPath={(p) => openPath(p)}
430
464
  onQuoteText={canQuote ? (text, context) => quoteText(file.path, text, context) : undefined}
431
- onBack={() => { setDir(file.path.includes("/") ? file.path.slice(0, file.path.lastIndexOf("/")) : ""); panels.show("files"); setTab("files"); }}
465
+ onBack={() => { setDir(previous => workspaceFileDirectory(file.path, workspaceRootRef.current) ?? previous); panels.show("files"); setTab("files"); }}
466
+ resolveMissing={resolveMissing} onResolved={(to) => replacePath(file.path, to)} resolvedFrom={file.resolvedFrom}
432
467
  />
433
468
  );
434
469
  }
@@ -465,13 +500,12 @@ function BoardInner({ jobId: jobIdProp, taskId: taskIdProp, tabs, availableTabs,
465
500
  ))}
466
501
  </div>
467
502
  <PanelControls toolbarRef={setToolbarHost} available={allowedPanels} open={panels.open} label={tabLabel}
468
- upload={!readOnly && builtinTabs.includes("files") && uploadToWorkspace ? { onChoose: upload.choose, disabled: upload.busy || !info?.dispatched, hint: !info?.dispatched ? "工作区尚未就绪" : "保存到当前会话,不发送消息" } : undefined}
503
+ upload={!readOnly && builtinTabs.includes("files") && uploadToWorkspace ? { onChoose: upload.choose, disabled: upload.busy || !info?.dispatched, hint: !info?.dispatched ? "工作区尚未就绪" : "保存到当前目录,不发送消息" } : undefined}
469
504
  onShow={id => { panels.show(id); selectTab(id); }}
470
505
  onClose={id => { panels.close(id); if (activeTab === id) setTab(shownTabs.find(t => t !== id) ?? ""); }} />
471
506
  {info?.dispatched && !file && <button className="rail-collapse" onClick={refreshAll} title={running ? "运行中 · 本轮结束后同步,点击立即检查" : "刷新"}>
472
507
  <span className={`cli-sync-dot ${running ? "on" : ""}`} />↻
473
508
  </button>}
474
- {onCollapse && <button className="rail-collapse" onClick={onCollapse} title="隐藏面板">{Icon.chevRight()}</button>}
475
509
  </div>;
476
510
  return <>
477
511
  {inlineLayout?.tabsHost && createPortal(tabBar, inlineLayout.tabsHost)}
@@ -149,6 +149,15 @@ export interface FileViewerProps {
149
149
  toolbarHost?: HTMLElement | null;
150
150
  /** 给了就支持「选中文字 → 引用到对话」:在预览里选中一段文字时浮出按钮(Markdown / 代码 / 文本 / 表格 / HTML / Word,及各自的源文件)。 */
151
151
  onQuoteText?: (text: string, context?: { revision: string }) => void;
152
+ /**
153
+ * 打不开时(相对路径、后端说文件不存在)按对话里的线索补全:返回确实存在的候选路径(见 board/pathResolve.ts)。
154
+ * 只有一个就调 onResolved 直接换过去;有几个列出来让用户选。不给就只显示读取失败。
155
+ */
156
+ resolveMissing?: (path: string, signal: AbortSignal) => Promise<string[]>;
157
+ /** 换成补全后的路径打开。 */
158
+ onResolved?: (path: string) => void;
159
+ /** 这个文件是由对话里写的这个路径补全来的(显示一行说明)。 */
160
+ resolvedFrom?: string;
152
161
  }
153
162
 
154
163
  /** 选中的文字超过这么多只带开头(引用是给智能体指位置的,不是搬运全文)。 */
@@ -159,7 +168,7 @@ export function FileViewer(props:FileViewerProps) {
159
168
  let id=viewerBackendIds.get(props.backend);if(id===undefined){id=nextViewerBackendId++;viewerBackendIds.set(props.backend,id);}
160
169
  return <FileViewerInner key={JSON.stringify([id,props.jobId,props.path])} {...props}/>;
161
170
  }
162
- function FileViewerInner({ backend, jobId, path, displayName, size, mtime, version = 0, reloadKey, onOpenPath, onClose, lead, onBack, actions = [], bare, toolbarHost, onQuoteText }: FileViewerProps) {
171
+ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, version = 0, reloadKey, onOpenPath, onClose, lead, onBack, actions = [], bare, toolbarHost, onQuoteText, resolveMissing, onResolved, resolvedFrom }: FileViewerProps) {
163
172
  const name = displayName || path.split("/").pop() || path;
164
173
  const kind: PreviewKind = previewKind(path);
165
174
  const [loaded, setLoaded] = useState<Loaded | null>(null);
@@ -177,8 +186,8 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
177
186
  const htmlReading = kind === "html" && mode === "preview" && htmlPresentation === "reading";
178
187
  // 超大文本:看开头还是看末尾(日志看末尾)。
179
188
  const [tail, setTail] = useState(false);
180
- const progressiveText = !!backend.fileSync && (kind === "text" || kind === "code");
181
- const [textLimit, setTextLimit] = useState(kind === "html" || backend.fileSync && (kind === "markdown" || progressiveText) ? MARKDOWN_STEP : TEXT_MAX);
189
+ const progressiveText = kind === "csv" || !!backend.fileSync && (kind === "text" || kind === "code");
190
+ const [textLimit, setTextLimit] = useState(kind === "html" || progressiveText || backend.fileSync && kind === "markdown" ? MARKDOWN_STEP : TEXT_MAX);
182
191
  const [syncing, setSyncing] = useState(false);
183
192
  const [parsing, setParsing] = useState(false);
184
193
  const [cancelled, setCancelled] = useState(false);
@@ -188,9 +197,9 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
188
197
  const fileReadAbort = useRef<AbortController | null>(null);
189
198
  const readingAbort = useRef<AbortController | null>(null);
190
199
  const cancelRead = () => { fileReadAbort.current?.abort(); readingAbort.current?.abort(); setSyncing(false); setParsing(false); setCancelled(true); };
191
- useEffect(() => retainFileScope(backend, jobId, { paths: [path], dirs: [], onDenied: () => {
200
+ useEffect(() => retainFileScope(backend, jobId, { paths: [path], dirs: [], onDenied: message => {
192
201
  fileReadAbort.current?.abort(); readingAbort.current?.abort(); revisionRef.current = undefined;
193
- setLoaded(null); setHtmlDoc(null); setSyncing(false); setParsing(false); setError("文件访问权限已失效,请重新登录或检查任务权限");
202
+ setLoaded(null); setHtmlDoc(null); setSyncing(false); setParsing(false); setError(message || "文件访问受限,请检查任务文件目录或访问权限");
194
203
  } }), [backend, jobId, path]);
195
204
  // 放大:盖住页面看(看板窄的时候看报告、表格、图片)。Esc 还原。
196
205
  const [big, setBig] = useState(false);
@@ -401,7 +410,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
401
410
  textKey.current = key;
402
411
  if (!prev) setProgress(0);
403
412
  setSyncing(true);
404
- const max = htmlReading || backend.fileSync && (kind === "markdown" || progressiveText) ? textLimit : TEXT_MAX;
413
+ const max = htmlReading || progressiveText || backend.fileSync && kind === "markdown" ? textLimit : TEXT_MAX;
405
414
  const full = () => loadText(backend, jobId, path, { max, tail, preview: true, fresh: attempt > 0, signal: ctl.signal, onBytes: (n) => { if (alive && !prev) setProgress(n); } });
406
415
  (prev ? refreshText(backend, jobId, path, prev, max, { signal: ctl.signal, preview: true, fresh: attempt > 0 }).then((r) => r ?? full()) : full()).then(
407
416
  (r) => {
@@ -463,6 +472,24 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
463
472
  const shownSize = knownSize;
464
473
  const text = loaded?.kind === "text" ? loaded : null;
465
474
  const loading = !error && !src.error && (needsSrc ? (bridged ? htmlDoc === null : !src.url) : !loaded);
475
+ // 读取失败:相对路径可能是智能体相对它进入的子目录写的,按对话里的线索补全(resolveMissing 由看板 / 对话给)。
476
+ // 只确认存在的才算;找到唯一一个直接换过去,几个就列出来选。
477
+ const failed = !!((error && loaded?.kind !== "text" && !(htmlDoc && typeof htmlDoc === "object")) || src.error);
478
+ const [lookup, setLookup] = useState<{ state: "searching" } | { state: "done"; found: string[] } | null>(null);
479
+ const resolveRef = useRef(resolveMissing); resolveRef.current = resolveMissing;
480
+ const resolvedRef = useRef(onResolved); resolvedRef.current = onResolved;
481
+ useEffect(() => {
482
+ setLookup(null);
483
+ if (!failed || !resolveRef.current) return;
484
+ const ctl = new AbortController();
485
+ setLookup({ state: "searching" });
486
+ resolveRef.current(path, ctl.signal).then((found) => {
487
+ if (ctl.signal.aborted) return;
488
+ if (found.length === 1 && resolvedRef.current) { resolvedRef.current(found[0]); return; }
489
+ setLookup({ state: "done", found });
490
+ }, () => { if (!ctl.signal.aborted) setLookup({ state: "done", found: [] }); });
491
+ return () => ctl.abort();
492
+ }, [failed, path, attempt]);
466
493
  const slow = useSlow(loading);
467
494
  // 大文件显示读到哪了;很久没读完提示网络慢。
468
495
  const progressText = progress > 0 ? `已读取 ${fmtSize(progress)}${shownSize ? ` / ${fmtSize(shownSize)}` : ""}` : "";
@@ -474,7 +501,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
474
501
  const toolbar = <>
475
502
  {(copying || copied || busy) && <span className="cli-fv-status" role="status">{copying ? "正在复制路径…" : copied ? "路径已复制" : "正在下载…"}</span>}
476
503
  <div className="cli-fv-actions">
477
- {embedded && <button className="cli-fv-icon" title={syncing || parsing ? "正在同步当前文件" : "刷新当前文件"} aria-label="刷新当前文件" disabled={syncing || parsing} onClick={() => setAttempt(value => value + 1)}>↻</button>}
504
+ {embedded && <button className="cli-fv-icon" title={syncing || parsing ? "正在同步当前文件" : "刷新当前文件"} aria-label="刷新当前文件" aria-busy={syncing || parsing} disabled={syncing || parsing} onClick={() => setAttempt(value => value + 1)}>↻</button>}
478
505
  <button ref={moreRef} className="cli-fv-icon cli-fv-more" title="更多文件操作" aria-label="更多文件操作" aria-haspopup="dialog" aria-expanded={actionsOpen} onClick={() => setActionsOpen(open => !open)}>{Icon.dots()}</button>
479
506
  {actionsOpen && <Popover className="cli-fv-menu" ariaLabel="文件操作" returnFocusRef={moreRef} onClose={() => setActionsOpen(false)}>
480
507
  <div className="cli-fv-menu-head"><strong>文件操作</strong><span title={path}>{path}</span></div>
@@ -483,7 +510,10 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
483
510
  {visibleActions.length > 0 && <div className="cli-fv-menu-custom">{visibleActions.map(action => (
484
511
  <button key={action.label} className="pop-item" title={action.title} onClick={() => performAction(() => action.onClick(fileInfo(), jobId))}>{action.label}</button>
485
512
  ))}</div>}
486
- {canSource && <button className="pop-item" onClick={() => performAction(() => setMode(mode === "preview" ? "source" : "preview"))} title={mode === "preview" ? "查看源文件" : "查看预览"}>{Icon.doc()} {mode === "preview" ? "源文件" : "预览"}</button>}
513
+ {canSource && <button className="pop-item" onClick={() => performAction(() => {
514
+ if (kind === "csv" && mode === "source" && tail) { setTail(false); setTextLimit(MARKDOWN_STEP); }
515
+ setMode(mode === "preview" ? "source" : "preview");
516
+ })} title={mode === "preview" ? "查看源文件" : "查看预览"}>{Icon.doc()} {mode === "preview" ? "源文件" : "预览"}</button>}
487
517
  {kind === "html" && <button className="pop-item" onClick={() => performAction(() => { setMode("preview"); setHtmlPresentation(htmlReading ? "original" : "reading"); })}>{htmlReading ? "原样预览" : "分段阅读"}</button>}
488
518
  <button className="pop-item" disabled={copying} onClick={() => performAction(() => void copyPath())} title={copied ? "已复制" : "复制路径"}>{copied ? Icon.check() : Icon.copy()} {copying ? "复制中…" : copied ? "路径已复制" : "复制路径"}</button>
489
519
  <button className="pop-item" onClick={() => performAction(() => setBig((b) => !b))} title={big ? "还原(Esc)" : "放大查看"} aria-pressed={big}>{big ? "⤡" : "⤢"} {big ? "还原大小" : "放大查看"}</button>
@@ -526,6 +556,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
526
556
  <button className="cli-fv-btn" disabled={busy} onClick={() => void download()}>重试下载</button>
527
557
  <button className="cli-fv-btn" onClick={() => setDownloadError(null)} aria-label="关闭下载错误">关闭</button>
528
558
  </div>}
559
+ {resolvedFrom && resolvedFrom !== path && <div className="cli-fv-trunc cli-fv-resolved" role="status">对话里写的是 <code>{resolvedFrom}</code>,按对话里提到的目录打开了 <code>{path}</code>。</div>}
529
560
  {error && (loaded?.kind === "text" || (htmlDoc && typeof htmlDoc === "object")) && <div className="cli-fv-trunc" role="alert">同步失败:{error}。保留上次完整内容。<button className="cli-fv-btn" onClick={() => setAttempt(value => value + 1)}>重试</button></div>}
530
561
  {(syncing || parsing) && <div className="cli-fv-sync" role="status">{!syncing && parsing ? "正在整理正文…" : loaded?.kind === "text" || (htmlDoc && typeof htmlDoc === "object") ? "正在核对更新…" : "正在读取文件…"}<button className="cli-fv-btn" onClick={cancelRead}>暂停加载</button>{kind === "html" && mode === "preview" && !htmlReading && <button className="cli-fv-btn" onClick={() => setHtmlPresentation("reading")}>分段阅读</button>}</div>}
531
562
  {cancelled && <div className="cli-fv-trunc" role="status">已暂停加载,已读取的内容仍然保留。<button className="cli-fv-btn" onClick={() => setAttempt(value => value + 1)}>继续加载</button></div>}
@@ -538,6 +569,11 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
538
569
  <div className="cli-fv-note err">读取失败:{error ?? src.error}
539
570
  <button className="btn btn-line btn-sm" style={{ marginLeft: 8 }} onClick={retry}>重试</button>
540
571
  <button className="btn btn-line btn-sm" style={{ marginLeft: 8 }} onClick={() => void download()} disabled={busy}>{Icon.download()} 下载</button>
572
+ {lookup?.state === "searching" && <div className="cli-fv-resolve" role="status">正在按对话里提到的目录查找这个文件…</div>}
573
+ {lookup?.state === "done" && lookup.found.length > 1 && <div className="cli-fv-resolve" role="group" aria-label="可能的文件">
574
+ 对话里写的是相对路径,找到这几个可能的文件:
575
+ {lookup.found.map((candidate) => <button key={candidate} type="button" className="cli-fv-btn cli-fv-candidate" title={candidate} onClick={() => onResolved?.(candidate)}>{candidate}</button>)}
576
+ </div>}
541
577
  </div>
542
578
  ) : kind === "binary" ? (
543
579
  <div className="cli-fv-note">这种文件不能在这里预览。
@@ -569,9 +605,9 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
569
605
  {(text.truncated || tail) && !htmlReading && !(kind === "markdown" && backend.fileSync) && (
570
606
  <div className="cli-fv-trunc">
571
607
  {tail && !text.tail ? "执行节点不支持只读末尾,下面仍是开头;" : ""}
572
- 文件较大({fmtSize(text.size)}),只显示{text.tail ? "最后" : "前"} {fmtSize(progressiveText ? text.end - text.start : TEXT_MAX)};完整内容请下载。
573
- {progressiveText && text.truncated && textLimit < TEXT_MAX && <button className="cli-fv-btn" disabled={syncing || !!error} onClick={() => setTextLimit(limit => Math.min(TEXT_MAX, nextTextLimit(limit)))}>{syncing ? "读取中…" : "继续读取"}</button>}
574
- <button className="cli-fv-btn" onClick={() => { if (progressiveText) setTextLimit(MARKDOWN_STEP); setTail(!tail); }}>{tail ? "看开头" : "看末尾"}</button>
608
+ 文件较大({fmtSize(text.size)}),只显示{text.tail ? "最后" : "前"} {fmtSize(progressiveText ? text.end - text.start || Math.min(textLimit, text.size) : TEXT_MAX)};完整内容请下载。
609
+ {progressiveText && text.truncated && textLimit < TEXT_MAX && <button className="cli-fv-btn" disabled={syncing || !!error} onClick={() => setTextLimit(limit => Math.min(TEXT_MAX, kind === "csv" ? limit + MARKDOWN_STEP : nextTextLimit(limit)))}>{syncing ? "读取中…" : kind === "csv" ? "继续查看" : "继续读取"}</button>}
610
+ {(kind !== "csv" || mode === "source") && <button className="cli-fv-btn" onClick={() => { if (progressiveText) setTextLimit(MARKDOWN_STEP); setTail(!tail); }}>{tail ? "看开头" : "看末尾"}</button>}
575
611
  </div>
576
612
  )}
577
613
  {htmlReading ? <HtmlReadingPreview text={text.text} complete={!text.truncated} version={`${version}:${reloadKey ?? ""}:${attempt}:${text.revision ?? ""}`} onBusyChange={readingBusy} abortRef={readingAbort} scrollRef={bodyRef}
@@ -583,7 +619,7 @@ function FileViewerInner({ backend, jobId, path, displayName, size, mtime, versi
583
619
  </FileOpenContext.Provider>
584
620
  </FileLinkContext.Provider>
585
621
  ) : kind === "csv" && mode === "preview" ? (
586
- <CsvTable text={text.text} />
622
+ text.tail ? <div className="cli-fv-note">正在读取文件开头…</div> : <CsvTable text={text.text} complete={!text.truncated} />
587
623
  ) : kind === "code" && text.text.length <= HIGHLIGHT_MAX ? (
588
624
  <div className="cli-fv-code"><Markdown>{fenced(text.text, codeLang(path))}</Markdown></div>
589
625
  ) : (
@@ -684,10 +720,10 @@ function SourceView({ backend, jobId, path, version, fresh, onBusyChange, onRevi
684
720
  /** 表格先显示这么多行,「再显示」每次多这么多(几十万行一次画出来页面会卡住)。 */
685
721
  const CSV_PAGE = 2_000;
686
722
 
687
- function CsvTable({ text }: { text: string }) {
723
+ function CsvTable({ text, complete }: { text: string; complete: boolean }) {
688
724
  const [limit, setLimit] = useState(CSV_PAGE);
689
- const { rows, more } = useMemo(() => parseCsv(text, limit + 1), [text, limit]);
690
- if (!rows.length) return <div className="cli-fv-note">空文件。</div>;
725
+ const { rows, more } = useMemo(() => parseCsv(text, limit + 1, complete), [text, limit, complete]);
726
+ if (!rows.length) return <div className="cli-fv-note">{complete ? "空文件。" : "当前片段尚无完整记录。"}</div>;
691
727
  const [head, ...body] = rows;
692
728
  return (
693
729
  <div className="cli-fv-csv">
@@ -698,7 +734,7 @@ function CsvTable({ text }: { text: string }) {
698
734
  {more && (
699
735
  <div className="cli-fv-trunc">已显示前 {body.length.toLocaleString()} 行。
700
736
  <button className="cli-fv-btn" onClick={() => setLimit((n) => n + CSV_PAGE * 5)}>再显示 {(CSV_PAGE * 5).toLocaleString()} 行</button>
701
- (也可以切到「源文件」看全部文字)
737
+ (也可以切到「源文件」看已读取的文字)
702
738
  </div>
703
739
  )}
704
740
  </div>
@@ -50,7 +50,7 @@ export function FilesPane({ backend, jobId, dir, onDir, onOpen, refreshKey, onLi
50
50
  const end = Math.min(entries?.length ?? 0, first + Math.min(80, Math.ceil(viewport / rowHeight) + 8));
51
51
  const visiblePaths = (entries ?? []).slice(first, end).filter(file => file.type === "file").map(file => file.path);
52
52
  const scopeKey = JSON.stringify(visiblePaths);
53
- useEffect(() => retainFileScope(backend, jobId, { dirs: [dir || "."], paths: JSON.parse(scopeKey) as string[], onDenied: () => { generation.current++; pageAbort.current?.abort(); setLoading(false); setMoreLoading(false); setEntries(null); setError("工作区访问权限已失效,请重新登录或检查任务权限"); } }), [backend, jobId, dir, scopeKey]);
53
+ useEffect(() => retainFileScope(backend, jobId, { dirs: [dir || "."], paths: JSON.parse(scopeKey) as string[], onDenied: message => { generation.current++; pageAbort.current?.abort(); setLoading(false); setMoreLoading(false); setEntries(null); setError(message || "工作区访问受限,请检查任务文件目录或访问权限"); } }), [backend, jobId, dir, scopeKey]);
54
54
  useEffect(() => {
55
55
  if (!listRef.current || typeof ResizeObserver === "undefined") return;
56
56
  const observer = new ResizeObserver(([box]) => { if (box.contentRect.height) setViewport(box.contentRect.height); });
@@ -2,8 +2,34 @@ import type { BoardFile, BoardView } from './workspace';
2
2
  import { serializeBlock, splitMessage, VIEWING_NAME } from '../core/blocks';
3
3
  export const BOARD_HISTORY_MAX = 40;
4
4
  const identity=(file:BoardFile)=>JSON.stringify([file.sourceId??'',file.path]);
5
+ const isAbsolute=(path:string)=>path.startsWith('/')||/^[a-z]:\//i.test(path);
6
+ function absoluteBoardPath(file:string,root?:string):string|undefined {
7
+ const path=file.replace(/\\/g,'/');
8
+ if(!path||path.includes('\0'))return;
9
+ if(isAbsolute(path))return path;
10
+ const base=typeof root==='string'?root.replace(/\\/g,'/'):undefined;
11
+ if(!base||!isAbsolute(base)||path.startsWith('~')||/^[a-z][\w+.-]*:/i.test(path))return;
12
+ const parts:string[]=[];
13
+ for(const part of path.split('/')){
14
+ if(!part||part==='.')continue;
15
+ if(part==='..'){if(!parts.length)return;parts.pop();}else parts.push(part);
16
+ }
17
+ return `${base.replace(/\/+$/,'')}/${parts.join('/')}`;
18
+ }
19
+ /** Only a file's own source root may complete its path; no file body is read. */
20
+ export function withBoardPaths(view:BoardView,currentSourceId?:string,roots:Readonly<Record<string,string|undefined>>={}):BoardView {
21
+ const complete=(file:BoardFile):BoardFile=>{
22
+ const {absolutePath:previousAbsolute,...original}=file;
23
+ const source=file.sourceId??currentSourceId;
24
+ const root=(source?roots[source]:undefined)??(!file.sourceId||file.sourceId===currentSourceId?view.workspaceRoot:undefined);
25
+ const absolutePath=absoluteBoardPath(file.path,root)??(typeof previousAbsolute==='string'?absoluteBoardPath(previousAbsolute):undefined);
26
+ return {...original,...(absolutePath?{absolutePath}:{})};
27
+ };
28
+ return {...view,current:view.current?complete(view.current):view.current,opened:view.opened?.map(complete),history:view.history?.map(complete)};
29
+ }
5
30
  export function rememberBoardFile(history:readonly BoardFile[],file:BoardFile):BoardFile[]{
6
- return [...history.filter(item=>identity(item)!==identity(file)),{...file}].slice(-BOARD_HISTORY_MAX);
31
+ const previous=history.find(item=>identity(item)===identity(file));
32
+ return [...history.filter(item=>identity(item)!==identity(file)),{...previous,...file}].slice(-BOARD_HISTORY_MAX);
7
33
  }
8
34
  export function cloneBoardView(view:BoardView):BoardView {
9
35
  return {...view,files:[...view.files],current:view.current?{...view.current}:view.current,opened:view.opened?.map(file=>({...file})),history:view.history?.map(file=>({...file})),browser:view.browser?{title:view.browser.title,url:browserUrl(view.browser.url)}:view.browser};
@@ -12,16 +38,18 @@ function browserUrl(raw:string):string {
12
38
  try{const url=new URL(raw);return url.protocol==='http:'||url.protocol==='https:'?`${url.origin}${url.pathname}`:url.protocol==='about:'?`${url.protocol}${url.pathname}`:url.protocol;}catch{return '';}
13
39
  }
14
40
  function describe(file:BoardFile,currentSourceId?:string){
15
- return file.sourceId&&file.sourceId!==currentSourceId?{path:file.path,sourceTask:file.sourceId,note:'来源任务的工作区,非当前执行分支'}:{path:file.path};
41
+ const path={path:file.path,...(file.absolutePath?{absolutePath:file.absolutePath}:{})};
42
+ return file.sourceId&&file.sourceId!==currentSourceId?{...path,sourceTask:file.sourceId,note:'来源任务的工作区,非当前执行分支'}:path;
16
43
  }
17
44
  /** Metadata only; do not silently read/upload file bodies, URLs with auth tokens or arbitrary DOM. */
18
45
  export function formatBoardContext(view:BoardView,currentSourceId?:string):string {
19
46
  if(view.autoContext===false)return '';
20
- const current=view.current===undefined?(view.file?{path:view.file}:null):view.current;
21
- const opened=view.opened??view.files.map(path=>({path}));
47
+ view=withBoardPaths({...view,current:view.current===undefined?(view.file?{path:view.file}:null):view.current,opened:view.opened??view.files.map(path=>({path}))},currentSourceId);
48
+ const current=view.current;
49
+ const opened=view.opened??[];
22
50
  const history=view.history??[];
23
51
  if(!current&&!opened.length&&!history.length&&!view.browser)return '';
24
- const data={panelVisible:view.visible!==false,activeTab:view.tab,currentFile:current?describe(current,currentSourceId):null,
52
+ const data={panelVisible:view.visible!==false,activeTab:view.tab,...(view.workspaceRoot?{workspaceRoot:view.workspaceRoot}:{}),currentFile:current?describe(current,currentSourceId):null,
25
53
  openFiles:opened.slice(-8).map(file=>describe(file,currentSourceId)),recentlyVisited:history.slice(-BOARD_HISTORY_MAX).map(file=>describe(file,currentSourceId)),
26
54
  ...(view.browser?{browser:{url:browserUrl(view.browser.url),title:view.browser.title}}:{})};
27
55
  const text=JSON.stringify(data,null,2);
@@ -40,7 +68,8 @@ export function withoutBoardContext(text:string):string {
40
68
 
41
69
  /** Local selection changes may select an owner; shared history and remote page
42
70
  * metadata updates must not steal the user's active board. */
43
- const localBoardView=(view:BoardView)=>JSON.stringify({tab:view.tab,dir:view.dir,file:view.file,files:view.files,current:view.current,opened:view.opened,visible:view.visible!==false});
71
+ const localFile=(file:BoardFile)=>({path:file.path,sourceId:file.sourceId});
72
+ const localBoardView=(view:BoardView)=>JSON.stringify({tab:view.tab,dir:view.dir,directorySourceId:view.directorySourceId,file:view.file,files:view.files,current:view.current?localFile(view.current):view.current,opened:view.opened?.map(localFile),visible:view.visible!==false});
44
73
  export function selectedBoardOwner(sources:Map<string,BoardView>):[string,BoardView]|undefined {
45
74
  const entries=[...sources.entries()];return entries.reverse().find(([,view])=>view.visible!==false)??entries[0];
46
75
  }
@@ -55,7 +84,9 @@ export function activateBoardOwner(sources:Map<string,BoardView>,owner:string):[
55
84
  const view=sources.get(owner);if(view){sources.delete(owner);sources.set(owner,view);}return selectedBoardOwner(sources);
56
85
  }
57
86
  export function mergeBoardHistory(existing:readonly BoardFile[],previous:BoardView|undefined,next:BoardView):BoardFile[] {
58
- const old=previous?.history??[],incoming=next.history??[];let history=[...existing];
87
+ const old=previous?.history??[],incoming=next.history??[];
88
+ const metadata=new Map(incoming.map(file=>[identity(file),file]));
89
+ let history=existing.map(file=>metadata.get(identity(file))?.absolutePath?{...file,...metadata.get(identity(file))}:file);
59
90
  const known=new Set(old.map(identity));
60
91
  // Newly mounted boards may restore old history; only adopt previously unknown
61
92
  // records so a late restore cannot reorder the live workspace's recent visits.
@@ -0,0 +1,46 @@
1
+ // diff 正文的分行与着色:中枢看板的「改动」(ChangesPane)与节点的 TaskChanges 共用。
2
+ //
3
+ // 只按位置判断:文件头(`diff --git ` 到下一个 `@@` 之间的 index / --- / +++ / mode / rename…)不着色;
4
+ // hunk 里由第一个字符决定:`+` 新增、`-` 删除、空格是上下文、`\` 是「No newline at end of file」。
5
+ // 不能用「以 +++ / --- 开头就不是改动」来认文件头:被删掉的 `-- 注释` 显示为 `--- 注释`,
6
+ // Markdown 的分隔线 `---` 被增删时是 `+---` / `----`,新增的 `++x` 显示为 `+++x`——它们都是真实改动。
7
+
8
+ export type DiffLineKind = "hunk" | "add" | "del" | "";
9
+
10
+ /** 去掉开头的文件头,从第一个 `@@` 起;没有 hunk(二进制、只改权限 / 重命名)时返回空。 */
11
+ export function hunkLines(patch: string): string[] {
12
+ const lines = patch.split("\n");
13
+ const i = lines.findIndex((l) => l.startsWith("@@"));
14
+ return i >= 0 ? lines.slice(i) : [];
15
+ }
16
+
17
+ /**
18
+ * 每一行的种类。同一个文件的 patch 里可能再出现一段文件头(类型变化:一段删除 + 一段新增,
19
+ * 节点把两段拼在一起),那段文件头同样不着色。
20
+ */
21
+ export function diffLineKinds(lines: string[]): DiffLineKind[] {
22
+ let header = false;
23
+ return lines.map((line) => {
24
+ if (line.startsWith("diff --git ")) {
25
+ header = true;
26
+ return "";
27
+ }
28
+ if (line.startsWith("@@")) {
29
+ header = false;
30
+ return "hunk";
31
+ }
32
+ if (header) return "";
33
+ return line[0] === "+" ? "add" : line[0] === "-" ? "del" : "";
34
+ });
35
+ }
36
+
37
+ /** 一个文件 patch 里新增、删除的行数(只给了整段 unified diff 的节点没有统计,自己数)。 */
38
+ export function countChanges(patch: string): { additions: number; deletions: number } {
39
+ let additions = 0;
40
+ let deletions = 0;
41
+ for (const kind of diffLineKinds(hunkLines(patch))) {
42
+ if (kind === "add") additions++;
43
+ else if (kind === "del") deletions++;
44
+ }
45
+ return { additions, deletions };
46
+ }
@@ -0,0 +1,63 @@
1
+ import { useEffect, useRef, useState } from "react";
2
+
3
+ /** 运行中有工具执行完(可能改了文件)时,改动页签最多每这么久重读一次;最后一次变化之后一定再读一次。 */
4
+ export const DIFF_LIVE_GAP_MS = 5_000;
5
+
6
+ /**
7
+ * 改动页签(中枢看板 ChangesPane、节点 TaskChanges 共用)什么时候自动重读。只看事件,没有定时轮询:
8
+ * · settled 变了(一轮结束、对话结束、断线重连补齐):马上给信号;
9
+ * · edits 变了(运行中有工具执行完、工作区文件有变化):节流,最多每 DIFF_LIVE_GAP_MS 一次,
10
+ * 最后一次变化之后一定再给一次(只在有新事件时才排一次,没有事件就什么都不做);
11
+ * · 页面在后台时来的信号先记下,回到前台时给一次。
12
+ * 返回一个递增的数字,变了就重读。挂上时不给信号(组件挂上时自己会读一次)。
13
+ */
14
+ export function useDiffRefreshSignal(settled: number, edits: number): number {
15
+ const [signal, setSignal] = useState(0);
16
+ const seen = useRef({ settled, edits });
17
+ const lastAt = useRef(0);
18
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
19
+ const missed = useRef(false);
20
+ // 同一次提交里 settled 和 edits 一起变了(例如手动刷新同时碰了两个):只读一次。
21
+ const firedThisCommit = useRef(false);
22
+ const fire = useRef(() => {});
23
+ fire.current = () => {
24
+ if (timer.current) { clearTimeout(timer.current); timer.current = null; }
25
+ if (typeof document !== "undefined" && document.visibilityState === "hidden") { missed.current = true; return; }
26
+ lastAt.current = Date.now();
27
+ setSignal((n) => n + 1);
28
+ };
29
+
30
+ useEffect(() => {
31
+ if (seen.current.settled === settled) return;
32
+ seen.current.settled = settled;
33
+ fire.current();
34
+ firedThisCommit.current = true;
35
+ }, [settled]);
36
+
37
+ useEffect(() => {
38
+ if (seen.current.edits === edits) return;
39
+ seen.current.edits = edits;
40
+ // 刚因为 settled 读过,或者已经排着一次:那一次读到的会包含这次变化。
41
+ if (firedThisCommit.current || timer.current) return;
42
+ const delay = lastAt.current + DIFF_LIVE_GAP_MS - Date.now();
43
+ // 离上次读已经够久:马上读;否则排到间隔满了再读(只排这一次)。
44
+ if (delay <= 0) { fire.current(); return; }
45
+ timer.current = setTimeout(() => { timer.current = null; fire.current(); }, delay);
46
+ }, [edits]);
47
+ useEffect(() => { firedThisCommit.current = false; });
48
+
49
+ useEffect(() => {
50
+ const onVisible = () => {
51
+ if (document.visibilityState !== "visible" || !missed.current) return;
52
+ missed.current = false;
53
+ fire.current();
54
+ };
55
+ document.addEventListener("visibilitychange", onVisible);
56
+ return () => {
57
+ document.removeEventListener("visibilitychange", onVisible);
58
+ if (timer.current) { clearTimeout(timer.current); timer.current = null; }
59
+ };
60
+ }, []);
61
+
62
+ return signal;
63
+ }