@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
@@ -4,22 +4,26 @@ import { parentMessages, type SubagentTranscript } from "../../core/subagents";
4
4
  import { jget } from "./api";
5
5
  import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
6
6
  import type { AskQuestion, AskAnswers } from "./protocol/types";
7
- import { Icon } from "./icons";
7
+ import { Icon } from "../../ui/icons";
8
8
  import { agentLabel } from "./agents";
9
9
  import { Avatar, Skel } from "./shared";
10
10
  import { splitAttachments } from "./format";
11
11
  import type { ProjectRow, TaskRow, Msg, AgentsBundle } from "./types";
12
12
  import { MessageView, SessionBreak } from "./Transcript";
13
- import { RENDER_MAX, RENDER_STEP, RENDER_WINDOW, buildTranscriptItems, hasOpenAsk } from "./transcriptModel";
13
+ import { buildTranscriptItems, hasOpenAsk } from "../../ui/transcriptModel";
14
+ import { useTranscriptWindow } from "../../ui/useTranscriptWindow";
14
15
  import { OperatorBoardContext } from "./boardInteraction";
15
- import { toolDataOf } from "./transcriptModel";
16
- import { FileLinkContext } from "./fileLinks";
16
+ import { toolDataOf } from "../../ui/transcriptModel";
17
+ import { FileLinkContext, taskFileApiUrl } from "./fileLinks";
18
+ import { getOperatorBoardBackend } from "./boardBackend";
19
+ import { readBoardState, useBoardState } from "./boardState";
20
+ import { appendBoardContext, withoutBoardContext } from "../../board/context";
17
21
  import { Composer } from "./Composer";
18
22
  import { QueuedMessages } from "../../ui/QueuedMessages";
19
23
  import { useChatScrollbar } from "../../ui/useChatScrollbar";
20
24
  import { BranchHistory, useBranchHistory } from "./BranchHistory";
21
25
  import { BranchNavigator } from "./BranchNavigator";
22
- import type { Quote } from "./composerDraft";
26
+ import { restoreQueuedDraft, type Quote } from "./composerDraft";
23
27
  import type { RunControlProps } from "./RunControls";
24
28
  import type { ResolvedChatConfig } from "../../core/config";
25
29
  const QUIET_AFTER_MS = 180_000;
@@ -68,6 +72,7 @@ function useStableAsync<A extends unknown[], R>(fn: (...args: A) => Promise<R>):
68
72
  }
69
73
 
70
74
  export type ChatProps = {
75
+ readOnly?: boolean;
71
76
  project: ProjectRow; task: TaskRow; tasks: TaskRow[]; agents: AgentsBundle; messages: Msg[];
72
77
  running: boolean; blockedBy?: string[]; transcriptLoading?: boolean;
73
78
  older?: number; onLoadOlder?: (beforeApply?: () => void) => Promise<boolean>;
@@ -77,14 +82,24 @@ export type ChatProps = {
77
82
  onSend: (text: string) => Promise<boolean>; onStop: () => Promise<boolean>;
78
83
  onStart: () => void; onEdit: () => void; onClear: () => void; onSetSendContext: (v: boolean) => void;
79
84
  onReconnect?: () => void; onAnswer: (askId: string, questions: AskQuestion[], answers: AskAnswers) => void;
80
- onCancelQueued: (pendingId: string) => void;
85
+ /** 撤回排队消息。返回 false = 它已经开始执行(没撤回);编辑据此决定是否放回输入框。 */
86
+ onCancelQueued: (pendingId: string) => void | boolean | Promise<void | boolean>;
81
87
  };
82
88
  export function Chat(props: ChatProps) { return <ChatSession key={props.task.id} {...props} />; }
83
89
  function ChatSession({ project, task, tasks, agents, messages, running, transcriptLoading, older=0, onLoadOlder,
84
- controls, configBusy, composer, active=true, onSelectTask, onFork, onSend, onStop, onClear, onReconnect, onAnswer, onCancelQueued }: ChatProps) {
90
+ controls, configBusy, composer, active=true, readOnly=false, onSelectTask, onFork, onSend, onStop, onClear, onReconnect, onAnswer, onCancelQueued }: ChatProps) {
85
91
  const parent = useMemo(() => parentMessages(messages), [messages]);
92
+ const boardView=useBoardState(task.id);
93
+ const [attachmentRoot,setAttachmentRoot]=useState<{taskId:string;path?:string}|null>(null);
94
+ useEffect(()=>{
95
+ if(boardView?.workspaceRoot)return;
96
+ let alive=true;
97
+ void getOperatorBoardBackend().info(task.id).then(info=>{if(alive)setAttachmentRoot({taskId:task.id,path:info.workspaceRoot});},()=>{});
98
+ return()=>{alive=false;};
99
+ },[task.id,task.started,task.worktree_path,boardView?.workspaceRoot]);
100
+ const attachmentScope=useMemo(()=>({taskId:task.id,workspaceRoot:boardView?.workspaceRoot??(attachmentRoot?.taskId===task.id?attachmentRoot.path:undefined)}),[task.id,boardView?.workspaceRoot,attachmentRoot]);
86
101
  const loadSubagent = useCallback((id: string, generation: number, before?: string) => jget<SubagentTranscript>(`/api/tasks/${encodeURIComponent(task.id)}/subagents/${encodeURIComponent(id)}?generation=${generation}&limit=200${before ? `&before=${encodeURIComponent(before)}` : ""}`), [task.id]);
87
- const renderSubagentMessage = useCallback((message: Msg, name: string) => <MessageView m={message} initial={false} hideWho={false} agent={task.agent} agentLabel={name} userLabel="收到的任务" speakerLabel={name} readOnly />, [task.agent]);
102
+ const renderSubagentMessage = useCallback((message: Msg, name: string) => <MessageView m={message} initial={false} hideWho={false} agent={task.agent} agentLabel={name} userLabel="收到的任务" speakerLabel={name} readOnly attachmentScope={attachmentScope} />, [task.agent,attachmentScope]);
88
103
  const scrollRef = useRef<HTMLDivElement>(null);
89
104
  useChatScrollbar(scrollRef, task.id);
90
105
  const [quoteRequest, setQuoteRequest] = useState<Quote|null>(null);
@@ -93,7 +108,7 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
93
108
  const hasSession=true;
94
109
  const view=active?'chat':'changes';
95
110
  const quote=(m: Msg, source: TaskRow=task, selected?:string)=>{
96
- const text=selected||splitAttachments(m.content).text;
111
+ const text=selected||splitAttachments(m.content,source.id===task.id?attachmentScope:{taskId:source.id,workspaceRoot:readBoardState(source.id)?.workspaceRoot}).text;
97
112
  if(text.trim()) setQuoteRequest({id:m.id, author:`${m.role==='user'?'你':agentLabel(agents,source.agent)}${source.id===task.id?'':` · ${source.title}`}`,text,sourceTaskId:source.id});
98
113
  };
99
114
  const openBoard=useContext(OperatorBoardContext);
@@ -107,7 +122,18 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
107
122
  if(fresh)openBoard?.({kind:'browser',taskId:task.id});
108
123
  },[messages,transcriptLoading,openBoard,task.id]);
