Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 处理 review:只写回改动的档案文件、补投重试、通知导航排序、冲突放弃采用新资料
Claudeb0061183061a
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex 48504cb61d..009ea94222 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -915,11 +915,14 @@ describe('Bot canonical Session lifecycle', () => {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.+ // An explicit identity or user-context edit in settings writes only its own 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');+ expect(readFileSync(join(home, 'memories', 'USER.md'), 'utf8')).toBe('User context written in an editor\n');+ writeFileSync(join(home, 'SOUL.md'), 'Identity edited again\n');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');+ expect(readFileSync(join(home, 'SOUL.md'), 'utf8')).toBe('Identity edited again\n');});it('still recognizes an unchanged legacy Cindy without rewriting its identity', async () => {@@ -6137,7 +6140,12 @@ describe('Bot Session task end-to-end runtime', () => {expect(completionCalls()).toHaveLength(0);h.sqlite!.prepare("UPDATE bot_profiles SET status = 'active' WHERE id = 'bot-a'").run();+ // A transient read failure on resume retries with backoff instead of waiting for a relaunch.+ const select = vi.spyOn(h.db!, 'select').mockImplementationOnce(() => { throw new Error('database busy'); });await runtime.delegation.resumeCompletionDelivery('bot-a');+ expect(completionCalls()).toHaveLength(0);+ select.mockRestore();+ await vi.waitFor(() => expect(completionCalls()).toHaveLength(1), { timeout: 3_000 });await runtime.delegation.resumeCompletionDelivery('bot-a');expect(completionCalls()).toHaveLength(1);expect(h.sqlite!.prepare('SELECT completion_delivered_at FROM bot_delegations WHERE id = ?')diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.tsindex dcc98ba0de..d45fd75a9d 100644--- a/apps/desktop/src/main/localDb/ipc/bots.ts+++ b/apps/desktop/src/main/localDb/ipc/bots.ts@@ -169,15 +169,11 @@ function botUserContextSource(config: Record<string, unknown>): string {async function syncBotProfileFolder(botId: string,- identitySource: string,- config: Record<string, unknown>,+ patch: { identitySource?: string; userContextSource?: string },userDataDir = ownerScopedUserDataPath(),): Promise<void> {try {- await writeBotProfileFolder(userDataDir, botId, {- identitySource,- userContextSource: botUserContextSource(config),- });+ await writeBotProfileFolder(userDataDir, botId, patch);} catch (cause) {log.warn('write bot profile folder failed', { botId, error: String(cause) });}@@ -1175,8 +1171,7 @@ export async function createBotProfile(raw: unknown) {}await syncBotProfileFolder(id,- identitySource,- persistedCapabilities,+ { identitySource, userContextSource: botUserContextSource(persistedCapabilities) },creationOwnerBoundary.userDataDir,);assertCreationOwnerStillCurrent();@@ -1358,13 +1353,16 @@ export async function updateBotProfile(raw: unknown, expectedVersion?: number,broadcastSessionPatched(canonical.sessionId, { permissionMode: canonical.mode });}}- // 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);+ // The files are the user's editing surface: rewrite only the file whose content this+ // save changed, so pinning, a model change or editing the other file cannot clobber+ // hand edits that have not been reconciled yet.+ const nextUserContextSource = botUserContextSource(normalizedNextConfig);+ const folderPatch = {+ ...(nextIdentitySource !== (version?.identitySource ?? '') ? { identitySource: nextIdentitySource } : {}),+ ...(nextUserContextSource !== botUserContextSource(previous) ? { userContextSource: nextUserContextSource } : {}),+ };+ if (Object.keys(folderPatch).length > 0) {+ await syncBotProfileFolder(id, folderPatch, owner.userDataDir);owner.assertCurrent();}if (profileContentChanged) {diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.tsindex d509bb73db..3c3a8903e3 100644--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts@@ -389,6 +389,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {const completionInFlight = new Map<string, Promise<void>>();const interactionRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();const cleanupRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();+ const resumeRetryTimers = new Map<string, ReturnType<typeof setTimeout>>();/** Live resolver handles remain process-local; the user-visible waiting* summary and paused status are persisted on the delegation row. */const pendingInteractions = new Map<string, BotDelegationPendingInteraction & {@@ -1046,25 +1047,48 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {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),+ /**+ * Deliver the completions a paused teammate missed; called when it resumes.+ * Held completions have no backoff loop of their own, so a transient failure+ * here retries with the same backoff instead of waiting for the next launch.+ */+ const resumeCompletionDelivery = async (botId: string, attempt = 0): Promise<void> => {+ const pending = resumeRetryTimers.get(botId);+ if (pending) {+ clearTimeout(pending);+ resumeRetryTimers.delete(botId);+ }+ try {+ 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),+ });});+ }+ } catch (error) {+ log.warn('resume Bot task completion delivery failed; retrying', {+ botId,+ attempt,+ error: error instanceof Error ? error.message : String(error),});+ const timer = setTimeout(() => {+ resumeRetryTimers.delete(botId);+ void resumeCompletionDelivery(botId, attempt + 1);+ }, Math.min(MAX_RETRY_DELAY_MS, 1_000 * 2 ** Math.min(attempt, 6)));+ timer.unref?.();+ resumeRetryTimers.set(botId, timer);}};@@ -3858,6 +3882,8 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {interactionRetryTimers.clear();for (const timer of cleanupRetryTimers.values()) clearTimeout(timer);cleanupRetryTimers.clear();+ for (const timer of resumeRetryTimers.values()) clearTimeout(timer);+ resumeRetryTimers.clear();};return {@@ -3889,7 +3915,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {handleInteractionStart,handleInteractionEnd,restore,- resumeCompletionDelivery,+ resumeCompletionDelivery: (botId: string) => resumeCompletionDelivery(botId),dispose,};}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 3ddbb43d09..a6ea15e806 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -9923,10 +9923,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)onPaused: (botId) => updateBotRoutineLifecycle(botId, 'pause'),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) });- });+ // Task results that finished while the teammate was paused were held, not retried;+ // the service retries its own transient failures.+ void botDelegationServiceHolder?.resumeCompletionDelivery(botId);},onBeforeDelete: (botId) => updateBotRoutineLifecycle(botId, 'delete'),});diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsxindex 144a27a2b1..24892cafda 100644--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx@@ -101,7 +101,7 @@ import { makeFolderPickerNewMakerRouteState } from '@/features/cc-agent/lib/newMimport { makeGenericNewMakerRouteState } from '@/features/cc-agent/lib/genericNewMakerRouteState';import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';import { ensureBotProfilesLoaded, getBotProfiles } from '@/features/bots/botStore';-import { resolveBotRouteForSessionEntry } from '@/features/bots/botSessionOwners';+import { createSessionEntryNavigator, resolveBotRouteForSessionEntry } from '@/features/bots/botSessionOwners';import * as sessionService from '@/lib/sessionService';import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';import {@@ -493,7 +493,7 @@ export function MainLayout() {const currentPathRef = useRef(`${location.pathname}${location.search}`);currentPathRef.current = `${location.pathname}${location.search}`;const navigateToOrdinarySession = useCallback(- (sessionId: string, messageClientId?: string) => {+ (sessionId: string, messageClientId?: string, isLatest: () => boolean = () => true) => {// device-link 远程会话本地无 row:resolveSessionRoute 内部的 sessionService.get// 会 miss → 远程 Orca lead/worker 被当普通会话路由,CCAgentSessionView 再// redirect 到 orca 路由时会丢 searchJump 锚点。传入远程镜像的 session 对象,@@ -501,6 +501,7 @@ export function MainLayout() {const remoteSession =remoteProjectsStore.getMergedRemoteSessions().find((s) => s.id === sessionId) ?? null;void resolveSessionRoute(sessionId, remoteSession).then((target) => {+ if (!isLatest()) return;const visibleSession = resolveAgentIslandVisibleSessionFromRouteTarget(target);if (messageClientId) {// 带消息锚点:即使已在目标路由也要 navigate——新的 location.state 才能@@ -534,22 +535,22 @@ export function MainLayout() {},[navigate],);- const navigateToSession = useCallback(- (sessionId: string, messageClientId?: string) => {- void resolveBotRouteForSessionEntry(sessionId, {- readProfiles: getBotProfiles,- readSessionSource: async (id) => (await sessionService.get(id)).source,- loadProfiles: ensureBotProfilesLoaded,- }).then((botRoute) => {- if (!botRoute) {- navigateToOrdinarySession(sessionId, messageClientId);- return;- }- if (currentPathRef.current !== botRoute) navigate(botRoute);- });+ const sessionEntryDepsRef = useRef({ navigate, navigateToOrdinarySession });+ sessionEntryDepsRef.current = { navigate, navigateToOrdinarySession };+ // One navigator for the layout's lifetime: its sequence must span re-renders so a+ // late lookup for an earlier notification cannot override a newer click.+ const [navigateToSession] = useState(() => createSessionEntryNavigator({+ resolveBotRoute: (sessionId) => resolveBotRouteForSessionEntry(sessionId, {+ readProfiles: getBotProfiles,+ readSessionSource: async (id) => (await sessionService.get(id)).source,+ loadProfiles: ensureBotProfilesLoaded,+ }),+ openBotRoute: (route) => {+ if (currentPathRef.current !== route) sessionEntryDepsRef.current.navigate(route);},- [navigate, navigateToOrdinarySession],- );+ openOrdinary: (sessionId, messageClientId, isLatest) =>+ sessionEntryDepsRef.current.navigateToOrdinarySession(sessionId, messageClientId, isLatest),+ }));navigateToSessionRef.current = navigateToSession;useEffect(() => {const unsubscribe = window.electronAPI.onNotificationFocusSession((sessionId) => {diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.tsindex 1fb6d9d8e8..3541ae91b0 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts@@ -15,6 +15,7 @@ import type { Session } from '@/lib/ccAgent.types';import {botRouteForOwnedSession,buildBotSessionOwners,+ createSessionEntryNavigator,findBotProfileForSession,resolveBotRouteForSessionEntry,} from '../botSessionOwners';@@ -123,6 +124,30 @@ describe('通知入口在伙伴投影未加载时的路由', () => {expect(loadProfiles).toHaveBeenCalledWith(false);});+ it('连续点击时,先点的慢查询不会覆盖后点的导航', async () => {+ const pending = new Map<string, (route: string | null) => void>();+ const openBotRoute = vi.fn();+ const openOrdinary = vi.fn();+ const open = createSessionEntryNavigator({+ resolveBotRoute: (sessionId) => new Promise((resolve) => pending.set(sessionId, resolve)),+ openBotRoute,+ openOrdinary,+ });+ open('first');+ open('second', 'message-1');+ pending.get('second')!(null);+ await Promise.resolve();+ expect(openOrdinary).toHaveBeenCalledWith('second', 'message-1', expect.any(Function));+ pending.get('first')!('/bots/bot-a');+ await Promise.resolve();+ expect(openBotRoute).not.toHaveBeenCalled();+ // The ordinary path's own late async route checks the same latest gate.+ const isLatest = openOrdinary.mock.calls[0]![2] as () => boolean;+ expect(isLatest()).toBe(true);+ open('third');+ expect(isLatest()).toBe(false);+ });+it('读任务或加载投影失败时退回普通任务路由,不吞掉这次点击', async () => {const d = {readProfiles: () => [],diff --git a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts b/apps/desktop/src/renderer/features/bots/botSessionOwners.tsindex 31590dcd3f..6dac6ebf20 100644--- a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts+++ b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts@@ -70,6 +70,33 @@ export async function resolveBotRouteForSessionEntry(return botRouteForOwnedSession(profiles, sessionId);}+export interface SessionEntryNavigatorDeps {+ resolveBotRoute: (sessionId: string) => Promise<string | null>;+ openBotRoute: (route: string) => void;+ /** `isLatest` lets the ordinary path drop its own late async route result too. */+ openOrdinary: (sessionId: string, messageClientId: string | undefined, isLatest: () => boolean) => void;+}++/**+ * Session entries (notification clicks, task deep links) resolve asynchronously.+ * Only the latest entry may navigate, so a slow lookup for an earlier click can+ * never override a newer one.+ */+export function createSessionEntryNavigator(+ deps: SessionEntryNavigatorDeps,+): (sessionId: string, messageClientId?: string) => void {+ let sequence = 0;+ return (sessionId, messageClientId) => {+ const entry = ++sequence;+ const isLatest = () => sequence === entry;+ void deps.resolveBotRoute(sessionId).then((route) => {+ if (!isLatest()) return;+ if (route) deps.openBotRoute(route);+ else deps.openOrdinary(sessionId, messageClientId, isLatest);+ });+ };+}+export function buildBotSessionOwners(profiles: readonly BotProfile[],): Map<string, BotSessionOwner> {diff --git a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsxindex f0a75640b9..db9fa78ed4 100644--- a/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx+++ b/apps/mobile/src/__tests__/CompanionProfileSheet.test.tsx@@ -58,6 +58,9 @@ it('asks to discard a conflicted draft on back instead of ignoring the gesture',const discard = vi.mocked(Alert.alert).mock.calls[0][2]!.find(button => button.style === 'destructive')!;await act(async () => discard.onPress!());expect(h.view.page).toBe('home'); expect(h.close).not.toHaveBeenCalled();+ // The discarded draft gives way to the newer copy already read, not the stale one.+ await act(async () => h.view.onOpen('profile'));+ expect(h.view.values.name).toBe('Desktop edit'); expect(h.view.conflict).toBe(false);});it('waits for native dismissal before presenting the model picker and preserves the draft on return', async () => {await render(); await act(async () => h.view.onOpen('models'));diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsxindex 0232efa300..5a2696b662 100644--- a/apps/mobile/src/session/CompanionProfileSheet.tsx+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx@@ -259,6 +259,10 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {{ text: t('devices.common.cancel'), style: 'cancel' },{ text: t('devices.companions.automation.discard'), style: 'destructive', onPress: () => {if (current.current !== started || inFlight.current) return;+ // Discarding a conflicted draft adopts the newer copy already read, as 「放弃编辑并重新加载」 does.+ if (conflict?.page === page) {+ if (page === 'editor') setEditor(conflict.next); else setData(conflict.next);+ }setEditing(false); setConflict(null); void proceed();} },]);