@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
@@ -0,0 +1,117 @@
1
+ // 改动里一个文件的区块(看板「改动」页签和节点的任务改动共用),以及渐进式加载:
2
+ // 先拿文件列表和增删行数,点开哪个文件才取它的 patch。
3
+ import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import type { DiffFile } from "../core/types";
5
+ import { diffLineKinds, hunkLines } from "./diffLines";
6
+
7
+ /** 超过这么多行的文件缺省收起:一次画几万行会卡住页面。 */
8
+ export const COLLAPSE_LINES = 400;
9
+
10
+ /** 渐进式改动里一个文件 patch 的读取状态(点开才取)。 */
11
+ export type PatchState = { state: "loading" } | { state: "error"; message: string } | { state: "ready"; file: DiffFile };
12
+
13
+ export const FileDiff = memo(function FileDiff({ file: f, userToggled, onToggle, refs, onOpen, lazy, patch, onRetry }: {
14
+ file: DiffFile;
15
+ /** 用户把这个文件从缺省状态切换过(展开 / 收起),后台刷新不会把它改回去。 */
16
+ userToggled: boolean;
17
+ onToggle: (path: string) => void;
18
+ refs: { current: Record<string, HTMLDivElement | null> };
19
+ onOpen?: (path: string) => void;
20
+ /** 渐进式:这个文件的 patch 点开才取(缺省收起)。 */
21
+ lazy?: boolean; patch?: PatchState; onRetry?: (path: string) => void;
22
+ }) {
23
+ const shownFile = lazy ? (patch?.state === "ready" ? patch.file : null) : f;
24
+ const lines = useMemo(() => (!shownFile || shownFile.binary || shownFile.omitted ? [] : hunkLines(shownFile.patch)), [shownFile]);
25
+ const kinds = useMemo(() => diffLineKinds(lines), [lines]);
26
+ const big = lines.length > COLLAPSE_LINES;
27
+ // 渐进式缺省收起(点开才取 patch);整份 diff 时大文件缺省收起。
28
+ const collapsedByDefault = lazy ? true : big;
29
+ const isCollapsed = userToggled ? !collapsedByDefault : collapsedByDefault;
30
+ // content-visibility 下没画出来时的占位高度(表头约 34px,每行 12px × 1.55),跳转 / 滚动定位才准。
31
+ const est = Math.round(34 + (isCollapsed ? 38 : Math.max(1, lines.length) * 18.6));
32
+ return (
33
+ <div className="tc-file" style={{ containIntrinsicSize: `auto ${est}px` }} ref={(el) => { refs.current[f.path] = el; }}>
34
+ <button className="tc-fhead" onClick={() => onToggle(f.path)}>
35
+ <span className={`tc-chev ${isCollapsed ? "" : "open"}`}>▸</span>
36
+ <span className={`tc-st s-${f.status === "?" ? "new" : f.status}`}>{f.status}</span>
37
+ <span className="tc-fpath">{f.path}</span>
38
+ {onOpen && f.status !== "D" && (
39
+ <span className="cli-tc-open" role="button" tabIndex={0} title="打开文件" onClick={(e) => { e.stopPropagation(); onOpen(f.path); }} onKeyDown={(e) => { if (e.key === "Enter") { e.stopPropagation(); onOpen(f.path); } }}>打开</span>
40
+ )}
41
+ <span className="tc-cnt"><b className="add">+{f.additions}</b> <b className="del">−{f.deletions}</b></span>
42
+ </button>
43
+ {isCollapsed ? (
44
+ !lazy && big && <button className="tc-bigdiff" onClick={() => onToggle(f.path)}>大型 diff({lines.length.toLocaleString()} 行)—— 点击展开</button>
45
+ ) : lazy && patch?.state !== "ready" ? (
46
+ <div className="tc-hunks">
47
+ {patch?.state === "error"
48
+ ? <div className="tc-empty" role="alert">读取这个文件的改动失败:{patch.message} <button className="tc-btn" onClick={() => onRetry?.(f.path)}>重试</button></div>
49
+ : <div className="tc-empty" role="status">正在读取这个文件的改动…</div>}
50
+ </div>
51
+ ) : (
52
+ <div className="tc-hunks">
53
+ {shownFile?.omitted ? <div className="tc-empty">改动太多,这个文件的 diff 没有带上{onOpen && f.status !== "D" ? ",可以点「打开」看文件" : ""}。</div>
54
+ : f.binary ? <div className="tc-empty">二进制文件 —— 不予显示</div>
55
+ : lines.length === 0 ? <div className="tc-empty">没有文本改动(仅权限或重命名)。</div>
56
+ : lines.map((ln, i) => <div key={i} className={`dl ${kinds[i]}`}>{ln || " "}</div>)}
57
+ {shownFile?.truncated && <div className="tc-empty">… 文件 diff 已截断</div>}
58
+ </div>
59
+ )}
60
+ </div>
61
+ );
62
+ });
63
+
64
+ /** 新 summary 代表一个新修订;只重取展开文件,304 沿用同一份 files,不触发失效。 */
65
+ export function useLazyPatches({ files, lazy, toggled, fetchFile }: {
66
+ files: DiffFile[] | undefined;
67
+ lazy: boolean;
68
+ toggled: Set<string>;
69
+ fetchFile: ((path: string, signal: AbortSignal) => Promise<DiffFile | null>) | undefined;
70
+ }) {
71
+ const [patches, setPatches] = useState<Record<string, PatchState>>({});
72
+ const patchesRef = useRef(patches);
73
+ const fetchRef = useRef(fetchFile); fetchRef.current = fetchFile;
74
+ const generation = useRef(0);
75
+ const pending = useRef(new Map<string, AbortController>());
76
+ const fetchPatch = useCallback((file: DiffFile) => {
77
+ const fetch = fetchRef.current;
78
+ if (!fetch || pending.current.has(file.path)) return;
79
+ const token = generation.current;
80
+ const controller = new AbortController();
81
+ pending.current.set(file.path, controller);
82
+ const publish = (patch: PatchState) => {
83
+ const next = { ...patchesRef.current, [file.path]: patch };
84
+ patchesRef.current = next; setPatches(next);
85
+ };
86
+ publish({ state: "loading" });
87
+ fetch(file.path, controller.signal).then(
88
+ (found) => {
89
+ if (generation.current !== token || controller.signal.aborted) return;
90
+ publish(found ? { state: "ready", file: found } : { state: "error", message: "这个文件已经没有改动了" });
91
+ },
92
+ (error: unknown) => {
93
+ if (generation.current !== token || controller.signal.aborted) return;
94
+ publish({ state: "error", message: error instanceof Error ? error.message : String(error) });
95
+ },
96
+ ).finally(() => { if (pending.current.get(file.path) === controller) pending.current.delete(file.path); });
97
+ }, []);
98
+ useEffect(() => {
99
+ generation.current++;
100
+ patchesRef.current = {}; setPatches({});
101
+ const stop = () => {
102
+ generation.current++;
103
+ for (const controller of pending.current.values()) controller.abort();
104
+ pending.current.clear();
105
+ };
106
+ return stop;
107
+ }, [files, lazy, fetchFile]);
108
+ useEffect(() => {
109
+ if (!lazy || !files) return;
110
+ for (const file of files) if (toggled.has(file.path) && !patchesRef.current[file.path]) fetchPatch(file);
111
+ }, [toggled, lazy, files, fetchFile, fetchPatch]);
112
+ const retry = useCallback((path: string) => {
113
+ const file = files?.find((item) => item.path === path);
114
+ if (file) fetchPatch(file);
115
+ }, [files, fetchPatch]);
116
+ return { patches, retry };
117
+ }
@@ -54,12 +54,13 @@ export function resolveRelative(fromFile: string, href: string): string {
54
54
  return base.join("/");
55
55
  }
