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): 伙伴自主跟进 review 修正——长工具不算卡住、停止不算做完、主任务不自唤醒、工作台页脚钉底

Chris059ca9bd617c
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 686f6581e2..8941ed568b 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -1629,6 +1629,18 @@ export class AgentIslandService {
return activity ? canonicalSessionActivity(activity) : null;
}
+ /**
+ * Whether a foreground tool call is between tool_use and tool_result. A long
+ * tool (e.g. a build) emits no activity until it returns; Bot follow-up uses
+ * this public boolean so a healthy long call is not judged stuck. Never
+ * exposes the tool name or arguments.
+ */
+ isToolCallInFlight(sessionId: string): boolean {
+ const session = this.state.sessions.get(sessionId);
+ return !!session && session.running && session.phase === 'running'
+ && (session.currentToolUseId !== null || session.workingTools.size > 0);
+ }
+
/**
* Subscribe to canonical activity transitions. Future Bot consumers attach here;
* this service remains unaware of Bot/runtime implementations.
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 5c0a2ff616..5336b447dc 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/autonomyRules.test.ts
@@ -8,6 +8,7 @@
* - 现有覆盖缺口:新模块,无既有覆盖;taskWatch / runtime 测试只走代表路径,不穷举跟进者矩阵与阈值边界。
* - 最小失败输入:creator 暂停且未允许代跟 → 必须 null(不是总调度);同一 (类型, phaseSince) 第二次判定
* 不再出现;第 7 次同类事件被截停;另一台电脑上的任务在这台电脑发了事件(两台电脑的同名伙伴各跟一遍);
+ * 一次 10 分钟以上的长构建(工具在途、没有活动事件)被判卡住;
* 非总调度伙伴看不到别人开的任务。
* - tier:unit(纯函数,无 IO、无计时器)。
*/
@@ -18,9 +19,10 @@ import {
DEFAULT_SCHEDULER_BOT_ID,
type WatchedSession,
} from '../../../shared/botAutonomy.js';
-import { AutonomyEventLedger } from '../events.js';
+import { AutonomyEventLedger, dueEventType } from '../events.js';
import { deriveFollowerBotId, resolveSchedulerBotId, type FollowerBotState } from '../follower.js';
import { projectBotGlance } from '../glance.js';
+import { summarizeInteraction } from '../phase.js';
const bot = (status: string, allowSchedulerFollow = false, shadowed = false): FollowerBotState => ({
status, allowSchedulerFollow, shadowed,
@@ -112,6 +114,16 @@ describe('autonomy event thresholds and loop guard', () => {
});
});
+describe('stuck while a tool call is in flight', () => {
+ it('waits for the longer in-tool threshold before calling a running task stuck', () => {
+ const t0 = 0;
+ const longBuild = row({ phase: 'running', phaseSince: t0, lastActivityAt: t0, toolInFlight: true });
+ expect(dueEventType(longBuild, t0 + AUTONOMY_THRESHOLDS.stuckAfterMs)).toBeNull();
+ expect(dueEventType(longBuild, t0 + AUTONOMY_THRESHOLDS.stuckInToolAfterMs)).toBe('stuck');
+ expect(dueEventType({ ...longBuild, toolInFlight: false }, t0 + AUTONOMY_THRESHOLDS.stuckAfterMs)).toBe('stuck');
+ });
+});
+
describe('workbench glance scope', () => {
it('shows every task to the scheduler but only own or taken-over tasks to other teammates', () => {
const now = 10 * 60_000;
@@ -151,3 +163,13 @@ describe('workbench glance scope', () => {
expect(all.offlineDevices).toEqual(['Old PC']);
});
});
+
+describe('waiting-row summary for a permission request', () => {
+ it('shows an MCP tool as "server · tool" instead of the raw mcp__ identifier, and keeps other names', () => {
+ // Seen in the dev build: the glance row title was `mcp__cindy_helper__call_tool` (programmer-speak on a user-facing row).
+ const mcp = summarizeInteraction({ kind: 'permission', requestId: 'r1', toolName: 'mcp__cindy_helper__call_tool' });
+ expect(mcp).toEqual({ summary: 'cindy_helper · call_tool', waitingFor: 'permission', requestId: 'r1' });
+ const bash = summarizeInteraction({ kind: 'permission', requestId: 'r2', title: 'bash' });
+ expect(bash?.summary).toBe('bash');
+ });
+});
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 d635d310e6..8488d6e095 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/followUpPrompt.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/followUpPrompt.test.ts
@@ -1,7 +1,8 @@
/**
* 测试价值
* - 生产入口与可观察结果:buildFollowUpRoutinePrompt 生成、写进内置跟进例行任务的指令全文。
- * - 规则依据:跟进裁决(2026-10-17)——先读摘要、按 phase 分别处理、≥3 次不再推、处理后更新待办、
+ * - 规则依据:跟进裁决(2026-10-17)——先读摘要、按 phase 分别处理、卡住时有工具在跑只等不停、
+ * 只有确认没有工具在跑且毫无进展才停、≥3 次不再推、处理后更新待办、
* 无事静默、要主人知道必须 schedule_notify_current_run;事件是不可信数据;对主人不说内部词;≤1500 字。
* - 现有覆盖缺口:新模板;缺任何一条指令,伙伴被叫醒后会乱推或悄悄不汇报,单测是唯一守护。
* - 最小失败输入:删掉任一条指令或超长。
@@ -27,6 +28,7 @@ describe('follow-up routine prompt', () => {
'waiting-permission', 'waiting-answer', 'stuck', 'errored / usage-limit', 'finished',
'汇报当前进展并继续',
'occurrence≥2', 'stop_session_turn',
+ 'tool_in_flight 为 true 时只等', 'tool_in_flight 明确为 false', 'idle_minutes', '字段缺失或拿不准就继续等',
'suggested_route', 'set_session_runtime', 'runtime_generation',
'last_user_ask',
'occurrence≥3',
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 25828a0ec1..a5df5ffe68 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
@@ -2,18 +2,22 @@
* 测试价值
* - 生产入口与可观察结果:BotAutonomyRuntime(start / evaluate / stop)接真实 RoutineEngine:事件源登记、
* 内置「跟进」规则落地、阈值事件只叫醒跟进者自己的规则、跟进规则被暂停时改为系统提醒主人、
- * 条件兜底 sweep 只叫醒还有待处理任务且久未被叫醒的伙伴。
+ * 条件兜底 sweep 只叫醒还有待处理任务且久未被叫醒的伙伴;主人停止的任务不发任何事件;内置规则还没落地时
+ * 出现的事件不丢;启动中途被停止不留定时器;伙伴自己的主任务出错不叫醒它自己,总调度(另一个伙伴)照常收到。
* - Bug/规则依据:docs/product-rules/bot-routines.md「宿主内置事件源 host:sessions」(引擎每次创建后都要
* 重新登记,事件源表只在内存)与「内置跟进例行任务」;cindy-bots-runtime.md §6.3「没人跟 → 系统提醒」
* 与「条件兜底」(没有待处理任务的伙伴不被白叫醒)。
* - 现有覆盖缺口:maker-scheduler 测试只覆盖引擎自身;autonomyRules / taskWatch 不经过引擎,测不到重建后
* 事件源丢失、followerBotId 过滤与 accepted=0 的提醒分支。
* - 最小失败输入:引擎重建后不重登记 → publish 抛 "not listening";waiting 事件叫醒了非跟进者;
- * 跟进规则暂停后主人收不到提醒或被重复提醒;没有待处理任务也被兜底叫醒,或每 30 秒扫描重复叫醒。
+ * 跟进规则暂停后主人收不到提醒或被重复提醒;没有待处理任务也被兜底叫醒,或每 30 秒扫描重复叫醒;
+ * 停止被当成做完叫醒伙伴;首次安装时事件赶在 ensure 之前发布、accepted=0 后永久丢失;伙伴主任务的欢迎轮出错
+ * 后宿主把 errored 发给它自己,排在正在失败的主任务后面打转。
* - tier:unit(真实引擎 + 内存 load/save;状态表 IO 为内存 fake;时间由 now() 推进)。
*/
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
import { RoutineEngine, type RoutineEngineDeps, type RoutineState } from '@cindy/maker-scheduler';
+import type { AutonomyEngine } from '../runtime.js';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -29,17 +33,26 @@ const log = { info: vi.fn(), warn: vi.fn(), debug: vi.fn() };
function meta(id: string): LocalSessionMeta {
return {
id, title: `title ${id}`, workingDir: null, status: 'active', hiddenAt: null, source: 'desktop',
- orcaRole: null, laneRole: null, interrupted: false, activeTurnStartedAt: null,
+ orcaRole: null, laneRole: null, laneBotId: null, interrupted: false, activeTurnStartedAt: null, lastTurnEndedAt: null,
};
}
-function waiting(sessionId: string): SessionActivitySnapshot {
+/** 灵动岛在交互到来时记下活动时刻 `at`。 */
+function waiting(sessionId: string, at = 1): SessionActivitySnapshot {
return {
- sessionId, phase: 'needs-interaction', interactionKind: 'ask_user_question', startedAtMs: 1, lastActivityAtMs: 1,
+ sessionId, phase: 'needs-interaction', interactionKind: 'ask_user_question', startedAtMs: 1, lastActivityAtMs: at,
currentActionSummary: null, attention: true, workflow: null, turnGeneration: 1, gracefulStopState: 'none', source: 'local',
} as unknown as SessionActivitySnapshot;
}
+function running(sessionId: string): SessionActivitySnapshot {
+ return { ...waiting(sessionId), phase: 'running', interactionKind: undefined, attention: false } as SessionActivitySnapshot;
+}
+
+function errored(sessionId: string): SessionActivitySnapshot {
+ return { ...waiting(sessionId), phase: 'error', interactionKind: undefined, lastActivityAtMs: 5 } as SessionActivitySnapshot;
+}
+
async function setup() {
let now = 1_000_000;
let saved: RoutineState | null = null;
@@ -55,12 +68,11 @@ async function setup() {
onError: () => {},
};
const bots = new Map([
- ['sched', { status: 'active', allowSchedulerFollow: false }],
- ['a', { status: 'active', allowSchedulerFollow: false }],
+ ['sched', { status: 'active', allowSchedulerFollow: false, canonicalSessionId: 'sched-main' }],
+ ['a', { status: 'active', allowSchedulerFollow: false, canonicalSessionId: 'a-main' }],
['paused-bot', { status: 'paused', allowSchedulerFollow: false }],
]);
- const runtime = async (engine: RoutineEngine) => {
- const instance = new BotAutonomyRuntime({
+ const create = (engine: AutonomyEngine) => new BotAutonomyRuntime({
engine,
now: () => now,
log,
@@ -73,6 +85,7 @@ async function setup() {
log,
onChange,
getActivitySnapshots: () => [],
+ isToolCallInFlight: () => false,
getPendingInteractions: () => [],
readLocalSessions: async (ids) => ids.map(meta),
readInterruptedSessions: async () => [],
@@ -82,6 +95,8 @@ async function setup() {
invokeRemote: async () => { throw new Error('unused'); },
}),
});
+ const runtime = async (engine: RoutineEngine) => {
+ const instance = create(engine);
await instance.start({ timers: false });
return instance;
};
@@ -90,7 +105,7 @@ async function setup() {
await created.start();
return created;
};
- return { runtime, engine, execute, remind, advance: (ms: number) => { now += ms; } };
+ return { runtime, create, engine, execute, remind, now: () => now, advance: (ms: number) => { now += ms; } };
}
describe('BotAutonomyRuntime with the routine engine', () => {
@@ -121,7 +136,7 @@ describe('BotAutonomyRuntime with the routine engine', () => {
const engine = await t.engine();
const runtime = await t.runtime(engine);
try {
- runtime.watch.applyActivity('t1', waiting('t1'));
+ runtime.watch.applyActivity('t1', waiting('t1', t.now()));
await runtime.watch.settled();
await runtime.evaluate();
expect(t.execute).not.toHaveBeenCalled();
@@ -138,7 +153,7 @@ describe('BotAutonomyRuntime with the routine engine', () => {
// 主人暂停了总调度的跟进规则:事件没人接 → 本机任务改为系统提醒,同一事件只提醒一次。
await engine.put('sched', { ...engine.list('sched')[0]!, enabled: false }, builtinFollowUpRoutineId('sched'));
- runtime.watch.applyActivity('t2', waiting('t2'));
+ runtime.watch.applyActivity('t2', waiting('t2', t.now()));
await runtime.watch.settled();
t.advance(AUTONOMY_THRESHOLDS.waitingAfterMs);
await runtime.evaluate();
@@ -164,7 +179,7 @@ describe('BotAutonomyRuntime with the routine engine', () => {
expect(t.execute).not.toHaveBeenCalled();
// 有一条等你的任务、且距启动(视为上次叫醒)已满间隔 → 发一条 sweep;30 秒扫描再来也不重复。
- runtime.watch.applyActivity('t1', waiting('t1'));
+ runtime.watch.applyActivity('t1', waiting('t1', t.now()));
await runtime.watch.settled();
await runtime.evaluateFallback();
await runtime.evaluateFallback();
@@ -192,4 +207,83 @@ describe('BotAutonomyRuntime with the routine engine', () => {
await engine.stop();
}
});
+
+ it('publishes nothing when the owner stops a running task', async () => {
+ const t = await setup();
+ const engine = await t.engine();
+ const runtime = await t.runtime(engine);
+ try {
+ runtime.watch.applyActivity('t1', running('t1'));
+ await runtime.watch.settled();
+ // 停止:灵动岛直接撤掉条目,没有完成态。
+ runtime.watch.applyActivity('t1', null);
+ await runtime.watch.settled();
+ await runtime.evaluate();
+ t.advance(AUTONOMY_THRESHOLDS.fallbackIntervalMs);
+ await runtime.sweep();
+ expect(t.execute).not.toHaveBeenCalled();
+ expect(t.remind).not.toHaveBeenCalled();
+ expect(runtime.glance('sched').doneToday).toBe(0);
+ } finally {
+ runtime.stop();
+ await engine.stop();
+ }
+ });
+
+ it('does not lose an event that arrives before the built-in rule is in place on first install', async () => {
+ const t = await setup();
+ const engine = await t.engine();
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ // 首次安装:内置规则写盘慢于第一条事件。
+ const slow: AutonomyEngine = {
+ registerSource: (source) => engine.registerSource(source),
+ publish: (...args) => engine.publish(...args),
+ ensureBuiltin: async (...args) => { await gate; return engine.ensureBuiltin(...args); },
+ };
+ const runtime = t.create(slow);
+ try {
+ const started = runtime.start({ timers: false });
+ runtime.watch.applyActivity('t1', errored('t1'));
+ await runtime.watch.settled();
+ const early = runtime.evaluate();
+ release();
+ await Promise.all([started, early]);
+ await vi.waitFor(() => expect(t.execute).toHaveBeenCalledTimes(1));
+ expect(t.execute.mock.calls[0]![1].events.map((e) => [e.event.type, e.event.subject])).toEqual([['errored', 't1']]);
+ } finally {
+ runtime.stop();
+ await engine.stop();
+ }
+ });
+
+ it("never wakes a teammate for its own main task, while the scheduler still follows another teammate's main task", async () => {
+ const t = await setup();
+ const engine = await t.engine();
+ const runtime = await t.runtime(engine);
+ try {
+ // 两件主任务的欢迎轮都出错:总调度自己的 sched-main,与伙伴 a 的 a-main。
+ runtime.watch.applyActivity('sched-main', errored('sched-main'));
+ runtime.watch.applyActivity('a-main', errored('a-main'));
+ await runtime.watch.settled();
+ await runtime.evaluate();
+ await vi.waitFor(() => expect(t.execute).toHaveBeenCalledTimes(1));
+ const [routine, run] = t.execute.mock.calls[0]!;
+ expect(routine.id).toBe(builtinFollowUpRoutineId('sched'));
+ expect(run.events.map((e) => [e.event.type, e.event.subject, e.event.data.followerBotId])).toEqual([
+ ['errored', 'a-main', 'sched'],
+ ]);
+ expect(runtime.watch.get('sched-main')).toMatchObject({ canonicalOfBotId: 'sched', followerBotId: null });
+ // 满兜底间隔:自己的主任务也不触发对自己的 sweep。
+ t.advance(AUTONOMY_THRESHOLDS.fallbackIntervalMs);
+ await runtime.evaluateFallback();
+ expect(t.execute.mock.calls.every(([, r]) => r.events.every((e) => e.event.subject !== 'sched-main'))).toBe(true);
+ // 工作台:自己的主任务不进自己的「等你 / 在做」;总调度仍能看到伙伴 a 的主任务。
+ expect(runtime.glance('sched').waiting.map((r) => r.sessionId)).toEqual(['a-main']);
+ expect(runtime.glance('a').waiting).toEqual([]);
+ } 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 b027822947..689e188816 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
@@ -3,15 +3,18 @@
* - 生产入口与可观察结果:TaskWatch(start / applyActivity / applyInputProjection / sweep)产出的状态表行:
* 哪些任务进表、处于什么状态、等你的那句话、谁在跟;远程电脑失败时的退避与离线标记。
* - Bug/规则依据:docs/product-rules/cindy-bots-runtime.md §6.3(观察范围:排除伙伴专线 / 隐藏 / Orca
- * worker;启动时已做完的任务不补发;远程电脑离线保留最后状态;轮询失败退避,不形成重试风暴)。
+ * worker;启动时已做完的任务不补发;只有观察到完成才算做完,主人停止的任务静默离表;长工具调用在途;
+ * 等你状态的时刻跨重启稳定;远程电脑离线保留最后状态;轮询失败退避,不形成重试风暴)。
* - 现有覆盖缺口:新模块;autonomyRules 只测纯判定,不经过活动订阅、读库与远程轮询的组合时序。
- * - 最小失败输入:伙伴主任务(canonical)出现在活动里;启动时灵动岛残留「完成」;远程 list-active 连续失败。
+ * - 最小失败输入:伙伴主任务(canonical)出现在活动里;启动时灵动岛残留「完成」;主人点停止后灵动岛条目消失
+ * 被当成做完;同一条挂起交互在重启后得到新的事件 id;远程 list-active 连续失败。
* - tier:unit(全部 IO 经注入的内存 fake,时间由 now() 推进,无真实等待)。
*/
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
import { describe, expect, it, vi } from 'vitest';
import { AUTONOMY_THRESHOLDS } from '../../../shared/botAutonomy.js';
+import { AutonomyEventLedger } from '../events.js';
import {
REMOTE_BACKOFF_MAX_MS,
TaskWatch,
@@ -23,7 +26,7 @@ import {
function meta(id: string, patch: Partial<LocalSessionMeta> = {}): LocalSessionMeta {
return {
id, title: `title ${id}`, workingDir: '/w', status: 'active', hiddenAt: null, source: 'desktop',
- orcaRole: null, laneRole: null, interrupted: false, activeTurnStartedAt: null, ...patch,
+ orcaRole: null, laneRole: null, laneBotId: null, interrupted: false, activeTurnStartedAt: null, lastTurnEndedAt: null, ...patch,
};
}
@@ -40,8 +43,10 @@ function harness(options: {
devices?: RemoteDeviceTarget[] | null;
invokeRemote?: TaskWatchDeps['invokeRemote'];
creators?: Record<string, string>;
+ now?: number;
} = {}) {
- let now = 10_000;
+ let now = options.now ?? 10_000;
+ const toolsInFlight = new Set<string>();
const metas = new Map((options.metas ?? []).map((m) => [m.id, m]));
const pending = new Map<string, unknown[]>();
const onChange = vi.fn();
@@ -50,6 +55,7 @@ function harness(options: {
now: () => now,
log: { info: vi.fn(), warn: vi.fn(), debug: vi.fn() },
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)!] : [])),
readInterruptedSessions: async () => [...metas.values()].filter((m) => m.interrupted),
@@ -64,7 +70,7 @@ function harness(options: {
onChange,
});
return {
- watch, metas, pending, onChange, invokeRemote,
+ watch, metas, pending, onChange, invokeRemote, toolsInFlight,
advance: (ms: number) => { now += ms; },
now: () => now,
};
@@ -74,9 +80,10 @@ describe('TaskWatch local observation', () => {
it('tracks user and teammate tasks, skips teammate lanes, and ignores a completion seen only at startup', async () => {
const h = harness({
metas: [
- meta('user'), meta('delegated'), meta('lane', { laneRole: 'canonical', source: 'bot' }),
+ meta('user'), meta('delegated'), meta('lane', { laneRole: 'history', laneBotId: 'a', source: 'bot' }),
+ meta('sched-main', { laneRole: 'canonical', laneBotId: 'sched', source: 'bot' }),
meta('hidden', { hiddenAt: 1 }), meta('worker', { orcaRole: 'worker' }), meta('stale-done'),
- meta('crashed', { interrupted: true, activeTurnStartedAt: 5_000 }),
+ meta('crashed', { interrupted: true, activeTurnStartedAt: 5_000 }), meta('stopped'),
],
snapshots: [activity('stale-done', 'completed')],
creators: { delegated: 'a' },
@@ -87,13 +94,29 @@ describe('TaskWatch local observation', () => {
['crashed', 'errored', 5_000, 'sched'],
]);
- for (const id of ['user', 'delegated', 'lane', 'hidden', 'worker']) h.watch.applyActivity(id, activity(id, 'running'));
+ for (const id of ['user', 'delegated', 'lane', 'hidden', 'worker', 'stopped', 'sched-main']) h.watch.applyActivity(id, activity(id, 'running'));
await h.watch.settled();
+ // 历史专线不进表;总调度自己的主任务(按 canonical 链接认出)进表但没有跟进者——不叫醒它自己。
expect(h.watch.list().map((r) => [r.sessionId, r.source, r.followerBotId]).sort()).toEqual([
['crashed', 'user', 'sched'],
['delegated', 'bot-task', 'a'],
+ ['sched-main', 'other', null],
+ ['stopped', 'user', 'sched'],
['user', 'user', 'sched'],
]);
+ expect(h.watch.get('sched-main')?.canonicalOfBotId).toBe('sched');
+
+ // 长工具调用在途:灵动岛知道 tool_use 还没回;每次扫描刷新这个布尔事实。
+ h.toolsInFlight.add('stopped');
+ await h.watch.sweep();
+ expect(h.watch.get('stopped')?.toolInFlight).toBe(true);
+ expect(h.watch.get('user')?.toolInFlight).toBe(false);
+
+ // 主人点了停止:灵动岛直接撤掉条目、没有完成态 → 静默离表,不算做完。
+ h.watch.applyActivity('stopped', null);
+ await h.watch.settled();
+ expect(h.watch.get('stopped')).toBeUndefined();
+ expect(h.watch.finished()).toEqual([]);
// 等权限:带一句话摘要与请求 id,不带工具入参。
h.pending.set('user', [{ kind: 'permission', requestId: 'req-9', toolName: 'Bash', input: { command: 'secret' } }]);
@@ -105,12 +128,27 @@ describe('TaskWatch local observation', () => {
expect(JSON.stringify(h.watch.get('user'))).not.toContain('secret');
expect(h.watch.get('delegated')?.phase).toBe('usage-limit');
- // 跑完后活动条目消失:算一次「做完」,计入今天做完。
+ // 观察到完成才算做完:完成态之后条目被已读清掉,行仍留到保留期满,只计一次。
+ h.watch.applyActivity('user', activity('user', 'completed', { lastActivityAtMs: 9_000 }));
+ await h.watch.settled();
h.watch.applyActivity('user', null);
await h.watch.settled();
- expect(h.watch.get('user')?.phase).toBe('finished');
+ expect(h.watch.get('user')).toMatchObject({ phase: 'finished', phaseSince: 9_000 });
expect(h.watch.finished().map((f) => f.sessionId)).toEqual(['user']);
});
+
+ it('gives the same pending interaction the same event id after a restart', async () => {
+ const waitingSnapshot = activity('t', 'needs-interaction', { interactionKind: 'ask_user_question', lastActivityAtMs: 7_000 });
+ const ids: string[] = [];
+ // 第二个实例模拟重启后:时间已过去很久,灵动岛里还是同一条挂起交互。
+ for (const now of [10_000, 10_000 + 3 * AUTONOMY_THRESHOLDS.waitingAfterMs]) {
+ const h = harness({ metas: [meta('t')], snapshots: [waitingSnapshot], now });
+ await h.watch.start();
+ h.advance(AUTONOMY_THRESHOLDS.waitingAfterMs);
+ ids.push(...new AutonomyEventLedger().evaluate(h.watch.list(), h.now()).due.map((c) => c.id));
+ }
+ expect(ids).toEqual(['waiting:t:7000', 'waiting:t:7000']);
+ });
});
describe('TaskWatch remote polling', () => {
diff --git a/apps/desktop/src/main/bot-autonomy/botsChangedSignal.ts b/apps/desktop/src/main/bot-autonomy/botsChangedSignal.ts
new file mode 100644
index 0000000000..796dc6d3ad
--- /dev/null
+++ b/apps/desktop/src/main/bot-autonomy/botsChangedSignal.ts
@@ -0,0 +1,18 @@
+/**
+ * 伙伴资料 / 生命周期变化的零依赖信号:伙伴 IPC(bots.ts)与生命周期服务在广播时发,
+ * 观察层(service.ts)收到后立即重读归属与跟进者——「它开的任务也交给总调度跟」、新建 / 暂停 /
+ * 归档伙伴不必等 60 秒的定时重读。本文件不 import 任何模块,发送方不因此加载观察层依赖。
+ */
+let listener: (() => void) | null = null;
+
+export function setBotAutonomyBotsChangedListener(next: (() => void) | null): void {
+ listener = next;
+}
+
+export function signalBotAutonomyBotsChanged(): void {
+ try {
+ listener?.();
+ } catch {
+ // 观察层的失败不影响伙伴资料写入与广播。
+ }
+}
diff --git a/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts b/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts
index 0f960b35ad..4421ae731d 100644
--- a/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts
+++ b/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts
@@ -10,11 +10,17 @@
*/
import type { RoutineInput, RoutineTrigger } from '@cindy/maker-scheduler';
import { AUTONOMY_EVENT_TYPES, HOST_SESSIONS_SOURCE_ID } from '../../shared/botAutonomy.js';
-import { buildFollowUpRoutinePrompt } from './followUpPrompt.js';
+import { FOLLOW_UP_PROMPT_VERSION, buildFollowUpRoutinePrompt } from './followUpPrompt.js';
/** 内置规则的保存名;渲染层按 builtin 字段本地化显示,这里只是落盘值。 */
export const FOLLOW_UP_ROUTINE_NAME = '跟进任务';
+/**
+ * 模板版本:随规则落盘(`builtinVersion`)。ensure 时版本不同就重写这条内置规则(即使正文恰好相同),
+ * 指令措辞改动由 followUpPrompt.ts 的 FOLLOW_UP_PROMPT_VERSION 递增驱动。
+ */
+export const FOLLOW_UP_BUILTIN_VERSION = FOLLOW_UP_PROMPT_VERSION;
+
export function buildFollowUpRoutineInput(botId: string): RoutineInput {
const triggers: RoutineTrigger[] = AUTONOMY_EVENT_TYPES.map((type): RoutineTrigger => ({
id: `event-${type}`,
diff --git a/apps/desktop/src/main/bot-autonomy/events.ts b/apps/desktop/src/main/bot-autonomy/events.ts
index 4d59e44095..368fb2516f 100644
--- a/apps/desktop/src/main/bot-autonomy/events.ts
+++ b/apps/desktop/src/main/bot-autonomy/events.ts
@@ -62,8 +62,11 @@ export function dueEventType(row: WatchedSession, now: number): AutonomyEventTyp
// 另一台电脑上的任务由那台电脑上的伙伴跟:这里只进工作台,不发事件。
if (!row.online || row.deviceId !== null) return null;
switch (row.phase) {
- case 'running':
- return now - Math.max(row.lastActivityAt, row.phaseSince) >= AUTONOMY_THRESHOLDS.stuckAfterMs ? 'stuck' : null;
+ case 'running': {
+ // 前台工具调用在途(例如一次长构建)期间没有活动事件:用更长的阈值,不把健康的长调用当卡住。
+ const threshold = row.toolInFlight ? AUTONOMY_THRESHOLDS.stuckInToolAfterMs : AUTONOMY_THRESHOLDS.stuckAfterMs;
+ return now - Math.max(row.lastActivityAt, row.phaseSince) >= threshold ? 'stuck' : null;
+ }
case 'waiting-answer':
case 'waiting-permission':
return now - row.phaseSince >= AUTONOMY_THRESHOLDS.waitingAfterMs ? 'waiting' : null;
@@ -73,7 +76,8 @@ export function dueEventType(row: WatchedSession, now: number): AutonomyEventTyp
return 'usage-limit';
case 'finished':
// 自动化运行的任务有自己的结果通知,「做完」不再叫醒伙伴;卡住 / 等你 / 出错照常。
- return row.source === 'routine' ? null : 'finished';
+ // 伙伴主任务的一轮回复做完不是「任务做完」:否则别的伙伴每回一句话都会叫醒总调度。
+ return row.source === 'routine' || row.canonicalOfBotId ? null : 'finished';
default:
return null;
}
diff --git a/apps/desktop/src/main/bot-autonomy/followUpPrompt.ts b/apps/desktop/src/main/bot-autonomy/followUpPrompt.ts
index f9d9ac44b9..23ff7850ff 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 = 1;
+export const FOLLOW_UP_PROMPT_VERSION = 2;
export const FOLLOW_UP_PROMPT_MAX_CHARS = 1500;
@@ -17,7 +17,8 @@ export function buildFollowUpRoutinePrompt(botId: string): string {
'2. 按 phase 处理:',
'- waiting-permission:权限只能主人批(工作台上有「允许」),你不能代批;用 schedule_notify_current_run 提醒主人等批什么,并用 update_teammate_todo 记一条待办。',
'- waiting-answer:答案能从任务上下文确定就代答;不能确定就提醒主人。',
- '- stuck:用 continue_workbench_task 发「汇报当前进展并继续」;同一任务再次卡住(occurrence≥2)就用 stop_session_turn 停下(仅本机任务)并提醒主人。',
+ '- stuck:长时间构建、测试也会像卡住。tool_in_flight 为 true 时只等,不推也不停。否则用 continue_workbench_task 发一次「汇报当前进展并继续」,只推这一次。',
+ ' 再次卡住(occurrence≥2)时,只有 tool_in_flight 明确为 false、且摘要显示上次提醒后毫无进展(idle_minutes 一直在涨、last_assistant_line 还是上次那句),才用 stop_session_turn 停下(仅本机任务)并提醒主人;字段缺失或拿不准就继续等,不要停。',
'- errored / usage-limit:摘要里有 suggested_route 就用 set_session_runtime 换过去(expected_generation 填 runtime_generation),再 continue_workbench_task 让它继续;没有就提醒主人。',
'- finished:对照 last_user_ask 核对结果,有问题就继续跟进;只有主人会关心的结果才汇报。',
'- 别的伙伴开的任务默认由它自己跟进:continue_workbench_task 返回 TASK_FOLLOWED_BY_OTHER_BOT 时只读不推;确需你接手才告诉主人,可在那位伙伴的设置里打开「它开的任务也交给你跟进」。',
diff --git a/apps/desktop/src/main/bot-autonomy/follower.ts b/apps/desktop/src/main/bot-autonomy/follower.ts
index 32a15b8f9a..94510b4beb 100644
--- a/apps/desktop/src/main/bot-autonomy/follower.ts
+++ b/apps/desktop/src/main/bot-autonomy/follower.ts
@@ -15,6 +15,8 @@ export interface FollowerBotState {
allowSchedulerFollow: boolean;
/** 云端伙伴的主力电脑在别处:本机不运行它的例行任务,视为本机不可用。 */
shadowed?: boolean;
+ /** 资料上登记的主任务 id(bot_profiles.canonical_session_id)。 */
+ canonicalSessionId?: string | null;
}
export type FollowerBotDirectory = ReadonlyMap<string, FollowerBotState>;
diff --git a/apps/desktop/src/main/bot-autonomy/glance.ts b/apps/desktop/src/main/bot-autonomy/glance.ts
index 4e8f1f2fbe..cd419eebe4 100644
--- a/apps/desktop/src/main/bot-autonomy/glance.ts
+++ b/apps/desktop/src/main/bot-autonomy/glance.ts
@@ -47,6 +47,8 @@ export function projectBotGlance(input: GlanceInput): BotGlance {
const minutes = (since: number) => Math.max(0, Math.floor((input.now - since) / 60_000));
for (const row of input.rows) {
if (!inScope(row.sessionId, row.creatorBotId)) continue;
+ // 自己的主任务不进自己的工作台:看到自己在做事只是噪音。
+ if ((row.canonicalOfBotId ?? null) === input.botId) continue;
const base = {
sessionId: row.sessionId,
deviceId: row.deviceId,
diff --git a/apps/desktop/src/main/bot-autonomy/hostData.ts b/apps/desktop/src/main/bot-autonomy/hostData.ts
index a6308b7521..09f5dcf518 100644
--- a/apps/desktop/src/main/bot-autonomy/hostData.ts
+++ b/apps/desktop/src/main/bot-autonomy/hostData.ts
@@ -32,7 +32,7 @@ function toMeta(row: {
activeTurnStartedAt: number | null;
lastTurnEndedAt: number | null;
clearedAt: number | null;
-}, laneRole: string | null): LocalSessionMeta {
+}, lane: { role: string; botId: string } | null): LocalSessionMeta {
const started = row.activeTurnStartedAt;
return {
id: row.id,
@@ -42,9 +42,11 @@ function toMeta(row: {
hiddenAt: row.hiddenAt,
source: row.source,
orcaRole: row.orcaRole,
- laneRole,
+ laneRole: lane?.role ?? null,
+ laneBotId: lane?.botId ?? null,
interrupted: started !== null && started > (row.lastTurnEndedAt ?? 0) && started > (row.clearedAt ?? 0),
activeTurnStartedAt: started,
+ lastTurnEndedAt: row.lastTurnEndedAt,
};
}
@@ -61,15 +63,15 @@ const metaSelection = {
clearedAt: sessions.clearedAt,
};
-async function laneRoles(ids: readonly string[]): Promise<Map<string, string>> {
- const out = new Map<string, string>();
+async function laneRoles(ids: readonly string[]): Promise<Map<string, { role: string; botId: string }>> {
+ const out = new Map<string, { role: string; botId: string }>();
const db = getDbClient().drizzle;
for (let offset = 0; offset < ids.length; offset += SESSION_BATCH) {
const rows = await db
- .select({ sessionId: botSessionLinks.sessionId, role: botSessionLinks.role })
+ .select({ sessionId: botSessionLinks.sessionId, role: botSessionLinks.role, botId: botSessionLinks.botId })
.from(botSessionLinks)
.where(inArray(botSessionLinks.sessionId, ids.slice(offset, offset + SESSION_BATCH)));
- for (const row of rows) out.set(row.sessionId, row.role);
+ for (const row of rows) out.set(row.sessionId, { role: row.role, botId: row.botId });
}
return out;
}
@@ -109,7 +111,12 @@ export async function readInterruptedSessionMetas(sinceMs: number, limit: number
export async function readBotDirectory(): Promise<Map<string, FollowerBotState>> {
const db = getDbClient().drizzle;
const rows = await db
- .select({ id: botProfiles.id, status: botProfiles.status, capabilities: botProfileVersions.capabilitiesJson })
+ .select({
+ id: botProfiles.id,
+ status: botProfiles.status,
+ canonicalSessionId: botProfiles.canonicalSessionId,
+ capabilities: botProfileVersions.capabilitiesJson,
+ })
.from(botProfiles)
.leftJoin(
botProfileVersions,
@@ -121,6 +128,7 @@ export async function readBotDirectory(): Promise<Map<string, FollowerBotState>>
status: row.status,
allowSchedulerFollow: readAllowSchedulerFollow(row.capabilities),
shadowed: isCompanionShadowed(row.id),
+ canonicalSessionId: row.canonicalSessionId ?? null,
});
}
return out;
diff --git a/apps/desktop/src/main/bot-autonomy/phase.ts b/apps/desktop/src/main/bot-autonomy/phase.ts
index 154be915be..6c6356c01a 100644
--- a/apps/desktop/src/main/bot-autonomy/phase.ts
+++ b/apps/desktop/src/main/bot-autonomy/phase.ts
@@ -66,15 +66,6 @@ export function nextPhaseSince(
return candidate;
}
-/**
- * 「做完」:曾在跑(或等交互)的任务进入 finished,或直接回到空闲(例如主人正看着任务,
- * 完成态没有停留就被已读清掉)。
- */
-export function isFinishTransition(previous: WatchedPhase | null, next: WatchedPhase): boolean {
- if (next === 'finished') return previous !== 'finished';
- return next === 'idle' && (previous === 'running' || previous === 'waiting-answer' || previous === 'waiting-permission');
-}
-
export function truncateSummary(text: string, max = SUMMARY_MAX_CHARS): string {
const compact = text.replace(/\s+/gu, ' ').trim();
const chars = Array.from(compact);
@@ -89,6 +80,12 @@ function text(value: unknown): string | null {
return typeof value === 'string' && value.trim() ? value : null;
}
+/** `mcp__<server>__<tool>` 这种原始工具名在「等你」里太像代码,改成「server · tool」;其它名字原样。 */
+function readableToolName(name: string): string {
+ const match = /^mcp__(.+?)__(.+)$/u.exec(name.trim());
+ return match ? `${match[1]} · ${match[2]}` : name;
+}
+
/**
* 挂起交互 → 一句摘要(≤140 字,可能为 null)。只取问题本身或权限名,不带工具入参、计划正文
* 与代输入内容:代输入卡的填写值永远只交给宿主(docs/product-rules/input-handoff.md)。
@@ -107,7 +104,7 @@ export function summarizeInteraction(raw: unknown): InteractionSummary | null {
const kind = text(request.kind);
if (kind === 'permission') {
const name = text(request.title) ?? text(request.displayName) ?? text(request.toolName);
- return { summary: name ? truncateSummary(name) : null, waitingFor: 'permission', requestId: text(request.requestId) };
+ return { summary: name ? truncateSummary(readableToolName(name)) : null, waitingFor: 'permission', requestId: text(request.requestId) };
}
if (kind === 'ask_user_question') {
const questions = Array.isArray(request.questions) ? request.questions : [];
diff --git a/apps/desktop/src/main/bot-autonomy/runtime.ts b/apps/desktop/src/main/bot-autonomy/runtime.ts
index 5d7fe87ba3..e090c8d27a 100644
--- a/apps/desktop/src/main/bot-autonomy/runtime.ts
+++ b/apps/desktop/src/main/bot-autonomy/runtime.ts
@@ -20,7 +20,7 @@ import {
type BotGlance,
type WatchedSession,
} from '../../shared/botAutonomy.js';
-import { buildFollowUpRoutineInput } from './builtinRoutine.js';
+import { FOLLOW_UP_BUILTIN_VERSION, buildFollowUpRoutineInput } from './builtinRoutine.js';
import {
AutonomyEventLedger,
hostSessionsSource,
@@ -65,7 +65,8 @@ export class BotAutonomyRuntime {
private readonly inflight = new Set<string>();
private readonly reminded = new Map<string, number>();
private readonly ensured = new Set<string>();
- private readonly ensuring = new Set<string>();
+ /** 正在对齐的内置规则:并发的 ensure 与发布共用同一次写入。 */
+ private readonly ensuring = new Map<string, Promise<void>>();
/** 伙伴上次被叫醒(任一事件被它的规则接收)的时刻;启动时视为刚叫醒过,避免重启后一起白跑。 */
private readonly lastWokenAt = new Map<string, number>();
private readonly sweptIds = new Set<string>();
@@ -93,6 +94,8 @@ export class BotAutonomyRuntime {
await this.ensureBuiltins();
await this.evaluate();
this.schedulePush();
+ // start 期间可能已被停止(换账号 / 引擎重建):不再起定时器,免得泄漏。
+ if (this.stopped) return;
if (options.timers !== false) {
this.sweepTimer = setInterval(() => { void this.sweep(); }, SWEEP_INTERVAL_MS);
this.sweepTimer.unref?.();
@@ -192,23 +195,42 @@ export class BotAutonomyRuntime {
}
}
- private async ensureOne(botId: string): Promise<void> {
- if (this.stopped || this.ensuring.has(botId) || !this.deps.isCurrent()) return;
+ private ensureOne(botId: string): Promise<void> {
+ if (this.stopped || !this.deps.isCurrent()) return Promise.resolve();
+ const inflight = this.ensuring.get(botId);
+ if (inflight) return inflight;
const id = builtinFollowUpRoutineId(botId);
if (!ROUTINE_ID_PATTERN.test(id)) {
this.ensured.add(botId);
this.deps.log.warn('builtin routine skipped: unsupported teammate id');
- return;
- }
- this.ensuring.add(botId);
- try {
- await this.deps.engine.ensureBuiltin(botId, 'follow-up', buildFollowUpRoutineInput(botId), id);
- if (!this.stopped) this.ensured.add(botId);
- } catch (error) {
- this.deps.log.warn('builtin routine ensure failed', { error: errorCode(error) });
- } finally {
- this.ensuring.delete(botId);
+ return Promise.resolve();
}
+ const run = (async () => {
+ try {
+ await this.deps.engine.ensureBuiltin(
+ botId,
+ 'follow-up',
+ buildFollowUpRoutineInput(botId),
+ id,
+ FOLLOW_UP_BUILTIN_VERSION,
+ );
+ if (!this.stopped) this.ensured.add(botId);
+ } catch (error) {
+ this.deps.log.warn('builtin routine ensure failed', { error: errorCode(error) });
+ } finally {
+ this.ensuring.delete(botId);
+ }
+ })();
+ this.ensuring.set(botId, run);
+ return run;
+ }
+
+ /**
+ * 发布前先确保跟进者的内置规则已落地:首次安装或新伙伴时,事件若赶在 ensure 之前发布,
+ * 引擎会记下回执却没有规则接收(accepted=0),这次事件就永久丢了。
+ */
+ private async ensureFollower(botId: string): Promise<void> {
+ if (!this.ensured.has(botId)) await this.ensureOne(botId);
}
/** 判定并发布阈值事件。可重入:同一事件 id 在途时不重复处理。 */
@@ -238,6 +260,8 @@ export class BotAutonomyRuntime {
this.remindOwner(candidate, now);
return;
}
+ await this.ensureFollower(candidate.row.followerBotId);
+ if (this.stopped) return;
let accepted: number;
try {
const result = await this.deps.engine.publish(
@@ -283,6 +307,8 @@ export class BotAutonomyRuntime {
if (now - last < AUTONOMY_THRESHOLDS.fallbackIntervalMs) continue;
const id = sweepEventId(botId, now);
if (this.sweptIds.has(id)) continue;
+ await this.ensureFollower(botId);
+ if (this.stopped) return;
try {
const result = await this.deps.engine.publish(
HOST_SESSIONS_SOURCE_ID,
diff --git a/apps/desktop/src/main/bot-autonomy/service.ts b/apps/desktop/src/main/bot-autonomy/service.ts
index f1e7dba5d3..63ab320bbd 100644
--- a/apps/desktop/src/main/bot-autonomy/service.ts
+++ b/apps/desktop/src/main/bot-autonomy/service.ts
@@ -34,14 +34,29 @@ import {
scopeIsCurrent,
setActiveBotAutonomy,
} from './hub.js';
+import { setBotAutonomyBotsChangedListener } from './botsChangedSignal.js';
import { BotAutonomyRuntime } from './runtime.js';
import { TaskWatch, errorCode } from './taskWatch.js';
export { configureBotAutonomyHost } from './hub.js';
const log = createLogger('bot-autonomy');
+/** 伙伴资料 / 生命周期变化合并后再重读归属(同一次保存常连发几条广播)。 */
+const BOTS_CHANGED_DEBOUNCE_MS = 300;
let initialized = false;
+let botsChangedTimer: ReturnType<typeof setTimeout> | null = null;
+
+function onBotsChanged(): void {
+ if (botsChangedTimer) return;
+ botsChangedTimer = setTimeout(() => {
+ botsChangedTimer = null;
+ const active = getActiveBotAutonomy();
+ if (!active || !scopeIsCurrent(active.scope)) return;
+ active.runtime.refreshFollowers().catch((error) => log.warn('autonomy follower refresh failed', { error: errorCode(error) }));
+ }, BOTS_CHANGED_DEBOUNCE_MS);
+ botsChangedTimer.unref?.();
+}
function assertScope(scope: string): void {
if (!scopeIsCurrent(scope)) throw Object.assign(new Error('owner changed'), { code: 'OWNER_CHANGED' });
@@ -51,6 +66,7 @@ function assertScope(scope: string): void {
export function initBotAutonomy(): void {
if (initialized) return;
initialized = true;
+ setBotAutonomyBotsChangedListener(onBotsChanged);
onRoutineEngineLifecycle({
started: (engine, scope) => startRuntime(engine, scope),
stopped: (engine) => {
@@ -86,6 +102,7 @@ function startRuntime(engine: RoutineEngine, scope: string): void {
log,
onChange,
getActivitySnapshots: () => getAgentIslandService()?.getSessionActivitySnapshots() ?? [],
+ isToolCallInFlight: (sessionId) => getAgentIslandService()?.isToolCallInFlight(sessionId) ?? false,
getPendingInteractions: (sessionId) => {
try {
return getBotAutonomyHostDeps().getPendingInteractions?.(sessionId) ?? [];
diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
index 61d639b3a4..d47182dc53 100644
--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts
+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
@@ -29,7 +29,6 @@ import type { FinishedRecord } from './glance.js';
import {
deriveLocalPhase,
deriveRemotePhase,
- isFinishTransition,
nextPhaseSince,
summarizeInteraction,
truncateSummary,
@@ -54,8 +53,11 @@ const MISSING_META_RETRY_MS = 60_000;
const REMOTE_READ_BATCH = 50;
const USER_SOURCES = new Set(['desktop', 'feishu', 'slack', 'telegram', 'x', 'discord', 'wechat', 'dingtalk', 'wecom', 'shared']);
-/** 伙伴自己的专线(主任务 / 历史 / 群 / IM 渠道)不是「任务」,不进表。 */
-const BOT_LANE_ROLES = new Set(['canonical', 'history', 'group', 'channel']);
+/**
+ * 伙伴的历史 / 群 / IM 渠道专线不是「任务」,不进表。主任务(canonical)进表:总调度是另一个伙伴时要能
+ * 发现它坏了;但它永远不是主任务所属伙伴自己的事件对象(见 followerFor),也不进它自己的工作台。
+ */
+const BOT_LANE_ROLES = new Set(['history', 'group', 'channel']);
export interface LocalSessionMeta {
id: string;
@@ -67,9 +69,13 @@ export interface LocalSessionMeta {
orcaRole: string | null;
/** bot_session_links.role(无链接为 null)。 */
laneRole: string | null;
+ /** bot_session_links.bot_id(无链接为 null)。 */
+ laneBotId: string | null;
/** 上一轮没有正常收尾(startedAt > endedAt)。只在新鲜读库时有意义。 */
interrupted: boolean;
activeTurnStartedAt: number | null;
+ /** 上一轮收尾时刻(库里的 last_turn_ended_at);跨重启稳定,用作出错状态的时刻。 */
+ lastTurnEndedAt: number | null;
}
export interface OwnershipSnapshot {
@@ -98,6 +104,8 @@ export interface TaskWatchDeps {
now(): number;
log: TaskWatchLogger;
getActivitySnapshots(): readonly SessionActivitySnapshot[];
+ /** 本机任务是否有前台工具调用在途(tool_use 已发、tool_result 未回);只是布尔事实。 */
+ isToolCallInFlight(sessionId: string): boolean;
getPendingInteractions(sessionId: string): readonly unknown[];
readLocalSessions(ids: readonly string[]): Promise<LocalSessionMeta[]>;
readInterruptedSessions(sinceMs: number, limit: number): Promise<LocalSessionMeta[]>;
@@ -154,6 +162,8 @@ export class TaskWatch {
private readonly pending = new Set<string>();
private flushing: Promise<void> | null = null;
private ownership: OwnershipSnapshot = EMPTY_OWNERSHIP;
+ /** 主任务 id → 所属伙伴(来自伙伴资料 canonical_session_id)。 */
+ private canonicalOwners = new Map<string, string>();
private ownershipAt = 0;
private ownershipRefresh: Promise<void> | null = null;
private schedulerBotId: string | null = null;
@@ -313,7 +323,7 @@ export class TaskWatch {
}
const facts = this.factsFor(sessionId);
const activity = facts.activity;
- let phase: WatchedPhase = deriveLocalPhase({
+ const phase: WatchedPhase = deriveLocalPhase({
activityPhase: activity?.phase ?? null,
interactionKind: activity?.interactionKind ?? null,
inputError: !!facts.inputError,
@@ -325,10 +335,9 @@ export class TaskWatch {
if (phase === 'idle') {
if (previous && this.interrupted.has(sessionId)) return { changed: false, unowned: false };
if (previous?.phase === 'finished') return { changed: false, unowned: false };
- if (!previous || !isFinishTransition(previous.phase, 'idle')) {
- return { changed: this.rows.delete(sessionId), unowned: false };
- }
- phase = 'finished';
+ // 回到空闲但没观察到完成(主人点了停止 / 中止:灵动岛直接撤掉条目,不留完成卡):
+ // 不是「做完」,静默离表——不发事件、不计入今天做完,免得伙伴把主人刚停下的事又推起来。
+ return { changed: this.rows.delete(sessionId), unowned: false };
}
let phaseSince: number;
if (phase === 'running') {
@@ -336,7 +345,14 @@ export class TaskWatch {
} else if (phase === 'finished') {
phaseSince = nextPhaseSince(previous, phase, activity?.phase === 'completed' ? activity.lastActivityAtMs ?? now : now);
} else if (phase === 'errored') {
- phaseSince = nextPhaseSince(previous, phase, activity?.phase === 'error' ? activity.lastActivityAtMs ?? now : now);
+ // 时刻尽量取跨重启稳定的来源(灵动岛终态时刻,否则库里的上一轮收尾时刻),重启后同一次出错是同一个事件 id。
+ const terminal = activity?.phase === 'error' || activity?.phase === 'completed';
+ const ended = meta.lastTurnEndedAt;
+ const endedFresh = ended !== null && ended <= now && (previous?.startedAt == null || ended >= previous.startedAt);
+ phaseSince = nextPhaseSince(previous, phase, terminal ? activity?.lastActivityAtMs ?? now : endedFresh ? ended : now);
+ } else if (phase === 'waiting-answer' || phase === 'waiting-permission') {
+ // 进入等交互时灵动岛会记下活动时刻;等待期间没有新活动,重启后同一条挂起交互仍是同一个时刻。
+ phaseSince = nextPhaseSince(previous, phase, activity?.phase === 'needs-interaction' ? activity.lastActivityAtMs ?? now : now);
} else {
phaseSince = nextPhaseSince(previous, phase, now);
}
@@ -348,7 +364,8 @@ export class TaskWatch {
pendingQuestion = summary?.summary ?? (keep ? previous.pendingQuestion : null);
pendingRequestId = summary?.requestId ?? (keep ? previous.pendingRequestId ?? null : null);
}
- const creatorBotId = this.ownership.creatorBySession.get(sessionId) ?? null;
+ const canonicalOfBotId = this.canonicalOwner(sessionId, meta);
+ const creatorBotId = this.creatorOf(sessionId, canonicalOfBotId);
const row: WatchedSession = {
sessionId,
deviceId: null,
@@ -362,8 +379,10 @@ export class TaskWatch {
startedAt: activity?.startedAtMs ?? previous?.startedAt ?? null,
pendingQuestion,
pendingRequestId,
+ toolInFlight: phase === 'running' && this.deps.isToolCallInFlight(sessionId),
error: phase === 'errored' && facts.inputError ? truncateSummary(facts.inputError) : null,
creatorBotId,
+ canonicalOfBotId,
followerBotId: null,
source: localSource(meta, creatorBotId),
};
@@ -374,6 +393,8 @@ export class TaskWatch {
}
private recordFinished(row: WatchedSession, now: number): void {
+ // 伙伴主任务的一轮回复不计入「今天做完」。
+ if (row.canonicalOfBotId) return;
this.finishedLog.push({ sessionId: row.sessionId, creatorBotId: row.creatorBotId, at: now });
// 只为「今天做完 N 件」留两天的记录。
const cutoff = now - 2 * 24 * 60 * 60_000;
@@ -393,7 +414,8 @@ export class TaskWatch {
this.meta.set(meta.id, meta);
if (!this.isWatchable(meta) || !meta.interrupted || this.rows.has(meta.id) || this.local.get(meta.id)?.activity) continue;
const since = meta.activeTurnStartedAt ?? now;
- const creatorBotId = this.ownership.creatorBySession.get(meta.id) ?? null;
+ const canonicalOfBotId = this.canonicalOwner(meta.id, meta);
+ const creatorBotId = this.creatorOf(meta.id, canonicalOfBotId);
const row: WatchedSession = {
sessionId: meta.id,
deviceId: null,
@@ -408,6 +430,7 @@ export class TaskWatch {
pendingQuestion: null,
error: null,
creatorBotId,
+ canonicalOfBotId,
followerBotId: null,
source: localSource(meta, creatorBotId),
};
@@ -417,15 +440,31 @@ export class TaskWatch {
}
}
- private followerFor(row: Pick<WatchedSession, 'creatorBotId' | 'deviceId'>): string | null {
+ private followerFor(row: Pick<WatchedSession, 'creatorBotId' | 'deviceId' | 'canonicalOfBotId'>): string | null {
// 每台电脑上的任务由那台电脑上的伙伴跟:两台电脑上的同名伙伴(如各自的 Cindy 助理)不会各跟一遍。
// 另一台电脑的行只进工作台给主人看与允许;总调度仍可经工具显式继续它。
if (row.deviceId !== null) return null;
- return deriveFollowerBotId({
+ const follower = deriveFollowerBotId({
creatorBotId: row.creatorBotId,
schedulerBotId: this.schedulerBotId,
bots: this.ownership.bots,
});
+ // 伙伴自己的主任务永远不是它自己的事件对象:自己叫醒自己只会排在正在失败的主任务后面打转。
+ // 总调度是另一个伙伴时照常跟(它能发现别的伙伴的主任务坏了)。
+ return follower !== null && follower === (row.canonicalOfBotId ?? null) ? null : follower;
+ }
+
+ /** 这件任务是哪个伙伴的主任务:资料登记的 canonical_session_id 优先,其次 bot_session_links 的 canonical 链接。 */
+ private canonicalOwner(sessionId: string, meta: LocalSessionMeta | undefined): string | null {
+ const registered = this.canonicalOwners.get(sessionId);
+ if (registered) return registered;
+ return meta?.laneRole === 'canonical' ? meta.laneBotId : null;
+ }
+
+ /** 主任务所属伙伴不算它的「开的任务」:不让它经 creator 路径跟自己,也不进它自己的工作台。 */
+ private creatorOf(sessionId: string, canonicalOfBotId: string | null): string | null {
+ const creator = this.ownership.creatorBySession.get(sessionId) ?? null;
+ return creator !== null && creator === canonicalOfBotId ? null : creator;
}
private async refreshOwnership(force = false): Promise<void> {
@@ -439,14 +478,19 @@ export class TaskWatch {
if (this.stopped) return;
this.ownership = next;
this.ownershipAt = this.deps.now();
+ this.canonicalOwners = new Map();
+ for (const [botId, bot] of next.bots) {
+ if (bot.canonicalSessionId) this.canonicalOwners.set(bot.canonicalSessionId, botId);
+ }
} catch (error) {
this.deps.log.warn('ownership read failed', { error: errorCode(error) });
}
this.schedulerBotId = resolveSchedulerBotId(this.readOverride(), this.ownership.bots);
for (const row of this.rows.values()) {
if (row.deviceId === null) {
- row.creatorBotId = this.ownership.creatorBySession.get(row.sessionId) ?? null;
const meta = this.meta.get(row.sessionId);
+ row.canonicalOfBotId = this.canonicalOwner(row.sessionId, meta);
+ row.creatorBotId = this.creatorOf(row.sessionId, row.canonicalOfBotId);
if (meta) row.source = localSource(meta, row.creatorBotId);
}
row.followerBotId = this.followerFor(row);
@@ -484,6 +528,14 @@ export class TaskWatch {
for (const [id, facts] of this.local) {
if (!facts.activity && !facts.inputError && !facts.usageLimitWait && !this.rows.has(id)) this.local.delete(id);
}
+ // 查不到元数据的记录:过了重试间隔或已不在活动里就丢掉,避免无界增长(下次出现会重新查)。
+ for (const [id, at] of this.missingMeta) {
+ if (!this.local.has(id) || now - at >= MISSING_META_RETRY_MS) this.missingMeta.delete(id);
+ }
+ // 长工具调用期间没有活动事件:每次扫描刷新一次「工具在途」,stuck 判定据此放宽。
+ for (const row of this.rows.values()) {
+ if (row.deviceId === null) row.toolInFlight = row.phase === 'running' && this.deps.isToolCallInFlight(row.sessionId);
+ }
if (this.meta.size > 2_000) {
for (const id of this.meta.keys()) if (!this.rows.has(id) && !this.local.has(id)) this.meta.delete(id);
}
@@ -696,19 +748,12 @@ export class TaskWatch {
if (phase === 'finished' && previous?.phase !== 'finished') this.recordFinished(row, now);
this.rows.set(id, row);
}
- // 离开活动列表:之前在跑 / 等交互的算做完;做完的行留到保留期满。
+ // 离开活动列表:只有观察到完成(列表里出现过 completed)的行留到保留期满;其它(含被停止)静默离表,
+ // 不算「做完」。
for (const [id, row] of this.rows) {
if (row.deviceId !== deviceId || seen.has(id)) continue;
row.online = true;
- if (isFinishTransition(row.phase, 'idle')) {
- row.phase = 'finished';
- row.phaseSince = now;
- row.pendingQuestion = null;
- row.pendingRequestId = null;
- this.recordFinished(row, now);
- } else if (row.phase !== 'finished') {
- this.rows.delete(id);
- }
+ if (row.phase !== 'finished') this.rows.delete(id);
}
for (const remoteId of state.signals.keys()) {
if (!active.has(remoteId)) state.signals.delete(remoteId);
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index fe4544c89e..ee72638fea 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -48,6 +48,7 @@ import {
} from '../../maker-host/bot-model-chain-settings-store.js';
import { extractMessagePreview, sessionCreateToRow, sessionToCamel } from '../mapper.js';
import { normalizeBotToolCapabilities } from '../../../shared/botCapabilitySelection.js';
+import type { BotWorkbench } from '../../../shared/botWorkbench.js';
import {
botProfileContentChanged,
botProfileModelSelectionChanged,
@@ -219,6 +220,7 @@ import { buildDefaultBotIdentity } from '../../../shared/botProfileDefaults.js';
import { coordinateBotCanonicalReplacement } from '../../maker-ipc/botCanonicalReplacementCoordinator.js';
import { searchConversations } from '../conversationSearch.js';
import { registerBotAutonomyIpc } from '../../bot-autonomy/ipc.js';
+import { signalBotAutonomyBotsChanged } from '../../bot-autonomy/botsChangedSignal.js';
import {
BOT_FAILURE_REASONS,
isBotFailureAttentionWorthy,
@@ -1351,6 +1353,8 @@ export function broadcastBotProfileChanged(payload: {
change: 'created' | 'updated';
}): void {
broadcastBotRemoteResourceChanged(payload.botId);
+ // 伙伴自主跟进:新建伙伴、改「它开的任务也交给总调度跟」立即生效。
+ signalBotAutonomyBotsChanged();
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
try {
diff --git a/apps/desktop/src/main/maker-host/__tests__/botAutonomySettingsStore.test.ts b/apps/desktop/src/main/maker-host/__tests__/botAutonomySettingsStore.test.ts
index e5dd4d1346..b7cf0a4991 100644
--- a/apps/desktop/src/main/maker-host/__tests__/botAutonomySettingsStore.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/botAutonomySettingsStore.test.ts
@@ -7,7 +7,8 @@
* cindy-bots-runtime.md §6.3「总调度唯一,默认 Cindy 助理」。
* - 现有覆盖缺口:overrideSettingsFile.test 只测通用文件层,不测 null 作为有意义的 override(关掉总调度)
* 与「未自定义」的区分。
- * - 最小失败输入:写 null 后若不落盘(preserveDefaults 缺失),重新读会回到默认 Cindy 助理。
+ * - 最小失败输入:写 null 后若不落盘(preserveDefaults 缺失),重新读会回到默认 Cindy 助理;override 文件损坏时
+ * 回落默认,把主人关掉的总调度悄悄打开(必须失败关闭)。
* - tier:unit(临时目录真实文件,无计时器)。
*/
import fs from 'node:fs';
@@ -64,4 +65,16 @@ describe('bot autonomy scheduler setting', () => {
expect(readBotAutonomySettingsOverride({ rootPath }).customized).toBe(false);
expect(effective()).toBe(DEFAULT_SCHEDULER_BOT_ID);
});
+
+ it('fails closed when the override file exists but cannot be read, and reset recovers the default', async () => {
+ const file = path.join(rootPath, 'bot-autonomy-settings.json');
+ fs.writeFileSync(file, '{"schedulerBotId": nul');
+ expect(readBotAutonomySettingsOverride({ rootPath })).toEqual({ customized: true, schedulerBotId: null });
+ expect(effective()).toBeNull();
+ // 坏文件保留给主人检查;恢复默认删掉它,重新跟随默认。
+ expect(fs.readFileSync(file, 'utf8')).toBe('{"schedulerBotId": nul');
+ await resetBotAutonomySettings({ rootPath });
+ expect(fs.existsSync(file)).toBe(false);
+ expect(effective()).toBe(DEFAULT_SCHEDULER_BOT_ID);
+ });
});
diff --git a/apps/desktop/src/main/maker-host/bot-autonomy-settings-store.ts b/apps/desktop/src/main/maker-host/bot-autonomy-settings-store.ts
index 7cebb6756d..641be0ab40 100644
--- a/apps/desktop/src/main/maker-host/bot-autonomy-settings-store.ts
+++ b/apps/desktop/src/main/maker-host/bot-autonomy-settings-store.ts
@@ -9,6 +9,7 @@
* 文件:<owner userData>/bot-autonomy-settings.json,只有 `{ "schedulerBotId": ... }` 一个键。
*/
import { app } from 'electron';
+import fs from 'node:fs';
import path from 'node:path';
import type { BotAutonomySettings } from '../../shared/botAutonomy.js';
@@ -20,6 +21,8 @@ const log = desktopMakerLogger.child('bot-autonomy-settings-store');
/** 伙伴 id 的长度上限,与伙伴 IPC 校验一致。 */
const MAX_BOT_ID_LENGTH = 128;
+const MAX_FILE_BYTES = 4096;
+const FILE_NAME = 'bot-autonomy-settings.json';
function normalize(raw: unknown): BotAutonomySettings {
const value = raw && typeof raw === 'object' && !Array.isArray(raw)
@@ -32,20 +35,28 @@ function normalize(raw: unknown): BotAutonomySettings {
const stores = new Map<string, ReturnType<typeof createOverrideSettingsFile<BotAutonomySettings>>>();
+function ownerRootFor(rootPath?: string): string | null {
+ return rootPath ?? (getActiveAppSession().dataOwnerId ? ownerScopedUserDataPath() : null);
+}
+
+function settingsFilePath(ownerRoot: string | null): string {
+ return path.join(ownerRoot ?? app.getPath('userData'), FILE_NAME);
+}
+
function currentStore(rootPath?: string) {
- const ownerRoot = rootPath ?? (getActiveAppSession().dataOwnerId ? ownerScopedUserDataPath() : null);
+ const ownerRoot = ownerRootFor(rootPath);
const key = ownerRoot ?? '<global>';
let store = stores.get(key);
if (!store) {
store = createOverrideSettingsFile<BotAutonomySettings>({
- filePath: () => path.join(ownerRoot ?? app.getPath('userData'), 'bot-autonomy-settings.json'),
+ filePath: () => settingsFilePath(ownerRoot),
// 静态占位:未自定义时的有效值由调用方按伙伴列表派生,这里的 null 不代表「关掉」。
defaults: { schedulerBotId: null },
normalize,
log,
label: 'bot-autonomy',
scopeKey: rootPath ? () => `root:${rootPath}` : activeOwnerScopeKey,
- maxBytes: 4096,
+ maxBytes: MAX_FILE_BYTES,
preserveUnreadableFile: true,
});
stores.set(key, store);
@@ -59,16 +70,49 @@ export interface BotAutonomySettingsOverride {
schedulerBotId: string | null;
}
+/**
+ * 文件存在却读不出(坏 JSON、超限、根不是对象、无权限)。只在通用层报「未自定义」时复查:
+ * 通用层对坏文件回落默认值,而这里的默认是「交给 Cindy 助理」——主人关掉过总调度时会被悄悄打开。
+ */
+function existingFileUnreadable(file: string): boolean {
+ let size: number;
+ try {
+ size = fs.statSync(file).size;
+ } catch (error) {
+ return (error as NodeJS.ErrnoException | null)?.code !== 'ENOENT';
+ }
+ try {
+ if (size > MAX_FILE_BYTES) return true;
+ const parsed: unknown = JSON.parse(fs.readFileSync(file, 'utf8'));
+ return !parsed || typeof parsed !== 'object' || Array.isArray(parsed);
+ } catch {
+ return true;
+ }
+}
+
+let warnedUnreadableFile: string | null = null;
+
/** 只读 override;有效值(含默认派生)由观察层结合伙伴列表计算。 */
export function readBotAutonomySettingsOverride(options?: { rootPath?: string }): BotAutonomySettingsOverride {
const store = currentStore(options?.rootPath);
// 支持直接改文件即生效(Agent 按主人要求改本地配置)。
store.invalidateIfChanged();
const state: OverrideSettingsState<BotAutonomySettings> = store.readState();
- return {
- customized: state.customizedKeys.includes('schedulerBotId'),
- schedulerBotId: state.value.schedulerBotId,
- };
+ const customized = state.customizedKeys.includes('schedulerBotId');
+ if (!customized) {
+ const file = settingsFilePath(ownerRootFor(options?.rootPath));
+ // 失败关闭:override 文件在但读不出 → 当作主人关掉了总调度,不回落到默认的 Cindy 助理。
+ // 文件不存在才是「未自定义」。主人「恢复默认」会删掉坏文件。
+ if (existingFileUnreadable(file)) {
+ if (warnedUnreadableFile !== file) {
+ warnedUnreadableFile = file;
+ log.warn('bot autonomy settings unreadable; scheduler treated as off until reset');
+ }
+ return { customized: true, schedulerBotId: null };
+ }
+ }
+ if (warnedUnreadableFile !== null) warnedUnreadableFile = null;
+ return { customized, schedulerBotId: state.value.schedulerBotId };
}
/** 写 override:null 也落盘(表示主人关掉了总调度),与「未自定义」区分。 */
diff --git a/apps/desktop/src/main/maker-ipc/botLifecycleService.ts b/apps/desktop/src/main/maker-ipc/botLifecycleService.ts
index bc8ba2fcd2..169a1acdc9 100644
--- a/apps/desktop/src/main/maker-ipc/botLifecycleService.ts
+++ b/apps/desktop/src/main/maker-ipc/botLifecycleService.ts
@@ -24,6 +24,7 @@ import { MAKER_INVOKE, MAKER_PUSH } from './channels.js';
import type { BotDelegationService } from './botDelegationService.js';
import { resolveBotCanonicalSession } from './botCanonicalSessionRegistry.js';
import { broadcastBotRemoteResourceChanged } from './botRemoteResourceInvalidation.js';
+import { signalBotAutonomyBotsChanged } from '../bot-autonomy/botsChangedSignal.js';
import {
activeOwnerScopeKey,
isAppSessionBoundaryPending,
@@ -79,6 +80,8 @@ function broadcastBotLifecycleChanged(payload: {
botId: string;
action: BotLifecycleActionRequest['action'];
}): void {
+ // 伙伴自主跟进:暂停 / 恢复 / 归档后立即重算跟进者。
+ signalBotAutonomyBotsChanged();
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
try {
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts
index 1ba8fdb937..4a55f2d0d1 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/taskDigest.test.ts
@@ -4,7 +4,8 @@
* - 规则依据:摘要优先用观察层状态行(与工作台、事件同一口径),缺行时保守推断;子项失败不拖垮整份;
* 跨电脑不给换模型建议(set_session_runtime 只支持本机);离线电脑明确报 REMOTE_UNAVAILABLE。
* - 现有覆盖缺口:新模块。
- * - 最小失败输入:有 / 无观察层状态行的本机任务;PR 读取抛错;离线电脑;已删除任务。
+ * - 最小失败输入:有 / 无观察层状态行的本机任务;PR 读取抛错;离线电脑;已删除任务;状态行带 / 不带
+ * toolInFlight(不知道时摘要里不出现 tool_in_flight,伙伴不能把「没有字段」当成「没有工具在跑」)。
* - tier:unit(依赖全部注入,无数据库、Electron 与网络)。
*/
import { describe, expect, it, vi } from 'vitest';
@@ -48,7 +49,7 @@ describe('task digest assembly', () => {
expect(result).toEqual({
ok: true,
digest: {
- session_id: 'local-1', device: null, title: '修登录', phase: 'waiting-permission', elapsed_minutes: 9,
+ session_id: 'local-1', device: null, title: '修登录', phase: 'waiting-permission', elapsed_minutes: 9, idle_minutes: 9,
last_user_ask: '修登录', last_assistant_line: '要删旧表吗?', pending_question: null, error: null,
current_route: route, runtime_generation: 4,
suggested_route: { ...route, harness: 'claude-code', model: 'claude-opus-5-5' },
@@ -61,21 +62,29 @@ describe('task digest assembly', () => {
it('prefers the watcher row for phase, question, error and who follows', async () => {
const row = {
sessionId: 'local-1', deviceId: null, deviceName: null, online: true, title: '修登录(状态表)', workingDir: null,
- phase: 'usage-limit', phaseSince: NOW - 30 * 60_000, lastActivityAt: NOW, startedAt: null,
+ phase: 'usage-limit', phaseSince: NOW - 30 * 60_000, lastActivityAt: NOW - 25 * 60_000, startedAt: null,
pendingQuestion: null, error: '已达用量上限', creatorBotId: 'writer', followerBotId: 'writer', source: 'user',
} satisfies WatchedSession;
const result = await setup({ 'local-1': row }).read({ sessionId: 'local-1' });
expect(result).toMatchObject({
ok: true,
- digest: { title: '修登录(状态表)', phase: 'usage-limit', elapsed_minutes: 30, error: '已达用量上限', creator_bot_id: 'writer', follower_bot_id: 'writer' },
+ digest: { title: '修登录(状态表)', phase: 'usage-limit', elapsed_minutes: 30, idle_minutes: 25, error: '已达用量上限', creator_bot_id: 'writer', follower_bot_id: 'writer' },
});
+ // 只有本机且观察层给了这个事实才出现 tool_in_flight;另一台电脑的行缺省为 false 但并不可信,不给。
+ const busy = { ...row, phase: 'running' as const, toolInFlight: true };
+ const remoteIdle = { ...row, sessionId: 'laptop::s-1', phase: 'running' as const, toolInFlight: false };
+ const withFlag = setup({ 'local-1': busy, 'laptop::s-1': remoteIdle });
+ expect(await withFlag.read({ sessionId: 'local-1' })).toMatchObject({ ok: true, digest: { phase: 'running', tool_in_flight: true } });
+ expect(await withFlag.read({ sessionId: 'laptop::s-1' })).not.toHaveProperty('digest.tool_in_flight');
+ const { toolInFlight: _omitted, ...noFact } = busy;
+ expect(await setup({ 'local-1': noFact }).read({ sessionId: 'local-1' })).not.toHaveProperty('digest.tool_in_flight');
});
it('reads another computer without a route suggestion, and reports offline or missing tasks explicitly', async () => {
const { read } = setup();
expect(await read({ sessionId: 'laptop::s-1', callerSessionId: 'bot-main' })).toMatchObject({
ok: true,
- digest: { session_id: 'laptop::s-1', device: 'MacBook', phase: 'running', pr_status: 'PR o/r#3 open', suggested_route: null, runtime_generation: null, queued_count: null },
+ digest: { session_id: 'laptop::s-1', device: 'MacBook', phase: 'running', pr_status: 'PR o/r#3 open', suggested_route: null, runtime_generation: null, queued_count: null, idle_minutes: null },
});
expect(await read({ sessionId: 'offline::s-1' })).toMatchObject({ ok: false, errorCode: 'REMOTE_UNAVAILABLE' });
expect(await read({ sessionId: 'gone' })).toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });
diff --git a/apps/desktop/src/main/mcp-integrations/taskDigest.ts b/apps/desktop/src/main/mcp-integrations/taskDigest.ts
index ce0b34ab9d..f0e1904e7a 100644
--- a/apps/desktop/src/main/mcp-integrations/taskDigest.ts
+++ b/apps/desktop/src/main/mcp-integrations/taskDigest.ts
@@ -70,6 +70,15 @@ export function fallbackDigestPhase(activity: TaskDigestActivity | null): TaskDi
}
}
+/**
+ * 观察层是否看到有前台工具调用在途(长时间构建 / 测试时任务看起来像卡住)。观察层只对本机任务
+ * 掌握这个事实(另一台电脑的行缺省为 false,并不代表没有),所以只有本机且字段存在时才给出;
+ * 否则返回 undefined,摘要里不出现 tool_in_flight,伙伴按「不确定」处理。
+ */
+export function watchedToolInFlight(watched: WatchedSession | null, local: boolean): boolean | undefined {
+ return local && typeof watched?.toolInFlight === 'boolean' ? watched.toolInFlight : undefined;
+}
+
function minutesSince(now: number, since: number | null | undefined): number | null {
if (typeof since !== 'number' || !Number.isFinite(since) || since <= 0) return null;
return Math.max(0, Math.floor((now - since) / 60_000));
@@ -135,6 +144,7 @@ export function createTaskDigestReader(deps: TaskDigestDeps) {
ok: true,
digest: assemble({
key, now, watched, facts, activity, exchange, prStatus,
+ local: false,
device: watched?.deviceName ?? deviceName ?? deviceId,
queuedCount: null,
// 跨电脑换模型没有 expected_generation,set_session_runtime 只支持本机:不给建议。
@@ -160,6 +170,7 @@ export function createTaskDigestReader(deps: TaskDigestDeps) {
ok: true,
digest: assemble({
key, now, watched, facts, activity, exchange, prStatus, queuedCount, suggestedRoute,
+ local: true,
device: null,
runtimeGeneration: activity?.runtimeGeneration ?? null,
}),
@@ -178,10 +189,13 @@ function assemble(input: {
queuedCount: number | null;
suggestedRoute: TaskDigestRoute | null;
runtimeGeneration: number | null;
+ /** 本机任务;另一台电脑上的任务为 false。 */
+ local: boolean;
device: string | null;
}): TaskDigestWire {
const { watched, activity } = input;
const phase: TaskDigestPhase = watched?.phase ?? fallbackDigestPhase(activity);
+ const toolInFlight = watchedToolInFlight(watched, input.local);
const since = watched
? watched.phaseSince
: phase === 'running'
@@ -193,6 +207,7 @@ function assemble(input: {
title: watched?.title || input.facts.title,
phase,
elapsed_minutes: minutesSince(input.now, since),
+ idle_minutes: minutesSince(input.now, watched?.lastActivityAt ?? activity?.lastActivityAtMs),
last_user_ask: input.exchange.lastUserAsk,
last_assistant_line: input.exchange.lastAssistantLine,
pending_question: watched?.pendingQuestion ?? null,
@@ -204,6 +219,7 @@ function assemble(input: {
queued_count: input.queuedCount,
follower_bot_id: watched?.followerBotId ?? null,
creator_bot_id: watched?.creatorBotId ?? null,
+ ...(toolInFlight === undefined ? {} : { tool_in_flight: toolInFlight }),
};
}
diff --git a/apps/desktop/src/main/remote-agent/controller/router.ts b/apps/desktop/src/main/remote-agent/controller/router.ts
index 1cc0bece6f..aeaebf40b6 100644
--- a/apps/desktop/src/main/remote-agent/controller/router.ts
+++ b/apps/desktop/src/main/remote-agent/controller/router.ts
@@ -39,7 +39,6 @@ const PATH_ARGUMENTS = new Set([
'savedir', 'outpath', 'htmlpath', 'imagepath', 'iconsource', 'attachments', 'extradirs', 'writabledirs',
'debugimageout',
]);
-const WORKBENCH_PROJECT_TOOLS = new Set(['set_workbench_task', 'set_workbench_tasks']);
function json(status: number, value: unknown): Extract<RemoteAgentReply, { type: 'http' }> {
return {
@@ -73,28 +72,23 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
const doFetch = deps.fetch ?? fetch;
const workspace = deps.executor.workspace;
- const mapArguments = (value: unknown, key = '', toolName = ''): unknown => {
+ const mapArguments = (value: unknown, key = ''): unknown => {
if (typeof value === 'string') {
if (key === 'args') {
try {
const parsed = JSON.parse(value);
- if (parsed && typeof parsed === 'object') return JSON.stringify(mapArguments(parsed, '', toolName));
+ if (parsed && typeof parsed === 'object') return JSON.stringify(mapArguments(parsed));
} catch { /* 普通字符串参数保持原样。 */ }
}
if (/^(?:cmd|command)$/.test(key)) return workspace.mapCommand(value, resolveExecutorShell().dialect);
const fieldContext = pathTextContext(key);
if (fieldContext === 'ambiguous-path') return workspace.mapTextFromAgent(value, fieldContext);
- if (fieldContext === 'path'
- || PATH_ARGUMENTS.has(key.replace(/_/g, '').toLowerCase())
- || (key === 'project' && WORKBENCH_PROJECT_TOOLS.has(toolName))) return workspace.mapAlias(value);
+ if (fieldContext === 'path' || PATH_ARGUMENTS.has(key.replace(/_/g, '').toLowerCase())) return workspace.mapAlias(value);
return value;
}
- if (Array.isArray(value)) return value.map((item) => mapArguments(item, key, toolName));
+ if (Array.isArray(value)) return value.map((item) => mapArguments(item, key));
if (!value || typeof value !== 'object') return value;
- const effectiveToolName = toolName === 'call_tool' && typeof (value as Record<string, unknown>).name === 'string'
- ? (value as Record<string, unknown>).name as string
- : toolName;
- return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, mapArguments(item, name, effectiveToolName)]));
+ return Object.fromEntries(Object.entries(value).map(([name, item]) => [name, mapArguments(item, name)]));
};
const projectResult = (value: unknown, key = ''): unknown => {
if (typeof value === 'string') {
@@ -136,7 +130,7 @@ export function createReverseHttpRouter(deps: ReverseHttpRouterDeps) {
try {
const message = JSON.parse(body.toString('utf8'));
if (message.method === 'tools/call' && message.params?.arguments) {
- message.params.arguments = mapArguments(message.params.arguments, '', message.params.name ?? '');
+ message.params.arguments = mapArguments(message.params.arguments);
}
return Buffer.from(JSON.stringify(message));
} catch { return body; }
diff --git a/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts
index bc17f4cf79..dc1ec20cc0 100644
--- a/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts
+++ b/apps/desktop/src/main/remote-agent/executor/__tests__/virtualWorkspace.test.ts
@@ -631,7 +631,7 @@ describe('virtual workspace', () => {
}
});
- it('maps workbench project paths in direct and stringified generic-tool arguments', async () => {
+ it('maps path fields in direct and stringified generic-tool arguments, leaving opaque todo labels alone', async () => {
const virtual = '/Users/agent/workspace';
const { project, executor } = setup(virtual);
const forwarded: Array<Record<string, unknown>> = [];
@@ -647,21 +647,21 @@ describe('virtual workspace', () => {
},
});
try {
- for (const args of [
- { project: virtual },
- JSON.stringify({ project: virtual }),
- { items: [{ project: virtual }] },
- ]) {
+ // 伙伴待办里的 project 只是原样回传的标签(2026-10-17 放弃「项目」后不再授权),不做路径还原。
+ const calls: Array<[string, unknown]> = [
+ ['list_dir', { path: virtual }],
+ ['list_dir', JSON.stringify({ path: virtual })],
+ ['preflight_teammate_todo_events', { events: [{ source: 's', sequence: 1, key: 'k', project: virtual }] }],
+ ];
+ for (const [name, args] of calls) {
await router({ method: 'POST', path: '/mcp/cindy_helper', headers: [], body: Buffer.from(JSON.stringify({
- jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'call_tool', arguments: {
- name: args && typeof args === 'object' && !Array.isArray(args) && 'items' in args ? 'set_workbench_tasks' : 'set_workbench_task', args,
- } },
+ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'call_tool', arguments: { name, args } },
})).toString('base64') });
}
expect(forwarded).toEqual([
- { name: 'set_workbench_task', args: { project } },
- { name: 'set_workbench_task', args: JSON.stringify({ project }) },
- { name: 'set_workbench_tasks', args: { items: [{ project }] } },
+ { name: 'list_dir', args: { path: project } },
+ { name: 'list_dir', args: JSON.stringify({ path: project }) },
+ { name: 'preflight_teammate_todo_events', args: { events: [{ source: 's', sequence: 1, key: 'k', project: virtual }] } },
]);
} finally {
await executor.close();
diff --git a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
index 2cf2e03a72..cf204bf712 100644
--- a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
@@ -273,7 +273,6 @@ export function BotRoutines({
<BuiltinFollowUpRow
key={routine.id}
routine={routine}
- summary={routine.triggers.map(triggerSummary).join(' · ')}
disabled={busy}
onEnabledChange={(enabled) =>
void act(() => window.electronAPI.routines.save(botId, routineInput({ ...routine, enabled }), routine.id))
@@ -868,12 +867,10 @@ function routineInput(routine: Routine): RoutineInput {
*/
function BuiltinFollowUpRow({
routine,
- summary,
disabled,
onEnabledChange,
}: {
routine: Routine;
- summary: string;
disabled: boolean;
onEnabledChange: (enabled: boolean) => void;
}) {
@@ -890,10 +887,8 @@ function BuiltinFollowUpRow({
)}
<span className="min-w-0 flex-1">
<span className="block truncate">{name}</span>
- <span className="block text-12 text-[var(--text-secondary)]">
- {summary ? `${summary} · ` : ''}
- {t('routines.builtinFollowUp.hint')}
- </span>
+ {/* 触发条件由宿主维护、条数多且来源重复,这里只写一句白话,不逐条列出。 */}
+ <span className="block text-12 text-[var(--text-secondary)]">{t('routines.builtinFollowUp.hint')}</span>
</span>
<Switch
aria-label={name}
diff --git a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
index be183ef733..7cee9cafa0 100644
--- a/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotWorkbench.tsx
@@ -6,20 +6,19 @@ import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
import { useDeviceLinkDeviceList } from '@/features/device-link/useDeviceLinkDeviceList';
-import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { isSidebarWindow } from '@/lib/sidebarWindow';
import { toast } from '@/lib/toast';
import { cn } from '@/lib/utils';
import type { BotGlance, GlanceRow } from '../../../shared/botAutonomy';
-import { allowGlanceRow, bareGlanceSessionId, rebaseGlance, useBotGlance } from './botGlance';
+import { allowGlanceRow, canAllowGlanceRow, glanceSessionRoute, rebaseGlance, useBotGlance } from './botGlance';
/**
* 伙伴工作台「一眼」(右侧栏的一个标签)。
*
* 只有两块 + 一行页脚,数据全部来自宿主的 glance 投影:
* - 等你:一句问题(没有就用任务标题),一行「来源任务 · 电脑 · 等了多久」,下面是动作——
- * 权限类「允许」直接回应那一条请求(别的电脑经 device-link 到那台),回答类「回答」与出错类
- * 「看看」打开那件任务。
+ * 带具体请求 id 的权限类「允许」直接回应那一条请求(别的电脑经 device-link 到那台);回答类
+ * 「回答」、出错类与没有请求 id 的确认类「看看」打开那件任务(别的电脑上的按设备打开)。
* - 在做:标题 + 「电脑 · 做了多久」,最多先列 3 件;离线电脑上的变灰并写「离线」。
* - 页脚:「刚看过一遍 · 今天做完 N 件 · X 离线」。两块都空时只说一句安静的话。
* 负责所有任务的伙伴(scope = all)在顶部带「自动跟进所有任务」小标。
@@ -102,7 +101,7 @@ export function BotWorkbench({
(row: GlanceRow) => {
if (!canNavigate) return;
const owner = getDataOwnerGeneration();
- void resolveSessionRoute(bareGlanceSessionId(row))
+ void glanceSessionRoute(row)
.then((route) => {
if (isDataOwnerGenerationCurrent(owner)) navigate(route);
})
@@ -145,8 +144,9 @@ export function BotWorkbench({
];
return (
- <div className="h-full min-h-0 overflow-y-auto overflow-x-hidden bg-[var(--surface)]">
- <section className="flex flex-col gap-7 px-5 pb-6 pt-4" aria-label={t('bots.workbench.title')}>
+ // 两块在中间滚动,页脚钉在面板底部:行再多也一直看得见「刚看过一遍 · 今天做完 N 件」。
+ <section className="flex h-full min-h-0 flex-col bg-[var(--surface)]" aria-label={t('bots.workbench.title')}>
+ <div className="flex min-h-0 flex-1 flex-col gap-7 overflow-y-auto overflow-x-hidden px-5 pb-6 pt-4">
{glance.scope === 'all' ? (
<p className="inline-flex h-6 items-center self-start rounded-full border border-[var(--border-default)] px-2.5 text-12 leading-4 text-[var(--text-secondary)]">
{t('bots.autonomy.title')}
@@ -159,17 +159,17 @@ export function BotWorkbench({
) : null}
{glance.waiting.length > 0 ? <WaitingBlock rows={glance.waiting} ctx={ctx} /> : null}
{glance.working.length > 0 ? <WorkingBlock rows={glance.working} ctx={ctx} /> : null}
- <p
- className={cn(
- 'flex items-center gap-2 text-12 leading-[1.5] text-[var(--text-tertiary)]',
- quiet ? 'justify-center' : 'pl-5',
- )}
- >
- <span aria-hidden className="size-1 shrink-0 rounded-full bg-[var(--text-tertiary)]" />
- <span className="min-w-0 tabular-nums">{join(...footer)}</span>
- </p>
- </section>
- </div>
+ </div>
+ <footer
+ className={cn(
+ 'flex shrink-0 items-center gap-2 border-t border-[var(--border-default)] py-2.5 text-12 leading-[1.5] text-[var(--text-tertiary)]',
+ quiet ? 'justify-center px-5' : 'pl-10 pr-5',
+ )}
+ >
+ <span aria-hidden className="size-1 shrink-0 rounded-full bg-[var(--text-tertiary)]" />
+ <span className="min-w-0 truncate tabular-nums">{join(...footer)}</span>
+ </footer>
+ </section>
);
}
@@ -262,7 +262,7 @@ function WaitingRow({ row, ctx }: { row: GlanceRow; ctx: RowContext }) {
<li className="-ml-2 flex flex-col">
<RowText row={row} title={question} meta={meta} ctx={ctx} titleId={titleId} />
<div className="mt-1 flex gap-2 pl-2">
- {row.waitingFor === 'permission' ? (
+ {canAllowGlanceRow(row) ? (
<Button
variant="secondary"
size="xs"
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
index 9f0ae0bcdc..9dce46d4cd 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
@@ -16,6 +16,9 @@ const m = vi.hoisted(() => ({
toastError: vi.fn(),
remoteApi: { getPendingInteractions: vi.fn(), resolveInteraction: vi.fn() },
makerApiForDevice: vi.fn(),
+ resolveRoute: vi.fn(async (id: string) => `/cc-agent/${id}`),
+ pinSessionOrigin: vi.fn(),
+ mirrored: [] as Array<{ id: string }>,
}));
vi.mock('react-router-dom', () => ({ useNavigate: () => m.navigate }));
vi.mock('react-i18next', () => ({
@@ -33,11 +36,15 @@ vi.mock('@/features/device-link/useDeviceLinkDeviceList', () => ({
}));
vi.mock('@/lib/remoteDataOwnerPushFence', () => ({ isDeviceLinkRemotePushCurrent: () => true }));
vi.mock('@/lib/sidebarWindow', () => ({ isSidebarWindow: () => false }));
-vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: async (id: string) => `/cc-agent/${id}` }));
+vi.mock('@/lib/orcaSessionIdentity', () => ({ resolveSessionRoute: m.resolveRoute }));
+vi.mock('@/features/device-link/remoteProjectsStore', () => ({
+ remoteProjectsStore: { pinSessionOrigin: m.pinSessionOrigin, getMergedRemoteSessions: () => m.mirrored },
+}));
vi.mock('@/lib/toast', () => ({ toast: { warning: m.toastWarning, error: m.toastError } }));
vi.mock('@/lib/makerTransport', () => ({ makerApiForDevice: m.makerApiForDevice }));
import { BotWorkbench } from '../BotWorkbench';
+import { allowGlanceRow } from '../botGlance';
type Listener = (payload: { botIds?: string[] }) => void;
let listeners: Listener[] = [];
@@ -73,6 +80,7 @@ beforeEach(() => {
vi.clearAllMocks();
listeners = [];
m.makerApiForDevice.mockReturnValue(m.remoteApi);
+ m.mirrored = [];
(window as unknown as { electronAPI: unknown }).electronAPI = {
localDb: { bots: { autonomy: { glance: glanceApi } } },
maker: {
@@ -98,9 +106,14 @@ it('shows one quiet sentence when nothing waits or runs, and the follow-everythi
expect(await screen.findByText('bots.workbench.glance.quiet')).toBeTruthy();
expect(screen.getByText('bots.autonomy.title')).toBeTruthy();
expect(screen.queryByRole('heading')).toBeNull();
- expect(
- screen.getByText('bots.workbench.glance.seenJust · bots.workbench.glance.doneToday:3 · bots.workbench.glance.devicesOffline:Studio'),
- ).toBeTruthy();
+ const footerText = screen.getByText(
+ 'bots.workbench.glance.seenJust · bots.workbench.glance.doneToday:3 · bots.workbench.glance.devicesOffline:Studio',
+ );
+ // 页脚不跟两块一起滚:它是面板的直接子节点,与滚动的内容区并列(实测 800 高窗口里页脚曾被挤到折叠线下)。
+ const panel = screen.getByRole('region', { name: 'bots.workbench.title' });
+ const footer = footerText.closest('footer')!;
+ expect(footer.parentElement).toBe(panel);
+ expect(footer.previousElementSibling?.contains(screen.getByText('bots.workbench.glance.quiet'))).toBe(true);
});
it('allows only the permission request the row points at, and opens the task when that request is gone', async () => {
@@ -128,7 +141,7 @@ it('allows only the permission request the row points at, and opens the task whe
expect(localMaker.resolveInteraction).toHaveBeenCalledTimes(1);
});
-it('opens answer rows by their bare session id and cannot allow on an offline computer', async () => {
+it('opens a task on another computer through the device-aware route, not a same-id local lookup', async () => {
glanceApi.mockResolvedValue(glance({
waiting: [
row({ sessionId: 'dev-2::s7', deviceId: 'dev-2', deviceName: 'Studio', question: '用哪个分支?', waitingFor: 'answer' }),
@@ -140,8 +153,13 @@ it('opens answer rows by their bare session id and cannot allow on an offline co
const answer = (await screen.findByText('用哪个分支?')).closest('li')!;
expect(within(answer).queryByRole('button', { name: 'bots.workbench.glance.allow' })).toBeNull();
+ m.mirrored = [{ id: 's7' }];
fireEvent.click(within(answer).getByRole('button', { name: 'bots.workbench.glance.answer' }));
await waitFor(() => expect(m.navigate).toHaveBeenCalledWith('/cc-agent/s7'));
+ // 先登记这件任务属于 Studio,再按远程镜像里的那一行解析——与会话链接打开远程任务同一路径。
+ expect(m.pinSessionOrigin).toHaveBeenCalledWith('dev-2', 's7');
+ expect(m.resolveRoute).toHaveBeenCalledWith('s7', { id: 's7' });
+ expect(m.pinSessionOrigin.mock.invocationCallOrder[0]).toBeLessThan(m.resolveRoute.mock.invocationCallOrder[0]!);
const offline = screen.getByText('可以推送吗?').closest('li')!;
expect((within(offline).getByRole('button', { name: 'bots.workbench.glance.allow' }) as HTMLButtonElement).disabled).toBe(true);
@@ -178,3 +196,20 @@ it('reads a teammate on another computer from that computer and answers its own
expect(m.makerApiForDevice).toHaveBeenCalledWith('dev-2');
expect(m.remoteApi.getPendingInteractions).toHaveBeenCalledWith('s5');
});
+
+it('never approves a confirmation that carries no request id; it opens the task instead', async () => {
+ // 宿主把 kind 含 confirm 的交互归成权限类但没有 requestId:那件任务里唯一的权限请求不一定是这一行。
+ const confirmRow = row({ sessionId: 's3', question: '确认要发布吗?', waitingFor: 'permission', requestId: null });
+ glanceApi.mockResolvedValue(glance({ waiting: [confirmRow] }));
+ localMaker.getPendingInteractions.mockResolvedValue([permission('r-other')]);
+ render(<BotWorkbench botId="bot-1" />);
+
+ const waiting = (await screen.findByText('确认要发布吗?')).closest('li')!;
+ expect(within(waiting).queryByRole('button', { name: 'bots.workbench.glance.allow' })).toBeNull();
+ fireEvent.click(within(waiting).getByRole('button', { name: 'bots.workbench.glance.look' }));
+ await waitFor(() => expect(m.navigate).toHaveBeenCalledWith('/cc-agent/s3'));
+ expect(m.pinSessionOrigin).not.toHaveBeenCalled();
+ await expect(allowGlanceRow(confirmRow)).resolves.toBe('gone');
+ expect(localMaker.getPendingInteractions).not.toHaveBeenCalled();
+ expect(localMaker.resolveInteraction).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
index edf80f5f5d..ecd0045068 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
@@ -263,6 +263,10 @@ it('shows the host-owned follow-up as a pause-only built-in row that never opens
const toggle = await screen.findByRole('switch', { name: 'routines.builtinFollowUp.name' });
expect(screen.queryByText('follow-up')).toBeNull();
+ // 内置规则的触发条件很多且来源重复,只写一句固定白话,不逐条列出。
+ const row = toggle.parentElement!;
+ expect(row.textContent).toContain('routines.builtinFollowUp.hint');
+ expect(row.textContent).not.toContain('routines.everyMinutes');
fireEvent.click(screen.getByText('routines.builtinFollowUp.name'));
expect(screen.queryByLabelText('routines.instructions')).toBeNull();
diff --git a/apps/desktop/src/renderer/features/bots/botGlance.ts b/apps/desktop/src/renderer/features/bots/botGlance.ts
index 9739b68715..723103c092 100644
--- a/apps/desktop/src/renderer/features/bots/botGlance.ts
+++ b/apps/desktop/src/renderer/features/bots/botGlance.ts
@@ -9,6 +9,8 @@
import { useEffect, useState } from 'react';
import { getDataOwnerGeneration, isDataOwnerGenerationCurrent } from '@/contexts/dataOwnerGeneration';
+import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
+import { resolveSessionRoute } from '@/lib/orcaSessionIdentity';
import { isDeviceLinkRemotePushCurrent } from '@/lib/remoteDataOwnerPushFence';
import { BOT_AUTONOMY_IPC, type BotGlance, type GlanceRow } from '../../../shared/botAutonomy';
@@ -116,13 +118,32 @@ export function useBotGlance(botId: string, host: GlanceHost, enabled = true): G
return state;
}
+/** 这一行能不能直接「允许」:只有带着具体权限请求 id 的行才行。 */
+export function canAllowGlanceRow(row: GlanceRow): boolean {
+ return row.waitingFor === 'permission' && Boolean(row.requestId);
+}
+
+/**
+ * 打开这一行的任务。别的电脑上的任务走与会话链接相同的按设备路径:先登记它属于哪台电脑,
+ * 再按远程镜像里的那一行解析路由;不能只拿裸 id 去查本机库(会落到本机同 id 任务或找不到)。
+ */
+export async function glanceSessionRoute(row: GlanceRow): Promise<string> {
+ const sessionId = bareGlanceSessionId(row);
+ if (!row.deviceId) return resolveSessionRoute(sessionId);
+ remoteProjectsStore.pinSessionOrigin(row.deviceId, sessionId);
+ const mirrored = remoteProjectsStore.getMergedRemoteSessions().find((session) => session.id === sessionId) ?? null;
+ return resolveSessionRoute(sessionId, mirrored);
+}
+
export type AllowOutcome = 'allowed' | 'gone' | 'blocked' | 'failed';
/**
* 「允许」:只回应这一行对应的那条权限请求,本机走本机宿主,别的电脑走 device-link 隧道到那台。
- * 请求已经不在(被处理、被换掉)时不替主人批准别的请求,交给调用方改为「去任务里看」。
+ * 请求已经不在(被处理、被换掉)或行上没有请求 id 时不替主人批准别的请求,交给调用方改为「去任务里看」。
*/
export async function allowGlanceRow(row: GlanceRow): Promise<AllowOutcome> {
+ // 没有具体请求 id(例如按「需要确认」归成权限类的交互)时不替主人批准任何一条,交给调用方打开任务。
+ if (!row.requestId) return 'gone';
if (row.deviceId && !row.online) return 'blocked';
const sessionId = bareGlanceSessionId(row);
const api = row.deviceId
@@ -130,9 +151,7 @@ export async function allowGlanceRow(row: GlanceRow): Promise<AllowOutcome> {
: window.electronAPI.maker;
const pending = await api.getPendingInteractions(sessionId);
const permissions = (Array.isArray(pending) ? pending : []).filter((item) => item?.request?.kind === 'permission');
- const target = row.requestId
- ? permissions.find((item) => item.request.requestId === row.requestId)
- : permissions.length === 1 ? permissions[0] : undefined;
+ const target = permissions.find((item) => item.request.requestId === row.requestId);
if (!target) return 'gone';
const receipt = await api.resolveInteraction(target.request.requestId, { kind: 'permission', behavior: 'allow' });
return receipt?.accepted === true ? 'allowed' : 'failed';
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index e8b4a984f0..d4d3e97a61 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -15497,7 +15497,7 @@
"advancedSettings": "Advanced settings",
"builtinFollowUp": {
"name": "Follow-up (built-in)",
- "hint": "Built in, so it can only be paused or resumed"
+ "hint": "Wakes it when a session is stuck, waiting for you, errors out, hits the usage limit, or finishes. Built in, so it can only be paused or resumed."
}
},
"cindyMakeDoctor": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index e6e5a298a0..cd14471e15 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -15442,7 +15442,7 @@
"advancedSettings": "詳細設定",
"builtinFollowUp": {
"name": "フォロー(組み込み)",
- "hint": "組み込みのため、一時停止と再開のみできます"
+ "hint": "セッションが止まったとき、返信待ちになったとき、エラーになったとき、使用量の上限に達したとき、完了したときに起こします。組み込みのため、一時停止と再開のみできます。"
}
},
"cindyMakeDoctor": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index ecb82bf2d4..884b7d3846 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -15442,7 +15442,7 @@
"advancedSettings": "고급 설정",
"builtinFollowUp": {
"name": "후속 관리(기본 제공)",
- "hint": "기본 제공 루틴이라 일시 중지와 재개만 할 수 있습니다"
+ "hint": "세션이 멈추거나, 응답을 기다리거나, 오류가 나거나, 사용량 한도에 도달하거나, 끝나면 깨웁니다. 기본 제공 루틴이라 일시 중지와 재개만 할 수 있습니다."
}
},
"cindyMakeDoctor": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 301dcac9b9..cf5910ca35 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -15442,7 +15442,7 @@
"advancedSettings": "高级设置",
"builtinFollowUp": {
"name": "跟进(内置)",
- "hint": "内置,只能暂停或恢复"
+ "hint": "任务卡住、等你、出错、撞上用量上限或做完时叫醒它;内置,只能暂停或恢复。"
}
},
"cindyMakeDoctor": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index d0eddd9471..a79c6caa8e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -15442,7 +15442,7 @@
"advancedSettings": "進階設定",
"builtinFollowUp": {
"name": "跟進(內建)",
- "hint": "內建,只能暫停或恢復"
+ "hint": "任務卡住、等你、出錯、撞上用量上限或做完時叫醒它;內建,只能暫停或恢復。"
}
},
"cindyMakeDoctor": {
diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.ts
index 73aec162fe..a043dc1d3d 100644
--- a/apps/desktop/src/shared/botAutonomy.ts
+++ b/apps/desktop/src/shared/botAutonomy.ts
@@ -29,6 +29,11 @@ export const DEFAULT_SCHEDULER_BOT_ID = 'cindy-default';
export const AUTONOMY_THRESHOLDS = {
/** 运行中但无任何活动达到这么久 → stuck。 */
stuckAfterMs: 10 * 60_000,
+ /**
+ * 前台工具调用在途(tool_use 已发、tool_result 未回,例如一次长构建)时没有任何活动事件,
+ * 用更长的阈值判 stuck,避免把健康的长工具调用当成卡住。
+ */
+ stuckInToolAfterMs: 45 * 60_000,
/** 等权限 / 等回答达到这么久 → waiting(主人不在时伙伴代答或提醒)。 */
waitingAfterMs: 5 * 60_000,
/** 同一任务同一类事件 24h 内最多发布次数,防止伙伴与任务互相推着打转。 */
@@ -74,6 +79,16 @@ export interface WatchedSession {
* (实现者 A 新增,可选字段。)
*/
pendingRequestId?: string | null;
+ /**
+ * 本机任务当前有前台工具调用在途(只是布尔事实,不含工具名与入参);远程与缺省为 false。
+ * stuck 判定据此改用 `stuckInToolAfterMs`。(实现者 A 新增,可选字段。)
+ */
+ toolInFlight?: boolean;
+ /**
+ * 这件任务是哪个伙伴自己的主任务(canonical);不是则 null / 缺省。伙伴自己的主任务永远不是它自己的
+ * 事件对象,也不出现在它自己的工作台;总调度是另一个伙伴时照常看到、照常跟。(实现者 A 新增,可选字段。)
+ */
+ canonicalOfBotId?: string | null;
error: string | null;
/** 哪个伙伴开的这件任务(bot_delegations / task-responsibility),没有就是 null。 */
creatorBotId: string | null;
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 29004d2d7d..64d4cca15f 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -128,8 +128,9 @@ const receipt = await cindy.routines.request({
旧版带的 2 小时间隔条件在下一次 ensure 时被对齐掉。`silentWhenIdle` 开启,
这一轮的回复不自动发给主人,要主人知道的事显式通知。
- 指令由宿主模板生成(`apps/desktop/src/main/bot-autonomy/followUpPrompt.ts`),伙伴与主人都不能编辑。
-- 宿主在例行任务引擎每次启动、伙伴新建(下一次归属刷新,≤60 秒)与恢复时幂等 ensure:不存在就建;指令或触发条件与模板
- 不同就对齐;保留主人的暂停选择。暂停中的伙伴不建。
+- 宿主在例行任务引擎每次启动、伙伴新建(资料广播后立即重读归属)与恢复时幂等 ensure,事件发布前也先确认跟进者的规则已落地
+ (否则首次安装时的早期事件会被记下回执却没人接收):不存在就建;指令、触发条件或模板版本(`builtinVersion`,随
+ `FOLLOW_UP_PROMPT_VERSION` 递增)与模板不同就重写;保留主人的暂停选择。暂停中的伙伴不建。
- 主人只能暂停 / 恢复:删除(含 `routine_delete`)与修改内容一律以 `BUILTIN_ROUTINE` 拒绝。暂停后该伙伴不再被事件叫醒,
本机「等你」改由宿主直接提醒主人。伙伴暂停 / 归档时随伙伴的其它规则一起停摆,删除伙伴时一起清理。
- 云端伙伴的规则同步(companion cloud)不包含内置规则:每台电脑各自 ensure,执行只在主力电脑上发生。
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index d136e213f2..8be36bfb92 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -615,7 +615,11 @@ Session 任务遵守同一套机制与呈现契约:
那句话)与数据库兜底(标题、隐藏 / 归档、启动时上一轮被打断的任务)。远程只在存在在线、已开启远程控制、本机允许
控制且版本支持后台只读请求的同账号电脑时,每 60 秒经后台链路读 `maker:list-active` v2,再按需读标题与挂起交互;
失败按电脑指数退避(上限 15 分钟),离线电脑的行保留最后状态并标离线,24 小时后丢弃。手机不进轮询。
- 不进表:伙伴自己的专线(主任务 / 历史 / 群 / IM 渠道)、隐藏或归档的任务、Orca worker、复核任务;
+ 不进表:伙伴的历史 / 群 / IM 渠道专线、隐藏或归档的任务、Orca worker、复核任务;
+ 伙伴的主任务(资料 `canonical_session_id` 或 canonical 链接)进表,但**永远不是该伙伴自己的事件对象**(不发
+ stuck / waiting / errored / usage-limit / finished / sweep 给它自己——否则欢迎轮出错会把跟进排进正在失败的主任务里
+ 自己叫醒自己),也不进它自己工作台的等你 / 在做;总调度是另一个伙伴时照常收它的卡住 / 等你 / 出错 / 用量上限,
+ 以便发现别的伙伴的主任务坏了。主任务一轮回复做完不发 `finished`、不计入今天做完(每回一句话都叫醒总调度只是成本)。
远程电脑上伙伴自己的任务也不进表。
**每台电脑上的任务由那台电脑上的伙伴跟**:远程行只进工作台「一眼」供主人看与允许,跟进者恒为 null,不发布任何事件、
不发系统提醒。原因:同账号的两台电脑各自运行一套伙伴(例如各有一个在用的 Cindy 助理),若远程行也发事件,两台电脑上
@@ -639,6 +643,8 @@ Session 任务遵守同一套机制与呈现契约:
(桌面通知 + 手机推送,主窗口在前台时不弹桌面通知),同一事件只提醒一次。跟进者的内置规则被主人暂停时同样处理。
- 设置「自动跟进所有任务」:账号级、只存 override(`bot-autonomy-settings.json` 的 `schedulerBotId`,显式 null = 关掉);
恢复默认 = 删除 override。目标伙伴必须存在且未归档;它被归档后回到默认。设置只在本机可信界面读写,不开放给远程。
+ override 文件存在但读不出(损坏 / 超限 / 无权限)时失败关闭:按关掉处理并记一条警告,不回落到默认的 Cindy 助理;
+ 恢复默认会删掉坏文件。设置变化、伙伴新建 / 资料保存 / 暂停 / 恢复 / 归档都立即重算跟进者(不等 60 秒的定时重读)。
#### 6.3.3 事件与阈值
@@ -646,11 +652,11 @@ Session 任务遵守同一套机制与呈现契约:
| 事件 | 条件 |
| --- | --- |
-| `stuck` | 运行中且 10 分钟没有任何活动 |
+| `stuck` | 运行中且 10 分钟没有任何活动;有前台工具调用在途(如一次长构建,期间没有活动事件)时放宽到 45 分钟 |
| `waiting` | 等权限 / 等回答满 5 分钟 |
| `errored` | 出错,或启动时发现上一轮被打断 |
| `usage-limit` | 撞上用量上限、宿主正在等重置后自动继续 |
-| `finished` | 曾在跑的任务做完(自动化的运行任务不发,它有自己的结果通知) |
+| `finished` | 观察到任务完成(灵动岛完成态);主人点停止 / 中止的任务静默离表,不算做完、不发事件。自动化的运行任务不发,它有自己的结果通知 |
| `sweep` | 条件兜底:某跟进伙伴还有 ≥1 件等你 / 出错 / 用量上限 / 卡住的本机任务,且距它上次被叫醒(任一事件被它的规则接收)满 2 小时 |
- 去重:事件 id = `类型:任务:进入该状态的时刻`,同一状态只发一次;引擎另有 24 小时回执去重,重启后同一次状态不重发。
diff --git a/packages/lizi-mcps/src/__tests__/getTaskDigestTool.test.ts b/packages/lizi-mcps/src/__tests__/getTaskDigestTool.test.ts
index 7552a921c5..3c237c5ccd 100644
--- a/packages/lizi-mcps/src/__tests__/getTaskDigestTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/getTaskDigestTool.test.ts
@@ -30,6 +30,8 @@ const digest: TaskDigestWire = {
title: '修登录'.repeat(80),
phase: 'waiting-answer',
elapsed_minutes: 12,
+ idle_minutes: 12,
+ tool_in_flight: true,
last_user_ask: longText,
last_assistant_line: longText,
pending_question: longText,
@@ -58,7 +60,7 @@ describe('get_task_digest', () => {
const reg = setup({ taskDigest });
const { text, json } = parse(await reg.call('get_task_digest', { session_id: 'laptop::s-9' }));
expect(new TextEncoder().encode(text).length).toBeLessThanOrEqual(TASK_DIGEST_MAX_BYTES);
- expect(json).toMatchObject({ ok: true, session_id: 'laptop::s-9', phase: 'waiting-answer', queued_count: 1 });
+ expect(json).toMatchObject({ ok: true, session_id: 'laptop::s-9', phase: 'waiting-answer', queued_count: 1, tool_in_flight: true });
for (const key of ['last_user_ask', 'last_assistant_line', 'pending_question', 'error', 'pr_status'] as const) {
const value = json[key];
if (value !== null) expect(Array.from(String(value)).length).toBeLessThanOrEqual(300);
diff --git a/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts b/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts
index bd36066f16..449e48cca6 100644
--- a/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts
+++ b/packages/lizi-mcps/src/xdt-helper/get_task_digest.ts
@@ -39,6 +39,10 @@ export interface TaskDigestWire {
phase: TaskDigestPhase;
/** 处于当前状态(或本轮运行)多少分钟;未知为 null。 */
elapsed_minutes: number | null;
+ /** 距离任务最后一次有动静(输出、工具结果)多少分钟;未知为 null。 */
+ idle_minutes: number | null;
+ /** 当前有工具调用正在执行(长时间构建 / 测试);宿主不知道时不出现这个字段。 */
+ tool_in_flight?: boolean;
last_user_ask: string | null;
last_assistant_line: string | null;
pending_question: string | null;
@@ -101,6 +105,7 @@ export function boundTaskDigest(raw: TaskDigestWire): TaskDigestWire {
const DESCRIPTION = [
'读一件任务的短摘要(≤2KB):状态 phase、已持续分钟数、主人最后的要求、助手最后一句、待回答的问题、错误、当前模型路线、',
'建议换到的下一条路线(你的候选链里还没试过的那条,没有则 null)、PR 状态、排队消息数、谁开的 / 谁在跟。',
+ 'idle_minutes 距最后一次动静的分钟数;tool_in_flight 为 true 表示有工具调用(如长时间构建、测试)正在执行,宿主不知道时不出现。',
'被程序叫醒跟进任务时先读这一份再决定;要看原文再用 get_chat_history。',
'作用范围:本机任务直接传 id;另一台电脑上的任务传 deviceId::sessionId(只读,对方须在线)。',
'phase:running 运行中 / waiting-permission 等权限 / waiting-answer 等回答 / errored 出错 / usage-limit 撞用量上限 / finished 刚做完 / idle 空闲。',
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index 56dbfc6288..ec583e8a5c 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -796,10 +796,11 @@ describe('routine check configuration', () => {
/*
* 测试价值
* - 生产入口与可观察结果:RoutineEngine.ensureBuiltin / put / remove / publish;主人能暂停但删不掉、
- * 改不了宿主内置的「跟进」规则,宿主改模板后已有规则被对齐且保留暂停选择。
+ * 改不了宿主内置的「跟进」规则,宿主改模板(正文或模板版本)后已有规则被对齐且保留暂停选择。
* - Bug/规则依据:docs/product-rules/bot-routines.md「内置跟进例行任务」(只能暂停 / 恢复)。
* - 现有覆盖缺口:既有用例只覆盖普通规则;builtin 分支(拒删、拒改、对齐模板、保留 enabled)无覆盖。
- * - 最小失败输入:对 builtin 规则 remove,或 put 一份改了 prompt 的定义;宿主再次 ensure 新 prompt。
+ * - 最小失败输入:对 builtin 规则 remove,或 put 一份改了 prompt 的定义;宿主再次 ensure 新 prompt;
+ * 正文相同但模板版本递增时不重写(版本形同虚设)。
* - tier:unit(内存 load/save fake,无真实等待)。
*/
it('keeps a host built-in rule pausable but not deletable or editable, and realigns it on ensure', async () => {
@@ -815,8 +816,12 @@ describe('routine check configuration', () => {
const paused = await f.engine.put('bot', { ...input, enabled: false }, id);
expect(paused).toMatchObject({ builtin: 'follow-up', enabled: false });
expect(await f.engine.publish('github', event('while-paused'))).toEqual({ accepted: 0, duplicate: false });
- const realigned = await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id);
- expect(realigned).toMatchObject({ prompt: 'v2', enabled: false, builtin: 'follow-up' });
+ const realigned = await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 1);
+ expect(realigned).toMatchObject({ prompt: 'v2', enabled: false, builtin: 'follow-up', builtinVersion: 1 });
+ // 模板版本递增:正文相同也重写并记下新版本;同版本再 ensure 不产生新 revision。主人暂停后的选择保留。
+ const bumped = await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 2);
+ expect(bumped).toMatchObject({ builtinVersion: 2, enabled: false, revision: realigned!.revision + 1 });
+ expect((await f.engine.ensureBuiltin('bot', 'follow-up', { ...input, prompt: 'v2' }, id, 2))?.revision).toBe(bumped?.revision);
await f.engine.setBotPaused('bot', true);
expect(await f.engine.ensureBuiltin('bot', 'follow-up', input, id)).toBeNull();
} finally { await f.engine.stop(); }
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index ff5989a912..1b6f3bca7d 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -269,18 +269,24 @@ export class RoutineEngine {
* 保留用户的暂停选择(enabled)。暂停中的伙伴不建,恢复后由宿主再调一次。
* 这是唯一能写内置规则内容的入口;普通 put 只能切换 enabled,remove 一律拒绝。
*/
- async ensureBuiltin(botId: string, builtin: RoutineBuiltin, raw: RoutineInput, id: string): Promise<Routine | null> {
+ async ensureBuiltin(
+ botId: string,
+ builtin: RoutineBuiltin,
+ raw: RoutineInput,
+ id: string,
+ builtinVersion?: number,
+ ): 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);
return this.writeRoutine(
botId,
existing ? { ...raw, enabled: existing.enabled } : raw,
- { id, builtin },
+ { id, builtin, ...(builtinVersion !== undefined ? { builtinVersion } : {}) },
);
}
- private async writeRoutine(botId: string, raw: RoutineInput, options: { id?: string; expectedRevision?: number; creationId?: string; builtin?: RoutineBuiltin }): Promise<Routine> {
+ private async writeRoutine(botId: string, raw: RoutineInput, options: { id?: string; expectedRevision?: number; creationId?: string; builtin?: RoutineBuiltin; builtinVersion?: number }): Promise<Routine> {
const { expectedRevision, creationId } = options;
const id = options.id ?? creationId;
const parsed = parseRoutineInput(raw);
@@ -307,10 +313,11 @@ export class RoutineEngine {
JSON.stringify(parseRoutineInput({ ...existing, enabled: input.enabled })) !== JSON.stringify(input))
throw new Error(`${BUILTIN_ROUTINE_ERROR}: built-in routines can only be paused or resumed`);
const builtin = options.builtin ?? existing?.builtin;
+ const builtinVersion = options.builtinVersion ?? existing?.builtinVersion;
if (creationId && existing && JSON.stringify(parseRoutineInput(existing)) !== JSON.stringify(input)) throw new Error("Routine already created; refresh before editing");
if (expectedRevision !== undefined && existing?.revision !== expectedRevision) throw new Error("Routine changed; refresh before saving");
if (
- existing && existing.builtin === builtin &&
+ existing && existing.builtin === builtin && existing.builtinVersion === builtinVersion &&
JSON.stringify(parseRoutineInput(existing)) === JSON.stringify(input)
)
return structuredClone(existing);
@@ -319,6 +326,7 @@ export class RoutineEngine {
const routine: Routine = {
...input,
...(builtin ? { builtin } : {}),
+ ...(builtin && builtinVersion !== undefined ? { builtinVersion } : {}),
id: existing?.id ?? creationId ?? id ?? this.deps.id(),
botId,
revision: (existing?.revision ?? 0) + 1,
diff --git a/packages/maker-scheduler/src/routines.ts b/packages/maker-scheduler/src/routines.ts
index 3e15774262..aedf2c1df8 100644
--- a/packages/maker-scheduler/src/routines.ts
+++ b/packages/maker-scheduler/src/routines.ts
@@ -61,6 +61,11 @@ export interface Routine {
* state 版本不变。
*/
builtin?: RoutineBuiltin;
+ /**
+ * 内置规则的宿主模板版本(可选,只由 ensureBuiltin 写)。版本变化时 ensure 一定重写规则;
+ * 旧数据缺省视为与任何显式版本不同,下次 ensure 补写。
+ */
+ builtinVersion?: number;
revision: number;
createdAt: number;
updatedAt: number;