109
124
  const stableAnswer = useStableHandler(onAnswer);
110
- const stableCancelQueued = useStableHandler(onCancelQueued);
125
+ const cancelQueued = useStableAsync(async (pendingId: string) => onCancelQueued(pendingId));
126
+ // 转录里的撤回按钮不等结果:失败已由排队行 / 宿主说明,这里不留未处理的拒绝。
127
+ const stableCancelQueued = useCallback((pendingId: string) => { void cancelQueued(pendingId).catch(() => undefined); }, [cancelQueued]);
128
+ const stopTurn = useStableAsync(onStop);
129
+ // 排队消息「立即发送」:停掉正在执行的回复,节点随即发出排在最前面的那条。
130
+ const sendQueuedNow = useCallback(async () => { if (!(await stopTurn())) throw new Error("没能打断当前回复,请稍后重试"); }, [stopTurn]);
131
+ // 排队消息「编辑」:先撤回,撤回成功才放回输入框;它已经开始执行就不放回,免得出现两份。
132
+ const editQueued = useCallback(async (m: Msg) => {
133
+ if ((await cancelQueued(m.id)) === false) throw new Error("这条消息已经开始执行,不能再编辑");
134
+ restoreQueuedDraft(task.id, m.content, readBoardState(task.id)?.workspaceRoot??attachmentScope.workspaceRoot);
135
+ scrollRef.current?.closest(".transcript-wrap")?.parentElement?.querySelector<HTMLTextAreaElement>(".composer textarea")?.focus({ preventScroll: true });
136
+ }, [cancelQueued, task.id, attachmentScope]);
111
137
  const stableClear = useStableHandler(onClear);
112
138
  const stableReconnect = useStableHandler(onReconnect);
113
139
  // Retry for an approval-blocked failure (Transcript's APPROVAL_BLOCKED_NOTICE
@@ -118,7 +144,7 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
118
144
  const stableRetry = useStableHandler((msgId: string) => {
119
145
  const at = messages.findIndex((m) => m.id === msgId);
120
146
  for (let j = (at === -1 ? messages.length : at) - 1; j >= 0; j--) {
121
- if (messages[j].role === "user") { onSend(messages[j].content); return; }
147
+ if (messages[j].role === "user") { onSend(appendBoardContext(withoutBoardContext(messages[j].content),readBoardState(task.id),task.id)); return; }
122
148
  }
123
149
  });
124
150
  // browser_ask_user card → POST the values (lib/browserInput.ts); returns an
@@ -175,267 +201,16 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
175
201
  useEffect(() => { lastActivityRef.current = Date.now(); }, [messages]);
176
202
  const turnStartedAt = runSeenAt ?? lastUserTs;
177
203
 
178
- // Auto-scroll only while the user is parked at the bottom. If they scroll up to
179
- // read earlier output, we leave their position alone even as new messages stream
180
- // in, and surface a "jump to bottom" button instead.
181
- const pinned = useRef(true);
182
- const [atBottom, setAtBottom] = useState(true);
183
-
184
- // ---------- windowed transcript ----------
204
+ // ---------- windowed transcript (shared with CliChat: ui/useTranscriptWindow) ----------
185
205
  // Only a window of rows is in the DOM — never more than RENDER_MAX — so a task
186
206
  // with thousands of messages renders, scrolls and streams like a short one.
