Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): reuse session rows and preserve final streaming
zqchris317fa4c63db0
diff --git a/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.ts b/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.tsnew file mode 100644index 0000000000..73009757be--- /dev/null+++ b/apps/desktop/src/main/localDb/__tests__/sessionListPagination.test.ts@@ -0,0 +1,48 @@+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { eq, getTableColumns, getTableName } from 'drizzle-orm';+import { expect, it } from 'vitest';+import { sessions, messages, taskTags, sessionTaskTags } from '../schema';+import { selectSessionListRows } from '../sessionQueries';+import type { DbClient } from '../client/DbClient';++it('pages the actual list query across tied timestamps without skipping or repeating rows', async () => {+ const sqlite = new Database(':memory:');+ try {+ // Derive columns from production schema; no account DB or migrations are touched.+ for (const table of [sessions, messages, taskTags, sessionTaskTags]) {+ sqlite.exec(+ `CREATE TABLE "${getTableName(table)}" (${Object.values(getTableColumns(table))+ .map((column) => `"${column.name}" ${column.getSQLType()}`)+ .join(',')})`,+ );+ }+ const db = drizzle(sqlite) as unknown as DbClient['drizzle'];+ const insert = sqlite.prepare(+ 'INSERT INTO sessions (id,status,updated_at,list_preview,list_message_count) VALUES (?,?,?, ?,0)',+ );+ for (let n = 0; n < 507; n++)+ insert.run(`s${String(n).padStart(4, '0')}`, 'archived', Math.floor(n / 3), 'cached preview');+ insert.run('active', 'active', 200, 'active');+ insert.run('deleted', 'deleted', 200, 'deleted');+ const ids: string[] = [];+ let before: { id: string; updatedAt: number } | undefined;+ for (;;) {+ const rows = await selectSessionListRows(db, eq(sessions.status, 'archived'), 200, before);+ ids.push(...rows.map((row) => row.session.id));+ const tail = rows.at(-1)?.session;+ if (rows.length < 200 || !tail) break;+ before = { id: tail.id, updatedAt: tail.updatedAt };+ }+ expect(ids).toHaveLength(507);+ expect(new Set(ids).size).toBe(507);+ expect(ids).toEqual(+ Array.from({ length: 507 }, (_, n) => `s${String(506 - n).padStart(4, '0')}`),+ );+ expect(sqlite.prepare('SELECT status FROM sessions WHERE id=?').get('s0000')).toEqual({+ status: 'archived',+ });+ } finally {+ sqlite.close();+ }+});diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex cb7453c15c..4b3293e41d 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1256,6 +1256,19 @@ export function registerSessionIpc(const cap = clampLimit(limit, 20);const includePinned = shouldIncludePinnedSessions(options);const fresh = shouldBypassSessionListSingleFlight(options);+ const rawBefore = options && typeof options === 'object' ? (options as { before?: unknown }).before : undefined;+ let before: { updatedAt: number; id: string } | undefined;+ if (rawBefore !== undefined) {+ // Pagination is local renderer-only until remote capability negotiation exists.+ assertTrustedAppRendererEvent(event);+ const value = requireObject(rawBefore, 'before');+ if (typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0+ || typeof value.id !== 'string' || !value.id || value.id.length > 200 || usageHistory || includePinned) {+ throwIpcError('INVALID_PARAMS', 'Invalid session list cursor');+ }+ before = { updatedAt: value.updatedAt, id: value.id };+ }+// 支持 Sidebar Filter 的 Active/Archived/All status 过滤。// - 'active' / 'archived' → WHERE status = ?// - 'all' / undefined / 其它非法值 → WHERE status != 'deleted'@@ -1270,7 +1283,7 @@ export function registerSessionIpc(const sourceFilter = inArray(sessions.source, DESKTOP_VISIBLE_SESSION_SOURCES);const statusWhere = () =>statusFilter ? eq(sessions.status, statusFilter) : ne(sessions.status, 'deleted');- const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap);+ const rows = await selectSessionListRows(db, and(sourceFilter, statusWhere()), cap, before);let mergedRows = rows;if (includePinned) {@@ -1303,7 +1316,7 @@ export function registerSessionIpc(// forceRefresh / status 重拉带 fresh,不并入写前那次查询。const result = usageHistory? await loadUsageHistoryRows()- : userId && !fresh+ : userId && !fresh && !before? await runSessionListSingleFlight(buildSessionListFlightKey({userId,diff --git a/apps/desktop/src/main/localDb/sessionQueries.ts b/apps/desktop/src/main/localDb/sessionQueries.tsindex 364e5e5e6f..fc4f831288 100644--- a/apps/desktop/src/main/localDb/sessionQueries.ts+++ b/apps/desktop/src/main/localDb/sessionQueries.ts@@ -1,6 +1,6 @@import { normalizeTaskTags } from '@cindy/maker-shared';/** Shared database reads for local IPC, remote IPC and internal callers. */-import { desc, eq, inArray, sql, type SQL } from 'drizzle-orm';+import { and, desc, eq, inArray, sql, type SQL } from 'drizzle-orm';import type { DbClient } from './client/DbClient';import { sessions } from './schema';import { LIST_PREVIEW_EXTRACT_SQL, LATEST_VISIBLE_PREVIEW_FILTER_SQL } from './sessionListProjection';@@ -147,14 +147,17 @@ export function selectSessionListRows(db: DbClient['drizzle'],where: SQL | undefined,cap: number | null,+ before?: { updatedAt: number; id: string },): Promise<SessionListRow[]> {+ if (before) where = and(where, sql`(${sessions.updatedAt} < ${before.updatedAt}+ OR (${sessions.updatedAt} = ${before.updatedAt} AND ${sessions.id} < ${before.id}))`);const pickedBase = db.select({ id: sessions.id }).from(sessions).where(where);const picked = db.$with('picked').as(cap === null- ? pickedBase.orderBy(desc(sessions.updatedAt))- : pickedBase.orderBy(desc(sessions.updatedAt)).limit(cap),+ ? pickedBase.orderBy(desc(sessions.updatedAt), desc(sessions.id))+ : pickedBase.orderBy(desc(sessions.updatedAt), desc(sessions.id)).limit(cap),);return db.with(picked)@@ -162,5 +165,5 @@ export function selectSessionListRows(.from(sessions).innerJoin(picked, eq(picked.id, sessions.id)).where(where)- .orderBy(desc(sessions.updatedAt));+ .orderBy(desc(sessions.updatedAt), desc(sessions.id));}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 89fe9ec1a4..f73d6760a6 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -403,6 +403,8 @@ type DiscordBotSessionAuthCheckWire = {/** Public shape of the local session-list bridge options. */type LocalDbSessionListOptions = {+ /** Local list continuation; does not change the default capped query. */+ before?: { updatedAt: number; id: string };includePinned?: boolean;fresh?: boolean;usageHistory?: boolean;diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex f55249ded7..f6c5d8dd2a 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -699,6 +699,15 @@ describe('makerChatStore text delta batching', () => {assertRows();});+ it('preserves provider final phase through text batching before a turn completes', () => {+ for (const text of ['First ', 'words']) onEvent?.({ sessionId: SESSION_ID, persistId: 'phase-answer',+ event: { type: 'text', source: 'codex', data: { text, isFinal: false, phase: 'final_answer' } } });+ vi.advanceTimersByTime(32);+ expect(makerChatStore.getSnapshot(SESSION_ID).messages).toContainEqual(expect.objectContaining({+ content: 'First words', assistantPhase: 'final_answer', isStreaming: true,+ }));+ });+it('coalesces consecutive text deltas into one store notification', () => {let notifyCount = 0;const unsubscribe = makerChatStore.subscribe(SESSION_ID, () => {diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex c8b1352f9e..ed8bd494fb 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -6750,7 +6750,7 @@ const MessageItem = memo(function MessageItem({workingDir={workingDir}/>);- return simplifiedBotConversation && message.systemCardType === 'bot-session-task'+ return simplifiedBotConversation && (message.systemCardType === 'bot-session-task' || message.systemCardType === 'bot-session-task-result')? withAssistantAvatar(assistantAvatar ? (<span aria-hidden="true" className="invisible">diff --git a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsxindex 499475e3f0..0547633b91 100644--- a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx@@ -1,28 +1,8 @@-import { useEffect, useState } from 'react';-import { FileText, GitPullRequest, Megaphone, Square, TriangleAlert } from 'lucide-react';+import { Megaphone } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { useNavigate } from 'react-router-dom';--import { MAX_STATUS_QUERIES, prStatusKey, sessionPrUrl } from '@cindy/maker-shared';-import { useElementVisible } from '@/cindy-brain/ghostUnreadStore';-import { usePrActions, usePrRefsForSession, usePrStatuses } from '@/contexts/PrRefsContext';-import { PR_STATUS_COLOR, PR_STATUS_ICON } from '@/features/cc-agent/gitContextPrVisuals';-import { Button } from '@/components/ui/button';-import {- DropdownMenu,- DropdownMenuTrigger,- DropdownMenuContent,- DropdownMenuItem,-} from '@/components/ui/dropdown-menu';-import type { BotCollaborationMeta } from '../../../shared/botCollaboration';-import { makerApiForSticky } from '@/lib/makerTransport';-import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';-import { useRemoteBots } from './useRemoteBots';-import { cn } from '@/lib/utils';import { readBotCollaborationMeta } from '../../../shared/botCollaboration';-import { isActiveDelegationStatus, useBotDelegation } from './botDelegationLive';-import { BOT_TASK_CARD_CLASS, BotTaskCardHeader } from './BotTaskCardHeader';+import { BotSessionTaskLink } from './BotSessionTaskLink';/*** 「用时」是说给人听的,不是给日志看的:中文界面里 `8s` 和「用时」并排是两套语言。@@ -66,13 +46,12 @@ interface Props {}/**- * 伙伴启动后台任务后留在父任务消息流里的唯一任务卡。- * 状态来自持久任务行;卡片不会被额外的顶部状态条或右栏面板重复展示。+ * 伙伴历史位置保留原 session 的轻链接;操作与执行状态仍属于原任务。*/export function BotSessionTaskCard({ data, sessionId }: Props) {const parsed = readBotCollaborationCardData(data);if (!parsed || parsed.meta.role !== 'delegation-request') return null;- return <SessionTaskCardBody meta={parsed.meta} sessionId={sessionId} />;+ return <BotSessionTaskLink card={parsed.meta} sessionId={sessionId} />;}/** A quiet persisted trace for a message added to an already-running task. */@@ -89,235 +68,3 @@ export function BotSessionTaskMessageTrace({ data }: Pick<Props, 'data'>) {</div>);}--function SessionTaskCardBody({- meta,- sessionId,-}: {- meta: BotCollaborationMeta;- sessionId?: string;-}) {- const { t } = useTranslation();- const navigate = useNavigate();- const parentSessionId = sessionId ?? meta.parentSessionId ?? null;- const [sourceDeviceId] = useState(() =>- parentSessionId ? remoteProjectsStore.getSessionDeviceId(parentSessionId) : undefined,- );- const remoteBots = useRemoteBots();- const online =- !sourceDeviceId || remoteBots.some((bot) => bot.deviceId === sourceDeviceId && bot.online);- const { row, resolved, stale } = useBotDelegation(parentSessionId, meta.delegationId);- const [pending, setPending] = useState(false);- const [actionError, setActionError] = useState<string | null>(null);- const [now, setNow] = useState(() => Date.now());-- const { ref: observeCard, visible } = useElementVisible();- const active = row ? isActiveDelegationStatus(row.status) : false;- const childSessionId = row?.childSessionId ?? meta.childSessionId;- 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, sourceDeviceId);- }, [visible, childSessionId, sourceDeviceId, registerPrConsumer]);- useEffect(() => {- if (visible && childSessionId && sourceDeviceId && row?.updatedAt !== undefined) {- invalidateRemotePrRefs(childSessionId);- }- }, [visible, childSessionId, sourceDeviceId, row?.updatedAt, invalidateRemotePrRefs]);- const prIcon = (ref: (typeof pullRequests)[number]) => {- const result = statuses.get(prStatusKey(ref));- const confirmed = result?.ok ? result : successfulStatuses.get(prStatusKey(ref));- const kind = confirmed?.ok ? confirmed.status : undefined;- const Icon = kind ? PR_STATUS_ICON[kind] : GitPullRequest;- return (- <Icon- size={14}- aria-hidden="true"- style={{ color: kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)' }}- />- );- };-- // 只在还在干活时起秒级 tick,收拢后不再空转。- useEffect(() => {- if (!active) return;- setNow(Date.now());- const timer = setInterval(() => setNow(Date.now()), 1_000);- return () => clearInterval(timer);- }, [active]);-- const openChildTask = (): void => {- if (!childSessionId) return;- const deviceId = sourceDeviceId;- const existingOrigin = remoteProjectsStore.getSessionDeviceId(childSessionId);- if (deviceId && existingOrigin && existingOrigin !== deviceId) {- setActionError(t('bots.collab.actionFailed'));- return;- }- if (deviceId) remoteProjectsStore.pinSessionOrigin(deviceId, childSessionId);- navigate(`/cc-agent/${encodeURIComponent(childSessionId)}`);- };-- const watchWorkLabel = t('bots.collab.watchWork');-- const runAction = async (action: () => Promise<{ ok: boolean; message?: string }>) => {- setPending(true);- setActionError(null);- try {- const result = await action();- if (!result.ok) setActionError(result.message ?? t('bots.collab.actionFailed'));- return result.ok;- } catch {- setActionError(t('bots.collab.actionFailed'));- return false;- } finally {- setPending(false);- }- };-- const unverifiable = resolved && !row;- const statusLabel = row- ? t(`bots.collab.status.${row.status}`)- : unverifiable- ? t('bots.collab.status.unknown')- : t('bots.collab.status.queued');- const startedAt = row?.createdAt ?? null;- const endedAt = row && !active ? (row.completedAt ?? row.updatedAt) : now;- const duration =- startedAt === null ? null : formatBotCollaborationDuration(t, startedAt, endedAt);- const taskStatusClass =- !row || row.status === 'queued'- ? 'text-[var(--text-tertiary)]'- : row.status === 'completed'- ? 'text-[var(--status-success)]'- : row.status === 'failed' || row.status === 'timed-out'- ? 'text-[var(--error-fg)]'- : row.status === 'cancelled'- ? 'text-[var(--text-tertiary)]'- : 'text-[var(--status-info)]';- const taskTitle =- row?.title || meta.objective.trim().split('\n')[0] || t('bots.collab.backgroundTask');- const artifacts = row?.artifacts ?? [];- const actionClass = 'w-full min-w-[104px] gap-1.5 px-3';- 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 prButton = (- <Button- variant="secondary"- size="md"- className={actionClass}- onClick={pullRequests.length === 1 ? () => openPr(sessionPrUrl(pullRequests[0])) : undefined}- >- {pullRequests.length === 1 ? (- prIcon(pullRequests[0])- ) : (- <GitPullRequest size={14} aria-hidden="true" />- )}- {t('bots.collab.viewPr')}- </Button>- );-- return (- <div ref={observeCard} className={BOT_TASK_CARD_CLASS}>- <BotTaskCardHeader title={taskTitle} status={statusLabel} statusClass={taskStatusClass} />- <div className="mt-1 flex min-h-4 flex-wrap items-center gap-x-3 gap-y-1 text-[var(--text-tertiary)]">- {duration ? <span className="tabular-nums">{duration}</span> : null}- {artifacts.length > 0 ? (- <span>{t('bots.collab.artifactCount', { count: artifacts.length })}</span>- ) : null}- {pullRequests.length === 1 ? (- <span className="min-w-0 truncate" title={pullRequests[0].url}>- {pullRequests[0].owner}/{pullRequests[0].repo} #{pullRequests[0].prNumber}- </span>- ) : null}- {pullRequests.length > 1 ? (- <span>{t('bots.collab.prCount', { count: pullRequests.length })}</span>- ) : null}- </div>- {(stale || refreshError ||- !online ||- pullRequests.some((ref) => statuses.get(prStatusKey(ref))?.ok === false)) &&- row ? (- <p className="mt-1.5 flex items-center gap-1.5 text-[var(--text-tertiary)]">- <TriangleAlert size={13} aria-hidden="true" />- {t('bots.collab.stale')}- </p>- ) : null}- {row?.status === 'waiting' ? (- <p className="mt-1.5 line-clamp-2 break-words text-[var(--text-secondary)]">- {row.pendingInteraction?.summary || t('bots.collab.retrying')}- </p>- ) : null}- {row?.lastError && (row.status === 'failed' || row.status === 'timed-out') ? (- <p className="mt-1.5 line-clamp-2 break-words text-[var(--error-fg)]">- {row.lastError.replace(/^[A-Z_]+:\s*/, '')}- </p>- ) : null}- {active || childSessionId || pullRequests.length > 0 ? (- <div- className={cn(- 'mt-2.5 grid w-fit max-w-full items-center gap-2',- Number(active) + Number(Boolean(childSessionId)) + Number(pullRequests.length > 0) > 1- ? 'grid-cols-2'- : 'grid-cols-1',- )}- >- {pullRequests.length === 1 ? (- prButton- ) : pullRequests.length > 1 ? (- <DropdownMenu>- <DropdownMenuTrigger asChild>{prButton}</DropdownMenuTrigger>- <DropdownMenuContent align="start">- {pullRequests.map((pr) => (- <DropdownMenuItem key={pr.url} onSelect={() => openPr(sessionPrUrl(pr))}>- {prIcon(pr)} {pr.owner}/{pr.repo} #{pr.prNumber}- </DropdownMenuItem>- ))}- </DropdownMenuContent>- </DropdownMenu>- ) : null}- {childSessionId ? (- <Button variant="secondary" size="md" className={actionClass} onClick={openChildTask}>- <FileText size={14} aria-hidden="true" />- {watchWorkLabel}- </Button>- ) : null}- {active ? (- <Button- variant="secondary"- size="md"- className={actionClass}- disabled={pending || !parentSessionId || !online}- onClick={() => {- if (!parentSessionId || !online || pending) return;- void runAction(async () =>- makerApiForSticky(parentSessionId).cancelBotDelegation(- parentSessionId,- meta.delegationId,- ),- );- }}- >- <Square size={14} aria-hidden="true" />- {t('bots.collab.stopTask')}- </Button>- ) : null}- </div>- ) : null}- {actionError ? (- <p role="alert" className="mt-2 text-11 text-[var(--error-fg)]">- {actionError}- </p>- ) : null}- </div>- );-}diff --git a/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx b/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsxnew file mode 100644index 0000000000..8f7f498697--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/BotSessionTaskLink.tsx@@ -0,0 +1,158 @@+import { useEffect, useMemo, useState, useSyncExternalStore } from 'react';+import { useNavigate } from 'react-router-dom';+import { useTranslation } from 'react-i18next';+import { Tip } from '@/components/ui/tooltip';+import { SessionStatusIcon } from '@/features/cc-agent/sidebar/SessionStatusIcon';+import { useAgentIslandActivity } from '@/state/agentIslandActivity';+import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';+import { makerChatStore } from '@/lib/makerChatStore';+import { sessionsStore } from '@/lib/sessionsStore';+import { onPatch } from '@/lib/sessionsBus';+import { projectSidebarSessionActivity } from '@/features/cc-agent/sidebar/sidebarRightStatus';+import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';+import { useSessionDisplayRunningState } from '@/features/cc-agent/hooks/useSessionDisplayRunningState';+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';+import * as sessionService from '@/lib/sessionService';+import type { Session } from '@/lib/ccAgent.types';+import type { BotCollaborationMeta } from '../../../shared/botCollaboration';+import { useBotDelegation } from './botDelegationLive';++/** A reference to the original session, never a second task or completion state. */+export function BotSessionTaskLink({+ card,+ sessionId,+}: {+ card: BotCollaborationMeta;+ sessionId?: string;+}) {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { row } = useBotDelegation(sessionId ?? card.parentSessionId, card.delegationId);+ const targetId = row?.childSessionId ?? card.childSessionId;+ const [session, setSession] = useState<Session | null>(null);+ const activity = useAgentIslandActivity(targetId ?? '');+ const remoteActivity = useRemoteSessionActivity(targetId ?? '', session?.deviceLinkDeviceId);+ const locallyRunning = useSyncExternalStore(makerChatStore.subscribeAll, () =>+ Boolean(targetId && makerChatStore.getRunningSnapshot().get(targetId)?.isRunning),+ );+ const running = useMemo(+ () => new Set(locallyRunning && targetId ? [targetId] : []),+ [locallyRunning, targetId],+ );+ const rows = useMemo(() => (session ? [session] : []), [session]);+ const { displayRunningSessionIds } = useSessionDisplayRunningState(rows, running);+ const attention = useSessionAttentionKind(targetId ?? '');+ const [attached, setAttached] = useState(false);+ useEffect(() => {+ setSession(null);+ if (!targetId) return;+ let alive = true;+ const owner = getDataOwnerGeneration();+ const sourceDeviceId = remoteProjectsStore.getSessionDeviceId(+ sessionId ?? card.parentSessionId ?? '',+ );+ const existingOrigin = remoteProjectsStore.getSessionDeviceId(targetId);+ if (existingOrigin && existingOrigin !== sourceDeviceId) return;+ if (sourceDeviceId) remoteProjectsStore.pinSessionOrigin(sourceDeviceId, targetId);+ void sessionService+ .get(targetId)+ .then((value) => {+ if (alive && isDataOwnerGenerationCurrent(owner)) setSession(value);+ })+ .catch(() => {});+ const offPatch = onPatch((id, patch) => {+ if (id === targetId && isDataOwnerGenerationCurrent(owner))+ setSession((current) => (current ? { ...current, ...patch } : current));+ });+ const refreshAttached = () => {+ if (sourceDeviceId) return;+ void window.electronAPI.binding+ .resolveSession(targetId)+ .then((value) => {+ if (alive && isDataOwnerGenerationCurrent(owner)) setAttached(value.attached);+ })+ .catch(() => {});+ };+ setAttached(false);+ refreshAttached();+ const offReset = sessionsStore.subscribe((change) => {+ if (change === 'reset') {+ alive = false;+ setSession(null);+ setAttached(false);+ }+ });+ const offBinding = window.electronAPI.binding.onChanged(refreshAttached);+ return () => {+ alive = false;+ offPatch();+ offBinding();+ offReset();+ };+ }, [targetId, sessionId, card.parentSessionId]);+ const currentActivity = session+ ? projectSidebarSessionActivity({+ interruption: session,+ sessionId: session.id,+ title: session.title,+ recordStatus: session.status,+ liveActivity: session.deviceLinkDeviceId ? remoteActivity : activity,+ attentionKind: attention,+ isUrgentFromContext: false,+ isRunning: session.deviceLinkDeviceId+ ? remoteActivity?.phase === 'running'+ : displayRunningSessionIds.has(session.id),+ hasAttentionNotification: Boolean(attention),+ })+ : null;+ const sourceDevice = remoteProjectsStore.getSessionDeviceId(+ sessionId ?? card.parentSessionId ?? '',+ );+ const targetDevice = targetId ? remoteProjectsStore.getSessionDeviceId(targetId) : undefined;+ const originConflict = Boolean(targetDevice && targetDevice !== sourceDevice);+ const title =+ session?.title ||+ row?.title ||+ card.result?.title ||+ card.objective.split('\n')[0] ||+ t('bots.collab.backgroundTask');+ const preview = card.result?.text || session?.preview || row?.resultSummary || title;+ return (+ <Tip+ text={+ <span className="block max-w-xs whitespace-pre-wrap break-words text-12">+ {preview.slice(0, 500)}+ </span>+ }+ >+ <button+ type="button"+ disabled={!targetId || originConflict}+ className="inline-flex max-w-full items-baseline gap-1 text-left text-14 leading-6 text-[var(--text-primary)] underline decoration-[var(--border-default)] underline-offset-4 disabled:cursor-default"+ onClick={() => {+ if (targetId && !originConflict)+ void resolveSessionRoute(targetId, session ?? undefined).then((route) =>+ navigate(route),+ );+ }}+ >+ {session && (+ <SessionStatusIcon+ session={session}+ isRunning={currentActivity?.currentTurnActive === true}+ isAttached={attached}+ isActive={false}+ hasAttentionNotification={Boolean(attention)}+ size={13}+ />+ )}+ <span className="min-w-0 break-words">{title}</span>+ </button>+ </Tip>+ );+}diff --git a/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx b/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsxindex 970803bbed..802b89f433 100644--- a/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx+++ b/apps/desktop/src/renderer/features/bots/BotSessionTaskResultCard.tsx@@ -1,9 +1,7 @@+import { useBotDelegation } from './botDelegationLive';+import { BotSessionTaskLink } from './BotSessionTaskLink';import { useId, useState } from 'react';import { useTranslation } from 'react-i18next';-import { FileText } from 'lucide-react';-import { Button } from '@/components/ui/button';-import { BOT_TASK_CARD_CLASS, BotTaskCardHeader } from './BotTaskCardHeader';-import { useBotDelegation } from './botDelegationLive';import type { BotCollaborationMeta } from '../../../shared/botCollaboration';import { readBotCollaborationMeta } from '../../../shared/botCollaboration';import {@@ -16,7 +14,6 @@ import { MarkdownRenderer } from '@/components/chat/MarkdownRenderer';export function BotSessionTaskResultCard({data,sessionId,- attached = false,}: {data?: Record<string, unknown>;sessionId?: string;@@ -24,19 +21,17 @@ export function BotSessionTaskResultCard({}) {const card = readBotCollaborationMeta(data);if (card?.role !== 'delegation-result' || !card.result) return null;- return <TaskResultBody card={card} result={card.result} sessionId={sessionId} attached={attached} />;+ return <TaskResultBody card={card} result={card.result} sessionId={sessionId} />;}function TaskResultBody({card,result,sessionId,- attached,}: {card: BotCollaborationMeta;result: NonNullable<BotCollaborationMeta['result']>;sessionId?: string;- attached: boolean;}) {const { t } = useTranslation();const fileContext = useChatSessionFile();@@ -51,36 +46,27 @@ function TaskResultBody({row?.title?.trim() ||card.objective.trim().split('\n')[0] ||t('bots.collab.backgroundTask');- const statusClass =- result.status === 'completed'- ? 'text-[var(--status-success)]'- : result.status === 'cancelled'- ? 'text-[var(--text-tertiary)]'- : 'text-[var(--error-fg)]';const workingDir = result.workingDir ?? fileContext.workingDir;return (- <div className={attached ? "w-full min-w-0 rounded-xl border border-[var(--border-default)] bg-[var(--surface-elevated)] p-3" : BOT_TASK_CARD_CLASS}>- <BotTaskCardHeader- title={title}- status={t(`bots.collab.status.${result.status}`)}- statusClass={statusClass}- />- <Button- variant="secondary"- size="md"- className="mt-2.5 min-w-[104px] max-w-full gap-1.5 px-3"+ <div className="min-w-0 text-14 leading-6">+ <BotSessionTaskLink card={card} sessionId={sessionId} />+ <button+ type="button"+ className="ml-2 inline-flex max-w-full text-12 text-[var(--text-secondary)] underline underline-offset-4"aria-expanded={expanded}aria-controls={contentId}onClick={() => setExpanded(!expanded)}>- <FileText size={14} aria-hidden="true" />{t('bots.collab.viewResult')}- </Button>+ </button><divid={contentId}hidden={!expanded}className="mt-3 space-y-2 border-t border-[var(--border-default)] pt-3 text-14 text-[var(--text-primary)]">+ <p className="text-12 text-[var(--text-secondary)]">+ <span>{title}</span> · <span>{t(`bots.collab.status.${result.status}`)}</span>+ </p><ChatSessionFileProvidervalue={{ ...fileContext, workingDir, sessionId: card.childSessionId ?? undefined }}>@@ -102,7 +88,7 @@ function TaskResultBody({artifact.absolutePath.split(/[\\/]/).pop()- ?.replace(/[\[\]\\]/g, '\\$&') ?? t('bots.collab.viewResult')+ ?.replace(/[[\]\\]/g, '\\$&') ?? t('bots.collab.viewResult')}](<${encodeURI(artifact.absolutePath).replace(/[<>?#]/g, encodeURIComponent)}>)`}/>))}diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsxindex 8a1d3eb388..986dc43570 100644--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx@@ -1,8 +1,11 @@+import { WorkbenchSessionList } from './WorkbenchSessionList';+import { useWorkbenchSessionPages } from './useWorkbenchSessionPages';import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';import {ArrowLeft,ArrowUp,ChevronRight,+ ChevronDown,CircleCheck,CircleDot,CirclePause,@@ -51,6 +54,7 @@ import { useAgentIslandActivityMap } from '@/state/agentIslandActivity';import {BOT_WORKBENCH_MAX_DIRECTORIES,isCaseInsensitivePlatform,+ findWorkbenchProject,parseWorkbenchTaskId,validateWorkbenchRef,type BotWorkbench as BotWorkbenchData,@@ -62,6 +66,7 @@ import { isBotPrimaryGeneratedFile } from './botGeneratedArtifacts';import { useBotProfiles } from './botStore';import {buildWorkbenchProjectOptions,+ isWorkbenchCandidateSession,buildWorkbenchTiles,collectBotHiddenSessionIds,countUnjudgedCandidates,@@ -314,6 +319,14 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: sconst judgments = useMemo(() => workbench?.tasks ?? {}, [workbench]);const projectDirs = useMemo(() => directories.map((dir) => dir.path), [directories]);const candidates = useExternalCandidates(botId, projectDirs.join('\n'));+ const [archivedOpen, setArchivedOpen] = useState(false);+ const [listRevision, setListRevision] = useState(0);+ const listScope = `${botId}:${projectDirs.join('\n')}:${listRevision}`;+ const activePages = useWorkbenchSessionPages(listScope, 'active', Boolean(workbench));+ const archivedPages = useWorkbenchSessionPages(listScope, 'archived', archivedOpen);+ const sessionRows = activePages.rows;+ const refreshList = useCallback(() => { setListRevision(value => value + 1); emitRefresh(); }, []);+const hiddenIds = useMemo(() => collectBotHiddenSessionIds(profiles), [profiles]);const erroredIds = useMemo(() => new Set([...attentionKinds].filter(([, kind]) => kind === 'error').map(([id]) => id)),@@ -323,7 +336,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: sconst tiles = useMemo(() =>buildWorkbenchTiles({- sessions,+ sessions: sessionRows,hiddenIds,projectDirs,caseInsensitive,@@ -336,7 +349,7 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: scandidates,}),[- sessions,+ sessionRows,hiddenIds,projectDirs,caseInsensitive,@@ -350,6 +363,16 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s],);+ const listedIds = useMemo(() => new Set(tiles.filter(tile => tile.type === 'session').map(tile => tile.id)), [tiles]);+ const activeSessionRows = useMemo(() => sessionRows.filter(row => listedIds.has(row.id)), [sessionRows, listedIds]);+ const delegationChildIds = useMemo(() => new Set(delegations.flatMap(row => row.childSessionId ? [row.childSessionId] : [])), [delegations]);+ const archivedSessionRows = useMemo(() => archivedPages.rows.filter(row =>+ row.status === 'archived' && isWorkbenchCandidateSession({ ...row, status: 'active' }, hiddenIds, delegationChildIds)+ && findWorkbenchProject(row.workingDir, projectDirs, caseInsensitive)), [archivedPages.rows, hiddenIds, projectDirs, caseInsensitive, delegationChildIds]);+ const pageAction = (page: typeof activePages) => page.loading+ ? <Spinner size={14} className="mx-5 my-3" role="status" aria-label={t('ccAgent.common.loading')} />+ : page.error || page.hasMore ? <Button size="sm" variant="secondary" className="mx-4 my-2" onClick={() => void page.load()}>{t(page.error ? 'commonUi.retry' : 'settings.contacts.list.loadMore')}</Button> : null;+// 伙伴正在读这些项目:还有本机外部会话没写判断,且伙伴主任务正在跑。const unjudged = useMemo(() => countUnjudgedCandidates({ projectDirs, caseInsensitive, candidates, judgments }),@@ -366,7 +389,9 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: sconst openTile = useCallback((tile: WorkbenchTile) => {- if (tile.type === 'session' || tile.type === 'external' || tile.type === 'item') {+ if (tile.type === 'session') {+ void resolveSessionRoute(tile.id).then(route => navigate(route));+ } else if (tile.type === 'external' || tile.type === 'item') {// 任务在本标签内打开详情,不换路由、不跳任务页。setDetailOpened(tile);} else if (tile.type === 'schedule') {@@ -517,13 +542,24 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: s</>)}+ {!picking && <>+ <WorkbenchSessionList sessions={activeSessionRows} onChanged={refreshList} />+ {pageAction(activePages)}+ <section className="pb-3 pt-2">+ <button type="button" className="mx-3 flex min-h-9 items-center gap-1.5 rounded-lg px-2 text-12 text-[var(--text-secondary)] hover:bg-[var(--surface-hover)]" aria-expanded={archivedOpen} onClick={() => setArchivedOpen(value => !value)}>+ {archivedOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}{t('ccAgent.sidebar.filterStatus.archived')}+ </button>+ {archivedOpen && <><WorkbenchSessionList sessions={archivedSessionRows} onChanged={refreshList} />{pageAction(archivedPages)}</>}+ </section>+ </>}+{/* 还没接手项目时,伙伴已有的自动化(例行任务、导入来的自动化)照常列在下面。 */}{!picking || routineTiles.length > 0 ? (<TaskGroups- tiles={picking ? routineTiles : tiles}+ tiles={picking ? routineTiles : tiles.filter(tile => tile.type !== 'session')}now={now}language={i18n.language}- showEmpty={!picking && !understanding}+ showEmpty={false}followingKey={followingKey}onOpen={openTile}onFollowUp={followUp}diff --git a/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx b/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsxnew file mode 100644index 0000000000..d8d9377a39--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/WorkbenchSessionList.tsx@@ -0,0 +1,233 @@+import { useCallback, useMemo } from 'react';+import { useTranslation } from 'react-i18next';+import { useNavigate } from 'react-router-dom';+import type { Session } from '@/lib/ccAgent.types';+import { SessionCard } from '@/features/cc-agent/sidebar/SessionCard';+import type { SessionMoveTarget } from '@/features/cc-agent/sidebar/sessionMoveTarget';+import { toStoredSessionTitle } from '@/features/cc-agent/lib/sessionDisplayTitle';+import { useSessionLifecycleActions } from '@/features/cc-agent/hooks/useSessionLifecycleActions';+import { useSessionDisplayRunningState } from '@/features/cc-agent/hooks/useSessionDisplayRunningState';+import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';+import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';+import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';+import { resolveWorktreeRemovalPreflight } from '@/lib/worktreeRemovalWarning';+import { sessionsStore } from '@/lib/sessionsStore';+import * as service from '@/lib/sessionService';+import { isRemoteSessionWriteBlocked } from '@/features/cc-agent/lib/remoteSessionWriteGuard';+import { getDataOwnerGeneration } from '@/contexts/dataOwnerGeneration';+import { persistManualPinnedOrder } from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';+import { toast } from '@/lib/toast';++/** Same row and lifecycle APIs as the task sidebar; this view owns no task state. */+export function WorkbenchSessionList({+ sessions,+ onChanged,+}: {+ sessions: Session[];+ onChanged: () => void;+}) {+ const { t } = useTranslation();+ const navigate = useNavigate();+ const { confirm } = useConfirmDialog();+ const { runningSessionIds, notifications, clearNotification } =+ useSessionRunningStatus(undefined);+ const attached = useAttachedSessionIds();+ const { displayRunningSessionIds } = useSessionDisplayRunningState(sessions, runningSessionIds);+ const { runSessionAction, unarchiveSession } = useSessionLifecycleActions({+ includeArchived: 'all',+ });+ const byId = useMemo(() => new Map(sessions.map((row) => [row.id, row])), [sessions]);+ const open = useCallback(+ (id: string) => {+ clearNotification(id);+ void resolveSessionRoute(id, byId.get(id)).then((route) => navigate(route));+ },+ [byId, clearNotification, navigate],+ );+ const action = useCallback(+ async (+ id: string,+ kind: 'archive' | 'archive-now' | 'unarchive' | 'delete',+ sharedTaskId?: string,+ ) => {+ try {+ if (isRemoteSessionWriteBlocked(byId.get(id))) {+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));+ return;+ }+ if (kind === 'unarchive') {+ await unarchiveSession(id);+ onChanged();+ return;+ }+ const archive = kind !== 'delete';+ if (archive && runningSessionIds.has(id)) {+ toast.warning(t('ccAgent.sidebar.archiveBlocked.running'));+ return;+ }+ if (+ archive &&+ (attached.has(id) ||+ (await window.electronAPI.binding.resolveSession(id).catch(() => ({ attached: false })))+ .attached)+ ) {+ toast.warning(t('ccAgent.sidebar.archiveBlocked.attached'));+ return;+ }+ const preflight = await resolveWorktreeRemovalPreflight(+ id,+ byId.get(id)?.deviceLinkDeviceId,+ );+ const prefix = archive ? 'ccAgent.sidebar.confirmArchive' : 'ccAgent.sidebar.confirmDelete';+ if (+ (!archive || preflight !== 'clean') &&+ !(await confirm({+ title: t(prefix + '.title'),+ description:+ t(prefix + '.description') ++ (preflight === 'dirty' ? ' ' + t(prefix + '.dirtyWorktreeWarning') : ''),+ confirmText: t(prefix + '.confirm'),+ cancelText: t(prefix + '.cancel'),+ }))+ )+ return;+ if (sharedTaskId) {+ const result = (await window.electronAPI.sharedTask.account({+ action: 'close',+ sharedTaskId,+ })) as { closed?: string[] };+ if (!result.closed?.includes(sharedTaskId)) {+ toast.error(t('sharedTask.closeFailedToast', { count: 1 }));+ return;+ }+ }+ await runSessionAction(id, archive ? 'archive' : 'delete', { activeSessionId: null });+ onChanged();+ } catch {+ toast.error(+ t(kind === 'delete' ? 'ccAgent.sidebar.deleteFailed' : 'ccAgent.sidebar.archiveFailed'),+ );+ }+ },+ [byId, attached, confirm, onChanged, runSessionAction, runningSessionIds, t, unarchiveSession],+ );+ const rename = useCallback(+ async (id: string, title: string) => {+ const row = byId.get(id);+ if (!row) return;+ if (isRemoteSessionWriteBlocked(row)) {+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));+ return;+ }+ try {+ const patch = { title: toStoredSessionTitle(row, title) };+ await service.patchMeta(id, patch);+ sessionsStore.patchLocal(id, patch);+ onChanged();+ } catch {+ toast.error(t('ccAgent.sidebar.renameFailed'));+ }+ },+ [byId, onChanged, t],+ );+ const pin = useCallback(+ async (id: string, pinned: boolean) => {+ if (isRemoteSessionWriteBlocked(byId.get(id))) {+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));+ return;+ }+ const owner = getDataOwnerGeneration();+ try {+ const patch = { pinnedAt: pinned ? null : new Date().toISOString() };+ await service.patchMeta(id, patch);+ sessionsStore.patchLocal(id, pinned ? { ...patch, summary: null } : patch);+ if (!pinned)+ await persistManualPinnedOrder(+ { kind: 'promote', entryId: id },+ { dataOwnerId: owner.dataOwnerId, ownerGeneration: owner.generation },+ );+ onChanged();+ } catch {+ toast.error(t('ccAgent.sidebar.pinFailed'));+ }+ },+ [byId, onChanged, t],+ );+ const move = useCallback(+ async (id: string, target: SessionMoveTarget) => {+ const row = byId.get(id);+ if (row?.remoteHostId || row?.deviceLinkDeviceId) {+ toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRemoteUnsupported'));+ return;+ }+ if (runningSessionIds.has(id)) {+ toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectRunningBlocked'));+ return;+ }+ try {+ if (+ (await window.electronAPI.binding.resolveSession(id).catch(() => ({ attached: false })))+ .attached+ ) {+ toast.warning(t('ccAgent.sidebar.sessionMenu.moveToProjectAttachedBlocked'));+ return;+ }+ let workingDir = target.kind === 'project' ? target.workingDir : undefined;+ if (target.kind === 'browseProject') {+ const result = await window.electronAPI.showOpenDirectoryDialog();+ if (result.canceled || !result.path) return;+ workingDir = result.path;+ }+ if (target.kind !== 'dialogue' && !workingDir) return;+ const patch =+ target.kind === 'dialogue'+ ? { workspaceKind: 'dialogue' as const }+ : { workingDir, workspaceKind: 'project' as const };+ await service.update(id, patch);+ sessionsStore.patchLocal(id, patch);+ onChanged();+ } catch {+ toast.error(t('ccAgent.sidebar.sessionMenu.moveToProjectFailed'));+ }+ },+ [byId, onChanged, runningSessionIds, t],+ );+ const projectOptions = useMemo(+ () =>+ [+ ...new Set(+ sessions+ .filter((row) => !row.deviceLinkDeviceId && !row.remoteHostId)+ .map((row) => row.workingDir)+ .filter((path): path is string => Boolean(path)),+ ),+ ].map((path) => ({+ path,+ name: path.replace(/\\/g, '/').split('/').filter(Boolean).at(-1) ?? path,+ })),+ [sessions],+ );+ return (+ <div className="px-3" data-workbench-session-list>+ {sessions.map((session, index) => (+ <SessionCard+ key={session.id}+ session={session}+ variant="list"+ isFirst={index === 0}+ isActive={false}+ isRunning={displayRunningSessionIds.has(session.id)}+ isAttached={attached.has(session.id)}+ hasAttentionNotification={notifications.has(session.id)}+ onClick={open}+ onAction={action}+ projectOptions={projectOptions}+ onRename={rename}+ onTogglePin={pin}+ onMoveSession={move}+ />+ ))}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsxindex 2b008213b4..f318a5b959 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx@@ -1,617 +1,149 @@-import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';-import { __resetStickySessionOriginForTest } from '@/features/device-link/stickySessionOrigin';// @vitest-environment jsdom--import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';import { BotSessionTaskCard, BotSessionTaskMessageTrace } from '../BotCollaborationCard';-import { __resetBotDelegationLiveForTest } from '../botDelegationLive';-import type {- BotDelegationChangedPayload,- BotDelegationStatus,- BotDelegationView,-} from '../../../../shared/botDelegation';import type { BotCollaborationMeta } from '../../../../shared/botCollaboration';-const mocks = vi.hoisted(() => ({+ get: vi.fn(),navigate: vi.fn(),- remoteBots: [] as any[],- prRefs: [] as any[],- successfulPrStatuses: new Map(),- refreshError: false,- prStatuses: new Map(),- registerPrConsumer: vi.fn(() => () => {}),- invalidateRemotePrRefs: vi.fn(),+ route: vi.fn(),+ row: null as any,+ origin: vi.fn(),+ pin: vi.fn(),+ running: new Map(),+ activity: null as any,+ attached: false,}));--vi.mock('react-i18next', () => ({- useTranslation: () => ({- t: (key: string, opts?: Record<string, unknown>) =>- opts ? `${key}:${JSON.stringify(opts)}` : key,- i18n: { language: 'en' },- }),+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));+vi.mock('../botDelegationLive', () => ({ useBotDelegation: () => ({ row: mocks.row }) }));+vi.mock('@/lib/sessionService', () => ({ get: mocks.get }));+vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: mocks.route }));+vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { subscribe: () => () => {} } }));+vi.mock('@/components/ui/tooltip', () => ({ Tip: ({ children }: any) => children }));+vi.mock('@/state/agentIslandActivity', () => ({ useAgentIslandActivity: () => mocks.activity }));+vi.mock('@/features/device-link/remoteSessionActivityStore', () => ({+ useRemoteSessionActivity: () => null,}));-vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));-vi.mock('../useRemoteBots', () => ({ useRemoteBots: () => mocks.remoteBots }));-vi.mock('@/contexts/PrRefsContext', () => ({- usePrActions: () => ({- registerPrConsumer: mocks.registerPrConsumer,- invalidateRemotePrRefs: mocks.invalidateRemotePrRefs,- }),- usePrRefsForSession: (id: string) => (id === 'child-1' ? mocks.prRefs : []),- usePrStatuses: () => ({- statuses: mocks.prStatuses,- refreshError: mocks.refreshError,- successfulStatuses: mocks.successfulPrStatuses,+vi.mock('@/lib/makerChatStore', () => ({+ makerChatStore: { subscribeAll: () => () => {}, getRunningSnapshot: () => mocks.running },+}));+vi.mock('@/lib/sessionAttentionStore', () => ({ useSessionAttentionKind: () => undefined }));+vi.mock('@/features/cc-agent/hooks/useSessionDisplayRunningState', () => ({+ useSessionDisplayRunningState: (_: unknown, running: Set<string>) => ({+ displayRunningSessionIds: running,}),}));-const associatedPr = (n: number) => ({- id: `pr-${n}`,- sessionId: 'child-1',- owner: 'a',- repo: 'b',- prNumber: n,- url: `https://github.com/a/b/pull/${n}`,- firstSeenAt: 1,- lastSeenAt: 1,-});-vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.navigate }));--const SESSION_ID = 'parent-session-1';-const DELEGATION_ID = 'delegation-1';--function meta(overrides: Partial<BotCollaborationMeta> = {}): BotCollaborationMeta {- return {- v: 1,- role: 'delegation-request',- delegationId: DELEGATION_ID,- fromBotId: 'bot-cindy',- fromBotName: 'Cindy',- toBotId: null,- toBotName: 'Cindy',- parentSessionId: SESSION_ID,- childSessionId: 'child-1',- objective: '做一版方案',- ...overrides,- };-}--function delegation(- status: BotDelegationStatus,- overrides: Partial<BotDelegationView> = {},-): BotDelegationView {- return {- id: DELEGATION_ID,- requestingBotId: 'bot-cindy',- targetBotId: null,- targetBotName: 'Cindy',- parentSessionId: SESSION_ID,- childSessionId: 'child-1',- title: '方案任务',- objective: '做一版方案',- contextRefs: [],- permissionSnapshot: {},- lineage: [],- targetProfileVersion: 1,- depth: 1,- status,- pendingInteraction: null,- resultSummary: null,- artifacts: [],- lastError: null,- createdAt: Date.now() - 8_000,- acceptedAt: null,- completedAt: null,- updatedAt: Date.now(),- ...overrides,- };-}--let listeners: Array<(payload: BotDelegationChangedPayload, ownerStamp?: unknown) => void> = [];-let listBotDelegations: ReturnType<typeof vi.fn>;-let cancelBotDelegation: ReturnType<typeof vi.fn>;-+vi.mock('@/features/device-link/remoteProjectsStore', () => ({+ remoteProjectsStore: { getSessionDeviceId: mocks.origin, pinSessionOrigin: mocks.pin },+}));+vi.mock('@/features/cc-agent/sidebar/SessionStatusIcon', () => ({+ SessionStatusIcon: ({ session, isRunning, isAttached }: any) => (+ <i+ data-testid="original-harness"+ data-kind={session.agentKind}+ data-running={isRunning}+ data-attached={isAttached}+ />+ ),+}));+const card: BotCollaborationMeta = {+ v: 1,+ role: 'delegation-request',+ delegationId: 'd',+ fromBotId: 'b',+ fromBotName: 'Cindy',+ toBotId: null,+ toBotName: 'Cindy',+ parentSessionId: 'parent',+ childSessionId: 'child',+ objective: 'Original request',+};+const data = (value = card) => ({ ...value });beforeEach(() => {- mocks.successfulPrStatuses = new Map();- mocks.prRefs = [];- mocks.prStatuses = new Map();- mocks.registerPrConsumer.mockClear();- mocks.invalidateRemotePrRefs.mockClear();- listeners = [];- mocks.remoteBots = [];- mocks.navigate.mockClear();- __resetBotDelegationLiveForTest();- listBotDelegations = vi.fn(async () => ({ ok: true as const, delegations: [] }));- cancelBotDelegation = vi.fn(async () => ({- ok: true as const,- delegationId: DELEGATION_ID,- childSessionId: 'child-1',- }));+ vi.clearAllMocks();+ mocks.row = null;+ mocks.activity = null;+ mocks.running = new Map();+ mocks.origin.mockReturnValue(undefined);+ mocks.get.mockResolvedValue({+ id: 'child',+ title: 'Current title',+ agentKind: 'codex',+ status: 'active',+ });+ mocks.route.mockResolvedValue('/cc-agent/child');Object.defineProperty(window, 'electronAPI', {configurable: true,- writable: true,value: {- openExternal: vi.fn().mockResolvedValue({ success: true }),- maker: {- listBotDelegations: (...args: unknown[]) => listBotDelegations(...args),- cancelBotDelegation: (...args: unknown[]) => cancelBotDelegation(...args),- onBotDelegationChanged: (- cb: (payload: BotDelegationChangedPayload, ownerStamp?: unknown) => void,- ) => {- listeners.push(cb);- return () => {- listeners = listeners.filter((listener) => listener !== cb);- };- },+ binding: {+ resolveSession: vi.fn(async () => ({ attached: false })),+ onChanged: () => () => {},},},});});--afterEach(() => {- cleanup();- remoteProjectsStore.clear();- remoteProjectsStore.__resetPinnedOriginsForTest();- __resetStickySessionOriginForTest();- __resetBotDelegationLiveForTest();+afterEach(cleanup);+it('only renders valid requesting-side task references', () => {+ const { container, rerender } = render(<BotSessionTaskCard />);+ expect(container.firstChild).toBeNull();+ rerender(<BotSessionTaskCard data={data({ ...card, role: 'guest-request' })} />);+ expect(container.firstChild).toBeNull();});--describe('BotSessionTaskCard', () => {- it('renders nothing when the marker is missing or malformed', () => {- const { container: empty } = render(<BotSessionTaskCard sessionId={SESSION_ID} />);- expect(empty.firstChild).toBeNull();- const { container: broken } = render(- <BotSessionTaskCard data={{ v: 2, role: 'delegation-request' }} sessionId={SESSION_ID} />,- );- expect(broken.firstChild).toBeNull();- });-- it('renders a Session task as a tracked background task', async () => {- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('running')] });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);-- expect(screen.queryByText('bots.collab.backgroundTask')).toBeNull();- await waitFor(() => expect(screen.getByText(/bots\.collab\.status\.running/)).toBeTruthy());- expect(screen.getByText('bots.collab.stopTask')).toBeTruthy();- });-- it('ignores historical target-side task mirrors', () => {- const { container } = render(- <BotSessionTaskCard- data={{- ...meta({ role: 'guest-request' }),- }}- sessionId={SESSION_ID}- />,- );-- expect(container.firstChild).toBeNull();- });-- it('does not roll a completed card back when an older running snapshot arrives late', async () => {- let finishOldRead!: (value: unknown) => void;- listBotDelegations.mockImplementationOnce(- () =>- new Promise((resolve) => {- finishOldRead = resolve;- }),- );- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('completed')] });- await act(async () => {- for (const listener of listeners)- listener({- delegationId: DELEGATION_ID,- parentSessionId: SESSION_ID,- childSessionId: 'child-1',- status: 'completed',- });- });- await screen.findByText(/bots\.collab\.status\.completed/);- await act(async () => {- finishOldRead({ ok: true, delegations: [delegation('running')] });- });- expect(screen.getByText(/bots\.collab\.status\.completed/)).toBeTruthy();- expect(screen.queryByText('bots.collab.stopTask')).toBeNull();- });-- it('stops the delegation through the existing cancel channel', async () => {- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('waiting')] });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- await waitFor(() => expect(screen.getByText('bots.collab.stopTask')).toBeTruthy());-- await act(async () => {- fireEvent.click(screen.getByText('bots.collab.stopTask'));- });- expect(cancelBotDelegation).toHaveBeenCalledWith(SESSION_ID, DELEGATION_ID);- });-- it('keeps the finished task, duration, and work-process entry visible', async () => {- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [- delegation('completed', { createdAt: 1_000, completedAt: 43_000, updatedAt: 43_000 }),- ],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);-- await screen.findByText(/bots\.collab\.status\.completed/);- // 用时走 i18n 单位,不再是硬编码的 `42s` —— 中文界面里 `42s` 和「用时」并排- // 读起来是两套语言。- expect(screen.getByText(/bots\.collab\.duration\.seconds/).textContent).not.toContain('42s');- expect(screen.queryByText('bots.collab.stopTask')).toBeNull();- expect(screen.getByText('方案任务')).toBeTruthy();- expect(screen.queryByText('做一版方案')).toBeNull();- fireEvent.click(screen.getByText(/bots\.collab\.watchWork/));- expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/child-1');- });-- it('keeps the full returned report out of the compact task card', async () => {- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [- delegation('completed', {- completedAt: Date.now(),- resultSummary: '三条结论:先砍范围、再补测试、最后再谈发布日期。',- }),- ],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- await screen.findByText(/bots\.collab\.status\.completed/);- expect(screen.queryByText(/三条结论/)).toBeNull();- });-- it('reports a stopped delegation as stopped, not as a failure', async () => {- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [delegation('cancelled', { completedAt: Date.now() })],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- expect(await screen.findByText(/bots\.collab\.status\.cancelled/)).toBeTruthy();- });-- it('says the work has not started yet while the first handoff is still being retried', async () => {- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [delegation('waiting', { lastError: 'AGENT_NOT_READY: pi not authenticated' })],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- // 「等待开始」和「正在做」以前长得一模一样:用户以为对方在干活,其实一次都没开始。- expect(await screen.findByText('bots.collab.retrying')).toBeTruthy();- });-- it('puts the failure reason directly on the task card', async () => {- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [- delegation('failed', {- completedAt: Date.now(),- lastError: 'ACCOUNT_NOT_READY: 需要登录后才能执行:当前没有可用的账号与模型来源。',- }),- ],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- const line = await screen.findByText(/需要登录后才能执行/);- expect(line.textContent).toContain('需要登录后才能执行');- expect(line.textContent).not.toContain('ACCOUNT_NOT_READY');- });-- it('renders an interjection as a quiet one-line trace', () => {- render(- <BotSessionTaskMessageTrace- data={{ ...meta({ role: 'interjection' }), text: '先别铺开,我只要三条。' }}- />,- );- expect(screen.getByText(/bots\.collab\.messageSent/)).toBeTruthy();- expect(screen.queryByText(/先别铺开,我只要三条。/)).toBeNull();- expect(screen.queryByText('bots.collab.stopTask')).toBeNull();- });-- it('keeps the last task state when a later refresh fails', async () => {- listBotDelegations- .mockResolvedValueOnce({- ok: true,- delegations: [- delegation('completed', {- completedAt: Date.now(),- resultSummary: '已经交付。',- }),- ],- })- .mockResolvedValueOnce({ ok: false });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);-- await screen.findByText(/bots\.collab\.status\.completed/);- act(() => {- listeners[0]?.({- delegationId: DELEGATION_ID,- parentSessionId: SESSION_ID,- childSessionId: 'child-1',- status: 'completed',- pendingInteraction: null,- });- });- await waitFor(() => expect(listBotDelegations).toHaveBeenCalledTimes(2));-- expect(screen.getByText(/bots\.collab\.status\.completed/)).toBeTruthy();- expect(screen.getByText('bots.collab.stale')).toBeTruthy();- expect(screen.queryByText(/bots\.collab\.status\.unknown/)).toBeNull();- });- /*- 空头支票复核 2026-08-19。任务行读不到时(例如首次列表请求失败),卡片以前- 一律回落到「正在开始」+ 呼吸点,而- 操作区又整块不渲染 —— 一张永远在跑、也点不进去的卡。它画出来的「进行中」- 没有任何东西背书。现在必须如实说状态查不到了、停止呼吸,并保留任务过程入口。- */- it('says the status is unverifiable instead of faking a forever-running card', async () => {- listBotDelegations.mockResolvedValue({ ok: false });- const { container } = render(- <BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />,- );-- await waitFor(() => expect(screen.getByText(/bots\.collab\.status\.unknown/)).toBeTruthy());- expect(screen.queryByText(/bots\.collab\.status\.queued/)).toBeNull();- // 没有背书的状态就不许有"还在跑"的动效。- expect(container.querySelector('.animate-pulse')).toBeNull();- expect(screen.queryByText('bots.collab.stopTask')).toBeNull();- expect(screen.getByText('bots.collab.watchWork')).toBeTruthy();- });-- it('keeps the optimistic running look while the first fetch is still in flight', async () => {- // 一直不 resolve —— 模拟「还没读到」,这与「读完了没有」必须区分开。- listBotDelegations.mockReturnValue(new Promise(() => {}));- const { container } = render(- <BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />,- );-- expect(screen.getByText(/bots\.collab\.status\.queued/)).toBeTruthy();- expect(screen.queryByText(/bots\.collab\.status\.unknown/)).toBeNull();- expect(container.querySelector('.animate-pulse')).toBeNull();- });-- it('reports a new failed + TIMEOUT task as timed out, not as a failure', async () => {- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [- delegation('timed-out', {- completedAt: Date.now(),- lastError: 'TIMEOUT: exceeded the deadline',- }),- ],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);-- await waitFor(() => expect(screen.getByText(/bots\.collab\.status\.timed-out/)).toBeTruthy());- expect(screen.queryByText(/bots\.collab\.status\.failed/)).toBeNull();- });-});--it('routes remote task reads, stop, child navigation and push refresh to the same Mac', async () => {- mocks.remoteBots = [{ deviceId: 'home', online: true }];- remoteProjectsStore.pinSessionOrigin('home', SESSION_ID);- let push!: (value: any, stamp?: any) => void;- let status!: (value: any) => void;- const invoke = vi.fn(async (_device: string, channel: string) =>- channel === 'maker:bot-delegations:list'- ? { ok: true, delegations: [delegation('running', { updatedAt: 1_000 })] }- : { ok: true },- );- window.electronAPI.deviceLink = {- invoke,- onRemotePush: (fn: any) => {- push = fn;- return () => {};- },- onStatusChanged: (fn: any) => {- status = fn;- return () => {};- },- } as any;- render(<BotSessionTaskCard sessionId={SESSION_ID} data={meta() as any} />);- const stop = await screen.findByRole('button', { name: 'bots.collab.stopTask' });- expect(mocks.registerPrConsumer).toHaveBeenCalledWith('child-1', 'home');- expect(invoke).toHaveBeenCalledWith('home', 'maker:bot-delegations:list', [SESSION_ID]);- expect(listBotDelegations).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: 'bots.collab.watchWork' }));- expect(remoteProjectsStore.getSessionDeviceId('child-1')).toBe('home');- // Even when reconnect clears the transient registry, stop must never hit the local maker.- remoteProjectsStore.clear();- remoteProjectsStore.__resetPinnedOriginsForTest();- fireEvent.click(stop);- await waitFor(() =>- expect(invoke).toHaveBeenCalledWith('home', 'maker:bot-delegation:cancel', [- SESSION_ID,- DELEGATION_ID,- ]),- );- expect(cancelBotDelegation).not.toHaveBeenCalled();- const reads = invoke.mock.calls.length;- act(() =>- push({- deviceId: 'office',- channel: 'maker:bot-delegation:changed',- payload: { parentSessionId: SESSION_ID },- }),- );- expect(invoke).toHaveBeenCalledTimes(reads);- mocks.invalidateRemotePrRefs.mockClear();- invoke.mockResolvedValue({- ok: true,- delegations: [- delegation('completed', { resultSummary: 'Remote done', updatedAt: 2_000 }),- ],- });- act(() => status({ status: 'online' }));- await screen.findByText(/bots\.collab\.status\.completed/);- await waitFor(() => expect(mocks.invalidateRemotePrRefs).toHaveBeenCalledWith('child-1'));+it('uses the actual session title and native harness, and opens that same session without mutating it', async () => {+ render(<BotSessionTaskCard data={data()} />);+ fireEvent.click(await screen.findByRole('button', { name: 'Current title' }));+ await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith('/cc-agent/child'));+ expect(mocks.route).toHaveBeenCalledWith('child', expect.objectContaining({ id: 'child' }));+ expect(screen.getByTestId('original-harness').getAttribute('data-kind')).toBe('codex');+ expect(screen.getAllByRole('button')).toHaveLength(1);});--it('opens the child session associated PR even when the report contains another link', async () => {- mocks.prRefs = [associatedPr(733)];- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [- delegation('completed', {- resultSummary:- '## Deliverables\n[PR](https://github.com/MakeCindy/Cindy/pull/733/files)\n/private/report.md',- artifacts: [{ path: '/private/report.md', status: 'added' }],- }),- ],- });- const { container } = render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- const pr = await screen.findByRole('button', { name: 'bots.collab.viewPr' });- const task = screen.getByRole('button', { name: 'bots.collab.watchWork' });- expect(pr.className).toBe(task.className);- expect(pr.className).toContain('h-8');- expect(container.textContent).not.toContain('/private/report.md');- expect(container.textContent).not.toContain('## Deliverables');- fireEvent.click(pr);- expect(window.electronAPI.openExternal).toHaveBeenCalledWith('https://github.com/a/b/pull/733');+it('takes actual runtime state instead of treating an ended delegation as completed work', async () => {+ mocks.row = { childSessionId: 'child', status: 'done' };+ mocks.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');+ expect(screen.queryByText('bots.collab.status.done')).toBeNull();});--it('does not mistake a contextual PR in the objective for the task result', async () => {- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('completed')] });- render(- <BotSessionTaskCard- data={{ ...meta({ objective: 'Compare https://github.com/a/b/pull/1' }) }}- sessionId={SESSION_ID}- />,+it('preserves archived identity when opening; viewing never calls unarchive', async () => {+ mocks.get.mockResolvedValue({+ id: 'child',+ title: 'Archived title',+ agentKind: 'pi',+ status: 'archived',+ });+ render(<BotSessionTaskCard data={data()} />);+ fireEvent.click(await screen.findByRole('button', { name: 'Archived title' }));+ await waitFor(() =>+ expect(mocks.route).toHaveBeenCalledWith(+ 'child',+ expect.objectContaining({ status: 'archived' }),+ ),);- await screen.findByText(/bots\.collab\.status\.completed/);- expect(screen.queryByRole('button', { name: 'bots.collab.viewPr' })).toBeNull();});--it('offers only the same three associated PRs as the task header', async () => {- mocks.prRefs = [1, 2, 3, 4, 5].map(associatedPr);- listBotDelegations.mockResolvedValue({- ok: true,- delegations: [- delegation('completed', {- resultSummary: 'https://github.com/a/b/pull/1 https://github.com/a/b/pull/2',- }),- ],- });- render(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- const button = await screen.findByRole('button', { name: 'bots.collab.viewPr' });- fireEvent.keyDown(button, { key: 'Enter' });- const choice = await screen.findByRole('menuitem', { name: 'a/b #2' });- expect(screen.getAllByRole('menuitem')).toHaveLength(3);- expect(screen.getByText('bots.collab.prCount:{"count":3}')).toBeTruthy();- expect(screen.queryByRole('menuitem', { name: 'a/b #4' })).toBeNull();- expect(window.electronAPI.openExternal).not.toHaveBeenCalled();- fireEvent.click(choice);- expect(window.electronAPI.openExternal).toHaveBeenCalledWith('https://github.com/a/b/pull/2');-});--it('subscribes to the child session PR state and updates its icon without enlarging actions', async () => {- mocks.prRefs = [associatedPr(4)];- mocks.prStatuses = new Map([['a/b#4', { ok: true, status: 'open' }]]);- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('running')] });- const { rerender, container } = render(- <BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />,- );- await screen.findByRole('button', { name: 'bots.collab.viewPr' });- expect(mocks.registerPrConsumer).toHaveBeenCalledWith('child-1', undefined);- const button = screen.getByRole('button', { name: 'bots.collab.viewPr' });- const before = button.className;- mocks.prStatuses = new Map([['a/b#4', { ok: true, status: 'merged' }]]);- rerender(<BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />);- expect(container.querySelector('.lucide-git-merge')).not.toBeNull();- expect(button.className).toBe(before);+it('keeps a readable fallback when metadata is unavailable without inventing a harness', async () => {+ mocks.get.mockRejectedValue(new Error('offline'));+ render(<BotSessionTaskCard data={data()} />);+ await waitFor(() => expect(mocks.get).toHaveBeenCalled());+ expect(+ (screen.getByRole('button', { name: 'Original request' }) as HTMLButtonElement).disabled,+ ).toBe(false);+ expect(screen.queryByTestId('original-harness')).toBeNull();});--it('shows stale details on a rejected query while retaining the confirmed icon and button', async () => {- mocks.prRefs = [associatedPr(4)];- mocks.prStatuses = new Map([['a/b#4', { ok: true, status: 'merged' }]]);- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('completed')] });- const view = () => <BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />;- const { rerender, container } = render(view());- const button = await screen.findByRole('button', { name: 'bots.collab.viewPr' });- const classes = button.className;- mocks.refreshError = true;- rerender(view());- expect(screen.getByText('bots.collab.stale')).toBeTruthy();- expect(container.querySelector('.lucide-git-merge')).not.toBeNull();- expect(button.className).toBe(classes);- mocks.refreshError = false;- rerender(view());- expect(screen.queryByText('bots.collab.stale')).toBeNull();+it('pins remote child reads and navigation to the parent device', async () => {+ mocks.origin.mockImplementation((id: string) => (id === 'parent' ? 'mac-a' : undefined));+ render(<BotSessionTaskCard data={data()} />);+ await screen.findByRole('button', { name: 'Current title' });+ expect(mocks.pin).toHaveBeenCalledWith('mac-a', 'child');});--it('renders confirmed shared PR icons on failures and clears them when the shared cache resets', async () => {- mocks.prRefs = [associatedPr(4)];- mocks.prStatuses = new Map([['a/b#4', { ok: true, status: 'merged' }]]);- listBotDelegations.mockResolvedValue({ ok: true, delegations: [delegation('completed')] });- const view = () => <BotSessionTaskCard data={{ ...meta() }} sessionId={SESSION_ID} />;- const { rerender, container } = render(view());- await screen.findByRole('button', { name: 'bots.collab.viewPr' });- mocks.successfulPrStatuses = new Map(mocks.prStatuses);- for (const reason of ['fetch-failed', 'no-token']) {- mocks.prStatuses = new Map([['a/b#4', { ok: false, reason }]]);- rerender(view());- expect(container.querySelector('.lucide-git-merge')).not.toBeNull();- expect(screen.getByText('bots.collab.stale')).toBeTruthy();- }- mocks.prStatuses = new Map([['a/b#4', { ok: true, status: 'closed' }]]);- rerender(view());- expect(container.querySelector('.lucide-git-pull-request-closed')).not.toBeNull();- expect(screen.queryByText('bots.collab.stale')).toBeNull();- mocks.successfulPrStatuses = new Map();- mocks.prStatuses = new Map([['a/b#4', { ok: false, reason: 'no-token' }]]);- rerender(view());- expect(container.querySelector('.lucide-git-pull-request-closed')).toBeNull();+it('does not read a conflicting child origin', () => {+ mocks.origin.mockImplementation((id: string) => (id === 'parent' ? 'mac-a' : 'mac-b'));+ render(<BotSessionTaskCard data={data()} />);+ expect(mocks.get).not.toHaveBeenCalled();});--it('subscribes only visible task cards and retains cached PR actions outside the viewport', async () => {- const observers: Array<{ callback: IntersectionObserverCallback; disconnect: ReturnType<typeof vi.fn> }> = [];- vi.stubGlobal('IntersectionObserver', class {- disconnect = vi.fn();- observe = vi.fn();- constructor(callback: IntersectionObserverCallback) {- observers.push({ callback, disconnect: this.disconnect });- }- });- const release = vi.fn();- mocks.registerPrConsumer.mockImplementation(() => release);- mocks.remoteBots = [{ deviceId: 'home', online: true }];- remoteProjectsStore.pinSessionOrigin('home', SESSION_ID);- mocks.prRefs = [associatedPr(1)];- window.electronAPI.deviceLink = {- invoke: vi.fn(async () => ({ ok: true, delegations: [delegation('completed', { updatedAt: 1_000 })] })),- onRemotePush: () => () => {},- onStatusChanged: () => () => {},- } as any;- const view = render(<>- <BotSessionTaskCard sessionId={SESSION_ID} data={{ ...meta() }} />- <BotSessionTaskCard sessionId={SESSION_ID} data={{ ...meta() }} />- </>);- try {- await screen.findAllByRole('button', { name: 'bots.collab.viewPr' });- expect(observers).toHaveLength(2);- expect(mocks.registerPrConsumer).not.toHaveBeenCalled();- expect(mocks.invalidateRemotePrRefs).not.toHaveBeenCalled();- const report = (index: number, visible: boolean) => act(() => {- observers[index].callback([{ isIntersecting: visible, intersectionRatio: visible ? 1 : 0 } as IntersectionObserverEntry], {} as IntersectionObserver);- });- report(0, true);- expect(mocks.registerPrConsumer).toHaveBeenCalledTimes(1);- expect(mocks.registerPrConsumer).toHaveBeenCalledWith('child-1', 'home');- expect(mocks.invalidateRemotePrRefs).toHaveBeenCalledTimes(1);- report(0, false);- expect(release).toHaveBeenCalledTimes(1);- expect(screen.getAllByRole('button', { name: 'bots.collab.viewPr' })).toHaveLength(2);- report(1, true);- expect(mocks.registerPrConsumer).toHaveBeenCalledTimes(2);- report(1, false);- report(0, true);- expect(mocks.registerPrConsumer).toHaveBeenCalledTimes(3);- view.unmount();- expect(release).toHaveBeenCalledTimes(3);- expect(observers.every((observer) => observer.disconnect.mock.calls.length === 1)).toBe(true);- } finally {- view.unmount();- mocks.registerPrConsumer.mockImplementation(() => () => {});- vi.unstubAllGlobals();- }+it('keeps interjections as quiet traces', () => {+ render(<BotSessionTaskMessageTrace data={data({ ...card, role: 'interjection' })} />);+ expect(screen.getByText('bots.collab.messageSent')).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsxindex 29991e4631..cb81f8d8ed 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotSessionTaskResultCard.test.tsx@@ -1,3 +1,4 @@+vi.mock('../BotSessionTaskLink', () => ({ BotSessionTaskLink: () => <span data-testid="original-session-link" /> }));import { readBotCollaborationMeta } from '../../../../shared/botCollaboration';// @vitest-environment jsdomimport { render, screen, cleanup, fireEvent } from '@testing-library/react';diff --git a/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsxnew file mode 100644index 0000000000..da5d6a46a0--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/WorkbenchSessionList.test.tsx@@ -0,0 +1,112 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { WorkbenchSessionList } from '../WorkbenchSessionList';+const m = vi.hoisted(() => ({+ run: vi.fn(),+ unarchive: vi.fn(),+ navigate: vi.fn(),+ confirm: vi.fn(),+ preflight: vi.fn(),+ close: vi.fn(),+ binding: vi.fn(),+ running: new Set<string>(),+ attached: new Set<string>(),+ changed: vi.fn(),+ warning: vi.fn(),+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (s: string) => s }) }));+vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));+vi.mock('@/features/cc-agent/sidebar/SessionCard', () => ({+ SessionCard: (p: any) => (+ <div data-testid="native-row" data-variant={p.variant} data-status={p.session.status}>+ <button onClick={() => p.onClick(p.session.id)}>open</button>+ <button onClick={() => p.onAction(p.session.id, 'unarchive')}>restore</button>+ <button onClick={() => p.onAction(p.session.id, 'archive', 'shared')}>archive</button>+ </div>+ ),+}));+vi.mock('@/features/cc-agent/hooks/useSessionLifecycleActions', () => ({+ useSessionLifecycleActions: () => ({ runSessionAction: m.run, unarchiveSession: m.unarchive }),+}));+vi.mock('@/features/cc-agent/hooks/useSessionDisplayRunningState', () => ({+ useSessionDisplayRunningState: () => ({ displayRunningSessionIds: m.running }),+}));+vi.mock('@/hooks/useSessionRunningStatus', () => ({+ useSessionRunningStatus: () => ({+ runningSessionIds: m.running,+ notifications: new Set(),+ clearNotification: vi.fn(),+ }),+}));+vi.mock('@/hooks/useAttachedSessionIds', () => ({ useAttachedSessionIds: () => m.attached }));+vi.mock('@/components/ui/confirm-dialog-provider', () => ({+ useConfirmDialog: () => ({ confirm: m.confirm }),+}));+vi.mock('@/lib/orcaSessionIdentity', () => ({+ resolveSessionRoute: async (id: string) => '/cc-agent/' + id,+}));+vi.mock('@/lib/worktreeRemovalWarning', () => ({ resolveWorktreeRemovalPreflight: m.preflight }));+vi.mock('@/lib/sessionsStore', () => ({ sessionsStore: { patchLocal: vi.fn() } }));+vi.mock('@/lib/sessionService', () => ({ patchMeta: vi.fn(), update: vi.fn() }));+vi.mock('@/features/cc-agent/hooks/helpers/sidebarFilterCore', () => ({+ persistManualPinnedOrder: vi.fn(),+}));+vi.mock('@/lib/toast', () => ({ toast: { warning: m.warning, error: vi.fn() } }));+const row = {+ id: 'original',+ title: 'Original',+ status: 'archived',+ agentKind: 'codex',+ workingDir: '/project',+} as any;+beforeEach(() => {+ vi.clearAllMocks();+ m.running = new Set();+ m.attached = new Set();+ m.confirm.mockResolvedValue(true);+ m.preflight.mockResolvedValue('clean');+ m.close.mockResolvedValue({ closed: ['shared'] });+ m.binding.mockResolvedValue({ attached: false });+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { binding: { resolveSession: m.binding }, sharedTask: { account: m.close } },+ });+});+afterEach(cleanup);+it('opens the original archived session through the native row without restoring it', async () => {+ render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);+ expect(screen.getByTestId('native-row').getAttribute('data-variant')).toBe('list');+ fireEvent.click(screen.getByText('open'));+ await waitFor(() => expect(m.navigate).toHaveBeenCalledWith('/cc-agent/original'));+ expect(m.unarchive).not.toHaveBeenCalled();+ expect(m.run).not.toHaveBeenCalled();+});+it('restores only through the explicit existing lifecycle action', async () => {+ render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);+ fireEvent.click(screen.getByText('restore'));+ await waitFor(() => expect(m.unarchive).toHaveBeenCalledWith('original'));+});+it.each(['running', 'attached'] as const)('retains the %s archive guard', async (kind) => {+ m[kind].add('original');+ render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);+ fireEvent.click(screen.getByText('archive'));+ await waitFor(() => expect(m.warning).toHaveBeenCalled());+ expect(m.run).not.toHaveBeenCalled();+});+it('cancelling unknown worktree confirmation does not close sharing or archive', async () => {+ m.preflight.mockResolvedValue('unknown');+ m.confirm.mockResolvedValue(false);+ render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);+ fireEvent.click(screen.getByText('archive'));+ await waitFor(() => expect(m.confirm).toHaveBeenCalled());+ expect(m.close).not.toHaveBeenCalled();+ expect(m.run).not.toHaveBeenCalled();+});+it('does not archive a shared task when existing shared close fails', async () => {+ m.close.mockResolvedValue({ closed: [] });+ render(<WorkbenchSessionList sessions={[row]} onChanged={m.changed} />);+ fireEvent.click(screen.getByText('archive'));+ await waitFor(() => expect(m.close).toHaveBeenCalled());+ expect(m.run).not.toHaveBeenCalled();+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.tsindex 935ea55e18..e12b4a68ab 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts@@ -223,3 +223,33 @@ it('keeps explicitly delivered group private messages while the private model isexpect(proseIds(project(input, true))).toEqual(['group']);expect(proseIds(project([...input, message('final', 'assistant', 'Result', { turnCompleted: true })], false))).toEqual(['group', 'final']);});+++describe('provider final streaming', () => {+ it('keeps incremental final text visible before and after the seal, excluding commentary', () => {+ const prefix = [message('u', 'user'), message('process', 'assistant', 'Internal', { assistantPhase: 'commentary' })];+ for (const text of ['A', 'Answer', 'Answer with a reference']) {+ const final = message('answer', 'assistant', text, { assistantPhase: 'final_answer', isStreaming: true });+ expect(proseIds(project([...prefix, final], true))).toEqual(['answer']);+ expect(proseIds(project([...prefix, { ...final, message: { ...final.message, isStreaming: false } }], true))).toEqual(['answer']);+ }+ expect(proseIds(project([...prefix, message('answer', 'assistant', 'Answer', { assistantPhase: 'final_answer', turnCompleted: true })], false))).toEqual(['answer']);+ });+});++it('does not insert interleaved valid receipts ahead of live final prose and preserves exact host bindings', () => {+ const card = (id: string) => ({ v: 1 as const, role: 'delegation-result' as const, delegationId: id, fromBotId: 'bot',+ fromBotName: 'Cindy', toBotId: null, toBotName: '', parentSessionId: 'chat', childSessionId: id, objective: id,+ result: { runSequence: 1, status: 'completed' as const, text: 'Report', artifacts: [] } });+ const a = card('a'), b = card('b');+ const receipt = (id: string, data: ReturnType<typeof card>) => message(id, 'assistant', '', { systemCardType: 'bot-session-task-result', systemCardData: data });+ const streaming = message('answer', 'assistant', 'First words', { assistantPhase: 'final_answer', isStreaming: true });+ const input = [message('u', 'user'), streaming, receipt('b-result', b), receipt('a-result', a)];+ expect(allKeys(project(input, true))).toEqual(['msg-u', 'msg-answer']);+ const ended = { ...streaming, message: { ...streaming.message, isStreaming: false, turnCompleted: true, botTaskResults: [a] } };+ const visible = project([input[0], ended, ...input.slice(2)], false);+ expect(allKeys(visible)).toEqual(['msg-u', 'msg-answer', 'msg-b-result']);+ expect(ended.message.botTaskResults.map(value => value.childSessionId)).toEqual(['a']);+ // No final reply: every frozen result has a lightweight fallback once execution settles.+ expect(allKeys(project(input.slice(2), false))).toEqual(['msg-b-result', 'msg-a-result']);+});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsxnew file mode 100644index 0000000000..460030c31e--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/__tests__/useWorkbenchSessionPages.test.tsx@@ -0,0 +1,102 @@+// @vitest-environment jsdom+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { useWorkbenchSessionPages } from '../useWorkbenchSessionPages';+const mocks = vi.hoisted(() => ({+ list: vi.fn(),+ generation: 1,+ patch: null as any,+ reset: null as any,+}));+vi.mock('@/lib/sessionService', () => ({ list: mocks.list }));+vi.mock('@/contexts/dataOwnerGeneration', () => ({+ getDataOwnerGeneration: () => mocks.generation,+ isDataOwnerGenerationCurrent: (g: number) => g === mocks.generation,+}));+vi.mock('@/lib/sessionsBus', () => ({+ onRefresh: () => () => {},+ onPatch: (cb: any) => {+ mocks.patch = cb;+ return () => {};+ },+}));+vi.mock('@/lib/sessionsStore', () => ({+ sessionsStore: {+ subscribe: (cb: any) => {+ mocks.reset = cb;+ return () => {};+ },+ },+}));+const page = Array.from({ length: 200 }, (_, n) => ({+ id: `s${n}`,+ status: 'archived',+ updatedAt: new Date(1000 - n).toISOString(),+ title: `Task ${n}`,+}));+beforeEach(() => {+ mocks.list.mockReset();+ mocks.generation = 1;+});+afterEach(cleanup);+it('does not query collapsed archives; full pages expose continuation and stable cursor', async () => {+ mocks.list+ .mockResolvedValueOnce(page)+ .mockResolvedValueOnce([{ ...page[199], id: 'older', updatedAt: new Date(800).toISOString() }]);+ const { result, rerender } = renderHook(+ ({ enabled }) => useWorkbenchSessionPages('b', 'archived', enabled),+ { initialProps: { enabled: false } },+ );+ expect(mocks.list).not.toHaveBeenCalled();+ rerender({ enabled: true });+ await waitFor(() => expect(result.current.rows.length).toBe(200));+ expect(result.current.hasMore).toBe(true);+ await act(() => result.current.load());+ expect(mocks.list).toHaveBeenLastCalledWith(200, 'archived', {+ fresh: true,+ before: { updatedAt: 801, id: 's199' },+ });+ expect(result.current.rows.length).toBe(201);+ expect(result.current.hasMore).toBe(false);+});+it('keeps loaded history and its cursor on query failure, then retries without duplicates', async () => {+ mocks.list+ .mockResolvedValueOnce(page)+ .mockRejectedValueOnce(new Error('unavailable'))+ .mockResolvedValueOnce([page[199]]);+ const { result } = renderHook(() => useWorkbenchSessionPages('b', 'archived', true));+ await waitFor(() => expect(result.current.rows.length).toBe(200));+ await act(() => result.current.load());+ expect(result.current.error).toBe(true);+ expect(result.current.rows.length).toBe(200);+ await act(() => result.current.load());+ expect(result.current.error).toBe(false);+ expect(result.current.rows.length).toBe(200);+});+it('drops a late query from a different account/scope', async () => {+ let resolve!: (value: any) => void;+ mocks.list+ .mockReturnValueOnce(+ new Promise((r) => {+ resolve = r;+ }),+ )+ .mockResolvedValueOnce([]);+ const { result, rerender } = renderHook(+ ({ scope }) => useWorkbenchSessionPages(scope, 'archived', true),+ { initialProps: { scope: 'a' } },+ );+ mocks.generation++;+ rerender({ scope: 'b' });+ await act(async () => {+ resolve(page);+ });+ expect(result.current.rows).toEqual([]);+});+it('applies original session title/status patches without inferring completion', async () => {+ mocks.list.mockResolvedValueOnce([page[0]]);+ const { result } = renderHook(() => useWorkbenchSessionPages('b', 'archived', true));+ await waitFor(() => expect(result.current.rows.length).toBe(1));+ act(() => mocks.patch('s0', { title: 'New title', status: 'active' }));+ expect(result.current.rows[0]).toMatchObject({ title: 'New title', status: 'active' });+});diff --git a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.tsindex f9c31f6b65..c43e74dee6 100644--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts@@ -37,8 +37,8 @@ function expandWorkGroups(items: readonly RenderItem[]): RenderItem[] {/** A presentation-only projection. Never mutate messages or infer intent from prose.* isFinal from the adapters closes a text block, not a turn (Pi/Claude can call- * another tool afterwards). Reuse the normal work-group turn seal, omitting- * unsealed prose while running. The composer owns live action+ * another tool afterwards). Reuse the normal work-group turn seal, showing provider-marked final prose immediately while keeping+ * unclassified intermediate prose hidden. The composer owns live action* feedback. On stop/error or old history without a seal, expose the last useful* prose so an answer or plain-text question cannot disappear permanently.*/@@ -70,11 +70,20 @@ export function simplifyBotRenderItems(const attached = new Set(result.flatMap(item => item.type === 'message'&& item.message.role === 'assistant' && item.message.turnCompleted === true && item.message.content.trim()? (item.message.botTaskResults ?? []).map(botTaskResultKey) : []));- return result.filter(item => {+ const lastSealedIndex = result.findLastIndex(item => isProse(item) && isCompletedAssistantMessage(item.message));+ const fallbackReceipts: RenderItem[] = [];+ const visible = result.filter((item, index) => {if (item.type !== 'message' || item.message.systemCardType !== 'bot-session-task-result') return true;const card = readBotCollaborationMeta(item.message.systemCardData);- return !card?.result || !attached.has(botTaskResultKey(card));+ if (!card?.result) return true;+ if (attached.has(botTaskResultKey(card))) return false;+ // An unrelated later turn must not erase an already historical fallback link.+ if (index < lastSealedIndex) return true;+ if (!isStreaming) fallbackReceipts.push(item);+ return false;});+ // Unanswered/failed deliveries remain reachable without inserting ahead of a live reply.+ return [...visible, ...fallbackReceipts];}function projectWindow(@@ -123,7 +132,8 @@ function projectWindow(if (item.type === 'message' && item.message.isSyntheticTrigger) return;if (isProse(item)) {if (!item.message.content.trim() && !hasAttachments(item.message)) return;- if (!item.message.sourceGroup && !item.message.explicitDelivery && !isCompletedAssistantMessage(item.message) && !sealedAnswers.has(item.message)+ if (item.message.assistantPhase === 'commentary' && !item.message.explicitDelivery && !hasAttachments(item.message)) return;+ if (item.message.assistantPhase !== 'final_answer' && !item.message.sourceGroup && !item.message.explicitDelivery && !isCompletedAssistantMessage(item.message) && !sealedAnswers.has(item.message)&& !hasAttachments(item.message) && index !== fallbackProse&& extractRenderedMarkdownImageTargets(item.message.content).length === 0) {return;diff --git a/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.tsnew file mode 100644index 0000000000..f132dd7348--- /dev/null+++ b/apps/desktop/src/renderer/features/bots/useWorkbenchSessionPages.ts@@ -0,0 +1,113 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import type { Session } from '@/lib/ccAgent.types';+import * as sessionService from '@/lib/sessionService';+import {+ getDataOwnerGeneration,+ isDataOwnerGenerationCurrent,+} from '@/contexts/dataOwnerGeneration';+import { onPatch, onRefresh } from '@/lib/sessionsBus';+import { sessionsStore } from '@/lib/sessionsStore';++const PAGE_SIZE = 200;+/** Bounded local reads; a full page never means all history has loaded. */+export function useWorkbenchSessionPages(+ scope: string,+ status: 'active' | 'archived',+ enabled: boolean,+) {+ const [rows, setRows] = useState<Session[]>([]);+ const [loading, setLoading] = useState(false);+ const [error, setError] = useState(false);+ const [hasMore, setHasMore] = useState(true);+ const cursor = useRef<{ updatedAt: number; id: string } | undefined>(undefined);+ const busy = useRef(false);+ const generation = useRef(0);+ const enabledRef = useRef(enabled);+ enabledRef.current = enabled;+ const started = useRef(false);+ const load = useCallback(async () => {+ if (busy.current) return;+ started.current = true;+ busy.current = true;+ setLoading(true);+ setError(false);+ const version = generation.current;+ const owner = getDataOwnerGeneration();+ try {+ const page = await sessionService.list(PAGE_SIZE, status, {+ fresh: true,+ before: cursor.current,+ });+ if (version !== generation.current || !isDataOwnerGenerationCurrent(owner)) return;+ setRows((previous) => [+ ...new Map([...previous, ...page].map((row) => [row.id, row])).values(),+ ]);+ setHasMore(page.length === PAGE_SIZE);+ const tail = page.at(-1);+ if (tail) cursor.current = { updatedAt: Date.parse(tail.updatedAt), id: tail.id };+ } catch {+ if (version === generation.current && isDataOwnerGenerationCurrent(owner)) setError(true);+ } finally {+ if (version === generation.current) {+ busy.current = false;+ setLoading(false);+ }+ }+ }, [status]);+ useEffect(() => {+ generation.current++;+ started.current = false;+ cursor.current = undefined;+ busy.current = false;+ setRows([]);+ setHasMore(true);+ setError(false);+ setLoading(false);+ if (enabledRef.current) void load();+ const offPatch = onPatch((id, patch) =>+ setRows((previous) => previous.map((row) => (row.id === id ? { ...row, ...patch } : row))),+ );+ const unsubscribe = sessionsStore.subscribe((change) => {+ if (change !== 'reset') return;+ started.current = false;+ generation.current++;+ cursor.current = undefined;+ busy.current = false;+ setRows([]);+ setHasMore(true);+ setError(false);+ setLoading(false);+ if (enabledRef.current) void load();+ });+ const offRefresh = onRefresh(() => {+ if (!enabledRef.current || busy.current) return;+ const version = generation.current;+ const owner = getDataOwnerGeneration();+ // Refresh only the head; loaded older pages and their continuation stay in place.+ void sessionService+ .list(PAGE_SIZE, status, { fresh: true })+ .then((page) => {+ if (version !== generation.current || !isDataOwnerGenerationCurrent(owner)) return;+ setRows((previous) => {+ const latest = new Map(page.map((row) => [row.id, row]));+ const ids = new Set(previous.map((row) => row.id));+ return [+ ...page.filter((row) => !ids.has(row.id)),+ ...previous.map((row) => latest.get(row.id) ?? row),+ ];+ });+ })+ .catch(() => {});+ });+ return () => {+ offRefresh();+ generation.current++;+ unsubscribe();+ offPatch();+ };+ }, [scope, status, load]);+ useEffect(() => {+ if (enabled && !started.current) void load();+ }, [enabled, load]);+ return { rows, loading, error, hasMore, load };+}diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex a42226824b..504792eb63 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -508,6 +508,8 @@ export interface ChatMessage {sourceGroup?: MessageSourceGroup;/** Host-stamped delivery remains visible after source identity is redacted. */explicitDelivery?: boolean;+ /** Provider phase survives live deltas and durable history projection. */+ assistantPhase?: string;/** user 消息投递方式:普通新 turn 或运行中 steer。 */delivery?: 'turn' | 'steer';/** Hook 来源元数据(IM 平台 + 用户干净原文 + thread 上下文),UserMessage 据此渲染 Cindy 任务卡片。 */@@ -5582,10 +5584,14 @@ export function handleStreamEvent(// 让后台任务自动续跑时前一轮正式总结不会被后续补充回复顶掉。const assistantMetaFields: {botPrivateReply?: boolean;+ assistantPhase?: string;model?: string;parentToolUseId?: string;turnCompleted?: boolean;} = {+ ...(typeof (event.data as { phase?: unknown })?.phase === 'string'+ ? { assistantPhase: (event.data as { phase: string }).phase }+ : typeof incomingMeta?.assistantPhase === 'string' ? { assistantPhase: incomingMeta.assistantPhase } : {}),...(typeof incomingMeta?.model === 'string' && incomingMeta.model? { model: incomingMeta.model }: {}),@@ -5740,6 +5746,7 @@ export function handleStreamEvent(// 把 model/parentToolUseId 补写到在途流式 assistant 消息上,否则纯文本(零工具)// 子代理在流式渲染期间 buildSubagentModelMap 始终为空、chip 缺失(仅重载后才补上)。const hasAssistantFields =+ assistantMetaFields.assistantPhase !== undefined ||assistantMetaFields.model !== undefined ||assistantMetaFields.parentToolUseId !== undefined ||assistantMetaFields.turnCompleted === true ||@@ -7610,7 +7617,10 @@ function enqueueTextDeltaPayload(existing.text += text;if (!existing.persistId && persistId) existing.persistId = persistId;if (event.source) existing.source = event.source;- if (event.agentMeta) existing.agentMeta = event.agentMeta;+ if (event.agentMeta) existing.agentMeta = { ...existing.agentMeta, ...event.agentMeta };+ if (typeof (event.data as { phase?: unknown }).phase === 'string') {+ existing.agentMeta = { ...existing.agentMeta, assistantPhase: (event.data as { phase: string }).phase };+ }} else {pendingTextDeltaBatches.set(sessionId, {text,@@ -7618,7 +7628,10 @@ function enqueueTextDeltaPayload(ingress,source: event.source,persistId,- ...(event.agentMeta ? { agentMeta: event.agentMeta } : {}),+ agentMeta: { ...event.agentMeta,+ ...(typeof (event.data as { phase?: unknown }).phase === 'string'+ ? { assistantPhase: (event.data as { phase: string }).phase } : {}),+ },});}scheduleTextDeltaFlush();@@ -18840,6 +18853,7 @@ function mapServerMessages(serverMsgs: Message[]): ChatMessage[] {role: m.role,content: typeof m.content === 'string' ? m.content : JSON.stringify(m.content),...(m.role === 'assistant' ? { sourceGroup: readMessageSourceGroup(m.agentMeta) } : {}),+ ...(m.role === 'assistant' && typeof m.agentMeta?.assistantPhase === 'string' ? { assistantPhase: m.agentMeta.assistantPhase } : {}),...(m.role === 'assistant' && m.agentMeta?.explicitDelivery === true ? { explicitDelivery: true } : {}),...(m.role === 'assistant' ? { botLearning: m.agentMeta?.botLearning } : {}),...(m.agentMeta?.botPrivateReply === true ? { botPrivateReply: true } : {}),diff --git a/apps/desktop/src/renderer/lib/sessionService.ts b/apps/desktop/src/renderer/lib/sessionService.tsindex 78683c59f5..92d9a5c296 100644--- a/apps/desktop/src/renderer/lib/sessionService.ts+++ b/apps/desktop/src/renderer/lib/sessionService.ts@@ -55,6 +55,8 @@ function wrap<T>(p: Promise<T>): Promise<T> {const getInFlight = new Map<string, Promise<Session>>();export type SessionListOptions = {+ /** Local list continuation; does not change the default capped query. */+ before?: { updatedAt: number; id: string };includePinned?: boolean;/** forceRefresh / status 重拉:绕开 main 侧 in-flight 合并。 */fresh?: boolean;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 188e070f6a..9e5cb375a5 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1133,6 +1133,8 @@ type CindyMediaPreferenceKind = {};type ElectronLocalDbSessionListOptions = {+ /** Local list continuation; does not change the default capped query. */+ before?: { updatedAt: number; id: string };includePinned?: boolean;fresh?: boolean;usageHistory?: boolean;diff --git a/docs/design-rules/examples/bot-session-list/README.md b/docs/design-rules/examples/bot-session-list/README.mdnew file mode 100644index 0000000000..a340059c6f--- /dev/null+++ b/docs/design-rules/examples/bot-session-list/README.md@@ -0,0 +1,3 @@+# Teammate workbench session rows++Light/Dark reference captures render the existing `SessionCard` list variant with synthetic sessions, original harness icons and an expanded archive section. These are component-fixture captures, not a signed-in application or account-history acceptance test. The workbench retains its existing project and non-session panels outside this crop.diff --git a/docs/design-rules/examples/bot-session-list/dark.png b/docs/design-rules/examples/bot-session-list/dark.pngnew file mode 100644index 0000000000..58165f1a46Binary files /dev/null and b/docs/design-rules/examples/bot-session-list/dark.png differdiff --git a/docs/design-rules/examples/bot-session-list/light.png b/docs/design-rules/examples/bot-session-list/light.pngnew file mode 100644index 0000000000..07f8b5dddeBinary files /dev/null and b/docs/design-rules/examples/bot-session-list/light.png differdiff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex d8fc8979d3..fe8468afc3 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -308,11 +308,12 @@ Session 任务遵守同一套机制与呈现契约:- **代理恢复选择**:发起伙伴可通过任务专属公共工具查看该任务的当前路由及其下一条已配置候选;只在本轮执行结束后由伙伴明确选择切换。切换不自动重放工作;伙伴结合原目标和已完成动作,再决定是否向同一任务发补充消息。未配置的供应商或型号不可擅自加入候选。-- **任务卡**:发起方消息流原位出现一张持久任务卡,实时反映排队 / 执行 / 等待 / 终态。- 卡片不得使用“加入对话”等通讯语言,也不得再叠加顶部运行条或另造一套协同面板。状态由任务- 行推送驱动,不靠消息文本。-- **执行结果入口**:完成结果属于伙伴收尾回复末尾的紧凑附件,正文先读,卡片与该条回复同列、同一容器归属。宿主以本轮实际消费的完成信号绑定冻结结果,成功收尾后随回复持久保存;同轮多结果分别附上,不按相邻消息、时间或正文猜配,不把所有卡移到时间线末尾。忙时尚未消费的队列不参与当前回复;每个结果还必须有该完成输入持久化之后生成的新正文,旧正文延迟落库、同毫秒无法确认顺序或输入记录缺失时保留独立入口。重复信号不重复绑定,续跑按执行代次保留独立结果。+- **任务入口**:Desktop 发起方消息流保留原任务的轻量文本链接,标题与 harness 图标读取同一个 Session;悬停/聚焦按需预览,点击进入原任务。运行呼吸复用原 `SessionStatusIcon`,不从委派终态推断事项完成。Mobile 继续使用既有任务卡入口,存储与绑定合同不变。+ Desktop 伙伴工作台的 Session 部分复用 `SessionCard` 列表及既有菜单,不另造任务身份、生命周期或完成分组;项目关联、隐藏任务和活动时间范围沿用既有投影。非 Session 待办、PR metadata、外部任务及自动化保留原记录与入口。+ 已归档 Session 在列表底部默认折叠,只依据原 `status=archived` 字段;展开按页查询历史,完整一页不等于全部历史。打开查看不取消归档,恢复仍须显式操作。分页仅为本机可信 renderer 扩展,不向旧远端假报支持。+- **执行结果入口**:Desktop 使用轻量任务引用与按需展开的冻结结果;完成结果属于伙伴收尾回复末尾的紧凑附件,正文先读,卡片与该条回复同列、同一容器归属。宿主以本轮实际消费的完成信号绑定冻结结果,成功收尾后随回复持久保存;同轮多结果分别附上,不按相邻消息、时间或正文猜配,不把所有卡移到时间线末尾。忙时尚未消费的队列不参与当前回复;每个结果还必须有该完成输入持久化之后生成的新正文,旧正文延迟落库、同毫秒无法确认顺序或输入记录缺失时保留独立入口。重复信号不重复绑定,续跑按执行代次保留独立结果。原任务卡和消息顺序不变。结果先按既有机制独立持久化;没有最终正文、失败或中断、关联读取失败、旧记录没有关联、或仅加载到原回执时,保留独立结果入口,不伪造总结、不改用户历史库。关联回复加载后,其对应独立回执只在伙伴展示投影中收起。旧客户端忽略新增的可选 `botTaskResults`,继续显示独立回执。新回执保存当次子任务标题;旧回执只读回退到已有任务标题,再回退到目标首行。附件冻结的状态、正文、文件与错误不从当前任务覆盖。普通任务、执行调度与自动化静默不改变。+ Desktop 流式展示透传 provider 的 `final_answer` phase,首个 final delta 即可见;commentary 继续隐藏。未知 phase 不凭文本猜测,仍遵守既有收尾兜底。未绑定的新回执在当前流式期间不插队,结束且无对应正文时保留轻入口;不靠模型编造任务 URL。实现见 `botTaskReplyResults.ts`、`botConversationPresentation.ts` 与 Mobile `companionConversationPresentation.ts`。- **补充消息留痕**:`message_session_task` 的完整指令继续投递并保存在后台任务,主聊天的发送留痕只显示简短状态。桌面与手机的实时、历史展示都按结构化标记投影;旧记录不删改,正常用户内容、授权和提问继续保留。diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.tsindex 6ab7aa76a8..65c7ef70c4 100644--- a/packages/maker-core/src/agents/codex/translator.test.ts+++ b/packages/maker-core/src/agents/codex/translator.test.ts@@ -2472,3 +2472,11 @@ describe('codex internal citation 归一化 (#785)', () => {]);});});+++it('carries the provider final phase from item start onto the first delta', async () => {+ const rt = newCodexRuntimeState(), q = createAsyncQueue<AgentEvent>(), ctx = makeCtx(rt);+ translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item: { type: 'agentMessage', id: 'final', text: '', phase: 'final_answer' } }, q, ctx);+ translateAgentMessageDelta({ threadId: 'thread', turnId: 'turn', itemId: 'final', delta: 'Visible now' }, q, ctx);+ expect(await collect(q)).toContainEqual({ type: 'text', source: 'codex', data: { text: 'Visible now', isFinal: false, agentMessageId: 'final', phase: 'final_answer' } });+});diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.tsindex 2bd66ece7a..9f6739c6d8 100644--- a/packages/maker-core/src/agents/codex/translator.ts+++ b/packages/maker-core/src/agents/codex/translator.ts@@ -99,6 +99,7 @@ export interface CodexRuntimeState {itemDeltaText: Map<string, string>;/** item.id → item/started 或 item/updated 最新原始全文快照。 */itemSnapshotText: Map<string, string>;+ itemMessagePhase: Map<string, 'commentary' | 'final_answer'>;/** 已经 emit 过 tool_use 的 item.id (避免 started + 第一次 updated 重复)。 */emittedToolUse: Set<string>;/** 尚未 emit 的 Web Search 候选输入,供跨 started/updated/completed 快照补全。 */@@ -140,6 +141,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {itemRawText: new Map(),itemDeltaText: new Map(),itemSnapshotText: new Map(),+ itemMessagePhase: new Map(),emittedToolUse: new Set(),pendingWebSearchInput: new Map(),emittedWebSearchInput: new Map(),@@ -1106,7 +1108,9 @@ function emitAgentMessageProgress(if (delta.length === 0) return;queue.push({type: 'text',- data: { text: delta, isFinal: false, agentMessageId: itemId },+ data: { text: delta, isFinal: false, agentMessageId: itemId,+ ...(ctx.rt.itemMessagePhase.has(itemId) ? { phase: ctx.rt.itemMessagePhase.get(itemId) } : {}),+ },source: 'codex',});}@@ -1178,12 +1182,14 @@ function handleAgentMessage(ctx: CodexTranslateContext,): void {const rawText = item.text ?? '';+ if (item.phase) ctx.rt.itemMessagePhase.set(item.id, item.phase);if (phase === 'completed') {ctx.rt.itemTextLen.delete(item.id);ctx.rt.itemRawText.delete(item.id);ctx.rt.itemDeltaText.delete(item.id);ctx.rt.itemSnapshotText.delete(item.id);+ ctx.rt.itemMessagePhase.delete(item.id);// 既有契约:completed 只出 final 全文、不补 delta(desktop codexTranslator.test// 钉死 3 事件形状)。boundary 按住的尾段与「completed 才首次出现的文本」同一待遇:// 不进 delta 流,由 final 全文兜底(main 落库层 onAssistantTextEvent 的 isFinal