@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.
Files changed (100) hide show
  1. package/CHANGELOG.md +108 -2
  2. package/README.md +140 -7
  3. package/dist/{cli-ui-embed-CXaGT9e4.js → cli-ui-embed-Dsw7A8BQ.js} +20333 -19872
  4. package/dist/{cli-ui-index-bMQJjEBW.js → cli-ui-index-CHFgaDHY.js} +2 -2
  5. package/dist/{cli-ui-jszip.min-D_w3a6AF.js → cli-ui-jszip.min-DDRprLiN.js} +1 -1
  6. package/dist/{cli-ui-jszip.min-AMeWMDT5.js → cli-ui-jszip.min-Dw9DMuD5.js} +2 -2
  7. package/dist/{cli-ui-xlsx-DMzew4IO.js → cli-ui-xlsx-BUG2_Azh.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 +65 -30
  14. package/src/board/FileViewer.tsx +49 -13
  15. package/src/board/context.ts +38 -7
  16. package/src/board/diffLines.ts +46 -0
  17. package/src/board/diffRefresh.ts +63 -0
  18. package/src/board/fileDiff.tsx +117 -0
  19. package/src/board/fileKind.ts +5 -3
  20. package/src/board/fileScope.ts +4 -2
  21. package/src/board/fileWatch.ts +59 -9
  22. package/src/board/linkage.ts +68 -0
  23. package/src/board/pathResolve.ts +108 -0
  24. package/src/board/useBoardUpload.tsx +7 -7
  25. package/src/board/workspace.ts +7 -1
  26. package/src/chat/CliChat.tsx +197 -216
  27. package/src/chat/Composer.tsx +10 -9
  28. package/src/chat/queueEdit.ts +27 -0
  29. package/src/components.tsx +2 -2
  30. package/src/core/blocks.ts +4 -1
  31. package/src/core/client.ts +86 -9
  32. package/src/core/config.ts +1 -1
  33. package/src/core/conversation.ts +23 -5
  34. package/src/core/documentUpload.ts +22 -5
  35. package/src/core/provider.tsx +14 -8
  36. package/src/core/store.ts +307 -63
  37. package/src/core/types.ts +49 -0
  38. package/src/elements.tsx +8 -5
  39. package/src/msglist/CliMsgList.tsx +30 -9
  40. package/src/operator/node/AgentConnect.tsx +28 -29
  41. package/src/operator/node/AppearancePanel.tsx +1 -1
  42. package/src/operator/node/BranchHistory.tsx +11 -7
  43. package/src/operator/node/BranchNavigator.tsx +1 -1
  44. package/src/operator/node/BrowserPane.tsx +7 -7
  45. package/src/operator/node/Chat.tsx +53 -272
  46. package/src/operator/node/CommandPalette.tsx +1 -1
  47. package/src/operator/node/Composer.tsx +13 -6
  48. package/src/operator/node/Layout.tsx +1 -1
  49. package/src/operator/node/Markdown.tsx +6 -36
  50. package/src/operator/node/Modal.tsx +1 -1
  51. package/src/operator/node/OnboardingWizard.tsx +11 -9
  52. package/src/operator/node/Orchestrator.tsx +18 -8
  53. package/src/operator/node/ProjectLanding.tsx +1 -1
  54. package/src/operator/node/ProjectsColumn.tsx +1 -1
  55. package/src/operator/node/ProviderAuth.tsx +16 -16
  56. package/src/operator/node/RunSwitch.tsx +1 -1
  57. package/src/operator/node/Services.tsx +1 -1
  58. package/src/operator/node/SessionRail.tsx +55 -19
  59. package/src/operator/node/SessionView.tsx +18 -16
  60. package/src/operator/node/SettingsView.tsx +1 -1
  61. package/src/operator/node/TaskBoard.tsx +1 -1
  62. package/src/operator/node/TaskChanges.tsx +83 -108
  63. package/src/operator/node/TaskHero.tsx +5 -5
  64. package/src/operator/node/TasksColumn.tsx +1 -1
  65. package/src/operator/node/Transcript.tsx +15 -250
  66. package/src/operator/node/Welcome.tsx +1 -1
  67. package/src/operator/node/WorktreePrune.tsx +1 -1
  68. package/src/operator/node/api.ts +17 -0
  69. package/src/operator/node/boardBackend.ts +4 -1
  70. package/src/operator/node/boardEvents.ts +17 -3
  71. package/src/operator/node/boardInteraction.ts +7 -4
  72. package/src/operator/node/boardState.ts +23 -14
  73. package/src/operator/node/composerDraft.ts +22 -0
  74. package/src/operator/node/fileLinks.ts +4 -38
  75. package/src/operator/node/format.ts +13 -104
  76. package/src/operator/node/github.tsx +14 -14
  77. package/src/operator/node/liveStream.ts +47 -6
  78. package/src/operator/node/modals.tsx +59 -22
  79. package/src/operator/node/recheckOnReturn.ts +28 -0
  80. package/src/operator/node/shared.tsx +10 -50
  81. package/src/operator/node/types.ts +9 -0
  82. package/src/operator/node/useOrchestrator.ts +9 -8
  83. package/src/operator/node/useRecaps.ts +15 -4
  84. package/src/operator/node/useTaskStream.ts +2 -2
  85. package/src/operator.base.css +9 -4
  86. package/src/operator.css +9 -4
  87. package/src/styles.css +22 -8
  88. package/src/ui/Markdown.tsx +42 -21
  89. package/src/ui/Popover.tsx +1 -1
  90. package/src/ui/QueuedMessages.tsx +58 -15
  91. package/src/ui/SubagentChat.tsx +42 -6
  92. package/src/ui/Transcript.tsx +19 -14
  93. package/src/ui/fileLinks.ts +6 -3
  94. package/src/ui/format.ts +27 -9
  95. package/src/ui/icons.tsx +2 -0
  96. package/src/ui/shared.tsx +11 -7
  97. package/src/ui/transcriptModel.ts +40 -9
  98. package/src/ui/useTranscriptWindow.ts +253 -0
  99. package/src/operator/node/icons.tsx +0 -88
  100. package/src/operator/node/transcriptModel.ts +0 -129
@@ -7,7 +7,7 @@ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useSta
7
7
  import { CliErrorBoundary } from "../ui/ErrorBoundary";
8
8
  import type { CliEvent, CliStore, CliStoreOptions } from "../core/store";
9
9
  import { useCliState, useCliStore, useCliStoreContext, useComponentEvents, withOwnProvider, type ResultHandlers } from "../core/provider";
10
- import { formatBoardContext, withoutBoardContext } from "../board/context";
10
+ import { formatBoardContext, withoutBoardContext, rememberBoardFile, withBoardPaths } from "../board/context";
11
11
  import { MAX_MESSAGE_CHARS, charCount, boardContextBlock, serializeBlock, viewingBlock } from "../core/blocks";
12
12
  import { convKey, emptyConv, isChatTask, isNewInJob, isRunning, parseConvKey, runningTurn, TERMINAL_JOB, viewMessages } from "../core/conversation";
13
13
  import type { AskAnswers, AskQuestion, CenterTask, Msg } from "../core/types";
@@ -15,26 +15,29 @@ import { Icon } from "../ui/icons";
15
15
  import { agentLabel as labelOf, fmtTokens, formatAnswersText, modelLabel } from "../ui/format";
16
16
  import { AgentBadge, Avatar, Skel, StatusDot, type DotCls } from "../ui/shared";
17
17
  import { HANDOFF_NOTICE_PREFIX, MessageView, SessionBreak, type MessageHandlers } from "../ui/Transcript";
18
- import { RENDER_MAX, RENDER_STEP, RENDER_WINDOW, buildTranscriptItems, hasOpenAsk, toolDataOf } from "../ui/transcriptModel";
18
+ import { buildTranscriptItems, hasOpenAsk, toolDataOf } from "../ui/transcriptModel";
19
+ import { useTranscriptWindow } from "../ui/useTranscriptWindow";
19
20
  import { Composer, type ComposerOptions } from "./Composer";
20
21
  import { fillTemplate, refShown, resolveChatConfig, type CliChatConfig } from "../core/config";
21
22
  import { exportMarkdown } from "./export";
22
23
  import { FileLinkContext, FileOpenContext } from "../ui/fileLinks";
23
24
  import { FileViewer } from "../board/FileViewer";
25
+ import { pathHints, resolveMissingPath } from "../board/pathResolve";
24
26
  import { BrowserPane } from "../board/BrowserPane";
25
27
  import { CliBoard } from "../board/CliBoard";
26
28
  import { WorkspaceTabs } from "../ui/WorkspaceTabs";
27
29
  import { WorkspaceDrawer, useWorkspaceDrawer } from "../ui/WorkspaceDrawer";
28
30
  import { useChatScrollbar } from "../ui/useChatScrollbar";
29
31
  import { QueuedMessages } from "../ui/QueuedMessages";
32
+ import { restoreQueuedToDraft } from "./queueEdit";
30
33
  import { ReferenceCard } from "../ui/ReferenceCard";
31
- import type { UploadDocument } from "../core/documentUpload";
34
+ import { workspaceFileDirectory, type UploadDocument } from "../core/documentUpload";
32
35
  import { GroupChat, type GroupChatAdapter } from "./GroupChat";
33
36
  import { RunControls } from "./RunControls";
34
37
  import { useExecutionConfig } from "./useExecutionConfig";
35
38
  import { CenterError } from "../core/client";
36
39
 
37
- /** onTurnEnd / onConversationEnd:浏览器里从实时流算出的结果通知,不依赖 center 的 callback.url。 */
40
+ /** onTurnEnd / onConversationEnd / onTaskEnd:浏览器里从实时流算出的结果通知,不依赖 center 的 callback.url。 */
38
41
  export interface CliChatProps extends CliStoreOptions, ResultHandlers {
39
42
  /** 宿主提供的多发言人群聊;发送统一交给 group.onSend,不连接普通单任务转录。 */
40
43
  group?: GroupChatAdapter;
@@ -121,6 +124,11 @@ function batchStatusView(taskStatus: string | null, jobStatus: string | null): {
121
124
 
122
125
  /** 「智能体在工作」那一行:跑了多久,很久没输出时提示可能卡住。与 Operator 的 RunningIndicator 一致。 */
123
126
  const QUIET_AFTER_MS = 180_000;
127
+ /**
128
+ * 「正在加载会话」最多等这么久:会话记录还没到(执行节点暂时读不到、网关缓冲了实时数据、旧版中枢补发失败后
129
+ * 不再重试)就改成说明 +「重新读取」,不一直转圈。中枢报了 transcript_unavailable 时立刻说明。
130
+ */
131
+ export const TRANSCRIPT_WAIT_MS = 20_000;
124
132
  function RunningIndicator({ agent, agentName, startedAt, lastActivityRef }: { agent: string | null; agentName: string; startedAt: number | null; lastActivityRef: React.MutableRefObject<number> }) {
125
133
  const [now, setNow] = useState(() => Date.now());
126
134
  useEffect(() => { const t = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(t); }, []);
@@ -145,8 +153,8 @@ function RunningIndicator({ agent, agentName, startedAt, lastActivityRef }: { ag
145
153
  );
146
154
  }
147
155
 
148
- function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, jobId: jobIdProp, taskId: taskIdProp, title = "对话", color = "#b8613f", readOnly: readOnlyProp, allowClose = true, config, theme = "light", className, style, onEvent, onTurnEnd, onConversationEnd, onCallback, inProvider, fileUrl, fileOpen = "auto", newConversation, createConversation, businessIdFor }: CliChatProps & { inProvider: boolean }) {
149
- useComponentEvents(onEvent, { onTurnEnd, onConversationEnd, onCallback }, inProvider);
156
+ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, jobId: jobIdProp, taskId: taskIdProp, title = "对话", color = "#b8613f", readOnly: readOnlyProp, allowClose = true, config, theme = "light", className, style, onEvent, onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange, inProvider, fileUrl, fileOpen = "auto", newConversation, createConversation, businessIdFor }: CliChatProps & { inProvider: boolean }) {
157
+ useComponentEvents(onEvent, { onTurnEnd, onConversationEnd, onTaskEnd, onTaskAttemptEnd, onCallback, onFilesChange, onFilesWatch, onBoardContextChange }, inProvider);
150
158
  // 配置按内容比较:宿主每次渲染传新对象也不会让消息行全部重渲染。
151
159
  const configKey = JSON.stringify(config ?? {});
152
160
  const cfg = useMemo(() => resolveChatConfig(config), [configKey]); // eslint-disable-line react-hooks/exhaustive-deps
@@ -287,6 +295,24 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
287
295
  && (remoteAwaiting === true || (!running && !!lastTurn?.asked && lastTurn.status === "succeeded"));
288
296
  // 一次性任务的子任务还没派发(没有节点对话)、或者流已经结束还没有转录:不再转圈,转录里有说明。
289
297
  const loading = !!key && !isNew && !!conv && !conv.hasTranscript && !conv.turns.length && conv.stream !== "error" && conv.stream !== "ended" && !(conv.batch && !conv.remoteTaskId);
298
+ // 记录迟迟不来:到时改成说明(见 TRANSCRIPT_WAIT_MS);「重新读取」后重新计时。
299
+ const [loadStalled, setLoadStalled] = useState(false);
300
+ const [loadAttempt, setLoadAttempt] = useState(0);
301
+ useEffect(() => {
302
+ setLoadStalled(false);
303
+ if (!loading) return;
304
+ const timer = setTimeout(() => setLoadStalled(true), TRANSCRIPT_WAIT_MS);
305
+ return () => clearTimeout(timer);
306
+ }, [loading, key, loadAttempt]);
307
+ // 已结束的一次性任务:中枢补不到记录时关流前会先报 transcript_unavailable。
308
+ const transcriptProblem = !!key && !isNew && !!conv && !conv.hasTranscript && !conv.turns.length
309
+ ? conv.transcriptError ?? (loading && loadStalled
310
+ ? conv.stream === "connecting" || (conv.stream === "live" && !conv.job)
311
+ ? "实时连接还没有收到数据:网络或网关可能缓冲了实时推送。"
312
+ : "会话记录还没读到:执行节点暂时没有响应。"
313
+ : null)
314
+ : null;
315
+ const rereadTranscript = () => { if (!key) return; setLoadAttempt((n) => n + 1); store.reconnect(key, { force: true }); };
290
316
  const batchStatus = batch ? conv?.batchTask?.status ?? task?.status ?? null : null;
291
317
 
292
318
  // 用量:任务详情里的累计 + 实时流里上次刷新后的增量(「新开」的对话还没有用量,不借第一个对话的)。
@@ -332,18 +358,30 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
332
358
  useLayoutEffect(() => { sendOpts.current = { newConversation, createConversation, businessIdFor, select: !controlled }; });
333
359
  const prepareExecution = useRef(execution.prepareSend);
334
360
  const reloadExecution = useRef(execution.reload);
335
- useLayoutEffect(() => { prepareExecution.current = execution.prepareSend; reloadExecution.current = execution.reload; });
336
- const send = useCallback(async (text: string) => {
337
- const executionOptions = prepareExecution.current();
338
- // 一次性任务:发给正在看的那个子任务(接着它聊)。
339
- const id = latest.current.conv?.batch ? latest.current.runKey : latest.current.key;
361
+ const executionScope = useRef(draftScope);
362
+ useLayoutEffect(() => {
363
+ executionScope.current = draftScope;
364
+ prepareExecution.current = () => {
365
+ if (configurationBusy) throw new Error("请等待执行设置保存后再发送。");
366
+ return execution.prepareSend();
367
+ };
368
+ reloadExecution.current = execution.reload;
369
+ });
370
+ // 回答接口可能稍后才要求转为新消息;保留点击时的目标和设置,不借用切换后的对话。
371
+ const captureSendOrigin = useCallback(() => ({
372
+ refKey: latest.current.key,
373
+ id: latest.current.conv?.batch ? latest.current.runKey : latest.current.key,
374
+ options: sendOpts.current, scope: executionScope.current, prepare: prepareExecution.current, reload: reloadExecution.current,
375
+ }), []);
376
+ const send = useCallback(async (text: string, origin = captureSendOrigin()) => {
377
+ const executionOptions = (executionScope.current === origin.scope ? prepareExecution.current : origin.prepare)();
378
+ const { id, refKey } = origin;
340
379
  // 看板里引用到这个对话的东西:合成一个「看板上下文」块跟着这条消息发出去;发失败就放回去。
341
- // 看板上正在看的文件缺省也带上一次(已经明确引用了的不重复),单独一块「看板正在看」:转录里按 config.refs.viewing 显示或不显示。
342
- const refKey = latest.current.key;
380
+ // 看板上正在看的文件缺省也带上一次(已经明确引用了的不重复);自动背景始终不显示。
343
381
  const refs = refKey ? store.takeRefs(refKey) : [];
344
382
  const passiveView=refKey?store.getState().boardContext[refKey]:null;
345
383
  const passive=passiveContext&&passiveView?formatBoardContext(passiveView,refKey??undefined):'';
346
- const viewing = !passive && refKey ? store.takeViewing(refKey) : null;
384
+ const viewing = passiveContext && passiveView?.autoContext !== false && !passive && refKey ? store.takeViewing(refKey) : null;
347
385
  const blocks = [
348
386
  ...(passive ? [{name:"看板正在看",kind:"viewing" as const,text:passive}] : []),
349
387
  ...(viewing && !refs.some((r) => r.id === viewing.id) ? [viewingBlock(viewing.text)] : []),
@@ -353,22 +391,32 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
353
391
  let target: string;
354
392
  try {
355
393
  if(charCount(full)>MAX_MESSAGE_CHARS)throw new Error("加上看板背景后消息过长,请精简消息内容后重试。");
356
- target = await store.send(id ?? null, full, { ...sendOpts.current, ...executionOptions });
394
+ target = await store.send(id ?? null, full, { ...origin.options, ...executionOptions });
357
395
  } catch (error) {
358
396
  if (refKey) { store.restoreRefs(refKey, refs); store.restoreViewing(refKey, viewing); }
359
- if (error instanceof CenterError && error.code === "execution_config_conflict" && latest.current.key === refKey) await reloadExecution.current();
397
+ if (error instanceof CenterError && error.code === "execution_config_conflict" && latest.current.key === refKey) await origin.reload();
360
398
  throw error;
361
399
  }
362
400
  if (target !== id && latest.current.key === refKey) go(target);
363
- }, [store, go, passiveContext]);
401
+ return target;
402
+ }, [store, go, passiveContext, captureSendOrigin]);
364
403
  const passiveView=useCliState(state=>key?state.boardContext[key]:undefined);
365
- const passiveText=passiveContext&&passiveView?formatBoardContext(passiveView,key??undefined):'';
404
+ const board = store.client.board;
405
+ const [attachmentInfo,setAttachmentInfo]=useState<{key:string;workspaceRoot?:string;remoteTaskId?:string|null}|null>(null);
406
+ useEffect(()=>{
407
+ if(!key||isNew||!board||(passiveView?.workspaceRoot&&passiveView.remoteTaskId))return;
408
+ let alive=true;
409
+ void board.info(key).then(info=>{if(alive)setAttachmentInfo({key,workspaceRoot:info.workspaceRoot,remoteTaskId:info.remote_task_id});},()=>{});
410
+ return()=>{alive=false;};
411
+ },[board,key,isNew,remoteTaskId,passiveView?.workspaceRoot,passiveView?.remoteTaskId]);
412
+ const attachmentScope=useMemo(()=>{
413
+ const info=attachmentInfo?.key===key?attachmentInfo:null;
414
+ const taskId=passiveView?.remoteTaskId??info?.remoteTaskId;
415
+ return taskId?{taskId,workspaceRoot:passiveView?.workspaceRoot??info?.workspaceRoot}:undefined;
416
+ },[key,attachmentInfo,passiveView?.workspaceRoot,passiveView?.remoteTaskId]);
366
417
  const refs = useCliState((s) => (key ? s.refs[key] : undefined));
367
- const viewingState = useCliState((s) => (key ? s.viewing[key] : undefined));
368
- const viewingRef = viewingState && !viewingState.off && !refs?.some((r) => r.id === viewingState.ref.id) ? viewingState.ref : null;
369
- // 输入框上方显示哪些(config.refs):不显示的照样随消息带上。正在看的缺省不显示。
370
- const viewing = !passiveText && viewingRef && refShown(cfg, "viewing") ? viewingRef : null;
371
- const shownRefs = refs?.filter((r) => refShown(cfg, r.kind));
418
+ // 自动看板背景始终隐藏;明确引用仍按 config.refs 决定显示。
419
+ const shownRefs = useMemo(() => refs?.filter((r) => refShown(cfg, r.kind)), [refs, cfg]);
372
420
  const chatRef = useRef<HTMLDivElement>(null);
373
421
  // 业务方补充的背景(store.appendContext):随下一条消息带上,输入框上方显示出来,让用户知道会带上什么。
374
422
  const contextItems = useCliState((s) => s.context[key ?? ""]);
@@ -388,7 +436,29 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
388
436
  }, [key, conv, fileOpen, store, inlineOwner]);
389
437
 
390
438
  // 对话里弹窗打开的文件 / 浏览器(没有看板接的时候)。换对话就关掉。
391
- const [popup, setPopup] = useState<{ kind: "file"; path: string } | { kind: "browser" } | null>(null);
439
+ const [popup, setPopup] = useState<{ key: string; kind: "file"; path: string; resolvedFrom?: string } | { key: string; kind: "browser" } | null>(null);
440
+ const popupOwner=`${inlineOwner}:popup`;
441
+ const popupNavigation=useRef<string|null>(null);
442
+ useEffect(()=>{
443
+ if(!key||popup?.key!==key||popup.kind!=="file"){
444
+ if(key)store.reportBoard(key,null,popupOwner);
445
+ popupNavigation.current=null;return;
446
+ }
447
+ const navigation=JSON.stringify([key,popup.path]),changed=popupNavigation.current!==navigation;
448
+ const file={path:popup.path,sourceId:key};
449
+ const previous=store.getState().boardContext[key];
450
+ const history=changed?rememberBoardFile(previous?.history??[],file):previous?.history??[];
451
+ store.reportBoard(key,withBoardPaths({tab:`file:${popup.path}`,dir:workspaceFileDirectory(popup.path,attachmentScope?.workspaceRoot)??previous?.dir??"",directorySourceId:key,workspaceRoot:attachmentScope?.workspaceRoot,remoteTaskId:attachmentScope?.taskId,file:popup.path,files:[popup.path],current:file,opened:[file],history,visible:true,autoContext:passiveContext},key),popupOwner);
452
+ if(changed){popupNavigation.current=navigation;store.activateBoard(key,popupOwner);}
453
+ },[store,key,popup?.key,popup?.kind,popup?.kind==="file"?popup.path:null,popupOwner,attachmentScope?.workspaceRoot,attachmentScope?.taskId,passiveContext]);
454
+ useEffect(()=>()=>{if(key)store.reportBoard(key,null,popupOwner);},[store,key,popupOwner]);
455
+ // 弹窗里打不开的相对路径:和看板一样按这个对话里的线索补全(board/pathResolve.ts)。
456
+ const resolvePopupPath = useCallback((path: string, signal: AbortSignal) => {
457
+ const board = store.client.board, id = latest.current.key;
458
+ if (!board || !id) return Promise.resolve([]);
459
+ const seen = (store.getState().boardContext[id]?.history ?? []).map((f) => f.path);
460
+ return resolveMissingPath(board, id, path, pathHints(store.getState().convs[id]?.msgs ?? [], seen), signal);
461
+ }, [store]);
392
462
  useEffect(() => setPopup(null), [key]);
393
463
  useEffect(() => {
394
464
  if (!popup) return;
@@ -397,6 +467,7 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
397
467
  return () => window.removeEventListener("keydown", onKey);
398
468
  }, [popup]);
399
469
  const handlers = useMemo<MessageHandlers>(() => ({
470
+ attachmentScope,
400
471
  onQuote: readOnly ? undefined : (m,selected) => {
401
472
  const id = latest.current.key;
402
473
  if (!id) return;
@@ -405,16 +476,18 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
405
476
  },
406
477
  // 与 Operator 的 answerQuestion 一致:先把卡片标成已答,再把回答发出去(center 已结束提问那一轮,回答就是下一条消息)。
407
478
  onAnswer: readOnlyProp || (readOnly && !(batch && store.client.answerAsk)) ? undefined : async (askId: string, questions: AskQuestion[], answers: AskAnswers) => {
408
- const id = latest.current.key;
479
+ const origin = captureSendOrigin();
480
+ const id = origin.refKey;
409
481
  if (!id) return;
410
482
  // 一次性任务:提问时回合开着等,答案直接交给节点;不能改发消息。
411
483
  if (batch && !chat) { await report(store.answerAsk(latest.current.runKey ?? id, askId, questions, answers, { fallback: false }).then(() => undefined), "回答没有送到"); return; }
412
484
  const sent = askId
413
- ? store.answerAsk(id, askId, questions, answers, sendOpts.current).then((target) => { if (target !== id && latest.current.key === id) go(target); })
485
+ ? store.answerAsk(id, askId, questions, answers, { ...origin.options, fallbackSend: text => send(text, origin) })
414
486
  : send(formatAnswersText(questions, answers));
415
487
  await report(sent, "回答没有发出去");
416
488
  },
417
- onCancelQueued: readOnly || batch ? undefined : (m: Msg) => { const id = latest.current.key; if (id && m.turnId) void report(store.cancelTurn(id, m.turnId), "撤回失败").catch(() => undefined); },
489
+ // 错误由 report 显示在对话顶部;这里返回 promise 让排队行在撤回期间显示忙碌。
490
+ onCancelQueued: readOnly || batch ? undefined : (m: Msg) => { const id = latest.current.key; if (id && m.turnId) return report(store.cancelTurn(id, m.turnId), "撤回失败").then(() => undefined, () => undefined); },
418
491
  // 后端能直接处理的浏览器动作(Operator 后端)才给;center 不提供,卡片按 Operator「没有浏览器能力」时的样子显示。
419
492
  onInput: readOnlyProp || !store.client.submitInput ? undefined : async (inputId: string, values: string[]) => {
420
493
  const id = latest.current.runKey;
@@ -435,19 +508,30 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
435
508
  const id = latest.current.key;
436
509
  if (!id) return;
437
510
  if (fileOpen !== "modal" && store.openInBoard(id, { kind: "browser" }, inlineOwner)) return;
438
- if (fileOpen !== "board") setPopup({ kind: "browser" });
511
+ if (fileOpen !== "board") setPopup({ key: id, kind: "browser" });
439
512
  },
440
513
  onRetry: readOnly ? undefined : (msgId: string) => {
441
514
  const list = latest.current.messages;
442
515
  const at = list.findIndex((m) => m.id === msgId);
443
516
  for (let j = (at === -1 ? list.length : at) - 1; j >= 0; j--) if (list[j].role === "user") { void report(send(withoutBoardContext(list[j].content)), "重试没有发出去").catch(() => undefined); return; }
444
517
  },
445
- }), [readOnly, readOnlyProp, batch, chat, send, store, go, report, fileOpen, inlineOwner]);
518
+ }), [readOnly, readOnlyProp, batch, chat, send, store, go, report, fileOpen, inlineOwner, attachmentScope, captureSendOrigin]);
446
519
  const stop = useCallback(async () => {
447
520
  const { key: id, conv: c } = latest.current;
448
521
  const turn = c ? runningTurn(c) : null;
449
522
  if (id && turn) await report(store.cancelTurn(id, turn.turn_id), "停止失败");
450
523
  }, [store, report]);
