Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(bots): 补种最后写 SOUL.md;通知入口对未知任务总是重读伙伴投影

Claude64a050702d64
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts
index c57f6d506a..9bf55c1597 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botProfileFolder.test.ts
@@ -318,8 +318,11 @@ describe('搬家', () => {
it('无硬链接补种写到一半失败时保留恢复标记,下一次补种把截断的文件补全', async () => {
const link = vi.spyOn(fs, 'link').mockRejectedValue(Object.assign(new Error('EPERM'), { code: 'EPERM' }));
const realOpen = fs.open.bind(fs);
- const open = vi.spyOn(fs, 'open').mockImplementationOnce(async (target, flags) => {
+ let failed = false;
+ const open = vi.spyOn(fs, 'open').mockImplementation(async (target, flags) => {
const handle = await realOpen(target, flags);
+ if (failed || !String(target).endsWith('SOUL.md')) return handle;
+ failed = true;
return Object.assign(Object.create(handle), {
writeFile: async (data: string) => {
await handle.writeFile(data.slice(0, 2));
@@ -343,6 +346,33 @@ describe('搬家', () => {
await expect(fs.access(path.join(home, 'SOUL.md.seeding'))).rejects.toBeTruthy();
});
+ it('SOUL.md 之外的槽写失败时不落 SOUL.md,下一次仍会补齐,而不是把缺失的 USER.md 当成清空', async () => {
+ const realWriteFile = fs.writeFile.bind(fs);
+ const writeFile = vi.spyOn(fs, 'writeFile').mockImplementation(async (target, data, options) => {
+ if (String(target).includes('USER.md.tmp-')) {
+ await realWriteFile(target, String(data).slice(0, 2), options);
+ throw Object.assign(new Error('ENOSPC'), { code: 'ENOSPC' });
+ }
+ return realWriteFile(target, data, options);
+ });
+ const home = botProfileDir(root, 'bot-a');
+ try {
+ await expect(migrateBotProfileFolder(root, 'bot-a', SEED)).rejects.toMatchObject({ code: 'ENOSPC' });
+ } finally {
+ writeFile.mockRestore();
+ }
+ // SOUL.md marks a seeded Home, so it must not exist while a sibling slot is missing.
+ await expect(fs.access(path.join(home, 'SOUL.md'))).rejects.toBeTruthy();
+ // The half-written temp file does not linger either.
+ expect((await fs.readdir(path.join(home, 'memories'))).filter((name) => name.includes('.tmp-'))).toEqual([]);
+
+ expect((await migrateBotProfileFolder(root, 'bot-a', SEED)).seeded).toBe(true);
+ const content = await readBotProfileFolder(root, 'bot-a');
+ expect(content.identitySource).toBe(SEED.identitySource);
+ expect(content.userContextSource).toBe(SEED.userContextSource);
+ expect(content.config).toEqual(SEED.config);
+ });
+
it('被中断的无硬链接补种:截断的文件补全,中断后用户改过的原样保留', async () => {
const home = botProfileDir(root, 'bot-a');
await fs.mkdir(path.join(home, 'memories'), { recursive: true });
diff --git a/apps/desktop/src/main/maker-ipc/botProfileFolder.ts b/apps/desktop/src/main/maker-ipc/botProfileFolder.ts
index 74497e8669..219e021511 100644
--- a/apps/desktop/src/main/maker-ipc/botProfileFolder.ts
+++ b/apps/desktop/src/main/maker-ipc/botProfileFolder.ts
@@ -235,12 +235,14 @@ async function writeTextIfAbsent(absPath: string, content: string): Promise<bool
}
await fs.mkdir(path.dirname(absPath), { recursive: true });
const tmp = `${absPath}.tmp-${process.pid}-${(writeSeq += 1)}`;
- await fs.writeFile(tmp, content, 'utf8');
try {
- await fs.link(tmp, absPath);
- return true;
- } catch (cause) {
- if ((cause as NodeJS.ErrnoException).code === 'EEXIST') return false;
+ await fs.writeFile(tmp, content, 'utf8');
+ try {
+ await fs.link(tmp, absPath);
+ return true;
+ } catch (cause) {
+ if ((cause as NodeJS.ErrnoException).code === 'EEXIST') return false;
+ }
} finally {
await fs.rm(tmp, { force: true }).catch(() => {});
}
@@ -442,6 +444,7 @@ export interface BotProfileFolderMigration {
*
* 1. 用数据库里的当前值播种 `SOUL.md` / `memories/USER.md` / `config.json`。
* **只在没有 SOUL.md 时做**,且只补缺失的那几个文件,绝不覆盖用户已经改过的文件。
+ * SOUL.md 最后写:它在就代表家已建好,其他槽写失败时下次仍会重试补种。
* 2. 把 `<userData>/bot-skills/<botId>/` 整个搬成 `<家>/skills` 的邻居
* (`.claude-plugin/` 一并带走)。一个伙伴一个家,不该散在两处。
*
@@ -466,9 +469,12 @@ export async function migrateBotProfileFolder(
// Seed only what is missing, each slot with an atomic create-if-absent: a hand-edited
// USER.md or config.json next to a missing SOUL.md — or a file the user saves in an
// editor at this very moment — is the user's content and must not be reset.
- seeded = await writeTextIfAbsent(soulPath, seed.identitySource);
+ // SOUL.md goes last: its presence is what marks the Home as seeded, so if a sibling
+ // slot fails the next run still sees SOUL.md missing and retries, instead of
+ // reconciling an absent USER.md as an emptied user profile.
await writeTextIfAbsent(at(SLOT.userContext), seed.userContextSource);
await writeTextIfAbsent(at(SLOT.config), `${JSON.stringify(seed.config, null, 2)}\n`);
+ seeded = await writeTextIfAbsent(soulPath, seed.identitySource);
}
const skillsMoved = await migrateBotSkillsIntoProfileFolder(userDataDir, botId, legacyUserDataDir);
diff --git a/apps/desktop/src/renderer/components/layout/MainLayout.tsx b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
index 24892cafda..e757e06b6e 100644
--- a/apps/desktop/src/renderer/components/layout/MainLayout.tsx
+++ b/apps/desktop/src/renderer/components/layout/MainLayout.tsx
@@ -102,7 +102,6 @@ import { makeGenericNewMakerRouteState } from '@/features/cc-agent/lib/genericNe
import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { ensureBotProfilesLoaded, getBotProfiles } from '@/features/bots/botStore';
import { createSessionEntryNavigator, resolveBotRouteForSessionEntry } from '@/features/bots/botSessionOwners';
-import * as sessionService from '@/lib/sessionService';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import {
isAgentIslandVisibleSessionOwnedByWorkdirBrowseRoute,
@@ -542,7 +541,6 @@ export function MainLayout() {
const [navigateToSession] = useState(() => createSessionEntryNavigator({
resolveBotRoute: (sessionId) => resolveBotRouteForSessionEntry(sessionId, {
readProfiles: getBotProfiles,
- readSessionSource: async (id) => (await sessionService.get(id)).source,
loadProfiles: ensureBotProfilesLoaded,
}),
openBotRoute: (route) => {
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
index 3541ae91b0..806f437787 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botSessionOwners.test.ts
@@ -92,36 +92,50 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
function deps(over: {
current?: BotProfile[];
loaded?: BotProfile[];
- source?: string | null;
}) {
const loadProfiles = vi.fn<(refresh: boolean) => Promise<BotProfile[]>>(async () => over.loaded ?? []);
return {
loadProfiles,
deps: {
readProfiles: () => over.current ?? [],
- readSessionSource: vi.fn(async () => over.source ?? null),
loadProfiles,
},
};
}
- it('投影已含该任务时直接回伙伴页,不读任务也不重载', async () => {
+ it('投影已含该任务时直接回伙伴页,不重载', async () => {
const { deps: d, loadProfiles } = deps({ current: [profile()] });
await expect(resolveBotRouteForSessionEntry('s-main', d)).resolves.toBe('/bots/bot-a');
- expect(d.readSessionSource).not.toHaveBeenCalled();
expect(loadProfiles).not.toHaveBeenCalled();
});
it('启动后从未进过伙伴页时先加载投影,再回伙伴页', async () => {
- const { deps: d, loadProfiles } = deps({ loaded: [profile()], source: 'bot' });
+ const { deps: d, loadProfiles } = deps({ loaded: [profile()] });
await expect(resolveBotRouteForSessionEntry('s-old', d)).resolves.toBe('/bots/bot-a/session/s-old');
expect(loadProfiles).toHaveBeenCalledWith(true);
});
- it('普通任务只按需加载一次,不强制重读投影', async () => {
- const { deps: d, loadProfiles } = deps({ source: 'desktop' });
+ it('投影已加载后新委派出去的任务(行上仍是 desktop)也会重读投影,回到接手伙伴', async () => {
+ const stale = profile();
+ const delegated = profile({
+ id: 'bot-b',
+ canonicalSessionId: 's-b-main',
+ sessions: [
+ { id: 's-b-main', role: 'canonical' },
+ { id: 's-delegated', role: 'delegation' },
+ ] as unknown as BotProfile['sessions'],
+ });
+ const { deps: d, loadProfiles } = deps({ current: [stale], loaded: [stale, delegated] });
+ await expect(resolveBotRouteForSessionEntry('s-delegated', d)).resolves.toBe(
+ '/bots/bot-b/session/s-delegated',
+ );
+ expect(loadProfiles).toHaveBeenCalledWith(true);
+ });
+
+ it('不属于任何伙伴的任务重读后仍回普通任务路由', async () => {
+ const { deps: d, loadProfiles } = deps({ current: [profile()], loaded: [profile()] });
await expect(resolveBotRouteForSessionEntry('plain', d)).resolves.toBeNull();
- expect(loadProfiles).toHaveBeenCalledWith(false);
+ expect(loadProfiles).toHaveBeenCalledTimes(1);
});
it('连续点击时,先点的慢查询不会覆盖后点的导航', async () => {
@@ -148,10 +162,9 @@ describe('通知入口在伙伴投影未加载时的路由', () => {
expect(isLatest()).toBe(false);
});
- it('读任务或加载投影失败时退回普通任务路由,不吞掉这次点击', async () => {
+ it('加载投影失败时退回普通任务路由,不吞掉这次点击', async () => {
const d = {
readProfiles: () => [],
- readSessionSource: vi.fn(async () => { throw new Error('offline'); }),
loadProfiles: vi.fn(async () => { throw new Error('not ready'); }),
};
await expect(resolveBotRouteForSessionEntry('s-main', d)).resolves.toBeNull();
diff --git a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
index 6dac6ebf20..cdb330b5c2 100644
--- a/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
+++ b/apps/desktop/src/renderer/features/bots/botSessionOwners.ts
@@ -48,7 +48,6 @@ export function botRouteForOwnedSession(
export interface BotSessionEntryRouteDeps {
readProfiles: () => readonly BotProfile[];
- readSessionSource: (sessionId: string) => Promise<string | null | undefined>;
/** Loads the current owner's profiles; `refresh` re-reads an already loaded projection. */
loadProfiles: (refresh: boolean) => Promise<readonly BotProfile[]>;
}
@@ -57,7 +56,9 @@ export interface BotSessionEntryRouteDeps {
* Resolve a session-only entry such as a notification click. The in-memory
* projection is only kept fresh while a Bots view is mounted, so a click can
* arrive before it was ever loaded for this account, or after a new Bot session
- * was linked. Load it once, and re-read it when the row itself is a Bot session.
+ * was linked. The session row cannot tell: delegated tasks keep
+ * `source: 'desktop'` and their owner lives only in `bot_session_links`. So a
+ * session the projection does not know always re-reads it once.
*/
export async function resolveBotRouteForSessionEntry(
sessionId: string,
@@ -65,8 +66,7 @@ export async function resolveBotRouteForSessionEntry(
): Promise<string | null> {
const known = botRouteForOwnedSession(deps.readProfiles(), sessionId);
if (known) return known;
- const source = await deps.readSessionSource(sessionId).catch(() => null);
- const profiles = await deps.loadProfiles(source === 'bot').catch(() => []);
+ const profiles = await deps.loadProfiles(true).catch(() => []);
return botRouteForOwnedSession(profiles, sessionId);
}