Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge task route recovery and validate companion note length
Chris365af8f87ae0
diff --cc apps/desktop/src/main/maker-ipc/botDelegationService.tsindex 5196001f1f,7d302e439d..1b7f00c64f--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@@ -47,7 -47,7 +47,7 @@@ import typeBotCollaborationRole,BotDelegationInterjectResult,} from '../../shared/botCollaboration.js';- import { BOT_DELEGATION_CLIENT_ID, botInterjectionPreview } from '../../shared/botCollaboration.js';-import { BOT_DELEGATION_CLIENT_ID } from '../../shared/botCollaboration.js';++import { BOT_DELEGATION_CLIENT_ID, BOT_INTERJECTION_MAX_CHARS as MAX_INTERJECTION_CHARS, botInterjectionPreview } from '../../shared/botCollaboration.js';import { buildBotGroupTaskCard, type BotGroupTaskCardLabels, type BotGroupTaskCardState } from '../../shared/botGroupChat.js';import { t } from '../i18n.js';import type { BotGroupTaskPostInput, BotGroupTaskPostResult } from './botGroupChatService.js';@@@ -59,8 -59,8 +59,6 @@@ import { readBotTaskModelOverride, typimport { validateTaskModel, resolveTaskModelSelection, type TaskModelSelection } from './appDefaultModelControl.js';const ACTIVE_DELEGATION_STATUSES = ['queued', 'running', 'waiting'] as const;--/** 一条补充消息的正文上限:够写清「先别做 X,改做 Y」,又不至于变成另一项任务。 */--const MAX_INTERJECTION_CHARS = 4_000;const DEFAULT_MAX_DEPTH = 1;const DEFAULT_MAX_ACTIVE_CHILDREN = 10;const DEFAULT_TIMEOUT_MS = 30 * 60_000;diff --cc apps/desktop/src/main/maker-ipc/chatServer.tsindex 01f46ce81c,67c78a053a..bdafe28643--- a/apps/desktop/src/main/maker-ipc/chatServer.ts+++ b/apps/desktop/src/main/maker-ipc/chatServer.ts@@@ -596,22 -495,25 +596,31 @@@ function createChatServer(local: BotGroconst mirrors = new Set(links.flatMap(link => /^group:([^:]+):access:/.exec(link.routeKey ?? '')?.[1] ?? []));return result.groups.filter(group => !mirrors.has(group.id) && !workspaces().read(group.id));}+ /**+ * Final group → room answers of this account/endpoint: a server room stays a server room and an+ * upgraded history keeps its room. A pending upgrade is never cached, so it is asked again.+ */+ const resolvedGroups = new Map<string, string>();/**- * The server room a task started from `groupId` posts into, without touching the network:- * the upgraded room of an old local group, or the id itself for a server room. `null` is an old- * local group that has no room (yet): its local history row exists and is still a local source.+ * The server room a task started from `groupId` posts into: the upgraded room of an old+ * local group, or the id itself for a server room. Before returning `null` for a local source,+ * recover its account-scoped migration receipt; background migration may not have run yet.*/const taskRoomFor = async (groupId: string): Promise<string | null> => {- if (upgradedGroups.has(groupId)) return upgradedGroups.get(groupId)!;+ const known = resolvedGroups.get(groupId) ?? upgradedGroups.get(groupId);+ if (known) return known;if (!id.safeParse(groupId).success) return null;const [localRow] = await getDbClient().drizzle.select({ id: botGroups.id }).from(botGroups).where(eq(botGroups.id, groupId)).limit(1);- if (localRow && (await localSources()).some(group => group.id === groupId)) return null;+ if (localRow && (await localSources()).some(group => group.id === groupId)) {+ // Registration identifies the receipt's actor/endpoint scope. Transient failure leaves delivery+ // retryable rather than permanently falling back to private chat before we know the route.+ await register();+ if (upgradedGroups.has(groupId)) return upgradedGroups.get(groupId)!;+ const receipt = chatMigrationReceipts(config.baseUrl, selfId, current).read(groupId);+ if (!receipt) return null;+ upgradedGroups.set(groupId, receipt.roomId);+ return receipt.roomId;+ }return groupId;};const resolveGroup = async (groupId: string) => {diff --cc apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsxindex 7c4b528249,0547633b91..3ee545bd86--- a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx@@@ -1,39 -1,8 +1,39 @@@-import { Megaphone } from 'lucide-react';+import { useEffect, useId, useState, type ReactNode } from 'react';+import {+ ChevronDown,+ ChevronUp,+ Eye,+ FileText,+ GitPullRequest,+ Megaphone,+ Square,+ SquareArrowOutUpRight,+ TriangleAlert,+} from 'lucide-react';import { useTranslation } from 'react-i18next';++import { MAX_STATUS_QUERIES, prStatusKey, sessionPrUrl } from '@cindy/maker-shared';+import { useElementVisible } from '@/cindy-brain/ghostUnreadStore';+import {+ ChatSessionFileProvider,+ useChatSessionFile,+} from '@/components/chat/ChatSessionFileContext';+import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';+import { Spinner } from '@/components/ui/spinner';+import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';+import { usePrActions, usePrRefsForSession, usePrStatuses } from '@/contexts/PrRefsContext';+import { PR_STATUS_COLOR, PR_STATUS_ICON } from '@/features/cc-agent/gitContextPrVisuals';+import { makerChatStore } from '@/lib/makerChatStore';+import { makerApiForSticky } from '@/lib/makerTransport';+import * as sessionService from '@/lib/sessionService';+import { toast } from '@/lib/toast';+import { cn } from '@/lib/utils';+import { readWorkingPhase, WORKING_PHASE_KEYS } from '../../../shared/workingStatus';import type { BotCollaborationMeta } from '../../../shared/botCollaboration';--import { readBotCollaborationMeta } from '../../../shared/botCollaboration';-import { BotSessionTaskLink } from './BotSessionTaskLink';++import { BOT_INTERJECTION_MAX_CHARS, readBotCollaborationMeta } from '../../../shared/botCollaboration';+import { isActiveDelegationStatus } from './botDelegationLive';+import { useBotTaskSession } from './BotSessionTaskLink';+import { useRemoteBots } from './useRemoteBots';/*** 「用时」是说给人听的,不是给日志看的:中文界面里 `8s` 和「用时」并排是两套语言。@@@ -99,484 -68,3 +99,486 @@@ export function BotSessionTaskMessageTr</div>);}++type CardState = 'starting' | 'running' | 'waiting' | 'completed' | 'failed' | 'cancelled' | 'unknown';++const HARNESS_LABEL: Record<string, string> = { cc: 'Claude Code', codex: 'Codex', pi: 'Pi' };++function Chip({+ children,+ onClick,+ tone = 'default',+ disabled,+ expanded,+ controls,+}: {+ children: ReactNode;+ onClick: () => void;+ tone?: 'default' | 'danger';+ disabled?: boolean;+ expanded?: boolean;+ controls?: string;+}) {+ return (+ <button+ type="button"+ onClick={onClick}+ disabled={disabled}+ aria-expanded={expanded}+ aria-controls={controls}+ className={cn(+ 'inline-flex h-6 max-w-full shrink-0 items-center gap-1 rounded-full bg-[var(--surface-chip)] px-2.5 text-11 transition-colors',+ 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)] disabled:cursor-default disabled:opacity-50',+ tone === 'danger'+ ? 'text-[var(--error-fg)]'+ : 'text-[var(--text-secondary)] enabled:hover:text-[var(--text-primary)]',+ )}+ >+ {children}+ </button>+ );+}++function StatusGlyph({ state }: { state: CardState }) {+ if (state === 'starting' || state === 'running') {+ return <Spinner size={12} className="shrink-0 text-[var(--status-bar-accent)]" aria-hidden="true" />;+ }+ return (+ <span+ aria-hidden="true"+ className={cn(+ 'size-[7px] shrink-0 rounded-full',+ state === 'waiting' && 'bg-[var(--status-info)]',+ state === 'completed' && 'bg-[var(--status-success)]',+ state === 'failed' && 'bg-[var(--error-fg)]',+ (state === 'cancelled' || state === 'unknown') && 'bg-[var(--text-tertiary)]',+ )}+ />+ );+}++/**+ * Local bot chats only: the owner adds a line to the original task like typing in it.+ * The Bot's chat then keeps the same quiet trace a Bot's own `message_session_task`+ * leaves (first line only). The line is delivered before the trace, so a failed trace+ * never turns a sent note into an error.+ */+async function sendToTask(+ parentSessionId: string | null,+ delegationId: string,+ childSessionId: string,+ text: string,+): Promise<boolean> {++ if (text.length > BOT_INTERJECTION_MAX_CHARS) return false;+ const owner = getDataOwnerGeneration();+ const row = await sessionService.get(childSessionId);+ if (!isDataOwnerGenerationCurrent(owner) || !row?.workingDir) return false;+ const sent = await makerChatStore.sendMessage(+ childSessionId, text, row.model, row.effort, row.permissionMode, row.workingDir,+ );+ if (sent && parentSessionId && isDataOwnerGenerationCurrent(owner)) {+ await window.electronAPI.maker+ .traceBotDelegationNote(parentSessionId, delegationId, text)+ .catch(() => undefined);+ }+ return sent;+}++/**+ * Background task card. A `delegation-request` anchor follows the live task row;+ * a `delegation-result` receipt keeps its frozen status, text, files and error,+ * reading only the title and PR links from the original task. `attached` is the+ * receipt under the bot's closing reply: its result starts open.+ */+export function BotTaskCard({+ card,+ sessionId,+ attached = false,+}: {+ card: BotCollaborationMeta;+ sessionId?: string;+ attached?: boolean;+}) {+ const { t } = useTranslation();+ const fileContext = useChatSessionFile();+ const ref = useBotTaskSession(card, sessionId);+ const { row, session, activity } = ref;+ const frozen = card.role === 'delegation-result' ? card.result : undefined;+ const parentSessionId = sessionId ?? card.parentSessionId ?? null;+ const childSessionId = ref.targetId;+ const remoteBots = useRemoteBots();+ const online =+ !ref.sourceDeviceId || remoteBots.some((bot) => bot.deviceId === ref.sourceDeviceId && bot.online);+ const [resultOpen, setResultOpen] = useState(attached);+ const [noteOpen, setNoteOpen] = useState(false);+ const [note, setNote] = useState('');+ const [pending, setPending] = useState(false);+ const [actionError, setActionError] = useState<string | null>(null);+ const [now, setNow] = useState(() => Date.now());+ const resultId = useId();++ const state: CardState = frozen+ ? frozen.status === 'completed'+ ? 'completed'+ : frozen.status === 'cancelled'+ ? 'cancelled'+ : 'failed'+ : row?.status === 'waiting'+ ? 'waiting'+ : ref.running || row?.status === 'running'+ ? 'running'+ : !row+ ? ref.resolved ? 'unknown' : 'starting'+ : row.status === 'queued'+ ? 'starting'+ : row.status === 'completed'+ ? 'completed'+ : row.status === 'failed' || row.status === 'timed-out'+ ? 'failed'+ : row.status === 'cancelled'+ ? 'cancelled'+ : 'unknown';+ const live = state === 'starting' || state === 'running' || state === 'waiting';+ const active = !frozen && Boolean(row && isActiveDelegationStatus(row.status));+ const statusLabel = frozen+ ? t(`bots.collab.status.${frozen.status}`)+ : state === 'unknown'+ ? t('bots.collab.status.unknown')+ : state === 'starting'+ ? t('bots.collab.status.queued')+ : t(`bots.collab.status.${state === 'failed' && row ? row.status : state}`);++ // 只在还在干活时起秒级 tick,收拢后不再空转。+ useEffect(() => {+ if (!live || frozen) return;+ setNow(Date.now());+ const timer = setInterval(() => setNow(Date.now()), 1_000);+ return () => clearInterval(timer);+ }, [live, frozen]);++ const { ref: observeCard, visible } = useElementVisible();+ const { registerPrConsumer, invalidateRemotePrRefs } = usePrActions();+ const pullRequests = usePrRefsForSession(childSessionId ?? '').slice(0, MAX_STATUS_QUERIES);+ const { statuses, successfulStatuses, refreshError } = usePrStatuses(childSessionId ?? '');+ useEffect(() => {+ if (!visible || !childSessionId) return;+ return registerPrConsumer(childSessionId, ref.sourceDeviceId);+ }, [visible, childSessionId, ref.sourceDeviceId, registerPrConsumer]);+ useEffect(() => {+ if (visible && childSessionId && ref.sourceDeviceId && row?.updatedAt !== undefined) {+ invalidateRemotePrRefs(childSessionId);+ }+ }, [visible, childSessionId, ref.sourceDeviceId, row?.updatedAt, invalidateRemotePrRefs]);++ const title =+ (frozen?.title?.trim() ||+ (frozen ? row?.title?.trim() || session?.title : session?.title || row?.title) ||+ card.objective.trim().split('\n')[0] ||+ t('bots.collab.backgroundTask'));+ const harness = session ? HARNESS_LABEL[session.agentKind] : undefined;+ const startedAt = row ? (row.acceptedAt ?? row.createdAt) : null;+ const elapsed =+ !frozen && live && startedAt !== null ? formatBotCollaborationDuration(t, startedAt, now) : null;+ const took =+ !frozen && !live && row && row.completedAt !== null+ ? formatBotCollaborationDuration(t, row.createdAt, row.completedAt)+ : null;+ const phase = readWorkingPhase(activity?.workingPhase);+ const currentAction =+ activity?.compactDetail?.trim() || t(WORKING_PHASE_KEYS[phase ?? 'processing']);+ const resultText = frozen ? frozen.text : (row?.resultSummary ?? '');+ const errorText = frozen ? frozen.error : row?.lastError?.replace(/^[A-Z_]+:\s*/, '') || undefined;+ const files: string[] = frozen+ ? frozen.artifacts.map((file) => file.absolutePath)+ : (row?.artifacts ?? []).flatMap((file) => (file.absolutePath ? [file.absolutePath] : []));+ // Older remote hosts may omit the list; never let a missing field break the card.+ const fileCount = frozen ? frozen.artifacts.length : (row?.artifacts?.length ?? 0);+ // Relative links in the result belong to the background task's own directory, which may+ // differ from the Bot's main task: the frozen receipt records it, the live card reads the+ // child session's. The surrounding chat's directory is only the last resort.+ const workingDir = frozen?.workingDir ?? session?.workingDir ?? fileContext.workingDir;+ const canOpen = Boolean(childSessionId) && !ref.originConflict;+ const canAddNote = state === 'running' && Boolean(childSessionId) && !ref.sourceDeviceId && !frozen;+ const resultLabel =+ state === 'completed'+ ? t(resultOpen ? 'bots.collab.collapseResult' : 'bots.collab.expandResult')+ : t(resultOpen ? 'bots.collab.collapseDetails' : 'bots.collab.expandDetails');+ const hasResultBody = Boolean(frozen) || state === 'completed' || state === 'failed' || state === 'cancelled';++ const stop = async () => {+ if (!parentSessionId || pending || !online) return;+ setPending(true);+ setActionError(null);+ try {+ const result = await makerApiForSticky(parentSessionId).cancelBotDelegation(+ parentSessionId,+ card.delegationId,+ );+ if (!result.ok) setActionError(result.message || t('bots.collab.actionFailed'));+ } catch {+ setActionError(t('bots.collab.actionFailed'));+ } finally {+ setPending(false);+ }+ };+ const submitNote = async () => {+ const text = note.trim();+ if (!text || !childSessionId || pending) return;+ setPending(true);+ setActionError(null);+ try {+ if (await sendToTask(parentSessionId, card.delegationId, childSessionId, text)) {+ setNote('');+ setNoteOpen(false);+ toast.success(t('bots.collab.addNoteSent'));+ } else {+ setActionError(t('bots.collab.actionFailed'));+ }+ } catch {+ setActionError(t('bots.collab.actionFailed'));+ } finally {+ setPending(false);+ }+ };+ const openPr = (url: string) => {+ setActionError(null);+ void window.electronAPI+ .openExternal(url)+ .then((result) => {+ if (!result.success) setActionError(t('bots.collab.actionFailed'));+ })+ .catch(() => setActionError(t('bots.collab.actionFailed')));+ };++ const meta = [+ t('bots.collab.backgroundTask'),+ harness,+ took ? t('bots.collab.tookTime', { duration: took }) : null,+ ].filter(Boolean).join(' · ');++ let line2: ReactNode = null;+ if (state === 'running' || state === 'starting') {+ line2 = (+ <>+ <span className="min-w-0 truncate text-[var(--status-bar-accent)]">+ {state === 'starting' ? t('bots.collab.status.queued') : currentAction}+ </span>+ {elapsed ? (+ <span className="shrink-0 tabular-nums text-[var(--text-tertiary)]">+ · {t('bots.collab.elapsed', { duration: elapsed })}+ </span>+ ) : null}+ </>+ );+ } else if (state === 'waiting') {+ const summary = row?.pendingInteraction?.summary?.trim();+ line2 = (+ <span className="min-w-0 line-clamp-2 break-words">+ {summary+ ? t('bots.collab.awaitingConfirm', { summary })+ : t('bots.collab.awaitingConfirmGeneric')}+ </span>+ );+ } else if (state === 'completed' && resultText.trim() && !resultOpen) {+ line2 = (+ <span className="min-w-0 line-clamp-2 whitespace-pre-wrap break-words text-13 leading-[1.6] text-[var(--text-primary)]">+ {resultText.trim()}+ </span>+ );+ } else if (state === 'failed' && errorText && !resultOpen) {+ line2 = <span className="min-w-0 truncate text-[var(--error-fg)]">{errorText}</span>;+ }++ const prIcon = (pr: (typeof pullRequests)[number]) => {+ const result = statuses.get(prStatusKey(pr));+ const confirmed = result?.ok ? result : successfulStatuses.get(prStatusKey(pr));+ const kind = confirmed?.ok ? confirmed.status : undefined;+ const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;+ return (+ <Icon+ size={12}+ aria-hidden="true"+ style={{ color: kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)' }}+ />+ );+ };+ const stale =+ (ref.stale ||+ refreshError ||+ !online ||+ pullRequests.some((pr) => statuses.get(prStatusKey(pr))?.ok === false)) &&+ Boolean(row);++ return (+ <div+ ref={observeCard}+ data-bot-task-card={state}+ className="my-2 w-full min-w-0 max-w-[560px] rounded-xl border border-[var(--msg-tool-card-border)] bg-[var(--msg-tool-card-bg)] px-3 py-2.5"+ >+ <div className="flex min-w-0 items-center gap-2">+ <StatusGlyph state={state} />+ <span className="sr-only">{statusLabel}</span>+ <button+ type="button"+ disabled={!canOpen}+ onClick={ref.open}+ title={statusLabel}+ className="min-w-0 flex-1 truncate text-left text-13 font-medium text-[var(--text-primary)] underline-offset-[3px] enabled:hover:underline disabled:cursor-default"+ >+ {title}+ </button>+ {/* The title keeps its room in a narrow column (Thread open); the meta line gives way first. */}+ <span className="min-w-0 max-w-[55%] shrink truncate text-11 text-[var(--text-tertiary)]">{meta}</span>+ </div>+ {line2 ? (+ <div className="mt-1 flex min-w-0 items-center gap-1.5 text-12 text-[var(--text-secondary)]">+ {line2}+ </div>+ ) : null}+ {stale ? (+ <p className="mt-1 flex items-center gap-1.5 text-12 text-[var(--text-tertiary)]">+ <TriangleAlert size={12} aria-hidden="true" />+ {t('bots.collab.stale')}+ </p>+ ) : null}+ {noteOpen ? (+ <form+ className="mt-2"+ onSubmit={(event) => {+ event.preventDefault();+ void submitNote();+ }}+ >+ <input+ autoFocus+ value={note}++ maxLength={BOT_INTERJECTION_MAX_CHARS}+ disabled={pending}+ onChange={(event) => setNote(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ setNoteOpen(false);+ }+ }}+ aria-label={t('bots.collab.addNote')}+ placeholder={t('bots.collab.addNotePlaceholder')}+ className="h-8 w-full rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-3 text-12 text-[var(--text-primary)] placeholder:text-[var(--text-tertiary)] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[var(--focus-ring)]"+ />+ </form>+ ) : null}+ {resultOpen && hasResultBody ? (+ <div+ id={resultId}+ className="mt-2 space-y-2 border-t border-[var(--border-default)] pt-2 text-13 text-[var(--text-primary)]"+ >+ <ChatSessionFileProvider+ value={{ ...fileContext, workingDir, sessionId: childSessionId ?? undefined }}+ >+ {resultText ? (+ <MarkdownRenderer+ workingDir={workingDir}+ currentSessionId={childSessionId ?? undefined}+ content={resultText}+ />+ ) : (+ <p className="whitespace-pre-wrap break-words text-[var(--text-secondary)]">+ {t('bots.collab.noWrittenResult')}+ </p>+ )}+ {files.map((path) => (+ <MarkdownRenderer+ key={path}+ workingDir={workingDir}+ currentSessionId={childSessionId ?? undefined}+ content={`[${+ path+ .split(/[\\/]/)+ .pop()+ ?.replace(/[[\]\\]/g, '\\$&') ?? t('bots.collab.viewResult')+ }](<${encodeURI(path).replace(/[<>?#]/g, encodeURIComponent)}>)`}+ />+ ))}+ </ChatSessionFileProvider>+ {errorText ? (+ <details>+ <summary className="flex min-h-8 cursor-pointer items-center rounded-lg text-12 text-[var(--text-secondary)] focus-visible:outline focus-visible:outline-2">+ {t('appError.details')}+ </summary>+ <p className="whitespace-pre-wrap break-words text-12 text-[var(--text-secondary)]">+ {errorText}+ </p>+ </details>+ ) : null}+ </div>+ ) : null}+ <div className="mt-2 flex min-w-0 flex-wrap items-center gap-1.5">+ {state === 'waiting' && canOpen ? (+ <Chip onClick={ref.open}>+ <Eye size={12} aria-hidden="true" />+ {t('bots.collab.lookAt')}+ </Chip>+ ) : null}+ {(state === 'running' || state === 'starting') && canOpen ? (+ <Chip onClick={ref.open}>+ <SquareArrowOutUpRight size={12} aria-hidden="true" />+ {t('bots.collab.watchWork')}+ </Chip>+ ) : null}+ {canAddNote ? (+ <Chip onClick={() => setNoteOpen((open) => !open)} expanded={noteOpen} disabled={pending}>+ <Megaphone size={12} aria-hidden="true" />+ {t('bots.collab.addNote')}+ </Chip>+ ) : null}+ {!live && fileCount > 0 ? (+ <Chip onClick={() => setResultOpen(true)} controls={resultId}>+ <FileText size={12} aria-hidden="true" />+ {t('bots.collab.artifactCount', { count: fileCount })}+ </Chip>+ ) : null}+ {pullRequests.map((pr) => (+ <Chip key={pr.url} onClick={() => openPr(sessionPrUrl(pr))}>+ {prIcon(pr)}+ <span className="truncate" title={`${pr.owner}/${pr.repo} #${pr.prNumber}`}>+ PR #{pr.prNumber}+ </span>+ </Chip>+ ))}+ <span className="ml-auto flex shrink-0 items-center gap-1">+ {!live && hasResultBody ? (+ <Chip+ onClick={() => setResultOpen((open) => !open)}+ expanded={resultOpen}+ controls={resultId}+ >+ {resultOpen ? <ChevronUp size={12} aria-hidden="true" /> : <ChevronDown size={12} aria-hidden="true" />}+ {resultLabel}+ </Chip>+ ) : null}+ {!live && canOpen ? (+ <Chip onClick={ref.open}>+ <SquareArrowOutUpRight size={12} aria-hidden="true" />+ {t('bots.collab.watchWork')}+ </Chip>+ ) : null}+ {active ? (+ <Chip+ tone="danger"+ disabled={pending || !parentSessionId || !online}+ onClick={() => void stop()}+ >+ <Square size={12} aria-hidden="true" />+ {t('bots.collab.stop')}+ </Chip>+ ) : null}+ </span>+ </div>+ {actionError ? (+ <p role="alert" className="mt-1.5 text-11 text-[var(--error-fg)]">+ {actionError}+ </p>+ ) : null}+ </div>+ );+}diff --cc apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsxindex 34625e45d9,1851aabee3..3b00be1009--- a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx@@@ -177,115 -137,9 +177,137 @@@ it('takes actual runtime state insteadmocks.running.set('child', { isRunning: true });render(<BotSessionTaskCard data={data()} />);await screen.findByRole('button', { name: 'Current title' });- expect(screen.getByTestId('original-harness').getAttribute('data-running')).toBe('true');+ await waitFor(() => expect(cardState()).toBe('running'));expect(screen.queryByText('bots.collab.status.done')).toBeNull();});+it('shows the current action and elapsed time while running, and stops through the delegation', async () => {+ vi.useFakeTimers({ toFake: ['Date', 'setInterval', 'clearInterval'] });+ vi.setSystemTime(at + 65_000);+ try {+ mocks.row = delegation({ status: 'running' });+ mocks.activity = { phase: 'running', compactDetail: 'Running pnpm test', currentTurnActive: true };+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ expect(cardState()).toBe('running');+ expect(screen.getByText('Running pnpm test')).toBeTruthy();+ expect(screen.getByText(/bots\.collab\.elapsed/).textContent).toContain('bots.collab.duration.minutes');+ expect(screen.getByRole('button', { name: /bots\.collab\.watchWork/ })).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.stop/ }));+ await act(async () => {});+ expect(mocks.cancel).toHaveBeenCalledWith('parent', 'd');+ } finally {+ vi.useRealTimers();+ }+});+it('reports a failed stop without pretending the task stopped', async () => {+ mocks.row = delegation({ status: 'running' });+ mocks.cancel.mockResolvedValue({ ok: false, errorCode: 'X', message: 'Could not stop' });+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.stop/ }));+ expect((await screen.findByRole('alert')).textContent).toBe('Could not stop');+ expect(cardState()).toBe('running');+});+it('adds a note to a local running task as the owner, with the task runtime settings', async () => {+ mocks.row = delegation({ status: 'running' });+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));+ const input = screen.getByRole('textbox', { name: 'bots.collab.addNote' });+ fireEvent.change(input, { target: { value: ' Cover offline reconnect ' } });+ fireEvent.submit(input.closest('form')!);+ await waitFor(() => expect(mocks.send).toHaveBeenCalledWith(+ 'child', 'Cover offline reconnect', 'gpt-x', 'high', 'default', '/child',+ ));+ // The Bot's chat keeps the「已告诉后台任务」trace of what the owner told the task.+ await waitFor(() => expect(mocks.trace).toHaveBeenCalledWith('parent', 'd', 'Cover offline reconnect'));+ await waitFor(() => expect(screen.queryByRole('textbox')).toBeNull());+ expect(mocks.toast).toHaveBeenCalledWith('bots.collab.addNoteSent');+});++it.each([4000, 4001])('checks the trace length limit before delivering a %i-character note', async length => {++ mocks.row = delegation({ status: 'running' });++ render(<BotSessionTaskCard data={data()} sessionId="parent" />);++ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));++ const input = screen.getByRole('textbox', { name: 'bots.collab.addNote' }) as HTMLInputElement;++ const text = '字'.repeat(length);++ // Programmatic change bypasses the native input limit: submit must also validate before sending.++ fireEvent.change(input, { target: { value: text } });++ fireEvent.submit(input.closest('form')!);++ if (length === 4000) {++ await waitFor(() => expect(mocks.trace).toHaveBeenCalledWith('parent', 'd', text));++ expect(mocks.send).toHaveBeenCalledWith('child', text, 'gpt-x', 'high', 'default', '/child');++ expect(mocks.toast).toHaveBeenCalledWith('bots.collab.addNoteSent');++ } else {++ expect((await screen.findByRole('alert')).textContent).toBe('bots.collab.actionFailed');++ expect(mocks.send).not.toHaveBeenCalled();++ expect(mocks.trace).not.toHaveBeenCalled();++ expect(mocks.toast).not.toHaveBeenCalled();++ expect(input.value).toBe(text);++ }++ expect(input.maxLength).toBe(4000);++});+it('still reports a delivered note when only its chat trace fails, and leaves no trace for an undelivered one', async () => {+ mocks.row = delegation({ status: 'running' });+ mocks.trace.mockRejectedValueOnce(new Error('offline'));+ const { unmount } = render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));+ const input = screen.getByRole('textbox', { name: 'bots.collab.addNote' });+ fireEvent.change(input, { target: { value: 'Keep the risk list' } });+ fireEvent.submit(input.closest('form')!);+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('bots.collab.addNoteSent'));+ expect(screen.queryByRole('alert')).toBeNull();+ unmount();++ mocks.send.mockResolvedValueOnce(false);+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));+ const again = screen.getByRole('textbox', { name: 'bots.collab.addNote' });+ fireEvent.change(again, { target: { value: 'Never delivered' } });+ fireEvent.submit(again.closest('form')!);+ expect((await screen.findByRole('alert')).textContent).toBe('bots.collab.actionFailed');+ expect(mocks.trace).toHaveBeenCalledTimes(1);+});+it('shows what the task waits for and lets the user look at it', async () => {+ mocks.row = delegation({ status: 'waiting', pendingInteraction: { summary: 'Allow npm install', kind: 'permission' } });+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ expect(cardState()).toBe('waiting');+ expect(screen.getByText(/bots\.collab\.awaitingConfirm:.*Allow npm install/)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.lookAt/ }));+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/child'));+ expect(screen.getByRole('button', { name: /bots\.collab\.stop/ })).toBeTruthy();+ expect(screen.queryByRole('button', { name: /bots\.collab\.addNote/ })).toBeNull();+});+it('shows the result summary when completed and expands the result in place', async () => {+ mocks.row = delegation({ status: 'completed', completedAt: at + 14 * 60_000, resultSummary: 'Retry capped at 3.',+ artifacts: [{ path: 'a.ts', absolutePath: '/child/a.ts', status: 'modified' }] });+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ expect(cardState()).toBe('completed');+ // The child session (title, working directory) has loaded.+ await screen.findByRole('button', { name: 'Current title' });+ expect(screen.getByText('Retry capped at 3.')).toBeTruthy();+ expect(screen.getByText(/bots\.collab\.tookTime/)).toBeTruthy();+ expect(screen.queryByRole('button', { name: /bots\.collab\.stop/ })).toBeNull();+ const toggle = screen.getByRole('button', { name: /bots\.collab\.expandResult/ });+ expect(toggle.getAttribute('aria-expanded')).toBe('false');+ fireEvent.click(toggle);+ expect(screen.getAllByTestId('markdown').map((node) => node.textContent))+ .toEqual(['Retry capped at 3.', '[a.ts](</child/a.ts>)']);+ // Relative links in a live result resolve against the background task's own directory, not the chat's.+ expect(screen.getAllByTestId('markdown').map((node) => node.getAttribute('data-working-dir'))).toEqual(['/child', '/child']);+ expect(screen.getByRole('button', { name: /bots\.collab\.collapseResult/ }).getAttribute('aria-expanded')).toBe('true');+ expect(screen.getByRole('button', { name: /bots\.collab\.artifactCount/ })).toBeTruthy();+});+it('shows the failure reason in one line', () => {+ mocks.row = delegation({ status: 'timed-out', lastError: 'TIMEOUT: upstream did not finish' });+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ expect(cardState()).toBe('failed');+ expect(screen.getByText('upstream did not finish')).toBeTruthy();+ expect(screen.getByText('bots.collab.status.timed-out')).toBeTruthy();+ expect(screen.getByRole('button', { name: /bots\.collab\.expandDetails/ })).toBeTruthy();+});+it('keeps the stale warning when the task row cannot refresh', () => {+ mocks.row = delegation({ status: 'running' });+ mocks.stale = true;+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ expect(screen.getByText('bots.collab.stale')).toBeTruthy();+});it('preserves archived identity when opening; viewing never calls unarchive', async () => {mocks.get.mockResolvedValue({id: 'child',diff --cc packages/maker-shared/src/botCollaboration.tsindex 4f8054f54d,f7ed88adca..d36efd78af--- a/packages/maker-shared/src/botCollaboration.ts+++ b/packages/maker-shared/src/botCollaboration.ts@@@ -62,15 -56,6 +62,18 @@@ export interface BotCollaborationMeta};}++/** Maximum trimmed note length, in UTF-16 code units; shared by delivery UI and host validation. */++export const BOT_INTERJECTION_MAX_CHARS = 4_000;+++/** 补充消息留痕摘要的上限:只取首行,主聊天不复制完整指令。 */+export const BOT_INTERJECTION_PREVIEW_MAX = 200;++/** First non-empty line, bounded; never the full instruction. */+export function botInterjectionPreview(text: string): string {+ const line = text.split(/\r?\n/).map((value) => value.trim()).find(Boolean) ?? '';+ return Array.from(line).slice(0, BOT_INTERJECTION_PREVIEW_MAX).join('');+}+const ROLES = new Set<BotCollaborationRole>(['delegation-request','delegation-result',