524
+ // 排队消息「立即发送」:停掉正在执行的这一轮,中枢随即按顺序发出排队的消息(同一对话里排着的会合并成一轮)。
525
+ const sendQueuedNow = useCallback(async () => { await stop().catch(() => undefined); }, [stop]);
526
+ // 排队消息「编辑」:先撤回,撤回成功才放回输入框(失败时排队消息原样保留,不会出现两份)。
527
+ // 放回发出它的那个对话的草稿,期间切走了也不会放错地方。
528
+ const editQueued = useCallback(async (m: Msg) => {
529
+ const id = latest.current.key;
530
+ if (!id || !m.turnId) return;
531
+ try { await report(store.cancelTurn(id, m.turnId), "撤回失败,没有放回输入框"); } catch { return; }
532
+ restoreQueuedToDraft(store.draftScope ? `${store.draftScope}:${id}` : id, m.content);
533
+ if (latest.current.key === id) chatRef.current?.querySelector<HTMLTextAreaElement>(".composer textarea")?.focus({ preventScroll: true });
534
+ }, [store, report]);
451
535
  const [closeAction, setCloseAction] = useState<{ key: string; stage: "confirm" | "busy" } | null>(null);
452
536
  const closing = closeAction?.key === key ? closeAction.stage : "idle";
