Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 伙伴主进程的文件覆盖、重启恢复与任务回执修复
Claude56bf7411048a
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex e7fe39dbea..48504cb61d 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -869,6 +869,59 @@ describe('Bot canonical Session lifecycle', () => {expect(readConfig().templateId).toBe(templateId);});+ it('keeps a description created at full length editable', async () => {+ const description = '长'.repeat(12000);+ const created = await invoke('local-db:bots:create', { id: 'long-description', name: 'Long', description });+ const edited = await invoke('local-db:bots:update', { id: created.id, description: `${description.slice(1)}改` });+ expect(edited.description).toHaveLength(12000);+ await expect(invoke('local-db:bots:update', { id: created.id, description: `${description}!` }))+ .rejects.toMatchObject({ code: 'INVALID_PARAMS' });+ });++ it('adopts a hand-edited SOUL.md when creating the canonical task from the version the caller saw', async () => {+ const created = await invoke('local-db:bots:create', { id: 'file-first', name: 'File First', identitySource: 'Original identity' });+ const home = join(h.userDataDir, createHash('sha256').update(h.ownerScopeKey).digest('hex'), 'bots', created.id);+ writeFileSync(join(home, 'SOUL.md'), 'Identity written in an editor\n');+ // A stale caller from before an unrelated concurrent save still loses the CAS.+ await invoke('local-db:bots:update', { id: created.id, name: 'File First 2', expectedVersion: 1 });+ await expect(invoke('local-db:bots:create-canonical-session', {+ botId: created.id, expectedCanonicalSessionId: null, expectedProfileVersion: 1,+ })).rejects.toMatchObject({ code: 'PRECONDITION_FAILED' });++ const current = (await invoke('local-db:bots:get', created.id)).currentVersion as number;+ writeFileSync(join(home, 'SOUL.md'), 'Identity written again\n');+ const canonical = await invoke('local-db:bots:create-canonical-session', {+ botId: created.id, expectedCanonicalSessionId: null, expectedProfileVersion: current,+ });+ expect(canonical.canonicalSessionId).toBeTruthy();+ const loaded = await invoke('local-db:bots:get', created.id);+ expect(loaded.currentVersion).toBe(current + 1);+ expect(loaded.identitySource).toContain('Identity written again');+ });++ it('keeps hand-edited SOUL.md and USER.md through unrelated profile saves', async () => {+ const created = await invoke('local-db:bots:create', {+ id: 'hand-edited', name: 'Hand Edited', identitySource: 'Original identity',+ capabilities: { userContextSource: 'Original user context' },+ });+ const home = join(h.userDataDir, createHash('sha256').update(h.ownerScopeKey).digest('hex'), 'bots', created.id);+ writeFileSync(join(home, 'SOUL.md'), 'Identity written in an editor\n');+ writeFileSync(join(home, 'memories', 'USER.md'), 'User context written in an editor\n');++ await invoke('local-db:bots:update', { id: created.id, pinned: true });+ await invoke('local-db:bots:update', { id: created.id, hidden: true });+ await invoke('local-db:bots:update', { id: created.id, hidden: false, name: 'Renamed' });+ await invoke('local-db:bots:update', { id: created.id, capabilities: { permissions: 'auto' } });+ expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('Identity written in an editor\n');+ expect(readFileSync(join(home, 'memories', 'USER.md'), 'utf8')).toBe('User context written in an editor\n');++ // An explicit identity or user-context edit in settings still writes the file.+ await invoke('local-db:bots:update', { id: created.id, identitySource: 'Identity from settings' });+ expect(readFileSync(join(home, 'SOUL.md'), 'utf8').trim()).toBe('Identity from settings');+ await invoke('local-db:bots:update', { id: created.id, userContextSource: 'Context from settings' });+ expect(readFileSync(join(home, 'memories', 'USER.md'), 'utf8').trim()).toBe('Context from settings');+ });+it('still recognizes an unchanged legacy Cindy without rewriting its identity', async () => {await invoke('local-db:bots:create', { id: 'legacy-cindy', name: 'Cindy',identitySource: BOT_TEMPLATE_PRESET_IDENTITIES.cindy });@@ -6063,6 +6116,35 @@ describe('Bot Session task end-to-end runtime', () => {},);+ it('holds a paused requester\'s completion and delivers it once when the teammate resumes', async () => {+ await seedPair();+ const runtime = createDelegationRuntime();+ try {+ const started = await runtime.delegation.startSessionTask({+ callerSessionId: 'session-1', objective: 'Finish while I am paused',+ });+ if (!started.ok) throw new Error('Task did not start');+ h.sqlite!.prepare("UPDATE bot_profiles SET status = 'paused' WHERE id = 'bot-a'").run();+ await runtime.settleChild(started.childSessionId, 'Done while paused.');+ const completionCalls = () => runtime.dispatch.mock.calls.filter(([input]) => input.clientId ===+ `bot-delegation-completion:${started.delegationId}`);+ expect(completionCalls()).toHaveLength(0);+ // Still pending: nothing is lost while the teammate is away.+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id = ?')+ .pluck().get(started.delegationId)).toBeNull();+ // Resuming while still paused is a no-op, not a delivery.+ await runtime.delegation.resumeCompletionDelivery('bot-a');+ expect(completionCalls()).toHaveLength(0);++ h.sqlite!.prepare("UPDATE bot_profiles SET status = 'active' WHERE id = 'bot-a'").run();+ await runtime.delegation.resumeCompletionDelivery('bot-a');+ await runtime.delegation.resumeCompletionDelivery('bot-a');+ expect(completionCalls()).toHaveLength(1);+ expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id = ?')+ .pluck().get(started.delegationId)).not.toBeNull();+ } finally { runtime.dispose(); }+ });+it('delivers every continued run once without reusing the previous completion receipt', async () => {await seedPair();const runtime = createDelegationRuntime();diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex 987f68ce0e..dcc98ba0de 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -163,17 +163,20 @@ export function getBotMemoryService(): ReturnType<typeof createBotMemoryService>* 写文件失败**不让保存整个失败**:数据库那份才是运行时读的东西,文件只影响* 「能不能用编辑器改」。吞掉异常但记一笔,不静默。*/+function botUserContextSource(config: Record<string, unknown>): string {+ return typeof config.userContextSource === 'string' ? config.userContextSource : '';+}+async function syncBotProfileFolder(botId: string,identitySource: string,config: Record<string, unknown>,userDataDir = ownerScopedUserDataPath(),): Promise<void> {- const { userContextSource } = config;try {await writeBotProfileFolder(userDataDir, botId, {identitySource,- userContextSource: typeof userContextSource === 'string' ? userContextSource : '',+ userContextSource: botUserContextSource(config),});} catch (cause) {log.warn('write bot profile folder failed', { botId, error: String(cause) });@@ -286,8 +289,11 @@ async function reconcileCanonicalLink(* 挂在开新任务之前 —— 那正是「下一轮」的起点。整个过程失败不阻断开任务:最坏是* 这一轮还用旧身份,下一轮再收。*/-export async function reconcileBotProfileFolder(botId: string): Promise<void> {+export async function reconcileBotProfileFolder(+ botId: string,+): Promise<{ from: number; to: number } | null> {const userDataDir = ownerScopedUserDataPath();+ let derived: { from: number; to: number } | null = null;const legacyUserDataDir = app.getPath('userData');const client = getDbClient();const db = client.drizzle;@@ -323,7 +329,7 @@ export async function reconcileBotProfileFolder(botId: string): Promise<void> {await migrateBotProfileFolder(userDataDir, id, seed, legacyUserDataDir);},deriveVersion: async (input) => {- await client.tx('bots.updateProfile', {+ const result = await client.tx<{ currentVersion: number }>('bots.updateProfile', {id: input.botId,identitySource: input.identitySource,capabilitiesJson: safeJson(input.config),@@ -331,11 +337,13 @@ export async function reconcileBotProfileFolder(botId: string): Promise<void> {expectedCurrentVersion: input.expectedCurrentVersion,now: Date.now(),});+ derived = { from: input.expectedCurrentVersion, to: result.currentVersion };},});} catch (cause) {log.warn('reconcile bot profile folder failed', { botId, error: String(cause) });}+ return derived;}function botSessionAgentKind(config: { harness?: unknown }): 'cc' | 'codex' | 'pi' {@@ -1200,8 +1208,10 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,const patch: Partial<typeof botProfiles.$inferInsert> = { updatedAt: now };if (body.name !== undefined || body.displayName !== undefined)patch.displayName = readText(body.name ?? body.displayName, 'name', 200, true);+ // Same bound as creation and `update_teammate_profile`: a description created+ // there must stay editable here.if (body.description !== undefined)- patch.description = readText(body.description, 'description');+ patch.description = readText(body.description, 'description', 12000);const expectedAvatar =body.avatar !== undefined && body.expectedAvatar !== undefined@@ -1348,8 +1358,15 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });}}- await syncBotProfileFolder(id, nextIdentitySource, normalizedNextConfig, owner.userDataDir);- owner.assertCurrent();+ // The files are the user's editing surface: only rewrite them when this save changed+ // their content, so pinning, hiding or a model change cannot clobber hand edits.+ if (+ nextIdentitySource !== (version?.identitySource ?? '')+ || botUserContextSource(normalizedNextConfig) !== botUserContextSource(previous)+ ) {+ await syncBotProfileFolder(id, nextIdentitySource, normalizedNextConfig, owner.userDataDir);+ owner.assertCurrent();+ }if (profileContentChanged) {const [canonical] = await db.select({ sessionId: botSessionLinks.sessionId })@@ -1810,9 +1827,16 @@ export function registerBotIpc(): void {放在锁外面:它只读文件、按需派生版本,不碰 canonical 指针,与替换协调器要保护的东西不重叠。失败已在内部吞掉并记一笔,最坏是这一轮还用旧身份。*/- await reconcileBotProfileFolder(input.botId);+ const derived = await reconcileBotProfileFolder(input.botId);owner.assertCurrent();- return createBotCanonicalSessionPrepared(input);+ if (!derived) return createBotCanonicalSessionPrepared(input);+ // The host itself just folded the user's file edit into a new version. A caller+ // that saw the version before it is not racing a concurrent change; any other+ // mismatch still loses the create CAS.+ broadcastBotProfileChanged({ botId: input.botId, change: 'updated' });+ return createBotCanonicalSessionPrepared(input.expectedProfileVersion === derived.from+ ? { ...input, expectedProfileVersion: derived.to }+ : input);};ipcMain.handle('local-db:bots:create-canonical-session', async (event, raw: unknown) => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botRuntimeRestore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botRuntimeRestore.test.tsindex 13389606ee..a54ae6ed73 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botRuntimeRestore.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botRuntimeRestore.test.ts@@ -66,6 +66,25 @@ describe('botRuntimeRestore', () => {);});+ it('still restores delegations when direct messages fail, and retries only the failed stage', async () => {+ const h = harness();+ h.setIdentity({ userId: 'owner-a', clientEpoch: 1 });+ h.services.directMessages.restore.mockRejectedValueOnce(new Error('thread index conflict'));++ await expect(h.coordinator.restoreCurrentOwner()).resolves.toBe(false);+ expect(h.calls).toEqual(['delegation']);+ expect(h.log.warn).toHaveBeenCalledWith('Bot direct messages restore failed', expect.anything());++ await expect(h.coordinator.restoreCurrentOwner()).resolves.toBe(true);+ expect(h.calls).toEqual(['delegation', 'messages']);+ expect(h.services.delegation.restore).toHaveBeenCalledOnce();++ // A new client generation restores every stage again.+ h.setIdentity({ userId: 'owner-b', clientEpoch: 2 });+ await expect(h.coordinator.restoreCurrentOwner()).resolves.toBe(true);+ expect(h.calls).toEqual(['delegation', 'messages', 'messages', 'delegation']);+ });+it('stops the pass when the DbClient generation changes mid-restore', async () => {const h = harness();h.setIdentity({ userId: 'owner-a', clientEpoch: 1 });diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex 2af5672f75..d509bb73db 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -884,7 +884,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const initialReceiptSessionId = originalParent?.id?? await requesterLiveSessionId(params.requestingBotId, null);if (!initialReceiptSessionId) {- scheduleCompletionRetry(params, attempt);+ if (!(await holdCompletionForStoppedRequester(params))) scheduleCompletionRetry(params, attempt);return false;}let receiptSessionId: string = initialReceiptSessionId;@@ -938,6 +938,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {return false;}const targetSessionId = await requesterLiveSessionId(params.requestingBotId, params.parentSessionId);+ if (!targetSessionId && await holdCompletionForStoppedRequester(params)) return false;if (!targetSessionId) {log.warn('defer Bot delegation wake-up: requester has no live task', {delegationId: params.id,@@ -1024,6 +1025,49 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {completionRetryTimers.set(params.id, timer);}+ /**+ * A paused, archived or deleted requester cannot take the wake-up until it is+ * active again. Keep the run pending (the result card is already in its timeline)+ * but stop the backoff loop: resuming the teammate or the next restore delivers it.+ */+ async function holdCompletionForStoppedRequester(+ params: Parameters<typeof deliverCompletion>[0],+ ): Promise<boolean> {+ const [profile] = await getDbClient().drizzle.select({ status: botProfiles.status }).from(botProfiles)+ .where(eq(botProfiles.id, params.requestingBotId)).limit(1);+ if (profile && profile.status !== 'paused' && profile.status !== 'archived' && profile.status !== 'deleting') {+ return false;+ }+ clearCompletionRetryTimer(params.id);+ log.info('hold Bot Session task completion until its requester is active', {+ delegationId: params.id,+ requesterStatus: profile?.status ?? 'missing',+ });+ return true;+ }++ /** Deliver the completions a paused teammate missed; called when it resumes. */+ const resumeCompletionDelivery = async (botId: string): Promise<void> => {+ const db = getDbClient().drizzle;+ const rows = await db.select({ id: botDelegations.id }).from(botDelegations).where(and(+ eq(botDelegations.requestingBotId, botId),+ inArray(botDelegations.status, ['completed', 'failed', 'cancelled', 'timed-out']),+ isNull(botDelegations.completionDeliveredAt),+ ));+ for (const { id } of rows) {+ await withTaskOperation(id, async () => {+ const [current] = await db.select().from(botDelegations).where(eq(botDelegations.id, id)).limit(1);+ if (!current || isActiveDelegation(current.status as DelegationStatus) || current.completionDeliveredAt !== null) return;+ const row = await repairDelegationParent(current);+ await deliverCompletion({+ ...row,+ status: row.status as Extract<DelegationStatus, 'completed' | 'failed' | 'cancelled' | 'timed-out'>,+ artifacts: parseArtifacts(row.outputArtifactsJson),+ });+ });+ }+ };+/*** 发起伙伴此刻活着的那条任务:优先冻结的父任务;若它已被恢复流程替换,改投* 当前主任务。回执与交互事件属于伙伴本人,不属于损坏的旧任务。@@ -3845,6 +3889,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {handleInteractionStart,handleInteractionEnd,restore,+ resumeCompletionDelivery,dispose,};}diff --git a/apps/desktop/src/main/maker-ipc/botRuntimeRestore.ts b/apps/desktop/src/main/maker-ipc/botRuntimeRestore.tsindex 5cc00eb6bc..9cec618bfa 100644--- a/apps/desktop/src/main/maker-ipc/botRuntimeRestore.ts+++ b/apps/desktop/src/main/maker-ipc/botRuntimeRestore.ts@@ -32,6 +32,8 @@ export function createBotRuntimeRestoreCoordinator(deps: BotRuntimeRestoreCoordinatorDeps,): { restoreCurrentOwner(): Promise<boolean> } {let restoredClientEpoch: number | null = null;+ // Stages already restored for one client generation; a retry reruns only the rest.+ let restoredStages: { clientEpoch: number; labels: Set<string> } | null = null;let tail: Promise<boolean> = Promise.resolve(false);const restoreOnce = async (): Promise<boolean> => {@@ -46,21 +48,31 @@ export function createBotRuntimeRestoreCoordinator(['Bot direct messages', services.directMessages],['Bot delegation', services.delegation],] as const;+ if (restoredStages?.clientEpoch !== identity.clientEpoch) {+ restoredStages = { clientEpoch: identity.clientEpoch, labels: new Set() };+ }+ const done = restoredStages.labels;+ // The stages are independent queues: one failing must not leave the others+ // (task timeouts, undelivered completion receipts) unrestored until the next launch.+ let failed = false;for (const [label, service] of stages) {+ if (done.has(label)) continue;const current = deps.readDbIdentity();if (!current || current.clientEpoch !== identity.clientEpoch) return false;try {await service!.restore();+ done.add(label);} catch (error) {deps.log.warn(`${label} restore failed`, {userId: identity.userId,clientEpoch: identity.clientEpoch,error: error instanceof Error ? error.message : String(error),});- return false;+ failed = true;}}+ if (failed) return false;const current = deps.readDbIdentity();if (!current || current.clientEpoch !== identity.clientEpoch) return false;diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 210bcea84e..3ddbb43d09 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -9921,7 +9921,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)},getDelegationService: () => botDelegationServiceHolder,onPaused: (botId) => updateBotRoutineLifecycle(botId, 'pause'),- onResumed: (botId) => updateBotRoutineLifecycle(botId, 'resume'),+ onResumed: async (botId) => {+ await updateBotRoutineLifecycle(botId, 'resume');+ // Task results that finished while the teammate was paused were held, not retried.+ void botDelegationServiceHolder?.resumeCompletionDelivery(botId).catch((error) => {+ log.warn('resume Bot task completion delivery failed', { botId, error: String(error) });+ });+ },onBeforeDelete: (botId) => updateBotRoutineLifecycle(botId, 'delete'),});const delegationForRestore = botDelegationServiceHolder;diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.mdindex 1a2d4ca325..7b2f94cd44 100644--- a/docs/product-rules/cindy-bots-runtime.md+++ b/docs/product-rules/cindy-bots-runtime.md@@ -286,7 +286,9 @@ Session 任务遵守同一套机制与呈现契约:已送达。临时失败指数退避,Host 重启后重投未送达终态,固定 client id 保证重复投递不产生第二条消息。- **不静默丢失**:发起方的原父任务已被异常恢复流程替换时,完成信号改投该伙伴当前的- canonical Session;只有伙伴本身已暂停 / 归档才放弃投递,此时卡片终态仍然可见。+ canonical Session;只有伙伴本身已暂停 / 归档才暂缓投递,此时卡片终态仍然可见,完成信号+ 保持未送达且不轮询重试,伙伴恢复时补投一次(实现见 `botDelegationService.ts` 的+ `resumeCompletionDelivery`)。- Session 任务只创建一层子任务,受并发上限约束;超时是持久化的执行边界。默认执行预算30 分钟,创建时 `timeout_ms` 可指定至 24 小时;终态续接从新的开始时间按原预算计算,普通补充不延长正在运行的期限。没有 Host 回读证据不得声称已延长。