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): scope background observation to opted-in work

zqchrise43d559768a9
diff --git a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
index 882c7b96c1..98f5fb6cd9 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/hub.test.ts
@@ -26,7 +26,7 @@ vi.mock('../../maker-host/bot-autonomy-settings-store.js', () => ({
vi.mock('../hostData.js', () => ({
readLocalSessionMetas: h.readMetas, readTaskOwnership: h.readOwnership, readBotDirectory: vi.fn(),
}));
-import { currentFollowUpEvents, setActiveBotAutonomy } from '../hub.js';
+import { currentFollowUpEvents, getBotAutonomyGlance, setActiveBotAutonomy } from '../hub.js';
const meta = (id: string, source = 'desktop'): LocalSessionMeta => ({
id, source, title: 'Completed task', workingDir: null, status: 'active', hiddenAt: null,
@@ -61,3 +61,20 @@ it('defers rather than authorizing a durable read that crossed the account bound
h.readMetas.mockImplementationOnce(async () => { h.scope = 'b'; return [meta('mine')]; });
expect(await currentFollowUpEvents('sched', events)).toBeNull();
});
+
+// Unit §6.3: UI probe versus explicit view read, including an owner change while IO waits.
+it('only refreshes remote state for an explicit scheduler workbench read and discards cross-account results', async () => {
+ const remote = vi.fn(async () => {});
+ const projection = { botId: 'sched', waiting: [] };
+ setActiveBotAutonomy({ scope: 'a', engine: {} as RoutineEngine, runtime: {
+ watch: { getSchedulerBotId: () => 'sched', refreshRemote: remote },
+ glance: () => projection,
+ } as unknown as BotAutonomyRuntime });
+ expect(await getBotAutonomyGlance('sched', undefined, false)).toBe(projection);
+ await getBotAutonomyGlance('own');
+ expect(remote).not.toHaveBeenCalled();
+ expect(await getBotAutonomyGlance('sched')).toBe(projection);
+ expect(remote).toHaveBeenCalledOnce();
+ remote.mockImplementationOnce(async () => { h.scope = 'b'; });
+ await expect(getBotAutonomyGlance('sched')).rejects.toThrow('PRECONDITION_FAILED');
+});
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 b4faf5ce15..3b558596eb 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/runtime.test.ts
@@ -438,3 +438,41 @@ describe('BotAutonomyRuntime with the routine engine', () => {
}
});
});
+
+// Unit §6.3: earlier runtime tests disabled timers and could not detect idle scans.
+// Real runtime + TaskWatch, fake clock: default-off -> delegated running -> completed.
+it('starts the scan timer only for observed work and releases it when that work ends', async () => {
+ vi.useFakeTimers();
+ const options = { schedulerOff: true, creators: {} as Record<string, string> };
+ const t = await setup(options);
+ const runtime = t.create({ registerSource: vi.fn(), publish: vi.fn(async () => ({ accepted: 0, duplicate: false })),
+ ensureBuiltin: vi.fn(async () => ({} as never)) });
+ const sweep = vi.spyOn(runtime.watch, 'sweep');
+ try {
+ await runtime.start();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(sweep).not.toHaveBeenCalled();
+ options.creators.child = 'a';
+ runtime.watch.applyActivity('child', running('child'));
+ await runtime.refreshFollowers();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(sweep).toHaveBeenCalledTimes(1);
+ runtime.watch.applyActivity('child', null);
+ await runtime.watch.settled();
+ sweep.mockClear();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(sweep).not.toHaveBeenCalled();
+ options.schedulerOff = false;
+ await runtime.refreshFollowers();
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(sweep).toHaveBeenCalledTimes(1);
+ options.schedulerOff = true;
+ await runtime.refreshFollowers();
+ sweep.mockClear();
+ await vi.advanceTimersByTimeAsync(120_000);
+ expect(sweep).not.toHaveBeenCalled();
+ } finally {
+ runtime.stop();
+ vi.useRealTimers();
+ }
+});
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 b470cd603d..ac9ef86c3c 100644
--- a/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
+++ b/apps/desktop/src/main/bot-autonomy/__tests__/taskWatch.test.ts
@@ -47,6 +47,7 @@ function harness(options: {
invokeRemote?: TaskWatchDeps['invokeRemote'];
creators?: Record<string, string>;
now?: number;
+ schedulerOff?: boolean;
} = {}) {
let now = options.now ?? 10_000;
const toolsInFlight = new Set<string>();
@@ -58,26 +59,30 @@ function harness(options: {
let ownershipReadFailures = 0;
const creators = new Map(Object.entries(options.creators ?? {}));
const invokeRemote = vi.fn(options.invokeRemote ?? (async () => { throw new Error('offline'); }));
+ const readLocalSessions = vi.fn(async (ids: readonly string[]) => {
+ if (metaReadFailures > 0) {
+ metaReadFailures -= 1;
+ throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
+ }
+ return ids.flatMap((id) => (metas.has(id) ? [metas.get(id)!] : []));
+ });
+ const readInterruptedSessions = vi.fn(async (_since: number, _limit: number, ids?: readonly string[]) => {
+ if (interruptedReadFailures > 0) {
+ interruptedReadFailures -= 1;
+ throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
+ }
+ return [...metas.values()].filter((m) => m.interrupted && (ids === undefined || ids.includes(m.id)));
+ });
+ let schedulerOff = options.schedulerOff ?? false;
+ const listRemoteDevices = vi.fn(async () => options.devices ?? null);
const watch = new TaskWatch({
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) => {
- if (metaReadFailures > 0) {
- metaReadFailures -= 1;
- throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
- }
- return ids.flatMap((id) => (metas.has(id) ? [metas.get(id)!] : []));
- },
- readInterruptedSessions: async () => {
- if (interruptedReadFailures > 0) {
- interruptedReadFailures -= 1;
- throw Object.assign(new Error('busy'), { code: 'SQLITE_BUSY' });
- }
- return [...metas.values()].filter((m) => m.interrupted);
- },
+ readLocalSessions,
+ readInterruptedSessions,
readOwnership: async () => {
if (ownershipReadFailures > 0) {
ownershipReadFailures -= 1;
@@ -89,13 +94,14 @@ function harness(options: {
responsibleByBot: new Map(),
};
},
- readSchedulerOverride: () => ({ customized: true, schedulerBotId: 'sched' }),
- listRemoteDevices: async () => options.devices ?? null,
+ readSchedulerOverride: () => ({ customized: true, schedulerBotId: schedulerOff ? null : 'sched' }),
+ listRemoteDevices,
invokeRemote,
onChange,
});
return {
- watch, metas, pending, onChange, invokeRemote, toolsInFlight,
+ watch, metas, pending, onChange, invokeRemote, toolsInFlight, readLocalSessions, readInterruptedSessions, listRemoteDevices,
+ setSchedulerOff(value: boolean) { schedulerOff = value; },
advance: (ms: number) => { now += ms; },
failMetaReads: (count: number) => { metaReadFailures = count; },
failInterruptedReads: (count: number) => { interruptedReadFailures = count; },
@@ -263,7 +269,11 @@ describe('TaskWatch ownership and startup retries', () => {
});
it('does not add interrupted tasks with an empty ownership table; it waits until ownership loads', async () => {
- const h = harness({ metas: [meta('crashed', { interrupted: true, activeTurnStartedAt: 5_000 })], creators: { crashed: 'a' } });
+ const h = harness({
+ metas: [meta('crashed', { interrupted: true, activeTurnStartedAt: 5_000 }), meta('active')],
+ snapshots: [activity('active', 'running')],
+ creators: { crashed: 'a', active: 'a' }, schedulerOff: true,
+ });
h.failOwnershipReads(1);
await h.watch.start();
expect(h.watch.get('crashed')).toBeUndefined();
@@ -271,8 +281,10 @@ describe('TaskWatch ownership and startup retries', () => {
expect(h.watch.isReady()).toBe(false);
h.advance(10 * 60_000);
await h.watch.sweep();
+ await h.watch.settled();
expect(h.watch.isReady()).toBe(true);
expect(h.watch.get('crashed')).toMatchObject({ phase: 'errored', creatorBotId: 'a', followerBotId: 'a' });
+ expect(h.watch.get('active')).toMatchObject({ phase: 'running', creatorBotId: 'a', followerBotId: 'a' });
});
it('re-reads ownership before judging a newly seen task unowned, even right after the last read', async () => {
@@ -303,12 +315,12 @@ describe('TaskWatch remote polling', () => {
},
});
await h.watch.start();
- await h.watch.sweep();
+ await h.watch.refreshRemote();
expect(h.watch.get('dev-1::r1')).toMatchObject({ phase: 'running', title: 'Old host build', online: true });
shape = 'garbage';
h.advance(AUTONOMY_THRESHOLDS.remotePollMs);
- await h.watch.sweep();
+ await h.watch.refreshRemote();
expect(h.watch.get('dev-1::r1')).toMatchObject({ online: false });
expect(h.watch.offlineDevices()).toEqual(['Studio']);
});
@@ -339,7 +351,7 @@ describe('TaskWatch remote polling', () => {
},
});
await h.watch.start();
- await h.watch.sweep();
+ await h.watch.refreshRemote();
expect(h.watch.list().map((r) => [r.sessionId, r.deviceName, r.phase, r.followerBotId, r.online])).toEqual([
// 另一台电脑上的任务只进工作台:跟进者恒为 null,由那台电脑上的伙伴跟,避免同名伙伴各跟一遍。
['dev-1::r1', 'Studio', 'running', null, true],
@@ -348,17 +360,17 @@ describe('TaskWatch remote polling', () => {
fail = true;
h.advance(AUTONOMY_THRESHOLDS.remotePollMs);
- await h.watch.sweep();
+ await h.watch.refreshRemote();
expect(h.watch.get('dev-1::r1')?.online).toBe(false);
expect(h.watch.offlineDevices()).toEqual(['Studio']);
// 退避期内不再请求那台电脑;退避有上限。
const calls = h.invokeRemote.mock.calls.length;
h.advance(AUTONOMY_THRESHOLDS.remotePollMs);
- await h.watch.sweep();
+ await h.watch.refreshRemote();
expect(h.invokeRemote.mock.calls.length).toBe(calls);
h.advance(REMOTE_BACKOFF_MAX_MS);
- await h.watch.sweep();
+ await h.watch.refreshRemote();
expect(h.invokeRemote.mock.calls.length).toBe(calls + 1);
});
@@ -383,12 +395,12 @@ describe('TaskWatch remote polling', () => {
},
});
await h.watch.start();
- await h.watch.sweep();
+ await h.watch.refreshRemote();
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();
+ await h.watch.refreshRemote();
// 新请求是新的等待:「允许」对准 B,等待时刻从这次观察算起。
expect(h.watch.get('dev-1::r1')).toMatchObject({
phase: 'waiting-permission', pendingRequestId: 'req-B', pendingQuestion: 'Write', phaseSince: h.now(),
@@ -397,3 +409,63 @@ describe('TaskWatch remote polling', () => {
});
});
+
+// Unit: §6.3 demand-driven observation. Previous coverage checked model dispatch,
+// but not reads made with follow-up off. Minimal input: one unrelated active task.
+it('does no task reads or remote polling when off, and wakes only for a new explicit delegation', async () => {
+ const h = harness({ schedulerOff: true, metas: [meta('mine'), meta('child')],
+ snapshots: [activity('mine', 'running')] });
+ await h.watch.start();
+ h.watch.applyActivity('mine', activity('mine', 'needs-interaction'));
+ await h.watch.settled();
+ h.advance(120_000);
+ await h.watch.sweep();
+ expect(h.watch.needsSweep()).toBe(false);
+ expect(h.watch.list()).toEqual([]);
+ expect(h.readLocalSessions).not.toHaveBeenCalled();
+ expect(h.readInterruptedSessions).not.toHaveBeenCalled();
+ expect(h.listRemoteDevices).not.toHaveBeenCalled();
+
+ h.creators.set('child', 'a');
+ h.watch.applyActivity('child', activity('child', 'running'));
+ // Durable delegation change uses the same refresh as the production signal.
+ await h.watch.refreshFollowers();
+ expect(h.watch.list().map(row => row.sessionId)).toEqual(['child']);
+ expect(h.watch.needsSweep()).toBe(true);
+ expect(h.readLocalSessions.mock.calls.flatMap(([ids]) => ids)).toEqual(['child']);
+ expect(h.readInterruptedSessions.mock.calls[0]?.[2]).toEqual(['child']);
+ h.watch.applyActivity('child', activity('child', 'completed'));
+ await h.watch.settled();
+ expect(h.watch.needsSweep()).toBe(false);
+ expect(h.watch.finished().map(row => row.sessionId)).toEqual(['child']);
+});
+
+it('stops global observation on opt-out and rehydrates current activity on opt-in without polling peers', async () => {
+ const h = harness({ schedulerOff: true, metas: [meta('mine')], snapshots: [activity('mine', 'running')] });
+ await h.watch.start();
+ h.setSchedulerOff(false);
+ await h.watch.refreshFollowers();
+ expect(h.watch.get('mine')?.followerBotId).toBe('sched');
+ h.setSchedulerOff(true);
+ await h.watch.refreshFollowers();
+ expect(h.watch.get('mine')).toBeUndefined();
+ expect(h.watch.needsSweep()).toBe(false);
+ h.readLocalSessions.mockClear();
+ h.advance(120_000);
+ await h.watch.sweep();
+ expect(h.readLocalSessions).not.toHaveBeenCalled();
+ expect(h.listRemoteDevices).not.toHaveBeenCalled();
+});
+
+it('keeps remote IO out of scheduled sweeps and coalesces explicit view reads', async () => {
+ const h = harness({ devices: [{ deviceId: 'dev-1', name: 'Studio', online: true, eligible: true }],
+ invokeRemote: async () => [] });
+ await h.watch.start();
+ await h.watch.sweep();
+ expect(h.listRemoteDevices).not.toHaveBeenCalled();
+ await Promise.all([h.watch.refreshRemote(), h.watch.refreshRemote()]);
+ expect(h.invokeRemote).toHaveBeenCalledTimes(1);
+ h.advance(120_000);
+ await h.watch.sweep();
+ expect(h.invokeRemote).toHaveBeenCalledTimes(1);
+});
diff --git a/apps/desktop/src/main/bot-autonomy/hostData.ts b/apps/desktop/src/main/bot-autonomy/hostData.ts
index 09f5dcf518..812ee7cab5 100644
--- a/apps/desktop/src/main/bot-autonomy/hostData.ts
+++ b/apps/desktop/src/main/bot-autonomy/hostData.ts
@@ -90,21 +90,33 @@ export async function readLocalSessionMetas(ids: readonly string[]): Promise<Loc
}
/** 启动兜底:最近被打断(开始了一轮但没有正常收尾)的在用任务。 */
-export async function readInterruptedSessionMetas(sinceMs: number, limit: number): Promise<LocalSessionMeta[]> {
+export async function readInterruptedSessionMetas(
+ sinceMs: number, limit: number, sessionIds?: readonly string[],
+): Promise<LocalSessionMeta[]> {
const db = getDbClient().drizzle;
- const rows = await db.select(metaSelection).from(sessions)
- .where(and(
- sql`${sessions.status} = 'active'`,
- isNull(sessions.hiddenAt),
- isNotNull(sessions.activeTurnStartedAt),
- gte(sessions.activeTurnStartedAt, sinceMs),
- sql`${sessions.activeTurnStartedAt} > coalesce(${sessions.lastTurnEndedAt}, 0)`,
- sql`${sessions.activeTurnStartedAt} > coalesce(${sessions.clearedAt}, 0)`,
- ))
- .orderBy(desc(sessions.activeTurnStartedAt))
- .limit(limit);
- const roles = await laneRoles(rows.map((row) => row.id));
- return rows.map((row) => toMeta(row, roles.get(row.id) ?? null));
+ // An explicit empty scope means no query, never the whole account.
+ const ids = sessionIds === undefined ? undefined : [...new Set(sessionIds)];
+ const batches = ids === undefined ? [undefined] : Array.from(
+ { length: Math.ceil(ids.length / SESSION_BATCH) }, (_, index) => ids.slice(index * SESSION_BATCH, (index + 1) * SESSION_BATCH),
+ );
+ const rows: Array<Parameters<typeof toMeta>[0]> = [];
+ for (const batch of batches) {
+ rows.push(...await db.select(metaSelection).from(sessions)
+ .where(and(
+ sql`${sessions.status} = 'active'`,
+ isNull(sessions.hiddenAt),
+ isNotNull(sessions.activeTurnStartedAt),
+ gte(sessions.activeTurnStartedAt, sinceMs),
+ sql`${sessions.activeTurnStartedAt} > coalesce(${sessions.lastTurnEndedAt}, 0)`,
+ sql`${sessions.activeTurnStartedAt} > coalesce(${sessions.clearedAt}, 0)`,
+ batch === undefined ? undefined : inArray(sessions.id, batch),
+ ))
+ .orderBy(desc(sessions.activeTurnStartedAt))
+ .limit(limit));
+ }
+ const selected = rows.sort((a, b) => (b.activeTurnStartedAt ?? 0) - (a.activeTurnStartedAt ?? 0)).slice(0, limit);
+ const roles = await laneRoles(selected.map(row => row.id));
+ return selected.map(row => toMeta(row, roles.get(row.id) ?? null));
}
/** 伙伴目录:状态、能力位 allowSchedulerFollow、是否在别的电脑运行(云端伙伴)。 */
diff --git a/apps/desktop/src/main/bot-autonomy/hub.ts b/apps/desktop/src/main/bot-autonomy/hub.ts
index df90990362..8c2230b91f 100644
--- a/apps/desktop/src/main/bot-autonomy/hub.ts
+++ b/apps/desktop/src/main/bot-autonomy/hub.ts
@@ -67,10 +67,18 @@ function emptyGlance(botId: string): BotGlance {
return { botId, scope: 'own', waiting: [], working: [], lastSweepAt: 0, doneToday: 0, offlineDevices: [] };
}
-export function getBotAutonomyGlance(botId: string, options?: GlanceOptions): BotGlance {
+export async function getBotAutonomyGlance(
+ botId: string, options?: GlanceOptions, refreshRemote = true,
+): Promise<BotGlance> {
if (isAppSessionBoundaryPending()) throwIpcError('PRECONDITION_FAILED', 'App session is switching; retry later.');
const active = current && scopeIsCurrent(current.scope) ? current.runtime : null;
- return active ? active.glance(botId, options) : emptyGlance(botId);
+ if (!active) return emptyGlance(botId);
+ const scope = activeOwnerScopeKey();
+ // The hidden auto-open probe and Agent reads use cached projections only.
+ if (refreshRemote && active.watch.getSchedulerBotId() === botId) await active.watch.refreshRemote();
+ assertOwner(scope);
+ if (current?.runtime !== active) throwIpcError('PRECONDITION_FAILED', 'Task observation changed; retry later.');
+ return active.glance(botId, options);
}
export async function getBotAutonomySettingsView(): Promise<BotAutonomySettingsView> {
diff --git a/apps/desktop/src/main/bot-autonomy/ipc.ts b/apps/desktop/src/main/bot-autonomy/ipc.ts
index d5f55e23c4..cbeec5ee3d 100644
--- a/apps/desktop/src/main/bot-autonomy/ipc.ts
+++ b/apps/desktop/src/main/bot-autonomy/ipc.ts
@@ -20,10 +20,11 @@ import {
} from './hub.js';
export function registerBotAutonomyIpc(): void {
- ipcMain.handle(BOT_AUTONOMY_IPC.glance, async (event, rawId: unknown) => {
+ ipcMain.handle(BOT_AUTONOMY_IPC.glance, async (event, rawId: unknown, refreshRemote: unknown = true) => {
const remote = isDeviceLinkInvoke();
if (!remote) assertTrustedAppRendererEvent(event);
const botId = requireString(rawId, 'botId');
+ if (typeof refreshRemote !== 'boolean') throwIpcError('INVALID_PARAMS', 'refreshRemote must be boolean');
if (remote) {
// 远程只能看远程可见的伙伴(隐藏 / 归档的伙伴只在本机恢复)。
const [profile] = await getDbClient().drizzle
@@ -37,9 +38,9 @@ export function registerBotAutonomyIpc(): void {
.select({ id: botProfiles.id, hiddenAt: botProfiles.hiddenAt, status: botProfiles.status })
.from(botProfiles);
const excludeBotIds = new Set(profiles.filter((item) => !isBotVisibleRemotely(item)).map((item) => item.id));
- return getBotAutonomyGlance(botId, { excludeBotIds });
+ return getBotAutonomyGlance(botId, { excludeBotIds }, refreshRemote);
}
- return getBotAutonomyGlance(botId);
+ return getBotAutonomyGlance(botId, undefined, refreshRemote);
});
ipcMain.handle(BOT_AUTONOMY_IPC.settingsGet, async (event) => {
diff --git a/apps/desktop/src/main/bot-autonomy/runtime.ts b/apps/desktop/src/main/bot-autonomy/runtime.ts
index 8d0bcad4fd..e288b83612 100644
--- a/apps/desktop/src/main/bot-autonomy/runtime.ts
+++ b/apps/desktop/src/main/bot-autonomy/runtime.ts
@@ -84,6 +84,7 @@ export class BotAutonomyRuntime {
private sweeping = false;
/** 状态表首次观察完成(归属已读)之前不判定事件。 */
private started = false;
+ private timersEnabled = false;
private stopped = false;
constructor(private readonly deps: AutonomyRuntimeDeps) {
@@ -103,7 +104,16 @@ export class BotAutonomyRuntime {
this.schedulePush();
// start 期间可能已被停止(换账号 / 引擎重建):不再起定时器,免得泄漏。
if (this.stopped) return;
- if (options.timers !== false) {
+ this.timersEnabled = options.timers !== false;
+ this.syncSweepTimer();
+ }
+
+ private syncSweepTimer(): void {
+ const needed = this.started && !this.stopped && this.timersEnabled && this.watch.needsSweep();
+ if (!needed && this.sweepTimer) {
+ clearInterval(this.sweepTimer);
+ this.sweepTimer = null;
+ } else if (needed && !this.sweepTimer) {
this.sweepTimer = setInterval(() => { void this.sweep(); }, SWEEP_INTERVAL_MS);
this.sweepTimer.unref?.();
}
@@ -128,6 +138,10 @@ export class BotAutonomyRuntime {
/** 一次程序级扫描;定时器与单测共用。 */
async sweep(): Promise<void> {
if (this.stopped || this.sweeping || !this.deps.isCurrent()) return;
+ if (!this.watch.needsSweep()) {
+ this.syncSweepTimer();
+ return;
+ }
this.sweeping = true;
try {
if (!this.unsubscribe) this.unsubscribe = this.deps.subscribeActivity(this.watch);
@@ -139,6 +153,7 @@ export class BotAutonomyRuntime {
this.deps.log.warn('autonomy sweep failed', { error: errorCode(error) });
} finally {
this.sweeping = false;
+ this.syncSweepTimer();
}
}
@@ -182,6 +197,7 @@ export class BotAutonomyRuntime {
private onWatchChange(): void {
if (this.stopped) return;
+ this.syncSweepTimer();
this.schedulePush();
// 出错 / 用量上限 / 做完是即时事件:同一 tick 的变化合并后判定一次。
if (this.evaluateTimer) return;
diff --git a/apps/desktop/src/main/bot-autonomy/service.ts b/apps/desktop/src/main/bot-autonomy/service.ts
index a16831c037..151ba98abd 100644
--- a/apps/desktop/src/main/bot-autonomy/service.ts
+++ b/apps/desktop/src/main/bot-autonomy/service.ts
@@ -116,9 +116,9 @@ function startRuntime(engine: RoutineEngine, scope: string): void {
assertScope(scope);
return rows;
},
- readInterruptedSessions: async (sinceMs, limit) => {
+ readInterruptedSessions: async (sinceMs, limit, sessionIds) => {
assertScope(scope);
- const rows = await readInterruptedSessionMetas(sinceMs, limit);
+ const rows = await readInterruptedSessionMetas(sinceMs, limit, sessionIds);
assertScope(scope);
return rows;
},
diff --git a/apps/desktop/src/main/bot-autonomy/taskWatch.ts b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
index 4dd8339e3f..7d279c95a7 100644
--- a/apps/desktop/src/main/bot-autonomy/taskWatch.ts
+++ b/apps/desktop/src/main/bot-autonomy/taskWatch.ts
@@ -1,11 +1,11 @@
/**
* 伙伴自主跟进 · 层 0 状态表(程序级,不经模型)。
*
- * 一张表装下本机与已授权在线电脑上的全部任务:
+ * 只观察明确委派的本机任务;开启总调度后才扩大到本机全部任务:
* - 本机:灵动岛活动订阅(运行 / 等交互 / 完成 / 出错)+ 输入协调器投影(出错 / 用量上限等待)
* + 挂起交互(等你的那句话)+ 数据库兜底(标题、隐藏 / 归档、伙伴专线排除、启动时被打断的任务)。
- * - 远程:仅当存在在线、已开启远程控制且本机允许控制的同账号电脑时,按
- * `AUTONOMY_THRESHOLDS.remotePollMs` 轮询 `maker:list-active` v2,再按需读标题与挂起交互。
+ * - 远程:查看总调度工作台时才读取已授权电脑的 `maker:list-active` v2,再按需读标题与挂起交互;
+ * `AUTONOMY_THRESHOLDS.remotePollMs` 是读取节流,不注册后台轮询。
* 失败按设备指数退避(上限 15 分钟),离线电脑的行保留最后状态并标 online=false。
* 远程行只进工作台(给主人看与允许):followerBotId 恒为 null,不发事件、不发系统提醒——
* 那台电脑上的任务由那台电脑上的伙伴跟,避免两台电脑的同名伙伴各跟一遍。
@@ -21,6 +21,7 @@ import {
} from '../../shared/botAutonomy.js';
import {
deriveFollowerBotId,
+ isFollowerAvailable,
resolveSchedulerBotId,
type FollowerBotDirectory,
type FollowerBotState,
@@ -109,7 +110,7 @@ export interface TaskWatchDeps {
isToolCallInFlight(sessionId: string): boolean;
getPendingInteractions(sessionId: string): readonly unknown[];
readLocalSessions(ids: readonly string[]): Promise<LocalSessionMeta[]>;
- readInterruptedSessions(sinceMs: number, limit: number): Promise<LocalSessionMeta[]>;
+ readInterruptedSessions(sinceMs: number, limit: number, sessionIds?: readonly string[]): Promise<LocalSessionMeta[]>;
readOwnership(): Promise<OwnershipSnapshot>;
readSchedulerOverride(): { customized: boolean; schedulerBotId: string | null };
/** null = 当前不能用设备互联(未登录 / 换号中 / 无 device-link)。 */
@@ -185,6 +186,7 @@ export class TaskWatch {
private ownershipAt = 0;
/** 归属至少成功读到过一次:之前不重算、不通知,免得把启动时已有的事件按「没人跟」结清。 */
private ownershipLoaded = false;
+ private ownershipReadFailures = 0;
/** 启动兜底(上一轮被打断的任务)是否已读成功;读失败时在之后的扫描里重试。 */
private interruptedSeeded = false;
private ownershipRefresh: Promise<void> | null = null;
@@ -193,6 +195,7 @@ export class TaskWatch {
private readonly remote = new Map<string, RemoteDeviceState>();
private directory: { at: number; devices: RemoteDeviceTarget[] } | null = null;
private remotePolling = false;
+ private remoteRefresh: Promise<void> | null = null;
private lastSweepAt = 0;
private stopped = false;
@@ -239,7 +242,7 @@ export class TaskWatch {
await this.refreshOwnership();
for (const snapshot of this.deps.getActivitySnapshots()) {
this.local.set(snapshot.sessionId, { ...this.factsFor(snapshot.sessionId), activity: snapshot });
- this.pending.add(snapshot.sessionId);
+ if (this.observesLocal(snapshot.sessionId) || !this.ownershipLoaded) this.pending.add(snapshot.sessionId);
}
// 归属没读到时不补「上一轮被打断」的任务:空归属会把它判成没人开、先落到总调度;留给读到归属后的扫描。
if (this.ownershipLoaded) await this.seedInterrupted();
@@ -254,8 +257,10 @@ export class TaskWatch {
applyActivity(sessionId: string, current: SessionActivitySnapshot | null): void {
if (this.stopped) return;
- this.local.set(sessionId, { ...this.factsFor(sessionId), activity: current });
- this.queue(sessionId);
+ const facts = { ...this.factsFor(sessionId), activity: current };
+ if (!current && !facts.inputError && !facts.usageLimitWait) this.local.delete(sessionId);
+ else this.local.set(sessionId, facts);
+ if (this.observesLocal(sessionId) || !this.ownershipLoaded) this.queue(sessionId);
}
applyInputProjection(projection: BotAutonomyInputProjection): void {
@@ -272,7 +277,7 @@ export class TaskWatch {
// 没有任何活动、也没有出错 / 等待的会话不进表(投影会为每个会话广播)。
if (!this.local.has(projection.sessionId) && !inputError && !usageLimitWait) return;
this.local.set(projection.sessionId, { ...facts, inputError, inputErrorReason, usageLimitWait });
- this.queue(projection.sessionId);
+ if (this.observesLocal(projection.sessionId) || !this.ownershipLoaded) this.queue(projection.sessionId);
}
/** 设置变化(总调度换人)或资料变化后:重读归属并重算全部跟进者。 */
@@ -283,9 +288,43 @@ export class TaskWatch {
async refreshFollowers(): Promise<void> {
await this.refreshOwnership(true);
+ if (this.stopped) return;
+ for (const snapshot of this.deps.getActivitySnapshots()) {
+ this.local.set(snapshot.sessionId, { ...this.factsFor(snapshot.sessionId), activity: snapshot });
+ }
+ for (const id of this.local.keys()) if (this.observesLocal(id)) this.pending.add(id);
+ if (!this.interruptedSeeded && this.ownershipLoaded) await this.seedInterrupted();
+ await this.flush();
this.deps.onChange();
}
+ /** No timer for unassigned owner work or a completed delegation. Events can wake us again. */
+ needsSweep(): boolean {
+ if (this.stopped) return false;
+ if (!this.ownershipLoaded) return this.ownershipReadFailures <= 3 || this.pending.size > 0;
+ return this.hasScheduler()
+ || (!this.interruptedSeeded && this.ownership.creatorBySession.size > 0)
+ || [...this.pending].some(id => this.observesLocal(id))
+ || [...this.rows.values()].some(row => row.deviceId === null && row.phase !== 'finished');
+ }
+
+ private hasScheduler(): boolean {
+ return this.schedulerBotId !== null && isFollowerAvailable(this.ownership.bots.get(this.schedulerBotId));
+ }
+
+ private observesLocal(id: string): boolean {
+ return this.hasScheduler() || this.ownership.creatorBySession.has(id);
+ }
+
+ /** UI reads opt into remote IO explicitly. Concurrent windows share the same bounded read. */
+ refreshRemote(): Promise<void> {
+ if (this.stopped) return Promise.resolve();
+ if (!this.remoteRefresh) {
+ this.remoteRefresh = this.pollRemote(this.deps.now()).finally(() => { this.remoteRefresh = null; });
+ }
+ return this.remoteRefresh;
+ }
+
private factsFor(sessionId: string): LocalFacts {
return this.local.get(sessionId) ?? { activity: null, inputError: null, inputErrorReason: null, usageLimitWait: false };
}
@@ -293,12 +332,17 @@ export class TaskWatch {
private queue(sessionId: string): void {
this.pending.add(sessionId);
this.scheduleFlush();
+ this.deps.onChange();
}
private scheduleFlush(): void {
if (this.flushing) return;
// 同一 tick 的多条变化合成一次读库。
- this.flushing = Promise.resolve().then(() => this.flush()).finally(() => { this.flushing = null; });
+ this.flushing = Promise.resolve().then(() => this.flush()).finally(() => {
+ this.flushing = null;
+ // Even a filtered/unknown task can consume the last pending read without changing a row.
+ if (!this.stopped) this.deps.onChange();
+ });
}
/** 测试与 service 用:等当前排队的重算落定。 */
@@ -309,7 +353,7 @@ export class TaskWatch {
private async flush(): Promise<void> {
// 归属还没读到:只累积 pending,首次读到后再一起重算。
while (this.ownershipLoaded && this.pending.size && !this.stopped) {
- const ids = [...this.pending];
+ const ids = [...this.pending].filter(id => this.observesLocal(id));
this.pending.clear();
const now = this.deps.now();
const unknown = ids.filter((id) => !this.meta.has(id)
@@ -360,7 +404,7 @@ export class TaskWatch {
private recomputeLocal(sessionId: string, now: number): { changed: boolean; unowned: boolean } {
const meta = this.meta.get(sessionId);
const previous = this.rows.get(sessionId) ?? null;
- if (!this.isWatchable(meta)) {
+ if (!this.observesLocal(sessionId) || !this.isWatchable(meta)) {
this.interrupted.delete(sessionId);
return { changed: this.rows.delete(sessionId), unowned: false };
}
@@ -454,15 +498,22 @@ export class TaskWatch {
private async seedInterrupted(): Promise<void> {
const now = this.deps.now();
+ const ownership = this.ownership;
+ const schedulerBotId = this.schedulerBotId;
let rows: LocalSessionMeta[];
try {
- rows = await this.deps.readInterruptedSessions(now - INTERRUPTED_LOOKBACK_MS, INTERRUPTED_LIMIT);
+ const ids = this.hasScheduler() ? undefined : [...this.ownership.creatorBySession.keys()];
+ rows = ids?.length === 0 ? []
+ : await this.deps.readInterruptedSessions(now - INTERRUPTED_LOOKBACK_MS, INTERRUPTED_LIMIT, ids);
} catch (error) {
this.deps.log.warn('interrupted session seed failed', { error: errorCode(error) });
return;
}
+ // A read started for an older scope cannot finish recovery for a newly selected scope.
+ if (this.stopped || ownership !== this.ownership || schedulerBotId !== this.schedulerBotId) return;
this.interruptedSeeded = true;
for (const meta of rows) {
+ if (!this.observesLocal(meta.id)) continue;
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;
@@ -524,6 +575,7 @@ export class TaskWatch {
private async refreshOwnership(force = false): Promise<void> {
const wasLoaded = this.ownershipLoaded;
+ const previousScope = JSON.stringify([this.hasScheduler(), [...this.ownership.creatorBySession.keys()]]);
if (this.ownershipRefresh) {
await this.ownershipRefresh;
if (!force) return;
@@ -535,15 +587,26 @@ export class TaskWatch {
this.ownership = next;
this.ownershipAt = this.deps.now();
this.ownershipLoaded = true;
+ this.ownershipReadFailures = 0;
this.canonicalOwners = new Map();
for (const [botId, bot] of next.bots) {
if (bot.canonicalSessionId) this.canonicalOwners.set(bot.canonicalSessionId, botId);
}
} catch (error) {
+ this.ownershipReadFailures += 1;
this.deps.log.warn('ownership read failed', { error: errorCode(error) });
}
this.schedulerBotId = resolveSchedulerBotId(this.readOverride(), this.ownership.bots);
+ if (previousScope !== JSON.stringify([this.hasScheduler(), [...this.ownership.creatorBySession.keys()]])) {
+ this.interruptedSeeded = false;
+ }
for (const row of this.rows.values()) {
+ if (row.deviceId === null && !this.observesLocal(row.sessionId)) {
+ this.rows.delete(row.sessionId);
+ this.meta.delete(row.sessionId);
+ this.interrupted.delete(row.sessionId);
+ continue;
+ }
if (row.deviceId === null) {
const meta = this.meta.get(row.sessionId);
row.canonicalOfBotId = this.canonicalOwner(row.sessionId, meta);
@@ -574,9 +637,9 @@ export class TaskWatch {
// ─── 周期扫描 ──────────────────────────────────────────────────────────
- /** 程序级心跳:刷新归属与标题、清理做完的行、按需轮询远程电脑。阈值事件由 service 随后判定。 */
+ /** 有观察需求时刷新本机归属与标题、清理做完的行。远程读取由工作台显式触发。 */
async sweep(): Promise<void> {
- if (this.stopped) return;
+ if (this.stopped || !this.needsSweep()) return;
const now = this.deps.now();
if (now - this.ownershipAt >= OWNERSHIP_REFRESH_MS) await this.refreshOwnership();
await this.refreshLocalMeta();
@@ -602,7 +665,6 @@ export class TaskWatch {
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);
}
- await this.pollRemote(now);
if (this.stopped) return;
this.lastSweepAt = now;
this.deps.onChange();
diff --git a/apps/desktop/src/main/maker-ipc/botDelegationService.ts b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
index a66ee84499..fb401dc99b 100644
--- a/apps/desktop/src/main/maker-ipc/botDelegationService.ts
+++ b/apps/desktop/src/main/maker-ipc/botDelegationService.ts
@@ -1,3 +1,4 @@
+import { signalBotAutonomyBotsChanged } from '../bot-autonomy/botsChangedSignal.js';
import { formatForwardedRequest, captureAgentRequest, type CapturedAgentRequest } from './forwardedRequest.js';
import { readForwardedRequestSource, type AgentRequestReceipt, type ForwardedRequestSource } from '../../shared/forwardedRequest.js';
import { openSession } from '../localDb/sessionOpening.js';
@@ -696,6 +697,7 @@ export function createBotDelegationService(deps: BotDelegationServiceDeps) {
};
const emitChanged = (payload: BotDelegationChangedPayload): void => {
+ signalBotAutonomyBotsChanged();
deps.onChanged?.(payload);
};
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b1bd916750..22862919a4 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5773,8 +5773,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
},
/** 伙伴自主跟进:工作台「一眼」与「自动跟进所有任务」设置(shared/botAutonomy.ts)。 */
autonomy: {
- glance: (botId: string): Promise<import('../shared/botAutonomy').BotGlance> =>
- ipcRenderer.invoke('local-db:bots:autonomy:glance', botId),
+ glance: (botId: string, refreshRemote = true): Promise<import('../shared/botAutonomy').BotGlance> =>
+ ipcRenderer.invoke('local-db:bots:autonomy:glance', botId, refreshRemote),
getSettings: (): Promise<import('../shared/botAutonomy').BotAutonomySettingsView> =>
ipcRenderer.invoke('local-db:bots:autonomy:settings-get'),
setSettings: (
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 4ac130f868..00d26de683 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/BotWorkbenchView.test.tsx
@@ -51,6 +51,9 @@ vi.mock('@/lib/makerTransport', () => ({ makerApiForDevice: m.makerApiForDevice
import { BotWorkbench } from '../BotWorkbench';
import { allowGlanceRow } from '../botGlance';
+import '../../right-sidebar/plugins/bot-workbench';
+import { getTabKind } from '../../right-sidebar/registry';
+import type { TabKindHostContext } from '../../right-sidebar/types';
type Listener = (payload: { botIds?: string[] }) => void;
let listeners: Listener[] = [];
@@ -58,6 +61,27 @@ const glanceApi = vi.fn<(botId: string) => Promise<BotGlance>>();
const localMaker = { getPendingInteractions: vi.fn(), resolveInteraction: vi.fn() };
const remoteInvoke = vi.fn();
+// Unit: inactive tabs stay mounted in the sidebar shell. Reading their glance used to
+// trigger remote IO while hidden; exercise the registered body and real data hook.
+it('reads remote state only while the workbench tab is visible', async () => {
+ glanceApi.mockResolvedValue(glance());
+ const Body = getTabKind('bot-workbench')!.TabBody;
+ const ctx: TabKindHostContext = {
+ tabId: 'workbench', sessionId: 'main', workdir: '', remoteHostId: null,
+ deviceLinkDeviceId: null, patchState: vi.fn(), onVisibilityChange: vi.fn(),
+ setCloseInterceptor: () => () => {},
+ };
+ const props = { state: { botId: 'bot-1' }, ctx };
+ const view = render(<Body {...props} active={false} shellVisible />);
+ expect(glanceApi).not.toHaveBeenCalled();
+ view.rerender(<Body {...props} active shellVisible={false} />);
+ expect(glanceApi).not.toHaveBeenCalled();
+ view.rerender(<Body {...props} active shellVisible />);
+ await waitFor(() => expect(glanceApi).toHaveBeenCalledWith('bot-1', true));
+ view.rerender(<Body {...props} active shellVisible={false} />);
+ expect(listeners).toHaveLength(0);
+});
+
function row(patch: Partial<GlanceRow>): GlanceRow {
return {
sessionId: 's1',
@@ -181,6 +205,7 @@ it('re-reads only on changes for this teammate', async () => {
act(() => listeners.forEach((cb) => cb({ botIds: ['bot-2'] })));
expect(glanceApi).toHaveBeenCalledTimes(1);
+ expect(glanceApi).toHaveBeenLastCalledWith('bot-1', true);
act(() => listeners.forEach((cb) => cb({ botIds: ['bot-1'] })));
expect(await screen.findByText('新问题')).toBeTruthy();
});
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx
index 222715ba71..fcbade92f5 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botWorkbenchLifecycle.test.tsx
@@ -78,6 +78,8 @@ it('does not open on the first visit, opens once when something starts waiting,
await waitFor(() => expect(view.getByText('chat')).toBeTruthy());
await waitFor(() => expect(glance).toHaveBeenCalledOnce());
expect(getBucket('chat').tabs).toEqual([]);
+ // §6.3: the hidden auto-open check must not start cross-device reads.
+ expect(glance).toHaveBeenLastCalledWith('bot', false);
expect(visibility).not.toHaveBeenCalled();
await hostChanged(waitingCount(1));
diff --git a/apps/desktop/src/renderer/features/bots/botGlance.ts b/apps/desktop/src/renderer/features/bots/botGlance.ts
index f9f30f8645..4fdba9c2a4 100644
--- a/apps/desktop/src/renderer/features/bots/botGlance.ts
+++ b/apps/desktop/src/renderer/features/bots/botGlance.ts
@@ -73,13 +73,13 @@ export function rebaseGlance(glance: BotGlance, host: GlanceHost): BotGlance {
};
}
-function readGlance(botId: string, hostDeviceId: string | null): Promise<BotGlance> {
+function readGlance(botId: string, hostDeviceId: string | null, refreshRemote: boolean): Promise<BotGlance> {
if (hostDeviceId) {
- return window.electronAPI.deviceLink.invoke(hostDeviceId, BOT_AUTONOMY_IPC.glance, [botId]) as Promise<BotGlance>;
+ return window.electronAPI.deviceLink.invoke(hostDeviceId, BOT_AUTONOMY_IPC.glance, refreshRemote ? [botId] : [botId, false]) as Promise<BotGlance>;
}
const api = window.electronAPI?.localDb?.bots?.autonomy;
if (!api) return Promise.reject(new Error('Bot autonomy is not available'));
- return api.glance(botId);
+ return api.glance(botId, refreshRemote);
}
function subscribeGlance(botId: string, hostDeviceId: string | null, onChange: () => void): () => void {
@@ -99,7 +99,7 @@ function subscribeGlance(botId: string, hostDeviceId: string | null, onChange: (
}
/** 一位伙伴的 glance;`enabled = false` 时不读不订阅(例如还没确认任务归属)。 */
-export function useBotGlance(botId: string, host: GlanceHost, enabled = true): GlanceState {
+export function useBotGlance(botId: string, host: GlanceHost, enabled = true, refreshRemote = true): GlanceState {
const hostDeviceId = host.deviceId;
const [state, setState] = useState<GlanceState>({ glance: null, failed: false, fetchedAt: 0 });
useEffect(() => {
@@ -110,7 +110,7 @@ export function useBotGlance(botId: string, host: GlanceHost, enabled = true): G
const owner = getDataOwnerGeneration();
const load = () => {
const current = ++request;
- readGlance(botId, hostDeviceId)
+ readGlance(botId, hostDeviceId, refreshRemote)
.then((glance) => {
if (!alive || current !== request || !isDataOwnerGenerationCurrent(owner)) return;
setState({ glance, failed: false, fetchedAt: Date.now() });
@@ -127,7 +127,7 @@ export function useBotGlance(botId: string, host: GlanceHost, enabled = true): G
alive = false;
off();
};
- }, [botId, enabled, hostDeviceId]);
+ }, [botId, enabled, hostDeviceId, refreshRemote]);
return state;
}
diff --git a/apps/desktop/src/renderer/features/bots/useBotWorkbenchAutoOpen.ts b/apps/desktop/src/renderer/features/bots/useBotWorkbenchAutoOpen.ts
index 9a6f359a90..2dc39dfa76 100644
--- a/apps/desktop/src/renderer/features/bots/useBotWorkbenchAutoOpen.ts
+++ b/apps/desktop/src/renderer/features/bots/useBotWorkbenchAutoOpen.ts
@@ -12,7 +12,7 @@ const LOCAL_HOST: GlanceHost = { deviceId: null };
*/
export function useBotWorkbenchAutoOpen(sessionId: string | undefined, botId: string | undefined): void {
const enabled = Boolean(sessionId && botId);
- const { glance } = useBotGlance(botId ?? '', LOCAL_HOST, enabled);
+ const { glance } = useBotGlance(botId ?? '', LOCAL_HOST, enabled, false);
// 换了伙伴时上一位的投影可能还在这一帧里,只认这位伙伴自己的。
const waiting = enabled && glance && glance.botId === botId ? glance.waiting.length : null;
const previous = useRef<number | null>(null);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
index 1d69613b65..e6c0394e59 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/bot-workbench/index.tsx
@@ -26,8 +26,8 @@ const plugin: TabKindPlugin<BotWorkbenchTabState> = {
},
TabPillTitle: ({ t }) => <>{t('bots.workbench.title')}</>,
TabPillIcon: () => <LayoutGrid size={13} />,
- TabBody: ({ state, ctx }: TabKindBodyProps<BotWorkbenchTabState>) =>
- state.botId && ctx.deviceLinkDeviceId !== undefined && !ctx.remoteHostId ? (
+ TabBody: ({ state, ctx, active = true, shellVisible = true }: TabKindBodyProps<BotWorkbenchTabState>) =>
+ active && shellVisible && state.botId && ctx.deviceLinkDeviceId !== undefined && !ctx.remoteHostId ? (
<BotWorkbench
key={`${ctx.deviceLinkDeviceId ?? ''}:${state.botId}`}
botId={state.botId}
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index b6a04f9485..19f5a5a902 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4976,7 +4976,7 @@ interface ElectronAPI {
};
/** 伙伴自主跟进:工作台「一眼」投影与账号级「自动跟进所有任务」设置(shared/botAutonomy.ts)。 */
autonomy: {
- glance: (botId: string) => Promise<import('../shared/botAutonomy').BotGlance>;
+ glance: (botId: string, refreshRemote?: boolean) => Promise<import('../shared/botAutonomy').BotGlance>;
getSettings: () => Promise<import('../shared/botAutonomy').BotAutonomySettingsView>;
setSettings: (
patch: import('../shared/botAutonomy').BotAutonomySettings,
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 6db3647479..d5c1954d4b 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -113,6 +113,7 @@ const receipt = await cindy.routines.request({
[伙伴运行时合同 §6.3](./cindy-bots-runtime.md))。只为本机任务发:另一台电脑上的任务由那台电脑上的伙伴跟,这里只进工作台。它与插件来源走同一个引擎、同一套限速、24 小时回执去重和不可信数据封装,区别是:
- 来源 id 由宿主固定,插件不能冒充;事件源表只在内存里,例行任务引擎每次创建后(含换账号、重建)由宿主重新登记。
+- 注册事件源不等于开启后台扫描。默认只观察明确委派的工作;全局跟进须主动开启。没有待跟进委派且全局跟进关闭时释放扫描定时器,远程状态只在查看工作台时读取。
- 事件 `data` 只有扁平字段:`sessionId`、`deviceId`、`deviceName`、`title`、`phase`、`minutes`、`question`、`error`、
`creatorBotId`、`followerBotId`、`occurrence`;`subject` 是任务 id(`sweep` 是伙伴 id,任务相关字段为空串)。只带标题与一句话摘要,不带工具入参、计划正文、
代输入值或工作目录。
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 877774ea4d..1d8b22847c 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -631,7 +631,7 @@ Session 任务遵守同一套机制与呈现契约:
- 用户正在看对应任务时不发外部通知;后台时仍按全局桌面、飞书、移动端与灵动岛去重规则投递。
- 伙伴私聊的结构化入口不触发通知;接收伙伴随后产出的正常回复才有提醒价值。
- 自主跟进(6.3):内置「跟进」例行任务那一轮的回复不自动外发(`silentWhenIdle`),伙伴要主人知道的事显式调用本轮
- 通知,沿用例行任务的结果通知通道与开关。没人跟(无总调度、跟进者暂停、跟进规则被暂停)的本机任务「等你」满 5 分钟时,
+ 通知,沿用例行任务的结果通知通道与开关。已纳入观察范围、但没人跟(跟进者暂停、跟进规则被暂停)的本机任务「等你」满 5 分钟时,
宿主直接发一次系统提醒(桌面 `needs-reply` + 手机推送,事件 id 去重;主窗口在前台不弹桌面通知),不经模型。
- 点击伙伴任务的通知必须回到伙伴自己的主任务或历史任务路由,不能把隐藏的 `source=bot`
Session 丢进普通任务列表。群专线回到它所在的群,历史任务进只读历史路由;委派执行进入普通
@@ -664,11 +664,14 @@ Session 任务遵守同一套机制与呈现契约:
#### 6.3.1 三层
-- **层 0 宿主观察(程序级,不经模型)**:一张状态表装下本机与已授权在线电脑上的全部任务。本机来源是灵动岛活动
+- **层 0 宿主观察(程序级,不经模型)**:默认只观察明确委派或逐任务接手的本机任务;明确开启总调度后才观察本机全部任务。本机来源是灵动岛活动
订阅(运行 / 等交互 / 完成 / 出错)、输入协调器投影(出错、撞上用量上限且宿主已排好自动继续)、挂起交互(等你的
- 那句话)与数据库兜底(标题、隐藏 / 归档、启动时上一轮被打断的任务)。远程只在存在在线、已开启远程控制、本机允许
- 控制且版本支持后台只读请求的同账号电脑时,每 60 秒经后台链路读 `maker:list-active` v2,再按需读标题与挂起交互;
- 失败按电脑指数退避(上限 15 分钟),离线电脑的行保留最后状态并标离线,24 小时后丢弃。手机不进轮询。
+ 那句话)与数据库兜底(标题、隐藏 / 归档、启动时上一轮被打断的任务)。本机每 30 秒检查只在有待跟进的委派工作或已开启总调度时运行;没有需求则释放定时器,新委派和设置变化通过事件重新启动。启动归属读取失败可有限重试,有待处理事件时保留恢复机会。
+ 全局跟进关闭时,启动恢复也只查询明确委派的任务,不读无关任务的元数据和挂起交互。普通任务自身的通知链保持不变。
+ 远程只在查看总调度工作台时,经既有授权后台只读链路读 `maker:list-active` v2,再按需读标题与挂起交互;没有常驻远程轮询。
+ 同时读取合并、每台电脑至少间隔 60 秒,失败按电脑指数退避(上限 15 分钟);离线电脑的行保留最后状态并标离线,下次读取时清理超过 24 小时的离线行。手机不进查询目标。
+ 隐藏或收起的工作台不读取;自动打开判断只读已有投影,不触发远程查询。
+ 既有 glance IPC 增加可选的第二参数 `refreshRemote`:省略仍按显式查看处理,`false` 只读投影;返回结构不变。新版查看旧 Host 仍发原 `[botId]`,后台探测的附加 `false` 由旧 Host 忽略并保持原缓存读取。
不进表:伙伴的历史 / 群 / IM 渠道专线、隐藏或归档的任务、Orca worker、复核任务;
伙伴的主任务(资料 `canonical_session_id` 或 canonical 链接)进表,但**永远不是该伙伴自己的事件对象**(不发
stuck / waiting / errored / usage-limit / finished / sweep 给它自己——否则欢迎轮出错会把跟进排进正在失败的主任务里
@@ -693,7 +696,7 @@ Session 任务遵守同一套机制与呈现契约:
- 没有伙伴来源的本机任务(主人自己开的)由总调度跟。
- 共享给访客的任务(来源 `shared`)没人跟:里面有账号外的人发的话,不能借事件叫醒以主人权限运行的伙伴。它只进工作台,「等你」超过阈值时直接提醒主人;任务摘要不带对话原文(标 `shared_task`),工作台工具也不能继续它(`TASK_SHARED_WITH_GUESTS`)。
- 另一台电脑上的任务恒为 null:由那台电脑上的伙伴跟(见 6.3.1),这台电脑只在工作台里显示。
-- 没有可用总调度时为 null:不叫醒任何伙伴,只在工作台里能看到;本机任务「等你」超过阈值时宿主直接发系统提醒
+- 已纳入观察范围但没有可用跟进者时为 null:不叫醒任何伙伴;范围内的本机任务「等你」超过阈值时宿主直接发系统提醒
(桌面通知 + 手机推送,主窗口在前台时不弹桌面通知),同一事件只提醒一次。跟进者的内置规则被主人暂停时同样处理。
- 设置「自动跟进所有任务」:账号级、只存 override(`bot-autonomy-settings.json` 的 `schedulerBotId`,显式 null = 关掉);
恢复默认 = 删除 override。目标伙伴必须存在且未归档;它被归档后关闭,不擅自转交其他伙伴。本机 IPC 仅可信界面使用;远程和手机经同账号的伙伴设置资源、绑定 owner/controller/revision 的动作修改。
@@ -892,9 +895,9 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘
一律被宿主拒绝。
- 自主跟进:任务卡住 10 分钟 / 等你 5 分钟 / 出错 / 用量上限 / 做完时,只有跟进者的内置「跟进」规则被叫醒一次;
例行任务引擎重建后 `host:sessions` 事件源重新登记;内置规则不能删除、不能改内容、只能暂停;没人跟的本机「等你」
- 只提醒主人一次;「自动跟进所有任务」未自定义时跟随在用的 Cindy 助理,显式关掉后保持关闭,恢复默认删除 override;
+ 只提醒主人一次;「自动跟进所有任务」默认关闭,恢复默认删除 override 并回到关闭;无总调度、无待跟进委派时不起扫描定时器;
总调度工作台看全设备任务,其它伙伴只看自己开的或接手的任务;已授权的远程控制端读工作台时,与远程任务列表同一口径,隐藏 / 归档伙伴开的、它的主任务与它在跟的任务一律不返回;远程任务只进工作台、不叫醒伙伴也不提醒;没有待处理
- 任务的伙伴不被兜底叫醒,有待处理任务时距上次叫醒满 2 小时才发一次 `sweep`;远程电脑轮询失败退避且标离线,
+ 任务的伙伴不被兜底叫醒,有待处理任务时距上次叫醒满 2 小时才发一次 `sweep`;远程电脑按查看需求读取,失败退避且标离线,
不形成重试风暴。
- 通用 session 工具及历史查询不再按伙伴来源分档;账号、实例、目标与队列归属检查保持有效。
- 伙伴主聊天通知优先使用当前已完成轮次的最终回复纯文本摘要;Markdown 转为可读文字后才截断,遵守推送协议的 UTF-16 长度上限且不拆分代理对。无可用正文时使用本地化新回复兜底;沿用通知开关及系统预览隐私,静默自动化仍不外发。普通任务保留任务通知语义。