453
537
  useEffect(() => setCloseAction(null), [key]);
@@ -475,168 +559,31 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
475
559
  useEffect(() => { lastActivityRef.current = Date.now(); }, [messages]);
476
560
  const turnStartedAt = runSeenAt ?? lastUserTs;
477
561
 
478
- // ── 分窗渲染(移植自 Operator 的 SessionView):DOM 里最多 RENDER_MAX 行,几千条消息也照样流畅 ──
562
+ // ── 分窗渲染(与节点 Chat 共用 useTranscriptWindow):DOM 里最多 RENDER_MAX 行,几千条消息也照样流畅 ──
479
563
  const scrollRef = useRef<HTMLDivElement>(null);
480
564
  useChatScrollbar(scrollRef, key);
481
- const pinned = useRef(true);
482
- const [atBottom, setAtBottom] = useState(true);
483
565
  const committed = useMemo(() => messages.filter((m) => m.role !== "queued"), [messages]);
484
- const queued = useMemo(() => messages.filter((m) => m.role === "queued"), [messages]);
566
+ // 排队消息每次都是重新生成的对象:内容没变就沿用上一份,输入框上方的排队区不随流式输出重画。
567
+ const queuedNow = messages.filter((m) => m.role === "queued");
568
+ const queuedSig = queuedNow.map((m) => [m.id, m.content, m.note ?? "", m.turnId ?? "", m.ts ?? ""].join("\u0001")).join("\u0002");
569
+ const queued = useMemo(() => queuedNow, [queuedSig]); // eslint-disable-line react-hooks/exhaustive-deps
570
+ // 「立即发送」只在有一轮正在执行、且接入开放了停止时可用。
571
+ const queueSendNow = !readOnly && !batch && cfg.composer.stop && key && conv && runningTurn(conv) ? sendQueuedNow : undefined;
572
+ const queueSendNowHint = !cfg.composer.stop && conv && runningTurn(conv) ? "当前接入没有开放停止,排队消息会在这一轮结束后发送" : undefined;
485
573
  // 节点转录比手里更早、还没取的条数(实时流只给最新一段,往上翻时分页取,和 Operator 一样)。
