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(bot-autonomy): 归属与启动兜底即时生效——新任务先确认归属、接手立即重读、启动读失败可重试

Chris36345b0097dc
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
index ef6da2af81..1c36dcce09 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
@@ -9,7 +9,8 @@
* - 最小失败输入:伙伴主任务(canonical)出现在活动里;启动时灵动岛残留「完成」;主人点停止后灵动岛条目消失
* 被当成做完;同一条挂起交互在重启后得到新的事件 id;远程 list-active 连续失败;远程任务两次轮询之间从权限请求
* A 换到 B,仍显示 A;本机任务在同一相位里从请求 A 换到 B,沿用 A 的等待时刻;读任务元数据失败一次后,
- * 这批任务被丢掉,之后再无活动就永远不进表。
+ * 这批任务被丢掉,之后再无活动就永远不进表;启动兜底读失败一次后再不重试;伙伴刚开的任务在上次归属读取
+ * 几秒内出现,被当成「没人开」落到总调度。
* - tier:unit(全部 IO 经注入的内存 fake,时间由 now() 推进,无真实等待)。
*/
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
@@ -53,6 +54,8 @@ function harness(options: {
const pending = new Map<string, unknown[]>();
const onChange = vi.fn();
let metaReadFailures = 0;
+ let interruptedReadFailures = 0;
+ const creators = new Map(Object.entries(options.creators ?? {}));
const invokeRemote = vi.fn(options.invokeRemote ?? (async () => { throw new Error('offline'); }));
const watch = new TaskWatch({
now: () => now,
@@ -67,10 +70,16 @@ function harness(options: {
}
return ids.flatMap((id) => (metas.has(id) ? [metas.get(id)!] : []));
},
- readInterruptedSessions: async () => [...metas.values()].filter((m) => m.interrupted),
+ readInterruptedSessions: async () => {
+ if (interruptedReadFailures > 0) {
+ interruptedReadFailures -= 1;
+ throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
+ }
+ return [...metas.values()].filter((m) => m.interrupted);
+ },
readOwnership: async () => ({
bots: new Map([['sched', { status: 'active', allowSchedulerFollow: false }], ['a', { status: 'active', allowSchedulerFollow: false }]]),
- creatorBySession: new Map(Object.entries(options.creators ?? {})),
+ creatorBySession: new Map(creators),
responsibleByBot: new Map(),
}),
readSchedulerOverride: () => ({ customized: true, schedulerBotId: 'sched' }),
@@ -82,6 +91,8 @@ function harness(options: {
watch, metas, pending, onChange, invokeRemote, toolsInFlight,
advance: (ms: number) => { now += ms; },
failMetaReads: (count: number) => { metaReadFailures = count; },
+ failInterruptedReads: (count: number) => { interruptedReadFailures = count; },
+ creators,
now: () => now,
};
}
@@ -194,6 +205,28 @@ describe('TaskWatch local observation', () => {
});
});
+describe('TaskWatch ownership and startup retries', () => {
+ it('retries the startup read of interrupted tasks on a later sweep', async () => {
+ const h = harness({ metas: [meta('crashed', { interrupted: true, activeTurnStartedAt: 5_000 })] });
+ h.failInterruptedReads(1);
+ await h.watch.start();
+ expect(h.watch.get('crashed')).toBeUndefined();
+ await h.watch.sweep();
+ expect(h.watch.get('crashed')).toMatchObject({ phase: 'errored', phaseSince: 5_000, followerBotId: 'sched' });
+ });
+
+ it('re-reads ownership before judging a newly seen task unowned, even right after the last read', async () => {
+ const h = harness({ metas: [meta('fresh')] });
+ await h.watch.start();
+ // 伙伴 a 刚开出这件任务:委派记录在上次归属读取之后一秒才写入。
+ h.advance(1_000);
+ h.creators.set('fresh', 'a');
+ h.watch.applyActivity('fresh', activity('fresh', 'running'));
+ await h.watch.settled();
+ expect(h.watch.get('fresh')).toMatchObject({ creatorBotId: 'a', followerBotId: 'a', source: 'bot-task' });
+ });
+});
+
describe('TaskWatch remote polling', () => {
it('reads eligible online computers, then backs off and marks rows offline when polling fails', async () => {
let fail = false;
diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
index d9ef9c51e8..4e91d50850 100644
--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts
+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
@@ -167,6 +167,8 @@ export class TaskWatch {
private ownershipAt = 0;
/** 归属至少成功读到过一次:之前不重算、不通知,免得把启动时已有的事件按「没人跟」结清。 */
private ownershipLoaded = false;
+ /** 启动兜底(上一轮被打断的任务)是否已读成功;读失败时在之后的扫描里重试。 */
+ private interruptedSeeded = false;
private ownershipRefresh: Promise<void> | null = null;
private schedulerBotId: string | null = null;
private readonly finishedLog: FinishedRecord[] = [];
@@ -310,7 +312,9 @@ export class TaskWatch {
unowned ||= result.unowned;
}
// 新出现的任务可能刚由伙伴委派开出来:归属有点旧就提前重读一次。
- if (unowned && now - this.ownershipAt >= 5_000) await this.refreshOwnership();
+ // 新出现、又查不到创建者的任务:发布任何事件前先确认一次最新归属(委派任务与它的委派记录在同一事务里写入,
+ // 新读一次一定能认出来);不拿几秒前的缓存判它「没人开」,否则事件会先落到总调度并被结清。
+ if (unowned) await this.refreshOwnership(true);
if (changed || unowned) this.deps.onChange();
}
}
@@ -423,6 +427,7 @@ export class TaskWatch {
this.deps.log.warn('interrupted session seed failed', { error: errorCode(error) });
return;
}
+ this.interruptedSeeded = true;
for (const meta of rows) {
this.meta.set(meta.id, meta);
if (!this.isWatchable(meta) || !meta.interrupted || this.rows.has(meta.id) || this.local.get(meta.id)?.activity) continue;
@@ -538,6 +543,8 @@ export class TaskWatch {
const now = this.deps.now();
if (now - this.ownershipAt >= OWNERSHIP_REFRESH_MS) await this.refreshOwnership();
await this.refreshLocalMeta();
+ // 启动兜底读失败(如数据库一时忙):按扫描节奏重试,读成功一次后不再读。
+ if (!this.interruptedSeeded && !this.stopped) await this.seedInterrupted();
// 上次读元数据失败留下的 pending:按扫描节奏重试一次,不形成重试风暴。
if (this.pending.size && this.ownershipLoaded && !this.stopped) this.scheduleFlush();
for (const [id, row] of this.rows) {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
index 772fb7e8b0..a2ea66e930 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botTaskResponsibility.test.ts
@@ -4,6 +4,7 @@ import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { botProfileDir } from '../botProfileFolder.js';
import { collectTaskResponsibilityScopes, readTaskResponsibilities, responsibleSessionIds, setTaskResponsibility } from '../botTaskResponsibility.js';
+import { setBotAutonomyBotsChangedListener } from '../../bot-autonomy/botsChangedSignal.js';
// Lock mechanics have their own cross-process suite; exercise this store's guarded write.
vi.mock('../../device-link/crossProcessLock.js', () => ({
@@ -25,6 +26,18 @@ describe('task responsibility', () => {
expect(await readTaskResponsibilities(root, 'two')).toEqual({});
expect(await readTaskResponsibilities(root + '-other-owner', 'one')).toEqual({});
});
+ // 依据:伙伴自主跟进的归属须在接手 / 解除后立即生效(cindy-bots-runtime.md §6.3.2);缺口:写入成功后
+ // 观察层要等 60 秒定时重读。最小失败输入:一次成功接手、一次被拒的非法写入。tier:unit。
+ it('tells the autonomy layer to re-read ownership after a successful take or release only', async () => {
+ const changed = vi.fn();
+ setBotAutonomyBotsChangedListener(changed);
+ try {
+ await setTaskResponsibility(root, 'one', 'taken', true, () => {});
+ expect(changed).toHaveBeenCalledTimes(1);
+ await expect(setTaskResponsibility(root, 'one', '', true, () => {})).rejects.toThrow();
+ expect(changed).toHaveBeenCalledTimes(1);
+ } finally { setBotAutonomyBotsChangedListener(null); }
+ });
it('does not touch workbench judgments or Todo when taking or releasing', async () => {
const home = botProfileDir(root, 'one');
await fs.mkdir(home, { recursive: true });
diff --git a/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts b/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
index fa318cef0e..a1a22be515 100644
--- a/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
+++ b/apps/desktop/src/main/maker-ipc/botTaskResponsibility.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import { randomUUID } from 'node:crypto';
import { withCrossProcessLock } from '../device-link/crossProcessLock.js';
import { botProfileDir } from './botProfileFolder.js';
+import { signalBotAutonomyBotsChanged } from '../bot-autonomy/botsChangedSignal.js';
/** Per-task responsibility, independent of directories and Todo.
* Releases override creation evidence; nothing is inferred from conversation text.
@@ -69,6 +70,8 @@ export async function setTaskResponsibility(
}
assertCurrent();
});
+ // 接手 / 解除立即让自主跟进重读归属:工作台与跟进者不必等 60 秒的定时重读。
+ signalBotAutonomyBotsChanged();
}
export interface TaskResponsibilityScope {