187
- // While following the output it's the newest RENDER_WINDOW rows. Scrolling back
188
- // reveals RENDER_STEP more above at a time (paging older messages in from the
189
- // server once the loaded ones run out) and drops rows far below; scrolling down
190
- // brings those back. "Jump to latest" returns to following.
191
- const items = useMemo(() => buildTranscriptItems(parent, older > 0), [parent, older]);
192
- // First / last rendered row by key; null = derived (newest rows).
193
- const [win, setWin] = useState<{ start: string | null; end: string | null }>({ start: null, end: null });
194
- const { startIdx, endIdx } = useMemo(() => {
195
- const find = (key: string | null) => (key ? items.findIndex((it) => it.key === key) : -1);
196
- const e = find(win.end);
197
- const last = e >= 0 ? e : items.length - 1;
198
- let s = find(win.start);
199
- // The window is pinned on message rows (labels move when older pages load);
200
- // show the session label / break right above its first message.
201
- if (s >= 0) while (s > 0 && items[s - 1].kind !== "msg") s--;
202
- return { startIdx: s >= 0 && s <= last ? s : Math.max(0, last + 1 - RENDER_WINDOW), endIdx: last };
203
- }, [items, win]);
204
- const shown = useMemo(() => items.slice(startIdx, endIdx + 1), [items, startIdx, endIdx]);
205
- const hiddenAbove = useMemo(() => {
206
- let n = older;
207
- for (let i = 0; i < startIdx; i++) if (items[i].kind === "msg") n++;
208
- return n;
209
- }, [items, startIdx, older]);
210
- const hiddenBelow = useMemo(() => {
211
- let n = 0;
212
- for (let i = endIdx + 1; i < items.length; i++) if (items[i].kind === "msg") n++;
213
- return n;
214
- }, [items, endIdx]);
215
- const [loadingOlder, setLoadingOlder] = useState(false);
216
- const [expandReq, setExpandReq] = useState(0);
217
- const itemsRef = useRef(items);
218
- itemsRef.current = items;
219
- const rangeRef = useRef({ startIdx, endIdx });
220
- rangeRef.current = { startIdx, endIdx };
221
- const winRef = useRef(win);
222
- winRef.current = win;
223
- const olderRef = useRef(older);
224
- olderRef.current = older;
225
- const hiddenRef = useRef({ above: hiddenAbove, below: hiddenBelow });
226
- hiddenRef.current = { above: hiddenAbove, below: hiddenBelow };
227
- const loadingOlderRef = useRef(false);
228
- // A rendered row and where it sat on screen, measured right before rows are
229
- // added or dropped above it and restored once THAT window change commits, so
230
- // the reader's view stays put.
231
- type Anchor = { key: string; top: number };
232
- const anchorRef = useRef<(Anchor & { win: typeof win }) | null>(null);
233
- // Measured just before an older page is applied (see revealEarlier).
234
- const pageAnchorRef = useRef<Anchor | null>(null);
235
- // A message-nav click that had to reveal rows first: finish it afterwards.
236
- const navAfterRevealRef = useRef<0 | -1 | 1>(0);
237
-
238
- const measure = useCallback((key?: string): Anchor | null => {
239
- const el = scrollRef.current;
240
- const node = key ? el?.querySelector<HTMLElement>(`[data-tkey="${CSS.escape(key)}"]`) : el?.querySelector<HTMLElement>("[data-tkey][data-msg]");
241
- return node?.dataset.tkey ? { key: node.dataset.tkey, top: node.getBoundingClientRect().top } : null;
242
- }, []);
243
- // Window edges are stored as MESSAGE keys: a session label's position shifts
244
- // when older messages are paged in above it, a message's never does.
245
- const setRange = useCallback((s: number, e: number, anchor?: Anchor | null) => {
246
- const its = itemsRef.current;
247
- let a = s;
248
- while (a < its.length && its[a].kind !== "msg") a++;
249
- let b = e;
250
- while (b > 0 && its[b].kind !== "msg") b--;
251
- const next = { start: its[a]?.key ?? null, end: e >= its.length - 1 ? null : its[b]?.key ?? null };
252
- // Same window: no state change (and no anchor left waiting for a commit that won't come).
253
- if (winRef.current.start === next.start && winRef.current.end === next.end) return;
254
- if (anchor) anchorRef.current = { ...anchor, win: next };
255
- setWin(next);
256
- }, []);
257
-
258
- // Grow the window upward over rows already loaded (dropping rows far below).
259
- // The current first row stays rendered (RENDER_MAX > RENDER_STEP) and anchors.
260
- const growUp = useCallback((anchor?: Anchor | null): boolean => {
261
- const { startIdx: s, endIdx: e } = rangeRef.current;
262
- if (s <= 0) return false;
263
- const ns = Math.max(0, s - RENDER_STEP);
264
- setRange(ns, Math.min(e, ns + RENDER_MAX - 1), anchor ?? measure());
265
- return true;
266
- }, [measure, setRange]);
267
-
268
- // Show earlier rows: loaded ones first, then a page from the server.
269
- const revealEarlier = useCallback(async () => {
270
- if (loadingOlderRef.current || growUp()) return;
271
- if (olderRef.current > 0 && onLoadOlder) {
272
- // Hold the window on its current rows so the prepended page lands above
273
- // it; the expansion effect below then reveals the bottom of that page,
274
- // anchored on where the first row sat right before the page went in.
275
- const { startIdx: s, endIdx: e } = rangeRef.current;
276
- setRange(s, e);
277
- loadingOlderRef.current = true;
278
- setLoadingOlder(true);
279
- try {
280
- if (await onLoadOlder(() => { pageAnchorRef.current = measure(); })) setExpandReq((n) => n + 1);
281
- } finally {
282
- loadingOlderRef.current = false;
283
- setLoadingOlder(false);
284
- }
285
- }
286
- }, [growUp, setRange, measure, onLoadOlder]);
287
- // Show later rows again (after scrolling back), dropping rows far above —
288
- // anchored on the first row that stays.
289
- const revealLater = useCallback(() => {
290
- const its = itemsRef.current;
291
- const { startIdx: s, endIdx: e } = rangeRef.current;
292
- if (e >= its.length - 1) return;
293
- const ne = Math.min(its.length - 1, e + RENDER_STEP);
294
- const ns = Math.max(s, ne - RENDER_MAX + 1);
295
- setRange(ns, ne, ns > s ? measure(its[ns].key) : null);
296
- }, [measure, setRange]);
297
- const revealRef = useRef({ earlier: revealEarlier, later: revealLater });
298
- revealRef.current = { earlier: revealEarlier, later: revealLater };
299
-
300
- // A page of older messages arrived above the window: reveal the bottom of it.
301
- useLayoutEffect(() => {
302
- if (!expandReq) return;
303
- const anchor = pageAnchorRef.current;
304
- pageAnchorRef.current = null;
305
- growUp(anchor);
306
- }, [expandReq, growUp]);
307
-
308
- const onScroll = useCallback(() => {
309
- const el = scrollRef.current;
310
- if (!el) return;
311
- // "At the bottom" means at the newest output — not merely at the end of a
312
- // window that stops short of it.
313
- const bottom = el.scrollHeight - el.scrollTop - el.clientHeight < 60 && winRef.current.end === null;
314
- pinned.current = bottom;
315
- setAtBottom(bottom);
316
- if (!bottom && winRef.current.start === null) {
317
- // Reading back: freeze the window, so new output arriving below doesn't
318
- // drop the rows above the reader.
319
- const first = itemsRef.current.slice(rangeRef.current.startIdx).find((it) => it.kind === "msg");
320
- if (first) setWin((w) => ({ ...w, start: first.key }));
321
- } else if (bottom && winRef.current.start !== null) {
322
- // Back at the newest output: follow it again (sheds the rows revealed above).
323
- setWin({ start: null, end: null });
324
- }
325
- }, []);
326
-
327
- // Reveal more as the reader nears either end of the window (never while
328
- // following the output).
329
- const topSentinelRef = useRef<HTMLDivElement>(null);
330
- const bottomSentinelRef = useRef<HTMLDivElement>(null);
207
+ // This adapter does not draw the folded browser-wait rows, so it asks for none.
208
+ const items = useMemo(() => buildTranscriptItems(parent, older > 0, { fold: false }), [parent, older]);
209
+ const loadOlderPage = useCallback((beforeApply: () => void) => onLoadOlder ? onLoadOlder(beforeApply) : Promise.resolve(false), [onLoadOlder]);
210
+ const { shown, hiddenAbove, hiddenBelow, loadingOlder, atBottom, onScroll, revealEarlier, revealLater, scrollToBottom, scrollToUserMsg, unpin, topSentinelRef, bottomSentinelRef } =
211
+ useTranscriptWindow({ scrollRef, items, older, loadOlder: loadOlderPage, messages, running, remountKey: `${hasSession}|${view}` });
331
212
  const hasAbove = hiddenAbove > 0;