486
574
  const older = conv?.older ?? 0;
487
- const [loadingOlder, setLoadingOlder] = useState(false);
488
- const olderRef = useRef(older); olderRef.current = older;
489
- const keyRef2 = useRef(key); keyRef2.current = key;
490
575
  const items = useMemo(() => buildTranscriptItems(committed, older > 0)
491
576
  .filter((it) => cfg.transcript.initialPrompt || it.kind !== "msg" || !it.initial), [committed, older, cfg.transcript.initialPrompt]);
492
577
  // 展开了的「续等」折叠行(按折叠行的 key)。
493
578
  const [openFolds, setOpenFolds] = useState<Set<string>>(() => new Set());
494
- const [win, setWin] = useState<{ start: string | null; end: string | null }>({ start: null, end: null });
495
- const { startIdx, endIdx } = useMemo(() => {
496
- const find = (key: string | null) => (key ? items.findIndex((it) => it.key === key) : -1);
497
- const e = find(win.end);
498
- const last = e >= 0 ? e : items.length - 1;
499
- let s = find(win.start);
500
- if (s >= 0) while (s > 0 && items[s - 1].kind !== "msg") s--;
501
- return { startIdx: s >= 0 && s <= last ? s : Math.max(0, last + 1 - RENDER_WINDOW), endIdx: last };
502
- }, [items, win]);
503
- const shown = useMemo(() => items.slice(startIdx, endIdx + 1), [items, startIdx, endIdx]);
504
- const hiddenAbove = useMemo(() => { let n = 0; for (let i = 0; i < startIdx; i++) if (items[i].kind === "msg") n++; return n; }, [items, startIdx]);
505
- const hiddenBelow = useMemo(() => { let n = 0; for (let i = endIdx + 1; i < items.length; i++) if (items[i].kind === "msg") n++; return n; }, [items, endIdx]);
506
- const itemsRef = useRef(items); itemsRef.current = items;
507
- const rangeRef = useRef({ startIdx, endIdx }); rangeRef.current = { startIdx, endIdx };
508
- const winRef = useRef(win); winRef.current = win;
509
- type Anchor = { key: string; top: number };
510
- const anchorRef = useRef<(Anchor & { win: typeof win }) | null>(null);
511
-
512
- const measure = useCallback((key?: string): Anchor | null => {
513
- const el = scrollRef.current;
514
- const node = key ? el?.querySelector<HTMLElement>(`[data-tkey="${CSS.escape(key)}"]`) : el?.querySelector<HTMLElement>("[data-tkey][data-msg]");
515
- return node?.dataset.tkey ? { key: node.dataset.tkey, top: node.getBoundingClientRect().top } : null;
516
- }, []);
517
- const setRange = useCallback((s: number, e: number, anchor?: Anchor | null) => {
518
- const its = itemsRef.current;
519
- let a = s; while (a < its.length && its[a].kind !== "msg") a++;
520
- let b = e; while (b > 0 && its[b].kind !== "msg") b--;
521
- const next = { start: its[a]?.key ?? null, end: e >= its.length - 1 ? null : its[b]?.key ?? null };
522
- if (winRef.current.start === next.start && winRef.current.end === next.end) return;
523
- if (anchor) anchorRef.current = { ...anchor, win: next };
524
- setWin(next);
525
- }, []);
526
- const revealEarlier = useCallback(() => {
527
- const { startIdx: s, endIdx: e } = rangeRef.current;
528
- if (s <= 0) {
529
- // 手里的都显示了,节点上还有更早的:取一页接在前面,再往上展开(窗口按原来的那一行定位,不跳)。
530
- const k = keyRef2.current;
531
- if (!k || olderRef.current <= 0) return;
532
- setLoadingOlder(true);
533
- void store.loadOlder(k).then((ok) => { if (ok) requestAnimationFrame(() => revealRef.current.earlier()); }).finally(() => setLoadingOlder(false));
534
- return;
535
- }
536
- const ns = Math.max(0, s - RENDER_STEP);
537
- setRange(ns, Math.min(e, ns + RENDER_MAX - 1), measure());
538
- }, [measure, setRange, store]);
539
- const revealLater = useCallback(() => {
540
- const its = itemsRef.current;
541
- const { startIdx: s, endIdx: e } = rangeRef.current;
542
- if (e >= its.length - 1) return;
543
- const ne = Math.min(its.length - 1, e + RENDER_STEP);
544
- const ns = Math.max(s, ne - RENDER_MAX + 1);
545
- setRange(ns, ne, ns > s ? measure(its[ns].key) : null);
546
- }, [measure, setRange]);
547
- const revealRef = useRef({ earlier: revealEarlier, later: revealLater });
548
- revealRef.current = { earlier: revealEarlier, later: revealLater };
549
-
550
- const onScroll = useCallback(() => {
551
- const el = scrollRef.current;
552
- if (!el) return;
553
- const bottom = el.scrollHeight - el.scrollTop - el.clientHeight < 60 && winRef.current.end === null;
554
- pinned.current = bottom;
555
- setAtBottom(bottom);
556
- if (!bottom && winRef.current.start === null) {
557
- const first = itemsRef.current.slice(rangeRef.current.startIdx).find((it) => it.kind === "msg");
558
- if (first) setWin((w) => ({ ...w, start: first.key }));
559
- } else if (bottom && winRef.current.start !== null) {
560
- setWin({ start: null, end: null });
561
- }
562
- }, []);
563
-
564
- const topSentinelRef = useRef<HTMLDivElement>(null);
565
- const bottomSentinelRef = useRef<HTMLDivElement>(null);
566
- const hasAbove = hiddenAbove > 0 || older > 0;
579
+ const loadOlderPage = useCallback((beforeApply: () => void) => (key ? store.loadOlder(key, { beforeApply }) : Promise.resolve(false)), [store, key]);
580
+ const { shown, hiddenAbove, hiddenBelow, loadingOlder, atBottom, onScroll, revealEarlier, revealLater, scrollToBottom, scrollToUserMsg, topSentinelRef, bottomSentinelRef } =
581
+ useTranscriptWindow({ scrollRef, items, older, loadOlder: loadOlderPage, messages, running, resetKey: key });
567
582
  const hasBelow = hiddenBelow > 0;
