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): preserve agent locations across task recovery

david6642a9e735c2
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index c19a4d35c2..e6b21a318e 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -488,6 +488,10 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// (hook-script-generator)。lazy import:该链上有 electron app 依赖,且 maker
// 仅 description 生成模式需要,tool-call 时才解引用。
hookScript: {
+ isSessionAgentOnOtherDevice: async (sessionId) => {
+ const row = await getSessionRowSnapshot(sessionId);
+ return !!row?.agentDeviceId && !row.remoteHostId;
+ },
// 绑定会话(heartbeat)任务安装 hook 时解析会话真实工作目录 —— schedule
// 行上的 workingDir 为空/过期,落盘与自测必须用会话 meta.workDir。
resolveSessionWorkDir: async (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 f869b491d3..846de46ba6 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
@@ -379,6 +379,54 @@ describe('MakerScheduleRunner model selection', () => {
});
describe('resolved automation selection survives the full fire', () => {
+ // PR #6832: fire must resolve a replacement at the saved location from the saved
+ // preferences, not the relocated target's clamped copy. Existing archived cases
+ // used identical catalogs. Minimal input: archived persistent target on another
+ // device, with different effort/Fast support. Tier: unit (in-memory host).
+ // Windows standalone: 14.30s (collection 10.08s, 72 tests 3.85s). Reuses the
+ // existing file-level imports/fixture; no module resets or new real I/O.
+ it.each([undefined, 'studio'])('re-resolves an archived relocated target at %s', async (agentDeviceId) => {
+ const h = createSessionHarness();
+ Object.assign(h.session, { agentKind: 'codex', model: 'gpt-5.5' });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'archived', agentDeviceId: 'relocated' });
+ const resolveModelSelection = vi.fn(async (choice) => ({ ...choice, effort: 'high' as const }));
+ const harness = createRunnerHarness(h, null, {
+ acquirePendingAgentSwitch: async () => ({ release: vi.fn(), selection: {
+ agentKind: 'codex', model: 'gpt-5.5', providerId: 'relocated-provider',
+ effort: 'low', fastMode: false,
+ } }),
+ resolveModelSelection,
+ });
+ harness.runner.attachScheduler({ update: vi.fn(), isRunSilenced: () => false } as unknown as Scheduler);
+ const schedule = baseSchedule({ targetSessionId: h.session.id, persistentSession: true,
+ agentDeviceId, agentKind: 'codex', modelAgentKind: 'codex', model: 'gpt-5.5',
+ providerId: 'saved-provider', effort: 'ultra', fastMode: true });
+ const opts = await fireToCompletion(harness, h, schedule);
+ expect(resolveModelSelection.mock.calls[0]).toEqual([
+ expect.objectContaining({ providerId: 'saved-provider', effort: 'ultra', fastMode: true }),
+ ...(agentDeviceId ? [{ agentDeviceId }] : []),
+ ]);
+ expect(opts).toMatchObject({ providerId: 'saved-provider', effort: 'high' });
+ expect(harness.createSession.mock.calls[0][0].agentDeviceId).toBe(agentDeviceId);
+ });
+
+ // PR #6832: existing remote coverage only created new tasks. Cold resume and
+ // model-triggered rebuild must dispatch at the bound row's current location,
+ // even when the automation still saves its original location. Tier: unit.
+ it.each(['cold', 'rebuild'] as const)('keeps the bound task location during %s resume', async (mode) => {
+ const h = createSessionHarness();
+ if (mode === 'rebuild') Object.assign(h.session, { requiresModelSwitchRebuild: async () => true });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', agentDeviceId: 'relocated' });
+ const harness = createRunnerHarness(h, { model: h.session.model, workDir: '/work', sdkSessionId: 'native-history' }, {
+ sessionAlive: mode === 'rebuild',
+ });
+ const opts = await fireToCompletion(harness, h, baseSchedule({
+ targetSessionId: h.session.id, persistentSession: true, agentDeviceId: 'original',
+ }));
+ expect(opts).toMatchObject({ agentDeviceId: 'relocated', resumeSessionId: 'native-history' });
+ expect(harness.closeSession).toHaveBeenCalledTimes(mode === 'rebuild' ? 1 : 0);
+ });
+
it.each(['active', 'archived', 'missing'] as const)('uses the explicit Pi route for a %s Codex target', async (status) => {
const h = createSessionHarness();
Object.assign(h.session, { agentKind: 'pi', model: 'shared-model' });
@@ -391,6 +439,7 @@ describe('MakerScheduleRunner model selection', () => {
mocks.getSessionRowSnapshot.mockResolvedValue(status === 'missing' ? null : { status });
const harness = createRunnerHarness(h, { agentKind: 'pi', model: 'shared-model', effort: 'high', fastMode: false, workDir: '/work' }, {
sessionAlive: status === 'active',
+ resolveModelSelection: async (choice) => resolveScheduledModelSelection(choice, providers),
// The merged copy deliberately conflicts with the selected provider copy.
availableModels: [{ id: 'shared-model', efforts: ['low'], defaultEffort: 'low' }],
acquirePendingAgentSwitch: async (_id, _signal, selection) => ({
@@ -415,6 +464,7 @@ describe('MakerScheduleRunner model selection', () => {
expect(mocks.setSessionEffort).toHaveBeenLastCalledWith(h.session.id, 'high');
expect(mocks.backfillSessionMeta).toHaveBeenCalledWith(expect.anything(), h.session.id,
expect.objectContaining({ effort: 'high', fastMode: false, providerId: 'selected' }), expect.anything());
+ expect(mocks.setSessionProvider).toHaveBeenCalledWith(h.session.id, 'selected');
expect(h.setEffort.mock.calls.flat()).not.toContain('low');
expect(schedule).toEqual(saved);
expect(release).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index e56cf666c6..178744fe89 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -943,6 +943,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// 持续会话当前选定的来源(供应商)id —— schedule.providerId 留空时沿用它
// (与 model 留空沿用 meta.model 对称)。取自 sessions.provider_id 快照,null=未选。
let heartbeatProviderId: string | null = null;
+ let heartbeatAgentDeviceId: string | undefined;
// Fire-local catalog snapshot. Keep the saved preferences untouched, but never
// re-read their stale effort/Fast after the host has resolved the actual route.
let resolvedSelection: ScheduledModelSelection | undefined;
@@ -980,14 +981,6 @@ export class MakerScheduleRunner implements ScheduleRunner {
if (!lease || typeof lease === 'function')
throw new Error('Scheduled model selection was not resolved');
resolvedSelection = lease.selection;
- schedule = {
- ...schedule,
- agentKind: resolvedSelection.agentKind,
- model: resolvedSelection.model,
- providerId: resolvedSelection.providerId ?? undefined,
- effort: resolvedSelection.effort ?? undefined,
- fastMode: resolvedSelection.fastMode,
- };
}
} catch (error) {
if (error instanceof ScheduledModelSelectionBusyError) {
@@ -1017,6 +1010,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
this.deps.logger.warn?.('[runner] persistent rebind clear failed', err);
}
isHeartbeat = false;
+ // The replacement belongs to the schedule's saved location. Discard the
+ // old target's catalog snapshot and resolve the original preferences there.
+ resolvedSelection = undefined;
sessionId = randomUUID();
// resumeSessionId / heartbeatWorkingDir / heartbeatModel 仍是 undefined,
// 下方 workingDir 解析自然走 schedule.workingDir + schedule.useWorktree 分支
@@ -1037,6 +1033,16 @@ export class MakerScheduleRunner implements ScheduleRunner {
throw new Error(errMsg);
}
} else {
+ if (resolvedSelection) {
+ schedule = {
+ ...schedule,
+ agentKind: resolvedSelection.agentKind,
+ model: resolvedSelection.model,
+ providerId: resolvedSelection.providerId ?? undefined,
+ effort: resolvedSelection.effort ?? undefined,
+ fastMode: resolvedSelection.fastMode,
+ };
+ }
// B1 活跃礼让:最近有人往这个 session 发过输入(userSendAt 在窗口内)且
// session 正跑 turn → 本轮不抢,顺延。两条件都满足才让:仅"刚发过"
// 但 turn 已结束属正常 heartbeat 时机;仅"在跑"但非最近有输入多半是上轮
@@ -1110,6 +1116,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
heartbeatAgentKind = meta?.agentKind;
heartbeatFastMode = meta?.fastMode;
heartbeatProviderId = row?.providerId ?? null;
+ // A resumed/rebuilt task keeps its current location, including relocation
+ // since the automation was saved. SSH is a separate execution path.
+ heartbeatAgentDeviceId = !row.remoteHostId ? row.agentDeviceId || undefined : undefined;
// A cold heartbeat is still the owner's existing task. Never upgrade it
// to the independent-schedule default merely because its runtime was closed.
heartbeatPermissions = routinePermissionSnapshot(undefined, {
@@ -1494,6 +1503,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
return this.deferFire(schedule, sessionId, 'routine-permission-unavailable');
throwIfFireAborted(ctx.signal, 'session creation');
}
+ const createAgentDeviceId = isHeartbeat ? heartbeatAgentDeviceId : freshAgentDeviceId;
const createSessionOpts = {
id: sessionId,
agentKind: effectiveAgentKind,
@@ -1512,7 +1522,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
resumeSessionId,
// Explicit null means Cindy's default route for Pi.
providerId: createProviderId,
- ...(freshAgentDeviceId ? { agentDeviceId: freshAgentDeviceId } : {}),
+ ...(createAgentDeviceId ? { agentDeviceId: createAgentDeviceId } : {}),
vendorOptions: { source: 'scheduler' as const },
};
let session: Awaited<ReturnType<Maker['createSession']>>;
@@ -1735,6 +1745,7 @@ export class MakerScheduleRunner implements ScheduleRunner {
// heartbeat / 冷 resume 与本轮真实凭证/endpoint 才不会漂移。心跳只在默认模型
// 同轮落库成功时写(模型与来源成对);其余心跳留空不写,保留绑定会话自己的 provider_id。
providerId:
+ resolvedSelection?.providerId ??
explicitProviderId ??
(!isHeartbeat || (heartbeatModelChanged && modelSwitchApplied)
? materializedDefaultProviderId
diff --git a/docs/product-rules/agent-user-parity.md b/docs/product-rules/agent-user-parity.md
index adddcefe1b..7f752a932a 100644
--- a/docs/product-rules/agent-user-parity.md
+++ b/docs/product-rules/agent-user-parity.md
@@ -51,7 +51,7 @@
| 协同 / Worker | 单个 / 批量创建、指定已有目录、查询实际目录与自有 worktree | 有 | 有(运行设备;新建 worktree 仅本机) |
| 协同 / Worker | 为 Worker 新建 worktree、指定源分支、归档时回收 | 有 | 无 |
| 定时任务 | 列出、详情、运行记录、修改、暂停、恢复、删除、立即运行 | 有 | 有(2026-10-14) |
-| 定时任务 | 新建、安装检查脚本 | 有 | 无 |
+| 定时任务 | 新建、安装检查脚本 | 有(绑定远程 Agent 时由本机辅助模型生成脚本) | 无 |
| 定时任务 | 查可选运行位置与模型;设每次新建任务的 Agent 运行位置(其他电脑 / 分享来的供应商) | 有(2026-10-22) | 无 |
| 定时任务 | 删除单条运行记录、标记已读 | 无 | 无 |
| 项目 | 列出、登记、改名、移除;工作目录列表 | 有 | 无 |
diff --git a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
index 46382b75d4..fa31f859c8 100644
--- a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
@@ -1553,6 +1553,7 @@ describe('schedule_set_pre_run_hook — 统一安装通道', () => {
withService?: boolean;
scheduleRow?: Record<string, unknown> | null;
resolveSessionWorkDir?: (sessionId: string) => Promise<string | undefined>;
+ isSessionAgentOnOtherDevice?: (sessionId: string) => Promise<boolean>;
}) {
const installCalls: InstallCall[] = [];
const updates: Array<{ id: string; patch: Record<string, unknown> }> = [];
@@ -1571,6 +1572,9 @@ describe('schedule_set_pre_run_hook — 统一安装通道', () => {
? {}
: {
hookScript: {
+ ...(opts.isSessionAgentOnOtherDevice
+ ? { isSessionAgentOnOtherDevice: opts.isSessionAgentOnOtherDevice }
+ : {}),
...(opts.resolveSessionWorkDir
? { resolveSessionWorkDir: opts.resolveSessionWorkDir }
: {}),
@@ -1661,6 +1665,27 @@ describe('schedule_set_pre_run_hook — 统一安装通道', () => {
expect((data.test as Record<string, unknown>).decision).toBe('skip');
});
+ // PR #6832: the real tool must select the local utility route for remote bound
+ // tasks. Existing tests only inherited cwd, without remote-only model/provider.
+ // Minimal input: targetSessionId + remote provider, no schedule.agentDeviceId.
+ // Tier: unit; fake installer captures its public route and attachment result.
+ // Windows standalone: 0.85s for the file's 70 tests.
+ it.each([true, false])('uses the bound task location for hook generation (remote=%s)', async (remote) => {
+ const { registry, installCalls, updates } = setup({
+ scheduleRow: { id: 'sch-1', targetSessionId: 'bound', providerId: 'selected-provider',
+ agentKind: 'claude-code', model: 'selected-model' },
+ isSessionAgentOnOtherDevice: async () => remote,
+ });
+ const env = await callTool(registry, { scheduleId: 'sch-1', description: 'Check for pending work' });
+ expect(env.ok).toBe(true);
+ expect(installCalls[0]).toMatchObject({
+ providerId: remote ? undefined : 'selected-provider',
+ agentKind: remote ? undefined : 'claude-code',
+ model: remote ? undefined : 'selected-model',
+ });
+ expect(updates).toHaveLength(1);
+ });
+
it('bound script hooks are installed in script cwd rather than owner cwd', async () => {
const { registry, installCalls } = setup({
scheduleRow: { id: 'sch-1', name: 'watcher', executionMode: 'script',
diff --git a/packages/lizi-mcps/src/scheduler/setPreRunHook.ts b/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
index 17bdcd3dd2..da7fe44183 100644
--- a/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
+++ b/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
@@ -110,7 +110,10 @@ export function registerScheduleSetPreRunHookTool(
currentCommand = schedule.preRunHook?.command;
currentTimeoutMs = schedule.preRunHook?.timeoutMs;
// 脚本在本机生成;Agent 在另一台电脑运行时它的来源与模型只在那台可用,改走本机辅助模型兜底。
- if (!schedule.agentDeviceId) {
+ const remoteAgent = schedule.targetSessionId && hookScript.isSessionAgentOnOtherDevice
+ ? await hookScript.isSessionAgentOnOtherDevice(schedule.targetSessionId)
+ : !!schedule.agentDeviceId;
+ if (!remoteAgent) {
providerId = schedule.providerId;
agentKind = schedule.agentKind;
model = schedule.model;
diff --git a/packages/lizi-mcps/src/types.ts b/packages/lizi-mcps/src/types.ts
index 0ee4e9be1c..2245c28d26 100644
--- a/packages/lizi-mcps/src/types.ts
+++ b/packages/lizi-mcps/src/types.ts
@@ -343,6 +343,8 @@ export interface SchedulerHookScriptService {
* meta.workDir 为准。未注入时回落 schedule.workingDir 旧行为。
*/
resolveSessionWorkDir?(sessionId: string): Promise<string | undefined>;
+ /** Bound task's current Agent location; remote-only routes cannot generate local hook scripts. */
+ isSessionAgentOnOtherDevice?(sessionId: string): Promise<boolean>;
/**
* 把受支持的单脚本相对命令固化为绝对路径。任意 shell 命令保持原样;相对脚本
* 缺少原 cwd 或文件不存在时必须报错,避免改绑后以 fail-open 静默绕过 hook。