@spzxg/cli-ui 0.6.13 → 0.6.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +100 -2
- package/README.md +131 -7
- package/dist/{cli-ui-embed-CXaGT9e4.js → cli-ui-embed-REq-GvM7.js} +20350 -19892
- package/dist/{cli-ui-index-bMQJjEBW.js → cli-ui-index-p_XTnmsN.js} +2 -2
- package/dist/{cli-ui-jszip.min-D_w3a6AF.js → cli-ui-jszip.min-0mqaiYeK.js} +1 -1
- package/dist/{cli-ui-jszip.min-AMeWMDT5.js → cli-ui-jszip.min-CJa9yrKW.js} +2 -2
- package/dist/{cli-ui-xlsx-DMzew4IO.js → cli-ui-xlsx-BPL7P3mE.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 +62 -27
- 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 +36 -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
package/src/chat/Composer.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// 输入框与 Operator 共用原件上传。上传完成只保留附件引用,用户发送时才交给 Agent。
|
|
2
2
|
// 没有原件上传适配器的宿主继续使用原有文档文本解析。
|
|
3
|
-
import { useEffect, useRef, useState, type ReactNode } from "react";
|
|
3
|
+
import { memo, useEffect, useRef, useState, type ReactNode } from "react";
|
|
4
4
|
import {
|
|
5
5
|
ACCEPT_ATTR, ACCEPTED_LABEL, MAX_MESSAGE_CHARS, PASTE_NAME, charCount, composeMessage, isLongText, readFileText, type TextBlock,
|
|
6
6
|
} from "../core/blocks";
|
|
@@ -24,7 +24,8 @@ export interface ComposerOptions {
|
|
|
24
24
|
queue: boolean;
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
// memo:对话每次重画(流式输出时每来一块一次)不带着输入框重画;参数由 CliChat 保持引用稳定。
|
|
28
|
+
export const Composer = memo(function Composer({ draft, placeholder, disabled, disabledHint, running, onSend, onStop, taskControl, options, toolbar, queued, context, uploadDocument }: {
|
|
28
29
|
/** 草稿按这个键存在 localStorage(一般是对话 id)。 */
|
|
29
30
|
draft: string;
|
|
30
31
|
placeholder: string;
|
|
@@ -57,7 +58,7 @@ export function Composer({ draft, placeholder, disabled, disabledHint, running,
|
|
|
57
58
|
const fileRef = useRef<HTMLInputElement>(null);
|
|
58
59
|
const ref = useRef<HTMLTextAreaElement>(null);
|
|
59
60
|
const uploads = useRef(new Map<string, AbortController>());
|
|
60
|
-
const selectedFiles = useRef(new Map<string, File>());
|
|
61
|
+
const selectedFiles = useRef(new Map<string, { file: File; upload?: UploadDocument }>());
|
|
61
62
|
|
|
62
63
|
useEffect(() => () => {
|
|
63
64
|
const owned = new Set(uploads.current.keys());
|
|
@@ -75,16 +76,16 @@ export function Composer({ draft, placeholder, disabled, disabledHint, running,
|
|
|
75
76
|
const nextKey = () => `blk-${clientId()}`;
|
|
76
77
|
const addBlock = (block: TextBlock) => setBlocks((prev) => [...prev, { ...block, key: nextKey() }]);
|
|
77
78
|
|
|
78
|
-
const addFiles = (files: File[]) => {
|
|
79
|
+
const addFiles = (files: File[], upload = uploadDocument) => {
|
|
79
80
|
if (disabled || sending || !options.fileUpload) return;
|
|
80
81
|
for (const file of files) {
|
|
81
82
|
const key = nextKey();
|
|
82
|
-
const original = !!
|
|
83
|
+
const original = !!upload;
|
|
83
84
|
const controller = new AbortController();
|
|
84
85
|
uploads.current.set(key, controller);
|
|
85
|
-
selectedFiles.current.set(key, file);
|
|
86
|
+
selectedFiles.current.set(key, { file, upload });
|
|
86
87
|
setPending((prev) => [...prev, { key, name: file.name || "文件", status: "reading", ...(original ? { phase: "queued" as const, bytes: 0, size: file.size } : {}) }]);
|
|
87
|
-
const content = original ? Promise.resolve().then(() =>
|
|
88
|
+
const content = original ? Promise.resolve().then(() => upload!(file, { draftId: clientId(), signal: controller.signal,
|
|
88
89
|
onPhase: phase => { if (!controller.signal.aborted) setPending(prev => prev.map(p => p.key === key ? { ...p, phase } : p)); },
|
|
89
90
|
onBytes: bytes => { if (!controller.signal.aborted) setPending(prev => prev.map(p => p.key === key ? { ...p, bytes } : p)); },
|
|
90
91
|
})).then(documentMarker) : readFileText(file);
|
|
@@ -173,7 +174,7 @@ export function Composer({ draft, placeholder, disabled, disabledHint, running,
|
|
|
173
174
|
bytes={p.bytes} total={p.size} error={p.error}
|
|
174
175
|
onCancel={() => { uploads.current.get(p.key)?.abort(); selectedFiles.current.delete(p.key); setPending(prev => prev.filter(x => x.key !== p.key)); }}
|
|
175
176
|
onRemove={() => { selectedFiles.current.delete(p.key); setPending(prev => prev.filter(x => x.key !== p.key)); }}
|
|
176
|
-
onRetry={selectedFiles.current.has(p.key) ? () => { if (disabled || sending) return; const
|
|
177
|
+
onRetry={selectedFiles.current.has(p.key) ? () => { if (disabled || sending) return; const selected = selectedFiles.current.get(p.key)!; selectedFiles.current.delete(p.key); setPending(prev => prev.filter(x => x.key !== p.key)); addFiles([selected.file], selected.upload); } : undefined} /> : (
|
|
177
178
|
<div key={p.key} className={`attach-chip file ${p.status}`} title={p.error || p.name}>
|
|
178
179
|
<span className="attach-file">{Icon.doc()} {p.name}</span>
|
|
179
180
|
<span className={`attach-badge ${p.status === "error" ? "err" : ""}`}>{p.status === "reading" ? p.progress ?? "解析中…" : p.error}</span>
|
|
@@ -236,4 +237,4 @@ export function Composer({ draft, placeholder, disabled, disabledHint, running,
|
|
|
236
237
|
</div>
|
|
237
238
|
</div>
|
|
238
239
|
);
|
|
239
|
-
}
|
|
240
|
+
});
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// 编辑排队消息:把排队的正文拆回输入框——输入的文字 + 文本块(粘贴的长文本、文件原件、引用、业务背景)。
|
|
2
|
+
// 只去掉发送时会自动重新附带的部分:「看板正在看」的被动背景、带原件时自动加的那句提示。
|
|
3
|
+
import { ORIGINALS_NOTE, splitMessage, type TextBlock } from "../core/blocks";
|
|
4
|
+
import { clientId } from "../core/id";
|
|
5
|
+
import { updateComposerDraft } from "./draft";
|
|
6
|
+
|
|
7
|
+
export function queuedToDraft(content: string): { text: string; blocks: TextBlock[] } {
|
|
8
|
+
const texts: string[] = [];
|
|
9
|
+
const blocks: TextBlock[] = [];
|
|
10
|
+
for (const part of splitMessage(content)) {
|
|
11
|
+
if (part.kind === "text") texts.push(part.text);
|
|
12
|
+
else if (part.block.kind !== "viewing") blocks.push(part.block);
|
|
13
|
+
}
|
|
14
|
+
const text = texts.join("\n\n").split("\n").filter((line) => line.trim() !== ORIGINALS_NOTE).join("\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
15
|
+
return { text, blocks };
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** 放回输入框:排队的内容在前,输入框里还没发的草稿接在后面——两边都不丢。 */
|
|
19
|
+
export function restoreQueuedToDraft(draftId: string, content: string) {
|
|
20
|
+
const restored = queuedToDraft(content);
|
|
21
|
+
updateComposerDraft(draftId, (current) => ({
|
|
22
|
+
...current,
|
|
23
|
+
text: [restored.text, current.text].filter((value) => value.trim()).join("\n\n"),
|
|
24
|
+
blocks: [...restored.blocks.map((block) => ({ ...block, key: clientId() })), ...current.blocks],
|
|
25
|
+
error: null,
|
|
26
|
+
}));
|
|
27
|
+
}
|
package/src/components.tsx
CHANGED
|
@@ -9,5 +9,5 @@ export interface CliMsgListProps extends CenterMsgListProps { operator?: Compone
|
|
|
9
9
|
export interface CliChatProps extends CenterChatProps { operator?: ComponentProps<typeof SessionView> }
|
|
10
10
|
export interface CliBoardProps extends CenterBoardProps { operator?: ComponentProps<typeof SessionRail> }
|
|
11
11
|
export function CliMsgList(props: CliMsgListProps) { return props.operator ? <TasksColumn {...props.operator}/> : <CenterMsgList {...props}/>; }
|
|
12
|
-
export function CliChat(props: CliChatProps) { return props.operator ? <SessionView {...props.operator} composer={props.config?.composer ?? props.operator.composer} board={{...props.operator.board,autoContext:props.operator.board?.autoContext??props.passiveContext,onFilesChange:props.operator.board?.onFilesChange??props.onFilesChange,onFilesWatch:props.operator.board?.onFilesWatch??props.onFilesWatch,onBoardContextChange:props.operator.board?.onBoardContextChange??props.onBoardContextChange}}/> : <CenterChat {...props}/>; }
|
|
13
|
-
export function CliBoard(props: CliBoardProps) { return props.operator ? <SessionRail key={props.operator.task.id} {...props.operator} tabs={props.operator.tabs ?? props.tabs} availableTabs={props.operator.availableTabs ?? props.availableTabs} defaultTab={props.operator.defaultTab ?? props.defaultTab} autoContext={props.operator.autoContext ?? props.autoQuoteOpenFile} watchFiles={props.operator.watchFiles ?? props.watchFiles} fileWatchIntervalMs={props.operator.fileWatchIntervalMs ?? props.fileWatchIntervalMs} onFilesChange={props.operator.onFilesChange ?? props.onFilesChange} onFilesWatch={props.operator.onFilesWatch ?? props.onFilesWatch} onBoardContextChange={props.operator.onBoardContextChange ?? props.onBoardContextChange} onEvent={props.operator.onEvent ?? props.onEvent}/> : <CenterBoard {...props}/>; }
|
|
12
|
+
export function CliChat(props: CliChatProps) { return props.operator ? <SessionView {...props.operator} readOnly={props.readOnly || props.operator.readOnly} composer={props.config?.composer ?? props.operator.composer} board={{...props.operator.board,autoContext:props.operator.board?.autoContext??props.passiveContext,onFilesChange:props.operator.board?.onFilesChange??props.onFilesChange,onFilesWatch:props.operator.board?.onFilesWatch??props.onFilesWatch,onBoardContextChange:props.operator.board?.onBoardContextChange??props.onBoardContextChange}}/> : <CenterChat {...props}/>; }
|
|
13
|
+
export function CliBoard(props: CliBoardProps) { return props.operator ? <SessionRail key={props.operator.task.id} {...props.operator} readOnly={props.readOnly || props.operator.readOnly} tabs={props.operator.tabs ?? props.tabs} availableTabs={props.operator.availableTabs ?? props.availableTabs} defaultTab={props.operator.defaultTab ?? props.defaultTab} autoContext={props.operator.autoContext ?? props.autoQuoteOpenFile} watchFiles={props.operator.watchFiles ?? props.watchFiles} fileWatchIntervalMs={props.operator.fileWatchIntervalMs ?? props.fileWatchIntervalMs} onFilesChange={props.operator.onFilesChange ?? props.onFilesChange} onFilesWatch={props.operator.onFilesWatch ?? props.onFilesWatch} onBoardContextChange={props.operator.onBoardContextChange ?? props.onBoardContextChange} onEvent={props.operator.onEvent ?? props.onEvent}/> : <CenterBoard {...props}/>; }
|
package/src/core/blocks.ts
CHANGED
|
@@ -86,10 +86,13 @@ export function serializeBlock(block: TextBlock): string {
|
|
|
86
86
|
return `----- 附件:${name}(${charCount(block.text).toLocaleString("en-US")} 字)-----\n${block.text}\n${CLOSE(name)}`;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/** 带原件附件时自动加在正文后的一句(编辑排队消息放回输入框时去掉,发送时会重新加上)。 */
|
|
90
|
+
export const ORIGINALS_NOTE = "请先读取以下附件原件,再处理本条消息。";
|
|
91
|
+
|
|
89
92
|
/** 输入框里的文字 + 文本块 → 发给 center 的正文。 */
|
|
90
93
|
export function composeMessage(typed: string, blocks: TextBlock[]): string {
|
|
91
94
|
const originals = blocks.some(block => block.kind === "file" && (/^\[Attached (?:file|image): /.test(block.text) || /^\[文件原件:.*\]\(cli-upload:\/\//.test(block.text)));
|
|
92
|
-
return [typed.trim(), originals ?
|
|
95
|
+
return [typed.trim(), originals ? ORIGINALS_NOTE : "", ...blocks.map(serializeBlock)].filter(Boolean).join("\n\n");
|
|
93
96
|
}
|
|
94
97
|
|
|
95
98
|
export type MessagePart = { kind: "text"; text: string } | { kind: "block"; block: TextBlock };
|
package/src/core/client.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { SubagentTranscript } from "./subagents";
|
|
|
2
2
|
import { createSseParser } from "./sse";
|
|
3
3
|
import { NEW_TASK, parseConvKey } from "./conversation";
|
|
4
4
|
import type {
|
|
5
|
-
BoardInfo, BrowserMessage, BrowserStatus, CenterJob, CenterTask, CenterTurn, DiffResult, DirListing, FileInfo, Message,
|
|
5
|
+
BoardInfo, BrowserMessage, BrowserStatus, CenterJob, CenterTask, CenterTurn, DiffFile, DiffResult, DirListing, FileInfo, Message,
|
|
6
6
|
BatchStreamSnapshot, BrowserFramesState, NewConversationOptions, SendResult, StreamEnd, StreamItem, StreamSnapshot, WorkspaceFileBatch,
|
|
7
7
|
} from "./types";
|
|
8
8
|
import { decodeText } from "./textDecode";
|
|
@@ -60,6 +60,9 @@ export class CenterError extends Error {
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
/** 读改动(git diff)最多等多久:比中枢等节点的 50 秒、节点自己的 40 秒都长。 */
|
|
64
|
+
const DIFF_TIMEOUT_MS = 65_000;
|
|
65
|
+
|
|
63
66
|
/** center 的错误码翻成看得懂、知道怎么办的中文。 */
|
|
64
67
|
const ERROR_TEXT: Record<string, string> = {
|
|
65
68
|
conversation_closed: "这个对话已经结束,不能再发消息;需要继续请新建对话",
|
|
@@ -196,7 +199,15 @@ export interface BoardBackend {
|
|
|
196
199
|
* 弱网:FILE_HEADER_TIMEOUT_MS 内没回响应头、或传输中 FILE_STALL_MS 没收到数据,按网络错误(NETWORK)失败。
|
|
197
200
|
*/
|
|
198
201
|
readBuffer(jobId: string, path: string, opts?: { signal?: AbortSignal; onBytes?: (bytes: number) => void }): Promise<ArrayBuffer>;
|
|
199
|
-
|
|
202
|
+
/** fresh:不与已在途的同一请求共用结果(轮末刷新要的是这一刻之后的改动,不是之前发出的那次)。 */
|
|
203
|
+
diff(jobId: string, options?: { fresh?: boolean }): Promise<DiffResult>;
|
|
204
|
+
/**
|
|
205
|
+
* 渐进式改动(新版中枢 + 节点):只要文件列表和增删行数,不带 patch(summary=true)。etag 是上次拿到的,
|
|
206
|
+
* 没变时返回 { notModified: true },不传正文。旧版节点不认这个参数会回整份 diff(summary 不为 true),照用即可。
|
|
207
|
+
*/
|
|
208
|
+
diffSummary?(jobId: string, options?: { etag?: string; signal?: AbortSignal }): Promise<{ notModified: true; etag?: string } | (DiffResult & { etag?: string; notModified?: false })>;
|
|
209
|
+
/** 一个文件的 patch(点开改动里的某个文件时取)。旧版节点不认 path 参数时从整份 diff 里挑出它。 */
|
|
210
|
+
diffFile?(jobId: string, path: string, options?: { signal?: AbortSignal }): Promise<DiffFile | null>;
|
|
200
211
|
browserStatus(jobId: string): Promise<BrowserStatus>;
|
|
201
212
|
browserAction(jobId: string, action: "open" | "close" | "takeover" | "handback"): Promise<BrowserStatus>;
|
|
202
213
|
/** 浏览器状态实时流;返回停止函数。onClose 在断开时调用(error 为 null 表示正常结束)。 */
|
|
@@ -267,11 +278,12 @@ export function createCenterClient(options: CenterClientOptions = {}): Conversat
|
|
|
267
278
|
// 同一时刻对同一地址的 GET 只发一次,后来的共用结果:列表、对话、看板经常同时要同一份数据(同一个任务的详情、看板概况、目录),
|
|
268
279
|
// 浏览器对一个域名的连接有限,重复请求会把真正要紧的(点开文件、发消息)挤到后面排队。
|
|
269
280
|
const inflight = new Map<string, Promise<unknown>>();
|
|
270
|
-
|
|
281
|
+
// fresh:不搭在途的那次(它可能在数据变化之前发出),自己发一次;之后来的共用这一次。
|
|
282
|
+
function request<T>(path: string, init: RequestInit = {}, timeoutMs = options.requestTimeoutMs ?? 30_000, fresh = false): Promise<T> {
|
|
271
283
|
if ((init.method ?? "GET") !== "GET" || init.body) return send<T>(path, init, timeoutMs);
|
|
272
|
-
const shared = inflight.get(path);
|
|
284
|
+
const shared = fresh ? undefined : inflight.get(path);
|
|
273
285
|
if (shared) return shared as Promise<T>;
|
|
274
|
-
const p = send<T>(path, init, timeoutMs).finally(() => inflight.delete(path));
|
|
286
|
+
const p: Promise<T> = send<T>(path, init, timeoutMs).finally(() => { if (inflight.get(path) === p) inflight.delete(path); });
|
|
275
287
|
inflight.set(path, p);
|
|
276
288
|
return p;
|
|
277
289
|
}
|
|
@@ -292,7 +304,15 @@ export function createCenterClient(options: CenterClientOptions = {}): Conversat
|
|
|
292
304
|
throw new CenterError(`连不上任务中心:${error instanceof Error ? error.message : String(error)}`, "NETWORK", 0);
|
|
293
305
|
}
|
|
294
306
|
// 响应体也算在时限里(代理把响应头发了、正文却挂住)。
|
|
295
|
-
|
|
307
|
+
let text: string | null = null;
|
|
308
|
+
let readError: unknown = null;
|
|
309
|
+
try { text = await response.text(); } catch (error) { readError = error; } finally { clearTimeout(timer); }
|
|
310
|
+
// 空正文(204、只回状态的接口)照旧当 null;有内容却不是 JSON(代理 / 单点登录的 200 网页)单独报错。
|
|
311
|
+
let body: Record<string, unknown> | null = null;
|
|
312
|
+
let unreadable = false;
|
|
313
|
+
if (text?.trim()) {
|
|
314
|
+
try { body = JSON.parse(text) as Record<string, unknown> | null; } catch { unreadable = true; }
|
|
315
|
+
}
|
|
296
316
|
if (!response.ok) {
|
|
297
317
|
// 413:消息 / 请求体超过中枢上限(中枢回的是 Fastify 的英文说明)。
|
|
298
318
|
if (response.status === 413) throw new CenterError("内容太大,超过任务中心单次请求的上限,请删减或分几条发送", "payload_too_large", 413, body);
|
|
@@ -300,6 +320,14 @@ export function createCenterClient(options: CenterClientOptions = {}): Conversat
|
|
|
300
320
|
const detail = typeof body?.detail === "string" ? body.detail : undefined;
|
|
301
321
|
throw new CenterError(ERROR_TEXT[code] ?? detail ?? `任务中心返回错误(HTTP ${response.status})`, code, response.status, body);
|
|
302
322
|
}
|
|
323
|
+
// 成功状态却没读完正文 / 读到的不是数据:明确失败,不能当成「没有内容」让界面一直停在读取中。
|
|
324
|
+
if (readError) {
|
|
325
|
+
if (timedOut) throw new CenterError(`任务中心 ${Math.round(timeoutMs / 1000)} 秒没有响应,请稍后重试`, "NETWORK", 0);
|
|
326
|
+
throw new CenterError(`读取任务中心的响应时连接中断:${readError instanceof Error ? readError.message : String(readError)}`, "NETWORK", 0);
|
|
327
|
+
}
|
|
328
|
+
if (unreadable) {
|
|
329
|
+
throw new CenterError("任务中心返回的不是数据(可能是登录页或代理错误页),请刷新页面或重新登录后重试", "bad_response", response.status);
|
|
330
|
+
}
|
|
303
331
|
return body as T;
|
|
304
332
|
}
|
|
305
333
|
|
|
@@ -409,7 +437,9 @@ export function createCenterClient(options: CenterClientOptions = {}): Conversat
|
|
|
409
437
|
* 订阅对话的实时流(GET /api/jobs/:id/stream)。返回关闭函数。
|
|
410
438
|
* 不自动重连:重连策略(退避、结束后不再连)由调用方决定。
|
|
411
439
|
*/
|
|
412
|
-
board: createBoardClient(base, headers, doFetch, request, options.directFileLinks ?? (!options.token && !options.headers && !options.line)
|
|
440
|
+
board: createBoardClient(base, headers, doFetch, request, options.directFileLinks ?? (!options.token && !options.headers && !options.line),
|
|
441
|
+
// 改动:节点限时 40 秒、中枢等 50 秒;这里等得更久,让它们的答复(超时也有明确原因)先到。
|
|
442
|
+
Math.max(options.requestTimeoutMs ?? 30_000, DIFF_TIMEOUT_MS)),
|
|
413
443
|
stream(jobId: string, handlers: StreamHandlers, intervalMs = 300, taskId?: string | null): () => void {
|
|
414
444
|
const ctl = new AbortController();
|
|
415
445
|
let stopped = false;
|
|
@@ -575,8 +605,9 @@ function createBoardClient(
|
|
|
575
605
|
base: string,
|
|
576
606
|
headers: (extra?: Record<string, string>) => Record<string, string>,
|
|
577
607
|
doFetch: typeof fetch,
|
|
578
|
-
request: <T>(path: string, init?: RequestInit, timeoutMs?: number) => Promise<T>,
|
|
608
|
+
request: <T>(path: string, init?: RequestInit, timeoutMs?: number, fresh?: boolean) => Promise<T>,
|
|
579
609
|
directLinks: boolean,
|
|
610
|
+
diffTimeoutMs = DIFF_TIMEOUT_MS,
|
|
580
611
|
): BoardBackend {
|
|
581
612
|
/**
|
|
582
613
|
* 取文件:响应头限时 FILE_HEADER_TIMEOUT_MS;body() 边读边看门(FILE_STALL_MS 没数据就断),
|
|
@@ -712,6 +743,47 @@ function createBoardClient(
|
|
|
712
743
|
const LINK_REFRESH_MS = 5 * 60_000;
|
|
713
744
|
const uploads = new Map<string, UploadDocument>();
|
|
714
745
|
const fileSync = createFileSyncTransport(doFetch, (jobId, operation) => `${base}${boardPath(jobId, `file-sync/${operation}`)}`, headers);
|
|
746
|
+
// Summary and per-file patches share cancellation, timeouts and response validation.
|
|
747
|
+
async function readDiff(jobId: string, query: string, options: { etag?: string; signal?: AbortSignal } = {}): Promise<{ notModified: true; etag?: string } | (DiffResult & { etag?: string; notModified?: false })> {
|
|
748
|
+
if (options.signal?.aborted) throw new DOMException("已取消", "AbortError");
|
|
749
|
+
const ctl = new AbortController();
|
|
750
|
+
const cancel = () => ctl.abort();
|
|
751
|
+
options.signal?.addEventListener("abort", cancel, { once: true });
|
|
752
|
+
let timedOut = false;
|
|
753
|
+
const timer = setTimeout(() => { timedOut = true; ctl.abort(); }, diffTimeoutMs);
|
|
754
|
+
try {
|
|
755
|
+
let response: Response;
|
|
756
|
+
try {
|
|
757
|
+
response = await doFetch(`${base}${boardPath(jobId, "diff", query)}`, { headers: headers(options.etag ? { "If-None-Match": options.etag } : {}), signal: ctl.signal, cache: "no-store" });
|
|
758
|
+
} catch (error) {
|
|
759
|
+
if (options.signal?.aborted) throw new DOMException("已取消", "AbortError");
|
|
760
|
+
if (timedOut) throw new CenterError(`读取改动 ${Math.round(diffTimeoutMs / 1000)} 秒没有响应,请稍后重试`, "NETWORK", 0);
|
|
761
|
+
throw new CenterError(`连不上任务中心:${error instanceof Error ? error.message : String(error)}`, "NETWORK", 0);
|
|
762
|
+
}
|
|
763
|
+
const etag = response.headers.get("etag") ?? undefined;
|
|
764
|
+
if (response.status === 304) return { notModified: true as const, etag: etag ?? options.etag };
|
|
765
|
+
let text: string;
|
|
766
|
+
try { text = await response.text(); } catch (error) {
|
|
767
|
+
if (options.signal?.aborted) throw new DOMException("已取消", "AbortError");
|
|
768
|
+
if (timedOut) throw new CenterError(`读取改动 ${Math.round(diffTimeoutMs / 1000)} 秒没有响应,请稍后重试`, "NETWORK", 0);
|
|
769
|
+
throw new CenterError(`读取任务中心的响应时连接中断:${error instanceof Error ? error.message : String(error)}`, "NETWORK", 0);
|
|
770
|
+
}
|
|
771
|
+
let body: (DiffResult & { error?: string; detail?: string }) | null = null;
|
|
772
|
+
let unreadable = false;
|
|
773
|
+
if (text.trim()) { try { body = JSON.parse(text); } catch { unreadable = true; } }
|
|
774
|
+
if (response.ok && unreadable) throw new CenterError("任务中心返回的不是数据(可能是登录页或代理错误页),请刷新页面或重新登录后重试", "bad_response", response.status);
|
|
775
|
+
if (!response.ok) {
|
|
776
|
+
const code = typeof body?.error === "string" ? body.error : `HTTP_${response.status}`;
|
|
777
|
+
throw new CenterError(ERROR_TEXT[code] ?? body?.detail ?? `任务中心返回错误(HTTP ${response.status})`, code, response.status, body);
|
|
778
|
+
}
|
|
779
|
+
if (!body || typeof body !== "object") throw new CenterError("改动接口没有返回内容,请稍后重试", "bad_response", response.status);
|
|
780
|
+
return { ...body, ...(etag ? { etag } : {}) };
|
|
781
|
+
} finally {
|
|
782
|
+
clearTimeout(timer);
|
|
783
|
+
options.signal?.removeEventListener("abort", cancel);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
|
|
715
787
|
return {
|
|
716
788
|
directLinks,
|
|
717
789
|
uploadFile(jobId, file, options) {
|
|
@@ -772,7 +844,12 @@ function createBoardClient(
|
|
|
772
844
|
const { body } = await fileFetch(jobId, path, {}, opts.signal);
|
|
773
845
|
return (await body({ onBytes: opts.onBytes })).buffer;
|
|
774
846
|
},
|
|
775
|
-
diff: (jobId) => request<DiffResult>(boardPath(jobId, "diff")),
|
|
847
|
+
diff: (jobId, options) => request<DiffResult>(boardPath(jobId, "diff"), {}, diffTimeoutMs, options?.fresh),
|
|
848
|
+
diffSummary: (jobId, options) => readDiff(jobId, "summary=1", options),
|
|
849
|
+
async diffFile(jobId, path, options) {
|
|
850
|
+
const result = await readDiff(jobId, `path=${encodeURIComponent(path)}`, options);
|
|
851
|
+
return "notModified" in result && result.notModified ? null : result.files?.find((file) => file.path === path) ?? null;
|
|
852
|
+
},
|
|
776
853
|
browserStatus: (jobId) => request<BrowserStatus>(boardPath(jobId, "browser")),
|
|
777
854
|
browserAction: (jobId, action) => request<BrowserStatus>(boardPath(jobId, "browser"), { method: "POST", body: JSON.stringify({ action }) }, 150_000),
|
|
778
855
|
browserEvents: (jobId, handlers) => openSse(doFetch, `${base}${boardPath(jobId, "browser/events")}`, headers(), (event, data) => {
|
package/src/core/config.ts
CHANGED
|
@@ -146,7 +146,7 @@ export interface CliMsgListConfig {
|
|
|
146
146
|
newButton?: boolean;
|
|
147
147
|
/** 「+ 对话」按钮的文字。 */
|
|
148
148
|
newButtonText?: string;
|
|
149
|
-
/**
|
|
149
|
+
/** 手动刷新按钮,缺省隐藏。列表不定时轮询:打开着的对话实时更新,其余在页面回到前台、获得焦点、网络恢复时刷新。 */
|
|
150
150
|
refresh?: boolean;
|
|
151
151
|
/** 上下文说明框(需同时给 context 或 onEditContext)。 */
|
|
152
152
|
context?: boolean;
|
package/src/core/conversation.ts
CHANGED
|
@@ -68,13 +68,23 @@ export interface ConvState {
|
|
|
68
68
|
/** 节点转录(Operator 消息)。 */
|
|
69
69
|
msgs: Msg[];
|
|
70
70
|
hasTranscript: boolean;
|
|
71
|
+
/** 中枢说这段对话记录暂时读不到(transcript_unavailable);读到转录后清掉。 */
|
|
72
|
+
transcriptError: string | null;
|
|
71
73
|
/** 节点转录里比 msgs 更早、还没取的条数(实时流只给最新一段;往上翻时 store.loadOlder 分页取)。 */
|
|
72
74
|
older: number;
|
|
73
75
|
nodeRunning: boolean;
|
|
76
|
+
/**
|
|
77
|
+
* 收尾计数:一轮在节点上结束(中枢把这一轮标成结束;没有轮次的一次性任务看节点 turn_end)、对话结束、
|
|
78
|
+
* 断线重连后补齐时 +1。首次连上不算。看板的「改动」据此重读 diff。
|
|
79
|
+
*/
|
|
80
|
+
settled: number;
|
|
81
|
+
/** 运行中工具执行完的次数(节点 tool_result 事件):工具可能改了文件,看板的「改动」据此在一轮当中节流重读。 */
|
|
82
|
+
edits: number;
|
|
74
83
|
resolvedModel: string | null;
|
|
75
84
|
/** 上次刷新任务详情之后,实时流里累计的用量(usage 事件)。 */
|
|
76
85
|
liveUsage: { fresh: number; cacheRead: number };
|
|
77
|
-
|
|
86
|
+
/** offline:自动重连用完、已停下,等网络恢复 / 页面回到前台 / 获得焦点 / 发消息 / store.reconnect() 时再连。 */
|
|
87
|
+
stream: "idle" | "connecting" | "live" | "reconnecting" | "offline" | "ended" | "error";
|
|
78
88
|
streamError: string | null;
|
|
79
89
|
endReason: string | null;
|
|
80
90
|
/** 接续这个对话的新对话的键(对话任务结束后再发消息开出来的)。 */
|
|
@@ -91,7 +101,7 @@ export interface ConvState {
|
|
|
91
101
|
}
|
|
92
102
|
|
|
93
103
|
export const emptyConv = (key: string): ConvState => ({
|
|
94
|
-
key, ...parseConvKey(key), job: null, task: null, turns: [], msgs: [], hasTranscript: false, older: 0, nodeRunning: false, resolvedModel: null,
|
|
104
|
+
key, ...parseConvKey(key), job: null, task: null, turns: [], msgs: [], hasTranscript: false, transcriptError: null, older: 0, nodeRunning: false, settled: 0, edits: 0, resolvedModel: null,
|
|
95
105
|
liveUsage: { fresh: 0, cacheRead: 0 }, stream: "idle", streamError: null, endReason: null, continuedBy: null, localAnswers: {},
|
|
96
106
|
batch: false, batchTask: null, remoteTaskId: null,
|
|
97
107
|
});
|
|
@@ -155,7 +165,7 @@ function focusBatchTask(conv: ConvState, task: BatchStreamTask | null): ConvStat
|
|
|
155
165
|
const batchTask = task ? { ...kept, ...task } : null;
|
|
156
166
|
return {
|
|
157
167
|
...conv, batch: true, batchTask, task: batchTask ? batchStreamTask(batchTask) : null, remoteTaskId: remote,
|
|
158
|
-
...(sameRemote ? {} : { msgs: [], hasTranscript: false, older: 0, nodeRunning: false }),
|
|
168
|
+
...(sameRemote ? {} : { msgs: [], hasTranscript: false, transcriptError: null, older: 0, nodeRunning: false }),
|
|
159
169
|
};
|
|
160
170
|
}
|
|
161
171
|
|
|
@@ -184,12 +194,14 @@ export function applyItems(conv: ConvState, items: StreamItem[]): ConvState {
|
|
|
184
194
|
let next = conv;
|
|
185
195
|
for (const item of items) {
|
|
186
196
|
// 一次性任务:只认看的这个子任务所在的节点对话。
|
|
187
|
-
if (next.batch && (item.type === "transcript" || item.type === "node") && item.remote_task_id && item.remote_task_id !== next.remoteTaskId) continue;
|
|
197
|
+
if (next.batch && (item.type === "transcript" || item.type === "node" || item.type === "transcript_unavailable") && item.remote_task_id && item.remote_task_id !== next.remoteTaskId) continue;
|
|
188
198
|
if (item.type === "transcript") {
|
|
189
199
|
// 节点转录全量(连上 / 重连节点时各一次):整体替换,没变的消息保留对象引用。
|
|
190
200
|
const messages = Array.isArray(item.messages) ? item.messages.map(toMsg) : [];
|
|
191
201
|
const merged = mergeSnapshot(next.msgs, messages, typeof item.older === "number" ? item.older : 0);
|
|
192
|
-
next = { ...next, msgs: merged.msgs, older: merged.older, hasTranscript: true, nodeRunning: item.running === true };
|
|
202
|
+
next = { ...next, msgs: merged.msgs, older: merged.older, hasTranscript: true, transcriptError: null, nodeRunning: item.running === true };
|
|
203
|
+
} else if (item.type === "transcript_unavailable") {
|
|
204
|
+
if (!next.hasTranscript) next = { ...next, transcriptError: typeof item.error === "string" && item.error ? item.error : "暂时读不到这段对话记录" };
|
|
193
205
|
} else if (item.type === "node") {
|
|
194
206
|
next = applyNodeEvent(next, item.event);
|
|
195
207
|
} else if (item.type === "turn") {
|
|
@@ -220,6 +232,12 @@ const localId = (prefix: string) => `${prefix}-${Date.now()}-${++synthetic}`;
|
|
|
220
232
|
|
|
221
233
|
/** 节点的一个回合事件。与 Operator 的 handleStreamEvent 同一套规则。 */
|
|
222
234
|
export function applyNodeEvent(conv: ConvState, ev: NodeEvent): ConvState {
|
|
235
|
+
const next = applyTranscriptEvent(conv, ev);
|
|
236
|
+
// 工具执行完(不管对不对得上卡片)都算一次:看板的「改动」据此重读。
|
|
237
|
+
return ev.type === "tool_result" ? { ...next, edits: (next.edits ?? 0) + 1 } : next;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function applyTranscriptEvent(conv: ConvState, ev: NodeEvent): ConvState {
|
|
223
241
|
const e = ev as Record<string, any>;
|
|
224
242
|
const gen = typeof e.generation === "number" ? e.generation : 1;
|
|
225
243
|
const set = (msgs: Msg[]) => ({ ...conv, msgs });
|
|
@@ -21,8 +21,20 @@ export const uploadFileType = (name: string) => {
|
|
|
21
21
|
};
|
|
22
22
|
export type DocumentReceipt = { uploadId: string; draftId: string; name: string; size: number; sha256: string; path?: string; url?: string };
|
|
23
23
|
export type UploadPhase = "queued" | "checking" | "uploading" | "verifying";
|
|
24
|
-
export type DocumentUploadOptions = { draftId: string; signal?: AbortSignal; onBytes?: (bytes: number) => void; onPhase?: (phase: UploadPhase) => void };
|
|
24
|
+
export type DocumentUploadOptions = { draftId: string; destinationDir?: string; signal?: AbortSignal; onBytes?: (bytes: number) => void; onPhase?: (phase: UploadPhase) => void };
|
|
25
25
|
export type UploadDocument = (file: File, options: DocumentUploadOptions) => Promise<DocumentReceipt>;
|
|
26
|
+
/** 未确认属于当前工作区的绝对文件,不改变既有浏览目录。 */
|
|
27
|
+
export function workspaceFileDirectory(file: string, workspaceRoot?: string): string | undefined {
|
|
28
|
+
const path = file.replace(/\\/g, "/");
|
|
29
|
+
if (path.split("/").some(part => part === "..")) return;
|
|
30
|
+
let relative = path;
|
|
31
|
+
if (/^(?:\/|[a-z]:\/)/i.test(path)) {
|
|
32
|
+
const root = workspaceRoot?.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
33
|
+
if (root === undefined || !/^(?:\/|[a-z]:\/)/i.test(workspaceRoot ?? "") || !path.startsWith(`${root}/`)) return;
|
|
34
|
+
relative = path.slice(root.length + 1);
|
|
35
|
+
}
|
|
36
|
+
return relative.includes("/") ? relative.slice(0, relative.lastIndexOf("/")) : "";
|
|
37
|
+
}
|
|
26
38
|
const aborted = () => new DOMException("上传已取消", "AbortError");
|
|
27
39
|
function pause(ms: number, signal?: AbortSignal) {
|
|
28
40
|
return new Promise<void>((resolve, reject) => {
|
|
@@ -94,7 +106,7 @@ export async function documentRequest<T>(fetcher: typeof fetch, url: string, ini
|
|
|
94
106
|
if (response.status === 202) throw Object.assign(new Error("文件正在校验"), { status: 202, retryAfterMs: retryAfterMs ?? 1000 });
|
|
95
107
|
if (!response.ok) {
|
|
96
108
|
const missing = value.error === "file_not_found" ? "文件不存在(可能已被删除或改名)" : "服务端尚未支持原件上传或增量文件同步,请升级节点和中枢";
|
|
97
|
-
const common: Record<string, string> = { file_sync_busy: "文件服务繁忙,请稍后重试", too_many_snapshot_builds: "文件服务繁忙,请稍后重试", too_many_uploads: "上传任务较多,请稍后重试", file_sync_queue_timeout: "文件处理排队超时,请稍后重试", file_sync_timeout: "文件服务响应超时,请重试", snapshot_cache_full: "文件缓存空间不足,请稍后重试", upload_storage_full: "文件上传空间不足,请稍后重试" };
|
|
109
|
+
const common: Record<string, string> = { file_exists: "目标目录已有同名文件,请重命名后重新上传;已有文件不会被覆盖", upload_destination_forbidden: "只能上传到当前任务工作区内的目录", upload_directory_not_found: "上传目标目录不存在,请重新选择目录", file_sync_busy: "文件服务繁忙,请稍后重试", too_many_snapshot_builds: "文件服务繁忙,请稍后重试", too_many_uploads: "上传任务较多,请稍后重试", file_sync_queue_timeout: "文件处理排队超时,请稍后重试", file_sync_timeout: "文件服务响应超时,请重试", snapshot_cache_full: "文件缓存空间不足,请稍后重试", upload_storage_full: "文件上传空间不足,请稍后重试" };
|
|
98
110
|
const error = new Error(common[String(value.error)] ?? String(value.detail || (response.status === 404 ? missing : value.error) || `文件请求失败(HTTP ${response.status})`));
|
|
99
111
|
Object.assign(error, { status: response.status, code: value.error, ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
|
|
100
112
|
throw error;
|
|
@@ -129,6 +141,7 @@ export function createDocumentUploader(fetcher: typeof fetch, base: string, head
|
|
|
129
141
|
let queue = uploadQueues.get(fetcher);
|
|
130
142
|
if (!queue) { queue = createFileWorkQueue(1, 128); uploadQueues.set(fetcher, queue); }
|
|
131
143
|
return (file, options) => {
|
|
144
|
+
const destinationDir = options.destinationDir;
|
|
132
145
|
options.onPhase?.("queued");
|
|
133
146
|
const upload = async (): Promise<DocumentReceipt> => {
|
|
134
147
|
const { signal, onBytes, onPhase, draftId } = options;
|
|
@@ -139,9 +152,13 @@ export function createDocumentUploader(fetcher: typeof fetch, base: string, head
|
|
|
139
152
|
if (file.size > maxBytes) throw new Error(`“${file.name}”超过 ${isOriginalDocument(file.name) ? "100" : "10"} MiB,请缩小后重试。`);
|
|
140
153
|
if (new TextEncoder().encode(file.name).length > 240) throw new Error("文件名超过 240 个 UTF-8 字节,请缩短文件名后重试。");
|
|
141
154
|
onPhase?.("checking");
|
|
142
|
-
const sha256 = await hashDocument(file, signal);
|
|
143
155
|
const request = <T>(path: string, init: RequestInit) => documentRequest<T>(fetcher, `${base}${path}`, { ...init, signal }, headers);
|
|
144
|
-
|
|
156
|
+
if (destinationDir !== undefined) {
|
|
157
|
+
const capabilities = await retryUploadRequest(() => request<{ uploadDestinationDir?: boolean }>("/capabilities", {}), signal);
|
|
158
|
+
if (capabilities.uploadDestinationDir !== true) throw new Error("服务端尚未支持上传到当前目录,请升级节点和中枢");
|
|
159
|
+
}
|
|
160
|
+
const sha256 = await hashDocument(file, signal);
|
|
161
|
+
const session = await retryUploadRequest(() => request<{ uploadId: string; chunkBytes: number }>("/uploads", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ draftId, name: file.name, size: file.size, type, sha256, ...(destinationDir !== undefined ? { destinationDir } : {}) }) }), signal, true);
|
|
145
162
|
if (!session.uploadId || session.chunkBytes !== DOCUMENT_CHUNK_BYTES) throw new Error("上传协议不匹配,请升级服务端");
|
|
146
163
|
const root = `/uploads/${encodeURIComponent(session.uploadId)}`;
|
|
147
164
|
try {
|
|
@@ -179,7 +196,7 @@ export function createDocumentUploader(fetcher: typeof fetch, base: string, head
|
|
|
179
196
|
|
|
180
197
|
export function documentMarker(receipt: DocumentReceipt) {
|
|
181
198
|
if (receipt.path) {
|
|
182
|
-
if (/[\r\n
|
|
199
|
+
if (/[\r\n]/.test(receipt.path)) throw new Error("上传文件路径无效,请重试");
|
|
183
200
|
return `[Attached ${uploadFileType(receipt.name)?.startsWith("image/") ? "image" : "file"}: ${receipt.path}]`;
|
|
184
201
|
}
|
|
185
202
|
const name = receipt.name.replace(/[\r\n\[\]]/g, " ");
|
package/src/core/provider.tsx
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { notifyCallback } from "./callbacks";
|
|
2
2
|
import { Fragment, createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useSyncExternalStore, type ReactNode } from "react";
|
|
3
3
|
import { connectionDraftScope } from "./identity";
|
|
4
|
-
import { createCliStore, cloneWorkspaceEvent, type CliEvent, type CliState, type CliStore, type CliStoreOptions } from "./store";
|
|
5
|
-
import type { ConversationCallback, ConversationEndPayload, TurnEndPayload } from "./types";
|
|
4
|
+
import { createCliStore, cloneResultPayload, cloneWorkspaceEvent, type CliEvent, type CliState, type CliStore, type CliStoreOptions } from "./store";
|
|
5
|
+
import type { ConversationCallback, ConversationEndPayload, TaskAttemptEndPayload, TaskEndPayload, TurnEndPayload } from "./types";
|
|
6
6
|
|
|
7
7
|
/**
|
|
8
8
|
* 积木的拼接点。放在同一个 <CliCenterProvider> 里的组件共享一个仓库,切换时一起变:
|
|
@@ -48,19 +48,25 @@ export interface ResultHandlers extends WorkspaceHandlers {
|
|
|
48
48
|
onTurnEnd?: (payload: TurnEndPayload) => void;
|
|
49
49
|
/** 对话结束(关闭 / 取消 / 过期……)。 */
|
|
50
50
|
onConversationEnd?: (payload: ConversationEndPayload) => void;
|
|
51
|
+
/** 一次性任务(含续派)里一个子任务结束(成功 / 失败 / 取消)。字段与中枢一次性任务回调体 tasks[] 的一项同名。 */
|
|
52
|
+
onTaskEnd?: (payload: TaskEndPayload) => void;
|
|
53
|
+
/** 一次已派发执行批次结束(成功 / 失败 / 取消);旧服务缺少 execution_id 时不通知。 */
|
|
54
|
+
onTaskAttemptEnd?: (payload: TaskAttemptEndPayload) => void;
|
|
51
55
|
/** @deprecated 旧名字,等同于同时监听 onTurnEnd 和 onConversationEnd(payload.type 区分)。 */
|
|
52
56
|
onCallback?: (payload: ConversationCallback) => void;
|
|
53
57
|
}
|
|
54
58
|
|
|
55
59
|
export function dispatchResult(event: CliEvent, handlers: ResultHandlers) {
|
|
56
|
-
if (event.type === "conversation_turn") { notifyCallback(handlers.onTurnEnd, event.payload); notifyCallback(handlers.onCallback, event.payload); }
|
|
57
|
-
else if (event.type === "conversation_closed") { notifyCallback(handlers.onConversationEnd, event.payload); notifyCallback(handlers.onCallback, event.payload); }
|
|
60
|
+
if (event.type === "conversation_turn") { notifyCallback(handlers.onTurnEnd, cloneResultPayload(event.payload)); notifyCallback(handlers.onCallback, cloneResultPayload(event.payload)); }
|
|
61
|
+
else if (event.type === "conversation_closed") { notifyCallback(handlers.onConversationEnd, cloneResultPayload(event.payload)); notifyCallback(handlers.onCallback, cloneResultPayload(event.payload)); }
|
|
62
|
+
else if (event.type === "task_end") notifyCallback(handlers.onTaskEnd, cloneResultPayload(event.payload));
|
|
63
|
+
else if (event.type === "task_attempt_end") notifyCallback(handlers.onTaskAttemptEnd, cloneResultPayload(event.payload));
|
|
58
64
|
else if(event.type === "files_changed") notifyCallback(handlers.onFilesChange,event);
|
|
59
65
|
else if(event.type === "files_watch") notifyCallback(handlers.onFilesWatch,event);
|
|
60
66
|
else if(event.type === "board_context") notifyCallback(handlers.onBoardContextChange,event);
|
|
61
67
|
}
|
|
62
68
|
|
|
63
|
-
export function CliCenterProvider({ store: external, selectedId, onEvent, onTurnEnd, onConversationEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, children, ...options }: CliCenterProviderProps) {
|
|
69
|
+
export function CliCenterProvider({ store: external, selectedId, onEvent, onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, children, ...options }: CliCenterProviderProps) {
|
|
64
70
|
// 连接参数只在建仓库时用一次:中途换 baseUrl / token 请换 key 重建。
|
|
65
71
|
const optionsRef = useRef(options);
|
|
66
72
|
const applied = useRef<string | null | undefined>(undefined);
|
|
@@ -86,7 +92,7 @@ export function CliCenterProvider({ store: external, selectedId, onEvent, onTurn
|
|
|
86
92
|
const onEventRef = useRef(onEvent);
|
|
87
93
|
onEventRef.current = onEvent;
|
|
88
94
|
const resultRef = useRef<ResultHandlers>({});
|
|
89
|
-
resultRef.current = { onTurnEnd, onConversationEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange };
|
|
95
|
+
resultRef.current = { onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange };
|
|
90
96
|
useEffect(() => store.on((event) => {
|
|
91
97
|
notifyCallback(onEventRef.current, cloneWorkspaceEvent(event));
|
|
92
98
|
dispatchResult(event, resultRef.current);
|
|
@@ -113,11 +119,11 @@ export function useCliState<T>(selector: (state: CliState) => T): T {
|
|
|
113
119
|
/** 组件外面没有 Provider 时,用组件自己的 props 包一层。 */
|
|
114
120
|
export function withOwnProvider<P extends object>(props: P & CliStoreOptions & ResultHandlers & { onEvent?: (event: CliEvent) => void; store?: CliStore }, inner: ReactNode, hasContext: boolean) {
|
|
115
121
|
if (hasContext) return inner;
|
|
116
|
-
const { baseUrl, token, line, headers, fetch, client, namespace, newConversation, createConversation, businessIdFor, onEvent, onTurnEnd, onConversationEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, store } = props;
|
|
122
|
+
const { baseUrl, token, line, headers, fetch, client, namespace, newConversation, createConversation, businessIdFor, onEvent, onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, store } = props;
|
|
117
123
|
// 连接参数变了(换了中枢地址、令牌、产品线、命名空间)就换一个新仓库重连,不沿用旧连接。
|
|
118
124
|
const connection = connectionDraftScope({baseUrl,token,line,namespace,headers,fetch,client});
|
|
119
125
|
return (
|
|
120
|
-
<CliCenterProvider key={store ? "external" : connection} {...{ baseUrl, token, line, headers, fetch, client, namespace, newConversation, createConversation, businessIdFor, onEvent, onTurnEnd, onConversationEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, store }}>
|
|
126
|
+
<CliCenterProvider key={store ? "external" : connection} {...{ baseUrl, token, line, headers, fetch, client, namespace, newConversation, createConversation, businessIdFor, onEvent, onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, store }}>
|
|
121
127
|
{inner}
|
|
122
128
|
</CliCenterProvider>
|
|
123
129
|
);
|