568
- useEffect(() => {
569
- const root = scrollRef.current;
570
- if (!root || typeof IntersectionObserver === "undefined") return;
571
- const watch = (target: HTMLElement | null, margin: string, go: () => void) => {
572
- if (!target) return null;
573
- const io = new IntersectionObserver((entries) => { if (!pinned.current && entries.some((e) => e.isIntersecting)) go(); }, { root, rootMargin: margin });
574
- io.observe(target);
575
- return io;
576
- };
577
- const up = hasAbove ? watch(topSentinelRef.current, "1800px 0px 0px 0px", () => revealRef.current.earlier()) : null;
578
- const down = hasBelow ? watch(bottomSentinelRef.current, "0px 0px 1800px 0px", () => revealRef.current.later()) : null;
579
- return () => { up?.disconnect(); down?.disconnect(); };
580
- }, [hasAbove, hasBelow]);
581
-
582
- useLayoutEffect(() => {
583
- if (win.start === null || win.end !== null || endIdx - startIdx + 1 <= RENDER_MAX + 2) return;
584
- const el = scrollRef.current;
585
- if (!el) return;
586
- if (el.scrollTop < (el.scrollHeight - el.clientHeight) / 2) setRange(startIdx, startIdx + RENDER_MAX - 1);
587
- else { const ns = endIdx - RENDER_MAX + 1; setRange(ns, endIdx, measure(itemsRef.current[ns].key)); }
588
- }, [win, startIdx, endIdx, setRange, measure]);
589
-
590
- const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {
591
- const el = scrollRef.current;
592
- if (!el) return;
593
- pinned.current = true;
594
- setAtBottom(true);
595
- if (winRef.current.start !== null || winRef.current.end !== null) { setWin({ start: null, end: null }); return; }
596
- el.scrollTo({ top: el.scrollHeight, behavior });
597
- }, []);
598
-
599
- // 在「你」的消息之间跳。
600
- const scrollToUserMsg = useCallback((dir: -1 | 1) => {
601
- const el = scrollRef.current;
602
- if (!el) return;
603
- const base = el.getBoundingClientRect().top;
604
- const tops = Array.from(el.querySelectorAll<HTMLElement>(".msg.user:not(.queued)")).map((n) => n.getBoundingClientRect().top - base + el.scrollTop);
605
- const cur = el.scrollTop;
606
- const candidates = dir < 0 ? tops.filter((t) => t < cur - 8) : tops.filter((t) => t > cur + 8);
607
- if (!candidates.length) { if (dir < 0) revealRef.current.earlier(); else revealRef.current.later(); }
608
- if (!tops.length) return;
609
- const target = candidates.length ? (dir < 0 ? candidates[candidates.length - 1] : candidates[0]) : dir < 0 ? tops[0] : tops[tops.length - 1];
610
- el.scrollTo({ top: Math.max(0, target - 12), behavior: "smooth" });
611
- }, []);
612
-
613
- useLayoutEffect(() => {
614
- const a = anchorRef.current;
615
- const el = scrollRef.current;
616
- if (a && a.win === win) {
617
- anchorRef.current = null;
618
- const node = el?.querySelector<HTMLElement>(`[data-tkey="${CSS.escape(a.key)}"]`);
619
- if (el && node) { const delta = node.getBoundingClientRect().top - a.top; if (Math.abs(delta) > 1) el.scrollTop += delta; }
620
- }
621
- }, [win]);
622
- useLayoutEffect(() => { if (pinned.current && scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; }, [messages, running, startIdx, endIdx, win]);
623
- useEffect(() => {
624
- const el = scrollRef.current;
625
- if (!el || typeof ResizeObserver === "undefined") return;
626
- const ro = new ResizeObserver(() => { if (pinned.current) el.scrollTop = el.scrollHeight; });
627
- ro.observe(el);
628
- return () => ro.disconnect();
629
- }, []);
630
- useEffect(() => {
631
- pinned.current = true;
632
- setAtBottom(true);
633
- setWin({ start: null, end: null });
634
- if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
635
- }, [key]);
636
583
 
637
584
  const contextReset = !!lastTurn?.context_reset && conv?.turns.some((turn) => turn.context_reset);
638
585
  const h = cfg.header;
639
- const view = useMemo(() => ({ timestamps: cfg.transcript.timestamps, initialBadge: cfg.transcript.initialBadge, userLabel: cfg.labels.user, agentName: cfg.labels.agent, viewingBlock: refShown(cfg, "viewing") }), [cfg]);
586
+ const view = useMemo(() => ({ timestamps: cfg.transcript.timestamps, initialBadge: cfg.transcript.initialBadge, userLabel: cfg.labels.user, agentName: cfg.labels.agent, viewingBlock: false }), [cfg]);
640
587
  const composerOptions = useMemo<ComposerOptions>(() => ({
641
588
  placeholderRunning: cfg.composer.placeholderRunning, hints: cfg.composer.hints, charCount: cfg.composer.charCount,
642
589
  fileUpload: cfg.composer.fileUpload, fileButtonText: cfg.composer.fileButtonText, queue: cfg.composer.queue,
@@ -650,7 +597,6 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
650
597
 
651
598
  const fileUrlRef = useRef(fileUrl);
652
599
  fileUrlRef.current = fileUrl;
653
- const board = store.client.board;
654
600
  const mobileWorkspace = useWorkspaceDrawer(chatRef);
655
601
  const workspaceAvailable = h.show && !!key && !isNew && !!board && !externalBoardVisible;
656
602
  const workspaceTabs = workspaceAvailable && !mobileWorkspace;
@@ -675,26 +621,74 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
675
621
  return (path: string) => {
676
622
  if (fileOpen !== "modal" && store.openInBoard(key, { kind: "file", path }, inlineOwner)) return true;
677
623
  if (fileOpen === "board" || !board) return false;
678
- setPopup({ kind: "file", path });
624
+ setPopup({ key, kind: "file", path });
679
625
  return true;
680
626
  };
681
627
  }, [key, fileOpen, store, board, inlineOwner]);
682
628
  const uploadDocument = useMemo<UploadDocument | undefined>(() => {
683
629
  const staging = store.client.uploadDocument;
684
- if (!key || isNew || !board?.uploadFile) return staging;
630
+ const destinationDir = passiveView?.dir || ".";
631
+ const stage: UploadDocument | undefined = staging ? (file, options) => staging(file, { ...options, destinationDir }) : undefined;
632
+ if (!key || isNew || !board?.uploadFile) return stage;
685
633
  return async (file, options) => {
634
+ const uploadOptions = { ...options, destinationDir };
686
635
  const target = await board.info(key);
687
636
  if (options.signal?.aborted) throw new DOMException("上传已取消", "AbortError");
688
637
  if (!target.dispatched) {
689
- if (staging) return staging(file, options);
638
+ if (stage) return stage(file, uploadOptions);
690
639
  throw new Error("当前会话工作区尚未就绪");
691
640
  }
692
- const receipt = await board.uploadFile!(key, file, options);
641
+ const receipt = await board.uploadFile!(key, file, uploadOptions);
693
642
  if (!receipt.path) throw new Error("文件尚未进入当前工作区,请重试");
643
+ void board.info(key).then(info=>{if(latest.current.key===key)setAttachmentInfo({key,workspaceRoot:info.workspaceRoot,remoteTaskId:info.remote_task_id});},()=>{});
694
644
  if (!options.signal?.aborted && latest.current.key === key) openFile?.(receipt.path);
695
645
  return receipt;
696
646
  };
697
- }, [store, key, isNew, board, openFile]);
647
+ }, [store, key, isNew, board, openFile, passiveView?.dir]);
648
+
649
+ // ── 输入框和内嵌看板的参数:保持引用稳定(输入框、看板都是 memo),智能体流式输出时不跟着每一块重画 ──
650
+ const saveExecution = useRef(execution.save);
651
+ saveExecution.current = execution.save;
652
+ const runControls = useMemo(() => <>
653
+ <RunControls task={{ id: draftScope, agent: execution.config?.agent ?? agent ?? initialOptions?.agent ?? undefined,
654
+ model: execution.config?.model, reasoning: execution.config?.reasoning, permission_mode: execution.config?.permission_mode }}
655
+ agents={execution.config?.agents} caps={executionAgent?.capabilities} defaults={executionAgent?.defaults}
656
+ showAgent={cfg.composer.agentSelector} showPermission={cfg.composer.executionMode}
657
+ unavailableReason={batch ? "一次性任务沿用任务执行设置,不支持在对话中修改。" : executionReadOnly ? "当前接入仅支持读取执行设置。" : execution.error ?? (!executionEnabled || execution.loading ? "正在读取执行设置…" : undefined)}
658
+ disabled={!executionEnabled || composerDisabled || running || batchPending || !!configurationBusy || execution.loading || executionReadOnly}
659
+ onSetAgent={agent => saveExecution.current({ agent, model: null, reasoning: null, permission_mode: null })}
660
+ onSetModel={model => saveExecution.current({ model })} onSetReasoning={reasoning => saveExecution.current({ reasoning })}
661
+ onSetPermission={permission_mode => saveExecution.current({ permission_mode })} />
662
+ {slots?.composerToolbar}
663
+ </>, [draftScope, execution.config, agent, initialOptions?.agent, executionAgent, cfg, batch, executionReadOnly, execution.error, executionEnabled, execution.loading,
664
+ composerDisabled, running, batchPending, configurationBusy, slots?.composerToolbar]);
665
+ const focusComposer = useCallback(() => chatRef.current?.querySelector<HTMLTextAreaElement>(".composer textarea")?.focus({ preventScroll: true }), []);
666
+ const composerReferences = useMemo(() => !!shownRefs?.length && <div className="cli-refs composer-references" aria-label="下一条消息的引用">
667
+ {(shownRefs ?? []).map(ref => <ReferenceCard key={`${key}:${ref.id}`} title={ref.kind === "message" && ref.label === "引用你的消息" ? "你" : ref.kind === "message" && ref.label === "引用智能体消息" ? "智能体" : ref.label} text={ref.text} disabled={composerDisabled || !!configurationBusy} removeLabel={`不带上 ${ref.label}`} onRemove={() => { if (key) store.removeRef(key, ref.id); focusComposer(); }} />)}
668
+ </div>, [shownRefs, key, composerDisabled, configurationBusy, store, focusComposer]);
669
+ const queuedMessages = useMemo(() => <QueuedMessages scopeKey={key ?? "new"} messages={queued} onCancel={handlers.onCancelQueued} onSendNow={queueSendNow} sendNowUnavailable={queueSendNowHint} onEdit={handlers.onCancelQueued ? editQueued : undefined} attachmentUrl={handlers.attachmentUrl} attachmentScope={attachmentScope} />,
670
+ [key, queued, handlers, queueSendNow, queueSendNowHint, editQueued]);
671
+ const onClearRef = useRef(onClear);
672
+ onClearRef.current = onClear;
673
+ // 发出前记下当时是否在执行:在执行时发的消息会排队,不滚到底。
674
+ const busyRef = useRef(false);
675
+ busyRef.current = running || batchPending;
676
+ const sendFromComposer = useCallback(async (text: string) => {
677
+ if (text.trim() === "/clear" && onClearRef.current) { onClearRef.current(); return; }
678
+ const sentFrom = key;
679
+ const wasBusy = busyRef.current;
680
+ await send(text);
681
+ if (!wasBusy && latest.current.key === sentFrom) scrollToBottom("auto");
682
+ }, [key, send, scrollToBottom]);
683
+ const pauseResume = useMemo(() => cfg.composer.stop && !readOnlyProp && controlTask && jobId && store.client.pauseTask && store.client.resumeTask ? {
684
+ paused: controlTask.status === "paused",
685
+ onToggle: async () => {
686
+ const action = controlTask.status === "paused" ? store.client.resumeTask! : store.client.pauseTask!;
687
+ await report(action(controlTask.id).then(() => store.refreshJob(jobId, true)), controlTask.status === "paused" ? "继续任务失败" : "暂停任务失败");
688
+ },
689
+ } : undefined, [cfg, readOnlyProp, controlTask, jobId, store, report]);
690
+ const inlineLayout = useMemo(() => (mobileWorkspace ? undefined : { tabsHost, active: workspaceActive, onActivate: showWorkspace, onChat: showChat }),
691
+ [mobileWorkspace, tabsHost, workspaceActive, showWorkspace, showChat]);
698
692
 