332
213
  const hasBelow = hiddenBelow > 0;
333
- useEffect(() => {
334
- const root = scrollRef.current;
335
- if (!root || typeof IntersectionObserver === "undefined") return;
336
- const watch = (target: HTMLElement | null, margin: string, go: () => void) => {
337
- if (!target) return null;
338
- const io = new IntersectionObserver((entries) => {
339
- if (!pinned.current && entries.some((e) => e.isIntersecting)) go();
340
- }, { root, rootMargin: margin });
341
- io.observe(target);
342
- return io;
343
- };
344
- const up = hasAbove ? watch(topSentinelRef.current, "1800px 0px 0px 0px", () => void revealRef.current.earlier()) : null;
345
- const down = hasBelow ? watch(bottomSentinelRef.current, "0px 0px 1800px 0px", () => revealRef.current.later()) : null;
346
- return () => { up?.disconnect(); down?.disconnect(); };
347
- // `view`: on mobile the chat pane remounts when toggling chat/changes.
348
- }, [hasAbove, hasBelow, view]);
349
-
350
- // Reading back while a long turn keeps streaming: the window's bottom edge
351
- // follows the output, so cap it at RENDER_MAX. Reader in the upper half →
352
- // stop extending (new output waits below the "show later" control); in the
353
- // lower half → drop the oldest rows above instead, holding the view in place.
354
- useLayoutEffect(() => {
355
- // +2: a session break and label may sit above the first message row.
356
- if (win.start === null || win.end !== null || endIdx - startIdx + 1 <= RENDER_MAX + 2) return;
357
- const el = scrollRef.current;
358
- if (!el) return;
359
- if (el.scrollTop < (el.scrollHeight - el.clientHeight) / 2) {
360
- setRange(startIdx, startIdx + RENDER_MAX - 1);
361
- } else {
362
- const ns = endIdx - RENDER_MAX + 1;
363
- setRange(ns, endIdx, measure(itemsRef.current[ns].key));
364
- }
365
- }, [win, startIdx, endIdx, setRange, measure]);
366
-
367
- const scrollToBottom = useCallback((behavior: ScrollBehavior = "smooth") => {
368
- const el = scrollRef.current;
369
- if (!el) return;
370
- pinned.current = true;
371
- setAtBottom(true);
372
- // Not showing the newest rows: switch back to following; the pinned layout
373
- // effect below lands on the bottom once they render.
374
- if (winRef.current.start !== null || winRef.current.end !== null) { setWin({ start: null, end: null }); return; }
375
- el.scrollTo({ top: el.scrollHeight, behavior });
376
- }, []);
377
-
378
- // Jump between the user's own messages in the transcript. dir < 0 goes to the
379
- // previous one above the current scroll position, dir > 0 to the next below it;
380
- // queued (not-yet-sent) bubbles are excluded so nav only lands on real turns.
381
- // Past the edge of the rendered window it reveals more rows first.
382
- const scrollToUserMsg = useCallback((dir: -1 | 1) => {
383
- const el = scrollRef.current;
384
- if (!el) return;
385
- const base = el.getBoundingClientRect().top;
386
- const tops = Array.from(el.querySelectorAll<HTMLElement>(".msg.user:not(.queued)"))
387
- .map((n) => n.getBoundingClientRect().top - base + el.scrollTop);
388
- const cur = el.scrollTop;
389
- const eps = 8;
390
- const candidates = dir < 0 ? tops.filter((t) => t < cur - eps) : tops.filter((t) => t > cur + eps);
391
- if (!candidates.length && (dir < 0 ? hiddenRef.current.above : hiddenRef.current.below) > 0) {
392
- navAfterRevealRef.current = dir;
393
- if (dir < 0) void revealRef.current.earlier();
394
- else revealRef.current.later();
395
- return;
396
- }
397
- if (!tops.length) return;
398
- const target = candidates.length ? (dir < 0 ? candidates[candidates.length - 1] : candidates[0]) : dir < 0 ? tops[0] : tops[tops.length - 1];
399
- el.scrollTo({ top: Math.max(0, target - 12), behavior: "smooth" });
400
- }, []);
401
-
402
- // The window moved: put the anchored row back where it was (a no-op where the
403
- // browser's own scroll anchoring already did it), then finish a pending nav.
404
- // Only the commit of the window change the anchor was measured for restores
405
- // it — an intermediate commit (an older page landing) must not consume it.
406
- useLayoutEffect(() => {
407
- const a = anchorRef.current;
408
- const el = scrollRef.current;
409
- if (a && a.win === win) {
410
- anchorRef.current = null;
411
- const node = el?.querySelector<HTMLElement>(`[data-tkey="${CSS.escape(a.key)}"]`);
412
- if (el && node) {
413
- const delta = node.getBoundingClientRect().top - a.top;
414
- if (Math.abs(delta) > 1) el.scrollTop += delta;
415
- }
416
- }
417
- const nav = navAfterRevealRef.current;
418
- if (nav && !anchorRef.current) {
419
- navAfterRevealRef.current = 0;
420
- scrollToUserMsg(nav);
421
- }
422
- }, [win, scrollToUserMsg]);
423
-
424
- // Following the output: stay on the newest row as content arrives or the
425
- // window sheds rows above. Layout effect, so it lands before paint (no jump).
426
- useLayoutEffect(() => {
427
- if (pinned.current && scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
428
- }, [messages, running, startIdx, endIdx, win]);
429
- // …and when the pane itself resizes (the composer growing, a banner
430
- // appearing). Content resizes are left alone, so expanding a tool card at
431
- // the bottom doesn't yank its top out of view.
432
- useEffect(() => {
433
- const el = scrollRef.current;
434
- if (!el || typeof ResizeObserver === "undefined") return;
435
- const ro = new ResizeObserver(() => { if (pinned.current) el.scrollTop = el.scrollHeight; });
436
- ro.observe(el);
437
- return () => ro.disconnect();
438
- }, [hasSession, view]);
439
214
 
440
215
  const flowPositioned=useRef(!task.parent_task_id);
441
216
  useLayoutEffect(()=>{
@@ -444,10 +219,11 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
444
219
  const boundary=Array.from(el?.querySelectorAll<HTMLElement>(".branch-nav")??[]).find(e=>e.dataset.parentId===task.parent_task_id);
445
220
  if(!el || !boundary) return;
446
221
  el.scrollTop+=boundary.getBoundingClientRect().top-el.getBoundingClientRect().top-60;
447
- pinned.current=false; setAtBottom(false); flowPositioned.current=true;
222
+ unpin(); flowPositioned.current=true;
448
223
  },[active,flow.ready,task.parent_task_id]);
449
224
  useEffect(()=>{if(!task.parent_task_id && active) scrollToBottom("auto");},[active,task.id]);
450
- const queued = <QueuedMessages scopeKey={task.id} messages={messages.filter(message => message.role === "queued")} onCancel={message => stableCancelQueued(message.id)} attachmentUrl={attachment => `/api/tasks/${encodeURIComponent(attachment.taskId)}/uploads/${encodeURIComponent(attachment.name)}`} renderMessage={message => <MessageView m={message} initial={false} hideWho readOnly />} />;
225
+ const queued = <QueuedMessages scopeKey={task.id} messages={messages.filter(message => message.role === "queued")} onCancel={readOnly ? undefined : message => cancelQueued(message.id)}
226
+ onSendNow={!readOnly && running ? sendQueuedNow : undefined} onEdit={!readOnly && composer?.show !== false ? editQueued : undefined} attachmentScope={attachmentScope} attachmentUrl={attachment => attachment.workspace?taskFileApiUrl(attachment.taskId,attachment.path):`/api/tasks/${encodeURIComponent(attachment.taskId)}/uploads/${encodeURIComponent(attachment.name)}`} renderMessage={message => <MessageView m={message} initial={false} hideWho readOnly attachmentScope={attachmentScope} />} />;
451
227
  return (<FileLinkContext.Provider value={fileScope}>
452
228
  <SubagentChatScope scopeKey={task.id} messages={messages} load={loadSubagent} renderMessage={renderSubagentMessage}>
453
229
  <div className="transcript-wrap">
@@ -485,9 +261,14 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
485
261
  <div key={it.key} data-tkey={it.key} className="session-label"><span className="ln" />第 {it.n} 次会话{it.current ? " · 当前" : ""}<span className="ln" /></div>
486
262
  ) : it.kind === "break" ? (
487
263
  <div key={it.key} data-tkey={it.key}><SessionBreak summary={it.summary} /></div>
264
+ ) : it.kind === "fold" ? (
265
+ // Not requested here ({ fold: false }); kept total so a folded row can never vanish.
266
+ <div key={it.key} data-tkey={it.key} data-msg="">
267
+ {it.msgs.map((m) => <MessageView readOnly={readOnly} key={m.id} m={m} initial={false} hideWho running={running} agent={task.agent} agentLabel={agentLabel(agents, task.agent)} attachmentScope={attachmentScope} onAnswer={stableAnswer} onCancelQueued={stableCancelQueued} onClear={stableClear} onReconnect={stableReconnect} onRetry={stableRetry} onInput={stableInput} onBrowser={stableBrowser} onQuote={(msg,selected)=>quote(msg,task,selected)} />)}
268
+ </div>
488
269
  ) : (
489
270
  <div key={it.key} data-tkey={it.key} data-msg="">
490
- <MessageView m={it.m} initial={it.initial} hideWho={it.hideWho} running={running} agent={task.agent} agentLabel={agentLabel(agents, task.agent)} onAnswer={stableAnswer} onCancelQueued={stableCancelQueued} onClear={stableClear} onReconnect={stableReconnect} onRetry={stableRetry} onInput={stableInput} onBrowser={stableBrowser} onQuote={(m,selected)=>quote(m,task,selected)} />
271
+ <MessageView readOnly={readOnly} m={it.m} initial={it.initial} hideWho={it.hideWho} running={running} agent={task.agent} agentLabel={agentLabel(agents, task.agent)} attachmentScope={attachmentScope} onAnswer={stableAnswer} onCancelQueued={stableCancelQueued} onClear={stableClear} onReconnect={stableReconnect} onRetry={stableRetry} onInput={stableInput} onBrowser={stableBrowser} onQuote={(m,selected)=>quote(m,task,selected)} />
491
272
  </div>
492
273
  )
493
274
  )}
