Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(bot-autonomy): 回应第二轮 review 的四处运行期缺陷

Chrisc5709ec088d7
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 a5df5ffe68..d176348a1e 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
@@ -12,7 +12,9 @@
* - 最小失败输入:引擎重建后不重登记 → publish 抛 "not listening";waiting 事件叫醒了非跟进者;
* 跟进规则暂停后主人收不到提醒或被重复提醒;没有待处理任务也被兜底叫醒,或每 30 秒扫描重复叫醒;
* 停止被当成做完叫醒伙伴;首次安装时事件赶在 ensure 之前发布、accepted=0 后永久丢失;伙伴主任务的欢迎轮出错
- * 后宿主把 errored 发给它自己,排在正在失败的主任务后面打转。
+ * 后宿主把 errored 发给它自己,排在正在失败的主任务后面打转;启动时第一次读归属失败,补快照里已出错的任务被按
+ * 「没人跟」结清、之后归属读到也不再发;内置规则落地失败仍发布(accepted=0 + 回执)后永久丢失;
+ * 120 字符的合法伙伴 id 拼出超过 128 字符的规则 id、永远没有内置规则。
* - tier:unit(真实引擎 + 内存 load/save;状态表 IO 为内存 fake;时间由 now() 推进)。
*/
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
@@ -20,11 +22,8 @@ import { RoutineEngine, type RoutineEngineDeps, type RoutineState } from '@cindy
import type { AutonomyEngine } from '../runtime.js';
import { describe, expect, it, vi } from 'vitest';
-import {
- AUTONOMY_THRESHOLDS,
- HOST_SESSIONS_SOURCE_ID,
- builtinFollowUpRoutineId,
-} from '../../../shared/botAutonomy.js';
+import { AUTONOMY_THRESHOLDS, HOST_SESSIONS_SOURCE_ID } from '../../../shared/botAutonomy.js';
+import { builtinFollowUpRoutineId } from '../builtinRoutine.js';
import { BotAutonomyRuntime } from '../runtime.js';
import { TaskWatch, type LocalSessionMeta } from '../taskWatch.js';
@@ -53,7 +52,13 @@ function errored(sessionId: string): SessionActivitySnapshot {
return { ...waiting(sessionId), phase: 'error', interactionKind: undefined, lastActivityAtMs: 5 } as SessionActivitySnapshot;
}
-async function setup() {
+async function setup(options: {
+ /** 每次读归属前调用;抛错即这次读失败(模拟启动时读库 / 读文件出错)。 */
+ beforeOwnershipRead?: () => void;
+ creators?: Record<string, string>;
+ extraBots?: string[];
+ subscribeActivity?: (watch: TaskWatch) => (() => void) | null;
+} = {}) {
let now = 1_000_000;
let saved: RoutineState | null = null;
const execute = vi.fn<RoutineEngineDeps['execute']>(async () => ({}));
@@ -71,6 +76,7 @@ async function setup() {
['sched', { status: 'active', allowSchedulerFollow: false, canonicalSessionId: 'sched-main' }],
['a', { status: 'active', allowSchedulerFollow: false, canonicalSessionId: 'a-main' }],
['paused-bot', { status: 'paused', allowSchedulerFollow: false }],
+ ...(options.extraBots ?? []).map((id) => [id, { status: 'active', allowSchedulerFollow: false }] as const),
]);
const create = (engine: AutonomyEngine) => new BotAutonomyRuntime({
engine,
@@ -79,7 +85,7 @@ async function setup() {
isCurrent: () => true,
remind,
push: () => {},
- subscribeActivity: () => () => {},
+ subscribeActivity: options.subscribeActivity ?? (() => () => {}),
createWatch: (onChange) => new TaskWatch({
now: () => now,
log,
@@ -89,7 +95,10 @@ async function setup() {
getPendingInteractions: () => [],
readLocalSessions: async (ids) => ids.map(meta),
readInterruptedSessions: async () => [],
- readOwnership: async () => ({ bots, creatorBySession: new Map(), responsibleByBot: new Map() }),
+ readOwnership: async () => {
+ options.beforeOwnershipRead?.();
+ return { bots, creatorBySession: new Map(Object.entries(options.creators ?? {})), responsibleByBot: new Map() };
+ },
readSchedulerOverride: () => ({ customized: true, schedulerBotId: 'sched' }),
listRemoteDevices: async () => null,
invokeRemote: async () => { throw new Error('unused'); },
@@ -286,4 +295,90 @@ describe('BotAutonomyRuntime with the routine engine', () => {
await engine.stop();
}
});
+
+ it('does not judge startup tasks before ownership has loaded once, even if the first read fails', async () => {
+ let ownershipReads = 0;
+ // 与 service 一致:订阅时把灵动岛当前快照同步补进状态表;启动时第一次读归属失败,下一次扫描才读到。
+ const t = await setup({
+ creators: { t1: 'a' },
+ beforeOwnershipRead: () => {
+ ownershipReads += 1;
+ if (ownershipReads === 1) throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
+ },
+ subscribeActivity: (watch) => {
+ watch.applyActivity('t1', errored('t1'));
+ return () => {};
+ },
+ });
+ const engine = await t.engine();
+ const runtime = await t.runtime(engine);
+ try {
+ // 让补快照的重算与它触发的判定都有机会先跑(setTimeout 0,不是真实等待)。
+ for (let i = 0; i < 3; i += 1) await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(t.execute).not.toHaveBeenCalled();
+ await runtime.sweep();
+ await vi.waitFor(() => expect(t.execute).toHaveBeenCalledTimes(1));
+ const [routine, run] = t.execute.mock.calls[0]!;
+ expect(routine.id).toBe(builtinFollowUpRoutineId('a'));
+ expect(run.events.map((e) => [e.event.type, e.event.subject, e.event.data.followerBotId])).toEqual([
+ ['errored', 't1', 'a'],
+ ]);
+ } finally {
+ runtime.stop();
+ await engine.stop();
+ }
+ });
+
+ it('keeps an event for the next scan when the built-in rule cannot be written yet', async () => {
+ const t = await setup();
+ const engine = await t.engine();
+ let failing = true;
+ const publish = vi.fn<AutonomyEngine['publish']>((...args) => engine.publish(...args));
+ const flaky: AutonomyEngine = {
+ registerSource: (source) => engine.registerSource(source),
+ publish,
+ ensureBuiltin: async (...args) => {
+ if (failing) throw Object.assign(new Error('disk full'), { code: 'ENOSPC' });
+ return engine.ensureBuiltin(...args);
+ },
+ };
+ const runtime = t.create(flaky);
+ try {
+ await runtime.start({ timers: false });
+ runtime.watch.applyActivity('t1', errored('t1'));
+ await runtime.watch.settled();
+ // 规则落地失败:不发布、不结清,留到下一次扫描。
+ await runtime.evaluate();
+ expect(publish).not.toHaveBeenCalled();
+
+ failing = false;
+ await runtime.evaluate();
+ await vi.waitFor(() => expect(t.execute).toHaveBeenCalledTimes(1));
+ expect(publish).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('gives a teammate with a long id a valid built-in rule id, and keeps short ids unchanged', async () => {
+ const longId = `b${'x'.repeat(119)}`;
+ const shortId = 'teammate-0123456789abc';
+ const t = await setup({ extraBots: [longId, shortId] });
+ const engine = await t.engine();
+ const runtime = await t.runtime(engine);
+ try {
+ // 已落盘的普通伙伴规则 id 不变:仍是前缀 + 伙伴 id。
+ expect(engine.list(shortId).map((r) => r.id)).toEqual([`builtin-follow-up-${shortId}`]);
+ // 120 字符的合法伙伴 id:拼接超过 128 字符,改用稳定的摘要 id,规则照样落地。
+ const id = builtinFollowUpRoutineId(longId);
+ expect(id).toMatch(/^[a-zA-Z0-9_-]{16,128}$/);
+ expect(builtinFollowUpRoutineId(longId)).toBe(id);
+ expect(engine.list(longId).map((r) => r.id)).toEqual([id]);
+ } 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 689e188816..abe83f20eb 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
@@ -7,7 +7,8 @@
* 等你状态的时刻跨重启稳定;远程电脑离线保留最后状态;轮询失败退避,不形成重试风暴)。
* - 现有覆盖缺口:新模块;autonomyRules 只测纯判定,不经过活动订阅、读库与远程轮询的组合时序。
* - 最小失败输入:伙伴主任务(canonical)出现在活动里;启动时灵动岛残留「完成」;主人点停止后灵动岛条目消失
- * 被当成做完;同一条挂起交互在重启后得到新的事件 id;远程 list-active 连续失败。
+ * 被当成做完;同一条挂起交互在重启后得到新的事件 id;远程 list-active 连续失败;远程任务两次轮询之间从权限请求
+ * A 换到 B,仍显示 A。
* - tier:unit(全部 IO 经注入的内存 fake,时间由 now() 推进,无真实等待)。
*/
import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
@@ -200,4 +201,39 @@ describe('TaskWatch remote polling', () => {
await h.watch.sweep();
expect(h.invokeRemote.mock.calls.length).toBe(calls + 1);
});
+
+ it('re-reads the pending request on every poll while a remote task keeps waiting', async () => {
+ const requests = [
+ { kind: 'permission', requestId: 'req-A', toolName: 'Bash' },
+ { kind: 'permission', requestId: 'req-B', toolName: 'Write' },
+ ];
+ let poll = 0;
+ const h = harness({
+ devices: [{ deviceId: 'dev-1', name: 'Studio', online: true, eligible: true }],
+ invokeRemote: async (_deviceId, channel) => {
+ if (channel === 'maker:list-active') {
+ poll += 1;
+ return { format: 'active-sessions-v2', sessions: [{ sessionId: 'r1', isTurnRunning: true, activityPhase: 'needs-interaction' }] };
+ }
+ if (channel === 'local-db:sessions:get-many') {
+ return [{ id: 'r1', title: 'Remote deploy', source: 'desktop', status: 'active', hiddenAt: null, updatedAt: 9_000, messageCount: 3 }];
+ }
+ // 两次轮询之间远程任务从权限请求 A 直接换到 B,中间的「在跑」没被观察到。
+ return [{ request: requests[poll - 1] }];
+ },
+ });
+ await h.watch.start();
+ await h.watch.sweep();
+ const first = h.watch.get('dev-1::r1');
+ expect(first).toMatchObject({ phase: 'waiting-permission', pendingRequestId: 'req-A', pendingQuestion: 'Bash' });
+
+ h.advance(AUTONOMY_THRESHOLDS.remotePollMs);
+ await h.watch.sweep();
+ // 新请求是新的等待:「允许」对准 B,等待时刻从这次观察算起。
+ expect(h.watch.get('dev-1::r1')).toMatchObject({
+ phase: 'waiting-permission', pendingRequestId: 'req-B', pendingQuestion: 'Write', phaseSince: h.now(),
+ });
+ expect(h.invokeRemote.mock.calls.filter(([, channel]) => channel === 'maker:get-pending-interactions')).toHaveLength(2);
+ });
});
+
diff --git a/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts b/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts
index 4421ae731d..2521c06420 100644
--- a/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts
+++ b/apps/desktop/src/main/bot-autonomy/builtinRoutine.ts
@@ -8,10 +8,29 @@
* - silentWhenIdle:没事可报时不打扰主人。
* - 用户只能暂停 / 恢复,不能删除或改内容;宿主每次 ensure 时把指令与触发条件对齐到模板。
*/
+import { createHash } from 'node:crypto';
import type { RoutineInput, RoutineTrigger } from '@cindy/maker-scheduler';
-import { AUTONOMY_EVENT_TYPES, HOST_SESSIONS_SOURCE_ID } from '../../shared/botAutonomy.js';
+import {
+ AUTONOMY_EVENT_TYPES,
+ BUILTIN_FOLLOW_UP_ROUTINE_PREFIX,
+ HOST_SESSIONS_SOURCE_ID,
+} from '../../shared/botAutonomy.js';
import { FOLLOW_UP_PROMPT_VERSION, buildFollowUpRoutinePrompt } from './followUpPrompt.js';
+/** 与例行任务引擎的 creationId 校验一致。 */
+const ROUTINE_ID_PATTERN = /^[a-zA-Z0-9_-]{16,128}$/;
+
+/**
+ * 内置跟进规则的 id:前缀 + 伙伴 id 合法时原样拼接(已落盘的 id 不变);伙伴 id 过长(合法伙伴 id 可到
+ * 128 字符)或含引擎不接受的字符时,改用前缀 + 伙伴 id 的 sha256 前 40 位,长度与字符集都稳定合法。
+ * 不要从 id 反推伙伴 id。
+ */
+export function builtinFollowUpRoutineId(botId: string): string {
+ const plain = `${BUILTIN_FOLLOW_UP_ROUTINE_PREFIX}${botId}`;
+ if (ROUTINE_ID_PATTERN.test(plain)) return plain;
+ return `${BUILTIN_FOLLOW_UP_ROUTINE_PREFIX}${createHash('sha256').update(botId).digest('hex').slice(0, 40)}`;
+}
+
/** 内置规则的保存名;渲染层按 builtin 字段本地化显示,这里只是落盘值。 */
export const FOLLOW_UP_ROUTINE_NAME = '跟进任务';
diff --git a/apps/desktop/src/main/bot-autonomy/runtime.ts b/apps/desktop/src/main/bot-autonomy/runtime.ts
index e090c8d27a..78feb1c148 100644
--- a/apps/desktop/src/main/bot-autonomy/runtime.ts
+++ b/apps/desktop/src/main/bot-autonomy/runtime.ts
@@ -16,11 +16,10 @@ import type { RoutineEngine } from '@cindy/maker-scheduler';
import {
AUTONOMY_THRESHOLDS,
HOST_SESSIONS_SOURCE_ID,
- builtinFollowUpRoutineId,
type BotGlance,
type WatchedSession,
} from '../../shared/botAutonomy.js';
-import { FOLLOW_UP_BUILTIN_VERSION, buildFollowUpRoutineInput } from './builtinRoutine.js';
+import { FOLLOW_UP_BUILTIN_VERSION, buildFollowUpRoutineInput, builtinFollowUpRoutineId } from './builtinRoutine.js';
import {
AutonomyEventLedger,
hostSessionsSource,
@@ -66,7 +65,7 @@ export class BotAutonomyRuntime {
private readonly reminded = new Map<string, number>();
private readonly ensured = new Set<string>();
/** 正在对齐的内置规则:并发的 ensure 与发布共用同一次写入。 */
- private readonly ensuring = new Map<string, Promise<void>>();
+ private readonly ensuring = new Map<string, Promise<boolean>>();
/** 伙伴上次被叫醒(任一事件被它的规则接收)的时刻;启动时视为刚叫醒过,避免重启后一起白跑。 */
private readonly lastWokenAt = new Map<string, number>();
private readonly sweptIds = new Set<string>();
@@ -78,6 +77,8 @@ export class BotAutonomyRuntime {
private lastPushAt = 0;
private lastSignature = '';
private sweeping = false;
+ /** 状态表首次观察完成(归属已读)之前不判定事件。 */
+ private started = false;
private stopped = false;
constructor(private readonly deps: AutonomyRuntimeDeps) {
@@ -91,6 +92,7 @@ export class BotAutonomyRuntime {
this.unsubscribe = this.deps.subscribeActivity(this.watch);
await this.watch.start();
if (this.stopped) return;
+ this.started = true;
await this.ensureBuiltins();
await this.evaluate();
this.schedulePush();
@@ -195,17 +197,19 @@ export class BotAutonomyRuntime {
}
}
- private ensureOne(botId: string): Promise<void> {
- if (this.stopped || !this.deps.isCurrent()) return Promise.resolve();
+ /** 返回内置规则是否已落地;失败时不记为已对齐,下次扫描或发布前重试。 */
+ private ensureOne(botId: string): Promise<boolean> {
+ if (this.stopped || !this.deps.isCurrent()) return Promise.resolve(false);
const inflight = this.ensuring.get(botId);
if (inflight) return inflight;
const id = builtinFollowUpRoutineId(botId);
if (!ROUTINE_ID_PATTERN.test(id)) {
+ // 兜底:builtinFollowUpRoutineId 对任何伙伴 id 都给出合法 id,正常不会走到这里。
this.ensured.add(botId);
this.deps.log.warn('builtin routine skipped: unsupported teammate id');
- return Promise.resolve();
+ return Promise.resolve(false);
}
- const run = (async () => {
+ const run = (async (): Promise<boolean> => {
try {
await this.deps.engine.ensureBuiltin(
botId,
@@ -214,9 +218,12 @@ export class BotAutonomyRuntime {
id,
FOLLOW_UP_BUILTIN_VERSION,
);
- if (!this.stopped) this.ensured.add(botId);
+ if (this.stopped) return false;
+ this.ensured.add(botId);
+ return true;
} catch (error) {
this.deps.log.warn('builtin routine ensure failed', { error: errorCode(error) });
+ return false;
} finally {
this.ensuring.delete(botId);
}
@@ -229,13 +236,13 @@ export class BotAutonomyRuntime {
* 发布前先确保跟进者的内置规则已落地:首次安装或新伙伴时,事件若赶在 ensure 之前发布,
* 引擎会记下回执却没有规则接收(accepted=0),这次事件就永久丢了。
*/
- private async ensureFollower(botId: string): Promise<void> {
- if (!this.ensured.has(botId)) await this.ensureOne(botId);
+ private async ensureFollower(botId: string): Promise<boolean> {
+ return this.ensured.has(botId) || await this.ensureOne(botId);
}
/** 判定并发布阈值事件。可重入:同一事件 id 在途时不重复处理。 */
async evaluate(): Promise<void> {
- if (this.stopped || !this.deps.isCurrent()) return;
+ if (!this.started || this.stopped || !this.deps.isCurrent()) return;
const now = this.deps.now();
const { due, capped } = this.ledger.evaluate(this.watch.list(), now);
for (const candidate of capped) {
@@ -260,8 +267,13 @@ export class BotAutonomyRuntime {
this.remindOwner(candidate, now);
return;
}
- await this.ensureFollower(candidate.row.followerBotId);
+ const ready = await this.ensureFollower(candidate.row.followerBotId);
if (this.stopped) return;
+ if (!ready) {
+ // 规则没落地就发布会 accepted=0 并留下回执,之后同一事件再也发不出去:不发、不结清,下次扫描重试。
+ this.deps.log.warn('autonomy event deferred: builtin routine not ready', { type: candidate.type });
+ return;
+ }
let accepted: number;
try {
const result = await this.deps.engine.publish(
@@ -307,8 +319,12 @@ 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);
+ const ready = await this.ensureFollower(botId);
if (this.stopped) return;
+ if (!ready) {
+ this.deps.log.warn('autonomy sweep deferred: builtin routine not ready');
+ continue;
+ }
try {
const result = await this.deps.engine.publish(
HOST_SESSIONS_SOURCE_ID,
diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
index d47182dc53..b98cdbe5b6 100644
--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts
+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
@@ -165,6 +165,8 @@ export class TaskWatch {
/** 主任务 id → 所属伙伴(来自伙伴资料 canonical_session_id)。 */
private canonicalOwners = new Map<string, string>();
private ownershipAt = 0;
+ /** 归属至少成功读到过一次:之前不重算、不通知,免得把启动时已有的事件按「没人跟」结清。 */
+ private ownershipLoaded = false;
private ownershipRefresh: Promise<void> | null = null;
private schedulerBotId: string | null = null;
private readonly finishedLog: FinishedRecord[] = [];
@@ -259,6 +261,10 @@ export class TaskWatch {
private queue(sessionId: string): void {
this.pending.add(sessionId);
+ this.scheduleFlush();
+ }
+
+ private scheduleFlush(): void {
if (this.flushing) return;
// 同一 tick 的多条变化合成一次读库。
this.flushing = Promise.resolve().then(() => this.flush()).finally(() => { this.flushing = null; });
@@ -270,7 +276,8 @@ export class TaskWatch {
}
private async flush(): Promise<void> {
- while (this.pending.size && !this.stopped) {
+ // 归属还没读到:只累积 pending,首次读到后再一起重算。
+ while (this.ownershipLoaded && this.pending.size && !this.stopped) {
const ids = [...this.pending];
this.pending.clear();
const now = this.deps.now();
@@ -468,6 +475,7 @@ export class TaskWatch {
}
private async refreshOwnership(force = false): Promise<void> {
+ const wasLoaded = this.ownershipLoaded;
if (this.ownershipRefresh) {
await this.ownershipRefresh;
if (!force) return;
@@ -478,6 +486,7 @@ export class TaskWatch {
if (this.stopped) return;
this.ownership = next;
this.ownershipAt = this.deps.now();
+ this.ownershipLoaded = true;
this.canonicalOwners = new Map();
for (const [botId, bot] of next.bots) {
if (bot.canonicalSessionId) this.canonicalOwners.set(bot.canonicalSessionId, botId);
@@ -502,6 +511,8 @@ export class TaskWatch {
} finally {
if (this.ownershipRefresh === run) this.ownershipRefresh = null;
}
+ // 首次读到归属(含启动时读失败、之后扫描才读到):把期间累积的变化补算一次。
+ if (!wasLoaded && this.ownershipLoaded && this.pending.size && !this.stopped) this.scheduleFlush();
}
private readOverride(): { customized: boolean; schedulerBotId: string | null } {
@@ -696,21 +707,23 @@ export class TaskWatch {
let pendingQuestion: string | null = null;
let pendingRequestId: string | null = null;
if (activity.activityPhase === 'needs-interaction') {
- if (previous && (previous.phase === 'waiting-answer' || previous.phase === 'waiting-permission')) {
+ // 每次轮询都重读挂起交互(每个等待中的远程任务每分钟一次):两次轮询之间可能从请求 A 直接换到 B。
+ let summary: ReturnType<typeof summarizeInteraction> = null;
+ try {
+ const pending = await this.deps.invokeRemote(deviceId, 'maker:get-pending-interactions', [remoteId]);
+ const first = Array.isArray(pending) ? record(pending[0])?.request ?? pending[0] : undefined;
+ summary = summarizeInteraction(first);
+ } catch {
+ // 读不到:沿用上次读到的;从没读到过时仍按「等回答」显示。
+ }
+ if (summary) {
+ interactionKind = summary.waitingFor === 'permission' ? 'permission' : 'ask_user_question';
+ pendingQuestion = summary.summary;
+ pendingRequestId = summary.requestId;
+ } else if (previous && (previous.phase === 'waiting-answer' || previous.phase === 'waiting-permission')) {
interactionKind = previous.phase === 'waiting-permission' ? 'permission' : 'ask_user_question';
pendingQuestion = previous.pendingQuestion;
pendingRequestId = previous.pendingRequestId ?? null;
- } else {
- try {
- const pending = await this.deps.invokeRemote(deviceId, 'maker:get-pending-interactions', [remoteId]);
- const first = Array.isArray(pending) ? record(pending[0])?.request ?? pending[0] : undefined;
- const summary = summarizeInteraction(first);
- interactionKind = summary?.waitingFor === 'permission' ? 'permission' : 'ask_user_question';
- pendingQuestion = summary?.summary ?? null;
- pendingRequestId = summary?.requestId ?? null;
- } catch {
- // 读不到具体问题:仍按「等回答」显示。
- }
}
}
const phase = deriveRemotePhase({ ...activity, interactionKind });
@@ -723,9 +736,13 @@ export class TaskWatch {
const updatedAt = finiteNumber(meta.updatedAt);
// 出错的时刻尽量用被控端的更新时间,重启后同一次出错仍是同一个事件 id。
const candidateSince = phase === 'errored' && updatedAt !== null && updatedAt <= now ? updatedAt : now;
- const phaseSince = phase === 'running' && previous?.phase === 'running'
+ let phaseSince = phase === 'running' && previous?.phase === 'running'
? previous.phaseSince
: nextPhaseSince(previous, phase, candidateSince);
+ // 同一任务从请求 A 换到请求 B 是新的等待:重新计时(也就是新的事件 id)。
+ if (previous?.phase === phase && previous.pendingRequestId && pendingRequestId && previous.pendingRequestId !== pendingRequestId) {
+ phaseSince = now;
+ }
const row: WatchedSession = {
sessionId: id,
deviceId,
diff --git a/apps/desktop/src/shared/botAutonomy.ts b/apps/desktop/src/shared/botAutonomy.ts
index a043dc1d3d..4f50cdc455 100644
--- a/apps/desktop/src/shared/botAutonomy.ts
+++ b/apps/desktop/src/shared/botAutonomy.ts
@@ -15,13 +15,9 @@
/** 事件源 id;在引擎每次创建后由宿主重新登记。 */
export const HOST_SESSIONS_SOURCE_ID = 'host:sessions';
-/** 内置跟进例行任务的 id 前缀;`creationId = BUILTIN_FOLLOW_UP_ROUTINE_PREFIX + botId`,幂等。 */
+/** 内置跟进例行任务的 id 前缀;完整 id 由主进程 builtinRoutine.ts 的 builtinFollowUpRoutineId 生成,幂等。 */
export const BUILTIN_FOLLOW_UP_ROUTINE_PREFIX = 'builtin-follow-up-';
-export function builtinFollowUpRoutineId(botId: string): string {
- return `${BUILTIN_FOLLOW_UP_ROUTINE_PREFIX}${botId}`;
-}
-
/** 默认总调度伙伴:出厂 Cindy 助理。未自定义时派生,不写 override。 */
export const DEFAULT_SCHEDULER_BOT_ID = 'cindy-default';
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 64d4cca15f..57ef67bcab 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -122,7 +122,7 @@ const receipt = await cindy.routines.request({
## 内置跟进例行任务
-每个在用、且本机是主力电脑的伙伴有一条宿主内置规则(`builtin: 'follow-up'`,id 固定为 `builtin-follow-up-<伙伴 id>`):
+每个在用、且本机是主力电脑的伙伴有一条宿主内置规则(`builtin: 'follow-up'`,id 固定为 `builtin-follow-up-<伙伴 id>`;伙伴 id 过长或含引擎不接受的字符时改为前缀 + 伙伴 id 的 sha256 前 40 位,同样幂等,不要从 id 反推伙伴 id):
- 触发条件:6 个事件条件(含条件兜底 `sweep`)订阅 `host:sessions`,筛选 `followerBotId` 等于自己;没有时间或间隔条件,
旧版带的 2 小时间隔条件在下一次 ensure 时被对齐掉。`silentWhenIdle` 开启,