699
693
  return (
700
694
  <FileLinkContext.Provider value={resolveFile}>
@@ -753,6 +747,7 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
753
747
  {actionError && <div className="sync-banner conflict"><span className="sync-msg">⚠ {actionError}</span><span className="sync-spacer" /><button className="btn btn-ghost btn-sm" onClick={() => setActionError(null)}>知道了</button></div>}
754
748
  {conv?.stream === "reconnecting" && <div className="sync-banner"><span className="sync-msg">实时连接中断,正在重连…{conv.streamError ? `(${conv.streamError})` : ""}</span></div>}
755
749
  {conv?.stream === "error" && <div className="sync-banner conflict"><span className="sync-msg">⚠ {conv.streamError}</span></div>}
750
+ {conv?.stream === "offline" && <div className="sync-banner conflict" role="status"><span className="sync-msg">⚠ 实时连接已中断{conv.streamError ? `(${conv.streamError})` : ""},已停止自动重试;网络恢复、回到页面或发出消息时会再连。</span><span className="sync-spacer" /><button className="btn btn-ghost btn-sm" onClick={() => { if (key) store.reconnect(key); }}>重新连接</button></div>}
756
751
 
757
752
  <div className="transcript-wrap">
758
753
  <div className="transcript" ref={scrollRef} onScroll={onScroll}>
@@ -773,7 +768,12 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
773
768
  </div></div>
774
769
  )}
