@spzxg/cli-ui 0.6.13 → 0.6.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +108 -2
- package/README.md +140 -7
- package/dist/{cli-ui-embed-CXaGT9e4.js → cli-ui-embed-Dsw7A8BQ.js} +20333 -19872
- package/dist/{cli-ui-index-bMQJjEBW.js → cli-ui-index-CHFgaDHY.js} +2 -2
- package/dist/{cli-ui-jszip.min-D_w3a6AF.js → cli-ui-jszip.min-DDRprLiN.js} +1 -1
- package/dist/{cli-ui-jszip.min-AMeWMDT5.js → cli-ui-jszip.min-Dw9DMuD5.js} +2 -2
- package/dist/{cli-ui-xlsx-DMzew4IO.js → cli-ui-xlsx-BUG2_Azh.js} +1 -1
- package/dist/cli-ui.css +1 -1
- package/dist/cli-ui.js +1 -1
- package/package.json +1 -1
- package/src/board/BrowserPane.tsx +93 -30
- package/src/board/ChangesPane.tsx +86 -62
- package/src/board/CliBoard.tsx +65 -30
- package/src/board/FileViewer.tsx +49 -13
- package/src/board/context.ts +38 -7
- package/src/board/diffLines.ts +46 -0
- package/src/board/diffRefresh.ts +63 -0
- package/src/board/fileDiff.tsx +117 -0
- package/src/board/fileKind.ts +5 -3
- package/src/board/fileScope.ts +4 -2
- package/src/board/fileWatch.ts +59 -9
- package/src/board/linkage.ts +68 -0
- package/src/board/pathResolve.ts +108 -0
- package/src/board/useBoardUpload.tsx +7 -7
- package/src/board/workspace.ts +7 -1
- package/src/chat/CliChat.tsx +197 -216
- package/src/chat/Composer.tsx +10 -9
- package/src/chat/queueEdit.ts +27 -0
- package/src/components.tsx +2 -2
- package/src/core/blocks.ts +4 -1
- package/src/core/client.ts +86 -9
- package/src/core/config.ts +1 -1
- package/src/core/conversation.ts +23 -5
- package/src/core/documentUpload.ts +22 -5
- package/src/core/provider.tsx +14 -8
- package/src/core/store.ts +307 -63
- package/src/core/types.ts +49 -0
- package/src/elements.tsx +8 -5
- package/src/msglist/CliMsgList.tsx +30 -9
- package/src/operator/node/AgentConnect.tsx +28 -29
- package/src/operator/node/AppearancePanel.tsx +1 -1
- package/src/operator/node/BranchHistory.tsx +11 -7
- package/src/operator/node/BranchNavigator.tsx +1 -1
- package/src/operator/node/BrowserPane.tsx +7 -7
- package/src/operator/node/Chat.tsx +53 -272
- package/src/operator/node/CommandPalette.tsx +1 -1
- package/src/operator/node/Composer.tsx +13 -6
- package/src/operator/node/Layout.tsx +1 -1
- package/src/operator/node/Markdown.tsx +6 -36
- package/src/operator/node/Modal.tsx +1 -1
- package/src/operator/node/OnboardingWizard.tsx +11 -9
- package/src/operator/node/Orchestrator.tsx +18 -8
- package/src/operator/node/ProjectLanding.tsx +1 -1
- package/src/operator/node/ProjectsColumn.tsx +1 -1
- package/src/operator/node/ProviderAuth.tsx +16 -16
- package/src/operator/node/RunSwitch.tsx +1 -1
- package/src/operator/node/Services.tsx +1 -1
- package/src/operator/node/SessionRail.tsx +55 -19
- package/src/operator/node/SessionView.tsx +18 -16
- package/src/operator/node/SettingsView.tsx +1 -1
- package/src/operator/node/TaskBoard.tsx +1 -1
- package/src/operator/node/TaskChanges.tsx +83 -108
- package/src/operator/node/TaskHero.tsx +5 -5
- package/src/operator/node/TasksColumn.tsx +1 -1
- package/src/operator/node/Transcript.tsx +15 -250
- package/src/operator/node/Welcome.tsx +1 -1
- package/src/operator/node/WorktreePrune.tsx +1 -1
- package/src/operator/node/api.ts +17 -0
- package/src/operator/node/boardBackend.ts +4 -1
- package/src/operator/node/boardEvents.ts +17 -3
- package/src/operator/node/boardInteraction.ts +7 -4
- package/src/operator/node/boardState.ts +23 -14
- package/src/operator/node/composerDraft.ts +22 -0
- package/src/operator/node/fileLinks.ts +4 -38
- package/src/operator/node/format.ts +13 -104
- package/src/operator/node/github.tsx +14 -14
- package/src/operator/node/liveStream.ts +47 -6
- package/src/operator/node/modals.tsx +59 -22
- package/src/operator/node/recheckOnReturn.ts +28 -0
- package/src/operator/node/shared.tsx +10 -50
- package/src/operator/node/types.ts +9 -0
- package/src/operator/node/useOrchestrator.ts +9 -8
- package/src/operator/node/useRecaps.ts +15 -4
- package/src/operator/node/useTaskStream.ts +2 -2
- package/src/operator.base.css +9 -4
- package/src/operator.css +9 -4
- package/src/styles.css +22 -8
- package/src/ui/Markdown.tsx +42 -21
- package/src/ui/Popover.tsx +1 -1
- package/src/ui/QueuedMessages.tsx +58 -15
- package/src/ui/SubagentChat.tsx +42 -6
- package/src/ui/Transcript.tsx +19 -14
- package/src/ui/fileLinks.ts +6 -3
- package/src/ui/format.ts +27 -9
- package/src/ui/icons.tsx +2 -0
- package/src/ui/shared.tsx +11 -7
- package/src/ui/transcriptModel.ts +40 -9
- package/src/ui/useTranscriptWindow.ts +253 -0
- package/src/operator/node/icons.tsx +0 -88
- 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
|
+
}
|
package/src/board/fileKind.ts
CHANGED
|
@@ -54,12 +54,13 @@ export function resolveRelative(fromFile: string, href: string): string {
|
|
|
54
54
|
return base.join("/");
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/**
|
|
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 (
|
|
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
|
|
package/src/board/fileScope.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { BoardBackend } from "../core/client";
|
|
2
2
|
|
|
3
|
-
|
|
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,7 +16,8 @@ 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
|
-
|
|
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
22
|
export function denyFileScope(backend: BoardBackend, jobId: string, message?: string, denied?: { paths: readonly string[]; dirs: readonly string[] }) {
|
|
21
23
|
for (const scope of scopes.get(backend)?.get(jobId)?.values() ?? []) {
|
package/src/board/fileWatch.ts
CHANGED
|
@@ -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[];
|
|
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
|
-
|
|
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,9 +90,23 @@ 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
|
|
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
|
+
};
|
|
81
110
|
let accessError:string|undefined;
|
|
82
111
|
const forbidden=(error:unknown)=>(error as {status?:number;code?:string})?.status===403&&(error as {code?:string}).code==='file_forbidden';
|
|
83
112
|
const deny=(error:unknown,paths:string[],dirs:string[])=>{
|
|
@@ -94,7 +123,8 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
|
|
|
94
123
|
if(result.type!=='dir')continue;
|
|
95
124
|
for(const file of result.entries)listed.set(file.path,file);
|
|
96
125
|
const revision=result.revision??JSON.stringify(result.entries.map(file=>[file.path,fingerprint(file)]));
|
|
97
|
-
if(nextDirectories.has(dir)&&nextDirectories.get(dir)!==revision)changes.push({kind:'modified',path:dir});
|
|
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);
|
|
98
128
|
nextDirectories.set(dir,revision);
|
|
99
129
|
}catch(error){if(!current())return;if(!forbidden(error))throw error;deny(error,[],[dir||'.']);}
|
|
100
130
|
}
|
|
@@ -123,7 +153,15 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
|
|
|
123
153
|
if(!Array.isArray(batch.directories))throw invalidResponse('目录变化响应不完整,请重试');
|
|
124
154
|
for(const dir of batch.directories){
|
|
125
155
|
if(!dir||!dirs.includes(dir.path)||(dir.revision!==null&&typeof dir.revision!=='string'))throw invalidResponse('目录变化响应范围错误');
|
|
126
|
-
|
|
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
|
+
}
|
|
127
165
|
nextDirectories.set(dir.path,dir.revision);
|
|
128
166
|
}
|
|
129
167
|
}
|
|
@@ -141,7 +179,12 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
|
|
|
141
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);}
|
|
142
180
|
for(const dir of nextDirectories.keys())if(!scope.dirs.includes(dir))nextDirectories.delete(dir);
|
|
143
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;
|
|
144
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);
|
|
145
188
|
if(previews?.error)throw previews.error;
|
|
146
189
|
failed=0;serverNotBefore=0;retryAt=0;exhaustedUntil=0;if(current())status(accessError?'error':'ready',accessError);
|
|
147
190
|
}catch(error){if(current()){
|
|
@@ -203,6 +246,13 @@ export function subscribeWorkspaceFiles(backend:BoardBackend,jobId:string,listen
|
|
|
203
246
|
const releasePreviews=backend.fileSync?onFilePreviewScope(backend.fileSync,jobId,()=>wake()):()=>{};
|
|
204
247
|
if(typeof window!=='undefined'){window.addEventListener('online',recover);document.addEventListener('visibilitychange',visibility);}
|
|
205
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
|
+
};
|
|
206
256
|
owned.stop=()=>{alive=false;clearTimer();controller?.abort();releaseScope();releasePreviews();if(typeof window!=='undefined'){window.removeEventListener('online',recover);document.removeEventListener('visibilitychange',visibility);}};
|
|
207
257
|
queueMicrotask(()=>{if(alive)void scan();});
|
|
208
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
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// 智能体在回复里写的相对路径打不开时(相对它 cd 进去的子目录写的,例如 manual/rules.md,实际在 data/run-1/prepare/manual/rules.md),
|
|
2
|
+
// 按这个对话自己的线索补全:消息里提到过的目录、工具读写过的完整路径、看板打开过的文件。
|
|
3
|
+
// 只用对话里已有的东西,不扫工作区;补出来的地址逐个向后端确认存在才算(中枢和节点适配共用)。
|
|
4
|
+
import type { BoardBackend } from "../core/client";
|
|
5
|
+
import type { Msg } from "../core/types";
|
|
6
|
+
import { localFilePath } from "../ui/fileLinks";
|
|
7
|
+
import { toolDataOf } from "../ui/transcriptModel";
|
|
8
|
+
|
|
9
|
+
/** 最多看最近这么多条消息、留这么多条线索、补出这么多个候选(每个候选要问一次后端)。 */
|
|
10
|
+
const HINT_MESSAGES = 400;
|
|
11
|
+
const HINT_MAX = 600;
|
|
12
|
+
export const CANDIDATE_MAX = 8;
|
|
13
|
+
/** 工具输出很长时只看开头这一段(ls / find 的结果里也有完整路径)。 */
|
|
14
|
+
const TOOL_RESULT_SCAN = 20_000;
|
|
15
|
+
|
|
16
|
+
export interface PathHint {
|
|
17
|
+
/** 规范化后的路径(相对工作目录或绝对路径,不带末尾斜杠)。 */
|
|
18
|
+
path: string;
|
|
19
|
+
/** 写的时候以 / 结尾:是目录。 */
|
|
20
|
+
dir: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// 路径样子的一段:至少有一个 /,不含空白、引号、括号和中文标点(路径里的中文本身照常保留)。
|
|
24
|
+
const TOKEN = /[^\s`'"<>()[\]{}|,。;:、!?“”‘’()【】《》]*\/[^\s`'"<>()[\]{}|,。;:、!?“”‘’()【】《》]*/gu;
|
|
25
|
+
const LINK = /\]\(([^)\s]+)\)/g;
|
|
26
|
+
|
|
27
|
+
function hintsFromText(text: string, out: PathHint[]) {
|
|
28
|
+
const raw: string[] = [];
|
|
29
|
+
for (const m of text.matchAll(LINK)) raw.push(m[1]);
|
|
30
|
+
for (const m of text.matchAll(TOKEN)) raw.push(m[0]);
|
|
31
|
+
for (const token of raw) {
|
|
32
|
+
const trimmed = token.replace(/[.,;:!?]+$/, "");
|
|
33
|
+
if (!trimmed || trimmed === "/" || /^\/+$/.test(trimmed)) continue;
|
|
34
|
+
const path = localFilePath(trimmed);
|
|
35
|
+
if (!path || !path.includes("/")) continue;
|
|
36
|
+
out.push({ path, dir: trimmed.endsWith("/") });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 对话里的路径线索,最近的在前(去重)。 */
|
|
41
|
+
export function pathHints(messages: readonly Msg[], extra: readonly string[] = []): PathHint[] {
|
|
42
|
+
const out: PathHint[] = [];
|
|
43
|
+
for (const path of [...extra].reverse()) { const p = localFilePath(path); if (p && p.includes("/")) out.push({ path: p, dir: false }); }
|
|
44
|
+
for (let i = messages.length - 1, seen = 0; i >= 0 && seen < HINT_MESSAGES; i--, seen++) {
|
|
45
|
+
const m = messages[i];
|
|
46
|
+
if (m.role === "tool") {
|
|
47
|
+
const data = toolDataOf(m);
|
|
48
|
+
hintsFromText([data.title, data.detail ?? "", (data.result ?? "").slice(0, TOOL_RESULT_SCAN)].join("\n"), out);
|
|
49
|
+
} else if (m.role !== "queued") hintsFromText(m.content, out);
|
|
50
|
+
if (out.length >= HINT_MAX * 2) break;
|
|
51
|
+
}
|
|
52
|
+
const seenPaths = new Set<string>();
|
|
53
|
+
return out.filter((h) => { const key = `${h.dir ? "d" : "f"}:${h.path}`; if (seenPaths.has(key)) return false; seenPaths.add(key); return true; }).slice(0, HINT_MAX);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const isAbsolute = (p: string) => p.startsWith("/") || p.startsWith("~") || /^[a-z]:\//i.test(p);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 相对路径 requested 可能指的完整路径,最可能的在前,最多 CANDIDATE_MAX 个:
|
|
60
|
+
* · 线索里的文件以 /requested 结尾;
|
|
61
|
+
* · 线索里出现了 requested 的第一段目录:取它前面的部分接上 requested;
|
|
62
|
+
* · 线索是目录:目录接上 requested。
|
|
63
|
+
* 绝对路径不补(照原样就是它)。
|
|
64
|
+
*/
|
|
65
|
+
export function candidatePaths(requested: string, hints: readonly PathHint[]): string[] {
|
|
66
|
+
const want = localFilePath(requested);
|
|
67
|
+
if (!want || isAbsolute(want)) return [];
|
|
68
|
+
const segs = want.split("/");
|
|
69
|
+
const out: string[] = [];
|
|
70
|
+
const add = (p: string) => { if (p !== want && !out.includes(p)) out.push(p); };
|
|
71
|
+
// 线索里直接就有这个文件:最可靠,放最前。
|
|
72
|
+
for (const h of hints) if (!h.dir && h.path.endsWith(`/${want}`)) add(h.path);
|
|
73
|
+
for (const h of hints) {
|
|
74
|
+
if (out.length >= CANDIDATE_MAX) break;
|
|
75
|
+
const parts = h.path.split("/");
|
|
76
|
+
for (let i = parts.length - 1; i > 0; i--) {
|
|
77
|
+
if (parts[i] !== segs[0]) continue;
|
|
78
|
+
add([...parts.slice(0, i), ...segs].join("/"));
|
|
79
|
+
}
|
|
80
|
+
if (h.dir) add(`${h.path}/${want}`);
|
|
81
|
+
}
|
|
82
|
+
return out.slice(0, CANDIDATE_MAX);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 原路径确实不存在(后端回 404)时,按线索补全并逐个确认:返回确实存在的那些(顺序同 candidatePaths)。
|
|
87
|
+
* 原路径存在、或者读失败不是因为不存在(断网、没权限):返回 [],不乱猜。
|
|
88
|
+
*/
|
|
89
|
+
export async function resolveMissingPath(backend: Pick<BoardBackend, "stat">, jobId: string, requested: string, hints: readonly PathHint[], signal?: AbortSignal): Promise<string[]> {
|
|
90
|
+
const candidates = candidatePaths(requested, hints);
|
|
91
|
+
if (!candidates.length) return [];
|
|
92
|
+
try {
|
|
93
|
+
await backend.stat(jobId, requested);
|
|
94
|
+
return [];
|
|
95
|
+
} catch (error) {
|
|
96
|
+
if ((error as { status?: number }).status !== 404) return [];
|
|
97
|
+
}
|
|
98
|
+
const found = new Array<boolean>(candidates.length).fill(false);
|
|
99
|
+
let next = 0;
|
|
100
|
+
const worker = async () => {
|
|
101
|
+
while (next < candidates.length && !signal?.aborted) {
|
|
102
|
+
const at = next++;
|
|
103
|
+
try { const info = await backend.stat(jobId, candidates[at]); found[at] = info.type === "file"; } catch { /* 不存在或读不到:不算 */ }
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
await Promise.all(Array.from({ length: Math.min(4, candidates.length) }, worker));
|
|
107
|
+
return signal?.aborted ? [] : candidates.filter((_, i) => found[i]);
|
|
108
|
+
}
|
|
@@ -4,10 +4,10 @@ import type { DocumentReceipt, UploadDocument, UploadPhase } from "../core/docum
|
|
|
4
4
|
import { FILE_UPLOAD_ACCEPT } from "../core/documentUpload";
|
|
5
5
|
import { UploadProgress } from "../ui/UploadProgress";
|
|
6
6
|
|
|
7
|
-
type PendingUpload = { file: File; phase: UploadPhase | "ready" | "error"; bytes: number; error?: string };
|
|
7
|
+
type PendingUpload = { file: File; destinationDir?: string; phase: UploadPhase | "ready" | "error"; bytes: number; error?: string };
|
|
8
8
|
|
|
9
9
|
/** Uploading a file only changes the current workspace. It never submits a message. */
|
|
10
|
-
export function useBoardUpload(scope: string | null, upload: UploadDocument | undefined, onUploaded: (receipt: DocumentReceipt) => void) {
|
|
10
|
+
export function useBoardUpload(scope: string | null, upload: UploadDocument | undefined, onUploaded: (receipt: DocumentReceipt) => void, destinationDir?: string) {
|
|
11
11
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
12
12
|
const active = useRef<AbortController | null>(null);
|
|
13
13
|
const committedScope = useRef(scope);
|
|
@@ -18,20 +18,20 @@ export function useBoardUpload(scope: string | null, upload: UploadDocument | un
|
|
|
18
18
|
return () => { active.current?.abort(); active.current = null; };
|
|
19
19
|
}, [scope, upload]);
|
|
20
20
|
|
|
21
|
-
const start = (file: File) => {
|
|
21
|
+
const start = (file: File, targetDir = destinationDir) => {
|
|
22
22
|
if (!scope || !upload || active.current) return;
|
|
23
23
|
const controller = new AbortController();
|
|
24
24
|
active.current = controller;
|
|
25
25
|
const current = () => active.current === controller && committedScope.current === scope && !controller.signal.aborted;
|
|
26
|
-
setPending({ file, phase: "queued", bytes: 0 });
|
|
26
|
+
setPending({ file, destinationDir: targetDir, phase: "queued", bytes: 0 });
|
|
27
27
|
void Promise.resolve().then(() => upload(file, {
|
|
28
|
-
draftId: clientId(), signal: controller.signal,
|
|
28
|
+
draftId: clientId(), signal: controller.signal, ...(targetDir !== undefined ? { destinationDir: targetDir } : {}),
|
|
29
29
|
onPhase: phase => { if (current()) setPending(previous => previous ? { ...previous, phase } : previous); },
|
|
30
30
|
onBytes: bytes => { if (current()) setPending(previous => previous ? { ...previous, bytes } : previous); },
|
|
31
31
|
})).then(receipt => {
|
|
32
32
|
if (!current()) return;
|
|
33
33
|
if (!receipt.path) throw new Error("文件尚未进入当前工作区,请稍后重试");
|
|
34
|
-
setPending({ file, phase: "ready", bytes: file.size });
|
|
34
|
+
setPending({ file, destinationDir: targetDir, phase: "ready", bytes: file.size });
|
|
35
35
|
onUploaded(receipt);
|
|
36
36
|
}).catch(error => {
|
|
37
37
|
if (current()) setPending(previous => previous ? { ...previous, phase: "error", error: error instanceof Error ? error.message : "上传失败,请重试" } : previous);
|
|
@@ -46,6 +46,6 @@ export function useBoardUpload(scope: string | null, upload: UploadDocument | un
|
|
|
46
46
|
onChange={event => { const file = event.target.files?.[0]; event.target.value = ""; if (file) start(file); }} />,
|
|
47
47
|
progress: pending && <div className="cli-board-upload"><UploadProgress name={pending.file.name} status={pending.phase}
|
|
48
48
|
bytes={pending.bytes} total={pending.file.size} error={pending.error} onCancel={dismiss} onRemove={dismiss}
|
|
49
|
-
onRetry={() => start(pending.file)} /></div>,
|
|
49
|
+
onRetry={() => start(pending.file, pending.destinationDir)} /></div>,
|
|
50
50
|
};
|
|
51
51
|
}
|
package/src/board/workspace.ts
CHANGED
|
@@ -28,7 +28,7 @@ export const WORKSPACE_FILE_MAX = 500 * 1024 * 1024;
|
|
|
28
28
|
/** listAll 最多列这么多个文件。 */
|
|
29
29
|
export const WORKSPACE_LIST_MAX = 10_000;
|
|
30
30
|
|
|
31
|
-
export interface BoardFile { path: string; sourceId?: string }
|
|
31
|
+
export interface BoardFile { path: string; sourceId?: string; /** 服务端工作目录补齐的完整路径;path 保留原值。 */ absolutePath?: string }
|
|
32
32
|
|
|
33
33
|
/** 看板现在的样子(看板组件报告给仓库;没有看板时没有)。 */
|
|
34
34
|
export interface BoardView {
|
|
@@ -36,6 +36,12 @@ export interface BoardView {
|
|
|
36
36
|
tab: string;
|
|
37
37
|
/** 文件列表所在目录("" = 工作区根目录)。 */
|
|
38
38
|
dir: string;
|
|
39
|
+
/** 当前目录的来源任务;来源目录不能作为当前任务的上传目的地。 */
|
|
40
|
+
directorySourceId?: string;
|
|
41
|
+
/** 当前任务的可信工作目录,不用于猜测其他 sourceId 的文件路径。 */
|
|
42
|
+
workspaceRoot?: string;
|
|
43
|
+
/** 中枢适配当前对应的节点任务,仅用于已有附件和文件地址。 */
|
|
44
|
+
remoteTaskId?: string;
|
|
39
45
|
/** 正在看的文件(当前页签是文件时),否则 null。 */
|
|
40
46
|
file: string | null;
|
|
41
47
|
/** 开着的文件页签。 */
|