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(scheduler): recheck remote routes before dispatch

Yuewei-LL72bf584ee44a
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
index d4a6562a18..873c035a16 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/makerSendTransaction.test.ts
@@ -359,17 +359,23 @@ describe('MCP App message authorization', () => {
expect(dispatch).not.toHaveBeenCalled();
});
- it('rechecks card authorization after accepted persistence and blocks vendor dispatch', async () => {
+ // PR #6830 / unit: route validation adds an await after persistence; card
+ // revocation during that await must still block the actual dispatch.
+ it.each(['persistence', 'route'] as const)('rechecks card authorization after %s and blocks vendor dispatch', async (stage) => {
let visible = true;
const dispatch = vi.fn();
const guard = vi.fn(async () => { if (!visible) throw new Error('MCP_APP_CARD_UNAVAILABLE'); });
const { deps, session } = createDeps({
prepareProductTurn: () => dispatch,
- createDbMessage: vi.fn(async () => { visible = false; }),
+ createDbMessage: vi.fn(async () => { if (stage === 'persistence') visible = false; }),
+ assertScheduledDispatchRoute: async () => { if (stage === 'route') visible = false; },
});
await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'App text', undefined, {
[AUTO_REVIEW_DELEGATED_CONTINUATION]: true,
[MCP_APP_MESSAGE_GUARD]: guard,
+ ...(stage === 'route' ? {
+ origin: { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'Follow up', runId: 'r' },
+ } : {}),
persistUserMessage: { clientId: 'app-input', content: 'App text' },
})).rejects.toThrow('MCP_APP_CARD_UNAVAILABLE');
expect(guard).toHaveBeenCalledTimes(2);
@@ -3628,6 +3634,32 @@ describe('session-agent-switch handoff injection', () => {
}
});
+ // PR #6830 / unit: the accepted queue callback runs before history/vision
+ // preparation. Existing cases changed only permissions. A remote source
+ // suspended during history loading must reject the transaction before vendor send.
+ it('rejects a scheduled remote route disabled after acceptance', async () => {
+ let suspended = false;
+ const vendor = vi.fn();
+ const { deps, session } = createDeps({
+ readAutoReviewHistory: async () => { suspended = true; return []; },
+ assertScheduledDispatchRoute: async (sessionId) => {
+ expect(sessionId).toBe('session-1');
+ if (suspended) throw new Error('REMOTE_AGENT_UNAVAILABLE');
+ },
+ });
+ vi.mocked(session.send).mockImplementation(async (_message, opts) => {
+ await opts?.onAccepted?.();
+ await opts?.resolveAutoReviewUserIntent?.();
+ opts?.onDispatching?.();
+ vendor();
+ return { accepted: true };
+ });
+ await expect(createMakerSendTransaction(deps).sendToAgentAccepted('session-1', 'Follow up', undefined, {
+ origin: { kind: 'scheduler', scheduleId: 's', scheduleName: 'Follow up', runId: 'r' },
+ })).rejects.toThrow('REMOTE_AGENT_UNAVAILABLE');
+ expect(vendor).not.toHaveBeenCalled();
+ });
+
it.each([false, true])('restores scheduled intent from owner history, not the prompt (unavailable=%s)', async (unavailable) => {
const { deps, session } = createDeps({ readAutoReviewHistory: vi.fn(async () => {
if (unavailable) throw new Error('history unavailable');
diff --git a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
index a612329b8e..fec0962454 100644
--- a/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
+++ b/apps/desktop/src/main/maker-ipc/makerSendTransaction.ts
@@ -392,6 +392,8 @@ export interface MakerSendTransactionDeps {
/** The same clear/rewind-filtered transcript used for native context handoffs. */
readAutoReviewHistory?(sessionId: string): Promise<AutoReviewHistoryMessage[]>;
readScheduledPermissions?(sessionId: string): Promise<{ permissionMode: unknown; planModeEnabled: unknown } | null>;
+ /** Scheduler-only final route check, after asynchronous send preparation. */
+ assertScheduledDispatchRoute?(sessionId: string): Promise<void>;
ensureRemoteReadyForSessionStart(params: {
session?: { agentKind: AgentKind; remoteHostId: string | null } | null;
createOpts?: unknown;
@@ -1845,11 +1847,16 @@ export function createMakerSendTransaction(deps: MakerSendTransactionDeps): Make
: undefined);
// Session awaits this existing authorization hook after all
// preparation (including vision), immediately before dispatch.
+ if (scheduledOrigin) await deps.assertScheduledDispatchRoute?.(sessionId);
await assertAppCurrent();
return intent;
},
}
- : resolveScheduledIntent ? { resolveAutoReviewUserIntent: resolveScheduledIntent } : {}),
+ : resolveScheduledIntent ? { resolveAutoReviewUserIntent: async () => {
+ const intent = await resolveScheduledIntent();
+ await deps.assertScheduledDispatchRoute?.(sessionId);
+ return intent;
+ } } : {}),
[AUTO_REVIEW_SOURCE_CONTENT]: autoReviewSourceContent,
...(so[AUTO_REVIEW_DELEGATED_CONTINUATION] ? { [AUTO_REVIEW_DELEGATED_CONTINUATION]: true as const } : {}),
...(so[INHERITED_CAPABILITY_SELECTION] !== undefined
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index a1d976649a..6995ff113a 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -68,7 +68,7 @@ import { setBotRemoteMessageService } from './botRemoteMessageReceiver.js';
import { handleListDevices, defaultDeps as deviceDirectoryDeps } from '../device-link/ipc.js';
import { configureBotAutonomyHost, getBotAutonomyGlance, noteBotAutonomyInputProjection } from '../bot-autonomy/hub.js';
import { getHostSourceDevice, getSelfDeviceId, remoteBackgroundInvoke, remoteInvoke as invokeBotPeer } from '../device-link/index.js';
-import { readDeviceProviderViews } from '../remote-agent/controller/deviceCatalog.js';
+import { readDeviceProviderViews, readRemoteProviderRoute } from '../remote-agent/controller/deviceCatalog.js';
import { checkDeviceRoute } from '../remote-agent/controller/deviceRouteCheck.js';
import { cancelPendingRemoteStart } from '../remote-agent/controller/startRemote.js';
import { forgetCredentialGrants } from '../remote-agent/executor/credentialGrants.js';
@@ -17996,6 +17996,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
readAutoReviewHistory,
readScheduledPermissions: getSessionFsSnapshot,
+ assertScheduledDispatchRoute: async (sessionId) => {
+ const session = maker.getSession(sessionId);
+ if (!session) throw new Error('Scheduled session unavailable before dispatch');
+ if (!session.agentDeviceId) return;
+ await readRemoteProviderRoute({
+ agentDeviceId: session.agentDeviceId,
+ agentKind: session.agentKind,
+ model: session.model,
+ providerId: getSessionProvider(sessionId),
+ });
+ },
getSession: (sessionId) => maker.getSession(sessionId),
closeSession: (sessionId) => maker.closeSession(sessionId),
getSessionMeta: (sessionId) => maker.getSessionMeta(sessionId),
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
index 5744e27e2e..90971efd73 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
@@ -38,6 +38,7 @@ import {
const mocks = vi.hoisted(() => ({
createMessage: vi.fn(),
getSessionRowSnapshot: vi.fn(),
+ getSessionFsSnapshot: vi.fn(),
ensureDialogueWorkspaceDir: vi.fn(),
wireSessionToIpc: vi.fn(),
resolveWorkingDir: vi.fn(),
@@ -67,6 +68,7 @@ vi.mock('../../localDb/ipc/messages.js', () => ({
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionRowSnapshot: mocks.getSessionRowSnapshot,
+ getSessionFsSnapshot: mocks.getSessionFsSnapshot,
touchUserSendInDb: vi.fn().mockResolvedValue(undefined),
}));
@@ -112,6 +114,7 @@ function createSessionHarness(): FakeSessionHarness {
const listeners: Array<(event: AgentEvent) => void> = [];
const send = vi.fn<SendImpl>(async (_message, opts) => {
await opts?.onAccepted?.();
+ await opts?.resolveAutoReviewUserIntent?.();
opts?.onDispatching?.();
return { accepted: true };
});
@@ -251,6 +254,8 @@ function createRunnerHarness(
acquirePendingAgentSwitch?: ConstructorParameters<typeof MakerScheduleRunner>[0]['acquirePendingAgentSwitch'];
prepareModelPreferences?: ConstructorParameters<typeof MakerScheduleRunner>[0]['prepareModelPreferences'];
onModelDispatched?: ConstructorParameters<typeof MakerScheduleRunner>[0]['onModelDispatched'];
+ beforeDispatchUserTurn?: ConstructorParameters<typeof MakerScheduleRunner>[0]['beforeDispatchUserTurn'];
+ readAutoReviewHistory?: ConstructorParameters<typeof MakerScheduleRunner>[0]['readAutoReviewHistory'];
applyPiModelSelectionUnderLock?: ConstructorParameters<typeof MakerScheduleRunner>[0]['applyPiModelSelectionUnderLock'];
resolveModelSelection?: ConstructorParameters<typeof MakerScheduleRunner>[0]['resolveModelSelection'];
activeSessions?: Session[];
@@ -295,6 +300,8 @@ function createRunnerHarness(
acquirePendingAgentSwitch: opts.acquirePendingAgentSwitch,
prepareModelPreferences: opts.prepareModelPreferences,
onModelDispatched: opts.onModelDispatched,
+ beforeDispatchUserTurn: opts.beforeDispatchUserTurn,
+ readAutoReviewHistory: opts.readAutoReviewHistory,
applyPiModelSelectionUnderLock: opts.applyPiModelSelectionUnderLock ?? (async (_id, targetModel, providerId) => {
await h.session.setModel(targetModel, { providerId });
return { status: 'applied' as const };
@@ -330,6 +337,7 @@ describe('MakerScheduleRunner model selection', () => {
mocks.setSessionFastMode.mockReset();
mocks.isSessionInTurn.mockReturnValue(false);
mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active' });
+ mocks.getSessionFsSnapshot.mockResolvedValue({ permissionMode: 'ask', planModeEnabled: false });
});
// Integration: a new automation must pass the remote route to createSession,
@@ -423,6 +431,44 @@ describe('MakerScheduleRunner model selection', () => {
});
describe('resolved automation selection survives the full fire', () => {
+ // PR #6830 / unit: existing remote cases only checked the initial catalog.
+ // Suspend the selected source during accepted-turn preparation; fire must
+ // fail before vendor dispatch, including for a reused remote task.
+ it.each(['accepted', 'intent'])('rejects a remote source suspended during direct dispatch preparation (%s)', async (stage) => {
+ const h = createSessionHarness();
+ Object.assign(h.session, { agentDeviceId: 'studio' });
+ mocks.getSessionProvider.mockReturnValue('remote-sub');
+ const providers = [{ id: 'remote-sub', name: 'Remote', connected: true,
+ agents: ['claude-code'], routing: { 'claude-code': {} }, suspended: false,
+ models: { 'claude-code': [{ id: h.session.model, name: 'Sonnet' }] },
+ }] as unknown as ProviderView[];
+ const onModelDispatched = vi.fn();
+ h.send.mockImplementation(async (_message, options) => {
+ await options?.onAccepted?.();
+ await options?.resolveAutoReviewUserIntent?.();
+ options?.onDispatching?.();
+ h.emit({ type: 'done', data: {} });
+ return { accepted: true };
+ });
+ const harness = createRunnerHarness(h, { model: h.session.model, workDir: '/work' }, {
+ sessionAlive: true, onModelDispatched,
+ resolveModelSelection: async (choice, location) => {
+ expect(location).toEqual({ agentDeviceId: 'studio' });
+ return resolveScheduledModelSelection(choice, providers);
+ },
+ beforeDispatchUserTurn: async () => { if (stage === 'accepted') providers[0].suspended = true; },
+ readAutoReviewHistory: async () => {
+ if (stage === 'intent') providers[0].suspended = true;
+ return [];
+ },
+ });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', agentDeviceId: 'studio' });
+ await expect(harness.runner.fire(baseSchedule({ targetSessionId: h.session.id }), createFireContext()))
+ .rejects.toThrow('Session send failed before dispatch');
+ expect(providers[0].suspended).toBe(true);
+ expect(onModelDispatched).not.toHaveBeenCalled();
+ });
+
// Merge regression, unit: a legacy remote default must not mask an explicit
// local override. Cover fresh creation and persistent replacement via fire.
it.each([false, true])('honors local selection over a saved remote default (replacement=%s)', async (replacement) => {
@@ -527,6 +573,7 @@ describe('MakerScheduleRunner model selection', () => {
mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', agentDeviceId: 'relocated' });
const harness = createRunnerHarness(h, { model: h.session.model, workDir: '/work', sdkSessionId: 'native-history' }, {
sessionAlive: mode === 'rebuild',
+ resolveModelSelection: async (choice) => choice,
});
const opts = await fireToCompletion(harness, h, baseSchedule({
targetSessionId: h.session.id, persistentSession: true, agentDeviceId: 'original',
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 16dd6441f4..a27aeda9c2 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -496,6 +496,26 @@ export class MakerScheduleRunner implements ScheduleRunner {
return this.deps.checkModelRoute!(agent, model, providerId);
}
+ /** Re-read the execution computer's catalog after dispatch preparation. */
+ private async assertRemoteDispatchRoute(
+ agentDeviceId: string | null | undefined,
+ agentKind: AgentKind,
+ model: string,
+ providerId: string | null,
+ ): Promise<void> {
+ if (!agentDeviceId) return;
+ try {
+ if (!this.deps.resolveModelSelection) throw new Error('Scheduled model selection is not available');
+ await this.deps.resolveModelSelection({
+ agentDeviceId, agentKind, model, providerId, effort: null, fastMode: false,
+ }, { agentDeviceId });
+ } catch (error) {
+ throw new QueuedRouteDisabledError(
+ `schedule remote route unavailable before dispatch: ${error instanceof Error ? error.message : String(error)}`,
+ );
+ }
+ }
+
private async retireHeartbeat(
schedule: Schedule,
ctx: FireContext,
@@ -2011,27 +2031,35 @@ export class MakerScheduleRunner implements ScheduleRunner {
}
const sendResult = await session.send(outgoingMessage as never, {
origin,
- ...(schedule.targetSessionId || schedule.source === 'bot'
+ ...(isHeartbeat || schedule.source === 'bot' || agentDeviceId
? {
resolveAutoReviewUserIntent: async () => {
// A teammate routine is judged by the instruction it runs, not by the
// owner's unrelated chat history in the teammate's main task.
const intent = schedule.source === 'bot'
? routineInstructionFromPrompt(schedule.prompt)
- : restoreAutoReviewUserIntent(
+ : isHeartbeat ? restoreAutoReviewUserIntent(
(await this.deps.readAutoReviewHistory?.(session.id).catch(() => [])) ?? [],
- );
- const current = await this.readRoutinePermissions(session.id, session);
- const expected = routinePermissions ?? heartbeatPermissions;
- if (
- !current ||
- current.permissionMode !== expected?.permissionMode ||
- current.planMode !== expected?.planMode
- ) {
- throw new RoutineDispatchDeferredError(
- 'Heartbeat modes changed during preparation',
- );
+ ) : undefined;
+ if (isHeartbeat || schedule.source === 'bot') {
+ const current = await this.readRoutinePermissions(session.id, session);
+ const expected = routinePermissions ?? heartbeatPermissions;
+ if (
+ !current ||
+ current.permissionMode !== expected?.permissionMode ||
+ current.planMode !== expected?.planMode
+ ) {
+ throw new RoutineDispatchDeferredError(
+ 'Heartbeat modes changed during preparation',
+ );
+ }
}
+ // Session invokes this after accepted preparation and the vision
+ // bridge, immediately before its synchronous dispatch boundary.
+ await this.assertRemoteDispatchRoute(
+ session.agentDeviceId ?? agentDeviceId, effectiveAgentKind, runtimeModel,
+ getSessionProvider(session.id),
+ );
return intent;
},
}
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index c61e75f253..2443df5fda 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -3559,6 +3559,8 @@ SQL NULL 对应缺省;项目 `version: 1` 配置同样允许该字段,旧文
`undefined` 后交给 Scheduler 与存储。省略字段仍是不修改,不在发送前丢掉清空意图。
旧调用方修改新自动化的非模型字段仍保留位置;修改模型路线却未携带已固定的位置时拒绝保存,
避免意外把另一台电脑的供应商当作本机来源。执行与恢复仍使用既有远程授权、目录与切换协议。
+直接发送与排队派发在准备完成后,按实际运行位置、模型及供应商重新读取远程目录;来源或模型
+已停用、离线或授权不可用时拒绝本次调用,排队项取消发送预留并失败收口,不回退到本机来源。
## 公共插件分享(未发布首版)