@@ -517,7 +298,7 @@ function ChatSession({ project, task, tasks, agents, messages, running, transcri
517
298
  )}
518
299
  </div>
519
300
  </div>
520
- {composer?.show !== false ? <Composer tasks={tasks} onFork={onFork} task={task} agentLabel={agentLabel(agents, task.agent)} disabled={task.started!==1} configBusy={configBusy} running={running} onSend={async text => { const sent = await onSend(text); if (sent && !running) scrollToBottom("auto"); return sent; }} onStop={onStop} onClear={onClear} quoteRequest={quoteRequest} onQuoteHandled={()=>setQuoteRequest(null)} controls={controls}
301
+ {!readOnly && composer?.show !== false ? <Composer tasks={tasks} onFork={onFork} task={task} agentLabel={agentLabel(agents, task.agent)} disabled={task.started!==1} configBusy={configBusy} running={running} onSend={async text => { const sent = await onSend(text); if (sent && !running) scrollToBottom("auto"); return sent; }} onStop={onStop} onClear={onClear} quoteRequest={quoteRequest} onQuoteHandled={()=>setQuoteRequest(null)} controls={controls}
521
302
  fileUpload={composer?.fileUpload} queued={queued} /> : queued}
522
303
  </SubagentChatScope></FileLinkContext.Provider>
523
304
  );
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  import { useEffect, useMemo, useRef, useState } from "react";
4
- import { Icon } from "./icons";
4
+ import { Icon } from "../../ui/icons";
5
5
  import { jget } from "./api";
