Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge group-task-home-reply-timeout into bots-ux
Chrisfd744178c2bc
diff --cc apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex 5ea7e4f10d,e5b7ccfb45..e4c90c1ca2--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@@ -1,19 -1,14 +1,19 @@@-import type { ReactNode } from 'react';/**- * 群聊页:顶栏(成员头像、群名、成员名单、群设置入口)+ 多作者时间线 + 输入框。+ * 群聊页:顶栏(成员头像、群名、成员与负责人、此刻谁在做什么、群设置入口)+ 多作者时间线 ++ * 进行中条 + 输入框。*- * 数据全部来自 main(docs/product-rules/bot-group-chat.md §3):进入时读一页最新消息,- * 之后每条 `onBotGroupChanged` 推送(含分工的 `'plan'`)都整页重读,renderer 不自己拼- * 时间线。加载沿用 BotDirectMessageView 的新鲜度护栏:请求代次 + data owner 代次 + 推送- * owner 戳,过期响应一律丢弃。更早的消息按需翻页,连同其引用的安排合并进当前时间线。+ * 数据全部来自 main(docs/product-rules/bot-group-chat.md §3):进入时读一页最新消息,之后每条+ * `onBotGroupChanged` 推送(含分工的 `'plan'`)都重读最新一页。读取同一时刻只有一个在飞,期间+ * 来的推送合并成一次补读——一阵推送也会边到边显示,较新的结果从不被丢掉。新的一页**并入**+ * 屏幕上已有的消息(BotGroupTimelineModel.ts):被新消息挤出最新页的旧消息留着,不出缺口、+ * 不跳;内容没变的消息沿用原对象,memo 过的消息行不重绘。账号(data owner)代次照旧作废+ * 迟到的回包。更早的消息按需翻页,连同其引用的安排合并进当前时间线。*- * 分工(§7):安排卡、交接文件与「下一步 · 继续」「没做完 · 重试」见 BotGroupPlan.tsx;- * 这里只负责把安排快照接到对应消息上,并调用 main 的安排操作。+ * 发送是乐观的:按下发送,自己的消息立刻出现在末尾(发送中略淡),main 的详情里出现这条消息- * 后原地换成正式那条(同一个 React key,不闪不跳);失败就撤掉、草稿放回。++ * 后原地换成正式那条(同一个 React key,不闪不跳);失败优先放回空输入框,否则留在原行重试。+ *+ * 分工(§7):安排卡、交接文件与「下一步 · 继续」「没做完 · 重试」见 BotGroupPlan.tsx;进行中+ * 条、发言行与顶栏状态见 BotGroupLiveStatus.tsx;这里把安排快照接到对应消息上并调用 main。** 引用回复(§10):页面持有本群的待发引用(随群切换整页重建,不会串群);已发消息上的* 引用块以已加载的原消息为准,点击跳到原消息并高亮,原消息不在已加载范围时向前翻几页找。@@@ -59,41 -66,30 +59,39 @@@ import type} from '../../../shared/botGroupChat';import { botGroupQuoteFromMessage, isBotGroupMessageQuotable, resolveBotGroupQuote } from '../../../shared/botGroupChat';import { useRegisterContentHeader } from '../feature-context';-import { BotAvatar } from './BotAvatar';-import { BotGenerationLabel } from './BotGenerationLabel';import { BotGroupAvatarStack } from './BotGroupAvatars';import { botGroupAttachmentScope, refreshPendingBotGroupAttachments } from './botGroupAttachments';- import { BotGroupComposer, type BotGroupOutgoingMessage, type BotGroupSendOutcome } from './BotGroupComposer';-import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';+ import { BotGroupComposer } from './BotGroupComposer';-import { BotGroupQuoteBlock } from './BotGroupQuote';-import { ChatInviteButton, ChatMessageActions, messageReactionRevision } from './ChatServerControls';+import {+ BotGroupHeaderStatusText,+ BotGroupProgressStrip,+ BotGroupSpeakerInteraction,+ BotGroupSpeakingLine,+ botGroupHeaderStatus,+ type BotGroupLiveSpeaker,+} from './BotGroupLiveStatus';+import { ChatInviteButton, messageReactionRevision } from './ChatServerControls';import { animateThreadPanelWidth, ChatThreadPanel } from './ChatThreadPanel';-import { BotGroupPendingInteraction } from './BotGroupPendingInteraction';-import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';-import { BotGroupTaskCard } from './BotGroupTaskCard';-import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';import {- BotGroupHandoffFiles,BotGroupOrganizerTag,- BotGroupPlanCard,- BotGroupPlanEndDivider,BotGroupPlanFollowUpRow,type BotGroupFollowUpAction,type BotGroupPlanCardAction,} from './BotGroupPlan';-import { splitBotGroupMentionSegments } from './botGroupMentions';+import { BotGroupDateDivider, BotGroupTimelineItem } from './BotGroupTimelineItem';+import {+ botGroupHandoffStepNumbers,+ botGroupMemberDisplayName,+ botGroupOwnedBotNames,+ layoutBotGroupTimeline,- matchBotGroupPendingSends,+ mergeBotGroupLatestPage,+ pendingBotGroupMessage,+ pendingBotGroupMessageId,+ runningBotGroupPlanStep,+ stabilizeById,+ type BotGroupLoadedTimeline,- type BotGroupPendingSend,+ type BotGroupTimelineMessage,+} from './BotGroupTimelineModel';import {BOT_GROUP_SETTINGS_PARAM,botGroupComposerPlanState,@@@ -107,11 -104,36 +105,16 @@@openBotGroupPlan,} from './botGroupPresentation';import { botGroupApi, editBotGroupPlanStep, runBotGroupPlanAction, useBotGroupSummary } from './botGroupStore';+import { botGroupReadKey, markBotRead } from './botReadState';+ import {- beginBotGroupTimelineRead,- discardBotGroupOutbox,- editBotGroupSend,- getBotGroupOutboxClaims,- getBotGroupOutboxPreviews,- interleaveBotGroupOutbox,- mergeBotGroupLocalAttachments,- noteBotGroupTimeline,- projectBotGroupOutbox,- retryBotGroupSend,- useBotGroupOutbox,- type BotGroupOutboxEntry,++ beginBotGroupTimelineRead, discardBotGroupOutbox, getBotGroupOutboxClaims,++ getBotGroupOutboxPreviews, interleaveBotGroupOutbox, mergeBotGroupLocalAttachments,++ noteBotGroupTimeline, projectBotGroupOutbox, useBotGroupOutbox,+ } from './botGroupOutbox';-import { botGroupReadKey, markBotRead } from './botReadState';-import { collectBotMessageTimeGroups, formatBotMessageGroupTime } from './botConversationTimeline';type GroupViewState =| { kind: 'loading' }- | ({ kind: 'ready' } & BotGroupLoadedTimeline)- | {- kind: 'ready';- group: BotGroupDetail;- /** Pages loaded through 「查看更早的消息」, merged under the latest page. */- older: BotGroupMessageView[];- /** Plans referenced by the older pages; the latest read wins on overlap. */- olderPlans: BotGroupPlanView[];- olderHasMore: boolean;- /** Outbox read token of the read that produced `group` (see beginBotGroupTimelineRead). */- readToken: number;- }++ | ({ kind: 'ready'; readToken: number } & BotGroupLoadedTimeline)| { kind: 'missing' }| { kind: 'error' };@@@ -228,48 -233,48 +229,54 @@@ function BotGroupChatContent({ groupIduseEffect(() => {let cancelled = false;- let requestVersion = 0;- // The composer queues under the group's own id, which an older local route may not match.+ const discardOutbox = () => {+ const shown = stateRef.current;+ discardBotGroupOutbox(groupId);+ if (shown.kind === 'ready' && shown.group.id !== groupId) discardBotGroupOutbox(shown.group.id);+ };- const load = async (additionalSources: string[] = []) => {- const version = ++requestVersion;+ /** Bumped when a read starts (and on delete): re-checks spawned by older reads stop. */+ let version = 0;+ let inFlight = false;+ let queued: { sources: string[]; changed: string[] } | null = null;+ const run = async (additionalSources: string[], changedIds: string[]) => {+ inFlight = true;+ const current = ++version;++ const readToken = beginBotGroupTimelineRead();const owner = getDataOwnerGeneration();const api = botGroupApi();- const isCurrent = () =>- !cancelled && version === requestVersion && isDataOwnerGenerationCurrent(owner);- if (!api || !groupId) {- if (isCurrent()) setState({ kind: groupId ? 'error' : 'missing' });- return;- }- const readToken = beginBotGroupTimelineRead();+ const isCurrent = () => !cancelled && current === version && isDataOwnerGenerationCurrent(owner);+ // Reads run one at a time, so a result is never older than what is on screen; only the+ // account (data owner) or a delete can make it stale.+ const isApplicable = () => !cancelled && isDataOwnerGenerationCurrent(owner) && current <= version;try {+ if (!api || !groupId) {+ if (isApplicable()) setState({ kind: groupId ? 'error' : 'missing' });+ return;+ }const displayed = stateRef.current;const sourceMessageIds = [...new Set([...(displayed.kind === 'ready' && displayed.group.id === groupId? mergeBotGroupMessages(displayed.older, displayed.group.messages).map(message => message.id) : []), ...additionalSources])];const result = sourceMessageIds.length ? await api.getBotGroup(groupId, { sourceMessageIds }) : await api.getBotGroup(groupId);- if (!isCurrent()) return;+ if (!isApplicable()) return;if (result.ok) {readOwner.current = owner;- setState((previous) =>- previous.kind === 'ready'- ? { ...previous, group: result.group, readToken }- : {- kind: 'ready',- group: result.group,- older: [],- olderPlans: [],- olderHasMore: result.group.hasMoreBefore,- readToken,- },- );const shown = stateRef.current;+ setState((previous) => {+ if (previous.kind !== 'ready') {- return { kind: 'ready', group: result.group, older: [], olderPlans: [], olderHasMore: result.group.hasMoreBefore };++ return { kind: 'ready', group: result.group, older: [], olderPlans: [], olderHasMore: result.group.hasMoreBefore, readToken };+ }+ const merged = mergeBotGroupLatestPage(previous, result.group);- return merged === previous ? previous : { kind: 'ready', ...merged };++ return { kind: 'ready', ...merged, readToken };+ });if (shown.kind === 'ready') {- const targets = quotedOlderOriginals(shown.older, result.group.messages);- if (targets.length > 0) void recheckQuotedOriginals(api, targets, isCurrent);+ const quoted = quotedOlderOriginals([...shown.older, ...shown.group.messages], result.group.messages);+ // A message changed here (a reaction) that sits only on an opened older page: the+ // latest page cannot refresh its copy, so its page is re-read like a quoted original's.+ const latestIds = new Set(result.group.messages.map((message) => message.id));+ const changed = shown.older.filter((message) => changedIds.includes(message.id)+ && !latestIds.has(message.id) && !quoted.some((target) => target.id === message.id));+ const targets = [...quoted, ...changed].sort((a, b) => b.sequence - a.sequence);+ if (targets.length > 0) void recheckOlderCopies(api, targets, isCurrent);}if (displayed.kind === 'ready' && displayed.group.id === groupId && result.group.messages.length > 0) {const latestFrom = Math.min(...result.group.messages.map((message) => message.sequence));@@@ -285,6 -290,8 +292,7 @@@}}} else if (result.errorCode === 'NOT_FOUND') {- // Gone for this account (deleted, archived or left): nothing of it is left to send.+ discardOutbox();setState({ kind: 'missing' });} else {// Keep a timeline that is already on screen; only a first read fails loudly.@@@ -358,10 -346,10 +366,11 @@@botGroupApi()?.onBotGroupChanged?.((payload, ownerStamp) => {if (!isDataOwnerPushCurrent(ownerStamp) || payload.groupId !== groupId) return;if (payload.change === 'deleted') {- requestVersion += 1;+ cancelled = true;+ queued = null;// Unsent attachments go with the group (staged copies included).discardDraft(botGroupAttachmentScope(groupId));+ discardOutbox();setState({ kind: 'missing' });return;}@@@ -396,77 -371,36 +405,94 @@@() => (state.kind === 'ready' ? projectBotGroupExecutionFailures(mergeBotGroupMessages(state.older, state.group.messages), state.group.executionFailures) : []),[state],);- /** Real message id → the key its optimistic copy had, so the row is kept, not remounted. */- // The composer sends under the group's own id; an older local route can still lead here.+ const outboxGroupId = group?.id ?? groupId;+ const outbox = useBotGroupOutbox(outboxGroupId);- // Settle receipts only once the read that shows them is on screen, so a pending bubble- // never disappears a frame before its real message appears. Older pages count too: a- // message pushed off the latest page settles its previews once 查看更早的消息 shows it.- // A receipt for a message the timeline already shows settles when it comes back.+ useLayoutEffect(() => {+ if (state.kind === 'ready') noteBotGroupTimeline(outboxGroupId, mergeBotGroupMessages(state.older, state.group.messages), state.readToken);+ }, [outboxGroupId, state, outbox]);- const { pending: pendingSends, localAttachments } = useMemo(- () => projectBotGroupOutbox(outbox, messages, getBotGroupOutboxClaims(outboxGroupId), getBotGroupOutboxPreviews(outboxGroupId)),- [outboxGroupId, messages, outbox],++ const { pending, localAttachments, replacements } = useMemo(++ () => projectBotGroupOutbox(outbox, realMessages, getBotGroupOutboxClaims(outboxGroupId), getBotGroupOutboxPreviews(outboxGroupId)),++ [outboxGroupId, realMessages, outbox],+ );- // A receipt the timeline does not show yet: read again so the real message takes its place.- const unreadReceipts = pendingSends.flatMap((entry) => (entry.status === 'sent' && entry.messageId ? [entry.messageId] : [])).join(',');- useEffect(() => {- if (unreadReceipts) loadRef.current();- }, [unreadReceipts]);++ /** Retain the same row when a queue entry becomes the server's message. */+ const adoptedKeysRef = useRef(new Map<string, string>());- const pendingMatches = useMemo(() => matchBotGroupPendingSends(pendingSends, realMessages, adoptedKeysRef.current), [pendingSends, realMessages]);- for (const [clientId, messageId] of pendingMatches) adoptedKeysRef.current.set(messageId, pendingBotGroupMessageId(clientId));- useEffect(() => {- if (pendingMatches.size === 0) return;- setPendingSends((previous) => previous.filter((send) => !pendingMatches.has(send.clientId)));- }, [pendingMatches]);++ for (const [messageId, clientId] of replacements) adoptedKeysRef.current.set(messageId, pendingBotGroupMessageId(clientId));+ const rows = useStableRows(useMemo<BotGroupTimelineMessage[]>(- () => [...realMessages, ...pendingSends.filter((send) => !pendingMatches.has(send.clientId)).map(pendingBotGroupMessage)],- [realMessages, pendingSends, pendingMatches],++ () => interleaveBotGroupOutbox(realMessages, pending).map((row) => {++ if (row.entry) {++ const entry = row.entry;++ return { ...pendingBotGroupMessage({++ clientId: entry.input.clientId, text: entry.input.text, mentions: entry.input.mentions,++ attachments: [...entry.attachments], quote: entry.quote ?? null,++ createdAt: entry.createdAt, afterSequence: entry.after,++ }), outbox: entry };++ }++ const local = localAttachments.get(row.message.id);++ return local && row.message.isSelf !== false && !row.message.deleted++ ? { ...row.message, attachments: mergeBotGroupLocalAttachments(row.message.attachments, local) }++ : row.message;++ }),++ [realMessages, pending, localAttachments],+ ));++ const unreadReceipts = pending.flatMap((entry) => entry.status === 'sent' && entry.messageId ? [entry.messageId] : []).join(',');++ useEffect(() => { if (unreadReceipts) loadRef.current(); }, [unreadReceipts]);+ const messageByIdRef = useRef(new Map<string, BotGroupMessageView>());+ messageByIdRef.current = new Map(realMessages.map((message) => [message.id, message]));+ const lastRealSequence = realMessages[realMessages.length - 1]?.sequence ?? 0;- const lastRealSequenceRef = useRef(lastRealSequence);- lastRealSequenceRef.current = lastRealSequence;+ /** Rows after this sequence arrived while the page was open: they fade in. */+ const enterAfterRef = useRef<number | null>(null);+ if (enterAfterRef.current === null && state.kind === 'ready') enterAfterRef.current = lastRealSequence;+// Quotes resolve against verified copies only; an unverified original falls back to the snapshot.const quoteSources = useMemo(- () => (unverifiedOriginals.size > 0 ? messages.filter((message) => !unverifiedOriginals.has(message.id)) : messages),- [messages, unverifiedOriginals],+ () => (unverifiedOriginals.size > 0 ? realMessages.filter((message) => !unverifiedOriginals.has(message.id)) : realMessages),+ [realMessages, unverifiedOriginals],);+ const quoteDisplayCache = useRef(new Map<string, { key: string; display: BotGroupQuoteDisplay }>());+ const quoteDisplays = useMemo(() => {+ const next = new Map<string, { key: string; display: BotGroupQuoteDisplay }>();+ for (const message of rows) {+ if (!message.quote) continue;+ const display = resolveBotGroupQuote(message.quote, quoteSources);+ const key = JSON.stringify(display);+ const cached = quoteDisplayCache.current.get(message.id);+ next.set(message.id, cached && cached.key === key ? cached : { key, display });+ }+ quoteDisplayCache.current = next;+ return next;+ }, [rows, quoteSources]);++ // Read marks: the newest incoming message (a Bot or another human) once it is in view.+ // Same range as the unread count (`incomingMessageTimes`): spoken messages and a Bot's+ // plan card; notices never count, so a plan card at the tail cannot leave a stuck badge.+ const latestIncomingAt = useMemo(() => realMessages.reduce((latest, message) =>+ (message.kind === 'message' || message.kind === 'plan') && (message.authorKind === 'bot' || message.isSelf === false)+ ? Math.max(latest, message.createdAt) : latest, 0), [realMessages]);+ const latestIncomingRef = useRef(latestIncomingAt);+ latestIncomingRef.current = latestIncomingAt;const acknowledge = useCallback(() => {if (!isDataOwnerGenerationCurrent(readOwner.current) || !stickToBottomRef.current || document.visibilityState !== 'visible' || !document.hasFocus()) return;- const at = messages.reduce((latest, message) => message.kind === 'message' && (message.authorKind === 'bot' || message.isSelf === false)- ? Math.max(latest, message.createdAt) : latest, 0);+ const at = latestIncomingRef.current;if (at > 0) markBotRead(botGroupReadKey(groupId), at);- }, [groupId, messages]);+ }, [groupId]);+ const lastAcknowledgeRef = useRef(0);+ const acknowledgeTimerRef = useRef<number | null>(null);+ /** Leading-edge throttle for scroll: the first event marks at once, a burst marks once more after. */+ const acknowledgeSoon = useCallback(() => {+ const now = Date.now();+ if (now - lastAcknowledgeRef.current >= ACKNOWLEDGE_THROTTLE_MS) {+ lastAcknowledgeRef.current = now;+ acknowledge();+ return;+ }+ if (acknowledgeTimerRef.current !== null) return;+ acknowledgeTimerRef.current = window.setTimeout(() => {+ acknowledgeTimerRef.current = null;+ lastAcknowledgeRef.current = Date.now();+ acknowledge();+ }, ACKNOWLEDGE_THROTTLE_MS);+ }, [acknowledge]);+ useEffect(() => () => { if (acknowledgeTimerRef.current !== null) window.clearTimeout(acknowledgeTimerRef.current); }, []);useEffect(() => {const frame = requestAnimationFrame(acknowledge);window.addEventListener('focus', acknowledge);@@@ -832,87 -722,6 +858,72 @@@}};+ // Stable handlers for the memoized rows; each reads the latest page state through refs.+ const actionsRef = useRef({ locateQuoted, continueRound, runPlanAction, editPlanStep });+ actionsRef.current = { locateQuoted, continueRound, runPlanAction, editPlanStep };+ const onLocateQuote = useCallback((quote: BotGroupQuoteView) => void actionsRef.current.locateQuoted(quote), []);+ const onContinue = useCallback(() => void actionsRef.current.continueRound(), []);+ const onPlanAction = useCallback((action: 'start' | 'dismiss', planId: string) => void actionsRef.current.runPlanAction(action, planId), []);+ const onEditStep = useCallback((planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) =>+ void actionsRef.current.editPlanStep(planId, step, action, botId), []);+ const onChanged = useCallback((messageId: string) => loadRef.current([], [messageId]), []);+ const onQuote = useCallback((messageId: string) => {+ const message = messageByIdRef.current.get(messageId);+ if (message) setQuoteDraft(botGroupQuoteFromMessage(message));+ }, []);+ const onOpenThread = useCallback((messageId: string) => {+ threadOpenerRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;+ if (threadCloseAnimationRef.current) {+ threadCloseAnimationRef.current.cancel();+ threadCloseAnimationRef.current = null;+ const panel = threadLayoutRef.current?.querySelector('aside');+ if (panel) panel.inert = false;+ if (messageId === threadRootIdRef.current) {+ (panel?.querySelector<HTMLTextAreaElement>('textarea:not(:disabled)') ?? panel?.querySelector<HTMLButtonElement>('header button'))?.focus();+ }+ }+ setThreadRootId(messageId);+ }, []);- const onSendStart = useCallback((message: BotGroupOutgoingMessage) => {- stickToBottomRef.current = true;- setPendingSends((previous) => [- ...previous.filter((send) => send.clientId !== message.clientId),- { ...message, createdAt: Date.now(), afterSequence: lastRealSequenceRef.current },- ]);- }, []);- const onSendSettled = useCallback((clientId: string, outcome: BotGroupSendOutcome) => {- setPendingSends((previous) => outcome.ok- ? previous.map((send) => (send.clientId === clientId ? { ...send, messageId: outcome.messageId } : send))- : previous.filter((send) => send.clientId !== clientId));- }, []);- const onSent = useCallback(() => {- stickToBottomRef.current = true;- loadRef.current();- }, []);++ const onSending = useCallback(() => { stickToBottomRef.current = true; }, []);++ const planById = useMemo(() => new Map(plans.map((plan) => [plan.id, plan])), [plans]);+ const layout = useMemo(() => layoutBotGroupTimeline(rows), [rows]);+ const stepNumbers = useMemo(() => botGroupHandoffStepNumbers(realMessages, planById), [realMessages, planById]);+ /** Finish time of each done step (1-based) per plan, from the hand-off messages; stable per content. */+ const doneAtCache = useRef(new Map<string, { key: string; value: ReadonlyMap<number, number> }>());+ const planDoneAt = useMemo(() => {+ const byPlan = new Map<string, Map<number, number>>();+ for (const message of realMessages) {+ const number = stepNumbers.get(message.id);+ if (number === undefined || !message.planId) continue;+ const entry = byPlan.get(message.planId) ?? new Map<number, number>();+ entry.set(number, message.createdAt);+ byPlan.set(message.planId, entry);+ }+ const next = new Map<string, { key: string; value: ReadonlyMap<number, number> }>();+ for (const [planId, value] of byPlan) {+ const key = JSON.stringify([...value]);+ const cached = doneAtCache.current.get(planId);+ next.set(planId, cached && cached.key === key ? cached : { key, value });+ }+ doneAtCache.current = next;+ return next;+ }, [realMessages, stepNumbers]);++ const openPlan = group ? openBotGroupPlan({ openPlan: group.openPlan, plans }) : null;+ const runningStep = runningBotGroupPlanStep(openPlan);+ const speakers = useMemo<BotGroupLiveSpeaker[]>(() => (running && group+ ? group.round.speakers.flatMap((speaker) => {+ const member = memberById.get(speaker.botId);+ return member ? [{ member, displayName: botGroupMemberDisplayName(member), sessionId: speaker.sessionId, activity: speaker.activity }] : [];+ })+ : []), [running, group, memberById]);+ const stepSpeaker = runningStep+ ? speakers.find((speaker) => speaker.activity === 'step' && speaker.member.botId === runningStep.step.botId)+ : undefined;+ const stepLive = useAgentIslandActivity(stepSpeaker?.sessionId ?? '');+ const planRunningSince = runningStep ? stepLive?.startedAtMs ?? runningStep.plan.updatedAt : null;+const resetDrag = () => {dragCounterRef.current = 0;setDragOver(false);@@@ -1164,9 -1015,9 +1175,7 @@@dragOver={dragOver}quote={quoteDraft ? { view: quoteDraft, display: resolveBotGroupQuote(quoteDraft, quoteSources) } : null}onQuoteChange={setQuoteDraft}- onSendStart={onSendStart}- onSendSettled={onSendSettled}- onSent={onSent}- onSending={() => {- stickToBottomRef.current = true;- }}++ onSending={onSending}/>}{group.migrationPending && <p role="status" className="px-4 py-2 text-13 text-[var(--text-secondary)]">{t('bots.groupChat.migrationPending')}</p>}{/* Whole-page drop hint, as over a task's chat area; the card repeats it. */}diff --cc apps/desktop/src/renderer/features/bots/BotGroupComposer.tsxindex 18847088b0,303606862a..f5ff0237b9--- a/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx@@@ -17,18 -22,8 +17,18 @@@** 附件(§3.1)与普通聊天同一套:托盘状态来自页面持有的 `useAttachments`(整页拖入也能* 加),缩略图与拒收提示复用 ComposerAttachments;「+」→「添加文件、图片或视频…」、粘贴- * 文件或截图都进托盘。有附件时可以不写字。发送前烧录图片标注,发出去之后才从托盘移走- * 这一批;没发出去就原样留着。- * 文件或截图都进托盘。有附件时可以不写字。发送时这一批随消息离开托盘- * (不删除文件),发件箱提交前烧录图片标注;没发出去就随消息放回。++ * 文件或截图都进托盘。有附件时可以不写字。发送即交给群聊发件箱,托盘马上空出;发件箱++ * 负责标注烧录、顺序提交、失败后的原样恢复和重试。+ *+ * 草稿随群持久(与普通任务一样存进 composerDraftStore,附件已经在同一个键下):切走再回来、+ * 分享选择时输入框暂时卸载,文字都还在;群被删除时随草稿一起丢弃。+ *- * 乐观发送:按下发送的那一刻 `onSendStart` 交出这条消息的本地副本(页面立刻插进时间线),- * main 答复后 `onSendSettled` 带回结果(成功带 messageId,失败页面撤掉副本、草稿放回)。++ * 主群的乐观发送由 botGroupOutbox 统一管理;话题仍用 `onSendStart` / `onSendSettled`++ * 把本地副本与回执交给话题时间线。+ *+ * 话题模式(`mode="thread"`):同一个输入框用于话题回复——没有「+」菜单(不能安排分工;+ * Chat Server 的话题回复不带附件)、没有引用回复,发送键是「发送回复」,失败原因写在输入框+ * 上方;同一段文字、按当次成员解析出的点名目标也不变时,重发沿用同一个 clientId 和点名。*/import {useEffect,@@@ -51,16 -46,8 +51,15 @@@ importDropdownMenuTrigger,} from '@/components/ui/dropdown-menu';import { Tip } from '@/components/ui/tooltip';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';import { MENU_ITEM_CLASS } from '@/features/cc-agent/sidebar/menuStyles';import type { UseAttachmentsReturn } from '@/hooks/useAttachments';- import { isAnnotationBurnInError, materializeAnnotatedAttachmentsForSend } from '@/lib/annotationBurnIn';+import {+ captureDraftDiscardToken,+ getDraft,+ isDraftDiscardTokenCurrent,+ saveDraft,+} from '@/lib/composerDraftStore';import type { AttachedFile } from '@/lib/fileTypes';import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';@@@ -75,40 -70,16 +74,39 @@@ importkeepBotGroupComposerInputFocus,useRefitBotGroupComposerInputOnResize,} from './botGroupComposerChrome';-import { botGroupAttachmentSignature } from './botGroupAttachments';-import { botGroupSendSignature, enqueueBotGroupSend, registerBotGroupComposer } from './botGroupOutbox';import {+ BOT_GROUP_ATTACHMENTS_MAX,+ BOT_GROUP_MESSAGE_MAX_CHARS,+ type BotGroupAttachment,+ type BotGroupMemberView,+ type BotGroupMention,+ type BotGroupQuoteDisplay,+ type BotGroupQuoteView,+ type ChatServerResult,+} from '../../../shared/botGroupChat';+import { BotGroupQuotePreview } from './BotGroupQuote';+import {- botGroupAttachmentPreview,+ botGroupAttachmentSignature,+ botGroupDraftDoc,+ botGroupDraftText,- toBotGroupAttachmentInputs,+} from './botGroupAttachments';+import { chatErrorKey } from './chatError';+import {+ botGroupErrorKey,isActiveBotGroupMember,isBotGroupDivisionBlocked,type BotGroupComposerPlanState,} from './botGroupPresentation';import { botGroupApi } from './botGroupStore';++import { botGroupSendSignature, enqueueBotGroupSend, registerBotGroupComposer } from './botGroupOutbox';import { useBotGroupMentionPicker } from './useBotGroupMentionPicker';+/** 话题 replies also accept the Chat Server's own 「everyone」 spellings. */+const THREAD_ALL_ALIASES = ['所有人', 'all', 'everyone'] as const;++const sameBotGroupMentions = (a: BotGroupMention, b: BotGroupMention) =>+ a.all === b.all && a.botIds.length === b.botIds.length && a.botIds.every((botId, index) => botId === b.botIds[index]);+function isComposingKey(event: KeyboardEvent): boolean {return event.nativeEvent.isComposing || event.keyCode === 229;}@@@ -175,48 -117,29 +173,54 @@@ export function BotGroupComposer(dragOver = false,quote = null,onQuoteChange,+ sendReply,+ onSendStart,+ onSendSettled,+ onSent,+ onSending,}: {groupId: string;+ /** `thread`: a 话题's reply box (no 「+」 menu, attachments or quotes). */+ mode?: 'group' | 'thread';+ /** Where the unsent text is kept (the group's attachment scope, or the 话题's own key). */+ draftKey: string;members: readonly BotGroupMemberView[];running: boolean;+ /** Archived group: nothing can be sent. */+ disabled?: boolean;/** The group's open plan, for placeholders and the 「安排分工」 gate. */planState?: BotGroupComposerPlanState | null;- attachments: BotGroupComposerAttachments;+ attachments?: BotGroupComposerAttachments;/** Scope for writing annotated images before send (see botGroupAttachmentScope). */- attachmentScope: string;+ attachmentScope?: string;/** Files are being dragged over the page: the card shows the same drop hint as a task's. */dragOver?: boolean;/** 引用回复 waiting to go with the next message, and how its original reads right now. */quote?: { view: BotGroupQuoteView; display: BotGroupQuoteDisplay } | null;onQuoteChange?: (quote: BotGroupQuoteView | null) => void;- /** Called when a message enters the outbox, so the view can follow it to the bottom. */- onSending: () => void;+ /** Thread mode: posts the reply. */+ sendReply?: (input: { text: string; clientId: string; mentions: BotGroupMention }) => Promise<ChatServerResult<{ messageId: string }>>;+ /** The message is on its way: show its local copy now. */+ onSendStart?: (message: BotGroupOutgoingMessage) => void;+ /** Main answered (or the send failed before reaching it). */+ onSendSettled?: (clientId: string, outcome: BotGroupSendOutcome) => void;+ /** Called after main accepted the message, so the view can re-read at once. */+ onSent?: () => void;++ /** Main-group send was queued; keep the timeline at the bottom. */++ onSending?: () => void;}) {const { t } = useTranslation();- const [text, setText] = useState('');+ const thread = mode === 'thread';+ const [text, setText] = useState(() => botGroupDraftText(getDraft(draftKey)?.text));+ const [error, setError] = useState('');const [stopping, setStopping] = useState(false);- /** A send is in flight: its attachments stay in the tray but cannot change. */++ /** Thread send in flight; group sends are owned by the outbox. */+ const [sending, setSending] = useState(false);/** 「分工」 tag from 「+」→「安排分工」: this message goes to the organizer for a plan. */const [division, setDivision] = useState(false);++ const divisionRef = useRef(division);++ divisionRef.current = division;++ const groupAttemptRef = useRef<{ clientId: string; signature: string } | null>(null);const [menuOpen, setMenuOpen] = useState(false);const textareaRef = useRef<HTMLTextAreaElement>(null);const fileInputRef = useRef<HTMLInputElement>(null);@@@ -242,20 -152,11 +246,16 @@@quoteRef.current = quote?.view ?? null;const quotedMessageId = quote?.view.messageId ?? null;const focusInputOnMenuCloseRef = useRef(false);+ const sendingRef = useRef(false);const stoppingRef = useRef(false);- /** Idempotency key for the text, targets and attachments currently being (re)sent. */- const divisionRef = useRef(division);- divisionRef.current = division;- /** The failed send last put back into the input: an unchanged resend reuses its clientId. */- const attemptRef = useRef<{ clientId: string; signature: string } | null>(null);++ /** Thread retry identity: text and targets resolved against the original roster. */+ const attemptRef = useRef<{+ text: string;+ clientId: string;- division: boolean;- attachments: string;- mentionSignature: string;- quoteId: string | null;+ /** 话题 replies keep the targets resolved on the first attempt, with the roster of that moment. */+ mentions?: BotGroupMention;+ roster?: readonly BotGroupMemberView[];+ } | null>(null);const activeMembers = useMemo(() => members.filter(isActiveBotGroupMember), [members]);@@@ -300,158 -183,90 +300,140 @@@}, [text]);useRefitBotGroupComposerInputOnResize(textareaRef);+ /**+ * 话题 reply: a retry reuses the attempt only for the same text and the same targets+ * (bot-group-chat.md). Targets are re-resolved against the attempt's own roster: a roster+ * refresh alone changes nothing and the host still rejects a departed target; re-picking+ * someone else gets a new clientId.+ */+ const sendThreadReply = async () => {+ if (!canSend || sendingRef.current || !sendReply) return;+ const previous = attemptRef.current;+ const attempt =+ previous?.mentions && previous.roster && previous.text === trimmed+ && sameBotGroupMentions(mention.resolve(text, previous.roster), previous.mentions)+ ? previous+ : {- text: trimmed, clientId: crypto.randomUUID(), division: false, attachments: '', mentionSignature: '', quoteId: null,++ text: trimmed, clientId: crypto.randomUUID(),+ mentions: mention.resolve(text), roster: members,+ };+ attemptRef.current = attempt;+ const draft = text;+ const mentions = attempt.mentions!;+ const tracked = mention.tracked;+ sendingRef.current = true;+ setSending(true);+ setError('');+ setText('');+ mention.reset();+ onSendStart?.({ clientId: attempt.clientId, text: attempt.text, mentions, attachments: [], quote: null });+ const owner = getDataOwnerGeneration();+ const fail = (message: string) => {+ onSendSettled?.(attempt.clientId, { ok: false });+ if (!textRef.current) mention.setTracked(tracked);+ setText((current) => (current ? current : draft));+ setError(message);+ };+ try {+ const result = await sendReply({ text: attempt.text, clientId: attempt.clientId, mentions });+ if (!isDataOwnerGenerationCurrent(owner)) return;+ if (!result.ok) { fail(t(chatErrorKey(result.errorCode))); return; }+ attemptRef.current = null;+ onSendSettled?.(attempt.clientId, { ok: true, messageId: result.messageId });+ onSent?.();+ } catch {+ if (isDataOwnerGenerationCurrent(owner)) fail(t('bots.groupChat.server.requestFailed'));+ } finally {+ sendingRef.current = false;+ setSending(false);+ }+ };+- const send = async () => {- if (thread) { await sendThreadReply(); return; }- if (!canSend || sendingRef.current) return;- const api = botGroupApi();- if (!api) {+ // A message that did not go out comes back only into an empty input: never over new+ // text, a new tag or files added meanwhile. Pressing send again reuses its clientId.+ // Registered once per group (mount / group change): re-registering on every render would+ // pull a failed message back in the moment the user clears the input.+ const restoreAttachmentsRef = useRef(attachmentState.restoreFiles);+ restoreAttachmentsRef.current = attachmentState.restoreFiles;+ const tRef = useRef(t);+ tRef.current = t;+ const onQuoteChangeRef = useRef(onQuoteChange);+ onQuoteChangeRef.current = onQuoteChange;+ useEffect(- () =>++ () => thread ? undefined :+ registerBotGroupComposer(groupId, {+ restore: (entry) => {+ if (textRef.current || attachmentsRef.current.length > 0 || divisionRef.current) return false;- attemptRef.current = { clientId: entry.input.clientId, signature: entry.signature };++ groupAttemptRef.current = { clientId: entry.input.clientId, signature: entry.signature };+ textRef.current = entry.draft;+ setText(entry.draft);+ mention.setTracked([...entry.tracked]);+ const restoredDivision = entry.input.division === true;+ divisionRef.current = restoredDivision;+ if (restoredDivision) setDivision(true);+ // A quote picked meanwhile wins.+ if (entry.quote && !quoteRef.current) {+ quoteRef.current = entry.quote;+ onQuoteChangeRef.current?.(entry.quote);+ }+ if (entry.files.length > 0) attachmentsRef.current = restoreAttachmentsRef.current(entry.files);+ return true;+ },+ notifyFailed: (errorKey) => toast.error(tRef.current(errorKey)),+ }),- [groupId],++ [groupId, thread],+ );++ const send = () => {++ if (thread) { void sendThreadReply(); return; }+ // A second Enter before the cleared input has rendered must not send the same draft twice.+ if (!canSend || textRef.current !== text || attachmentsRef.current !== attachmentState.attachments) return;+ if (!botGroupApi()) {toast.error(t('bots.groupChat.composer.sendFailed'));return;}const files: readonly AttachedFile[] = attachmentState.attachments;- const signature = botGroupAttachmentSignature(files);- // The tag changes what main does with the text, so it is part of the idempotency key;- // so are the attachments that go with it.const mentions = mention.resolve(text);const tracked = mention.tracked;- const mentionSignature = JSON.stringify([mentions.all, mentions.botIds]);+ // Every field main gets is part of the attempt's identity (the tag changes what main does+ // with the text, the quote is part of the message), and so are the attachments that go with it.const sentQuote = quoteRef.current;- const quoteId = sentQuote?.messageId ?? null;- const attempt =- attemptRef.current?.text === trimmed &&- attemptRef.current.division === division &&- attemptRef.current.attachments === signature &&- attemptRef.current.mentionSignature === mentionSignature &&- attemptRef.current.quoteId === quoteId- ? attemptRef.current- : { text: trimmed, clientId: crypto.randomUUID(), division, attachments: signature, mentionSignature, quoteId };- attemptRef.current = attempt;- const draft = text;- sendingRef.current = true;- setSending(true);- // Clear at once like any chat; a failed send puts the draft back if the- // user has not started typing something else meanwhile. Attachments stay in- // the tray until main has them.- setText('');- mention.reset();- setDivision(false);- if (sentQuote) onQuoteChange?.(null);- onSendStart?.({- clientId: attempt.clientId,- text: attempt.text,+ const fields = {+ groupId,+ text: trimmed,mentions,- attachments: files.map(botGroupAttachmentPreview),+ ...(division ? { division: true } : {}),+ ...(sentQuote ? { quote: { messageId: sentQuote.messageId } } : {}),+ };+ const signature = botGroupSendSignature({ ...fields, clientId: '' }, botGroupAttachmentSignature(files));- const clientId = attemptRef.current?.signature === signature ? attemptRef.current.clientId : crypto.randomUUID();++ const clientId = groupAttemptRef.current?.signature === signature ? groupAttemptRef.current.clientId : crypto.randomUUID();+ // The outbox owns this attempt now; a failure hands it back through `restore`.- attemptRef.current = null;++ groupAttemptRef.current = null;+ enqueueBotGroupSend({+ input: { ...fields, clientId },+ signature,+ draft: text,+ tracked,quote: sentQuote,+ files,+ attachmentScope,});- const owner = getDataOwnerGeneration();- const restore = (keepQuote = true) => {- onSendSettled?.(attempt.clientId, { ok: false });- // The tag and the quote come back only with their own draft, never onto newly typed- // text; a quote picked meanwhile wins, and an unavailable original is not put back.- if (!textRef.current) {- if (attempt.division) setDivision(true);- mention.setTracked(tracked);- if (keepQuote && sentQuote && !quoteRef.current) onQuoteChange?.(sentQuote);- }- setText((current) => (current ? current : draft));- };- try {- // Drawn annotations are burned in first, as in a task; a failure keeps everything for a retry.- const prepared =- files.length > 0- ? ((await materializeAnnotatedAttachmentsForSend(files, attachmentScope, { burnFailure: 'abort' })) ?? [])- : [];- const result = await api.sendBotGroupMessage({- groupId,- text: attempt.text,- mentions,- clientId: attempt.clientId,- ...(attempt.division ? { division: true } : {}),- ...(sentQuote ? { quote: { messageId: sentQuote.messageId } } : {}),- ...(prepared.length > 0 ? { attachments: toBotGroupAttachmentInputs(prepared) } : {}),- });- if (!isDataOwnerGenerationCurrent(owner)) return;- if (!result.ok) {- restore(result.errorCode !== 'QUOTE_UNAVAILABLE');- toast.error(- t(- result.errorCode === 'INVALID_PARAMS' && prepared.length > 0- ? 'bots.groupChat.composer.attachmentsFailed'- : botGroupErrorKey(result.errorCode, 'bots.groupChat.composer.sendFailed'),- ),- );- return;- }- attemptRef.current = null;- if (files.length > 0) {- // Main now holds these files; take only this batch out of the tray (never delete- // them) and keep anything added while the message was on its way.- const sentIds = new Set(files.map((file) => file.id));- const remaining = attachmentsRef.current.filter((file) => !sentIds.has(file.id));- attachmentState.clearFiles();- attachmentState.restoreFiles(remaining);- }- onSendSettled?.(attempt.clientId, { ok: true, messageId: result.messageId });- onSent?.();- } catch (error) {- if (!isDataOwnerGenerationCurrent(owner)) return;- restore();- toast.error(- t(isAnnotationBurnInError(error) ? 'chat.media.annotateBurnFailedNotSent' : 'bots.groupChat.composer.sendFailed'),- );- } finally {- sendingRef.current = false;- setSending(false);+ // Clear at once like any chat, so the next message can be written while this one+ // goes out. The batch leaves the tray without deleting its files: the message has them.+ textRef.current = '';+ setText('');+ mention.reset();+ setDivision(false);+ divisionRef.current = false;+ if (sentQuote) {+ quoteRef.current = null;+ onQuoteChange?.(null);+ }+ if (files.length > 0) {+ attachmentState.clearFiles();+ attachmentsRef.current = [];}- onSending();++ onSending?.();};/** Files copied in a file manager attach by path; a screenshot or copied image attaches as an image. */diff --cc apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsxindex 186b3fa641,0000000000..c528e1e275mode 100644,000000..100644--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx@@@ -1,428 -1,0 +1,483 @@@+/**+ * 群聊时间线的一行(主时间线与话题面板共用),Telegram / Slack 式的紧凑排版:+ *+ * - 自己的消息靠右、浅色气泡;其他人(伙伴与别的人)一律靠左平铺:28px 头像 + 名字+ * (text-13)+ 时刻(text-11),正文在下。同一作者五分钟内的连续消息合并:后续行不再带+ * 头像和名字,时刻只在悬停时出现在左侧槽位。+ * - 引用块在正文上方,表情回应在正文下方;消息操作栏(复制、分享、引用回复、话题、表情、+ * 时间)悬停时浮在右上角,键盘聚焦与触屏时常显。+ * - @ 点名在所有消息里都高亮:正文仍交给 MarkdownRenderer,高亮走 CSS Custom Highlight+ * (不改 Markdown 的 DOM,也就不会和 React 抢节点)。+ * - 轮次结束、分工结束与系统提示是居中的一行小字。+ *+ * 行用 `memo` 包住:父组件只在这条消息(或它的引用、安排快照、高亮状态)真的变了时才会+ * 让它重绘;回调一律是父组件的稳定引用,按消息 id 调用。+ */- import { memo, useLayoutEffect, useRef, type ReactNode } from 'react';++import { memo, useEffect, useState, useLayoutEffect, useRef, type ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { CircleAlert, RefreshCcw } from 'lucide-react';++import { toast } from '@/lib/toast';++import { editBotGroupSend, retryBotGroupSend, type BotGroupOutboxEntry } from './botGroupOutbox';++import { formatBotTimelineClock, formatBotTimelineDate } from '@cindy/maker-shared/botTimeline';+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';+import { ShareMessageCheckbox } from '@/components/chat/ShareMessageCheckbox';+import { Button } from '@/components/ui/button';+import { SHARE_MESSAGE_ATTR, SHARE_SESSION_ATTR } from '@/lib/shareConversationImage';+import { cn } from '@/lib/utils';+import type {+ BotGroupMemberView,+ BotGroupPlanStepView,+ BotGroupPlanView,+ BotGroupQuoteDisplay,+ BotGroupQuoteView,+} from '../../../shared/botGroupChat';+import { isBotGroupRuntimeFailureCode } from '../../../shared/botGroupChat';+import { BotAvatar } from './BotAvatar';+import { splitBotGroupMentionSegments } from './botGroupMentions';+import { botGroupNoticeKey } from './botGroupPresentation';+import {+ BotGroupHandoffFiles,+ BotGroupOrganizerTag,+ BotGroupPlanCard,+ BotGroupPlanEndDivider,+ type BotGroupPlanCardAction,+} from './BotGroupPlan';+import { BotGroupMessageAttachments } from './BotGroupMessageAttachments';+import { BotGroupQuoteBlock } from './BotGroupQuote';+import { BotGroupRuntimeFailureNotice } from './BotGroupRuntimeFailureNotice';+import { BotGroupTaskCard } from './BotGroupTaskCard';+import type { BotGroupTimelineMessage } from './BotGroupTimelineModel';+import { ChatMessageHoverActions, ChatMessageReactions } from './ChatServerControls';++/** Group chat body: one step smaller than a task's reading text, Slack-dense. */+export const BOT_GROUP_BODY_CLASS = 'text-14 font-normal leading-relaxed';++// ---- @ mention highlight ----------------------------------------------------------------++const MENTION_HIGHLIGHT = 'bot-group-mention';+const mentionRanges = new Map<object, Range[]>();+let highlightSyncQueued = false;+let highlightStyleInstalled = false;++type HighlightRegistry = { set: (name: string, value: unknown) => void; delete: (name: string) => void };+function highlightApi(): { registry: HighlightRegistry; Highlight: new (...ranges: Range[]) => unknown } | null {+ const registry = (globalThis as { CSS?: { highlights?: HighlightRegistry } }).CSS?.highlights;+ const Highlight = (globalThis as { Highlight?: new (...ranges: Range[]) => unknown }).Highlight;+ return registry && typeof Highlight === 'function' ? { registry, Highlight } : null;+}++function installHighlightStyle(): void {+ if (highlightStyleInstalled || typeof document === 'undefined') return;+ highlightStyleInstalled = true;+ const style = document.createElement('style');+ style.dataset.botGroupMention = '';+ // Same chip colors as the composer's mention chip; both modes follow the tokens.+ style.textContent = `::highlight(${MENTION_HIGHLIGHT}) { background-color: var(--surface-chip); color: var(--text-primary); }`;+ document.head.append(style);+}++function syncMentionHighlight(): void {+ if (highlightSyncQueued) return;+ highlightSyncQueued = true;+ queueMicrotask(() => {+ highlightSyncQueued = false;+ const api = highlightApi();+ if (!api) return;+ const ranges = [...mentionRanges.values()].flat();+ if (ranges.length === 0) api.registry.delete(MENTION_HIGHLIGHT);+ else api.registry.set(MENTION_HIGHLIGHT, new api.Highlight(...ranges));+ });+}++function collectMentionRanges(root: HTMLElement, labels: readonly string[]): Range[] {+ const ranges: Range[] = [];+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ for (let node = walker.nextNode() as Text | null; node; node = walker.nextNode() as Text | null) {+ if (!node.data.includes('@') || node.parentElement?.closest('pre, code')) continue;+ let offset = 0;+ for (const segment of splitBotGroupMentionSegments(node.data, labels)) {+ if (segment.mention) {+ const range = document.createRange();+ range.setStart(node, offset);+ range.setEnd(node, offset + segment.text.length);+ ranges.push(range);+ }+ offset += segment.text.length;+ }+ }+ return ranges;+}++/** Message text as Markdown, with `@名字` of known members highlighted like a chip. */+function BotGroupMessageText({ content, mentionLabels }: { content: string; mentionLabels: readonly string[] }) {+ const ref = useRef<HTMLDivElement>(null);+ const labelsKey = mentionLabels.join('\u0000');+ useLayoutEffect(() => {+ const root = ref.current;+ if (!root || !content.includes('@') || !highlightApi()) return;+ installHighlightStyle();+ const owner = {};+ const refresh = () => {+ mentionRanges.set(owner, collectMentionRanges(root, mentionLabels));+ syncMentionHighlight();+ };+ refresh();+ // Markdown may finish later (code highlighting, lazy blocks); follow its DOM.+ const observer = typeof MutationObserver === 'undefined' ? null : new MutationObserver(refresh);+ observer?.observe(root, { childList: true, subtree: true, characterData: true });+ return () => {+ observer?.disconnect();+ mentionRanges.delete(owner);+ syncMentionHighlight();+ };+ // labelsKey stands in for the label array.+ }, [content, labelsKey]);+ return (+ <div ref={ref} className="min-w-0 break-words">+ <MarkdownRenderer workingDir="" content={content} allowPrivilegedLinks={false} />+ </div>+ );+}++// ---- Pieces ----------------------------------------------------------------------------++/** Quiet pill after an author name (负责人, 第 k 步, 某某的主人). */+export function BotGroupNameTag({ children }: { children: ReactNode }) {+ return (+ <span className="inline-flex min-h-[18px] max-w-[12rem] shrink-0 select-none items-center truncate rounded-full bg-[var(--surface-chip)] px-1.5 py-px text-11 font-medium leading-tight text-[var(--text-secondary)]">+ {children}+ </span>+ );+}++/** One line per local day; it sticks to the top while that day scrolls by. */+export function BotGroupDateDivider({ timestamp, locale }: { timestamp: number; locale: string }) {+ return (+ <div data-testid="bot-group-date-divider" className="sticky top-1 z-[5] mt-4 flex select-none justify-center first:mt-0">+ <span className="rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-2.5 py-0.5 text-11 leading-4 text-[var(--text-tertiary)]">+ {formatBotTimelineDate(timestamp, locale)}+ </span>+ </div>+ );+}++// ---- The row ---------------------------------------------------------------------------++export interface BotGroupTimelineItemProps {+ message: BotGroupTimelineMessage;+ /** Same author as the row above within five minutes: no avatar or name. */+ continued: boolean;+ /** Author name as this reader sees it (`伙伴名 (主人昵称)` where it applies). */+ authorName: string;+ /** Avatar identity of the author (the organizer on a 安排卡). */+ avatar?: { name: string; avatar: string | null; avatarUrl?: string | null; avatarColor: string | null };+ /** Bots a human author brought into the group: 「某某的主人」. */+ ownerOf?: string;+ /** 「第 k 步」 on a step hand-off. */+ stepNumber?: number;+ members: readonly BotGroupMemberView[];+ mentionLabels: readonly string[];+ locale: string;+ shareScope: string;+ sharing: boolean;+ /** Server group id: reactions and the toolbar's reaction picker. */+ reactionGroupId?: string;+ /** The message's reaction version (`messageReactionRevision`): who reacted is re-read when it moves. */+ reactionRevision?: string;+ quoteDisplay?: BotGroupQuoteDisplay;+ onLocateQuote?: (quote: BotGroupQuoteView) => void;+ onQuote?: (messageId: string) => void;+ onOpenThread?: (messageId: string) => void;+ /** This client changed the message (a reaction): the timeline refreshes its copy. */+ onChanged: (messageId: string) => void;+ highlighted?: boolean;+ /** Focusable only as a jump target, so a click elsewhere keeps its usual focus. */+ focusable?: boolean;+ /** Arrived while the reader was watching: fade in (opacity only). */+ entering?: boolean;+ // Round and plan pieces; the Thread panel leaves them out.+ canContinue?: boolean;+ continuing?: boolean;+ onContinue?: () => void;+ plan?: BotGroupPlanView;+ planActionable?: boolean;+ planReassignable?: boolean;+ planPending?: BotGroupPlanCardAction | null;+ /** Live start of the plan's running step (its Session's turn), for the elapsed time. */+ planRunningSince?: number | null;+ /** Finish time of each done step (1-based), read off its hand-off message. */+ planDoneAt?: ReadonlyMap<number, number>;+ onPlanAction?: (action: 'start' | 'dismiss', planId: string) => void;+ onEditStep?: (planId: string, step: BotGroupPlanStepView, action: 'reassign' | 'remove', botId?: string) => void;+}++function Row({ message, highlighted, focusable, entering, block, children }: {+ message: BotGroupTimelineMessage; highlighted?: boolean; focusable?: boolean; entering?: boolean;+ /** Space above: a new author block, a merged line, or a compact system line. */+ block: 'author' | 'continued' | 'system';+ children: ReactNode;+}) {+ return (+ <div+ data-bot-group-message-id={message.id}+ tabIndex={focusable ? -1 : undefined}+ className={cn(+ 'rounded-lg outline-none transition-colors first:mt-0',+ block === 'continued' ? 'mt-0.5' : block === 'author' ? 'mt-3.5' : 'mt-3',+ entering && 'animate-fade-in motion-reduce:animate-none',+ highlighted && 'bg-[hsl(var(--search-match-bg))] ring-1 ring-[var(--border-default)]',+ )}+ >+ {children}+ </div>+ );+}++function SystemLine({ children, testId }: { children: ReactNode; testId?: string }) {+ return (+ <div data-testid={testId} className="flex select-none items-center gap-3 text-12 text-[var(--text-tertiary)]">+ <span aria-hidden className="h-px min-w-6 flex-1 bg-[var(--border-default)]" />+ {children}+ <span aria-hidden className="h-px min-w-6 flex-1 bg-[var(--border-default)]" />+ </div>+ );+}++/** A task card is live only for a member of this group whose teammate is mine; unknown authors are snapshots. */+export function botGroupTaskOwned(authorBotId: string | null, members: readonly BotGroupMemberView[]): boolean {+ const author = authorBotId ? members.find((member) => member.botId === authorBotId) : undefined;+ return author !== undefined && author.isOwned !== false;+}++function BotGroupTimelineItemImpl(props: BotGroupTimelineItemProps) {+ const { t } = useTranslation();+ const { message, continued, authorName, members, mentionLabels, locale, shareScope, sharing } = props;+ const rowProps = { message, highlighted: props.highlighted, focusable: props.focusable, entering: props.entering };++ if (message.kind === 'round-end') {+ return (+ <Row {...rowProps} block="system">+ <SystemLine>+ <span>{t('bots.groupChat.timeline.roundEnded')}</span>+ {props.canContinue && props.onContinue ? (+ <Button variant="secondary" tone="quiet" size="sm" compact type="button" loading={props.continuing} onClick={props.onContinue}>+ {t('bots.groupChat.timeline.continue')}+ </Button>+ ) : null}+ </SystemLine>+ </Row>+ );+ }+ if (message.kind === 'plan-end') {+ return (+ <Row {...rowProps} block="system">+ <BotGroupPlanEndDivider stepCount={props.plan ? props.plan.steps.length : null} />+ </Row>+ );+ }+ if (message.kind === 'notice' || message.authorKind === 'system') {+ const name = message.authorName.trim() || authorName;+ if (isBotGroupRuntimeFailureCode(message.runtimeFailureCode)) {+ return (+ <Row {...rowProps} block="system">+ <BotGroupRuntimeFailureNotice name={name} code={message.runtimeFailureCode} />+ </Row>+ );+ }+ const key = botGroupNoticeKey(message.noticeCode, message.planId !== null);+ return (+ <Row {...rowProps} block="system">+ <p className="select-none text-center text-12 leading-5 text-[var(--text-tertiary)]">{key ? t(key, { name }) : message.content}</p>+ </Row>+ );+ }++ const shareable = message.kind === 'message' && !message.pending;+ const shareAttrs = shareable ? { [SHARE_SESSION_ATTR]: shareScope, [SHARE_MESSAGE_ATTR]: message.id } : {};+ const hasText = message.content.trim().length > 0;+ const quote = props.quoteDisplay ? (+ <BotGroupQuoteBlock+ display={props.quoteDisplay}+ onLocate={props.onLocateQuote && message.quote ? () => props.onLocateQuote!(message.quote!) : undefined}+ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}+ />+ ) : null;+ const actions = shareable ? (+ <ChatMessageHoverActions+ groupId={props.reactionGroupId}+ shareScope={shareScope}+ message={message}+ align={message.authorKind === 'user' && message.isSelf !== false ? 'right' : 'left'}+ onQuote={props.onQuote ? () => props.onQuote!(message.id) : undefined}+ onReply={props.onOpenThread ? () => props.onOpenThread!(message.id) : undefined}+ onChanged={props.onChanged}+ />+ ) : null;++ if (message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false) {+ return (+ <Row {...rowProps} block={continued ? 'continued' : 'author'}>+ <article+ {...shareAttrs}- aria-busy={message.pending ? true : undefined}++ data-testid={message.outbox ? "bot-group-outbox" : undefined}++ data-status={message.outbox?.status}++ aria-busy={message.pending && message.outbox?.status !== 'failed' ? true : undefined}+ className={cn('group/message relative flex min-w-0 justify-end rounded-lg py-0.5', sharing && 'ml-10')}+ >+ {sharing && shareable ? <ShareMessageCheckbox clientId={message.id} /> : null}- <div className={cn('flex min-w-0 max-w-[78%] flex-col items-end gap-1.5 transition-opacity', message.pending && 'opacity-60')}>++ <div className={cn('flex min-w-0 max-w-[78%] flex-col items-end gap-1.5 transition-opacity', message.pending && message.outbox?.status !== 'failed' && 'opacity-60')}>+ {quote}+ <BotGroupMessageAttachments attachments={message.attachments ?? []} align="end" />+ {hasText ? (+ <div+ data-testid="bot-group-self-bubble"+ className={`max-w-full rounded-xl border border-[var(--msg-user-border)] bg-[var(--msg-user-bg)] px-3 py-1.5 text-[var(--msg-user-text)] ${BOT_GROUP_BODY_CLASS}`}+ >+ <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} />+ </div>+ ) : null}- {message.pending ? <span className="sr-only">{t('bots.groupChat.timeline.sending')}</span> : null}- <ChatMessageReactions groupId={props.reactionGroupId} message={message} members={members} reactionRevision={props.reactionRevision} align="right" onChanged={props.onChanged} />++ {message.outbox ? <BotGroupOutboxStatus entry={message.outbox} /> : null}++ {message.pending && !message.outbox ? <span className="sr-only">{t('bots.groupChat.timeline.sending')}</span> : null}++ {!message.pending ? <ChatMessageReactions groupId={props.reactionGroupId} message={message} members={members} reactionRevision={props.reactionRevision} align="right" onChanged={props.onChanged} /> : null}+ </div>+ {actions}+ </article>+ </Row>+ );+ }++ // A server plan is signed by its human creator; present the organizer without changing authorship.+ const isPlanCard = message.kind === 'plan';+ const timed = Number.isFinite(message.createdAt) && message.createdAt > 0;+ const clock = timed ? formatBotTimelineClock(message.createdAt, locale) : '';+ const dateTime = timed ? new Date(message.createdAt).toISOString() : undefined;+ return (+ <Row {...rowProps} block={continued ? 'continued' : 'author'}>+ <article+ {...shareAttrs}+ className={cn(+ 'group/message relative -mx-2 flex min-w-0 items-start gap-2.5 rounded-lg px-2 py-0.5 transition-colors hover:bg-[var(--surface-hover-soft)]',+ sharing && 'ml-8',+ )}+ >+ {sharing && shareable ? <ShareMessageCheckbox clientId={message.id} /> : null}+ <div className="flex w-7 shrink-0 justify-end">+ {continued ? (+ <time+ dateTime={dateTime}+ className="select-none pt-0.5 text-11 leading-5 tabular-nums text-[var(--text-tertiary)] opacity-0 group-hover/message:opacity-100"+ >+ {clock}+ </time>+ ) : (+ <BotAvatar bot={props.avatar ?? { name: authorName, avatar: null, avatarColor: null }} size="sm" />+ )}+ </div>+ <div className="flex min-w-0 flex-1 flex-col">+ {!continued ? (+ <span className="flex min-w-0 select-none items-baseline gap-1.5">+ <span className="min-w-0 truncate text-13 font-medium leading-5 text-[var(--text-primary)]">{authorName}</span>+ {isPlanCard ? <BotGroupOrganizerTag /> : null}+ {props.stepNumber ? <BotGroupNameTag>{t('bots.groupChat.timeline.stepTag', { count: props.stepNumber })}</BotGroupNameTag> : null}+ {props.ownerOf ? <BotGroupNameTag>{t('bots.groupChat.ownerOf', { name: props.ownerOf })}</BotGroupNameTag> : null}+ {timed ? (+ <time dateTime={dateTime} className="shrink-0 text-11 tabular-nums text-[var(--text-tertiary)]">+ {clock}+ </time>+ ) : null}+ </span>+ ) : null}+ {isPlanCard ? (+ <div className="mt-1">+ <BotGroupPlanCard+ plan={props.plan}+ members={members}+ actionable={props.planActionable ?? false}+ reassignable={props.planReassignable ?? false}+ pending={props.planPending ?? null}+ runningSince={props.planRunningSince ?? null}+ doneAt={props.planDoneAt}+ locale={locale}+ onStart={() => { if (message.planId) props.onPlanAction?.('start', message.planId); }}+ onDismiss={() => { if (message.planId) props.onPlanAction?.('dismiss', message.planId); }}+ onEditStep={(step, action, botId) => { if (message.planId) props.onEditStep?.(message.planId, step, action, botId); }}+ />+ </div>+ ) : (+ <div className="flex min-w-0 flex-col gap-1">+ {quote}+ {/* A task this teammate started from the group; mine is live where it runs, another owner's+ is a snapshot. An author no longer in the group is unknown: its task may run on another+ computer, so it stays a snapshot rather than a lookup on this one. */}+ {message.task ? (+ <BotGroupTaskCard task={message.task} owned={botGroupTaskOwned(message.authorBotId, members)}+ botId={message.authorBotId} />+ ) : null}+ {hasText ? (+ <div className={`min-w-0 text-[var(--msg-assistant-text)] ${BOT_GROUP_BODY_CLASS}`}>+ <BotGroupMessageText content={message.content} mentionLabels={mentionLabels} />+ </div>+ ) : null}+ <BotGroupMessageAttachments attachments={message.attachments ?? []} align="start" />+ <BotGroupHandoffFiles files={message.files ?? []} workDir={props.plan?.workDir ?? null} />+ <ChatMessageReactions groupId={props.reactionGroupId} message={message} members={members} reactionRevision={props.reactionRevision} onChanged={props.onChanged} />+ </div>+ )}+ </div>+ {actions}+ </article>+ </Row>+ );+}++export const BotGroupTimelineItem = memo(BotGroupTimelineItemImpl);++++/** Queue feedback shares the same message row, so receipts do not remount its content. */++function BotGroupOutboxStatus({ entry }: { entry: BotGroupOutboxEntry }) {++ const { t } = useTranslation();++ const sending = entry.status === 'sending';++ const [slow, setSlow] = useState(false);++ useEffect(() => {++ if (!sending) {++ setSlow(false);++ return;++ }++ const timer = window.setTimeout(() => setSlow(true), 600);++ return () => window.clearTimeout(timer);++ }, [sending]);++ return (++ <>++ {sending && slow ? (++ <p role="status" className="select-none text-12 leading-[1.33] text-[var(--text-tertiary)]">++ {t('bots.groupChat.outbox.sending')}++ </p>++ ) : null}++ {entry.status === 'failed' ? (++ <div role="alert" className="flex flex-wrap items-center justify-end gap-2">++ <span className="flex select-none items-center gap-1 text-12 leading-[1.33] text-[var(--text-danger)]">++ <CircleAlert size={13} aria-hidden className="shrink-0" />++ {t('bots.groupChat.outbox.failed')}++ </span>++ <Button++ variant="secondary"++ size="sm"++ compact++ type="button"++ onClick={() => {++ if (!editBotGroupSend(entry.input.groupId, entry.input.clientId)) toast.warning(t('bots.groupChat.outbox.editBlocked'));++ }}++ >++ {t('bots.groupChat.outbox.edit')}++ </Button>++ {entry.retryable !== false ? (++ <Button variant="secondary" size="sm" compact type="button" onClick={() => retryBotGroupSend(entry.input.groupId, entry.input.clientId)}>++ <RefreshCcw size={13} />++ {t('bots.retry')}++ </Button>++ ) : null}++ </div>++ ) : null}++ </>++ );++}diff --cc apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.tsindex 0e9c02ffa6,0000000000..d0cf347996mode 100644,000000..100644--- a/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts+++ b/apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts@@@ -1,362 -1,0 +1,363 @@@+/**+ * 群聊时间线的纯数据层(不挂 React,便于单测):+ *+ * - 推送刷新的增量合并:main 每次只回最新一页(BOT_GROUP_PAGE_SIZE),这里把它并进屏幕上+ * 已有的消息,而不是整页替换——被新消息挤出最新页的旧消息留在「更早」里,不会出现缺口或+ * 顶部跳动;最新页覆盖的序号区间内以 main 为准(编辑、删除、表情、话题数就地更新)。+ * - 引用稳定:内容没变的消息、安排沿用上一份对象,memo 过的消息行就不会重绘。+ * - 乐观发送:发出那一刻先插一条「发送中」的自己的消息,main 的详情里出现对应消息+ * (按 send 返回的 messageId,返回前按序号之后的同文自发消息)后撤掉。+ * - Telegram / Slack 式排版:同一作者五分钟内的连续消息合并(只首条带头像与名字),+ * 每个自然日一条日期分隔。+ * - 多人群的显示名「伙伴名 (主人昵称)」与人类成员的「某某的主人」小标。+ */+import { collectBotTimelineDateDividers, isSameBotTimelineDay } from '@cindy/maker-shared/botTimeline';+import type {+ BotGroupAttachment,+ BotGroupDetail,+ BotGroupMemberView,+ BotGroupMention,+ BotGroupMessageView,+ BotGroupPlanStepView,+ BotGroupPlanView,+ BotGroupQuoteView,+} from '../../../shared/botGroupChat';++import type { BotGroupOutboxEntry } from './botGroupOutbox';+import { mergeBotGroupMessages, mergeBotGroupPlans } from './botGroupPresentation';++/** A timeline row; `pending` marks the optimistic copy of a message still on its way. */- export type BotGroupTimelineMessage = BotGroupMessageView & { pending?: true };++export type BotGroupTimelineMessage = BotGroupMessageView & { pending?: true; outbox?: BotGroupOutboxEntry };++/** Consecutive messages by one author within this window share one header. */+export const BOT_GROUP_MERGE_WINDOW_MS = 5 * 60 * 1_000;++export interface BotGroupLoadedTimeline {+ group: BotGroupDetail;+ /** Messages on screen that the latest page no longer covers (paged in, or pushed out). */+ older: BotGroupMessageView[];+ olderPlans: BotGroupPlanView[];+ olderHasMore: boolean;+}++const signatures = new WeakMap<object, string>();+function signature(value: object): string {+ let cached = signatures.get(value);+ if (cached === undefined) {+ cached = JSON.stringify(value);+ signatures.set(value, cached);+ }+ return cached;+}++/**+ * `next` with every entry whose content equals the previous entry of the same id replaced by+ * that previous object; the previous array itself when nothing changed at all.+ */+export function stabilizeById<T extends { id: string }>(+ previous: readonly T[],+ next: readonly T[],+ /** More earlier copies to reuse (e.g. messages that moved between pages). */+ pool: readonly T[] = [],+): T[] {+ if (previous === next) return next as T[];+ const byId = new Map([...pool, ...previous].map((item) => [item.id, item]));+ let same = previous.length === next.length;+ const result = next.map((item, index) => {+ const old = byId.get(item.id);+ if (old && (old === item || signature(old) === signature(item))) {+ if (previous[index] !== old) same = false;+ return old;+ }+ same = false;+ return item;+ });+ return same ? (previous as T[]) : result;+}++/**+ * Merges a push refresh's latest page into the timeline on screen. Inside the page's range the+ * page wins; anything displayed below it stays (as `older`), so a message pushed out of the+ * newest page by new ones never disappears. A page that is the whole history drops the rest.+ */+export function mergeBotGroupLatestPage(+ previous: BotGroupLoadedTimeline,+ next: BotGroupDetail,+): BotGroupLoadedTimeline {+ const page = next.messages;+ const floor = page.reduce((min, message) => Math.min(min, message.sequence), Number.POSITIVE_INFINITY);+ const ceiling = previous.group.messages.reduce((max, message) => Math.max(max, message.sequence), Number.NEGATIVE_INFINITY);+ // More than a page arrived at once (e.g. while the window was in the background): the new page+ // does not reach the one on screen, and messages may sit between them. Keeping the old rows+ // would hide that gap for good, so start over from the new page, as on first load; 「查看更早」+ // then reads on from right below it.+ if (next.hasMoreBefore && page.length > 0 && previous.group.messages.length > 0 && floor > ceiling) {+ return {+ group: { ...next, messages: stabilizeById(previous.group.messages, page, previous.older),+ plans: stabilizeById(previous.group.plans, next.plans, previous.olderPlans) },+ older: [],+ olderPlans: [],+ olderHasMore: next.hasMoreBefore,+ };+ }+ // A page that says nothing comes before it is the whole recent history: whatever the last+ // latest page showed below it is gone. Pages opened through 「查看更早」 stay as they were;+ // their quoted originals are re-checked separately.+ const pushedOut = next.hasMoreBefore+ ? previous.group.messages.filter((message) => message.sequence < floor)+ : [];+ const older = pushedOut.length > 0+ ? stabilizeById(previous.older, mergeBotGroupMessages(previous.older, pushedOut))+ : previous.older;+ // The first rows moving down take over what the old latest page said about earlier history.+ const olderHasMore = pushedOut.length > 0 && previous.older.length === 0 ? previous.group.hasMoreBefore : previous.olderHasMore;+ const messages = stabilizeById(previous.group.messages, page, previous.older);+ const plans = stabilizeById(previous.group.plans, next.plans, previous.olderPlans);+ // Plans the pushed-out messages point at stay with them.+ const olderPlans = pushedOut.length > 0+ ? stabilizeById(previous.olderPlans, mergeBotGroupPlans(previous.olderPlans, previous.group.plans))+ : previous.olderPlans;+ // Nothing moved: hand back the same object so the page skips the render entirely.+ if (messages === previous.group.messages && plans === previous.group.plans && older === previous.older+ && olderPlans === previous.olderPlans+ && olderHasMore === previous.olderHasMore+ && signature({ ...next, messages: null, plans: null }) === signature({ ...previous.group, messages: null, plans: null })) {+ return previous;+ }+ return {+ group: { ...next, messages, plans },+ older,+ olderPlans,+ olderHasMore,+ };+}++// ---- Optimistic sends -------------------------------------------------------------------++export interface BotGroupPendingSend {+ clientId: string;+ text: string;+ mentions: BotGroupMention;+ attachments: BotGroupAttachment[];+ quote: BotGroupQuoteView | null;+ createdAt: number;+ /** Last real sequence on screen when it was sent; its echo comes after this. */+ afterSequence: number;+ /** Set once main accepted it. */+ messageId?: string;+}++export function pendingBotGroupMessageId(clientId: string): string {+ return `pending:${clientId}`;+}++/** The optimistic row for a send still on its way. */+export function pendingBotGroupMessage(send: BotGroupPendingSend): BotGroupTimelineMessage {+ return {+ id: pendingBotGroupMessageId(send.clientId),+ // Shown after every real row; never used for paging or failure reconciliation.+ sequence: Number.MAX_SAFE_INTEGER,+ kind: 'message',+ authorKind: 'user',+ isSelf: true,+ authorBotId: null,+ authorName: '',+ content: send.text,+ mentions: send.mentions,+ noticeCode: null,+ planId: null,+ files: [],+ attachments: send.attachments,+ ...(send.quote ? { quote: send.quote } : {}),+ createdAt: send.createdAt,+ pending: true,+ };+}++function isOwnMessage(message: BotGroupMessageView): boolean {+ return message.kind === 'message' && message.authorKind === 'user' && message.isSelf !== false;+}++const NO_MATCHES: ReadonlyMap<string, string> = new Map();++/**+ * Which pending sends have shown up, as clientId → message id. A send main accepted matches its+ * message id; before the answer it matches the first own message after it with the same text and+ * as many attachments (each message settles one send). `adopted` (real message id → the pending+ * row key that already took it) carries those settlements across renders, so a later send of the+ * same words never claims a message an earlier send already became.+ */+export function matchBotGroupPendingSends(+ pending: readonly BotGroupPendingSend[],+ displayed: readonly BotGroupMessageView[],+ adopted: ReadonlyMap<string, string> = NO_MATCHES,+): ReadonlyMap<string, string> {+ if (pending.length === 0) return NO_MATCHES;+ const ids = new Set(displayed.map((message) => message.id));+ const claimed = new Set<string>();+ const matches = new Map<string, string>();+ for (const send of pending) {+ if (send.messageId && ids.has(send.messageId)) {+ claimed.add(send.messageId);+ matches.set(send.clientId, send.messageId);+ }+ }+ for (const send of pending) {+ if (send.messageId) continue;+ const text = send.text.trim();+ const key = pendingBotGroupMessageId(send.clientId);+ const echo = displayed.find((message) => !claimed.has(message.id) && (adopted.get(message.id) ?? key) === key && isOwnMessage(message)+ && message.sequence > send.afterSequence && message.content.trim() === text+ && message.attachments.length === send.attachments.length);+ if (!echo) continue;+ claimed.add(echo.id);+ matches.set(send.clientId, echo.id);+ }+ return matches.size === 0 ? NO_MATCHES : matches;+}++/** Pending sends whose message has not shown up yet; the same array when nothing settled. */+export function settleBotGroupPendingSends<T extends BotGroupPendingSend>(+ pending: readonly T[],+ displayed: readonly BotGroupMessageView[],+): T[] {+ const matches = matchBotGroupPendingSends(pending, displayed);+ if (matches.size === 0) return pending as T[];+ return pending.filter((send) => !matches.has(send.clientId));+}++// ---- Layout ----------------------------------------------------------------------------++export interface BotGroupRowLayout {+ /** Same author as the row above, within the merge window: no avatar or name. */+ continued: boolean;+ /** First message of a local day: the date to show above it. */+ dateDivider: number | null;+}++function authorKey(message: BotGroupTimelineMessage): string | null {+ // Notices, dividers, plan cards and step hand-offs (which carry a step tag) always open a block.+ if (message.kind !== 'message' || message.authorKind === 'system' || message.planId) return null;+ if (isOwnMessage(message)) return 'self';+ return `${message.authorKind}:${message.authorBotId ?? ''}:${message.authorName}`;+}++export function layoutBotGroupTimeline(+ messages: readonly BotGroupTimelineMessage[],+): ReadonlyMap<string, BotGroupRowLayout> {+ const dividers = collectBotTimelineDateDividers(messages.map((message) => ({ clientId: message.id, createdAt: message.createdAt })));+ const layout = new Map<string, BotGroupRowLayout>();+ let previous: BotGroupTimelineMessage | null = null;+ for (const message of messages) {+ const dateDivider = dividers.get(message.id) ?? null;+ const key = authorKey(message);+ const continued = previous !== null && dateDivider === null && key !== null && key === authorKey(previous)+ && message.createdAt - previous.createdAt >= 0+ && message.createdAt - previous.createdAt < BOT_GROUP_MERGE_WINDOW_MS+ && isSameBotTimelineDay(previous.createdAt, message.createdAt);+ layout.set(message.id, { continued, dateDivider });+ previous = message;+ }+ return layout;+}++// ---- Names -----------------------------------------------------------------------------++type NamedMember = Pick<BotGroupMemberView, 'name' | 'ownerName' | 'isOwned' | 'actorKind'>;++function ownerSuffix(member: NamedMember): string | null {+ const owner = member.ownerName?.trim();+ return owner ? ` (${owner})` : null;+}++/** The member's own name without a 「 (主人昵称)」 suffix the host may already have added. */+export function botGroupMemberBaseName(member: NamedMember): string {+ const name = member.name.trim();+ const suffix = ownerSuffix(member);+ return suffix && name.endsWith(suffix) && name.length > suffix.length ? name.slice(0, -suffix.length) : name;+}++/**+ * 多人群里别人带来的伙伴显示为 `伙伴名 (主人昵称)`(bot-group-chat.md §10);自己的伙伴、+ * 人类成员与本地群照常显示名字。只用于展示,点名与身份仍按 id。+ */+export function botGroupMemberDisplayName(member: NamedMember): string {+ const suffix = ownerSuffix(member);+ if (suffix && member.isOwned === false && member.actorKind !== 'human') return `${botGroupMemberBaseName(member)}${suffix}`;+ return member.name.trim();+}++/** Names of the bots a human member brought into the group (for 「某某的主人」). */+export function botGroupOwnedBotNames(+ member: Pick<BotGroupMemberView, 'actorId' | 'actorKind'> | undefined,+ members: readonly BotGroupMemberView[],+): string[] {+ if (!member?.actorId || member.actorKind !== 'human') return [];+ return members+ .filter((candidate) => candidate.actorKind === 'bot' && candidate.ownerActorId === member.actorId)+ .map(botGroupMemberBaseName)+ .filter(Boolean);+}++// ---- Plans -----------------------------------------------------------------------------++export interface BotGroupRunningStep {+ plan: BotGroupPlanView;+ step: BotGroupPlanStepView;+ /** 1-based place in the plan, as shown to the user. */+ index: number;+ total: number;+}++/** The step of an open plan that is in progress right now. */+export function runningBotGroupPlanStep(plan: BotGroupPlanView | null): BotGroupRunningStep | null {+ if (!plan || plan.status !== 'running') return null;+ const index = plan.steps.findIndex((step) => step.status === 'running');+ if (index < 0) return null;+ return { plan, step: plan.steps[index]!, index: index + 1, total: plan.steps.length };+}++/**+ * 「第 k 步」 on a step's hand-off message. Where the plan names each step's latest hand-off, that+ * message gets its step exactly, and a hand-off a redo replaced gets the step of the same+ * author's next hand-off (a redo follows the step it redoes); one that matches nothing stays+ * unnumbered rather than numbered wrong. Without those ids (Chat Server plans, older hosts) the+ * author's hand-offs are matched to the author's steps in order.+ */+export function botGroupHandoffStepNumbers(+ messages: readonly BotGroupMessageView[],+ plans: ReadonlyMap<string, BotGroupPlanView>,+): ReadonlyMap<string, number> {+ const numbers = new Map<string, number>();+ const handoffs = messages.filter((message) => message.kind === 'message' && message.authorKind === 'bot'+ && message.planId && message.authorBotId && plans.has(message.planId));+ const exact = new Map<string, number>();+ const exactPlans = new Set<string>();+ for (const plan of plans.values()) {+ plan.steps.forEach((step, index) => {+ if (step.resultMessageId === undefined) return;+ exactPlans.add(plan.id);+ if (step.resultMessageId) exact.set(step.resultMessageId, index + 1);+ });+ }+ const next = new Map<string, number>();+ for (const message of [...handoffs].reverse()) {+ if (!exactPlans.has(message.planId!)) continue;+ const key = `${message.planId}:${message.authorBotId}`;+ const number = exact.get(message.id) ?? next.get(key);+ if (number === undefined) continue;+ numbers.set(message.id, number);+ next.set(key, number);+ }+ const seen = new Map<string, number>();+ for (const message of handoffs) {+ if (exactPlans.has(message.planId!)) continue;+ const plan = plans.get(message.planId!)!;+ const key = `${plan.id}:${message.authorBotId}`;+ const nth = seen.get(key) ?? 0;+ const positions = plan.steps.flatMap((step, index) => (step.botId === message.authorBotId ? [index + 1] : []));+ const number = positions[Math.min(nth, positions.length - 1)];+ if (number !== undefined) numbers.set(message.id, number);+ seen.set(key, nth + 1);+ }+ return numbers;+}diff --cc apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 7ff1ec76e9,17f47f6e2d..6838250197--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@@ -11,8 -11,9 +11,9 @@@ import { afterEach, beforeAll, beforeEaimport { clearDraft, getDraft } from '@/lib/composerDraftStore';import { FeatureSidebarSlotProvider, useFeatureContentHeader } from '../../feature-context';import { markBotRead, getBotLastReadAt, botGroupReadKey, resetBotReadStateForTests } from '../botReadState';-import { botGroupAttachmentScope } from '../botGroupAttachments';+import { botGroupAttachmentScope, botGroupThreadDraftKey } from '../botGroupAttachments';import { getBotGroupListSnapshot, refreshBotGroups, resetBotGroupStoreForTests } from '../botGroupStore';+ import { getBotGroupOutbox, getBotGroupOutboxPreviews, resetBotGroupOutboxForTests } from '../botGroupOutbox';import { BotGroupChatView } from '../BotGroupChatView';import { ControlledBanner, __resetControlledBannerForTests } from '../../remote-device/ControlledBanner';import type {@@@ -1311,6 -1288,349 +1313,352 @@@ describe('BotGroupChatView', () =>expect(await screen.findByText('bots.groupChat.unavailableTitle')).toBeTruthy();});+ describe('乐观显示', () => {+ /** A send main has not answered yet; the test decides when and how. */+ function pendingSend() {+ let resolve!: (result: unknown) => void;+ const promise = new Promise((res) => {+ resolve = res;+ });+ mocks.sendBotGroupMessage.mockImplementationOnce(() => promise);+ return { resolve: (result: unknown) => act(async () => { resolve(result); await promise; }) };+ }+ const outboxItems = () => screen.queryAllByTestId('bot-group-outbox');+ const withSelf = (id: string, sequence: number, content: string) =>+ detail({ messages: [...detail().messages, msg({ id, sequence, content })] });+ const pushMessages = (groupId = 'g1') =>+ act(() => mocks.pushes.forEach((push) => push({ groupId, change: 'messages' })));++ it('shows and settles the message when an older local route opens a migrated group', async () => {+ // The route still carries the local id; main answers with the group's server room id.+ const send = pendingSend();+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ id: 'room-1' }) });+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '迁移后的群' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ expect(outboxItems()).toHaveLength(1);+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ expect((mocks.sendBotGroupMessage.mock.calls[0]![0] as { groupId: string }).groupId).toBe('room-1');++ mocks.getBotGroup.mockResolvedValue({+ ok: true,+ group: detail({ id: 'room-1', messages: [...detail().messages, msg({ id: 'u2', sequence: 5, content: '迁移后的群' })] }),+ });+ await send.resolve({ ok: true, messageId: 'u2' });+ await waitFor(() => expect(getBotGroupOutbox('room-1')).toHaveLength(0));+ expect(screen.getAllByText('迁移后的群')).toHaveLength(1);+ });++ it('shows the message as soon as it is sent and swaps in the real one without a duplicate', async () => {+ const send = pendingSend();+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '@咪咪 慢一点', selectionStart: 7 } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(input.value).toBe('');+ expect(outboxItems()).toHaveLength(1);+ expect(outboxItems()[0]!.textContent).toContain('慢一点');- // The mention keeps its chip in the pending bubble too.- expect(within(outboxItems()[0]!).getByText('@咪咪')).toBeTruthy();++ // Pending and confirmed messages use the same Markdown/highlight renderer.++ const bubble = within(outboxItems()[0]!).getByText('@咪咪 慢一点');++ const row = bubble.closest('[data-bot-group-message-id]');++ expect(bubble).toBeTruthy();+ expect(within(outboxItems()[0]!).queryByRole('status')).toBeNull();+ expect(await screen.findByText('bots.groupChat.outbox.sending', {}, { timeout: 2000 })).toBeTruthy();+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));++ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withSelf('u2', 5, '@咪咪 慢一点') });+ await send.resolve({ ok: true, messageId: 'u2' });+ pushMessages();+ await waitFor(() => expect(outboxItems()).toHaveLength(0));- expect(screen.getAllByText('慢一点')).toHaveLength(1);++ expect(screen.getAllByText('@咪咪 慢一点')).toHaveLength(1);++ expect(screen.getByText('@咪咪 慢一点').closest('[data-bot-group-message-id]')).toBe(row);+ expect(screen.queryByText('bots.groupChat.outbox.sending')).toBeNull();+ });++ it('does not show the message twice when a push re-read lands before the receipt', async () => {+ const send = pendingSend();+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '早到的推送' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));++ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withSelf('u2', 5, '早到的推送') });+ pushMessages();+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(outboxItems()).toHaveLength(0));+ expect(screen.getAllByText('早到的推送')).toHaveLength(1);++ // The receipt settles against the timeline already on screen, with no further push.+ await send.resolve({ ok: true, messageId: 'u2' });+ await waitFor(() => expect(getBotGroupOutbox('g1')).toHaveLength(0));+ pushMessages();+ await waitFor(() => expect(mocks.getBotGroup).toHaveBeenCalledTimes(3));+ expect(screen.getAllByText('早到的推送')).toHaveLength(1);+ expect(outboxItems()).toHaveLength(0);+ });++ it('keeps a failed message where it was sent, above messages that came after it', async () => {+ const first = pendingSend();+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '先发的' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ fireEvent.change(input, { target: { value: '后发的' } });+ await first.resolve({ ok: false, errorCode: 'SERVICE_ERROR', message: '' });+ expect(outboxItems()[0]!.getAttribute('data-status')).toBe('failed');++ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: true, messageId: 'u2' });+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withSelf('u2', 5, '后发的') });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(screen.getAllByText('后发的')).toHaveLength(1));+ await waitFor(() => expect(outboxItems()).toHaveLength(1));+ const order = [...document.querySelectorAll('article')]+ .map((article) => article.textContent ?? '')+ .filter((text) => text.includes('先发的') || text.includes('后发的'))+ .map((text) => (text.includes('先发的') ? '先发的' : '后发的'));+ expect(order).toEqual(['先发的', '后发的']);+ });++ it('keeps a later failed message below an earlier one that went out', async () => {+ const first = pendingSend();+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '先发的' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ fireEvent.change(input, { target: { value: '后发的' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ // New text in the input keeps the failed message on the timeline.+ fireEvent.change(input, { target: { value: '还在写' } });++ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR', message: '' });+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withSelf('u2', 5, '先发的') });+ await first.resolve({ ok: true, messageId: 'u2' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(screen.getAllByText('先发的')).toHaveLength(1));+ await waitFor(() => expect(outboxItems().map((item) => item.getAttribute('data-status'))).toEqual(['failed']));+ const order = [...document.querySelectorAll('article')]+ .map((article) => article.textContent ?? '')+ .filter((text) => text.includes('先发的') || text.includes('后发的'))+ .map((text) => (text.includes('先发的') ? '先发的' : '后发的'));+ expect(order).toEqual(['先发的', '后发的']);+ });++ it('takes the next message while the first is still out, and sends them in order', async () => {+ const first = pendingSend();+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '同一句' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ fireEvent.change(input, { target: { value: '同一句' } });+ fireEvent.keyDown(input, { key: 'Enter' });++ expect(outboxItems().map((item) => item.textContent)).toEqual(['同一句', '同一句']);+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: true, messageId: 'u3' });+ await first.resolve({ ok: true, messageId: 'u2' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(2));+ const [firstSend, secondSend] = mocks.sendBotGroupMessage.mock.calls.map(([call]) => call as Record<string, unknown>);+ // Same text, two messages: each keeps its own identity.+ expect(firstSend!.clientId).not.toBe(secondSend!.clientId);++ mocks.getBotGroup.mockResolvedValue({+ ok: true,+ group: detail({ messages: [...detail().messages, msg({ id: 'u2', sequence: 5, content: '同一句' }), msg({ id: 'u3', sequence: 6, content: '同一句' })] }),+ });+ pushMessages();+ await waitFor(() => expect(outboxItems()).toHaveLength(0));+ expect(screen.getAllByText('同一句')).toHaveLength(2);+ });++ it('keeps a failed message in place while new text is in the input; 重试 reuses its clientId and 编辑 waits for an empty input', async () => {+ const send = pendingSend();+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '第一条' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ fireEvent.change(input, { target: { value: '正在写的' } });+ await send.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });++ expect(mocks.toastError).toHaveBeenCalledWith('bots.groupChat.composer.sendFailed');+ expect(input.value).toBe('正在写的');+ const failed = await screen.findByTestId('bot-group-outbox');+ expect(failed.getAttribute('data-status')).toBe('failed');+ expect(within(failed).getByText('bots.groupChat.outbox.failed')).toBeTruthy();+ // Nothing goes out again on its own.+ expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1);++ fireEvent.click(within(failed).getByRole('button', { name: 'bots.groupChat.outbox.edit' }));+ expect(mocks.toastWarning).toHaveBeenCalledWith('bots.groupChat.outbox.editBlocked');+ expect(input.value).toBe('正在写的');++ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ fireEvent.click(within(failed).getByRole('button', { name: /bots\.retry/ }));+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(2));+ const [firstAttempt, retry] = mocks.sendBotGroupMessage.mock.calls.map(([call]) => call as Record<string, unknown>);+ expect(retry!.clientId).toBe(firstAttempt!.clientId);+ await waitFor(() => expect(screen.getByTestId('bot-group-outbox').getAttribute('data-status')).toBe('failed'));++ fireEvent.change(input, { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: 'bots.groupChat.outbox.edit' }));+ expect(input.value).toBe('第一条');+ expect(outboxItems()).toHaveLength(0);+ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: true, messageId: 'u2' });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(3));+ expect(lastSend().clientId).toBe(firstAttempt!.clientId);+ });++ it('keeps the local image on screen while the server copy of a confirmed message is still loading', async () => {+ const send = pendingSend();+ renderView();+ await screen.findByRole('textbox');+ pickFiles([diskFile('photo.png', 'image/png')]);+ await screen.findByAltText('photo.png');+ fireEvent.click(screen.getByRole('button', { name: 'bots.send' }));+ // Out of the tray and into the pending bubble at once.+ expect(within(outboxItems()[0]!).getByAltText('photo.png')).toBeTruthy();+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));++ const image = { id: 's1', name: 'photo.png', category: 'image' as const, mimeType: 'image/png', size: 7 };+ mocks.getBotGroup.mockResolvedValue({+ ok: true,+ group: detail({ messages: [...detail().messages, msg({ id: 'u2', sequence: 5, attachments: [{ ...image, url: null, path: null }] })] }),+ });+ await send.resolve({ ok: true, messageId: 'u2' });+ pushMessages();+ await waitFor(() => expect(outboxItems()).toHaveLength(0));+ expect(screen.getAllByAltText('photo.png')).toHaveLength(1);+ expect(screen.getByAltText('photo.png').getAttribute('src')).toContain('photo.png');++ mocks.getBotGroup.mockResolvedValue({+ ok: true,+ group: detail({ messages: [...detail().messages, msg({ id: 'u2', sequence: 5, attachments: [{ ...image, url: 'cindy-media://blobs/server.png', path: null }] })] }),+ });+ pushMessages();+ await waitFor(() => expect(screen.getByAltText('photo.png').getAttribute('src')).toContain('server.png'));+ expect(screen.getAllByAltText('photo.png')).toHaveLength(1);+ });++ it('puts a message that failed while the group was closed back into its empty composer on return', async () => {+ const send = pendingSend();+ const view = renderView();+ const tree = () => (+ <Tooltip.Provider>+ <FeatureSidebarSlotProvider isCollapsed={false}>+ <HeaderSlot />+ <BotGroupChatView />+ </FeatureSidebarSlotProvider>+ </Tooltip.Provider>+ );+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '离开时失败的' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ mocks.groupId = 'g2';+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ id: 'g2', name: '另一个群' }) });+ view.rerender(tree());+ await screen.findByText('另一个群');+ await send.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });+ // Nothing of g1 shows here, and g2's composer is not touched.+ expect(outboxItems()).toHaveLength(0);+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('');++ mocks.groupId = 'g1';+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail() });+ view.rerender(tree());+ await screen.findByText('周六 8:10 有票');+ await waitFor(() => expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('离开时失败的'));+ expect(outboxItems()).toHaveLength(0);+ expect(mocks.toastError).toHaveBeenCalledWith('bots.groupChat.composer.sendFailed');+ // Sending it again is the same attempt.+ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: true, messageId: 'u2' });+ fireEvent.keyDown(screen.getByRole('textbox'), { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(2));+ expect(mocks.sendBotGroupMessage.mock.calls[1]![0].clientId).toBe(mocks.sendBotGroupMessage.mock.calls[0]![0].clientId);+ });++ it('settles the local preview of a message pushed off the latest page once an older page shows it', async () => {+ const send = pendingSend();+ renderView();+ await screen.findByRole('textbox');+ pickFiles([diskFile('photo.png', 'image/png')]);+ await screen.findByAltText('photo.png');+ fireEvent.click(screen.getByRole('button', { name: 'bots.send' }));+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));+ // The receipt comes back; the next read's latest page no longer holds the message.+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ hasMoreBefore: true }) });+ await send.resolve({ ok: true, messageId: 'u-old' });+ pushMessages();+ await waitFor(() => expect(getBotGroupOutbox('g1')).toEqual([]));+ expect(getBotGroupOutboxPreviews('g1').size).toBe(1);++ const image = { id: 's1', name: 'photo.png', category: 'image' as const, mimeType: 'image/png', size: 7, url: 'cindy-media://blobs/server.png', path: null };+ mocks.getBotGroup.mockResolvedValueOnce({+ ok: true,+ group: detail({ messages: [msg({ id: 'u-old', sequence: 0, attachments: [image] })], hasMoreBefore: false }),+ });+ fireEvent.click(await screen.findByRole('button', { name: 'bots.groupChat.timeline.loadEarlier' }));+ await waitFor(() => expect(getBotGroupOutboxPreviews('g1').size).toBe(0));+ });++ it('drops the outbox of a group that reads as gone', async () => {+ renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ mocks.sendBotGroupMessage.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ fireEvent.change(input, { target: { value: '没发出去' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ fireEvent.change(input, { target: { value: '正在写' } });+ await waitFor(() => expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['failed']));+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'NOT_FOUND', message: '' });+ pushMessages();+ expect(await screen.findByText('bots.groupChat.unavailableTitle')).toBeTruthy();+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('keeps a late receipt out of the next group and shows the message when coming back', async () => {+ const send = pendingSend();+ const view = renderView();+ const input = (await screen.findByRole('textbox')) as HTMLTextAreaElement;+ fireEvent.change(input, { target: { value: '离开前发的' } });+ fireEvent.keyDown(input, { key: 'Enter' });+ await waitFor(() => expect(mocks.sendBotGroupMessage).toHaveBeenCalledTimes(1));++ mocks.groupId = 'g2';+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: detail({ id: 'g2', name: '另一个群' }) });+ view.rerender(+ <Tooltip.Provider>+ <FeatureSidebarSlotProvider isCollapsed={false}>+ <HeaderSlot />+ <BotGroupChatView />+ </FeatureSidebarSlotProvider>+ </Tooltip.Provider>,+ );+ await screen.findByText('另一个群');+ await send.resolve({ ok: true, messageId: 'u2' });+ expect(outboxItems()).toHaveLength(0);+ expect(screen.queryByText('离开前发的')).toBeNull();++ mocks.groupId = 'g1';+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withSelf('u2', 5, '离开前发的') });+ view.rerender(+ <Tooltip.Provider>+ <FeatureSidebarSlotProvider isCollapsed={false}>+ <HeaderSlot />+ <BotGroupChatView />+ </FeatureSidebarSlotProvider>+ </Tooltip.Provider>,+ );+ await waitFor(() => expect(screen.getAllByText('离开前发的')).toHaveLength(1));+ expect(outboxItems()).toHaveLength(0);+ });+ });+describe('引用回复', () => {const quoteOf = (messageId: string, overrides: Partial<NonNullable<BotGroupMessageView['quote']>> = {}) => ({messageId, authorName: '小满', authorKind: 'bot' as const, excerpt: '周六 8:10 有票', attachmentCount: 0, attachmentName: null, sequence: 2, ...overrides,diff --cc apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.tsindex 0000000000,1b87a3bd70..d25cd775femode 000000,100644..100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botGroupOutbox.test.ts@@@ -1,0 -1,948 +1,948 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++ import type { AttachedFile } from '@/lib/fileTypes';+ import type {+ BotGroupAttachment,+ BotGroupMessageView,+ BotGroupSendInput,+ BotGroupSendResult,+ } from '../../../../shared/botGroupChat';+ import {+ BOT_GROUP_GONE_RETRY_MS,+ beginBotGroupTimelineRead,+ botGroupSendSignature,+ discardBotGroupOutbox,+ editBotGroupSend,+ enqueueBotGroupSend,+ getBotGroupOutbox,+ getBotGroupOutboxClaims,+ noteBotGroupTimeline,+ registerBotGroupComposer,+ resetBotGroupOutboxForTests,+ getBotGroupOutboxPreviews,+ mergeBotGroupLocalAttachments,+ projectBotGroupOutbox,+ retryBotGroupSend,+ type BotGroupOutboxDraft,+ type BotGroupOutboxSendInput,+ } from '../botGroupOutbox';++ const mocks = vi.hoisted(() => ({+ /** Data owner account (null = an auth boundary's fence); `generation` moves on same-owner repairs. */+ owner: 1 as number | null,+ generation: 0,+ send: vi.fn<(input: BotGroupSendInput) => Promise<BotGroupSendResult>>(),+ materialize: vi.fn(async (files: readonly AttachedFile[]) => [...files]),+ protectedUrls: [] as string[],+ cleanupStaged: vi.fn(),+ getBotGroup: vi.fn(),+ list: { groups: [] as Array<{ id: string }>, loaded: false },+ listListeners: new Set<() => void>(),+ }));++ vi.mock('@/contexts/dataOwnerGeneration', () => ({+ getDataOwnerGeneration: () => ({ dataOwnerId: mocks.owner === null ? null : `account-${mocks.owner}`, generation: mocks.generation }),+ isDataOwnerGenerationCurrent: (owner: { dataOwnerId: string | null; generation: number }) =>+ owner.dataOwnerId === (mocks.owner === null ? null : `account-${mocks.owner}`) && owner.generation === mocks.generation,+ }));+ vi.mock('../botGroupStore', () => ({+ botGroupApi: () => ({ sendBotGroupMessage: mocks.send, getBotGroup: mocks.getBotGroup }),+ getBotGroupListSnapshot: () => mocks.list,+ subscribeBotGroups: (listener: () => void) => {+ mocks.listListeners.add(listener);+ return () => mocks.listListeners.delete(listener);+ },+ }));++ /** The sidebar list re-read: these groups exist for the account. */+ function listGroups(ids: string[]) {+ mocks.list = { groups: ids.map((id) => ({ id })), loaded: true };+ for (const listener of [...mocks.listListeners]) listener();+ }+ vi.mock('@/lib/annotationBurnIn', () => ({+ isAnnotationBurnInError: () => false,+ materializeAnnotatedAttachmentsForSend: (files: readonly AttachedFile[]) => mocks.materialize(files),+ }));+ vi.mock('@/lib/composerDraftStore', () => ({+ setBotGroupOutboxAttachmentUrls: (urls: readonly string[]) => {+ mocks.protectedUrls = [...new Set(urls)].sort();+ },+ }));+ vi.mock('@/lib/chatAttachmentStageCleanup', () => ({+ cleanupStagedChatAttachmentFiles: (files: unknown) => mocks.cleanupStaged(files),+ }));++ /** A send main has not answered yet; the test decides when and how. */+ function deferred() {+ let resolve!: (result: BotGroupSendResult) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<BotGroupSendResult>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+ }++ /** A draft as the composer builds it; `input` fields and draft fields override separately. */+ function draft(+ input: Partial<BotGroupOutboxSendInput> = {},+ overrides: Partial<Omit<BotGroupOutboxDraft, 'input'>> = {},+ ): BotGroupOutboxDraft {+ const full: BotGroupOutboxSendInput = {+ groupId: 'g1',+ clientId: 'c1',+ text: '你好',+ mentions: { all: false, botIds: [] },+ ...input,+ };+ return {+ input: full,+ signature: botGroupSendSignature(full, '[]'),+ draft: full.text,+ tracked: [],+ files: [],+ attachmentScope: `bot-group:${full.groupId}`,+ ...overrides,+ };+ }++ function msg(overrides: Partial<BotGroupMessageView>): BotGroupMessageView {+ return {+ id: 'm',+ sequence: 1,+ kind: 'message',+ authorKind: 'user',+ authorBotId: null,+ authorName: '',+ content: '',+ mentions: { all: false, botIds: [] },+ noticeCode: null,+ planId: null,+ files: [],+ attachments: [],+ createdAt: 1,+ isSelf: true,+ ...overrides,+ };+ }++ const flush = () => new Promise<void>((resolve) => setTimeout(resolve, 0));++ function visible(groupId: string, messages: BotGroupMessageView[]) {+ return project(groupId, messages).pending.map((entry) => `${entry.input.clientId}:${entry.status}`);+ }++ function project(groupId: string, messages: BotGroupMessageView[]) {+ return projectBotGroupOutbox(+ getBotGroupOutbox(groupId),+ messages,+ getBotGroupOutboxClaims(groupId),+ getBotGroupOutboxPreviews(groupId),+ );+ }++ beforeEach(() => {+ mocks.owner = 1;+ mocks.generation = 0;+ mocks.send.mockReset();+ mocks.materialize.mockReset().mockImplementation(async (files: readonly AttachedFile[]) => [...files]);+ mocks.protectedUrls = [];+ mocks.cleanupStaged.mockReset();+ mocks.getBotGroup.mockReset().mockResolvedValue({ ok: true, group: {} });+ mocks.list = { groups: [], loaded: false };+ resetBotGroupOutboxForTests();+ });++ afterEach(() => {+ resetBotGroupOutboxForTests();+ });++ describe('botGroupOutbox', () => {+ it('shows a message at once and submits a group’s sends one after another', async () => {+ const first = deferred();+ const second = deferred();+ mocks.send.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ noteBotGroupTimeline('g1', [msg({ id: 'old', sequence: 3 })], beginBotGroupTimelineRead());++ enqueueBotGroupSend(draft({ clientId: 'c1', text: '一' }));+ enqueueBotGroupSend(draft({ clientId: 'c2', text: '二' }));+ expect(visible('g1', [])).toEqual(['c1:sending', 'c2:sending']);+ await flush();+ // The second waits for the first, so the server sees them in the order they were sent.+ expect(mocks.send).toHaveBeenCalledTimes(1);+ expect(mocks.send.mock.calls[0]![0]).toMatchObject({ groupId: 'g1', clientId: 'c1', text: '一' });++ first.resolve({ ok: true, messageId: 'm1' });+ await flush();+ expect(mocks.send).toHaveBeenCalledTimes(2);+ expect(mocks.send.mock.calls[1]![0]).toMatchObject({ clientId: 'c2', text: '二' });+ expect(visible('g1', [])).toEqual(['c1:sent', 'c2:sending']);+ });++ it('swaps a receipt for the real message whether the receipt or the re-read comes first, and ignores repeats', async () => {+ const pending = deferred();+ mocks.send.mockReturnValueOnce(pending.promise);+ noteBotGroupTimeline('g1', [msg({ id: 'old', sequence: 3, content: '你好' })], beginBotGroupTimelineRead());+ enqueueBotGroupSend(draft());+ await flush();++ // A push re-read lands before main answers: the copy after the baseline stands in for it,+ // while the earlier message with the same text does not.+ const real = msg({ id: 'm9', sequence: 4, content: '你好' });+ const reread = [msg({ id: 'old', sequence: 3, content: '你好' }), real];+ noteBotGroupTimeline('g1', reread, beginBotGroupTimelineRead());+ expect(visible('g1', [msg({ id: 'old', sequence: 3, content: '你好' })])).toEqual(['c1:sending']);+ expect(visible('g1', reread)).toEqual([]);++ pending.resolve({ ok: true, messageId: 'm9' });+ await flush();+ expect(visible('g1', reread)).toEqual([]);+ // The same receipt id read again (a duplicate push) settles the entry for good.+ const read = beginBotGroupTimelineRead();+ noteBotGroupTimeline('g1', reread, read);+ noteBotGroupTimeline('g1', reread, read);+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('never lets a re-read hide a message that is not the one in flight', async () => {+ const first = deferred();+ const second = deferred();+ mocks.send.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ noteBotGroupTimeline('g1', [], beginBotGroupTimelineRead());+ enqueueBotGroupSend(draft({ clientId: 'c1', text: '好' }));+ enqueueBotGroupSend(draft({ clientId: 'c2', text: '好' }));+ await flush();+ first.resolve({ ok: true, messageId: 'm1' });+ await flush();++ // m1 belongs to c1's receipt; c2 (same text, now in flight) must stay visible.+ const timeline = [msg({ id: 'm1', sequence: 1, content: '好' })];+ noteBotGroupTimeline('g1', timeline, beginBotGroupTimelineRead());+ expect(visible('g1', timeline)).toEqual(['c2:sending']);+ // A queued message is never matched, nor a message from someone else.+ expect(visible('g1', [...timeline, msg({ id: 'x', sequence: 2, content: '好', isSelf: false })])).toEqual(['c2:sending']);++ second.resolve({ ok: true, messageId: 'm2' });+ await flush();+ expect(visible('g1', timeline)).toEqual(['c2:sent']);+ noteBotGroupTimeline('g1', [...timeline, msg({ id: 'm2', sequence: 2, content: '好' })], beginBotGroupTimelineRead());+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('settles a receipt that a later read no longer shows on its page', async () => {+ const pending = deferred();+ mocks.send.mockReturnValueOnce(pending.promise);+ enqueueBotGroupSend(draft());+ await flush();+ const early = beginBotGroupTimelineRead();+ pending.resolve({ ok: true, messageId: 'm1' });+ await flush();+ // A read that started before the receipt cannot speak for it.+ noteBotGroupTimeline('g1', [], early);+ expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['sent']);+ // One that started after it can: the message is in history even when pushed off the page.+ noteBotGroupTimeline('g1', [msg({ id: 'later', sequence: 50, isSelf: false })], beginBotGroupTimelineRead());+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('hands a failure back to an empty composer, otherwise keeps it for 重试 with the same clientId', async () => {+ const restore = vi.fn(() => false);+ const notifyFailed = vi.fn();+ registerBotGroupComposer('g1', { restore, notifyFailed });+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ clientId: 'keep' }));+ await flush();+ expect(restore).toHaveBeenCalledTimes(1);+ expect(notifyFailed).toHaveBeenCalledWith('bots.groupChat.composer.sendFailed');+ expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['failed']);+ // Nothing is sent again on its own.+ await flush();+ expect(mocks.send).toHaveBeenCalledTimes(1);++ mocks.send.mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ retryBotGroupSend('g1', 'keep');+ await flush();+ expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['failed']);+ retryBotGroupSend('g1', 'keep');+ await flush();+ expect(mocks.send.mock.calls.map(([input]) => input.clientId)).toEqual(['keep', 'keep', 'keep']);+ expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['sent']);++ // An empty composer takes the next failure back; the bubble goes away.+ restore.mockReturnValue(true);+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'MENTION_UNAVAILABLE', message: '' });+ enqueueBotGroupSend(draft({ clientId: 'back' }));+ await flush();+ expect(restore).toHaveBeenLastCalledWith(+ expect.objectContaining({ input: expect.objectContaining({ clientId: 'back' }), status: 'failed' }),+ );+ expect(notifyFailed).toHaveBeenLastCalledWith('bots.groupChat.errors.mentionUnavailable');+ expect(getBotGroupOutbox('g1').map((entry) => entry.input.clientId)).toEqual(['keep']);+ });++ it('offers no 重试 when main refused the message itself: only 编辑 can change it', async () => {+ registerBotGroupComposer('g1', { restore: vi.fn(() => false), notifyFailed: vi.fn() });+ for (const errorCode of ['QUOTE_UNAVAILABLE', 'MENTION_UNAVAILABLE', 'INVALID_PARAMS', 'INVALID_ATTACHMENT', 'ATTACHMENT_TOO_LARGE'] as const) {+ mocks.send.mockReset().mockResolvedValueOnce({ ok: false, errorCode, message: '' });+ enqueueBotGroupSend(draft({ clientId: errorCode }));+ await flush();+ expect(getBotGroupOutbox('g1').find((entry) => entry.input.clientId === errorCode)).toMatchObject({ status: 'failed', retryable: false });+ retryBotGroupSend('g1', errorCode);+ await flush();+ expect(mocks.send).toHaveBeenCalledTimes(1);+ }+ // A failure that may pass later stays retryable.+ mocks.send.mockReset().mockResolvedValueOnce({ ok: false, errorCode: 'SERVICE_ERROR', message: '' });+ enqueueBotGroupSend(draft({ clientId: 'later' }));+ await flush();+ expect(getBotGroupOutbox('g1').find((entry) => entry.input.clientId === 'later')?.retryable).toBe(true);+ });++ it('edits a failed message only into a composer that accepts it', async () => {+ const restore = vi.fn(() => false);+ registerBotGroupComposer('g1', { restore, notifyFailed: vi.fn() });+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft());+ await flush();+ expect(editBotGroupSend('g1', 'c1')).toBe(false);+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ restore.mockReturnValue(true);+ expect(editBotGroupSend('g1', 'c1')).toBe(true);+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('keeps groups apart: another group’s composer never takes a failure', async () => {+ const otherRestore = vi.fn(() => true);+ registerBotGroupComposer('g2', { restore: otherRestore, notifyFailed: vi.fn() });+ const g1 = deferred();+ mocks.send.mockReturnValueOnce(g1.promise).mockResolvedValueOnce({ ok: true, messageId: 'g2-m' });+ enqueueBotGroupSend(draft({ groupId: 'g1', clientId: 'a' }));+ enqueueBotGroupSend(draft({ groupId: 'g2', clientId: 'b' }));+ await flush();+ // Groups do not queue behind each other.+ expect(mocks.send).toHaveBeenCalledTimes(2);+ g1.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });+ await flush();+ expect(otherRestore).not.toHaveBeenCalled();+ expect(visible('g1', [])).toEqual(['a:failed']);+ expect(visible('g2', [])).toEqual(['b:sent']);+ });++ it('drops late answers after the account changes or the group is deleted', async () => {+ const late = deferred();+ mocks.send.mockReturnValueOnce(late.promise);+ enqueueBotGroupSend(draft());+ await flush();+ mocks.owner = 2;+ late.resolve({ ok: true, messageId: 'm1' });+ await flush();+ expect(getBotGroupOutbox('g1')).toEqual([]);++ const gone = deferred();+ mocks.send.mockReturnValueOnce(gone.promise);+ enqueueBotGroupSend(draft({ clientId: 'c2' }));+ await flush();+ discardBotGroupOutbox('g1');+ gone.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });+ await flush();+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('keeps the attachments with the message and sends them in the existing shape', async () => {+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ const file = {+ id: 'f1',+ name: 'report.pdf',+ path: '/tmp/report.pdf',+ ext: '.pdf',+ size: 7,+ category: 'pdf',+ mimeType: 'application/pdf',+ type: 'file',+ } as unknown as AttachedFile;+ enqueueBotGroupSend(draft({ text: '' }, { files: [file] }));+ expect(getBotGroupOutbox('g1')[0]!.attachments).toEqual([+ expect.objectContaining({ id: 'f1', name: 'report.pdf', category: 'pdf', path: '/tmp/report.pdf' }),+ ]);+ await flush();+ expect(mocks.send.mock.calls[0]![0].attachments).toEqual([+ expect.objectContaining({ name: 'report.pdf', path: '/tmp/report.pdf', category: 'pdf' }),+ ]);+ });++ it('sends the whole input it was given, first time and on 重试, without dropping fields it does not know', async () => {+ // A field a later composer feature adds (here a stand-in) must survive the outbox untouched.+ const extra = { replyTo: { messageId: 'root-1' } } as unknown as Partial<BotGroupOutboxSendInput>;+ mocks.send+ .mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' })+ .mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ enqueueBotGroupSend(draft({ division: true, mentions: { all: true, botIds: ['a'] }, ...extra }));+ await flush();+ retryBotGroupSend('g1', 'c1');+ await flush();+ const expected = {+ groupId: 'g1',+ clientId: 'c1',+ text: '你好',+ mentions: { all: true, botIds: ['a'] },+ division: true,+ replyTo: { messageId: 'root-1' },+ };+ expect(mocks.send.mock.calls.map(([input]) => input)).toEqual([expected, expected]);+ });++ it('ties a clientId to every send field except itself, plus the attachments', () => {+ const base = draft().input;+ const same = botGroupSendSignature({ ...base, clientId: 'other' }, '[]');+ expect(same).toBe(botGroupSendSignature(base, '[]'));+ for (const changed of [+ { ...base, text: '别的' },+ { ...base, mentions: { all: false, botIds: ['a'] } },+ { ...base, division: true },+ { ...base, replyTo: 'x' } as unknown as BotGroupOutboxSendInput,+ ]) {+ expect(botGroupSendSignature(changed, '[]')).not.toBe(same);+ }+ expect(botGroupSendSignature(base, '[["f1"]]')).not.toBe(same);+ });++ describe('attachments of a confirmed message', () => {+ const local = (id: string, name: string): BotGroupAttachment => ({+ id, name, category: 'image', mimeType: 'image/png', size: 1, url: `cindy-media://blobs/${id}.png`, path: '/tmp/' + name,+ });+ /** A server copy not downloaded yet keeps id and name only. */+ const placeholder = (id: string, name: string): BotGroupAttachment => ({+ id, name, category: 'image', mimeType: 'image/png', size: 1, url: null, path: null,+ });+ const usable = (id: string, name: string): BotGroupAttachment => ({ ...placeholder(id, name), url: `cindy-media://blobs/${id}.png` });++ it('keeps each local preview until its server copy is usable, under the server id, in send order', () => {+ const mine = [local('l1', 'a.png'), local('l2', 'b.png')];+ // The server keeps the order the files were sent in.+ expect(mergeBotGroupLocalAttachments([placeholder('s1', 'a.png'), placeholder('s2', 'b.png')], mine)).toEqual([+ { ...mine[0], id: 's1' },+ { ...mine[1], id: 's2' },+ ]);+ expect(mergeBotGroupLocalAttachments([usable('s1', 'a.png'), placeholder('s2', 'b.png')], mine)).toEqual([+ usable('s1', 'a.png'),+ { ...mine[1], id: 's2' },+ ]);+ // Main leaves a copy out until it downloads: never show it missing or twice.+ expect(mergeBotGroupLocalAttachments([usable('s2', 'b.png')], mine)).toEqual([mine[0], usable('s2', 'b.png')]);+ // A burned-in image may come back renamed; equal counts pair the rest in order.+ expect(mergeBotGroupLocalAttachments([usable('s1', 'a-annotated.png'), usable('s2', 'b.png')], mine)).toEqual([+ usable('s1', 'a-annotated.png'),+ usable('s2', 'b.png'),+ ]);+ });++ it('carries the previews from the pending bubble onto the real message, then lets them go', async () => {+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ const file = { id: 'l1', name: 'a.png', path: '/tmp/a.png', size: 1, category: 'image', mimeType: 'image/png',+ url: 'cindy-media://blobs/l1.png', type: 'image' } as unknown as AttachedFile;+ enqueueBotGroupSend(draft({ text: '' }, { files: [file] }));+ await flush();+ const shownLocal = getBotGroupOutbox('g1')[0]!.attachments;++ const loading = [msg({ id: 'm1', sequence: 1, attachments: [placeholder('s1', 'a.png')] })];- expect(project('g1', loading)).toEqual({ pending: [], localAttachments: new Map([['m1', shownLocal]]) });++ expect(project('g1', loading)).toEqual({ pending: [], localAttachments: new Map([['m1', shownLocal]]), replacements: new Map([['m1', 'c1']]) });+ noteBotGroupTimeline('g1', loading, beginBotGroupTimelineRead());+ // The entry is settled, the preview stays with the message.+ expect(getBotGroupOutbox('g1')).toEqual([]);+ expect(project('g1', loading).localAttachments.get('m1')).toEqual(shownLocal);++ noteBotGroupTimeline('g1', [msg({ id: 'm1', sequence: 1, attachments: [usable('s1', 'a.png')] })], beginBotGroupTimelineRead());+ expect(getBotGroupOutboxPreviews('g1').size).toBe(0);+ });++ it('drops the previews of a message deleted before its server copies were usable', async () => {+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ const file = { id: 'l1', name: 'a.png', path: '/tmp/a.png', size: 1, category: 'image', mimeType: 'image/png',+ url: 'cindy-media://blobs/l1.png', type: 'image' } as unknown as AttachedFile;+ enqueueBotGroupSend(draft({ text: '' }, { files: [file] }));+ await flush();+ noteBotGroupTimeline('g1', [msg({ id: 'm1', sequence: 1, attachments: [placeholder('s1', 'a.png')] })], beginBotGroupTimelineRead());+ expect(getBotGroupOutboxPreviews('g1').size).toBe(1);++ // Deleted on another device: the tombstone has no attachments, and the preview goes with it.+ noteBotGroupTimeline('g1', [msg({ id: 'm1', sequence: 1, deleted: true, attachments: [] })], beginBotGroupTimelineRead());+ expect(getBotGroupOutboxPreviews('g1').size).toBe(0);+ });++ it('keeps a later message below the copy a re-read shows of an earlier one', async () => {+ const pending = deferred();+ mocks.send.mockReturnValueOnce(pending.promise);+ noteBotGroupTimeline('g1', [], beginBotGroupTimelineRead());+ enqueueBotGroupSend(draft({ text: '先发的', clientId: 'a' }));+ enqueueBotGroupSend(draft({ text: '后发的', clientId: 'b' }));+ await flush();+ // Both were sent on the same timeline; the copy of the first lands before its receipt.+ const projected = project('g1', [msg({ id: 'm1', sequence: 1, content: '先发的' })]);+ expect(projected.pending.map((entry) => [entry.input.clientId, entry.after])).toEqual([['b', 1]]);+ });++ it('lays the previews over the copy a re-read shows before the receipt', async () => {+ const pending = deferred();+ mocks.send.mockReturnValueOnce(pending.promise);+ noteBotGroupTimeline('g1', [], beginBotGroupTimelineRead());+ const file = { id: 'l1', name: 'a.png', path: '/tmp/a.png', size: 1, category: 'image', mimeType: 'image/png',+ url: 'cindy-media://blobs/l1.png', type: 'image' } as unknown as AttachedFile;+ enqueueBotGroupSend(draft({ text: '看图' }, { files: [file] }));+ await flush();+ const copy = msg({ id: 'm1', sequence: 1, content: '看图', attachments: [placeholder('s1', 'a.png')] });+ const projected = project('g1', [copy]);+ expect(projected.pending).toEqual([]);+ expect(projected.localAttachments.get('m1')).toEqual(getBotGroupOutbox('g1')[0]!.attachments);+ });++ it('never swaps two files with the same name, whether the server lists all of them or not yet', () => {+ // Two different photo.png; the first was drawn on, so its burned-in copy is renamed.+ const mine = [local('l1', 'photo-annotated.png'), local('l2', 'photo.png')];+ expect(mergeBotGroupLocalAttachments(+ [placeholder('s1', 'photo-annotated.png'), usable('s2', 'photo.png')], mine,+ )).toEqual([{ ...mine[0], id: 's1' }, usable('s2', 'photo.png')]);+ // Copies listed one by one as they download.+ expect(mergeBotGroupLocalAttachments([usable('s2', 'photo.png')], mine)).toEqual([mine[0], usable('s2', 'photo.png')]);+ expect(mergeBotGroupLocalAttachments([usable('s1', 'photo-annotated.png')], mine)).toEqual([+ usable('s1', 'photo-annotated.png'), mine[1],+ ]);+ });++ it('keeps the local previews of files that share a name until every copy is listed', () => {+ // Two different photo.png and a.png; downloads finish in any order.+ const mine = [local('l1', 'photo.png'), local('l2', 'photo.png'), local('l3', 'a.png')];+ // Only the second photo.png is in: which one it is cannot be told, so neither is replaced.+ expect(mergeBotGroupLocalAttachments([usable('s2', 'photo.png')], mine)).toEqual(mine);+ // A unique name still pairs on its own.+ expect(mergeBotGroupLocalAttachments([usable('s2', 'photo.png'), usable('s3', 'a.png')], mine)).toEqual([+ mine[0], mine[1], usable('s3', 'a.png'),+ ]);+ // Every copy listed: the send order decides.+ expect(mergeBotGroupLocalAttachments([usable('s1', 'photo.png'), usable('s2', 'photo.png'), usable('s3', 'a.png')], mine)).toEqual([+ usable('s1', 'photo.png'), usable('s2', 'photo.png'), usable('s3', 'a.png'),+ ]);+ });+ });++ describe('drawn annotations', () => {+ const original = {+ id: 'l1', name: 'photo.png', path: '/tmp/photo.png', size: 1, category: 'image', mimeType: 'image/png', type: 'image',+ url: 'cindy-media://blobs/original.png', annotationStrokes: [{ points: [{ x: 1, y: 1 }] }],+ } as unknown as AttachedFile;+ const burned = {+ ...original, name: 'photo-annotated.png', url: 'cindy-media://blobs/burned.png', annotated: true,+ annotationSourceUrl: 'cindy-media://blobs/original.png',+ } as unknown as AttachedFile;++ it('shows the burned-in copy as soon as it is ready and burns once for every (re)try', async () => {+ let finishBurn!: (files: AttachedFile[]) => void;+ mocks.materialize.mockImplementationOnce(() => new Promise((resolve) => { finishBurn = resolve; }));+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' })+ .mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ enqueueBotGroupSend(draft({ text: '圈出来的地方' }, { files: [original] }));+ await flush();+ expect(mocks.send).not.toHaveBeenCalled();+ finishBurn([burned]);+ await flush();+ expect(getBotGroupOutbox('g1')[0]!.attachments).toEqual([+ expect.objectContaining({ name: 'photo-annotated.png', url: 'cindy-media://blobs/burned.png' }),+ ]);+ retryBotGroupSend('g1', 'c1');+ await flush();+ expect(mocks.materialize).toHaveBeenCalledTimes(1);+ expect(mocks.send.mock.calls.map(([input]) => input.attachments?.[0]?.url)).toEqual([+ 'cindy-media://blobs/burned.png', 'cindy-media://blobs/burned.png',+ ]);+ });++ it('hands the original with its strokes back to the composer, not the burned copy', async () => {+ const restore = vi.fn(() => true);+ registerBotGroupComposer('g1', { restore, notifyFailed: vi.fn() });+ mocks.materialize.mockResolvedValueOnce([burned]);+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({}, { files: [original] }));+ await flush();+ expect(restore).toHaveBeenCalledWith(expect.objectContaining({ files: [original] }));+ });++ it('never sends a queued message whose early burn failed until 重试', async () => {+ const slow = deferred();+ mocks.send.mockReturnValueOnce(slow.promise).mockResolvedValueOnce({ ok: true, messageId: 'm2' });+ // The early burn fails; a second burn would succeed.+ mocks.materialize.mockRejectedValueOnce(new Error('burn')).mockResolvedValue([burned]);+ enqueueBotGroupSend(draft({ clientId: 'first' }));+ enqueueBotGroupSend(draft({ clientId: 'drawn' }, { files: [original] }));+ await flush();+ slow.resolve({ ok: true, messageId: 'm1' });+ await flush();+ // Its turn came: the failure is the message's, not a cue to burn again on its own.+ expect(getBotGroupOutbox('g1').find((entry) => entry.input.clientId === 'drawn')?.status).toBe('failed');+ expect(mocks.send).toHaveBeenCalledTimes(1);+ expect(mocks.materialize).toHaveBeenCalledTimes(1);+ retryBotGroupSend('g1', 'drawn');+ await flush();+ expect(mocks.materialize).toHaveBeenCalledTimes(2);+ expect(mocks.send.mock.calls[1]![0].attachments?.[0]?.url).toBe('cindy-media://blobs/burned.png');+ });++ it('tries the burn again on 重试 after it failed', async () => {+ mocks.materialize.mockRejectedValueOnce(new Error('burn')).mockResolvedValueOnce([burned]);+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ enqueueBotGroupSend(draft({}, { files: [original] }));+ await flush();+ expect(getBotGroupOutbox('g1')[0]!.status).toBe('failed');+ expect(mocks.send).not.toHaveBeenCalled();+ retryBotGroupSend('g1', 'c1');+ await flush();+ expect(mocks.materialize).toHaveBeenCalledTimes(2);+ expect(mocks.send.mock.calls[0]![0].attachments?.[0]?.url).toBe('cindy-media://blobs/burned.png');+ });+ });++ describe('holding files outside the draft', () => {+ const file = {+ id: 'f1', name: 'shot.png', path: '/staged/shot.bin', size: 1, category: 'image', mimeType: 'image/png', type: 'image',+ url: 'cindy-media://blobs/shot.png',+ } as unknown as AttachedFile;++ it('protects the media of messages still held from storage cleanup until they are settled', async () => {+ const pending = deferred();+ mocks.send.mockReturnValueOnce(pending.promise);+ enqueueBotGroupSend(draft({ text: '' }, { files: [file] }));+ await flush();+ expect(mocks.protectedUrls).toEqual(['cindy-media://blobs/shot.png']);+ pending.resolve({ ok: true, messageId: 'm1' });+ await flush();+ expect(mocks.protectedUrls).toEqual(['cindy-media://blobs/shot.png']);+ noteBotGroupTimeline('g1', [msg({ id: 'm1', sequence: 1, attachments: [+ { id: 's1', name: 'shot.png', category: 'image', mimeType: 'image/png', size: 1, url: 'cindy-media://blobs/server.png', path: null },+ ] })], beginBotGroupTimelineRead());+ expect(mocks.protectedUrls).toEqual([]);+ });++ it('cleans up staged copies of unsent messages when the group is deleted, never of sent ones', async () => {+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' })+ .mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ const sentFile = { ...file, id: 'f0', path: '/staged/sent.bin' } as AttachedFile;+ enqueueBotGroupSend(draft({ clientId: 'sent' }, { files: [sentFile] }));+ enqueueBotGroupSend(draft({ clientId: 'unsent' }, { files: [file] }));+ await flush();+ discardBotGroupOutbox('g1');+ expect(mocks.cleanupStaged).toHaveBeenCalledTimes(1);+ expect(mocks.cleanupStaged).toHaveBeenCalledWith([file]);+ expect(mocks.protectedUrls).toEqual([]);+ });+ });++ describe('a failure while the composer was away', () => {+ it('comes back into an empty composer when it registers, with the reason', async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'MENTION_UNAVAILABLE', message: '' });+ enqueueBotGroupSend(draft());+ await flush();+ expect(getBotGroupOutbox('g1').map((entry) => entry.status)).toEqual(['failed']);+ const busy = { restore: vi.fn(() => false), notifyFailed: vi.fn() };+ const release = registerBotGroupComposer('g1', busy);+ expect(busy.notifyFailed).not.toHaveBeenCalled();+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ release();+ const empty = { restore: vi.fn(() => true), notifyFailed: vi.fn() };+ registerBotGroupComposer('g1', empty);+ expect(empty.restore).toHaveBeenCalledWith(expect.objectContaining({ input: expect.objectContaining({ clientId: 'c1' }) }));+ expect(empty.notifyFailed).toHaveBeenCalledWith('bots.groupChat.errors.mentionUnavailable');+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });+ });++ describe('staged files of messages that never went out', () => {+ const staged = (id: string) =>+ ({ id, name: `${id}.txt`, path: `/staged/${id}.bin`, size: 1, category: 'text', mimeType: 'text/plain', type: 'file' }) as unknown as AttachedFile;+ const released = () => mocks.cleanupStaged.mock.calls.map(([files]) => (files as AttachedFile[]).map((file) => file.id).join(','));++ it('on an account switch: releases queued and failed sends, settles the one in flight by its answer', async () => {+ const inFlight = deferred();+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm-sent' })+ .mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' })+ .mockReturnValueOnce(inFlight.promise);+ enqueueBotGroupSend(draft({ clientId: 'sent' }, { files: [staged('sent')] }));+ enqueueBotGroupSend(draft({ clientId: 'failed' }, { files: [staged('failed')] }));+ enqueueBotGroupSend(draft({ clientId: 'flying' }, { files: [staged('flying')] }));+ enqueueBotGroupSend(draft({ clientId: 'queued' }, { files: [staged('queued')] }));+ await flush();+ expect(mocks.send).toHaveBeenCalledTimes(3);++ mocks.owner = 2;+ expect(getBotGroupOutbox('g1')).toEqual([]);+ // Not yet submitted: the outbox owns them and releases them now. The one in flight is main's.+ expect(released().sort()).toEqual(['failed', 'queued']);+ // The in-flight send went out after all: its file stays with the message.+ inFlight.resolve({ ok: true, messageId: 'm-late' });+ await flush();+ // Nothing is sent under the new account, and nothing more is released.+ expect(mocks.send).toHaveBeenCalledTimes(3);+ expect(released().sort()).toEqual(['failed', 'queued']);+ });++ it('on an account switch: releases an in-flight send that did not go out, and one still burning in', async () => {+ const inFlight = deferred();+ let finishBurn!: (files: AttachedFile[]) => void;+ mocks.send.mockReturnValueOnce(inFlight.promise);+ enqueueBotGroupSend(draft({ groupId: 'g1', clientId: 'flying' }, { files: [staged('flying')] }));+ const drawn = { ...staged('drawn'), category: 'image', annotationStrokes: [{ points: [{ x: 1, y: 1 }] }] } as unknown as AttachedFile;+ mocks.materialize.mockImplementationOnce(() => new Promise((resolve) => { finishBurn = resolve; }));+ enqueueBotGroupSend(draft({ groupId: 'g2', clientId: 'burning' }, { files: [drawn] }));+ await flush();+ mocks.owner = 2;+ getBotGroupOutbox('g1');+ inFlight.resolve({ ok: false, errorCode: 'INTERNAL', message: '' });+ finishBurn([drawn]);+ await flush();+ expect(released().sort()).toEqual(['drawn', 'flying']);+ // The burn finished under the new account: the old message is never sent.+ expect(mocks.send).toHaveBeenCalledTimes(1);+ });++ it('on an account switch with no group open: a queued send settles the outbox when its turn comes', async () => {+ const inFlight = deferred();+ mocks.send.mockReturnValueOnce(inFlight.promise);+ const shot = { ...staged('queued'), category: 'image', url: 'cindy-media://blobs/queued.png' } as unknown as AttachedFile;+ enqueueBotGroupSend(draft({ clientId: 'flying' }));+ enqueueBotGroupSend(draft({ clientId: 'queued' }, { files: [shot] }));+ await flush();+ expect(mocks.protectedUrls).toEqual(['cindy-media://blobs/queued.png']);+ // Nothing calls into the outbox after the switch: the queue itself notices it.+ mocks.owner = 2;+ inFlight.resolve({ ok: true, messageId: 'm-late' });+ await flush();+ expect(mocks.protectedUrls).toEqual([]);+ expect(released()).toEqual(['queued']);+ expect(mocks.send).toHaveBeenCalledTimes(1);+ });++ const goneGroup = () => {+ mocks.getBotGroup.mockImplementation(async (groupId: string) =>+ groupId === 'gone' ? { ok: false, errorCode: 'NOT_FOUND', message: '' } : { ok: true, group: {} });+ listGroups(['unrelated']);+ };++ it('discards a group that left the list once a read confirms it is gone; unsubmitted files go at once', async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ groupId: 'gone', clientId: 'failed' }, { files: [staged('failed')] }));+ enqueueBotGroupSend(draft({ groupId: 'kept', clientId: 'other' }, { files: [staged('other')] }));+ await flush();+ mocks.send.mockReturnValue(new Promise(() => undefined));+ // `kept` is missing from the list too (e.g. a legacy id), but still reads fine: untouched.+ goneGroup();+ await flush();+ expect(mocks.getBotGroup.mock.calls.map(([groupId]) => groupId).sort()).toEqual(['gone', 'kept']);+ expect(getBotGroupOutbox('gone')).toEqual([]);+ expect(getBotGroupOutbox('kept')).toHaveLength(1);+ expect(released()).toEqual(['failed']);+ });++ it.each([+ ['went out', { ok: true, messageId: 'm1' }, []],+ ['was refused', { ok: false, errorCode: 'INTERNAL', message: '' }, ['flying']],+ ] as const)('A) a send already with main when its group is discarded: files stay until main answers, then kept if it %s', async (_label, answer, expected) => {+ const late = deferred();+ mocks.send.mockReturnValueOnce(late.promise);+ enqueueBotGroupSend(draft({ groupId: 'gone', clientId: 'flying' }, { files: [staged('flying')] }));+ await flush();+ expect(mocks.send).toHaveBeenCalledTimes(1);+ goneGroup();+ await flush();+ expect(getBotGroupOutbox('gone')).toEqual([]);+ // Main may still be reading the file and deciding: nothing is cleaned up before it answers.+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ late.resolve(answer);+ await flush();+ expect(released()).toEqual(expected);+ expect(getBotGroupOutbox('gone')).toEqual([]);+ });++ it('A) a lost answer (the call itself rejects) after its group is discarded releases the files once', async () => {+ const late = deferred();+ mocks.send.mockReturnValueOnce(late.promise);+ enqueueBotGroupSend(draft({ groupId: 'gone', clientId: 'flying' }, { files: [staged('flying')] }));+ await flush();+ goneGroup();+ await flush();+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ late.reject(new Error('ipc closed'));+ await flush();+ expect(released()).toEqual(['flying']);+ });++ it('B) a message still burning in when its group is discarded is never sent, and its files go once', async () => {+ let finishBurn!: (files: AttachedFile[]) => void;+ const drawn = { ...staged('drawn'), category: 'image', annotationStrokes: [{ points: [{ x: 1, y: 1 }] }] } as unknown as AttachedFile;+ mocks.materialize.mockImplementationOnce(() => new Promise((resolve) => { finishBurn = resolve; }));+ enqueueBotGroupSend(draft({ groupId: 'gone', clientId: 'burning' }, { files: [drawn] }));+ await flush();+ goneGroup();+ await flush();+ expect(getBotGroupOutbox('gone')).toEqual([]);+ // Submission has started (it owns the files): not released yet, not sent yet.+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ finishBurn([{ ...drawn, annotated: true } as AttachedFile]);+ await flush();+ expect(mocks.send).not.toHaveBeenCalled();+ expect(released()).toEqual(['drawn']);+ });++ describe('a read that is not definite', () => {+ const failOne = async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ groupId: 'g1', clientId: 'failed' }, { files: [staged('failed')] }));+ await flush();+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ };+ afterEach(() => vi.useRealTimers());++ it('is retried on its own and discards once a later read says NOT_FOUND', async () => {+ await failOne();+ mocks.getBotGroup.mockRejectedValueOnce(new Error('ipc'))+ .mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' })+ .mockResolvedValueOnce({ ok: false, errorCode: 'NOT_FOUND', message: '' });+ listGroups([]);+ await vi.advanceTimersByTimeAsync(0);+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(1);+ await vi.advanceTimersByTimeAsync(BOT_GROUP_GONE_RETRY_MS[0]);+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(2);+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ await vi.advanceTimersByTimeAsync(BOT_GROUP_GONE_RETRY_MS[1]);+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(3);+ expect(getBotGroupOutbox('g1')).toEqual([]);+ expect(released()).toEqual(['failed']);+ });++ it('gives up after the last retry, keeping the outbox', async () => {+ await failOne();+ mocks.getBotGroup.mockResolvedValue({ ok: false, errorCode: 'INTERNAL', message: '' });+ listGroups([]);+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(1 + BOT_GROUP_GONE_RETRY_MS.length);+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ });++ it('stops once the group is listed again or reads fine', async () => {+ await failOne();+ mocks.getBotGroup.mockRejectedValueOnce(new Error('ipc'));+ listGroups([]);+ await vi.advanceTimersByTimeAsync(0);+ mocks.list = { groups: [{ id: 'g1' }], loaded: true };+ await vi.advanceTimersByTimeAsync(10 * 60_000);+ expect(mocks.getBotGroup).toHaveBeenCalledTimes(1);+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ });+ });++ it('keeps a group that is only missing from the list when the read fails or is not definite', async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ groupId: 'g1', clientId: 'failed' }, { files: [staged('failed')] }));+ await flush();+ mocks.getBotGroup.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ listGroups([]);+ await flush();+ mocks.getBotGroup.mockRejectedValueOnce(new Error('offline'));+ listGroups([]);+ await flush();+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ // Listed groups are never re-read.+ mocks.getBotGroup.mockClear();+ listGroups(['g1']);+ await flush();+ expect(mocks.getBotGroup).not.toHaveBeenCalled();+ });+ });++ describe('the same account', () => {+ const staged = (id: string) =>+ ({ id, name: `${id}.txt`, path: `/staged/${id}.bin`, size: 1, category: 'text', mimeType: 'text/plain', type: 'file' }) as unknown as AttachedFile;++ it('keeps queued, failed and in-flight messages through a same-owner generation repair and a passing null', async () => {+ const inFlight = deferred();+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' }).mockReturnValueOnce(inFlight.promise);+ enqueueBotGroupSend(draft({ clientId: 'failed' }, { files: [staged('failed')] }));+ enqueueBotGroupSend(draft({ clientId: 'flying' }, { files: [staged('flying')] }));+ enqueueBotGroupSend(draft({ clientId: 'queued' }, { files: [staged('queued')] }));+ await flush();+ // A repair keeps the account and moves the generation; an auth boundary publishes null for a moment.+ mocks.generation += 1;+ expect(getBotGroupOutbox('g1').map((entry) => entry.input.clientId)).toEqual(['failed', 'flying', 'queued']);+ mocks.owner = null;+ expect(getBotGroupOutbox('g1')).toHaveLength(3);+ inFlight.resolve({ ok: true, messageId: 'm-flying' });+ mocks.owner = 1;+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm-queued' });+ await flush();+ expect(getBotGroupOutbox('g1').map((entry) => `${entry.input.clientId}:${entry.status}`)).toEqual([+ 'failed:failed', 'flying:sent', 'queued:sent',+ ]);+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ });++ it('still clears for a different account, even after a null in between', async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ clientId: 'failed' }, { files: [staged('failed')] }));+ await flush();+ mocks.owner = null;+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ mocks.owner = 2;+ expect(getBotGroupOutbox('g1')).toEqual([]);+ expect(mocks.cleanupStaged).toHaveBeenCalledWith([staged('failed')]);+ });+ });++ describe('previews of confirmed messages', () => {+ const image = (id: string) =>+ ({ id, name: `${id}.png`, path: `/tmp/${id}.png`, size: 1, category: 'image', mimeType: 'image/png', type: 'image', url: `cindy-media://blobs/${id}.png` }) as unknown as AttachedFile;+ const loading = (messageId: string, name: string) => msg({ id: messageId, sequence: 1, attachments: [+ { id: `media-${messageId}`, name, category: 'image', mimeType: 'image/png', size: 1, url: null, path: null },+ ] });++ it('are not listed for storage cleanup protection: main pinned them when the message was sent', async () => {+ mocks.send.mockResolvedValueOnce({ ok: true, messageId: 'm1' });+ enqueueBotGroupSend(draft({ text: '' }, { files: [image('a')] }));+ await flush();+ noteBotGroupTimeline('g1', [loading('m1', 'a.png')], beginBotGroupTimelineRead());+ expect(getBotGroupOutboxPreviews('g1').size).toBe(1);+ expect(mocks.protectedUrls).toEqual([]);+ });++ it('are never evicted while their server copies are not usable, however many there are', async () => {+ const count = 40;+ for (let i = 0; i < count; i += 1) mocks.send.mockResolvedValueOnce({ ok: true, messageId: `m${i}` });+ for (let i = 0; i < count; i += 1) enqueueBotGroupSend(draft({ clientId: `c${i}`, text: '' }, { files: [image(`p${i}`)] }));+ await flush();+ noteBotGroupTimeline('g1', Array.from({ length: count }, (_, i) => ({ ...loading(`m${i}`, `p${i}.png`), sequence: i + 1 })), beginBotGroupTimelineRead());+ expect(getBotGroupOutboxPreviews('g1').size).toBe(count);+ expect(getBotGroupOutbox('g1')).toEqual([]);+ });++ it('a gone-check read that spans an owner change is no answer; a later read under a stable owner decides', async () => {+ mocks.send.mockResolvedValueOnce({ ok: false, errorCode: 'INTERNAL', message: '' });+ enqueueBotGroupSend(draft({ clientId: 'failed' }, { files: [image('kept')] }));+ await flush();+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });+ try {+ let answer!: (value: unknown) => void;+ mocks.getBotGroup.mockImplementationOnce(() => new Promise((resolve) => { answer = resolve; }))+ .mockResolvedValueOnce({ ok: false, errorCode: 'NOT_FOUND', message: '' });+ listGroups([]);+ await vi.advanceTimersByTimeAsync(0);+ // Same account, repaired generation while the read was out.+ mocks.generation += 1;+ answer({ ok: false, errorCode: 'NOT_FOUND', message: '' });+ await vi.advanceTimersByTimeAsync(0);+ expect(getBotGroupOutbox('g1')).toHaveLength(1);+ expect(mocks.cleanupStaged).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(BOT_GROUP_GONE_RETRY_MS[0]);+ expect(getBotGroupOutbox('g1')).toEqual([]);+ } finally {+ vi.useRealTimers();+ }+ });+ });+ });diff --cc apps/desktop/src/renderer/features/bots/botGroupOutbox.tsindex 0000000000,683d4be507..2ffc4857fcmode 000000,100644..100644--- a/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts+++ b/apps/desktop/src/renderer/features/bots/botGroupOutbox.ts@@@ -1,0 -1,714 +1,718 @@@+ /**+ * 群聊发件箱:用户点发送后立即在时间线末尾显示自己的消息,不等 main / 服务器回执。+ *+ * 只是 renderer 内存里的展示状态,不持久化,也不替代 main 的幂等与服务器的权威时间线:+ * - 每条消息保存 composer 交来的完整发送输入(`BotGroupSendInput`,附件除外——附件在+ * 入队时就开始烧录标注,提交时序列化),提交与重试都原样发出,这里不挑字段;新增发送字段只需+ * composer 放进 `input`,显示、回执与重试自动带上。+ * - `input.clientId` 是身份,失败重试沿用同一个 clientId,main 与服务器据此去重,+ * 所以这里绝不自动重发。+ * - 同一个群的提交按发出顺序一条一条交给 main,保持用户看到的先后。+ * - 回执带回的 `messageId` 是替换依据:时间线读到这条消息就收起临时气泡;回执之后开始的+ * 一次重读即使没读到(被挤出最新一页),也说明它已进历史,同样收起。+ * - 推送重读可能先于回执到达。此时只对正在提交的那一条(同群同时最多一条)做显示上的+ * 去重:基线之后出现、未被任何回执认领、正文与附件数一致的自己的消息视为它,回执到达后+ * 仍以 messageId 为准。+ * - 附件:临时消息从输入的附件生成列表;带手绘标注的图片烧录完成后改用烧录后的本地预览+ * (同一份烧录结果也用于提交与重试,不重复烧录;放回输入框的仍是带笔迹的原件)。真实消息到了+ * 而服务器副本还没下载好(没有 url / path,或还没出现在列表里——main 只列已下载的副本)时,按同一 messageId+ * 把本地预览接到真实消息上,直到副本可用(见 `mergeBotGroupLocalAttachments`)。+ * - 离开输入框的附件不再受草稿保护:发件箱条目持有的图片地址(含标注原图与烧录副本)登记进+ * 存储清理的保护清单,条目移除时同步撤下;已确认消息的本地预览不登记——发送时 main 已在群的+ * `bot-group-attachment` 引用下固定这些图片。尚未进入消息的暂存文件按归属回收:还没开始提交的条目+ * (排队中、已失败)归发件箱,群被删除(含不在当前页的群:列表里消失且读取确认已不存在)时+ * 立即回收;已开始提交的条目归它的那次请求,条目在烧录期间被丢弃就不再发出并回收,+ * 已交给 main 的等结果——成功(已进入消息)不碰,失败才回收。main 的发送在 IPC 返回前读完+ * 全部本地文件,失败时不留任何引用暂存路径的本地记录(服务端只引用已上传的副本)。+ * 切换账号时同样按此发出回收,但 main 只删当前账号暂存目录里的副本,而 renderer 看到切换时+ * main 已在新账号(或边界)下:前一账号的副本留在它自己的暂存目录,renderer 无法再删,+ * 不在发件箱范围内(main 的暂存副本按账号划界)。+ * - 失败时交还输入框(输入框空着才交还,见 `registerBotGroupComposer`),否则留在时间线上+ * 显示没发出去,可重试或编辑;失败时输入框不在(切群、分享模式),回来注册输入框时同样交还。+ * - 切换到另一个账号时整体清空,旧账号的迟到回执一律丢弃;同账号的 generation 修复、认证边界+ * 短暂发布的 null、退出后重新登录同一账号都不清空。群被删除时丢弃该群的条目。+ */+ import { useCallback, useSyncExternalStore } from 'react';++ import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+ import { isAnnotationBurnInError, materializeAnnotatedAttachmentsForSend } from '@/lib/annotationBurnIn';+ import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';+ import { setBotGroupOutboxAttachmentUrls } from '@/lib/composerDraftStore';+ import type { AttachedFile } from '@/lib/fileTypes';+ import type {+ BotGroupAttachment,+ BotGroupErrorCode,+ BotGroupMessageView,+ BotGroupQuoteView,+ BotGroupSendInput,+ BotGroupSendResult,+ } from '../../../shared/botGroupChat';+ import { toBotGroupAttachmentInputs } from './botGroupAttachments';+ import type { BotGroupTrackedMention } from './botGroupMentions';+ import { botGroupErrorKey } from './botGroupPresentation';+ import { botGroupApi, getBotGroupListSnapshot, subscribeBotGroups } from './botGroupStore';++ export type BotGroupOutboxStatus = 'sending' | 'sent' | 'failed';++ /** The send as main receives it; attachments are prepared from `files` (see `prepared`). */+ export type BotGroupOutboxSendInput = Omit<BotGroupSendInput, 'attachments'>;++ /** What the composer hands over when the user presses send. */+ export interface BotGroupOutboxDraft {+ /** Sent unchanged on every (re)try; `groupId` and `clientId` identify the entry. */+ input: BotGroupOutboxSendInput;+ /** Same-attempt identity from `botGroupSendSignature`: a changed field means a new clientId. */+ signature: string;+ /** The composer text as typed, put back on failure. */+ draft: string;+ /** Composer-only state put back with the draft (which typed @ picked which teammate). */+ tracked: readonly BotGroupTrackedMention[];+ /** The 引用回复 picked for this message, put back with the draft; `input.quote` is what goes out. */+ quote?: BotGroupQuoteView | null;+ files: readonly AttachedFile[];+ /** Scope for burning drawn annotations into images (see botGroupAttachmentScope). */+ attachmentScope: string;+ }++ /**+ * Identity of one send attempt: every field of the input except the clientId, plus the+ * attachments. A failed send may reuse its clientId only while this is unchanged.+ */+ export function botGroupSendSignature(input: BotGroupOutboxSendInput, attachmentSignature: string): string {+ return JSON.stringify([{ ...input, clientId: undefined }, attachmentSignature]);+ }++ export interface BotGroupOutboxEntry extends BotGroupOutboxDraft {+ status: BotGroupOutboxStatus;+ createdAt: number;+ /** Highest timeline sequence known when the user pressed send: the message shows after it. */+ after: number;+ /** The attachments as the timeline shows them (the burned-in copies once `prepared`). */+ attachments: readonly BotGroupAttachment[];+ /** `files` with drawn annotations burned in; reused by every (re)try. */+ prepared?: readonly AttachedFile[];+ /** From the receipt. */+ messageId?: string;+ /** Order of the receipt against timeline reads (see `beginBotGroupTimelineRead`). */+ receiptTick?: number;+ /** Highest timeline sequence known when this entry's request started; set only while in flight. */+ baseline?: number;+ /** i18n key explaining a failure. */+ errorKey?: string;+ /** False when main refused the message itself: resending it unchanged can only fail again. */+ retryable?: boolean;+ }++ /** The mounted composer of a group: takes a failed message back into the input when it is empty. */+ export interface BotGroupComposerHandle {+ restore: (entry: BotGroupOutboxEntry) => boolean;+ notifyFailed: (errorKey: string) => void;+ }++ interface GroupOutbox {+ entries: readonly BotGroupOutboxEntry[];+ chain: Promise<void>;+ /** Recent receipt ids: a re-read can never mistake them for the message still in flight. */+ claimed: string[];+ latestSequence: number;+ /** Local attachment previews of confirmed messages, by messageId, until the server copy is usable. */+ previews: ReadonlyMap<string, readonly BotGroupAttachment[]>;+ }++ const CLAIMED_LIMIT = 64;+ /**+ * Refusals of the message's own content (a quoted original or a named teammate that is gone,+ * invalid fields or files): only 编辑 can change the outcome, so 重试 is not offered.+ */+ const CONTENT_REFUSALS: ReadonlySet<BotGroupErrorCode> = new Set([+ 'QUOTE_UNAVAILABLE',+ 'MENTION_UNAVAILABLE',+ 'INVALID_PARAMS',+ 'INVALID_ATTACHMENT',+ 'ATTACHMENT_TOO_LARGE',+ ]);+ const NO_PREVIEWS: ReadonlyMap<string, readonly BotGroupAttachment[]> = new Map();+ const EMPTY: readonly BotGroupOutboxEntry[] = [];++ /**+ * The account the outbox holds messages for: the last non-null data owner. Only a different+ * account replaces it — not a same-owner generation repair, not the null an auth boundary+ * publishes for a moment, not signing back in to the same account.+ */+ let account = getDataOwnerGeneration().dataOwnerId;++ function accountChanged(): boolean {+ const current = getDataOwnerGeneration().dataOwnerId;+ return current !== null && current !== account;+ }+ let generation = 0;+ let tick = 0;+ const groups = new Map<string, GroupOutbox>();+ const composers = new Map<string, BotGroupComposerHandle>();+ const listeners = new Set<() => void>();+ /** One burn-in per message, shared by the bubble and its submission. */+ const preparing = new Map<string, Promise<readonly AttachedFile[]>>();++ /**+ * Media only this outbox still refers to; storage cleanup must not sweep it. Previews of+ * confirmed messages are not listed: the send pinned those images under the group's+ * `bot-group-attachment` reference in main.+ */+ function protectHeldMedia(): void {+ const urls: string[] = [];+ const add = (file: { url?: string | null; annotationSourceUrl?: string }) => {+ if (file.url) urls.push(file.url);+ if (file.annotationSourceUrl) urls.push(file.annotationSourceUrl);+ };+ for (const group of groups.values()) {+ for (const entry of group.entries) {+ entry.files.forEach(add);+ entry.prepared?.forEach(add);+ }+ }+ setBotGroupOutboxAttachmentUrls(urls);+ }++ function emit(): void {+ protectHeldMedia();+ for (const listener of listeners) listener();+ }++ /** Staged copies only a message that never reached a message still points at. */+ function releaseStaged(files: readonly AttachedFile[]): void {+ if (files.length > 0) cleanupStagedChatAttachmentFiles(files);+ }++ /** Entries whose `submit` has started: that request owns their files until it settles. */+ const submitting = new Set<string>();+ const entryKey = (groupId: string, clientId: string) => `${groupId}\n${clientId}`;++ /** Drop entries the outbox still owns; a request in progress settles its own (see `submit`). */+ function releaseUnsubmitted(groupId: string, entries: readonly BotGroupOutboxEntry[]): void {+ for (const entry of entries) {+ if (entry.status !== 'sent' && !submitting.has(entryKey(groupId, entry.input.clientId))) releaseStaged(entry.files);+ }+ }++ function ensureOwner(): void {+ if (!accountChanged()) return;+ const previous = account;+ account = getDataOwnerGeneration().dataOwnerId;+ // Nothing was held for another account yet: whatever is here was written for this one.+ if (previous === null) return;+ generation += 1;+ // The previous account's queued and failed sends go with it; one being submitted settles itself.+ for (const [groupId, group] of groups) releaseUnsubmitted(groupId, group.entries);+ groups.clear();+ preparing.clear();+ protectHeldMedia();+ }++ function groupOf(groupId: string): GroupOutbox {+ ensureOwner();+ watchGroupList();+ let group = groups.get(groupId);+ if (!group) {+ group = { entries: EMPTY, chain: Promise.resolve(), claimed: [], latestSequence: 0, previews: NO_PREVIEWS };+ groups.set(groupId, group);+ }+ return group;+ }++ function update(groupId: string, clientId: string, patch: Partial<BotGroupOutboxEntry>): BotGroupOutboxEntry | null {+ const group = groups.get(groupId);+ const index = group?.entries.findIndex((entry) => entry.input.clientId === clientId) ?? -1;+ if (!group || index < 0) return null;+ const next = { ...group.entries[index]!, ...patch };+ group.entries = group.entries.map((entry, at) => (at === index ? next : entry));+ emit();+ return next;+ }++ function remove(groupId: string, clientId: string): void {+ const group = groups.get(groupId);+ if (!group || !group.entries.some((entry) => entry.input.clientId === clientId)) return;+ group.entries = group.entries.filter((entry) => entry.input.clientId !== clientId);+ emit();+ }++ function displayAttachments(files: readonly AttachedFile[]): BotGroupAttachment[] {+ return toBotGroupAttachmentInputs(files).map((file) => ({+ id: file.id,+ name: file.name,+ category: file.category,+ mimeType: file.mimeType,+ size: file.size ?? 0,+ url: file.url ?? null,+ path: file.path || null,+ ...(file.annotated ? { annotated: true } : {}),+ }));+ }++ /** Show the message at once and queue it behind the group's earlier sends. */+ export function enqueueBotGroupSend(draft: BotGroupOutboxDraft): void {+ const { groupId, clientId } = draft.input;+ const group = groupOf(groupId);+ const entry: BotGroupOutboxEntry = {+ ...draft,+ input: { ...draft.input },+ files: [...draft.files],+ tracked: [...draft.tracked],+ attachments: displayAttachments(draft.files),+ status: 'sending',+ createdAt: Date.now(),+ after: group.latestSequence,+ };+ group.entries = [...group.entries.filter((existing) => existing.input.clientId !== clientId), entry];+ // Sent again after 编辑 (same clientId): a burn that failed before is tried afresh.+ preparing.delete(entryKey(groupId, clientId));+ emit();+ schedule(groupId, clientId);+ // Burn annotations in now, not when the message's turn comes: the bubble shows the result.+ if (entry.files.length > 0) void prepare(groupId, clientId).catch(() => undefined);+ }++ /**+ * The message's files with annotations burned in, once. A failure stays until 重试 clears it:+ * the early burn's failure is the message's, it never goes out on a second try nobody asked for.+ */+ function prepare(groupId: string, clientId: string): Promise<readonly AttachedFile[]> {+ const entry = groups.get(groupId)?.entries.find((candidate) => candidate.input.clientId === clientId);+ if (!entry) return Promise.reject(new Error('OUTBOX_ENTRY_GONE'));+ if (entry.prepared) return Promise.resolve(entry.prepared);+ if (entry.files.length === 0) return Promise.resolve([]);+ const key = `${groupId}\n${clientId}`;+ const existing = preparing.get(key);+ if (existing) return existing;+ const requestGeneration = generation;+ const pending = materializeAnnotatedAttachmentsForSend(entry.files, entry.attachmentScope, { burnFailure: 'abort' })+ .then((files) => {+ const prepared = files ?? [];+ if (requestGeneration === generation) {+ update(groupId, clientId, { prepared, attachments: displayAttachments(prepared) });+ }+ if (preparing.get(key) === pending) preparing.delete(key);+ return prepared;+ });+ preparing.set(key, pending);+ return pending;+ }++ /** 重试 on a message that did not go out: the same clientId, so main returns any copy it already has. */+ export function retryBotGroupSend(groupId: string, clientId: string): void {+ ensureOwner();+ const entry = groups.get(groupId)?.entries.find((candidate) => candidate.input.clientId === clientId);+ if (!entry || entry.status !== 'failed' || entry.retryable === false) return;+ // A burn that failed is tried again now, on the user's 重试.+ preparing.delete(entryKey(groupId, clientId));+ update(groupId, clientId, { status: 'sending', errorKey: undefined });+ schedule(groupId, clientId);+ }++ /** 编辑: hand a message that did not go out back to the composer. False when the input is busy. */+ export function editBotGroupSend(groupId: string, clientId: string): boolean {+ ensureOwner();+ const entry = groups.get(groupId)?.entries.find((candidate) => candidate.input.clientId === clientId);+ const composer = composers.get(groupId);+ if (!entry || entry.status !== 'failed' || !composer?.restore(entry)) return false;+ remove(groupId, clientId);+ return true;+ }++ function schedule(groupId: string, clientId: string): void {+ const group = groupOf(groupId);+ const requestGeneration = generation;+ // Kept by the request itself: after an account switch the entry is gone but its files are not.+ const files = group.entries.find((entry) => entry.input.clientId === clientId)?.files ?? [];+ group.chain = group.chain.then(() => submit(groupId, clientId, requestGeneration, files)).catch(() => undefined);+ }++ async function submit(+ groupId: string,+ clientId: string,+ requestGeneration: number,+ files: readonly AttachedFile[],+ ): Promise<void> {+ // An account switch nothing else noticed yet (no group open) settles the outbox here.+ ensureOwner();+ const isCurrent = () => requestGeneration === generation && !accountChanged();+ // Dropped before its turn (account switch, deleted group): whoever dropped it released its files.+ if (!isCurrent()) return;+ const group = groups.get(groupId);+ const entry = group?.entries.find((candidate) => candidate.input.clientId === clientId);+ if (!group || !entry || entry.status !== 'sending') return;+ // From here this request owns the files. Still the outbox's message: same account, still listed.+ const owned = () =>+ isCurrent() && (groups.get(groupId)?.entries.some((candidate) => candidate.input.clientId === clientId) ?? false);+ const key = entryKey(groupId, clientId);+ submitting.add(key);+ try {+ await submitOwned(group, entry, owned, files);+ } finally {+ submitting.delete(key);+ }+ }++ async function submitOwned(+ group: GroupOutbox,+ entry: BotGroupOutboxEntry,+ owned: () => boolean,+ files: readonly AttachedFile[],+ ): Promise<void> {+ const { groupId, clientId } = entry.input;+ update(groupId, clientId, { baseline: group.latestSequence });+ const api = botGroupApi();+ let errorKey = 'bots.groupChat.composer.sendFailed';+ let retryable = true;+ try {+ if (!api) throw new Error('HOST_NOT_READY');+ // Drawn annotations are burned in first, as in a task; a failure keeps everything for a retry.+ const prepared = await prepare(groupId, clientId);+ // Dropped while annotations were burning in: it never reaches main.+ if (!owned()) {+ releaseStaged(files);+ return;+ }+ const result: BotGroupSendResult = await api.sendBotGroupMessage({+ ...entry.input,+ ...(prepared.length > 0 ? { attachments: toBotGroupAttachmentInputs(prepared) } : {}),+ });+ if (!owned()) {+ // A late answer for a dropped message: keep what went out, release what did not. Main has+ // read the files by the time it answers.+ if (!result.ok) releaseStaged(files);+ return;+ }+ if (result.ok) {+ group.claimed = [...group.claimed, result.messageId].slice(-CLAIMED_LIMIT);+ update(groupId, clientId, { status: 'sent', messageId: result.messageId, receiptTick: ++tick, baseline: undefined });+ return;+ }+ // An original that is no longer available is not put back with the draft.+ if (result.errorCode === 'QUOTE_UNAVAILABLE') update(groupId, clientId, { quote: null });+ retryable = !CONTENT_REFUSALS.has(result.errorCode);+ errorKey =+ result.errorCode === 'INVALID_PARAMS' && prepared.length > 0+ ? 'bots.groupChat.composer.attachmentsFailed'+ : botGroupErrorKey(result.errorCode, 'bots.groupChat.composer.sendFailed');+ } catch (error) {+ // Burn-in failed (never sent) or the call failed without an answer from main's handler.+ if (!owned()) {+ releaseStaged(files);+ return;+ }+ if (isAnnotationBurnInError(error)) errorKey = 'chat.media.annotateBurnFailedNotSent';+ }+ const failed = update(groupId, clientId, { status: 'failed', errorKey, retryable, baseline: undefined });+ if (!failed) return;+ const composer = composers.get(groupId);+ if (composer?.restore(failed)) remove(groupId, clientId);+ composer?.notifyFailed(errorKey);+ }++ /** Mark the start of a timeline read; pass the token to `noteBotGroupTimeline` when it lands. */+ export function beginBotGroupTimelineRead(): number {+ return ++tick;+ }++ /**+ * A timeline read for this group succeeded. Receipts it contains, or that came back before+ * the read started, are settled: the server timeline now speaks for them.+ */+ export function noteBotGroupTimeline(groupId: string, messages: readonly BotGroupMessageView[], readToken: number): void {+ const group = groupOf(groupId);+ group.latestSequence = messages.reduce((latest, message) => Math.max(latest, message.sequence), group.latestSequence);+ const byId = new Map(messages.map((message) => [message.id, message]));+ const settled = (entry: BotGroupOutboxEntry) =>+ entry.status === 'sent' &&+ ((entry.messageId !== undefined && byId.has(entry.messageId)) || (entry.receiptTick ?? Infinity) < readToken);+ const previews = new Map(group.previews);+ let changed = false;+ // A settled message keeps its local previews until the timeline has a usable copy of each.+ for (const entry of group.entries) {+ if (settled(entry) && entry.messageId && entry.attachments.length > 0) previews.set(entry.messageId, entry.attachments);+ }+ for (const [messageId, local] of previews) {+ const message = byId.get(messageId);+ // A message deleted meanwhile (here or on another device) shows no attachments at all.+ if (message && (message.deleted || botGroupLocalAttachmentsSettled(message.attachments, local))) previews.delete(messageId);+ }+ if (previews.size !== group.previews.size || [...previews].some(([id, value]) => group.previews.get(id) !== value)) {+ group.previews = previews;+ changed = true;+ }+ if (group.entries.some(settled)) {+ // Messages sent later stay below the settled ones: their anchors move past the real message.+ let floor = -Infinity;+ const kept: BotGroupOutboxEntry[] = [];+ for (const entry of group.entries) {+ if (!settled(entry)) {+ kept.push(floor > entry.after ? { ...entry, after: floor } : entry);+ continue;+ }+ const sequence = entry.messageId ? byId.get(entry.messageId)?.sequence : undefined;+ if (sequence !== undefined) floor = Math.max(floor, sequence);+ }+ group.entries = kept;+ changed = true;+ }+ if (changed) emit();+ }++ /** A server attachment that can be shown: an image with its address or a file on this computer. */+ function isUsable(attachment: BotGroupAttachment): boolean {+ return Boolean(attachment.url || attachment.path);+ }++ /**+ * Pair the server's attachments of a message with the local ones it was sent with. The server+ * keeps the order they were sent in, so equal counts pair by position. Main lists a copy only+ * once it is downloaded, and downloads finish in any order: then a name that is unique among+ * the local files pairs by name, while files sharing a name cannot be told apart and keep their+ * local previews (their server copies wait unshown) until the counts match. Local names are the+ * burned-in ones (see `prepared`), as on the server. Returns, for each local attachment, the+ * server copy it matches (or undefined), plus the server attachments no local name accounts for.+ */+ function pairLocalAttachments(server: readonly BotGroupAttachment[], local: readonly BotGroupAttachment[]) {+ if (server.length === local.length) return { pairs: [...server], extra: [] as BotGroupAttachment[] };+ const counts = new Map<string, number>();+ for (const file of local) counts.set(file.name, (counts.get(file.name) ?? 0) + 1);+ const pairs = local.map((file) =>+ counts.get(file.name) === 1 ? server.find((copy) => copy.name === file.name) : undefined,+ );+ return { pairs, extra: server.filter((copy) => !counts.has(copy.name)) };+ }++ /**+ * What a confirmed message shows: each attachment's server copy once it is usable, the local+ * preview until then (under the server's id when known), in the order the user sent them.+ */+ export function mergeBotGroupLocalAttachments(+ server: readonly BotGroupAttachment[],+ local: readonly BotGroupAttachment[],+ ): BotGroupAttachment[] {+ const { pairs, extra } = pairLocalAttachments(server, local);+ return [+ ...local.map((file, at) => {+ const echo = pairs[at];+ if (!echo) return file;+ return isUsable(echo) ? echo : { ...file, id: echo.id };+ }),+ ...extra,+ ];+ }++ /** Every local attachment has a usable server copy: the preview is no longer needed. */+ function botGroupLocalAttachmentsSettled(+ server: readonly BotGroupAttachment[],+ local: readonly BotGroupAttachment[],+ ): boolean {+ return pairLocalAttachments(server, local).pairs.every((echo) => echo !== undefined && isUsable(echo));+ }++ /**+ * The group was deleted: nothing of it is left to send or show. Staged copies of files that+ * never reached a message go too; the draft no longer lists them, so nothing else would.+ */+ export function discardBotGroupOutbox(groupId: string): void {+ ensureOwner();+ const group = groups.get(groupId);+ if (!group) return;+ groups.delete(groupId);+ releaseUnsubmitted(groupId, group.entries);+ emit();+ }++ let unwatchGroupList: (() => void) | null = null;+ const verifying = new Set<string>();+ const retryTimers = new Set<ReturnType<typeof setTimeout>>();+ /** A read that was not definite (thrown, or a failure other than NOT_FOUND) is tried again. */+ export const BOT_GROUP_GONE_RETRY_MS = [5_000, 30_000, 120_000] as const;++ /**+ * Groups deleted while their page is closed (or from another device) send no event this+ * outbox sees. The group list does: a group that drops out of it is read once more, and only+ * a definite NOT_FOUND discards its outbox (a legacy id still resolves). A read that fails is+ * retried a few times on its own: the event that dropped the group may never come again.+ */+ function watchGroupList(): void {+ if (unwatchGroupList) return;+ unwatchGroupList = subscribeBotGroups(() => {+ for (const groupId of groups.keys()) verifyGroupGone(groupId, 0);+ });+ }++ function verifyGroupGone(groupId: string, attempt: number): void {+ if (verifying.has(groupId)) return;+ const group = groups.get(groupId);+ if (!group || (group.entries.length === 0 && group.previews.size === 0)) return;+ const list = getBotGroupListSnapshot();+ if (!list.loaded || list.groups.some((listed) => listed.id === groupId)) return;+ const api = botGroupApi();+ if (!api) return;+ const requestGeneration = generation;+ // A read that spans an owner change (same-account repair, an auth boundary's null) is no answer.+ const requestOwner = getDataOwnerGeneration();+ let definite = false;+ verifying.add(groupId);+ void api+ .getBotGroup(groupId)+ .then((result) => {+ if (!isDataOwnerGenerationCurrent(requestOwner)) return;+ definite = result.ok || result.errorCode === 'NOT_FOUND';+ if (requestGeneration === generation && !result.ok && result.errorCode === 'NOT_FOUND') discardBotGroupOutbox(groupId);+ })+ .catch(() => undefined)+ .finally(() => {+ verifying.delete(groupId);+ const delay = BOT_GROUP_GONE_RETRY_MS[attempt];+ if (definite || delay === undefined || requestGeneration !== generation) return;+ const timer = setTimeout(() => {+ retryTimers.delete(timer);+ if (requestGeneration === generation) verifyGroupGone(groupId, attempt + 1);+ }, delay);+ retryTimers.add(timer);+ });+ }++ /**+ * The group's composer is on screen. A message that failed while it was away (another group,+ * share mode) comes back into it now, the same way as a failure seen in place.+ */+ export function registerBotGroupComposer(groupId: string, handle: BotGroupComposerHandle): () => void {+ composers.set(groupId, handle);+ const failed = groups.get(groupId)?.entries.find((entry) => entry.status === 'failed');+ if (failed && handle.restore(failed)) {+ remove(groupId, failed.input.clientId);+ handle.notifyFailed(failed.errorKey ?? 'bots.groupChat.composer.sendFailed');+ }+ return () => {+ if (composers.get(groupId) === handle) composers.delete(groupId);+ };+ }++ export interface BotGroupOutboxProjection {++ /** Server message id → local client id, to keep the same rendered row. */++ replacements: ReadonlyMap<string, string>;+ /** Entries still shown under the timeline. */+ pending: BotGroupOutboxEntry[];+ /** Local attachment previews to lay over timeline messages, by message id. */+ localAttachments: ReadonlyMap<string, readonly BotGroupAttachment[]>;+ }++ /**+ * Split the outbox against the timeline. A receipt already in the timeline is no longer+ * pending; so is the one request in flight once a re-read shows an unclaimed copy of it (see+ * above). Either way the real message keeps the local attachment previews until usable.+ */+ export function projectBotGroupOutbox(+ entries: readonly BotGroupOutboxEntry[],+ messages: readonly BotGroupMessageView[],+ claimed: readonly string[],+ previews: ReadonlyMap<string, readonly BotGroupAttachment[]> = NO_PREVIEWS,+ ): BotGroupOutboxProjection {+ const localAttachments = new Map(previews);- if (entries.length === 0) return { pending: [], localAttachments };++ const replacements = new Map<string, string>();++ if (entries.length === 0) return { pending: [], localAttachments, replacements };+ const claimedIds = new Set(claimed);+ const sequenceOf = new Map(messages.map((message) => [message.id, message.sequence]));+ // A message sent later never shows above an earlier one the timeline already has.+ let floor = -Infinity;+ const pending: BotGroupOutboxEntry[] = [];+ const shown = (entry: BotGroupOutboxEntry) => {+ pending.push(floor > entry.after ? { ...entry, after: floor } : entry);+ };+ const replaced = (messageId: string, entry: BotGroupOutboxEntry) => {++ replacements.set(messageId, entry.input.clientId);+ floor = Math.max(floor, sequenceOf.get(messageId) ?? -Infinity);+ if (entry.attachments.length > 0) localAttachments.set(messageId, entry.attachments);+ };+ for (const entry of entries) {+ if (entry.status === 'sent') {+ if (entry.messageId && sequenceOf.has(entry.messageId)) replaced(entry.messageId, entry);+ else shown(entry);+ continue;+ }+ if (entry.status !== 'sending' || entry.baseline === undefined) {+ shown(entry);+ continue;+ }+ const baseline = entry.baseline;+ const copy = messages.find(+ (message) =>+ message.kind === 'message' &&+ message.authorKind === 'user' &&+ message.isSelf !== false &&+ message.sequence > baseline &&+ !claimedIds.has(message.id) &&+ message.content.trim() === entry.input.text &&+ message.attachments.length === entry.files.length,+ );+ if (copy) replaced(copy.id, entry);+ else shown(entry);+ }- return { pending, localAttachments };++ return { pending, localAttachments, replacements };+ }++ export type BotGroupTimelineRow =+ | { message: BotGroupMessageView; entry?: undefined }+ | { entry: BotGroupOutboxEntry; message?: undefined };++ /**+ * The timeline with the messages still in the outbox where they were sent: each after the+ * messages the timeline had then, so a failed message never moves below later ones. Both lists+ * are in order (messages by sequence, entries as sent), so the anchors only grow.+ */+ export function interleaveBotGroupOutbox(+ messages: readonly BotGroupMessageView[],+ pending: readonly BotGroupOutboxEntry[],+ ): BotGroupTimelineRow[] {+ const rows: BotGroupTimelineRow[] = [];+ let at = 0;+ for (const entry of pending) {+ while (at < messages.length && messages[at]!.sequence <= entry.after) rows.push({ message: messages[at++]! });+ rows.push({ entry });+ }+ while (at < messages.length) rows.push({ message: messages[at++]! });+ return rows;+ }++ function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => listeners.delete(listener);+ }++ export function getBotGroupOutbox(groupId: string): readonly BotGroupOutboxEntry[] {+ ensureOwner();+ return groups.get(groupId)?.entries ?? EMPTY;+ }++ export function getBotGroupOutboxClaims(groupId: string): readonly string[] {+ ensureOwner();+ return groups.get(groupId)?.claimed ?? [];+ }++ export function getBotGroupOutboxPreviews(groupId: string): ReadonlyMap<string, readonly BotGroupAttachment[]> {+ ensureOwner();+ return groups.get(groupId)?.previews ?? NO_PREVIEWS;+ }++ export function useBotGroupOutbox(groupId: string): readonly BotGroupOutboxEntry[] {+ const read = useCallback(() => getBotGroupOutbox(groupId), [groupId]);+ return useSyncExternalStore(subscribe, read, read);+ }++ /** Test-only reset of the module state. */+ export function resetBotGroupOutboxForTests(): void {+ generation += 1;+ account = getDataOwnerGeneration().dataOwnerId;+ groups.clear();+ preparing.clear();+ verifying.clear();+ submitting.clear();+ for (const timer of retryTimers) clearTimeout(timer);+ retryTimers.clear();+ unwatchGroupList?.();+ unwatchGroupList = null;+ composers.clear();+ }diff --cc docs/design-rules/design-inventory.mdindex 6dea0f39ea,22f6f81870..e0708f04ef--- a/docs/design-rules/design-inventory.md+++ b/docs/design-rules/design-inventory.md@@@ -18,7 -18,7 +18,7 @@@| `desktop.auth.add-account` | desktop | 添加账号 | hash `/add-account`(ProtectedRoute → AddAccountLoginPage) | AddAccountLoginPage | apps/desktop/src/renderer/components/login/AddAccountLoginPage.tsx, apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 || `desktop.auth.legacy-migration` | desktop | 首登数据迁移弹窗 | App 顶层挂载 LegacyMigrationDialog(仅主窗;main 检测到旧版 userData 经 `legacy-migration:state` 驱动) | LegacyMigrationDialog | apps/desktop/src/renderer/components/auth/LegacyMigrationDialog.tsx | 8 | 0 | 2 || `desktop.auth.login` | desktop | 登录页 | hash `/login`(GuestRoute → LoginPage) | LoginBrandStage, LoginCaptchaOverlay, LoginControls, LoginPage | apps/desktop/src/renderer/components/login/LoginBrandStage.tsx, apps/desktop/src/renderer/components/login/LoginCaptchaOverlay.tsx, apps/desktop/src/renderer/components/login/LoginControls.tsx, apps/desktop/src/renderer/components/login/LoginPage.tsx, apps/desktop/src/renderer/components/login/loginDesignTokens.ts | 59 | 0 | 20 |- | `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx, apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx, apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 38 | 509 |-| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskCardHeader.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotWorkingStatus.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 275 | 38 | 495 |++| `desktop.bots` | desktop | 伙伴(列表 / 对话 / 设置 / 历史 / 伙伴私聊 / 群聊) | hash `/bots`、`/bots/list`、`/bots/:botId`、`/bots/roster` 及伙伴当前/历史任务、伙伴私聊、伙伴群聊路由(BotsFeatureLayout) | BotBasicProfileFields, BotCollaborationCard, BotDirectMessageView, BotGroupChatView, BotGroupCreateDialog, BotGroupSettingsDrawer, BotHistorySessionView, BotLifecycleSettings, BotModelChainEditor, BotRosterView, BotSessionView, BotSettingsDrawer, BotsHomeView, BotsListView, RemoteBotSessionView | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/bots/BotAddToGroupMenu.tsx, apps/desktop/src/renderer/features/bots/BotAuthorizationCard.tsx, apps/desktop/src/renderer/features/bots/BotAvatar.tsx, apps/desktop/src/renderer/features/bots/BotBasicProfileFields.tsx, apps/desktop/src/renderer/features/bots/BotCapabilitySettings.tsx, apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx, apps/desktop/src/renderer/features/bots/BotConnectionStatus.tsx, apps/desktop/src/renderer/features/bots/BotCreateMenu.tsx, apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageCard.tsx, apps/desktop/src/renderer/features/bots/BotDirectMessageView.tsx, apps/desktop/src/renderer/features/bots/BotFollowMark.tsx, apps/desktop/src/renderer/features/bots/BotGenerationLabel.tsx, apps/desktop/src/renderer/features/bots/BotGroupAvatars.tsx, apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx, apps/desktop/src/renderer/features/bots/BotGroupComposer.tsx, apps/desktop/src/renderer/features/bots/BotGroupCreateDialog.tsx, apps/desktop/src/renderer/features/bots/BotGroupElapsed.tsx, apps/desktop/src/renderer/features/bots/BotGroupLivePreview.tsx, apps/desktop/src/renderer/features/bots/BotGroupLiveStatus.tsx, apps/desktop/src/renderer/features/bots/BotGroupMessageAttachments.tsx, apps/desktop/src/renderer/features/bots/BotGroupPendingInteraction.tsx, apps/desktop/src/renderer/features/bots/BotGroupPlan.tsx, apps/desktop/src/renderer/features/bots/BotGroupQuote.tsx, apps/desktop/src/renderer/features/bots/BotGroupRuntimeFailureNotice.tsx, apps/desktop/src/renderer/features/bots/BotGroupSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotGroupSidebarRow.tsx, apps/desktop/src/renderer/features/bots/BotGroupTaskCard.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineItem.tsx, apps/desktop/src/renderer/features/bots/BotGroupTimelineModel.ts, apps/desktop/src/renderer/features/bots/BotHistorySessionView.tsx, apps/desktop/src/renderer/features/bots/BotHomeComputerSetting.tsx, apps/desktop/src/renderer/features/bots/BotImportForm.tsx, apps/desktop/src/renderer/features/bots/BotInvitationWelcome.tsx, apps/desktop/src/renderer/features/bots/BotLearningFooter.tsx, apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx, apps/desktop/src/renderer/features/bots/BotMemorySettings.tsx, apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx, apps/desktop/src/renderer/features/bots/BotPortraitPicker.tsx, apps/desktop/src/renderer/features/bots/BotRosterView.tsx, apps/desktop/src/renderer/features/bots/BotRoutines.tsx, apps/desktop/src/renderer/features/bots/BotSessionContentHeader.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx, apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx, apps/desktop/src/renderer/features/bots/BotSessionView.tsx, apps/desktop/src/renderer/features/bots/BotSettingsBlock.tsx, apps/desktop/src/renderer/features/bots/BotSettingsDrawer.tsx, apps/desktop/src/renderer/features/bots/BotTaskModelEditor.tsx, apps/desktop/src/renderer/features/bots/BotTaskOwnerChip.tsx, apps/desktop/src/renderer/features/bots/BotTodoList.tsx, apps/desktop/src/renderer/features/bots/BotWorkbench.tsx, apps/desktop/src/renderer/features/bots/BotsFeatureLayout.tsx, apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx, apps/desktop/src/renderer/features/bots/BotsHomeView.tsx, apps/desktop/src/renderer/features/bots/BotsListView.tsx, apps/desktop/src/renderer/features/bots/ChatBotAccessField.tsx, apps/desktop/src/renderer/features/bots/ChatGroupSettings.tsx, apps/desktop/src/renderer/features/bots/ChatInviteDialog.tsx, apps/desktop/src/renderer/features/bots/ChatInviteHost.tsx, apps/desktop/src/renderer/features/bots/ChatReactionButton.tsx, apps/desktop/src/renderer/features/bots/ChatServerControls.tsx, apps/desktop/src/renderer/features/bots/ChatThreadPanel.tsx, apps/desktop/src/renderer/features/bots/CindyDevicePicker.tsx, apps/desktop/src/renderer/features/bots/CindyDeviceRow.tsx, apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx, apps/desktop/src/renderer/features/bots/CompanionShadowBanner.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSessionView.tsx, apps/desktop/src/renderer/features/bots/RemoteBotSettings.tsx, apps/desktop/src/renderer/features/bots/TeammateSearchResults.tsx, apps/desktop/src/renderer/features/bots/TeammatesSection.tsx, apps/desktop/src/renderer/features/bots/botAvatarIdentity.ts, apps/desktop/src/renderer/features/bots/botCapabilityDefaults.ts, apps/desktop/src/renderer/features/bots/botChatPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationPresentation.ts, apps/desktop/src/renderer/features/bots/botConversationTimeline.ts, apps/desktop/src/renderer/features/bots/botDelegationLive.ts, apps/desktop/src/renderer/features/bots/botFollowScopes.ts, apps/desktop/src/renderer/features/bots/botGeneratedArtifacts.ts, apps/desktop/src/renderer/features/bots/botGroupAttachments.ts, apps/desktop/src/renderer/features/bots/botGroupComposerChrome.ts, apps/desktop/src/renderer/features/bots/botGroupLane.ts, apps/desktop/src/renderer/features/bots/botGroupMentions.ts, apps/desktop/src/renderer/features/bots/botGroupOutbox.ts, apps/desktop/src/renderer/features/bots/botGroupPresentation.ts, apps/desktop/src/renderer/features/bots/botGroupStore.ts, apps/desktop/src/renderer/features/bots/botListDisplay.ts, apps/desktop/src/renderer/features/bots/botNavigation.ts, apps/desktop/src/renderer/features/bots/botPronounContext.tsx, apps/desktop/src/renderer/features/bots/botReadState.ts, apps/desktop/src/renderer/features/bots/botRosterDisplay.ts, apps/desktop/src/renderer/features/bots/botSessionOwners.ts, apps/desktop/src/renderer/features/bots/botSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/botStore.ts, apps/desktop/src/renderer/features/bots/botTodo.css, apps/desktop/src/renderer/features/bots/botWelcomeContext.ts, apps/desktop/src/renderer/features/bots/botWorkbenchProjection.ts, apps/desktop/src/renderer/features/bots/chatError.ts, apps/desktop/src/renderer/features/bots/cindyDeviceRoster.ts, apps/desktop/src/renderer/features/bots/companionCloudPresentation.ts, apps/desktop/src/renderer/features/bots/companionCloudStore.ts, apps/desktop/src/renderer/features/bots/remoteBotRoster.ts, apps/desktop/src/renderer/features/bots/remoteBotSettingsData.ts, apps/desktop/src/renderer/features/bots/teammatesSectionPrefs.ts, apps/desktop/src/renderer/features/bots/useBotGeneratedFileDeliveries.ts, apps/desktop/src/renderer/features/bots/useBotGroupMentionPicker.tsx, apps/desktop/src/renderer/features/bots/useBotIslandVisibleSession.ts, apps/desktop/src/renderer/features/bots/useBotSettingsAutosave.ts, apps/desktop/src/renderer/features/bots/useBotUnreadSync.ts, apps/desktop/src/renderer/features/bots/useRemoteBots.ts, apps/desktop/src/renderer/features/bots/useViewedBotSessionId.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionActions.ts, apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts, apps/desktop/src/renderer/features/bots/useWorkingStatusCopy.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx | 280 | 38 | 509 || `desktop.chat.files` | desktop | 工作目录文件浏览 | hash `/cc-agent/files/:sessionId`(WorkdirBrowseRoute) | FileBodyView, FileTreeView, WorkdirBrowseRoute | apps/desktop/src/renderer/features/cc-agent/workdir-browse/DocSearchBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/DrawioPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileBodyView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileFilterInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FileTreeView.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/FilterResultList.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/ImagePreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/OpenInSystemActions.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/PdfPreview.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/SessionTabsBar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/UnrenderablePlaceholder.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseRoute.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/WorkdirBrowseSidebar.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailCollapsed.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useChatRailResize.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useConfirmSwitchAwayIfDirty.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useDelayedFlag.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileContent.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useOpenTabs.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useProjectFileList.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useRevealFileInTree.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/activeFileBodyHandle.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/docModeSwitchProjects.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/drawioExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/expandedStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileContentCache.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileIcon.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileMeta.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileScrollStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/fileSelectionParams.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/filterFiles.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/imageExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/markdownAutosave.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/openTabsStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/pdfExt.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/lib/selectedFileStore.ts, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchInput.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchPanel.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/SearchResults.tsx, apps/desktop/src/renderer/features/cc-agent/workdir-browse/search/hooks/useProjectSearch.ts | 17 | 7 | 45 || `desktop.chat.new-draft` | desktop | 新建任务草稿页 | hash `/cc-agent/new`(NewMakerDraftRoute) | NewMakerDraftRoute | apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx | 15 | 0 | 3 || `desktop.chat.orca-workflow` | desktop | Orca 协同工作台 | hash `/cc-agent/orca/:sessionId`(OrcaWorkflowRoute) | CCAgentSessionView, OrcaSplitView, OrcaWorkerPanel, OrcaWorkflowRoute | apps/desktop/src/renderer/components/chat/AgentActionRow.tsx, apps/desktop/src/renderer/components/chat/AgentActionsBlock.tsx, apps/desktop/src/renderer/components/chat/AgentOnOtherDeviceContext.tsx, apps/desktop/src/renderer/components/chat/AgentTaskCard.tsx, apps/desktop/src/renderer/components/chat/AgentTaskLiveDetails.tsx, apps/desktop/src/renderer/components/chat/AnnotationStrokesSvg.tsx, apps/desktop/src/renderer/components/chat/AskUserQuestionBubble.tsx, apps/desktop/src/renderer/components/chat/AssistantMessage.tsx, apps/desktop/src/renderer/components/chat/AutomationOriginBadge.tsx, apps/desktop/src/renderer/components/chat/ChatAudioCard.tsx, apps/desktop/src/renderer/components/chat/ChatDisplaySnapshotContext.tsx, apps/desktop/src/renderer/components/chat/ChatImageView.tsx, apps/desktop/src/renderer/components/chat/ChatLoadingImage.tsx, apps/desktop/src/renderer/components/chat/ChatSessionFileContext.tsx, apps/desktop/src/renderer/components/chat/ChatSoundEffectCard.tsx, apps/desktop/src/renderer/components/chat/ChatVideoView.tsx, apps/desktop/src/renderer/components/chat/CindyMakeDoctorCard.tsx, apps/desktop/src/renderer/components/chat/CopyAsImageBlock.tsx, apps/desktop/src/renderer/components/chat/CredentialSwitchWaitBanner.tsx, apps/desktop/src/renderer/components/chat/DiffView.tsx, apps/desktop/src/renderer/components/chat/ErrorBanner.tsx, apps/desktop/src/renderer/components/chat/ErrorMessageCard.tsx, apps/desktop/src/renderer/components/chat/GeneratedFilesCard.tsx, apps/desktop/src/renderer/components/chat/GhostCardHostPrompts.tsx, apps/desktop/src/renderer/components/chat/GhostSummonCard.tsx, apps/desktop/src/renderer/components/chat/GhostToolCard.tsx, apps/desktop/src/renderer/components/chat/HookTaskCard.tsx, apps/desktop/src/renderer/components/chat/ImageGalleryContext.tsx, apps/desktop/src/renderer/components/chat/ImageHoverPreview.tsx, apps/desktop/src/renderer/components/chat/ImageLightbox.tsx, apps/desktop/src/renderer/components/chat/ImageMissingPlaceholder.tsx, apps/desktop/src/renderer/components/chat/InlineReferenceChip.tsx, apps/desktop/src/renderer/components/chat/InterruptedTurnBanner.tsx, apps/desktop/src/renderer/components/chat/JumpToBottomChip.tsx, apps/desktop/src/renderer/components/chat/MarkdownDiffBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownMermaidBlock.tsx, apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx, apps/desktop/src/renderer/components/chat/MermaidLightbox.tsx, apps/desktop/src/renderer/components/chat/MessageActionBar.tsx, apps/desktop/src/renderer/components/chat/MessageNavRail.tsx, apps/desktop/src/renderer/components/chat/MessageSourceLabels.tsx, apps/desktop/src/renderer/components/chat/MessageStream.tsx, apps/desktop/src/renderer/components/chat/MessageViewport.tsx, apps/desktop/src/renderer/components/chat/ModelLightbox.tsx, apps/desktop/src/renderer/components/chat/NewMessageIndicator.tsx, apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx, apps/desktop/src/renderer/components/chat/PrevMessageJumpChip.tsx, apps/desktop/src/renderer/components/chat/ProjectLinkChip.tsx, apps/desktop/src/renderer/components/chat/QuoteChip.tsx, apps/desktop/src/renderer/components/chat/RewindPreviewDialog.tsx, apps/desktop/src/renderer/components/chat/SelectionQuoteButton.tsx, apps/desktop/src/renderer/components/chat/SentAgentReferenceChip.tsx, apps/desktop/src/renderer/components/chat/SentInlineAtomBody.tsx, apps/desktop/src/renderer/components/chat/SessionHandoffCard.tsx, apps/desktop/src/renderer/components/chat/SessionLinkChip.tsx, apps/desktop/src/renderer/components/chat/ShareMessageCheckbox.tsx, apps/desktop/src/renderer/components/chat/ShareSelectionBar.tsx, apps/desktop/src/renderer/components/chat/SlackIcon.tsx, apps/desktop/src/renderer/components/chat/StreamFadeSpan.tsx, apps/desktop/src/renderer/components/chat/StreamingMarkdownChunk.tsx, apps/desktop/src/renderer/components/chat/SystemCard.tsx, apps/desktop/src/renderer/components/chat/TextLightbox.tsx, apps/desktop/src/renderer/components/chat/ThinkingCard.tsx, apps/desktop/src/renderer/components/chat/ThinkingText.tsx, apps/desktop/src/renderer/components/chat/TodoListCard.tsx, apps/desktop/src/renderer/components/chat/ToolCallCard.tsx, apps/desktop/src/renderer/components/chat/ToolPayloadLightbox.tsx, apps/desktop/src/renderer/components/chat/TopRightChipStack.tsx, apps/desktop/src/renderer/components/chat/TurnChangesCard.tsx, apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx, apps/desktop/src/renderer/components/chat/UpgradeBanner.tsx, apps/desktop/src/renderer/components/chat/UserAttachmentChip.tsx, apps/desktop/src/renderer/components/chat/UserMessage.tsx, apps/desktop/src/renderer/components/chat/UserMessageEditBox.tsx, apps/desktop/src/renderer/components/chat/UserMessageUrlLink.tsx, apps/desktop/src/renderer/components/chat/VideoLightbox.tsx, apps/desktop/src/renderer/components/chat/WorkGroupBlock.tsx, apps/desktop/src/renderer/components/chat/WorktreeRestoreBanner.tsx, apps/desktop/src/renderer/components/chat/XIcon.tsx, apps/desktop/src/renderer/components/chat/activityRowChrome.ts, apps/desktop/src/renderer/components/chat/animateFocusScroll.ts, apps/desktop/src/renderer/components/chat/autoFollowIntent.ts, apps/desktop/src/renderer/components/chat/chatChrome.ts, apps/desktop/src/renderer/components/chat/errorReasonI18n.ts, apps/desktop/src/renderer/components/chat/generatedFilesProjection.ts, apps/desktop/src/renderer/components/chat/imageDisplaySize.ts, apps/desktop/src/renderer/components/chat/lightboxAnnotations.ts, apps/desktop/src/renderer/components/chat/lightboxGestures.ts, apps/desktop/src/renderer/components/chat/markdownImageTargets.ts, apps/desktop/src/renderer/components/chat/markdownMedia.ts, apps/desktop/src/renderer/components/chat/messageNavRailModel.ts, apps/desktop/src/renderer/components/chat/messageNavRailWheel.ts, apps/desktop/src/renderer/components/chat/messageNavigationProjection.ts, apps/desktop/src/renderer/components/chat/messageProjectionCache.ts, apps/desktop/src/renderer/components/chat/messageStreamIndicatorPosition.ts, apps/desktop/src/renderer/components/chat/messageViewportCompensation.ts, apps/desktop/src/renderer/components/chat/messageViewportGeometry.ts, apps/desktop/src/renderer/components/chat/messageWorkGroups.ts, apps/desktop/src/renderer/components/chat/observeProgrammaticScroll.ts, apps/desktop/src/renderer/components/chat/rehypeFencedCodeMarker.ts, apps/desktop/src/renderer/components/chat/rehypeHighlightShared.ts, apps/desktop/src/renderer/components/chat/rehypeMathBlockMarker.ts, apps/desktop/src/renderer/components/chat/rehypeStreamWordFade.ts, apps/desktop/src/renderer/components/chat/remarkHtmlImages.ts, apps/desktop/src/renderer/components/chat/remarkLocalPathLinks.ts, apps/desktop/src/renderer/components/chat/remarkPreserveRawLocalDestinations.ts, apps/desktop/src/renderer/components/chat/remarkSessionLinks.ts, apps/desktop/src/renderer/components/chat/remarkStrictInlineMath.ts, apps/desktop/src/renderer/components/chat/remarkTruncateCjkUrls.ts, apps/desktop/src/renderer/components/chat/repairStreamingMarkdown.ts, apps/desktop/src/renderer/components/chat/scrollAnchoringDetect.ts, apps/desktop/src/renderer/components/chat/shareSelectionStore.ts, apps/desktop/src/renderer/components/chat/streamingMarkdownBlocks.tsx, apps/desktop/src/renderer/components/chat/streamingMarkdownChunks.ts, apps/desktop/src/renderer/components/chat/streamingMessageProjection.ts, apps/desktop/src/renderer/components/chat/toolLoopI18n.ts, apps/desktop/src/renderer/components/chat/unreadCount.ts, apps/desktop/src/renderer/components/chat/useAutomaticHistoryLoadBudget.ts, apps/desktop/src/renderer/components/chat/useCopyAsImage.tsx, apps/desktop/src/renderer/components/chat/useDeleteMessage.ts, apps/desktop/src/renderer/components/chat/useFileChipContextMenu.tsx, apps/desktop/src/renderer/components/chat/useForkAtMessage.ts, apps/desktop/src/renderer/components/chat/useImageClipboard.ts, apps/desktop/src/renderer/components/chat/useImageLoadFailure.ts, apps/desktop/src/renderer/components/chat/useMessageViewport.ts, apps/desktop/src/renderer/components/chat/useNavigationKeyListener.ts, apps/desktop/src/renderer/components/chat/useOpenWithMenu.tsx, apps/desktop/src/renderer/components/chat/usePrevUserMessageInView.ts, apps/desktop/src/renderer/components/chat/useTurnChangeSets.ts, apps/desktop/src/renderer/components/chat/userMessageCollapse.ts, apps/desktop/src/renderer/components/chat/userMessageDisplayText.ts, apps/desktop/src/renderer/components/chat/userMessageLinkify.ts, apps/desktop/src/renderer/components/chat/viewportFillDetect.ts, apps/desktop/src/renderer/components/new-chat/AddRemoteProjectDialog.tsx, apps/desktop/src/renderer/components/new-chat/AgentSelect.tsx, apps/desktop/src/renderer/components/new-chat/AskUserQuestionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/AtMentionPanel.tsx, apps/desktop/src/renderer/components/new-chat/AttachmentTypeThumb.tsx, apps/desktop/src/renderer/components/new-chat/ChatInput.tsx, apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts, apps/desktop/src/renderer/components/new-chat/CjkPunctuationUtils.ts, apps/desktop/src/renderer/components/new-chat/ComposerAttachments.tsx, apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts, apps/desktop/src/renderer/components/new-chat/ComposerListNodes.ts, apps/desktop/src/renderer/components/new-chat/ComposerQuoteNode.tsx, apps/desktop/src/renderer/components/new-chat/DeviceSwitcherPill.tsx, apps/desktop/src/renderer/components/new-chat/EffortSlider.tsx, apps/desktop/src/renderer/components/new-chat/EmptyDocSelectionGuard.ts, apps/desktop/src/renderer/components/new-chat/ExtraDirsButton.tsx, apps/desktop/src/renderer/components/new-chat/FastModeToggle.tsx, apps/desktop/src/renderer/components/new-chat/FolderPickerPopover.tsx, apps/desktop/src/renderer/components/new-chat/FullAccessConfirmContent.tsx, apps/desktop/src/renderer/components/new-chat/GhostCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/GoalAdvancedLimits.tsx, apps/desktop/src/renderer/components/new-chat/GoalIndicator.tsx, apps/desktop/src/renderer/components/new-chat/HomeUsageDashboard.tsx, apps/desktop/src/renderer/components/new-chat/ListComposerTextarea.tsx, apps/desktop/src/renderer/components/new-chat/LocalModelCatalogNotice.tsx, apps/desktop/src/renderer/components/new-chat/MentionChipNode.tsx, apps/desktop/src/renderer/components/new-chat/MentionDragCaretDecoration.ts, apps/desktop/src/renderer/components/new-chat/ModelCompatibilityNotice.tsx, apps/desktop/src/renderer/components/new-chat/ModelConfigFlyout.tsx, apps/desktop/src/renderer/components/new-chat/ModelHarnessPicker.tsx, apps/desktop/src/renderer/components/new-chat/ModelSelector.tsx, apps/desktop/src/renderer/components/new-chat/ModelSourceDetails.tsx, apps/desktop/src/renderer/components/new-chat/NewGoalDialog.tsx, apps/desktop/src/renderer/components/new-chat/PastedTextChipNode.tsx, apps/desktop/src/renderer/components/new-chat/PendingQueuePanel.tsx, apps/desktop/src/renderer/components/new-chat/PermissionPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PermissionSelector.tsx, apps/desktop/src/renderer/components/new-chat/PinnedPlanPanel.tsx, apps/desktop/src/renderer/components/new-chat/PlanActionCard.tsx, apps/desktop/src/renderer/components/new-chat/PlanModeIndicator.tsx, apps/desktop/src/renderer/components/new-chat/PlanViewerCard.tsx, apps/desktop/src/renderer/components/new-chat/PluginConnectionForm.tsx, apps/desktop/src/renderer/components/new-chat/PluginOauthDeviceCode.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupPrompt.tsx, apps/desktop/src/renderer/components/new-chat/PluginSetupRemoteDesktopButton.tsx, apps/desktop/src/renderer/components/new-chat/PluginWriteAccessRecovery.tsx, apps/desktop/src/renderer/components/new-chat/QuickStartPillMark.ts, apps/desktop/src/renderer/components/new-chat/RemoteOauthSetupCard.tsx, apps/desktop/src/renderer/components/new-chat/SendButton.tsx, apps/desktop/src/renderer/components/new-chat/SlashCommandDecoration.ts, apps/desktop/src/renderer/components/new-chat/SlashCommandPalette.tsx, apps/desktop/src/renderer/components/new-chat/TakeoverMask.tsx, apps/desktop/src/renderer/components/new-chat/ThinkingToggle.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedFlyoutHost.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelPanel.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRail.tsx, apps/desktop/src/renderer/components/new-chat/UnifiedModelRow.tsx, apps/desktop/src/renderer/components/new-chat/UsageDailyBars.tsx, apps/desktop/src/renderer/components/new-chat/UsageHeatmap.tsx, apps/desktop/src/renderer/components/new-chat/VendorSegmentedSwitcher.tsx, apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts, apps/desktop/src/renderer/components/new-chat/WindowsSelectionReplacement.ts, apps/desktop/src/renderer/components/new-chat/WorktreeChipsRow.tsx, apps/desktop/src/renderer/components/new-chat/WorktreeCreatingOverlay.tsx, apps/desktop/src/renderer/components/new-chat/agentOptions.ts, apps/desktop/src/renderer/components/new-chat/agentSwitchConfirmation.ts, apps/desktop/src/renderer/components/new-chat/branchPick.ts, apps/desktop/src/renderer/components/new-chat/composerBlankPointerFocus.ts, apps/desktop/src/renderer/components/new-chat/composerContentSerialization.ts, apps/desktop/src/renderer/components/new-chat/composerDocState.ts, apps/desktop/src/renderer/components/new-chat/composerFrameScheduler.ts, apps/desktop/src/renderer/components/new-chat/composerHistoryProjection.ts, apps/desktop/src/renderer/components/new-chat/composerModelSelection.ts, apps/desktop/src/renderer/components/new-chat/composerPromptRecommendation.ts, apps/desktop/src/renderer/components/new-chat/composerRenderGate.ts, apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts, apps/desktop/src/renderer/components/new-chat/composerSendSnapshot.ts, apps/desktop/src/renderer/components/new-chat/effortChangeQueue.ts, apps/desktop/src/renderer/components/new-chat/extraDirsActions.ts, apps/desktop/src/renderer/components/new-chat/ghostComposerPlacement.ts, apps/desktop/src/renderer/components/new-chat/localAttachmentPicker.ts, apps/desktop/src/renderer/components/new-chat/mentionChipInsertion.ts, apps/desktop/src/renderer/components/new-chat/modelWindowErrorToast.ts, apps/desktop/src/renderer/components/new-chat/pastePipeline.ts, apps/desktop/src/renderer/components/new-chat/pathPaste.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueLocks.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowActivity.ts, apps/desktop/src/renderer/components/new-chat/pendingQueueRowPresentation.ts, apps/desktop/src/renderer/components/new-chat/planModeComposerCommand.ts, apps/desktop/src/renderer/components/new-chat/priceTierMarks.tsx, apps/desktop/src/renderer/components/new-chat/remoteBrowseAdapters.ts, apps/desktop/src/renderer/components/new-chat/remoteExistingProjects.ts, apps/desktop/src/renderer/components/new-chat/restoreComposerDocument.ts, apps/desktop/src/renderer/components/new-chat/sessionLinkPaste.ts, apps/desktop/src/renderer/components/new-chat/sourceSwitch.ts, apps/desktop/src/renderer/components/new-chat/unifiedModelSelection.ts, apps/desktop/src/renderer/components/new-chat/usagePalette.ts, apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts, apps/desktop/src/renderer/components/new-chat/useModelDiscoveryPending.ts, apps/desktop/src/renderer/components/new-chat/useProviderWeeklyQuota.ts, apps/desktop/src/renderer/components/new-chat/useUnifiedRowActions.ts, apps/desktop/src/renderer/features/cc-agent/CCAgentFeatureLayout.tsx, apps/desktop/src/renderer/features/cc-agent/CCAgentSessionView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaSplitView.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkerPanel.tsx, apps/desktop/src/renderer/features/cc-agent/OrcaWorkflowRoute.tsx | 249 | 38 | 337 |diff --cc docs/product-rules/bot-group-chat.mdindex 1cde239c5e,50dd8c89ca..96ed410da2--- a/docs/product-rules/bot-group-chat.md+++ b/docs/product-rules/bot-group-chat.md@@@ -178,31 -176,13 +178,31 @@@- 群聊行与伙伴私聊混排在侧栏「伙伴」段(置顶上方,与任务列表共用一个侧栏,见[cindy-bots-runtime.md](cindy-bots-runtime.md#导航未读与系统角标));段头加号提供新建伙伴与新建群聊。群行显示两位成员的叠放头像、群名与最近一条消息,- 有伙伴正在发言时显示运行中标记。-- 群聊页:顶部为成员头像、群名与成员名单,右侧为群设置入口。时间线中用户消息靠右;伙伴消息左侧显示头像、- 名字与内容。正在发言的伙伴显示运行中状态,同时想时每位各占一行;输入框在本轮进行中提供停止。-- 输入框支持 @ 伙伴,候选第一项为「所有人」;支持附件(见 3.1)。服务器群的 Thread 回复框使用同一套 @ 候选- (`useBotGroupMentionPicker`):候选、筛选、键盘与鼠标选择、Esc 收起和同名伙伴按选中身份区分都与主群一致;候选与点名解析都不含当前用户自己(与手机一致)。+ 有伙伴正在发言时显示运行中标记。未读角标是真实条数:宿主随摘要给出最近(至多 99 条)别人发来的消息时间+ (`incomingMessageTimes`),与本机读位比较;旧宿主没有这份列表时只显示 1。伙伴发的安排卡与回复同样算来信:+ 本机群的 `lastReplyAt` 取两者里最新的一条,首次种读位时不会把最新的安排卡留成未读。+- 群聊页(2026-10-15 按 Telegram / Slack 的密度重做):顶部为成员头像、群名、成员名单(负责人带标)与此刻谁在做什么+ (「X 正在做第 2 步」「X 正在说…」「X 正在安排…」),右侧为群设置入口。时间线:自己的消息靠右浅色气泡;+ 伙伴与别人的消息靠左平铺(28px 头像 + 名字 + 时刻),同一作者五分钟内的连续消息合并——后续行不再带头像和名字,+ 时刻只在悬停时出现在左侧槽位;每个自然日一条吸顶的日期分隔(今天 / 昨天 / 短日期);消息操作栏(复制、分享、+ 引用回复、话题、表情、时间)悬停时浮在右上角,键盘聚焦与触屏时常显;@ 点名在所有消息里高亮;引用块在正文上方,+ 表情回应在正文下方;轮次结束、分工结束与系统提示是居中的一行小字。多人群里别人带来的伙伴显示「伙伴名 (主人昵称)」,+ 人类成员名字旁带「某某的主人」。+- 进行中:正在发言的伙伴在时间线末尾一行「X 正在想…」,本机能读到流式正文时下面跟最后两行;分工某一步在做,+ 或某位伙伴说了超过三秒时,输入框上方出现固定的进行中条(不随时间线滚走):「第 k/n 步 · 谁 做什么 · 已做多久 ·+ 当前动作」,带「看过程」(本机能读到这条专线时)与「停止」;分工进行中它替代时间线末尾的发言行,等确认的卡仍在时间线里。+- 输入框支持 @ 伙伴,候选第一项为「所有人」;支持附件(见 3.1)。服务器群的话题回复用同一个输入框的话题模式,@ 候选也是+ 同一套(`useBotGroupMentionPicker`):候选、筛选、键盘与鼠标选择、Esc 收起和同名伙伴按选中身份区分都与主群一致;候选与点名+ 解析都不含当前用户自己(与手机一致)。草稿随群持久(切走再回来文字还在,群被删除时丢弃)。- 发送是乐观的:按下发送自己的消息立刻出现在末尾(发送中略淡),宿主回包后原地换成正式那条,失败就撤掉、草稿放回。++ 发送是乐观的:按下发送自己的消息立刻出现(发送中略淡),宿主回包后原地换成正式那条。主群复用第 10 节的发件箱,失败时只放回空输入框,否则保留失败消息供重试或编辑;话题失败撤掉本地副本并恢复草稿。+- 不跳、不卡:宿主对同一群的变更通知合并成一次(150ms 窗口)、Renderer 同一时刻只读一次并把最新页**并入**屏幕上已有的消息+ (被挤出最新页的旧消息留着)、内容没变的消息沿用原对象不重绘;发送用实时订阅担保的最近快照(30 秒内),侧栏摘要按群的+ 变更头复用;自动分工判断整体不超过 8 秒(单候选 5 秒),超时按「不要」处理,不让第一条回复等它。- 新建群聊:填写群名称,选择 2–6 位伙伴。- 群设置:群名称、成员(添加与移出、设为负责人)、项目文件夹、「没有 @ 人的时候」回复方式、「发言方式」(自动/始终轮流)、删除群聊(二次确认)。+ 本地群与服务器群的这几项用同一套文案。+- 话题面板与主时间线同一套消息样式(合并、悬停操作、@ 高亮、引用块、附件),同一个输入框(话题模式:没有「+」菜单、+ 附件与引用,发送键是「发送回复」,失败原因写在输入框上方,同一段文字重发沿用同一个 clientId)。- 视觉遵循 [`DESIGN.md`](../design-rules/DESIGN.md);Light 与 Dark 同时实现。## 6. 本地旧群的限制(服务器群见第 10 节)@@@ -400,6 -376,8 +400,8 @@@ Chris 已明确扩展到多人各带伙同一草稿的点名目标 ID、顺序或所有人标记变化,即使显示名字与正文没变,也必须使用新的 `clientId`。只有正文、点名目标、分工标记和附件均不变时,失败重试才复用原发送尝试。-Desktop 主群输入框发送即乐观显示:点发送后消息立即接在时间线末尾,输入框与托盘马上空出,可以接着发下一条;同一个群的提交按发出顺序逐条交给 main,慢于 0.6 秒才在气泡下显示「发送中…」。回执的 `messageId` 是替换依据:时间线读到该消息即换成真实消息,回执之后开始的重读没读到也视为已进历史;推送重读先于回执到达时,只对正在提交的那一条按「基线之后、未被回执认领、正文与附件数一致的自己的消息」做显示去重,最终仍以 `messageId` 为准。附件按输入生成临时列表;带手绘标注的图片入队即烧录,完成后气泡改用烧录后的本地预览,提交与重试复用同一份烧录结果,放回输入框的仍是带笔迹的原件;入队烧录失败即这条消息失败,轮到它时不自动再烧,用户「重试」或编辑后重新发送才重新烧录。真实消息到达而服务器副本尚未可用(无 url / path,或旧版尚未列出)时,在同一 `messageId` 内配对:数量一致按发送顺序;副本按下载完成先后逐个列出、数量不一致时,只有名字(烧录后的名字)在这条消息里唯一的附件按名字配对,重名的附件分不出谁是谁,继续显示各自的本地预览、对应副本暂不单独显示,直到数量一致再按顺序替换;不退成缺失、不重复、同名文件不互换。离开输入框、尚未确认的图片(含标注原图与烧录副本)登记进存储清理的保护清单直到条目释放,已确认消息的本地预览不登记(发送时 main 已在群的 `bot-group-attachment` 引用下固定);本地预览按已加载的全部时间线(含更早的页)结算,不设条数上限,消息被删除(含在其他设备上删除)即撤下其本地预览;尚未进入消息的暂存文件按归属回收:还没开始提交的条目(排队中、已失败)归发件箱,群被删除(包括不在当前页、从列表消失且读取确认 `NOT_FOUND` 的群;读取不确定时在 5 秒、30 秒、2 分钟后各重试一次,群回到列表或读到仍存在即停止)时立即回收;已开始提交的条目归它的那次请求——烧录期间被丢弃的不再发出并回收,已交给 main 的等 main 答复,成功(已进入消息)不回收,失败或调用异常才回收(main 在答复前读完本地文件,失败时不留引用暂存路径的本地记录)。切换账号时发件箱同样发出回收,但 main 只删当前账号暂存目录里的副本,renderer 看到切换时 main 已在新账号(或边界)下,所以前一账号的暂存副本留在它自己的目录里,不在发件箱范围内。发送失败绝不自动重发:输入框为空(无文字、附件、分工标签)时把正文、点名、标签与附件原样放回并提示原因,再发沿用原 `clientId`;输入框已有新内容时消息留在时间线上显示「没发出去」(待发与失败的消息都排在按下发送时时间线已有的消息之后,之后到达的消息排在它下面,不会被挤到末尾;比它先发出、已出现在时间线上的自己的消息始终排在它上面),可「重试」(同一 `clientId`)或在输入框清空后「编辑」放回;main 拒绝的是消息内容本身时(引用原消息或点名对象已不可用、字段或附件无效:`QUOTE_UNAVAILABLE` / `MENTION_UNAVAILABLE` / `INVALID_PARAMS` / `INVALID_ATTACHMENT` / `ATTACHMENT_TOO_LARGE`),原样重发只会再次失败,只提供「编辑」;失败时输入框不在(切到别的群、分享模式),回到该群时同样放回空输入框并提示原因。「引用回复」随消息进入发件箱:待发气泡上方显示同一个引用块,引用是发送输入的一部分(换引用即换 `clientId`);失败放回时引用只随它自己的正文放回(期间已另选引用的以新选为准),原消息不可用(`QUOTE_UNAVAILABLE`)时只放回正文。发件箱原样保存并发出完整发送输入(附件入队即开始烧录标注,提交时序列化),首发与重试不挑字段;除 `clientId` 外的全部字段与附件共同决定能否复用原 `clientId`,新增发送字段无需改动发件箱。发件箱只在 renderer 内存中保留,切群后仍按群隔离(以 main 返回的群 ID 为准,从旧的本地路由打开已迁移到 Chat Server 的群时同样),切换到另一个账号时清空(同账号的 generation 修复、认证边界短暂的 null 不清空)、删群丢弃,不持久化。Thread 回复与手机端仍是等待回执后显示。实现见 `renderer/features/bots/botGroupOutbox.ts`,回归见 `botGroupOutbox.test.ts` 与 `BotGroupChatView.test.tsx`。++Desktop 主群输入框发送即乐观显示:点发送后消息立即接在时间线末尾,输入框与托盘马上空出,可以接着发下一条;同一个群的提交按发出顺序逐条交给 main,慢于 0.6 秒才在气泡下显示「发送中…」。回执的 `messageId` 是替换依据:时间线读到该消息即换成真实消息,回执之后开始的重读没读到也视为已进历史;推送重读先于回执到达时,只对正在提交的那一条按「基线之后、未被回执认领、正文与附件数一致的自己的消息」做显示去重,最终仍以 `messageId` 为准。附件按输入生成临时列表;带手绘标注的图片入队即烧录,完成后气泡改用烧录后的本地预览,提交与重试复用同一份烧录结果,放回输入框的仍是带笔迹的原件;入队烧录失败即这条消息失败,轮到它时不自动再烧,用户「重试」或编辑后重新发送才重新烧录。真实消息到达而服务器副本尚未可用(无 url / path,或旧版尚未列出)时,在同一 `messageId` 内配对:数量一致按发送顺序;副本按下载完成先后逐个列出、数量不一致时,只有名字(烧录后的名字)在这条消息里唯一的附件按名字配对,重名的附件分不出谁是谁,继续显示各自的本地预览、对应副本暂不单独显示,直到数量一致再按顺序替换;不退成缺失、不重复、同名文件不互换。离开输入框、尚未确认的图片(含标注原图与烧录副本)登记进存储清理的保护清单直到条目释放,已确认消息的本地预览不登记(发送时 main 已在群的 `bot-group-attachment` 引用下固定);本地预览按已加载的全部时间线(含更早的页)结算,不设条数上限,消息被删除(含在其他设备上删除)即撤下其本地预览;尚未进入消息的暂存文件按归属回收:还没开始提交的条目(排队中、已失败)归发件箱,群被删除(包括不在当前页、从列表消失且读取确认 `NOT_FOUND` 的群;读取不确定时在 5 秒、30 秒、2 分钟后各重试一次,群回到列表或读到仍存在即停止)时立即回收;已开始提交的条目归它的那次请求——烧录期间被丢弃的不再发出并回收,已交给 main 的等 main 答复,成功(已进入消息)不回收,失败或调用异常才回收(main 在答复前读完本地文件,失败时不留引用暂存路径的本地记录)。切换账号时发件箱同样发出回收,但 main 只删当前账号暂存目录里的副本,renderer 看到切换时 main 已在新账号(或边界)下,所以前一账号的暂存副本留在它自己的目录里,不在发件箱范围内。发送失败绝不自动重发:输入框为空(无文字、附件、分工标签)时把正文、点名、标签与附件原样放回并提示原因,再发沿用原 `clientId`;输入框已有新内容时消息留在时间线上显示「没发出去」(待发与失败的消息都排在按下发送时时间线已有的消息之后,之后到达的消息排在它下面,不会被挤到末尾;比它先发出、已出现在时间线上的自己的消息始终排在它上面),可「重试」(同一 `clientId`)或在输入框清空后「编辑」放回;main 拒绝的是消息内容本身时(引用原消息或点名对象已不可用、字段或附件无效:`QUOTE_UNAVAILABLE` / `MENTION_UNAVAILABLE` / `INVALID_PARAMS` / `INVALID_ATTACHMENT` / `ATTACHMENT_TOO_LARGE`),原样重发只会再次失败,只提供「编辑」;失败时输入框不在(切到别的群、分享模式),回到该群时同样放回空输入框并提示原因。「引用回复」随消息进入发件箱:待发气泡上方显示同一个引用块,引用是发送输入的一部分(换引用即换 `clientId`);失败放回时引用只随它自己的正文放回(期间已另选引用的以新选为准),原消息不可用(`QUOTE_UNAVAILABLE`)时只放回正文。发件箱原样保存并发出完整发送输入(附件入队即开始烧录标注,提交时序列化),首发与重试不挑字段;除 `clientId` 外的全部字段与附件共同决定能否复用原 `clientId`,新增发送字段无需改动发件箱。发件箱只在 renderer 内存中保留,切群后仍按群隔离(以 main 返回的群 ID 为准,从旧的本地路由打开已迁移到 Chat Server 的群时同样),切换到另一个账号时清空(同账号的 generation 修复、认证边界短暂的 null 不清空)、删群丢弃,不持久化。Thread 回复同样立即显示本地副本,但不进入主群发件箱;手机端仍是等待回执后显示。实现见 `renderer/features/bots/botGroupOutbox.ts`,回归见 `botGroupOutbox.test.ts` 与 `BotGroupChatView.test.tsx`。+完成全部显式目标校验后,最终点名列表继续沿用排除当前用户自己的既有规则;主群、Thread 与手机直连均一致,不因显式列表或所有人标记改变。手机直连入口同样在发送前读取已加入成员、校验全部显式目标,再展开所有人。点名失效沿用本地化提示和草稿恢复,不把群页标为离线;重选当前成员后可以立即继续发送。回归见 `chatServerMobileEntry.test.tsx` 与 `BotGroupChatScreen.test.tsx`。