Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 补一句留痕、安排卡已读、归档重试,路由不再动态加载 botStore
Chris7b2164f3071b
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 9dab43c79b..fa1b264a8c 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -8324,6 +8324,43 @@ describe('Bot Session task end-to-end runtime', () => {}});+ it('traces the owner’s own 补一句 into the Bot chat without re-sending it to the task', async () => {+ await seedPair();+ const runtime = createDelegationRuntime();+ try {+ const started = await runtime.delegation.startSessionTask({+ callerSessionId: 'session-1',+ objective: '先整理一版方案。',+ });+ if (!started.ok) throw new Error(started.message);+ const dispatches = runtime.dispatch.mock.calls.length;+ await expect(runtime.delegation.traceOwnerNote(+ 'session-1', started.delegationId, '补充:最后必须带风险清单。\n读取 /workspace/project/AGENTS.md。',+ )).resolves.toEqual({ ok: true, delegationId: started.delegationId });+ // The owner's line already reached the task as their own message; nothing is re-dispatched.+ expect(runtime.dispatch.mock.calls.length).toBe(dispatches);+ const trace = h.sqlite!.prepare(+ "SELECT role, content, agent_meta AS agentMeta FROM messages WHERE session_id = 'session-1' AND client_id LIKE ?",+ ).get(`bot-delegation-interject-mirror:${started.delegationId}:owner-%`) as { role: string; content: string; agentMeta: string };+ expect(trace).toMatchObject({ role: 'assistant', content: '' });+ const meta = JSON.parse(trace.agentMeta).botCollaboration;+ expect(meta.role).toBe('interjection');+ // Only the bounded first line reaches the Bot chat; the full note stays in the task.+ expect(meta.interjectionPreview).toBe('补充:最后必须带风险清单。');+ expect(trace.agentMeta).not.toContain('AGENTS.md');+ // Unknown task or blank note: nothing is written.+ await expect(runtime.delegation.traceOwnerNote('session-1', 'missing-task', '…'))+ .resolves.toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });+ await expect(runtime.delegation.traceOwnerNote('session-1', started.delegationId, ' '))+ .resolves.toMatchObject({ ok: false, errorCode: 'INVALID_ARGS' });+ expect(h.sqlite!.prepare(+ "SELECT COUNT(*) FROM messages WHERE session_id = 'session-1' AND client_id LIKE 'bot-delegation-interject-mirror:%'",+ ).pluck().get()).toBe(1);+ } finally {+ runtime.dispose();+ }+ });+it('preserves an incomplete result in the failed task card and completion receipt', async () => {await seedPair();const runtime = createDelegationRuntime();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.tsindex 83d665e952..a0ec097323 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/remoteBotDelegations.test.ts@@ -5,6 +5,8 @@ import { projectRemoteBotDelegations } from '../remoteBotDelegations';it('exports task controls while keeping profile mutations local', () => {for (const channel of ['maker:bot-delegations:list', 'maker:bot-delegation:cancel', 'maker:bot-direct-message-thread:get']) expect(REMOTE_INVOKE_ALLOWLIST.has(channel)).toBe(true);expect(REMOTE_INVOKE_ALLOWLIST.has('local-db:bots:update')).toBe(false);+ // The owner's 补一句 trace is offered for local tasks only; the renderer sends the note itself.+ expect(REMOTE_INVOKE_ALLOWLIST.has('maker:bot-delegation:note-trace')).toBe(false);expect(PUSH_FORWARD_ALLOWLIST.has('maker:bot-delegation:changed')).toBe(true);expect(PUSH_FORWARD_ALLOWLIST.has('maker:bot-direct-message:changed')).toBe(true);});diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex a5e7207e44..0773213a8a 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -3096,6 +3096,58 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {};};+ /**+ * The owner typed a line into a running background task from its card in the Bot's+ * chat. The line itself already went to the child as the owner's own message (the+ * card sends it like typing in that task); this only leaves the same quiet trace a+ * Bot's `message_session_task` leaves, so the Bot's chat shows what the task was told.+ * Scoped like cancel: the task must belong to the Bot whose chat holds the card.+ */+ const traceOwnerNote = async (+ callerSessionId: string,+ delegationId: string,+ text: string,+ ): Promise<BotDelegationResult<{ delegationId: string }>> => {+ const trimmed = text.trim();+ if (!trimmed || trimmed.length > MAX_INTERJECTION_CHARS) {+ return { ok: false, errorCode: 'INVALID_ARGS', message: '消息内容为空或超长' };+ }+ const caller = await resolveCaller(callerSessionId);+ if (!caller) {+ return { ok: false, errorCode: 'NOT_A_BOT_SESSION', message: '当前任务不属于任何伙伴' };+ }+ const db = getDbClient().drizzle;+ const [row] = await db+ .select()+ .from(botDelegations)+ .where(and(eq(botDelegations.id, delegationId), callerTaskScope(caller)))+ .limit(1);+ if (!row) return { ok: false, errorCode: 'NOT_FOUND', message: '后台任务不存在' };+ const preview = botInterjectionPreview(trimmed);+ await persistTimelineMessage({+ sessionId: callerSessionId,+ // Not idempotent across calls on purpose: each 补一句 is its own line in the chat.+ clientId: BOT_DELEGATION_CLIENT_ID.interjectionMirror(delegationId, `owner-${createId()}`),+ role: 'assistant',+ content: '',+ createdAt: now(),+ agentMeta: {+ botCollaboration: {+ ...await collaborationMeta(row, 'interjection'),+ // Only the bounded first line; the full note lives in the child task.+ ...(preview ? { interjectionPreview: preview } : {}),+ },+ },+ });+ emitChanged({+ delegationId: row.id,+ parentSessionId: row.parentSessionId,+ childSessionId: row.childSessionId,+ status: row.status as DelegationStatus,+ });+ return { ok: true, delegationId };+ };+/*** Continue in the same visible Session, preserving history, worktree ownership* and callback targets. An archived/deleted Session needs explicit restoration.@@ -4453,6 +4505,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {messageSessionTask: expose(messageSessionTask),stopSessionTask: expose(stopSessionTask),cancelDelegation: expose((callerSessionId: string, delegationId: string) => withTaskOperation(delegationId, () => cancelDelegation(callerSessionId, delegationId))),+ traceOwnerNote: expose(traceOwnerNote),cancelDelegationsForParentSession,cancelDelegationsForBot,settleSession,diff --git a/apps/desktop/src/main/maker-ipc/channels.ts b/apps/desktop/src/main/maker-ipc/channels.tsindex 15004fa89e..a572c8290a 100644--- a/apps/desktop/src/main/maker-ipc/channels.ts+++ b/apps/desktop/src/main/maker-ipc/channels.ts@@ -777,6 +777,11 @@ export const MAKER_INVOKE = {BOT_DELEGATIONS_LIST: 'maker:bot-delegations:list',/** Cindy Bot 父任务取消仍在运行或等待中的委派。 */BOT_DELEGATION_CANCEL: 'maker:bot-delegation:cancel',+ /**+ * 主人在伙伴聊天的任务卡上「补一句」后,给伙伴聊天留一条「已告诉后台任务:「…」」。+ * 消息本身由渲染端以主人身份发进子任务;只本机可用,不进 device-link 白名单。+ */+ BOT_DELEGATION_NOTE_TRACE: 'maker:bot-delegation:note-trace',/** Read one hidden Bot-to-Bot conversation after a timeline trace is opened. */BOT_DIRECT_MESSAGE_THREAD_GET: 'maker:bot-direct-message-thread:get',/** 伙伴群聊:列表、详情、创建、修改、成员、删除、发言、继续讨论与停止。 */diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 6ad8c2e357..0919d34add 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -12260,6 +12260,25 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)return delegationForRestore.cancelDelegation(parentSessionId, delegationId);},);+ ipcMain.handle(+ MAKER_INVOKE.BOT_DELEGATION_NOTE_TRACE,+ async (event, parentSessionId: unknown, delegationId: unknown, text: unknown) => {+ // Local only: the card offers 补一句 for tasks on this computer and the channel+ // stays out of the device-link allowlist, so the sender is always the app renderer.+ assertTrustedAppRendererEvent(event);+ if (+ typeof parentSessionId !== 'string'+ || (parentSessionId.length === 0 || parentSessionId.length > 128)+ || typeof delegationId !== 'string'+ || (delegationId.length === 0 || delegationId.length > 128)+ || typeof text !== 'string'+ || (text.trim().length === 0 || text.length > 4_000)+ ) {+ throwIpcError('INVALID_PARAMS', 'parentSessionId + delegationId + text required');+ }+ return delegationForRestore.traceOwnerNote(parentSessionId, delegationId, text);+ },+ );const captureSessionOwner = () => {const owner = getCurrentDbClientSnapshot();return () => {diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 05b1dfa9c1..63b90bfbc2 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -5959,6 +5959,12 @@ contextBridge.exposeInMainWorld('electronAPI', {delegationId: string,): Promise<import('../shared/botDelegation').BotDelegationCancelResult> =>ipcRenderer.invoke('maker:bot-delegation:cancel', parentSessionId, delegationId),+ traceBotDelegationNote: (+ parentSessionId: string,+ delegationId: string,+ text: string,+ ): Promise<import('../shared/botDelegation').BotDelegationNoteTraceResult> =>+ ipcRenderer.invoke('maker:bot-delegation:note-trace', parentSessionId, delegationId, text),onBotDelegationChanged: fanOutBotDelegationChanged,getBotDirectMessageThread: (threadId: string,diff --git a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.tsindex 5a8d86214d..903f35c8d0 100644--- a/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts+++ b/apps/desktop/src/renderer/__tests__/orcaSessionIdentity.test.ts@@ -8,12 +8,13 @@ import {isOrcaWorkerSession,resolveSessionRoute,} from '@/lib/orcaSessionIdentity';+import { registerLoadedBotProfilesReader } from '@/features/bots/botSessionOwners';+import type { BotProfile } from '@/features/bots/botStore';-const bots = vi.hoisted(() => ({ loaded: true, profiles: [] as unknown[] }));-vi.mock('@/features/bots/botStore', () => ({- hasLoadedBotProfiles: () => bots.loaded,- getBotProfiles: () => bots.profiles,-}));+// The loaded projection reaches the route helper through the registry botStore fills at+// load; the store itself never loads here (no dynamic import on a click).+const bots = { loaded: true, profiles: [] as unknown[] };+registerLoadedBotProfilesReader(() => (bots.loaded ? (bots.profiles as BotProfile[]) : null));describe('orcaSessionIdentity', () => {let originalWindow: unknown;diff --git a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsxindex 97d39a735b..513f2dfe2f 100644--- a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx@@ -157,14 +157,30 @@ function StatusGlyph({ state }: { state: CardState }) {);}-/** Local bot chats only: the owner adds a line to the original task like typing in it. */-async function sendToTask(childSessionId: string, text: string): Promise<boolean> {+/**+ * Local bot chats only: the owner adds a line to the original task like typing in it.+ * The Bot's chat then keeps the same quiet trace a Bot's own `message_session_task`+ * leaves (first line only). The line is delivered before the trace, so a failed trace+ * never turns a sent note into an error.+ */+async function sendToTask(+ parentSessionId: string | null,+ delegationId: string,+ childSessionId: string,+ text: string,+): Promise<boolean> {const owner = getDataOwnerGeneration();const row = await sessionService.get(childSessionId);if (!isDataOwnerGenerationCurrent(owner) || !row?.workingDir) return false;- return makerChatStore.sendMessage(+ const sent = await makerChatStore.sendMessage(childSessionId, text, row.model, row.effort, row.permissionMode, row.workingDir,);+ if (sent && parentSessionId && isDataOwnerGenerationCurrent(owner)) {+ await window.electronAPI.maker+ .traceBotDelegationNote(parentSessionId, delegationId, text)+ .catch(() => undefined);+ }+ return sent;}/**@@ -307,7 +323,7 @@ export function BotTaskCard({setPending(true);setActionError(null);try {- if (await sendToTask(childSessionId, text)) {+ if (await sendToTask(parentSessionId, card.delegationId, childSessionId, text)) {setNote('');setNoteOpen(false);toast.success(t('bots.collab.addNoteSent'));diff --git a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsxindex 730cc1ad1c..eed624e6b4 100644--- a/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotGroupChatView.tsx@@ -414,8 +414,10 @@ function BotGroupChatContent({ groupId }: { groupId: string }) {}, [rows, quoteSources]);// Read marks: the newest incoming message (a Bot or another human) once it is in view.+ // Same range as the unread count (`incomingMessageTimes`): spoken messages and a Bot's+ // plan card; notices never count, so a plan card at the tail cannot leave a stuck badge.const latestIncomingAt = useMemo(() => realMessages.reduce((latest, message) =>- message.kind === 'message' && (message.authorKind === 'bot' || message.isSelf === false)+ (message.kind === 'message' || message.kind === 'plan') && (message.authorKind === 'bot' || message.isSelf === false)? Math.max(latest, message.createdAt) : latest, 0), [realMessages]);const latestIncomingRef = useRef(latestIncomingAt);latestIncomingRef.current = latestIncomingAt;diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsxindex 4977f34972..ec2999eda0 100644--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx@@ -579,6 +579,11 @@ export function BotWorkbench({ botId, sessionId }: { botId: string; sessionId: srowMenu={rowMenu}archivedFooter={pageControl(archivedPages, true)}/>+ {/* No「做完」group yet (nothing finished, no archived row loaded): a failed archived+ read still needs its retry somewhere, or it could never be reloaded. */}+ {archivedPages.error && !groups.some((group) => group.key === 'done') ? (+ <div className="px-5">{pageControl(archivedPages, false)}</div>+ ) : null}{activePages.error || (activePages.hasMore && !activePages.loading) ? (<div className="px-5">{pageControl(activePages, false)}</div>) : null}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsxindex 2632527ca9..5f8db32bc8 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotCollaborationCard.test.tsx@@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({stale: false,cancel: vi.fn(),send: vi.fn(),+ trace: vi.fn(),toast: vi.fn(),prs: [] as any[],}));@@ -140,10 +141,12 @@ beforeEach(() => {permissionMode: 'default',});mocks.route.mockResolvedValue('/cc-agent/child');+ mocks.trace.mockResolvedValue({ ok: true, delegationId: 'd' });Object.defineProperty(window, 'electronAPI', {configurable: true,value: {deviceLink: { invoke: mocks.remoteGet },+ maker: { traceBotDelegationNote: mocks.trace },openExternal: vi.fn(async () => ({ success: true })),},});@@ -213,9 +216,32 @@ it('adds a note to a local running task as the owner, with the task runtime settawait waitFor(() => expect(mocks.send).toHaveBeenCalledWith('child', 'Cover offline reconnect', 'gpt-x', 'high', 'default', '/child',));+ // The Bot's chat keeps the「已告诉后台任务」trace of what the owner told the task.+ await waitFor(() => expect(mocks.trace).toHaveBeenCalledWith('parent', 'd', 'Cover offline reconnect'));await waitFor(() => expect(screen.queryByRole('textbox')).toBeNull());expect(mocks.toast).toHaveBeenCalledWith('bots.collab.addNoteSent');});+it('still reports a delivered note when only its chat trace fails, and leaves no trace for an undelivered one', async () => {+ mocks.row = delegation({ status: 'running' });+ mocks.trace.mockRejectedValueOnce(new Error('offline'));+ const { unmount } = render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));+ const input = screen.getByRole('textbox', { name: 'bots.collab.addNote' });+ fireEvent.change(input, { target: { value: 'Keep the risk list' } });+ fireEvent.submit(input.closest('form')!);+ await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith('bots.collab.addNoteSent'));+ expect(screen.queryByRole('alert')).toBeNull();+ unmount();++ mocks.send.mockResolvedValueOnce(false);+ render(<BotSessionTaskCard data={data()} sessionId="parent" />);+ fireEvent.click(screen.getByRole('button', { name: /bots\.collab\.addNote/ }));+ const again = screen.getByRole('textbox', { name: 'bots.collab.addNote' });+ fireEvent.change(again, { target: { value: 'Never delivered' } });+ fireEvent.submit(again.closest('form')!);+ expect((await screen.findByRole('alert')).textContent).toBe('bots.collab.actionFailed');+ expect(mocks.trace).toHaveBeenCalledTimes(1);+});it('shows what the task waits for and lets the user look at it', async () => {mocks.row = delegation({ status: 'waiting', pendingInteraction: { summary: 'Allow npm install', kind: 'permission' } });render(<BotSessionTaskCard data={data()} sessionId="parent" />);diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsxindex 45be72435b..4a55b57136 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotGroupChatView.test.tsx@@ -2160,6 +2160,22 @@ it('keeps copy/share in each author row and shares only message content through} finally { focus.mockRestore(); resetBotReadStateForTests(); }});+it('acknowledges a Bot’s plan card at the tail, the same range the unread badge counts', async () => {+ resetBotReadStateForTests();+ const focus = vi.spyOn(document, 'hasFocus').mockReturnValue(true);+ markBotRead(botGroupReadKey('g1'), 100);+ mocks.getBotGroup.mockResolvedValue({ ok: true, group: withPlan(plan(), [], { messages: [+ msg({ id: 'b', authorKind: 'bot', content: 'First reply', createdAt: 200 }),+ { ...planCard, createdAt: 300 },+ ] }) });+ const view = renderView();+ try {+ await screen.findByTestId('bot-group-plan');+ act(() => window.dispatchEvent(new Event('focus')));+ expect(getBotLastReadAt(botGroupReadKey('g1'))).toBe(300);+ } finally { focus.mockRestore(); resetBotReadStateForTests(); view.unmount(); }+});+describe('Telegram / Slack-grade timeline', () => {function deferred<T>() {let resolve!: (value: T) => void;diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsxindex 1332ffd1f4..88b0fad9bc 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx@@ -10,6 +10,11 @@ const m = vi.hoisted(() => ({readTask: vi.fn(),sendMessage: vi.fn(async () => true),rows: { active: [] as Session[], archived: [] as Session[] },+ pages: {+ active: { loading: false, error: false, hasMore: false },+ archived: { loading: false, error: false, hasMore: false },+ },+ load: { active: vi.fn(), archived: vi.fn() },activity: new Map<string, unknown>(),}));vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));@@ -24,10 +29,8 @@ vi.mock('../BotTodoList', () => ({ BotTodoList: () => <section aria-label="todosvi.mock('../useWorkbenchSessionPages', () => ({useWorkbenchSessionPages: (_scope: string, status: 'active' | 'archived') => ({rows: m.rows[status],- loading: false,- error: false,- hasMore: false,- load: vi.fn(),+ ...m.pages[status],+ load: m.load[status],}),}));vi.mock('../useWorkbenchSessionActions', () => ({@@ -187,6 +190,21 @@ it('opens a Cindy task inside the panel, reads it, and returns to the list', asyexpect(await screen.findByRole('region', { name: 'bots.workbench.group.todo' })).toBeTruthy();});+it('keeps a retry for a failed archived read when nothing is done or archived yet', async () => {+ m.rows = { active: [session('s-run')], archived: [] };+ m.pages.archived = { loading: false, error: true, hasMore: false };+ try {+ render(<BotWorkbench botId="bot-1" sessionId="bot-main" />);+ await screen.findByRole('region', { name: 'bots.workbench.group.running' });+ expect(screen.queryByRole('region', { name: 'bots.workbench.group.done' })).toBeNull();+ fireEvent.click(screen.getByRole('button', { name: 'commonUi.retry' }));+ expect(m.load.archived).toHaveBeenCalledTimes(1);+ expect(m.load.active).not.toHaveBeenCalled();+ } finally {+ m.pages.archived = { loading: false, error: false, hasMore: false };+ }+});+it('opens an archived task read-only, without restoring it or offering 补一句', async () => {render(<BotWorkbench botId="bot-1" sessionId="bot-main" />);const done = await screen.findByRole('region', { name: 'bots.workbench.group.done' });diff --git a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts b/apps/desktop/src/renderer/features/bots/botSessionOwners.tsindex 92efd24738..c1d35a5876 100644--- a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts+++ b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts@@ -56,6 +56,24 @@ export function botRouteForOwnedSession(return `/bots/${botId}/session/${id}`;}+type LoadedBotProfilesReader = () => readonly BotProfile[] | null;+let loadedBotProfilesReader: LoadedBotProfilesReader | null = null;++/**+ * botStore registers a reader for its loaded projection when its module loads, so+ * route helpers in `lib/` (notification clicks, sidebar) read it synchronously without+ * importing the store graph — and without a dynamic import on a click, which made the+ * shared-task dialog tests time out on slow CI runners.+ */+export function registerLoadedBotProfilesReader(reader: LoadedBotProfilesReader | null): void {+ loadedBotProfilesReader = reader;+}++/** The loaded Bot profiles, or null while the store is not loaded for this account. */+export function readLoadedBotProfiles(): readonly BotProfile[] | null {+ return loadedBotProfilesReader?.() ?? null;+}+export interface BotSessionEntryRouteDeps {readProfiles: () => readonly BotProfile[];/** Loads the current owner's profiles; `refresh` re-reads an already loaded projection. */diff --git a/apps/desktop/src/renderer/features/bots/botStore.ts b/apps/desktop/src/renderer/features/bots/botStore.tsindex 4134ca742f..ac9faa2179 100644--- a/apps/desktop/src/renderer/features/bots/botStore.ts+++ b/apps/desktop/src/renderer/features/bots/botStore.ts@@ -17,6 +17,7 @@ import {NEW_BOT_DEFAULT_HARNESS,} from '../../../shared/botDefaults';import { getBotLastReadAtMap, pruneBotReadState, seedMissingBotReadState } from './botReadState';+import { registerLoadedBotProfilesReader } from './botSessionOwners';import type { BotGender } from '../../../shared/botGender';import { BOT_FAILURE_REASONS, type BotFailureReason } from '../../../shared/botFailureReason';import type { BotCapabilityBaseline } from '../../../shared/botCapabilitySelection';@@ -857,6 +858,8 @@ export function getBotProfiles(): BotProfile[] {ensureProfileOwner();return profiles;}+// Route helpers in lib/ read the loaded projection through this registry (no store import).+registerLoadedBotProfilesReader(() => (hasLoadedBotProfiles() ? getBotProfiles() : null));export function subscribeBotProfiles(listener: () => void): () => void {listeners.add(listener);diff --git a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts b/apps/desktop/src/renderer/lib/orcaSessionIdentity.tsindex e8a870944e..3f1d659487 100644--- a/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts+++ b/apps/desktop/src/renderer/lib/orcaSessionIdentity.ts@@ -1,7 +1,7 @@import type { OrcaRole, Session } from '@/lib/ccAgent.types';import { getSessionFor, orcaWorkflowsFor } from '@/lib/makerTransport';import { CINDY_MAKE_ENABLED, isCindyMakeSource } from '@cindy/maker-shared/cindy-make-feature';-import { botRouteForOwnedSession } from '@/features/bots/botSessionOwners';+import { botRouteForOwnedSession, readLoadedBotProfiles } from '@/features/bots/botSessionOwners';export function isOrcaLeadSession(session: { orcaRole?: OrcaRole | null }): boolean {return session.orcaRole === 'lead';@@ -34,20 +34,15 @@ export function getSessionRouteOwnerId(route: string): string | null {/*** The Bot page for a Bot's own chat (main task, history, channel chat), read from- * the in-memory profile projection only: no IPC wait on a click. A background- * task stays on its ordinary `/cc-agent/:id` route; an unloaded projection falls- * back to the ordinary route too (the notification entry reloads it first).+ * the in-memory profile projection only: no IPC and no module load on a click. A+ * background task stays on its ordinary `/cc-agent/:id` route; an unloaded projection+ * falls back to the ordinary route too (the notification entry reloads it first).*/-async function loadedBotChatRoute(sessionId: string): Promise<string | null> {- try {- // Lazy: botStore is already loaded by the shell; this keeps lib free of its graph.- const store = await import('@/features/bots/botStore');- if (!store.hasLoadedBotProfiles()) return null;- const route = botRouteForOwnedSession(store.getBotProfiles(), sessionId);- return route && !route.startsWith('/cc-agent/') ? route : null;- } catch {- return null;- }+function loadedBotChatRoute(sessionId: string): string | null {+ const profiles = readLoadedBotProfiles();+ if (!profiles) return null;+ const route = botRouteForOwnedSession(profiles, sessionId);+ return route && !route.startsWith('/cc-agent/') ? route : null;}/**@@ -75,7 +70,7 @@ export async function resolveSessionRoute(}// Notifications, task cards and the main sidebar agree on one page per task.- const botRoute = await loadedBotChatRoute(sessionId);+ const botRoute = loadedBotChatRoute(sessionId);if (botRoute) return botRoute;return `/cc-agent/${sessionId}`;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex b031177c82..75f2c031a3 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -5338,6 +5338,12 @@ interface ElectronAPI {parentSessionId: string,delegationId: string,) => Promise<import('../shared/botDelegation').BotDelegationCancelResult>;+ /** The owner's 补一句 from a task card leaves its trace in the Bot's chat (local tasks only). */+ traceBotDelegationNote: (+ parentSessionId: string,+ delegationId: string,+ text: string,+ ) => Promise<import('../shared/botDelegation').BotDelegationNoteTraceResult>;onBotDelegationChanged: (cb: (payload: import('../shared/botDelegation').BotDelegationChangedPayload,diff --git a/packages/maker-shared/src/botDelegation.ts b/packages/maker-shared/src/botDelegation.tsindex c5db4eb3b7..7780ec484d 100644--- a/packages/maker-shared/src/botDelegation.ts+++ b/packages/maker-shared/src/botDelegation.ts@@ -220,3 +220,8 @@ export type BotDelegationListResult =export type BotDelegationCancelResult =| { ok: true; delegationId: string; childSessionId: string | null }| { ok: false; errorCode: string; message: string };++/** The owner's 补一句 from a task card: the quiet trace left in the Bot's own chat. */+export type BotDelegationNoteTraceResult =+ | { ok: true; delegationId: string }+ | { ok: false; errorCode: string; message: string };