6
6
  import type { PaletteTaskRow, ProjectRow } from "./types";
7
7
  import { StatusDot } from "./shared";
@@ -4,12 +4,12 @@ import { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type
4
4
  import { DOCUMENT_MAX_BYTES, FILE_UPLOAD_ACCEPT, isOriginalDocument, uploadFileType, UPLOAD_OTHER_MAX_BYTES } from "../../core/documentUpload";
5
5
  import { Popover } from "./shared";
6
6
  import type { TaskRow } from "./types";
7
- import { Icon } from "./icons";
7
+ import { Icon } from "../../ui/icons";
8
8
  import { attachmentMarker, fileAttachmentMarker } from "./format";
9
9
  import { MAX_MESSAGE_CHARS, PASTE_ATTACH_THRESHOLD } from "./protocol/promptLimits";
10
10
  import { RunControls, type RunControlProps } from "./RunControls";
11
11
  import { appendBoardContext } from "../../board/context";
12
- import { readBoardState, useBoardState } from "./boardState";
12
+ import { readBoardState, useBoardState, publishBoardState } from "./boardState";
13
13
  import { clientId } from "../../core/id";
14
14
  import { useComposerAutosize } from "../../ui/useComposerAutosize";
15
15
  import { ReferenceCard } from "../../ui/ReferenceCard";
@@ -49,7 +49,7 @@ export function Composer({ task, agentLabel, disabled, running, onSend, onStop,
49
49
  const caretRequest = useRef<number | null>(null);
50
50
  const composing = useRef(false);
51
51
  const uploads = useRef(new Map<string, AbortController>());
52
- const uploadFiles = useRef(new Map<string, File>());
52
+ const uploadFiles = useRef(new Map<string, { file: File; destinationDir: string }>());
53
53
  const backend = useMemo(() => getOperatorBoardBackend(), []);
54
54
  const parentBoard = useContext(OperatorBoardContext);
55
55
  const uploadScope = useRef({ taskId: task.id, openBoard: parentBoard ?? openOperatorBoard });
@@ -119,14 +119,16 @@ export function Composer({ task, agentLabel, disabled, running, onSend, onStop,
119
119
  const startUpload = (key: string, file: File) => {
120
120
  if (!fileUpload || !backend.uploadFile || locked || uploads.current.has(key)) return;
121
121
  const taskId = task.id;
122
+ const view = readBoardState(taskId);
123
+ const destinationDir = uploadFiles.current.get(key)?.destinationDir ?? (view && (!view.directorySourceId || view.directorySourceId === taskId) ? view.dir || "." : ".");
122
124
  const preview = draftRef.current.attachments.find(a => a.key === key)?.preview;
123
125
  const controller = new AbortController();
124
126
  uploads.current.set(key, controller);
125
- uploadFiles.current.set(key, file);
127
+ uploadFiles.current.set(key, { file, destinationDir });
126
128
  const current = () => mounted.current && uploadScope.current.taskId === taskId && uploads.current.get(key) === controller && !controller.signal.aborted && draftRef.current.attachments.some(a => a.key === key);
127
129
  update(d => ({ ...d, attachments: d.attachments.map(a => a.key === key ? { ...a, status: "uploading", phase: "queued", bytes: 0, size: file.size, error: undefined } : a) }));
128
130
  void Promise.resolve().then(() => backend.uploadFile!(taskId, file, {
129
- draftId: key, signal: controller.signal,
131
+ draftId: key, signal: controller.signal, destinationDir,
130
132
  onPhase: phase => { if (current()) update(d => ({ ...d, attachments: d.attachments.map(a => a.key === key ? { ...a, phase } : a) })); },
131
133
  onBytes: bytes => { if (current()) update(d => ({ ...d, attachments: d.attachments.map(a => a.key === key ? { ...a, bytes } : a) })); },
132
134
  })).then(receipt => {
@@ -136,6 +138,11 @@ export function Composer({ task, agentLabel, disabled, running, onSend, onStop,
136
138
  update(d => ({ ...d, attachments: d.attachments.map(a => a.key === key ? { ...a, path, preview: a.kind === "image" ? receipt.url ?? backend.fileUrl(taskId, path) : "", status: "ready", bytes: file.size } : a) }));
137
139
  uploadFiles.current.delete(key);
138
140
  uploadScope.current.openBoard({ kind: "file", taskId, path });
141
+ void backend.info(taskId).then(info=>{
142
+ if(!mounted.current||uploadScope.current.taskId!==taskId||!info.workspaceRoot)return;
143
+ const view=readBoardState(taskId)??{tab:"files",dir:destinationDir==="."?"":destinationDir,file:null,files:[],visible:false,directorySourceId:taskId};
144
+ publishBoardState(taskId,{...view,workspaceRoot:info.workspaceRoot,remoteTaskId:taskId});
145
+ },()=>{});
139
146
  }).catch((e: unknown) => {
140
147
  if (current()) update(d => ({ ...d, attachments: d.attachments.map(a => a.key === key ? { ...a, status: "error", error: e instanceof Error ? e.message : "上传失败,请重试。" } : a) }));
141
148
  }).finally(() => {
@@ -260,7 +267,7 @@ export function Composer({ task, agentLabel, disabled, running, onSend, onStop,
260
267
  {draft.attachments.some(a => a.status !== "ready") && <div className="composer-upload-list">{draft.attachments.filter(a => a.status !== "ready").map(a => <UploadProgress key={a.key} name={a.name}
261
268
  status={a.status === "error" ? "error" : a.phase ?? "queued"} bytes={a.bytes} total={a.size} disabled={locked}
262
269
  error={`${a.error || "上传失败,请重试。"}${uploadFiles.current.has(a.key) || a.error?.includes("重新选择文件") ? "" : " 请重新选择文件。"}`}
263
- onCancel={() => removeAtt(a.key)} onRemove={() => removeAtt(a.key)} onRetry={fileUpload && uploadFiles.current.has(a.key) ? () => startUpload(a.key, uploadFiles.current.get(a.key)!) : undefined} />)}</div>}
270
+ onCancel={() => removeAtt(a.key)} onRemove={() => removeAtt(a.key)} onRetry={fileUpload && uploadFiles.current.has(a.key) ? () => startUpload(a.key, uploadFiles.current.get(a.key)!.file) : undefined} />)}</div>}
264
271
  {readyAttachments.length > 0 && <div className="attach-row">{readyAttachments.map((a) => <div key={a.key} className={`attach-chip ${a.kind} ${a.status}`} title={a.name}>
265
272
  {a.kind === "image" && a.preview ? <img src={a.preview} alt={a.name} /> : <span className="attach-file">{Icon.clip()} {a.name}</span>}
266
273
  <button className="attach-x" disabled={locked} aria-label={`移除 ${a.name}`} onClick={() => removeAtt(a.key)}>×</button>
@@ -1,7 +1,7 @@
1
1
  "use client";
2
2
 
3
3
  import { useEffect, useRef, useState } from "react";
4
- import { Icon } from "./icons";
4
+ import { Icon } from "../../ui/icons";
5
5
  import { TerminalView } from "./Terminal";
6
6
  import { Skel } from "./shared";
7
7
 
@@ -1,11 +1,7 @@
1
1
  "use client";
2
2
 
3
- import { memo, useContext } from "react";
4
- import ReactMarkdown, { defaultUrlTransform } from "react-markdown";
5
- import remarkGfm from "remark-gfm";
6
- import rehypeHighlight from "rehype-highlight";
7
- import type { ComponentProps } from "react";
8
- import { inlineFilePath } from "../../ui/fileLinks";
3
+ import { useContext, type ComponentProps } from "react";
4
+ import { createMarkdown } from "../../ui/Markdown";
9
5
  import { OperatorBoardContext } from "./boardInteraction";
10
6
  import { FileLinkContext, localFilePath, rewriteFileHref, rewriteFileSrc } from "./fileLinks";
11
7
 
@@ -22,11 +18,6 @@ function MdLink({ href, ...props }: ComponentProps<"a">) {
22
18
  if(scope&&path&&open?.({kind:'file',taskId:scope.taskId,path}))event.preventDefault();}} />;
23
19
  }
24
20
 
25
- function MdCode({children, ...props}: ComponentProps<"code">) {
26
- const path=inlineFilePath(children);
27
- return path ? <MdLink href={path}><code {...props}>{children}</code></MdLink> : <code {...props}>{children}</code>;
28
- }
29
-
30
21
  function MdImg({ src, alt, ...props }: ComponentProps<"img">) {
31
22
  const scope = useContext(FileLinkContext);
32
23
  const local = typeof src === "string" ? rewriteFileSrc(scope, src) : null;
@@ -34,28 +25,7 @@ function MdImg({ src, alt, ...props }: ComponentProps<"img">) {
34
25
  return <img {...props} alt={alt ?? ""} src={local ?? src} />;
35
26
  }
36
27
 
37
- // The default transform blanks any non-web scheme; let file: (and C:\ paths)
38
- // through so MdLink can map them to the task's file route.
39
- const urlTransform = (url: string) => (/^file:/i.test(url) || /^[a-z]:[\\/]/i.test(url) ? url : defaultUrlTransform(url));
40
-
41
- // Renders Claude's markdown output: headings, lists, tables, fenced code blocks
42
- // (syntax-highlighted), inline code, links. Used for assistant + user messages.
43
- //
44
- // Perf: `detect: false` — only fenced blocks with an explicit language get
45
- // highlighted; hljs auto-detection ran over every bare code block and was a
46
- // hot spot during streaming turns. Memoized so messages whose text hasn't
47
- // changed skip the whole markdown parse + highlight on transcript re-renders.
48
- export const Markdown = memo(function Markdown({ children }: { children: string }) {
49
- return (
50
- <div className="md">
51
- <ReactMarkdown
52
- remarkPlugins={[remarkGfm]}
53
- rehypePlugins={[[rehypeHighlight, { detect: false, ignoreMissing: true }]]}
54
- components={{ a: MdLink, img: MdImg, code: MdCode }}
55
- urlTransform={urlTransform}
56
- >
57
- {children}
58
- </ReactMarkdown>
59
- </div>
60
- );
61
- });
28
+ // Rendering rules (plugins, highlighting, inline file-path code, memo) are shared
29
+ // with the center adapter (ui/Markdown createMarkdown); only how a local file
30
+ // link / image resolves is node-specific: the task's file route and board.
31
+ export const Markdown = createMarkdown({ Link: MdLink, Image: MdImg });
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { useCallback, useEffect, useRef, useState } from "react";
4
4
  import type { Priority } from "./protocol/types";
5
- import { Icon } from "./icons";
5
+ import { Icon } from "../../ui/icons";
6
6
  import { jget, jsend } from "./api";
7
7
  import { SLABEL, type FsListing, type TaskRow } from "./types";
8
8
  import { StatusDot, Skel, ErrNote } from "./shared";
@@ -1,10 +1,11 @@
1
1
  "use client";
2
2
 
3
3
  import { useCallback, useEffect, useState } from "react";
4
- import { Icon } from "./icons";
4
+ import { Icon } from "../../ui/icons";
5
5
  import { jget, jsend } from "./api";
6
6
  import { AgentConnect } from "./AgentConnect";
7
7
  import type { AgentInfoT, AgentsResponseT, ClaudeVerifyT, OnboardingT, OnbStep } from "./types";
8
+ import { useRecheckOnReturn } from "./recheckOnReturn";
8
9
 
9
10
  // The first-run wizard, trimmed to the two irreducible auth steps: connect a
10
11
  // coding agent, then verify it responds. "An agent" — not Claude specifically:
@@ -45,14 +46,11 @@ export function OnboardingWizard({
45
46
 
46
47
  const connected = (bundle?.agents ?? []).filter((a) => a.connected);
47
48
 
48
- // While nothing is connected yet, keep re-checking: a login can settle
49
- // server-side after a missed onConnected (e.g. the connect card was remounted
50
- // mid-login), and without this the Continue button stays locked until a reload.
51
- useEffect(() => {
52
- if (step !== "connect" || connected.length > 0) return;
53
- const t = setInterval(load, 3_000);
54
- return () => clearInterval(t);
55
- }, [step, connected.length, load]);
49
+ // While nothing is connected yet, re-check: a login can settle server-side
50
+ // after a missed onConnected (e.g. the connect card was remounted mid-login),
51
+ // and without this the Continue button stays locked until a reload. Checked
52
+ // when the user comes back to the tab or presses 重新检查 — no polling.
53
+ useRecheckOnReturn(step === "connect" && connected.length === 0, load);
56
54
  const verifyAgent =
57
55
  (justConnected && connected.find((a) => a.id === justConnected)) || connected[0] || null;
58
56
 
@@ -93,6 +91,7 @@ export function OnboardingWizard({
93
91
  bundle={bundle}
94
92
  done={connected.length > 0}
95
93
  onConnected={(id) => { setJustConnected(id); load(); }}
94
+ onRecheck={load}
96
95
  onContinue={() => goto("verify")}
97
96
  />
98
97
  )}
@@ -127,11 +126,13 @@ function ConnectStep({
127
126
  bundle,
128
127
  done,
129
128
  onConnected,
129
+ onRecheck,
130
130
  onContinue,
131
131
  }: {
132
132
  bundle: AgentsResponseT | null;
133
133
  done: boolean;
134
134
  onConnected: (agentId: string) => void;
135
+ onRecheck: () => void;
135
136
  onContinue: () => void;
136
137
  }) {
137
138
  const agents = bundle?.agents ?? [];
@@ -167,6 +168,7 @@ function ConnectStep({
167
168
  )}
168
169
  </div>
169
170
  <div className="wiz-foot">
171
+ {!done && bundle && <button className="linkbtn" onClick={onRecheck} title="在别处登录过了?重新读取连接状态">已经登录过?重新检查</button>}
170
172
  <span className="spacer" />
171
173
  <button className="btn btn-accent" disabled={!done} onClick={onContinue}>
172
174
  继续 {Icon.chevRight()}