56
56
 
57
- /** 一行 CSV(支持引号里的逗号和 "" 转义)。 */
58
- export function parseCsv(text: string, maxRows = 500): { rows: string[][]; more: boolean } {
57
+ /** CSV(支持引号里的逗号和 "" 转义);截断前缀不提交末尾尚未结束的记录。 */
58
+ export function parseCsv(text: string, maxRows = 500, complete = true): { rows: string[][]; more: boolean } {
59
59
  const rows: string[][] = [];
60
60
  let row: string[] = [];
61
61
  let cell = "";
62
62
  let quoted = false;
63
+ let recordStart = 0;
63
64
  const sep = text.includes("\t") && !text.split("\n")[0].includes(",") ? "\t" : ",";
64
65
  for (let i = 0; i < text.length; i++) {
65
66
  const ch = text[i];
@@ -73,10 +74,11 @@ export function parseCsv(text: string, maxRows = 500): { rows: string[][]; more:
73
74
  if (ch === "\r" && text[i + 1] === "\n") i++;
74
75
  row.push(cell); cell = "";
75
76
  rows.push(row); row = [];
77
+ recordStart = i + 1;
76
78
  if (rows.length > maxRows) return { rows: rows.slice(0, maxRows), more: true };
77
79
  } else cell += ch;
78
80
  }
79
- if (cell || row.length) { row.push(cell); rows.push(row); }
81
+ if (complete && recordStart < text.length) { row.push(cell); rows.push(row); }
80
82
  return { rows: rows.slice(0, maxRows), more: rows.length > maxRows };
81
83
  }
82
84
 
@@ -1,6 +1,7 @@
1
1
  import type { BoardBackend } from "../core/client";
2
2
 
3
- type Scope = { paths: string[]; dirs: string[]; onDenied?: () => void };
3
+ /** entries:这些目录变了时把变了的子项逐个报出来(多列一次目录,业务方显式要了才做)。 */
4
+ type Scope = { paths: string[]; dirs: string[]; entries?: string[]; onDenied?: (message?: string) => void };
4
5
  const scopes = new WeakMap<BoardBackend, Map<string, Map<object, Scope>>>();
5
6
  const listeners = new WeakMap<BoardBackend, Map<string, Set<() => void>>>();
6
7
  /** A preview/list owns its subscription. Unmounted/closed directories are not polled. */
@@ -15,10 +16,14 @@ export function retainFileScope(backend: BoardBackend, jobId: string, scope: Sco
15
16
  }
16
17
  export function readFileScope(backend: BoardBackend, jobId: string): Scope {
17
18
  const active = [...(scopes.get(backend)?.get(jobId)?.values() ?? [])];
18
- return { paths: [...new Set(active.flatMap(scope => scope.paths))].sort(), dirs: [...new Set(active.flatMap(scope => scope.dirs))].sort() };
19
+ const entries = [...new Set(active.flatMap(scope => scope.entries ?? []))].sort();
20
+ return { paths: [...new Set(active.flatMap(scope => scope.paths))].sort(), dirs: [...new Set(active.flatMap(scope => scope.dirs))].sort(), ...(entries.length ? { entries } : {}) };
19
21
  }
20
- export function denyFileScope(backend: BoardBackend, jobId: string) {
21
- for (const scope of scopes.get(backend)?.get(jobId)?.values() ?? []) scope.onDenied?.();
22
+ export function denyFileScope(backend: BoardBackend, jobId: string, message?: string, denied?: { paths: readonly string[]; dirs: readonly string[] }) {
23
+ for (const scope of scopes.get(backend)?.get(jobId)?.values() ?? []) {
24
+ // A list owns its directory; a rejected child file must not erase that list.
25
+ if (!denied || (scope.dirs.length ? scope.dirs.some(dir => denied.dirs.includes(dir || ".")) : scope.paths.some(path => denied.paths.includes(path)))) scope.onDenied?.(message);
26
+ }
22
27
  }
23
28
  export function onFileScope(backend: BoardBackend, jobId: string, listener: () => void) {
24
29
  let jobs = listeners.get(backend); if (!jobs) { jobs = new Map(); listeners.set(backend, jobs); }
@@ -15,7 +15,7 @@ export class FileSyncError extends Error {
15
15
  }
16
16
  export interface FileSyncProgress { phase: "manifest" | "chunks" | "verify"; loadedBytes: number; totalBytes: number; downloadedBytes: number; reusedBytes: number }
17
17
  export interface FileSyncOptions { signal?: AbortSignal; onProgress?: (progress: FileSyncProgress) => void; decode?: boolean; range?: { start?: number; maxBytes: number; tail?: boolean }; pendingTimeoutMs?: number; /** Require a manifest request started after this explicit refresh. */ fresh?: boolean; /** Remember only successfully viewed ranges, never downloads. */ preview?: boolean }
18
- export interface FilePreviewRefresh { changed: string[]; error?: Error }
18
+ export interface FilePreviewRefresh { changed: string[]; error?: Error; denied?: Array<{ path: string; message: string }> }
19
19
  export interface SyncedFile {
20
20
  readonly bytes: Uint8Array<ArrayBuffer>;
21
21
  revision: string; namespace: string; hash: string; size: number; start: number; end: number; truncated: boolean;
@@ -151,7 +151,7 @@ export function createFileSynchronizer(transport: FileSyncTransport, cache = new
151
151
  if ([401, 403, 404].includes(status)) {
152
152
  last.delete(resource);
153
153
  if (previous) {
154
- if (status === 404) { const scope = { namespace: previous.namespace, taskId: jobId, path }; retireFile(scope); await cache.purgeFile(scope); }
154
+ if (status === 404 || (status === 403 && (error as FileSyncError).code === "file_forbidden")) { const scope = { namespace: previous.namespace, taskId: jobId, path }; retireFile(scope); await cache.purgeFile(scope); }
155
155
  else { retireNamespace(previous.namespace); await cache.purgeNamespace(previous.namespace); }
156
156
  }
157
157
  }
@@ -261,6 +261,7 @@ export function createFileSynchronizer(transport: FileSyncTransport, cache = new
261
261
  // prevent several 100MiB workers allocating full buffers at the same time.
262
262
  const work = async (): Promise<FilePreviewRefresh> => {
263
263
  const changed = new Set<string>(); let error: Error | undefined, hasRecoverableError = false, retryAfterMs = 0;
264
+ const denied: NonNullable<FilePreviewRefresh["denied"]> = [];
264
265
  for (const path of requested) {
265
266
  if (signal?.aborted) throw aborted();
266
267
  const resource = JSON.stringify([jobId, path]), previous = previews.get(resource);
@@ -277,7 +278,14 @@ export function createFileSynchronizer(transport: FileSyncTransport, cache = new
277
278
  }
278
279
  } catch (failure) {
279
280
  const status = statusOf(failure);
280
- if (signal?.aborted || (failure instanceof Error && failure.name === "AbortError") || status === 401 || status === 403) throw failure;
281
+ if (signal?.aborted || (failure instanceof Error && failure.name === "AbortError") || status === 401) throw failure;
282
+ if (status === 403) {
283
+ if ((failure as FileSyncError).code !== "file_forbidden") throw failure;
284
+ const scope = { namespace: last.get(resource)?.namespace ?? previous.namespace, taskId: jobId, path };
285
+ last.delete(resource); previews.delete(resource); retireFile(scope); await cache.purgeFile(scope);
286
+ changed.delete(path); denied.push({ path, message: failure instanceof Error ? failure.message : String(failure) });
287
+ continue;
288
+ }
281
289
  if (status === 404) {
282
290
  changed.add(path);
283
291
  if (previews.get(resource) === previous) {
@@ -304,7 +312,7 @@ export function createFileSynchronizer(transport: FileSyncTransport, cache = new
304
312
  }
305
313
  // Preserve the original errors: consumers may share them with other reads.
306
314
  const combined = error && hasRecoverableError && retryAfterMs > 0 ? Object.assign(new Error(error.message), error, { name: error.name, retryAfterMs }) : error;
307
- return { changed: [...changed], ...(combined ? { error: combined } : {}) };
315
+ return { changed: [...changed], ...(combined ? { error: combined } : {}), ...(denied.length ? { denied } : {}) };
308
316
  };
309
317
  return refreshQueue.run(work, signal);
310
318
  };
@@ -1,8 +1,9 @@
1
1
  import { decodeText } from "../core/textDecode";
2
+ import { sha256 } from "../core/sha256";
2
3
 
3
4
  const aborted = () => new DOMException("文件同步已取消", "AbortError");
4
5
  const integrity = (message: string) => Object.assign(new Error(message), { status: 422, code: "integrity" });
5
- const digest = async (bytes: Uint8Array<ArrayBuffer>) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map(byte => byte.toString(16).padStart(2, "0")).join("");
6
+ const digest = async (bytes: Uint8Array<ArrayBuffer>) => globalThis.crypto?.subtle ? [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map(byte => byte.toString(16).padStart(2, "0")).join("") : sha256(bytes);
6
7
  type Processed = { bytes: Uint8Array<ArrayBuffer>; text?: string; encoding?: string };
7
8
 
8
9
  /** One worker owns the assembled buffer; chunks are transferred, not copied into a second main-thread file. */
@@ -18,8 +19,8 @@ export class FileSyncProcessor {
18
19
  private failed: Error | null = null;
19
20
  constructor(private signal: AbortSignal) {
20
21
  if (typeof Worker !== "undefined" && typeof URL.createObjectURL === "function") try {
21
- const script = `const decode=${decodeText.toString()};let output=null,offset=0;
22
- const hash=async b=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',b)),v=>v.toString(16).padStart(2,'0')).join('');
22
+ const script = `const decode=${decodeText.toString()},fallback=${sha256.toString()};let output=null,offset=0;
23
+ const hash=async b=>globalThis.crypto?.subtle?Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',b)),v=>v.toString(16).padStart(2,'0')).join(''):fallback(b instanceof Uint8Array?b:new Uint8Array(b));
23
24
  onmessage=async({data:m})=>{try{let value;
24
25
  if(m.op==='start'){output=new Uint8Array(m.size);offset=0;value=true;}
25
26
  if(m.op==='verify'){if(await hash(m.bytes)!==m.hash)throw Error('文件块校验失败');value={bytes:m.bytes};}
@@ -43,8 +43,8 @@ export function createFileSyncTransport(fetcher: typeof fetch, pathBuilder: (job
43
43
  const retryAfterMs = retry ? (/^\d+(\.\d+)?$/.test(retry) ? Number(retry) * 1000 : Math.max(0, Date.parse(retry) - Date.now())) : undefined;
44
44
  const missingRoute = response.status === 501 || (response.status === 404 && !["file_not_found", "task_not_found", "job_not_found"].includes(error.error ?? ""));
45
45
  const code = missingRoute ? "unsupported" : error.error ?? "http_error";
46
- const common: Record<string, string> = { node_unreachable: "执行节点暂时连不上,请稍后重试", unsupported: "服务端尚未支持大文件增量同步,请升级节点和中枢", file_sync_unsupported: "服务端尚未支持大文件增量同步,请升级节点和中枢", file_not_found: "文件不存在(可能已删除或改名)", file_forbidden: "文件访问权限失效,请重新登录或确认权限", file_sync_busy: "文件服务繁忙,请稍后重试", too_many_snapshot_builds: "文件服务繁忙,请稍后重试", too_many_uploads: "上传任务较多,请稍后重试", file_sync_queue_timeout: "文件处理排队超时,请稍后重试", file_sync_timeout: "文件服务响应超时,请重试", snapshot_cache_full: "文件缓存空间不足,请稍后重试", upload_storage_full: "文件上传空间不足,请稍后重试" };
47
- const message = common[code] ?? ([401, 403].includes(response.status) ? "文件访问权限失效,请重新登录或确认权限" : error.detail ?? `文件同步失败(HTTP ${response.status})`);
46
+ const common: Record<string, string> = { node_unreachable: "执行节点暂时连不上,请稍后重试", unsupported: "服务端尚未支持大文件增量同步,请升级节点和中枢", file_sync_unsupported: "服务端尚未支持大文件增量同步,请升级节点和中枢", file_not_found: "文件不存在(可能已删除或改名)", file_forbidden: error.detail || "文件不在当前任务允许访问的目录中,或没有访问权限", file_sync_busy: "文件服务繁忙,请稍后重试", too_many_snapshot_builds: "文件服务繁忙,请稍后重试", too_many_uploads: "上传任务较多,请稍后重试", file_sync_queue_timeout: "文件处理排队超时,请稍后重试", file_sync_timeout: "文件服务响应超时,请重试", snapshot_cache_full: "文件缓存空间不足,请稍后重试", upload_storage_full: "文件上传空间不足,请稍后重试" };
47
+ const message = response.status === 401 ? "登录已失效,请重新登录" : common[code] ?? (response.status === 403 ? error.detail || "没有读取该文件的权限,请检查任务访问权限" : error.detail ?? `文件同步失败(HTTP ${response.status})`);
48
48
  throw new FileSyncError(message, response.status, code, retryAfterMs);
49
49
  }
50
50
  return { response, bytes };
@@ -4,10 +4,12 @@ import type { FileEntry, WorkspaceChangeEvent, WorkspaceFileBatch, WorkspaceFile
4
4
  import { denyFileScope, onFileScope, readFileScope, retainFileScope } from './fileScope';
5
5
  import { onFilePreviewScope, refreshFilePreviews } from './fileSync';
6
6
  import { createFileWorkQueue } from './fileSyncQueue';
7
- export interface WorkspaceWatchOptions { /** @deprecated Retained for compatibility; checks are event-driven, never periodic. */ intervalMs?:number; paths?:readonly string[]; dirs?:readonly string[]; onStatus?:(status:WorkspaceWatchStatus)=>void }
7
+ export interface WorkspaceWatchOptions { /** @deprecated Retained for compatibility; checks are event-driven, never periodic. */ intervalMs?:number; paths?:readonly string[]; dirs?:readonly string[];
8
+ /** dirs 里的目录变了时,把变了的直接子项(新增 / 删除 / 修改的文件和子目录)逐个报出来;为此目录变化时多列一次目录。缺省只报目录本身变了。 */
9
+ dirEntries?:boolean; onStatus?:(status:WorkspaceWatchStatus)=>void }
8
10
  type Listener={change:(event:WorkspaceChangeEvent)=>void;status?:WorkspaceWatchOptions['onStatus']};
9
11
  export interface WorkspaceRefreshOptions { manual?:boolean }
10
- type Entry={listeners:Set<Listener>;stop:()=>void;retry:(manual?:boolean)=>void;status:WorkspaceWatchStatus};
12
+ type Entry={listeners:Set<Listener>;stop:()=>void;retry:(manual?:boolean)=>void;created:(path:string)=>void;status:WorkspaceWatchStatus};
11
13
  export function cloneWorkspaceChange(event:WorkspaceChangeEvent):WorkspaceChangeEvent {return {...event,changes:event.changes.map(change=>({...change,file:change.file?{...change.file}:undefined,previous:change.previous?{...change.previous}:undefined}))};}
12
14
  const registries=new WeakMap<BoardBackend,Map<string,Entry>>();
13
15
  const metadataQueues=new WeakMap<BoardBackend,ReturnType<typeof createFileWorkQueue>>();
@@ -15,18 +17,20 @@ function metadataQueue(backend:BoardBackend){
15
17
  let queue=metadataQueues.get(backend);if(!queue){queue=createFileWorkQueue(4,128);metadataQueues.set(backend,queue);}return queue;
16
18
  }
17
19
  export function retryWorkspaceFiles(backend:BoardBackend,jobId:string,options:WorkspaceRefreshOptions={}):void {registries.get(backend)?.get(jobId)?.retry(options.manual);}
20
+ /** A confirmed upload is a change, not an initial observation of an existing file. */
21
+ export function notifyWorkspaceFileCreated(backend:BoardBackend,jobId:string,path:string):void {registries.get(backend)?.get(jobId)?.created(path);}
18
22
  const fingerprint=(file:FileEntry)=>`${file.type}:${file.size}:${file.mtime}:${file.changeToken??''}`;
19
23
  const validFile=(file:FileEntry)=>!!file&&typeof file.path==='string'&&typeof file.name==='string'&&['file','dir'].includes(file.type)&&Number.isFinite(file.size)&&Number.isFinite(file.mtime);
20
24
  const invalidResponse=(message:string)=>Object.assign(new Error(message),{status:502,code:'invalid_response'});
21
25
  /** Shared event-driven HTTP checks. No recurring file timer or file event connection. */
22
26
  export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listener:(event:WorkspaceChangeEvent)=>void,options:WorkspaceWatchOptions={}):()=>void {
23
- const releaseOwnedScope=options.paths?.length||options.dirs?.length?retainFileScope(backend,jobId,{paths:[...options.paths??[]],dirs:[...options.dirs??[]]}):()=>{};
27
+ const releaseOwnedScope=options.paths?.length||options.dirs?.length?retainFileScope(backend,jobId,{paths:[...options.paths??[]],dirs:[...options.dirs??[]],...(options.dirEntries?{entries:[...options.dirs??[]]}:{})}):()=>{};
24
28
  let jobs=registries.get(backend);if(!jobs){jobs=new Map();registries.set(backend,jobs);}
25
29
  let entry=jobs.get(jobId);
26
30
  if(!entry){
27
31
  // Keep the public transport value for compatibility; it denotes bounded HTTP, not a timer.
28
32
  const statusBase={type:'files_watch' as const,jobId,mode:'poll' as const,coverage:'listed-files' as const,complete:false};
29
- entry={listeners:new Set(),stop:()=>{},retry:()=>{},status:{...statusBase,state:'connecting'}};jobs.set(jobId,entry);
33
+ entry={listeners:new Set(),stop:()=>{},retry:()=>{},created:()=>{},status:{...statusBase,state:'connecting'}};jobs.set(jobId,entry);
30
34
  const owned=entry;
31
35
  let alive=true,controller:AbortController|null=null,timer:ReturnType<typeof setTimeout>|undefined,failed=0,generation=0,dirty=false;
32
36
  let scopeKey=JSON.stringify(readFileScope(backend,jobId));
@@ -34,12 +38,23 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
34
38
  let serverNotBefore=0,retryAt=0,exhaustedUntil=0;
35
39
  const requests=metadataQueue(backend);
36
40
  let baseline=new Map<string,FileEntry>(),directories=new Map<string,string|null>(),cursors=new Map<string,string>();
41
+ // 监视目录的直接子项(不递归):目录变了时报出新增 / 删除 / 修改的是哪些,业务方据此拉新文件,不用自己再列目录。
42
+ let dirEntries=new Map<string,Map<string,FileEntry>>();
37
43
  let known=new Set<string>();
44
+ const announcedCreates=new Set<string>();
38
45
  type ScanState={baseline:Map<string,FileEntry>;known:Set<string>};
39
46
  const status=(state:WorkspaceWatchStatus['state'],error?:string)=>{owned.status={...statusBase,state,...(error?{error}:{})};for(const item of [...owned.listeners])notifyCallback(item.status,{...owned.status});};
40
- const publish=(changes:WorkspaceFileChange[],revision?:string)=>{
47
+ const publish=(changes:WorkspaceFileChange[],revision?:string,local=false)=>{
41
48
  if(!alive||!changes.length)return;
42
- const event:WorkspaceChangeEvent={type:'files_changed',jobId,mode:'poll',coverage:'listed-files',complete:false,changes,revision};
49
+ // 显式路径和目录子项可能命中同一文件;一批只交付一次,保留已有的前后元信息。
50
+ const unique=new Map<string,WorkspaceFileChange>();
51
+ for(const change of changes){
52
+ if(!local&&change.kind==='created'&&announcedCreates.has(change.path))continue;
53
+ const before=unique.get(change.path);
54
+ unique.set(change.path,before?{...before,...change,file:change.kind==='deleted'?undefined:change.file??before.file,previous:before.previous??change.previous}:change);
55
+ }
56
+ if(!unique.size)return;
57
+ const event:WorkspaceChangeEvent={type:'files_changed',jobId,mode:'poll',coverage:'listed-files',complete:false,changes:[...unique.values()],revision};
43
58
  for(const item of [...owned.listeners])notifyCallback(item.change,cloneWorkspaceChange(event));
44
59
  };
45
60
  const snapshot=(files:FileEntry[],paths:string[],state:ScanState):WorkspaceFileChange[]=>{
@@ -75,15 +90,61 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
75
90
  const ctl=new AbortController();controller=ctl;const token=++generation;
76
91
  let retryable=false;
77
92
  const current=()=>alive&&!ctl.signal.aborted&&token===generation;
78
- const state={baseline:new Map(baseline),known:new Set(known)},nextDirectories=new Map(directories),nextCursors=new Map(cursors);
93
+ const pendingCreates=new Set(announcedCreates);
94
+ const state={baseline:new Map(baseline),known:new Set(known)},nextDirectories=new Map(directories),nextCursors=new Map(cursors),nextDirEntries=new Map(dirEntries);
79
95
  try{
80
96
  const changes:WorkspaceFileChange[]=[];
97
+ /** 记下目录这一页的子项;之前记过且两次都列全了,就把差别报成子项的 created / deleted / modified。 */
98
+ const itemize=new Set(scope.entries??[]);
99
+ const childChanges=(dir:string,listing:{entries:FileEntry[];truncated?:boolean;nextCursor?:string})=>{
100
+ if(!itemize.has(dir))return;
101
+ const complete=!listing.truncated&&!listing.nextCursor&&Array.isArray(listing.entries)&&listing.entries.every(validFile);
102
+ const previous=nextDirEntries.get(dir);
103
+ if(!complete){nextDirEntries.delete(dir);return;}
104
+ const current=new Map(listing.entries.map(entry=>[entry.path,{...entry}]));
105
+ nextDirEntries.set(dir,current);
106
+ if(!previous)return;
107
+ for(const [path,file] of current){const before=previous.get(path);if(!before)changes.push({kind:'created',path,file});else if(fingerprint(before)!==fingerprint(file))changes.push({kind:'modified',path,file,previous:before});}
108
+ for(const [path,before] of previous)if(!current.has(path))changes.push({kind:'deleted',path,previous:before});
109
+ };
110
+ let accessError:string|undefined;
111
+ const forbidden=(error:unknown)=>(error as {status?:number;code?:string})?.status===403&&(error as {code?:string}).code==='file_forbidden';
112
+ const deny=(error:unknown,paths:string[],dirs:string[])=>{
113
+ accessError=error instanceof Error?error.message:String(error);
114
+ denyFileScope(backend,jobId,accessError,{paths,dirs});
115
+ };
116
+ // A rejected path in a batch is not evidence that the whole task lost access.
117
+ // Inspect only that batch's metadata; healthy files and directories remain usable.
118
+ const inspect=async(paths:string[],dirs:string[])=>{
119
+ const listed=new Map<string,FileEntry>(),deniedPaths=new Set<string>();
120
+ for(const dir of dirs){
121
+ try{
122
+ const result=await requests.run(()=>backend.stat(jobId,dir||'.'),ctl.signal);if(!current())return;
123
+ if(result.type!=='dir')continue;
124
+ for(const file of result.entries)listed.set(file.path,file);
125
+ const revision=result.revision??JSON.stringify(result.entries.map(file=>[file.path,fingerprint(file)]));
126
+ if(nextDirectories.has(dir)&&nextDirectories.get(dir)!==revision){changes.push({kind:'modified',path:dir});childChanges(dir,result);}
127
+ else if(!nextDirEntries.has(dir))childChanges(dir,result);
128
+ nextDirectories.set(dir,revision);
129
+ }catch(error){if(!current())return;if(!forbidden(error))throw error;deny(error,[],[dir||'.']);}
130
+ }
131
+ const files:FileEntry[]=[];
132
+ for(const path of paths){
133
+ const listedFile=listed.get(path);if(listedFile){files.push(listedFile);continue;}
134
+ try{const result=await requests.run(()=>backend.stat(jobId,path),ctl.signal);if(result.type==='file')files.push(result);}
135
+ catch(error){if(!current())return;if(forbidden(error)){deniedPaths.add(path);state.baseline.delete(path);state.known.delete(path);deny(error,[path],[]);}else if((error as {status?:number}).status!==404)throw error;}
136
+ if(!current())return;
137
+ }
138
+ changes.push(...snapshot(files,paths.filter(path=>!deniedPaths.has(path)),state));
139
+ };
81
140
  if(backend.pollFiles){
82
141
  const activeKeys=new Set<string>();
83
142
  const count=Math.max(Math.ceil(scope.paths.length/200),Math.ceil(scope.dirs.length/32));
84
143
  for(let index=0;index<count;index++){
85
144
  const paths=scope.paths.slice(index*200,index*200+200),dirs=scope.dirs.slice(index*32,index*32+32),key=JSON.stringify([paths,dirs]);activeKeys.add(key);
86
- const batch=await requests.run(()=>backend.pollFiles!(jobId,{paths,dirs,cursor:nextCursors.get(key)},ctl.signal),ctl.signal);
145
+ let batch:Awaited<ReturnType<NonNullable<BoardBackend['pollFiles']>>>;
146
+ try{batch=await requests.run(()=>backend.pollFiles!(jobId,{paths,dirs,cursor:nextCursors.get(key)},ctl.signal),ctl.signal);}
147
+ catch(error){if(!forbidden(error))throw error;nextCursors.delete(key);await inspect(paths,dirs);if(!current())return;continue;}
87
148
  if(!current())return;
88
149
  if(!batch||typeof batch!=='object')throw invalidResponse('文件变化响应不完整,请重试');
89
150
  if(batch.type==='resync'){cursors.delete(key);throw new Error('文件修订已变化,请重新核对');}
@@ -92,42 +153,40 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
92
153
  if(!Array.isArray(batch.directories))throw invalidResponse('目录变化响应不完整,请重试');
93
154
  for(const dir of batch.directories){
94
155
  if(!dir||!dirs.includes(dir.path)||(dir.revision!==null&&typeof dir.revision!=='string'))throw invalidResponse('目录变化响应范围错误');
95
- if(nextDirectories.has(dir.path)&&nextDirectories.get(dir.path)!==dir.revision)changes.push({kind:dir.revision===null?'deleted':'modified',path:dir.path});
156
+ const changed=nextDirectories.has(dir.path)&&nextDirectories.get(dir.path)!==dir.revision;
157
+ if(changed)changes.push({kind:dir.revision===null?'deleted':'modified',path:dir.path});
158
+ // 第一次看到这个目录先记下子项;之后目录变了再列一次,报出是哪些子项变了。删掉的目录不再列。
159
+ if(dir.revision===null)nextDirEntries.delete(dir.path);
160
+ else if(itemize.has(dir.path)&&(changed||!nextDirEntries.has(dir.path))){
161
+ // 尽力而为:列不出来只是这次不逐个报子项,不影响文件本身的变化。
162
+ try{const listing=await requests.run(()=>backend.stat(jobId,dir.path||'.'),ctl.signal);if(!current())return;if(listing.type==='dir')childChanges(dir.path,listing);else nextDirEntries.delete(dir.path);}
163
+ catch(error){if(!current())return;nextDirEntries.delete(dir.path);if(forbidden(error))deny(error,[],[dir.path||'.']);}
164
+ }
96
165
  nextDirectories.set(dir.path,dir.revision);
97
166
  }
98
167
  }
99
168
  for(const key of nextCursors.keys())if(!activeKeys.has(key))nextCursors.delete(key);
100
169
  }else{
101
170
  // Compatibility hosts: inspect requested entries, never recurse a workspace.
102
- const listed=new Map<string,FileEntry>();
103
- for(const dir of scope.dirs){
104
- const result=await requests.run(()=>backend.stat(jobId,dir||'.'),ctl.signal);if(!current())return;
105
- if(result.type!=='dir')continue;
106
- for(const file of result.entries)listed.set(file.path,file);
107
- const revision=result.revision??JSON.stringify(result.entries.map(file=>[file.path,fingerprint(file)]));
108
- if(nextDirectories.has(dir)&&nextDirectories.get(dir)!==revision)changes.push({kind:'modified',path:dir});
109
- nextDirectories.set(dir,revision);
110
- }
111
- const files:FileEntry[]=[];
112
- for(const path of scope.paths){
113
- const listedFile=listed.get(path);if(listedFile){files.push(listedFile);continue;}
114
- try{const result=await requests.run(()=>backend.stat(jobId,path),ctl.signal);if(result.type==='file')files.push(result);}
115
- catch(error){if((error as {status?:number}).status!==404)throw error;}
116
- if(!current())return;
117
- }
118
- changes.push(...snapshot(files,scope.paths,state));
171
+ await inspect(scope.paths,scope.dirs);
119
172
  }
120
173
  if(!current())return;
121
174
  const previews=backend.fileSync?await refreshFilePreviews(backend.fileSync,jobId,scope.paths,ctl.signal):undefined;
122
175
  if(!current())return;
176
+ for(const file of previews?.denied??[])deny(new Error(file.message),[file.path],[]);
123
177
  const changedPaths=new Set(changes.map(change=>change.path));
124
178
  for(const path of previews?.changed??[])if(!changedPaths.has(path)){changes.push({kind:'modified',path});changedPaths.add(path);}
125
179
  const active=new Set(scope.paths);for(const path of state.known)if(!active.has(path)){state.known.delete(path);state.baseline.delete(path);}
126
180
  for(const dir of nextDirectories.keys())if(!scope.dirs.includes(dir))nextDirectories.delete(dir);
127
181
  baseline=state.baseline;known=state.known;directories=nextDirectories;cursors=nextCursors;
182
+ for(const dir of [...nextDirEntries.keys()])if(!scope.dirs.includes(dir)||!itemize.has(dir))nextDirEntries.delete(dir);
183
+ dirEntries=nextDirEntries;
128
184
  publish(changes);
185
+ // The next completed scan has established the uploaded file's baseline.
186
+ // Unwatched uploads need no retained deduplication entry.
187
+ for(const path of pendingCreates)announcedCreates.delete(path);
129
188
  if(previews?.error)throw previews.error;
130
- failed=0;serverNotBefore=0;retryAt=0;exhaustedUntil=0;if(current())status('ready');
189
+ failed=0;serverNotBefore=0;retryAt=0;exhaustedUntil=0;if(current())status(accessError?'error':'ready',accessError);
131
190
  }catch(error){if(current()){
132
191
  failed++;const code=(error as {status?:number}).status??0;
133
192
  const failureCode=(error as {code?:string}).code;
@@ -139,7 +198,7 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
139
198
  retryAt=Math.max(Date.now()+base,serverNotBefore)+Math.floor(Math.random()*base/2);
140
199
  if(failed>retryDelays.length)exhaustedUntil=Math.max(Date.now()+30000,serverNotBefore);
141
200
  }
142
- if([401,403].includes(code))denyFileScope(backend,jobId);
201
+ if([401,403].includes(code))denyFileScope(backend,jobId,error instanceof Error?error.message:undefined);
143
202
  status('error',error instanceof Error?error.message:String(error));
144
203
  }}
145
204
  finally{if(controller===ctl){
@@ -187,6 +246,13 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
187
246
  const releasePreviews=backend.fileSync?onFilePreviewScope(backend.fileSync,jobId,()=>wake()):()=>{};
188
247
  if(typeof window!=='undefined'){window.addEventListener('online',recover);document.addEventListener('visibilitychange',visibility);}
189
248
  owned.retry=wake;
249
+ owned.created=path=>{
250
+ if(!alive||!path||announcedCreates.has(path))return;
251
+ announcedCreates.add(path);
252
+ generation++;const old=controller;controller=null;old?.abort();
253
+ publish([{kind:'created',path}],undefined,true);
254
+ wake();
255
+ };
190
256
  owned.stop=()=>{alive=false;clearTimer();controller?.abort();releaseScope();releasePreviews();if(typeof window!=='undefined'){window.removeEventListener('online',recover);document.removeEventListener('visibilitychange',visibility);}};
191
257
  queueMicrotask(()=>{if(alive)void scan();});
192
258
  }
@@ -0,0 +1,68 @@
1
+ // 对话与看板的联动(中枢适配的仓库 store、节点适配的 boardInteraction / boardState 共用)。纯 TS,没有 React。
2
+ //
3
+ // · createBoardSurfaces:「在看板里打开」的接收方登记表——对话里点了文件 / 「查看浏览器」,交给哪个看板;
4
+ // · createBoardOwners:同一个对话(任务)开着几个看板时,各自报告的样子,生效的是哪一个。
5
+ //
6
+ // 每个适配各有一份实例(中枢:每个仓库一份;节点:页面里一份),规则只有这一份。
7
+ import type { BoardView } from "./workspace";
8
+ import { activateBoardOwner, reportBoardOwner, selectedBoardOwner } from "./context";
9
+
10
+ export interface BoardSurfaceEntry<T> {
11
+ /** 接得住(显示的就是这个对话 / 任务)就打开并返回 true。 */
12
+ surface: (target: T) => boolean;
13
+ owner?: string;
14
+ /** 嵌在对话里的看板(只接它自己那个对话组件的请求)。 */
15
+ inline?: boolean;
16
+ /** 越大越先问;缺省 2。 */
17
+ priority?: () => number;
18
+ }
19
+
20
+ export function createBoardSurfaces<T>() {
21
+ const entries: BoardSurfaceEntry<T>[] = [];
22
+ return {
23
+ /** 登记一个接收方;返回注销函数。后登记的先问(例如弹出的看板盖在常驻的上面)。 */
24
+ register(surface: (target: T) => boolean, options: Omit<BoardSurfaceEntry<T>, "surface"> = {}): () => void {
25
+ const entry = { surface, ...options };
26
+ entries.push(entry);
27
+ return () => { const at = entries.indexOf(entry); if (at >= 0) entries.splice(at, 1); };
28
+ },
29
+ /** 依次问(后登记的先问,再按 priority 从高到低),有一个接住就停;filter 排除不该问的。一个接收方出错不影响别的。 */
30
+ open(target: T, filter?: (entry: BoardSurfaceEntry<T>) => boolean): boolean {
31
+ const available = [...entries].reverse().filter((entry) => !filter || filter(entry))
32
+ .sort((a, b) => (b.priority?.() ?? 2) - (a.priority?.() ?? 2));
33
+ for (const { surface } of available) {
34
+ let handled = false;
35
+ try { handled = surface(target); } catch (error) { console.error("[@spzxg/cli-ui] board surface callback failed", error); }
36
+ if (handled) return true;
37
+ }
38
+ return false;
39
+ },
40
+ };
41
+ }
42
+
43
+ /** 每个对话(任务)的各个看板(owner)报告的样子;生效的是最近在用、还开着的那个(规则见 board/context)。 */
44
+ export function createBoardOwners() {
45
+ const all = new Map<string, Map<string, BoardView>>();
46
+ const top = (sources: Map<string, BoardView> | undefined) => (sources?.size ? selectedBoardOwner(sources)?.[1] ?? null : null);
47
+ return {
48
+ /** 这个看板上次报告的样子。 */
49
+ previous(key: string, owner: string): BoardView | undefined { return all.get(key)?.get(owner); },
50
+ /** 记下 owner 的报告(null = 这个看板撤了),返回现在生效的样子。 */
51
+ report(key: string, owner: string, view: BoardView | null): BoardView | null {
52
+ const sources = all.get(key) ?? new Map<string, BoardView>();
53
+ if (view) reportBoardOwner(sources, owner, view); else sources.delete(owner);
54
+ if (sources.size) all.set(key, sources); else all.delete(key);
55
+ return top(sources);
56
+ },
57
+ /** 用户在 owner 这个看板上操作了:它变成生效的。没有这个看板时返回 null。 */
58
+ activate(key: string, owner: string): BoardView | null {
59
+ const sources = all.get(key);
60
+ if (!sources) return null;
61
+ return activateBoardOwner(sources, owner)?.[1] ?? null;
62
+ },
63
+ /** 现在生效的样子。 */
64
+ top(key: string): BoardView | null { return top(all.get(key)); },
65
+ /** 这个对话(任务)的全部看板报告(按先后)。 */
66
+ entries(key: string): Array<[string, BoardView]> { return [...all.get(key) ?? []]; },
67
+ };
68
+ }