775
770
  {contextReset && <div className="msg system info"><div className="msg-body">ℹ 执行节点上的会话重建过:从那一轮起是新的 Agent 会话,之前的对话上下文没有带过去(工作区文件还在)。</div></div>}
776
- {loading && (
771
+ {transcriptProblem && (
772
+ <div className="msg system info cli-transcript-problem" role="status"><div className="msg-body">⚠ {transcriptProblem}
773
+ <button className="btn btn-line btn-sm" style={{ marginLeft: 8 }} onClick={rereadTranscript}>重新读取</button>
774
+ </div></div>
775
+ )}
776
+ {loading && !transcriptProblem && (
777
777
  <div aria-hidden>
778
778
  <div className="session-label"><span className="ln" />正在加载会话<span className="ln" /></div>
779
779
  <div className="msg user" style={{ opacity: .7 }}>
@@ -786,9 +786,9 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
786
786
  </div>
787
787
  </div>
788
788
  )}
789
- {hasAbove && (
789
+ {hiddenAbove > 0 && (
790
790
  <div ref={topSentinelRef} className="load-older">
791
- <button className="btn btn-ghost btn-sm" onClick={revealEarlier} disabled={loadingOlder}>{loadingOlder ? "正在加载更早的消息…" : `加载更早的消息(还有 ${hiddenAbove + older} 条)`}</button>
791
+ <button className="btn btn-ghost btn-sm" onClick={() => void revealEarlier()} disabled={loadingOlder}>{loadingOlder ? "正在加载更早的消息…" : `加载更早的消息(还有 ${hiddenAbove} 条)`}</button>
792
792
  </div>
793
793
  )}
794
794
  {shown.map((it) =>
@@ -845,42 +845,22 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
845
845
  )}
846
846
  {slots?.beforeComposer}
847
847
  {showComposer && execution.error && <div className="control-error" role="status">{execution.error} {store.client.getExecutionConfig && <button type="button" className="btn btn-ghost btn-sm" disabled={execution.loading || execution.busy} onClick={() => void execution.reload()}>重新读取</button>}</div>}
848
- {!showComposer && <QueuedMessages scopeKey={key ?? "new"} messages={queued} onCancel={handlers.onCancelQueued} attachmentUrl={handlers.attachmentUrl} />}
848
+ {!showComposer && <QueuedMessages scopeKey={key ?? "new"} messages={queued} onCancel={handlers.onCancelQueued} onSendNow={queueSendNow} sendNowUnavailable={queueSendNowHint} attachmentUrl={handlers.attachmentUrl} attachmentScope={attachmentScope} />}
849
849
  {showComposer && (
850
850
  <Composer
851
851
  uploadDocument={uploadDocument}
852
852
  key={key ?? "new"}
853
853
  draft={draftScope}
854
- context={(!!shownRefs?.length || !!viewing) && <div className="cli-refs composer-references" aria-label="下一条消息的引用">
855
- {viewing && <ReferenceCard key={`${key}:viewing:${viewing.id}`} className="reference-viewing" title={`正在看${viewing.label}`} text={viewing.text} disabled={composerDisabled || !!configurationBusy} removeLabel={`不带上 ${viewing.label}`} onRemove={() => { if (key) store.dismissViewing(key); chatRef.current?.querySelector<HTMLTextAreaElement>(".composer textarea")?.focus({ preventScroll: true }); }} />}
856
- {(shownRefs ?? []).map(ref => <ReferenceCard key={`${key}:${ref.id}`} title={ref.kind === "message" && ref.label === "引用你的消息" ? "你" : ref.kind === "message" && ref.label === "引用智能体消息" ? "智能体" : ref.label} text={ref.text} disabled={composerDisabled || !!configurationBusy} removeLabel={`不带上 ${ref.label}`} onRemove={() => { if (key) store.removeRef(key, ref.id); chatRef.current?.querySelector<HTMLTextAreaElement>(".composer textarea")?.focus({ preventScroll: true }); }} />)}
857
- </div>}
854
+ context={composerReferences}
858
855
  placeholder={fillTemplate(key && !isNew ? cfg.composer.placeholder : cfg.composer.placeholderNew, { title: convTitle, agent: agentText })}
859
856
  disabled={composerDisabled || settingsBusy}
860
857
  disabledHint={cfg.composer.placeholderDisabled ? fillTemplate(cfg.composer.placeholderDisabled, { title: convTitle, agent: agentText }) : disabledHint}
861
858
  running={running || batchPending}
862
- toolbar={<>
863
- <RunControls task={{ id: draftScope, agent: execution.config?.agent ?? agent ?? initialOptions?.agent ?? undefined,
864
- model: execution.config?.model, reasoning: execution.config?.reasoning, permission_mode: execution.config?.permission_mode }}
865
- agents={execution.config?.agents} caps={executionAgent?.capabilities} defaults={executionAgent?.defaults}
866
- showAgent={cfg.composer.agentSelector} showPermission={cfg.composer.executionMode}
867
- unavailableReason={batch ? "一次性任务沿用任务执行设置,不支持在对话中修改。" : executionReadOnly ? "当前接入仅支持读取执行设置。" : execution.error ?? (!executionEnabled || execution.loading ? "正在读取执行设置…" : undefined)}
868
- disabled={!executionEnabled || composerDisabled || running || batchPending || !!configurationBusy || execution.loading || executionReadOnly}
869
- onSetAgent={agent => execution.save({ agent, model: null, reasoning: null, permission_mode: null })}
870
- onSetModel={model => execution.save({ model })} onSetReasoning={reasoning => execution.save({ reasoning })}
871
- onSetPermission={permission_mode => execution.save({ permission_mode })} />
872
- {slots?.composerToolbar}
873
- </>}
874
- queued={<QueuedMessages scopeKey={key ?? "new"} messages={queued} onCancel={handlers.onCancelQueued} attachmentUrl={handlers.attachmentUrl} />}
875
- onSend={async text => { if (text.trim() === "/clear" && onClear) { onClear(); return; } const sentFrom = key; await send(text); if (!running && !batchPending && latest.current.key === sentFrom) scrollToBottom("auto"); }}
859
+ toolbar={runControls}
860
+ queued={queuedMessages}
861
+ onSend={sendFromComposer}
876
862
  onStop={cfg.composer.stop && key && conv && runningTurn(conv) ? stop : undefined}
877
- taskControl={cfg.composer.stop && !readOnlyProp && controlTask && jobId && store.client.pauseTask && store.client.resumeTask ? {
878
- paused: controlTask.status === "paused",
879
- onToggle: async () => {
880
- const action = controlTask.status === "paused" ? store.client.resumeTask! : store.client.pauseTask!;
881
- await report(action(controlTask.id).then(() => store.refreshJob(jobId, true)), controlTask.status === "paused" ? "继续任务失败" : "暂停任务失败");
882
- },
883
- } : undefined}
863
+ taskControl={pauseResume}
884
864
  options={composerOptions}
885
865
  />
886
866
  )}
@@ -890,15 +870,16 @@ function ChatInner({ slots, passiveContext = true, configurationBusy, onClear, j
890
870
  readOnly={readOnly || externalBoardOptions?.readOnly} availableTabs={externalBoardOptions?.availableTabs}
891
871
  acceptOpen={fileOpen !== "modal" && fileOpen !== "link"} theme={theme}
892
872
  visible={workspaceActive} onExpand={showWorkspace} onQuoteToChat={quoteToChat}
893
- inlineLayout={mobileWorkspace ? undefined : { tabsHost, active: workspaceActive, onActivate: showWorkspace, onChat: showChat }} />}
873
+ inlineLayout={inlineLayout} />}
894
874
  </WorkspaceDrawer>
895
875
  </div>
896
876
  </SubagentChatScope>
897
- {popup && key && board && (
877
+ {popup && popup.key===key && key && board && (
898
878
  <div className="scrim" onClick={(e) => { if (e.target === e.currentTarget) setPopup(null); }}>
899
879
  <div className={`modal cli-popup ${popup.kind}`} role="dialog" aria-modal="true" aria-label={popup.kind === "file" ? popup.path : "任务浏览器"}>
900
880
  {popup.kind === "file" ? (
901
- <FileViewer backend={board} jobId={key} path={popup.path} onClose={() => setPopup(null)} onOpenPath={(p) => setPopup({ kind: "file", path: p })} />
881
+ <FileViewer backend={board} jobId={key} path={popup.path} onClose={() => setPopup(null)} onOpenPath={(p) => setPopup({ key: popup.key, kind: "file", path: p })}
882
+ resolveMissing={resolvePopupPath} onResolved={(to) => setPopup({ key: popup.key, kind: "file", path: to, resolvedFrom: popup.resolvedFrom ?? popup.path })} resolvedFrom={popup.resolvedFrom} />
902
883
  ) : (
903
884
  <>
904
885
  <div className="cli-fv-h"><span className="cli-fv-name">任务浏览器</span><span className="cli-fv-sp" /><button className="cli-fv-icon" onClick={() => setPopup(null)} title="关闭">{Icon.x()}</button></div>