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): 回应第三轮 review——远程可见性、暂停保留、兜底范围与状态刷新

Chrisb396017af541
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts
index 5336b447dc..48b7da2d2d 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts
@@ -162,6 +162,42 @@ describe('workbench glance scope', () => {
expect(all.doneToday).toBe(2);
expect(all.offlineDevices).toEqual(['Old PC']);
});
+
+ /*
+ * 测试价值
+ * - 生产入口与可观察结果:projectBotGlance 带 excludeBotIds(远程端 glance IPC 传入隐藏 / 归档伙伴)时的等你 / 在做 / 今天做完。
+ * - Bug/规则依据:隐藏伙伴只在本机恢复(botRemoteVisibility.ts);隐藏只写 botProfiles.hiddenAt、不写 sessions.hiddenAt,
+ * 总调度(scope all)的远程工作台曾照样列出隐藏伙伴开的、它的主任务与它在跟的任务。
+ * - 现有覆盖缺口:上一用例不传排除集;本机渲染层不排除,远程排除只有这里守护。
+ * - 最小失败输入:隐藏伙伴开的等你 / 在做任务、它的主任务、它今天做完的任务。
+ * - tier:unit(纯函数)。
+ */
+ it('hides tasks of companions excluded for a remote controller, keeping owner and visible teammates tasks', () => {
+ const now = 10 * 60_000;
+ const glance = projectBotGlance({
+ botId: 'sched',
+ schedulerBotId: 'sched',
+ rows: [
+ row({ sessionId: 'h-wait', creatorBotId: 'hidden', followerBotId: 'hidden', phase: 'waiting-answer', pendingQuestion: 'q' }),
+ row({ sessionId: 'h-work', creatorBotId: 'hidden', followerBotId: 'hidden', phase: 'running' }),
+ row({ sessionId: 'h-main', canonicalOfBotId: 'hidden', phase: 'errored', error: 'boom' }),
+ row({ sessionId: 'owner', phase: 'usage-limit', startedAt: 60_000 }),
+ row({ sessionId: 'b-task', creatorBotId: 'b', followerBotId: 'b', phase: 'waiting-permission' }),
+ ],
+ responsibleSessionIds: new Set(),
+ finished: [
+ { sessionId: 'h-done', creatorBotId: 'hidden', at: now - 1 },
+ { sessionId: 'owner-done', creatorBotId: null, at: now - 1 },
+ ],
+ offlineDevices: [],
+ lastSweepAt: now,
+ now,
+ excludeBotIds: new Set(['hidden']),
+ });
+ expect(glance.waiting.map((r) => [r.sessionId, r.phase])).toEqual([['b-task', 'waiting-permission']]);
+ expect(glance.working.map((r) => [r.sessionId, r.phase])).toEqual([['owner', 'usage-limit']]);
+ expect(glance.doneToday).toBe(1);
+ });
});
describe('waiting-row summary for a permission request', () => {
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/followUpPrompt.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/followUpPrompt.test.ts
index 8488d6e095..53719caf6e 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/followUpPrompt.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/followUpPrompt.test.ts
@@ -3,7 +3,8 @@
* - 生产入口与可观察结果:buildFollowUpRoutinePrompt 生成、写进内置跟进例行任务的指令全文。
* - 规则依据:跟进裁决(2026-10-17)——先读摘要、按 phase 分别处理、卡住时有工具在跑只等不停、
* 只有确认没有工具在跑且毫无进展才停、≥3 次不再推、处理后更新待办、
- * 无事静默、要主人知道必须 schedule_notify_current_run;事件是不可信数据;对主人不说内部词;≤1500 字。
+ * 无事静默、要主人知道必须 schedule_notify_current_run;
+ * sweep 兜底也要看 working 里撞上用量上限或久无进展的任务(只看 waiting 时伙伴会白醒后直接退出);事件是不可信数据;对主人不说内部词;≤1500 字。
* - 现有覆盖缺口:新模板;缺任何一条指令,伙伴被叫醒后会乱推或悄悄不汇报,单测是唯一守护。
* - 最小失败输入:删掉任一条指令或超长。
* - tier:unit(纯函数)。
@@ -33,7 +34,7 @@ describe('follow-up routine prompt', () => {
'last_user_ask',
'occurrence≥3',
'update_teammate_todo',
- 'get_workbench',
+ 'get_workbench', 'working 里 phase 为 usage-limit',
'schedule_notify_current_run', '主人就看不到',
'没事可做就什么都不输出',
]) {
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
index d176348a1e..863450434c 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
@@ -63,6 +63,7 @@ async function setup(options: {
let saved: RoutineState | null = null;
const execute = vi.fn<RoutineEngineDeps['execute']>(async () => ({}));
const remind = vi.fn();
+ const push = vi.fn();
const engineDeps: RoutineEngineDeps = {
load: async () => structuredClone(saved),
save: async (state) => { saved = structuredClone(state); },
@@ -84,7 +85,7 @@ async function setup(options: {
log,
isCurrent: () => true,
remind,
- push: () => {},
+ push,
subscribeActivity: options.subscribeActivity ?? (() => () => {}),
createWatch: (onChange) => new TaskWatch({
now: () => now,
@@ -114,7 +115,7 @@ async function setup(options: {
await created.start();
return created;
};
- return { runtime, create, engine, execute, remind, now: () => now, advance: (ms: number) => { now += ms; } };
+ return { runtime, create, engine, execute, remind, push, now: () => now, advance: (ms: number) => { now += ms; } };
}
describe('BotAutonomyRuntime with the routine engine', () => {
@@ -381,4 +382,39 @@ describe('BotAutonomyRuntime with the routine engine', () => {
await engine.stop();
}
});
+
+ /*
+ * 测试价值
+ * - 生产入口与可观察结果:BotAutonomyRuntime.sweep → 状态表 onChange → 节流推送,界面收到 push 的次数。
+ * - Bug/规则依据:页脚「上次看过 N 分钟前」读 lastSweepAt;推送签名曾不含它,没有别的变化时界面一直停在旧时间。
+ * - 现有覆盖缺口:其它用例不观察 push。
+ * - 最小失败输入:两次扫描之间状态表不变、时间跨过一分钟(应推)与只过 10 秒(不推)。
+ * - tier:unit(时间由 now() 推进;节流定时器为 setTimeout 0,不是真实等待)。
+ */
+ it('refreshes the workbench footer when a sweep crosses a minute, even if no task changed', async () => {
+ const t = await setup();
+ const engine = await t.engine();
+ const runtime = await t.runtime(engine);
+ const flush = async () => { for (let i = 0; i < 3; i += 1) await new Promise((resolve) => setTimeout(resolve, 0)); };
+ try {
+ await flush();
+ t.push.mockClear();
+ t.advance(60_000);
+ await runtime.sweep();
+ await flush();
+ expect(t.push).toHaveBeenCalledTimes(1);
+ // 同一分钟内再扫一次:页脚不变,不推。
+ t.advance(10_000);
+ await runtime.sweep();
+ await flush();
+ expect(t.push).toHaveBeenCalledTimes(1);
+ t.advance(60_000);
+ await runtime.sweep();
+ await flush();
+ expect(t.push).toHaveBeenCalledTimes(2);
+ } finally {
+ runtime.stop();
+ await engine.stop();
+ }
+ });
});
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 abe83f20eb..ef6da2af81 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
@@ -8,7 +8,8 @@
* - 现有覆盖缺口:新模块;autonomyRules 只测纯判定,不经过活动订阅、读库与远程轮询的组合时序。
* - 最小失败输入:伙伴主任务(canonical)出现在活动里;启动时灵动岛残留「完成」;主人点停止后灵动岛条目消失
* 被当成做完;同一条挂起交互在重启后得到新的事件 id;远程 list-active 连续失败;远程任务两次轮询之间从权限请求
- * A 换到 B,仍显示 A。
+ * A 换到 B,仍显示 A;本机任务在同一相位里从请求 A 换到 B,沿用 A 的等待时刻;读任务元数据失败一次后,
+ * 这批任务被丢掉,之后再无活动就永远不进表。
* - tier:unit(全部 IO 经注入的内存 fake,时间由 now() 推进,无真实等待)。
*/
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
@@ -51,6 +52,7 @@ function harness(options: {
const metas = new Map((options.metas ?? []).map((m) => [m.id, m]));
const pending = new Map<string, unknown[]>();
const onChange = vi.fn();
+ let metaReadFailures = 0;
const invokeRemote = vi.fn(options.invokeRemote ?? (async () => { throw new Error('offline'); }));
const watch = new TaskWatch({
now: () => now,
@@ -58,7 +60,13 @@ function harness(options: {
getActivitySnapshots: () => options.snapshots ?? [],
isToolCallInFlight: (id) => toolsInFlight.has(id),
getPendingInteractions: (id) => pending.get(id) ?? [],
- readLocalSessions: async (ids) => ids.flatMap((id) => (metas.has(id) ? [metas.get(id)!] : [])),
+ readLocalSessions: async (ids) => {
+ if (metaReadFailures > 0) {
+ metaReadFailures -= 1;
+ throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
+ }
+ return ids.flatMap((id) => (metas.has(id) ? [metas.get(id)!] : []));
+ },
readInterruptedSessions: async () => [...metas.values()].filter((m) => m.interrupted),
readOwnership: async () => ({
bots: new Map([['sched', { status: 'active', allowSchedulerFollow: false }], ['a', { status: 'active', allowSchedulerFollow: false }]]),
@@ -73,6 +81,7 @@ function harness(options: {
return {
watch, metas, pending, onChange, invokeRemote, toolsInFlight,
advance: (ms: number) => { now += ms; },
+ failMetaReads: (count: number) => { metaReadFailures = count; },
now: () => now,
};
}
@@ -150,6 +159,39 @@ describe('TaskWatch local observation', () => {
}
expect(ids).toEqual(['waiting:t:7000', 'waiting:t:7000']);
});
+
+ it('restarts the wait clock when a local task moves from one permission request to another', async () => {
+ const h = harness({ metas: [meta('t')] });
+ await h.watch.start();
+ const waiting = activity('t', 'needs-interaction', { interactionKind: 'permission', lastActivityAtMs: 7_000 });
+ h.pending.set('t', [{ kind: 'permission', requestId: 'req-A', toolName: 'Bash' }]);
+ h.watch.applyActivity('t', waiting);
+ await h.watch.settled();
+ expect(h.watch.get('t')).toMatchObject({ phase: 'waiting-permission', pendingRequestId: 'req-A', phaseSince: 7_000 });
+
+ // A 被处理后紧接着出现 B,中间的「在跑」没有被单独观察到:相位不变,请求换了。
+ h.advance(AUTONOMY_THRESHOLDS.waitingAfterMs);
+ h.pending.set('t', [{ kind: 'permission', requestId: 'req-B', toolName: 'Write' }]);
+ h.watch.applyActivity('t', waiting);
+ await h.watch.settled();
+ expect(h.watch.get('t')).toMatchObject({
+ phase: 'waiting-permission', pendingRequestId: 'req-B', pendingQuestion: 'Write', phaseSince: h.now(),
+ });
+ });
+
+ it('keeps tasks whose metadata read failed and retries them on the next sweep', async () => {
+ const h = harness({ metas: [meta('quiet')] });
+ await h.watch.start();
+ h.failMetaReads(1);
+ // 这是这件任务最后一条活动:之后一直安静(卡住),不会再有活动把它带回来。
+ h.watch.applyActivity('quiet', activity('quiet', 'running'));
+ await h.watch.settled();
+ expect(h.watch.get('quiet')).toBeUndefined();
+
+ await h.watch.sweep();
+ await h.watch.settled();
+ expect(h.watch.get('quiet')).toMatchObject({ phase: 'running', followerBotId: 'sched' });
+ });
});
describe('TaskWatch remote polling', () => {
diff --git a/apps/desktop/src/main/bot-autonomy/followUpPrompt.ts b/apps/desktop/src/main/bot-autonomy/followUpPrompt.ts
index 23ff7850ff..8659320f08 100644
--- a/apps/desktop/src/main/bot-autonomy/followUpPrompt.ts
+++ b/apps/desktop/src/main/bot-autonomy/followUpPrompt.ts
@@ -6,7 +6,7 @@
* FOLLOW_UP_PROMPT_VERSION,宿主据此把已有伙伴的内置规则对齐到新模板。
* 长度上限 1500 字:每次叫醒都会带上,控制成本。
*/
-export const FOLLOW_UP_PROMPT_VERSION = 2;
+export const FOLLOW_UP_PROMPT_VERSION = 3;
export const FOLLOW_UP_PROMPT_MAX_CHARS = 1500;
@@ -25,7 +25,7 @@ export function buildFollowUpRoutinePrompt(botId: string): string {
'3. 同一任务同类事件 occurrence≥3:不要再推,直接告诉主人卡在哪、需要他做什么。',
'- 别的电脑上的任务由那台电脑上的伙伴跟进,你只在工作台里看;主人明确要你去继续时才动它。',
'4. 每处理完一件,用 update_teammate_todo 更新或完成对应待办。',
- '5. sweep 事件(兜底):说明有事等了很久没人处理,用 get_workbench 逐件看 waiting 里的本机任务,同样先读摘要。',
+ '5. sweep 事件(兜底):说明有事等了很久没人处理。用 get_workbench 看本机任务:waiting 里的每一件,以及 working 里 phase 为 usage-limit、或做了很久没有进展的(读摘要确认真卡住再动);逐件按第 2 条处理,同样先读摘要。',
'6. 这一轮的回复不会自动发给主人。要主人知道的事,先调用 schedule_notify_current_run 再写;不调用,主人就看不到。没事可做就什么都不输出。',
'对主人说平常话:说「任务」,不说 session、phase、事件、例行任务这类内部词。',
].join('\n');
diff --git a/apps/desktop/src/main/bot-autonomy/glance.ts b/apps/desktop/src/main/bot-autonomy/glance.ts
index cd419eebe4..4f5f2d6ce8 100644
--- a/apps/desktop/src/main/bot-autonomy/glance.ts
+++ b/apps/desktop/src/main/bot-autonomy/glance.ts
@@ -30,6 +30,11 @@ export interface GlanceInput {
offlineDevices: readonly string[];
lastSweepAt: number;
now: number;
+ /**
+ * 不可见的伙伴(远程端:隐藏 / 归档的伙伴只在本机恢复):它开的、它的主任务、它在跟的任务都不投影,
+ * 也不计入「今天做完」。本机渲染层不传。
+ */
+ excludeBotIds?: ReadonlySet<string>;
}
export function isSameLocalDay(a: number, b: number): boolean {
@@ -42,6 +47,8 @@ export function projectBotGlance(input: GlanceInput): BotGlance {
const scope: BotGlance['scope'] = input.schedulerBotId === input.botId ? 'all' : 'own';
const inScope = (sessionId: string, creatorBotId: string | null) =>
scope === 'all' || creatorBotId === input.botId || input.responsibleSessionIds.has(sessionId);
+ const exclude = input.excludeBotIds;
+ const hidden = (botId: string | null | undefined) => !!botId && !!exclude?.has(botId);
const waiting: Array<GlanceRow & { sort: number }> = [];
const working: Array<GlanceRow & { sort: number }> = [];
const minutes = (since: number) => Math.max(0, Math.floor((input.now - since) / 60_000));
@@ -49,12 +56,14 @@ export function projectBotGlance(input: GlanceInput): BotGlance {
if (!inScope(row.sessionId, row.creatorBotId)) continue;
// 自己的主任务不进自己的工作台:看到自己在做事只是噪音。
if ((row.canonicalOfBotId ?? null) === input.botId) continue;
+ if (hidden(row.creatorBotId) || hidden(row.canonicalOfBotId) || hidden(row.followerBotId)) continue;
const base = {
sessionId: row.sessionId,
deviceId: row.deviceId,
deviceName: row.deviceName,
online: row.online,
title: row.title,
+ phase: row.phase,
followerBotId: row.followerBotId,
};
if (row.phase === 'waiting-answer' || row.phase === 'waiting-permission' || row.phase === 'errored') {
@@ -90,7 +99,8 @@ export function projectBotGlance(input: GlanceInput): BotGlance {
});
const doneToday = new Set(
input.finished
- .filter((item) => isSameLocalDay(item.at, input.now) && inScope(item.sessionId, item.creatorBotId))
+ .filter((item) => isSameLocalDay(item.at, input.now) && inScope(item.sessionId, item.creatorBotId)
+ && !hidden(item.creatorBotId))
.map((item) => item.sessionId),
).size;
return {
diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.ts
index 10866427f9..1bda58708c 100644
--- a/apps/desktop/src/main/bot-autonomy/hub.ts
+++ b/apps/desktop/src/main/bot-autonomy/hub.ts
@@ -22,7 +22,7 @@ import {
import { throwIpcError } from '../utils/ipcValidate.js';
import { resolveSchedulerBotId } from './follower.js';
import { readBotDirectory } from './hostData.js';
-import type { BotAutonomyRuntime } from './runtime.js';
+import type { BotAutonomyRuntime, GlanceOptions } from './runtime.js';
import { errorCode } from './taskWatch.js';
const log = createLogger('bot-autonomy');
@@ -68,10 +68,10 @@ function emptyGlance(botId: string): BotGlance {
return { botId, scope: 'own', waiting: [], working: [], lastSweepAt: 0, doneToday: 0, offlineDevices: [] };
}
-export function getBotAutonomyGlance(botId: string): BotGlance {
+export function getBotAutonomyGlance(botId: string, options?: GlanceOptions): BotGlance {
if (isAppSessionBoundaryPending()) throwIpcError('PRECONDITION_FAILED', 'App session is switching; retry later.');
const active = current && scopeIsCurrent(current.scope) ? current.runtime : null;
- return active ? active.glance(botId) : emptyGlance(botId);
+ return active ? active.glance(botId, options) : emptyGlance(botId);
}
/** 默认总调度:在用的 Cindy 助理,否则没有。 */
diff --git a/apps/desktop/src/main/bot-autonomy/ipc.ts b/apps/desktop/src/main/bot-autonomy/ipc.ts
index ecfd286da5..d5f55e23c4 100644
--- a/apps/desktop/src/main/bot-autonomy/ipc.ts
+++ b/apps/desktop/src/main/bot-autonomy/ipc.ts
@@ -32,6 +32,12 @@ export function registerBotAutonomyIpc(): void {
.where(eq(botProfiles.id, botId))
.limit(1);
if (!profile || !isBotVisibleRemotely(profile)) throwIpcError('NOT_FOUND', 'Bot 不存在');
+ // 总调度看全部任务:隐藏 / 归档伙伴开的、它的主任务与它在跟的任务也不能经远程露出。
+ const profiles = await getDbClient().drizzle
+ .select({ id: botProfiles.id, hiddenAt: botProfiles.hiddenAt, status: botProfiles.status })
+ .from(botProfiles);
+ const excludeBotIds = new Set(profiles.filter((item) => !isBotVisibleRemotely(item)).map((item) => item.id));
+ return getBotAutonomyGlance(botId, { excludeBotIds });
}
return getBotAutonomyGlance(botId);
});
diff --git a/apps/desktop/src/main/bot-autonomy/runtime.ts b/apps/desktop/src/main/bot-autonomy/runtime.ts
index 78feb1c148..8d0bcad4fd 100644
--- a/apps/desktop/src/main/bot-autonomy/runtime.ts
+++ b/apps/desktop/src/main/bot-autonomy/runtime.ts
@@ -58,6 +58,11 @@ export interface AutonomyRuntimeDeps {
subscribeActivity(watch: TaskWatch): (() => void) | null;
}
+/** 「一眼」的调用方附加限制(远程端排除不可见伙伴)。 */
+export interface GlanceOptions {
+ excludeBotIds?: ReadonlySet<string>;
+}
+
export class BotAutonomyRuntime {
readonly watch: TaskWatch;
private readonly ledger = new AutonomyEventLedger();
@@ -137,7 +142,7 @@ export class BotAutonomyRuntime {
}
}
- glance(botId: string): BotGlance {
+ glance(botId: string, options?: GlanceOptions): BotGlance {
return projectBotGlance({
botId,
schedulerBotId: this.watch.getSchedulerBotId(),
@@ -147,6 +152,7 @@ export class BotAutonomyRuntime {
offlineDevices: this.watch.offlineDevices(),
lastSweepAt: this.watch.getLastSweepAt(),
now: this.deps.now(),
+ ...(options?.excludeBotIds ? { excludeBotIds: options.excludeBotIds } : {}),
});
}
@@ -372,11 +378,15 @@ export class BotAutonomyRuntime {
this.pushTimer.unref?.();
}
- /** 只在「一眼」可见的内容变了时推送;分钟数由界面自己按时间刷新。 */
+ /**
+ * 只在「一眼」可见的内容变了时推送;分钟数由界面自己按时间刷新。
+ * 页脚「上次看过 N 分钟前」读 lastSweepAt:按分钟粒度计入签名,扫描后没别的变化也会刷新。
+ */
flushPush(): void {
if (this.stopped || !this.deps.isCurrent()) return;
const signature = JSON.stringify([
this.watch.getSchedulerBotId(),
+ Math.floor(this.watch.getLastSweepAt() / 60_000),
this.watch.offlineDevices(),
this.watch.finished().length,
this.watch.list().map((row) => [
diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
index b98cdbe5b6..d9ef9c51e8 100644
--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts
+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
@@ -296,7 +296,10 @@ export class TaskWatch {
for (const id of unknown) if (!found.has(id)) this.missingMeta.set(id, now);
} catch (error) {
this.deps.log.warn('session meta read failed', { error: errorCode(error) });
- continue;
+ // 读库失败不能丢掉这批 id:否则之后一直安静的任务(正是卡住的那种)再也进不了表。
+ // 放回 pending 并停下,不原地空转;下一条活动或下一次扫描再重试。
+ for (const id of ids) this.pending.add(id);
+ break;
}
}
let unowned = false;
@@ -371,6 +374,9 @@ export class TaskWatch {
pendingQuestion = summary?.summary ?? (keep ? previous.pendingQuestion : null);
pendingRequestId = summary?.requestId ?? (keep ? previous.pendingRequestId ?? null : null);
}
+ // 同一相位里从请求 A 换到 B:新请求是新的等待,等待时刻从这次观察算起(与远程一致)。
+ if (previous?.phase === phase && previous.pendingRequestId && pendingRequestId
+ && previous.pendingRequestId !== pendingRequestId) phaseSince = now;
const canonicalOfBotId = this.canonicalOwner(sessionId, meta);
const creatorBotId = this.creatorOf(sessionId, canonicalOfBotId);
const row: WatchedSession = {
@@ -532,6 +538,8 @@ export class TaskWatch {
const now = this.deps.now();
if (now - this.ownershipAt >= OWNERSHIP_REFRESH_MS) await this.refreshOwnership();
await this.refreshLocalMeta();
+ // 上次读元数据失败留下的 pending:按扫描节奏重试一次,不形成重试风暴。
+ if (this.pending.size && this.ownershipLoaded && !this.stopped) this.scheduleFlush();
for (const [id, row] of this.rows) {
if (row.phase === 'finished' && now - row.phaseSince >= FINISHED_ROW_RETENTION_MS
&& !(row.deviceId === null && this.local.get(id)?.activity)) this.rows.delete(id);
diff --git a/apps/desktop/src/main/maker-ipc/teammateGuide.ts b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
index 8ee6cfa338..7e71f22993 100644
--- a/apps/desktop/src/main/maker-ipc/teammateGuide.ts
+++ b/apps/desktop/src/main/maker-ipc/teammateGuide.ts
@@ -28,7 +28,7 @@ export function buildTeammateGuide(
'The application in this guide is the host providing teammate, task and settings tools, not the model provider or agent CLI. Use the host tools for these operations; provider documentation cannot tell you the application’s current settings or available controls.',
...(helperAvailable ? [
TEAMMATE_CONTROL_GUIDANCE,
- 'Your workbench (`get_workbench`) is a glance: tasks waiting for the owner and tasks in progress. The teammate the owner chose to follow every task sees and may continue every task, including tasks on other online computers; every other teammate sees only tasks it started or explicitly agreed to handle. Directories and message history never grant responsibility. Use set_workbench_task_responsibility to take or release one task; a take does not start execution, and release does not stop, move, archive or delete a task or affect Todo. When the host wakes you about a followed task, read `get_task_digest` first and act through the existing task tools (`continue_workbench_task`, `send_to_session`, `set_session_runtime`).',
+ 'Your workbench (`get_workbench`) is a glance: tasks waiting for the owner and tasks in progress. The teammate the owner chose to follow every task can read every task, including tasks on other online computers, but may continue only tasks no teammate started, tasks it started, or tasks the host handed to it (the starting teammate is paused or allows it to follow); another teammate’s task is read-only (`continue_workbench_task` returns TASK_FOLLOWED_BY_OTHER_BOT), and tasks on other computers are followed by that computer’s teammates, so continue one only when the owner explicitly asks. Every other teammate sees only tasks it started or explicitly agreed to handle. Directories and message history never grant responsibility. Use set_workbench_task_responsibility to take or release one task; a take does not start execution, and release does not stop, move, archive or delete a task or affect Todo. When the host wakes you about a followed task, read `get_task_digest` first and act through the existing task tools (`continue_workbench_task`, `send_to_session`, `set_session_runtime`).',
'For recurring work, first call routine_list and reuse the existing rule. Prefer an available event source, or a deterministic command/script pre-run check, over waking a model just to poll. Install and test scripts through schedule_set_pre_run_hook, then save its command as routine_save.preRunHook and read back with routine_list. Exit 2 means skip the model; exit 0 supplies a concise change summary; errors/timeouts must be nonzero failures, never fabricated no-change results. Use stable upstream event IDs or durable cursors and acknowledge only successfully handled changes; do not add arbitrary time windows or advance a cursor before delivery succeeds. For a check, explicitly set silentWhenIdle=true: no preamble, progress or no-change report. Call schedule_notify_current_run only for a new actionable result or a check failure requiring attention, then write one concise final report. Explicit reminders and scheduled sends are the work itself: set silentWhenIdle=false when creating those rules, preserve existing user choices, and never swallow their intended delivery. Omitted quiet settings preserve delivery. Advanced settings expose the saved quiet/check configuration; the user need not edit files. Preserve the standing authorization, owner and failure visibility.',
'The preloaded teammate-guide is itself your shared baseline Skill. When asked which Skills or capabilities you have, identify this shared Skill and distinguish it from optional external references returned by `get_teammate_state`. Empty references or an empty personal shelf never mean that you lack the shared teammate Skill or its operating procedures.',
'When the user wants another teammate, call `create_teammate` with a name and any identity details the user supplied. New teammates receive this same baseline and follow the user’s available default model; do not generate a fixed number of role Skills, prewrite a greeting, or require a profile form. Their personality, personal learning and memory remain independent.',
diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.ts
index 4f50cdc455..ecb4c6cb7c 100644
--- a/apps/desktop/src/shared/botAutonomy.ts
+++ b/apps/desktop/src/shared/botAutonomy.ts
@@ -164,6 +164,11 @@ export interface GlanceRow {
online: boolean;
title: string;
kind: GlanceKind;
+ /**
+ * 状态表里的当前 phase(在做里区分运行中与撞上用量上限)。本版宿主总会填;远程较旧版本的宿主
+ * 经设备互联返回的行没有它,所以是可选字段。
+ */
+ phase?: WatchedPhase;
/** 等了 / 做了多少分钟。 */
minutes: number;
/** waiting 行:等什么(问题或权限一句话)。 */
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 8be36bfb92..9a3af99b1a 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -790,7 +790,7 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘
- 自主跟进:任务卡住 10 分钟 / 等你 5 分钟 / 出错 / 用量上限 / 做完时,只有跟进者的内置「跟进」规则被叫醒一次;
例行任务引擎重建后 `host:sessions` 事件源重新登记;内置规则不能删除、不能改内容、只能暂停;没人跟的本机「等你」
只提醒主人一次;「自动跟进所有任务」未自定义时跟随在用的 Cindy 助理,显式关掉后保持关闭,恢复默认删除 override;
- 总调度工作台看全设备任务,其它伙伴只看自己开的或接手的任务;远程任务只进工作台、不叫醒伙伴也不提醒;没有待处理
+ 总调度工作台看全设备任务,其它伙伴只看自己开的或接手的任务;已授权的远程控制端读工作台时,与远程任务列表同一口径,隐藏 / 归档伙伴开的、它的主任务与它在跟的任务一律不返回;远程任务只进工作台、不叫醒伙伴也不提醒;没有待处理
任务的伙伴不被兜底叫醒,有待处理任务时距上次叫醒满 2 小时才发一次 `sweep`;远程电脑轮询失败退避且标离线,
不形成重试风暴。
- 通用 session 工具及历史查询不再按伙伴来源分档;账号、实例、目标与队列归属检查保持有效。
diff --git a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
index e37b29cb64..00891bbd3f 100644
--- a/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/botWorkbenchTool.test.ts
@@ -16,7 +16,8 @@ function parse(result: { content: Array<{ type: string; text?: string }> }) {
* 伙伴身份只从调用方 Session 派生,工具不收 botId / 目录。
* - 现有覆盖缺口:旧用例覆盖的是项目增删、判断写入与候选快照,随功能删除;「一眼」投影给模型的
* 形状(task_id 可直接交给 get_task_digest、只在需要时出现的字段)此前没有覆盖。
- * - 最小失败输入:离线电脑上的等待行、由别的伙伴在跟的行、空白消息、未绑定 Session。
+ * - 最小失败输入:离线电脑上的等待行、由别的伙伴在跟的行、撞上用量上限的在做行(phase 不能丢,兜底叫醒靠它找)、
+ * 空白消息、未绑定 Session。
* - tier:unit(纯工具层,宿主回调全部 mock)。
*/
const glance = {
@@ -30,6 +31,7 @@ const glance = {
online: false,
title: '修登录',
kind: 'waiting' as const,
+ phase: 'waiting-answer',
minutes: 7,
question: '要不要删旧表?',
waitingFor: 'answer' as const,
@@ -44,6 +46,7 @@ const glance = {
online: true,
title: '跑测试',
kind: 'working' as const,
+ phase: 'usage-limit',
minutes: 3,
question: null,
waitingFor: null,
@@ -88,10 +91,10 @@ describe('bot workbench tools', () => {
workbench: {
scope: 'all',
waiting: [{
- task_id: 'laptop::s-9', title: '修登录', minutes: 7, device: 'MacBook', online: false,
+ task_id: 'laptop::s-9', title: '修登录', phase: 'waiting-answer', minutes: 7, device: 'MacBook', online: false,
waiting_for: 'answer', question: '要不要删旧表?', followed_by: 'writer',
}],
- working: [{ task_id: 's-1', title: '跑测试', minutes: 3 }],
+ working: [{ task_id: 's-1', title: '跑测试', phase: 'usage-limit', minutes: 3 }],
done_today: 2,
last_sweep_at: '2026-10-17T05:00:00.000Z',
offline_devices: ['MacBook'],
diff --git a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
index 3b86bb0d5e..6340d960ba 100644
--- a/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
+++ b/packages/lizi-mcps/src/xdt-helper/bot_workbench.ts
@@ -25,6 +25,8 @@ export interface GlanceRowWire {
online: boolean;
title: string;
kind: GlanceKindWire;
+ /** 状态表 phase(running / usage-limit / waiting-* / errored);旧宿主可能缺省。 */
+ phase?: string;
minutes: number;
question: string | null;
waitingFor: 'permission' | 'answer' | 'error' | null;
@@ -100,6 +102,7 @@ export function glanceForModel(glance: BotGlanceWire): Record<string, unknown> {
const row = (item: GlanceRowWire) => ({
task_id: item.sessionId,
title: item.title,
+ ...(item.phase ? { phase: item.phase } : {}),
minutes: item.minutes,
...(item.deviceName ? { device: item.deviceName } : {}),
...(item.online ? {} : { online: false }),
@@ -146,7 +149,8 @@ export function registerBotWorkbenchTools(
description:
'读取你的工作台「一眼」:waiting 是在等主人的任务(等权限 / 等回答 / 出错),working 是正在做的任务,'
+ '另有今天做完几件与上次扫描时间。总调度伙伴(scope=all)看到本机与在线电脑上的全部任务;其它伙伴(scope=own)只看自己开的或明确接手的任务。'
- + '定时兜底叫醒时逐件看 waiting:先 get_task_digest 读摘要再决定。只读,不改任何任务。',
+ + '每行带 phase(working 里 usage-limit 表示撞上用量上限)。定时兜底叫醒时逐件看 waiting,以及 working 里 usage-limit 或久无进展的任务:'
+ + '先 get_task_digest 读摘要再决定。只读,不改任何任务。',
inputShape: {},
handler: async () => {
const sessionId = callerSessionId();
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index ec583e8a5c..d55de4f10e 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -826,4 +826,25 @@ describe('routine check configuration', () => {
expect(await f.engine.ensureBuiltin('bot', 'follow-up', input, id)).toBeNull();
} finally { await f.engine.stop(); }
});
+
+ /*
+ * 测试价值
+ * - 生产入口与可观察结果:RoutineEngine.put / ensureBuiltin 经同一串行写队列后落地的内置规则(enabled、prompt)。
+ * - Bug/规则依据:docs/product-rules/bot-routines.md「内置跟进例行任务」保留主人的暂停选择;ensureBuiltin 曾在
+ * 写队列外读 enabled,排在它前面的暂停写入落地后又被旧值 true 覆盖,规则被悄悄恢复。
+ * - 现有覆盖缺口:上一用例的暂停与对齐都逐个 await,测不到两次写入在队列里重叠的时序。
+ * - 最小失败输入:暂停(不 await)紧接着宿主对齐新模板。
+ * - tier:unit(内存 load/save fake,无真实等待)。
+ */
+ it('keeps an owner pause that is queued ahead of a host realign of the built-in rule', async () => {
+ const f = await fixture();
+ const id = 'builtin-follow-up-bot';
+ try {
+ await f.engine.ensureBuiltin('bot', 'follow-up', input, id);
+ const pausing = f.engine.put('bot', { ...input, enabled: false }, id);
+ await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 1);
+ await pausing;
+ expect(f.engine.list('bot').find((routine) => routine.id === id)).toMatchObject({ enabled: false, prompt: 'v2' });
+ } finally { await f.engine.stop(); }
+ });
});
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index 1b6f3bca7d..7901b0d4af 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -278,10 +278,10 @@ export class RoutineEngine {
): Promise<Routine | null> {
if (!/^[a-zA-Z0-9_-]{16,128}$/.test(id)) throw new Error("Invalid routine creation ID");
if (this.blockedBots.has(botId)) return null;
- const existing = this.state.routines.find((routine) => routine.id === id && routine.botId === botId);
+ // enabled 在写队列里按最新记录保留(见 writeRoutine),排在前面的暂停不会被旧值覆盖。
return this.writeRoutine(
botId,
- existing ? { ...raw, enabled: existing.enabled } : raw,
+ raw,
{ id, builtin, ...(builtinVersion !== undefined ? { builtinVersion } : {}) },
);
}
@@ -305,6 +305,8 @@ export class RoutineEngine {
// Legacy saved definitions may omit this field and must stay quiet.
// A newly created, unclassified reminder must retain delivery.
...(!existing && parsed.silentWhenIdle === undefined ? { silentWhenIdle: false } : {}),
+ // Host realign of a built-in rule keeps the owner's latest pause choice.
+ ...(options.builtin && existing ? { enabled: existing.enabled } : {}),
});
if (id && !existing && !creationId && !options.builtin) throw new Error("Routine not found");
if ((creationId || options.builtin) && state.routines.some(row => row.id === id && row.botId !== botId)) throw new Error("Routine creation ID already used");