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): 自动运行时恢复已归档任务并保留原会话

Dash605d88ff3583
diff --git a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
index 2cba423644..a265cd0f24 100644
--- a/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
+++ b/apps/desktop/src/main/maker-ipc/scheduledModelSelection.ts
@@ -113,7 +113,8 @@ export async function applyScheduledModelSelection(
},
): Promise<ScheduledModelSelection> {
const target = await deps.getTarget();
- // The runner owns missing/archived target recovery, including persistent-task rebinding.
+ // The runner restores ordinary archived targets before selection and owns
+ // deleted/missing-target rebinding for persistent tasks.
// Its replacement resolves at the schedule's saved location. Do not query the old
// target's catalog: that device may be offline or its provider share revoked.
if (!target || target.status === 'archived' || target.status === 'deleted') {
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 7e043d3b25..04c71c6a8d 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts
@@ -402,15 +402,15 @@ 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
+ // preferences, not the relocated target's clamped copy. Existing replacement cases
+ // used identical catalogs. Minimal input: deleted 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) => {
+ it.each([undefined, 'studio'])('re-resolves a deleted 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' });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'deleted', agentDeviceId: 'relocated' });
const resolveModelSelection = vi.fn(async (choice) => ({ ...choice, effort: 'high' as const }));
const harness = createRunnerHarness(h, null, {
acquirePendingAgentSwitch: async () => ({ release: vi.fn(), selection: {
@@ -435,17 +435,17 @@ describe('MakerScheduleRunner model selection', () => {
// PR #6832: the old rebinding fixture returned a successful catalog snapshot.
// Exercise the real selection entry with an unavailable old catalog; fire must
// still create at the saved location with its route (unit, in-memory host).
- it.each([undefined, 'studio'])('rebinds at %s when the archived target catalog is unavailable', async (agentDeviceId) => {
+ it.each([undefined, 'studio'])('rebinds at %s when the deleted target catalog is unavailable', async (agentDeviceId) => {
const h = createSessionHarness();
Object.assign(h.session, { agentKind: 'codex', model: 'gpt-5.5' });
- mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'archived', agentDeviceId: 'relocated' });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'deleted', agentDeviceId: 'relocated' });
const oldCatalog = vi.fn(async () => { throw new Error('old target offline or share revoked'); });
const resolveModelSelection = vi.fn(async (choice) => ({ ...choice, effort: 'high' as const }));
const harness = createRunnerHarness(h, null, {
acquirePendingAgentSwitch: async (_id, _signal, selection) => ({
release: vi.fn(),
selection: await applyScheduledModelSelection(selection!, {
- getTarget: async () => ({ agentKind: 'codex', status: 'archived' }),
+ getTarget: async () => ({ agentKind: 'codex', status: 'deleted' }),
isBusy: () => false,
resolveSelection: oldCatalog,
switchHarness: async () => ({ engineReady: true }),
@@ -485,7 +485,7 @@ describe('MakerScheduleRunner model selection', () => {
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) => {
+ it.each(['active', 'deleted', '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' });
const release = vi.fn();
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
index 63f5402adc..ebdfaeaf97 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
@@ -16,6 +16,8 @@ const mocks = vi.hoisted(() => ({
buildSkipResultText: vi.fn(() => 'skipped'),
createMessage: vi.fn(),
getSessionRowSnapshot: vi.fn(),
+ restoreArchivedSessionForSend: vi.fn(),
+ getManagedWorktreeReadinessForSession: vi.fn(),
ensureDialogueWorkspaceDir: vi.fn(),
wireSessionToIpc: vi.fn(),
resolveWorkingDir: vi.fn(),
@@ -32,8 +34,13 @@ vi.mock('../../localDb/ipc/messages.js', () => ({
}));
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionRowSnapshot: mocks.getSessionRowSnapshot,
+ getSessionRowSnapshotStrict: mocks.getSessionRowSnapshot,
+ restoreArchivedSessionForSend: mocks.restoreArchivedSessionForSend,
touchUserSendInDb: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock('../../worktree/restore', () => ({
+ getManagedWorktreeReadinessForSession: mocks.getManagedWorktreeReadinessForSession,
+}));
vi.mock('../../localDb/dialogueWorkspace', () => ({
ensureDialogueWorkspaceDir: mocks.ensureDialogueWorkspaceDir,
}));
@@ -104,7 +111,7 @@ function createRunner(getSessionMeta: Maker['getSessionMeta']) {
}
describe('MakerScheduleRunner pre-run hook cwd 解析', () => {
- it.each(['archived', 'deleted'])('stops a %s heartbeat before running any hook', async (status) => {
+ it.each(['deleted'])('stops a %s heartbeat before running any hook', async (status) => {
mocks.getSessionRowSnapshot.mockResolvedValueOnce({ status });
const { runner, notifier } = createRunner(vi.fn() as never);
const pause = vi.fn(async () => undefined);
@@ -117,6 +124,9 @@ describe('MakerScheduleRunner pre-run hook cwd 解析', () => {
});
beforeEach(() => {
vi.clearAllMocks();
+ mocks.getSessionRowSnapshot.mockReset();
+ mocks.restoreArchivedSessionForSend.mockReset();
+ mocks.getManagedWorktreeReadinessForSession.mockResolvedValue('ready');
// hook 判 skip → fire 在 hook 分支内早退,不进 session 创建,测试聚焦 cwd 传参
mocks.executePreRunHook.mockResolvedValue({
status: 'skipped',
@@ -134,6 +144,57 @@ describe('MakerScheduleRunner pre-run hook cwd 解析', () => {
mocks.buildSkipResultText.mockReturnValue('skipped');
});
+ // User decision 2026-10-23: scheduled input restores an archived task like a
+ // user message. Existing tests retired it before hooks. Minimal unit case:
+ // archived target with a recycled managed worktree; hook must see restored files.
+ it.each([false, true])('restores the same archived task and its worktree before the hook (persistent=%s)', async (persistentSession) => {
+ const target = { status: 'archived', workingDir: '/repo/.cindy-worktrees/task' };
+ mocks.getSessionRowSnapshot.mockImplementation(async () => ({ ...target }));
+ mocks.restoreArchivedSessionForSend.mockImplementation(async () => { target.status = 'active'; });
+ mocks.getManagedWorktreeReadinessForSession.mockImplementation(async () => {
+ expect(target.status).toBe('active');
+ return 'ready';
+ });
+ mocks.executePreRunHook.mockImplementation(async () => {
+ expect(target.status).toBe('active');
+ expect(mocks.getManagedWorktreeReadinessForSession).toHaveBeenCalledWith('owner', target.workingDir);
+ return { decision: 'skip', exitCode: 2 };
+ });
+ const { runner, maker } = createRunner(vi.fn(async () => ({ workDir: target.workingDir })) as never);
+ const pause = vi.fn();
+ const update = vi.fn();
+ runner.attachScheduler({ pause, update } as never);
+ await expect(runner.fire(baseSchedule({ targetSessionId: 'owner', persistentSession }), createFireContext()))
+ .resolves.toMatchObject({ skipped: true });
+ expect(target.status).toBe('active');
+ expect(pause).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ expect(maker.createSession).not.toHaveBeenCalled();
+ });
+
+ it('does not run the hook with an unrestored worktree snapshot', async () => {
+ const target = { status: 'archived', workingDir: '/repo/.cindy-worktrees/task' };
+ mocks.getSessionRowSnapshot.mockImplementation(async () => ({ ...target }));
+ mocks.restoreArchivedSessionForSend.mockImplementation(async () => { target.status = 'active'; });
+ mocks.getManagedWorktreeReadinessForSession.mockResolvedValue('retry');
+ const { runner } = createRunner(vi.fn(async () => ({ workDir: target.workingDir })) as never);
+ await expect(runner.fire(baseSchedule({ targetSessionId: 'owner' }), createFireContext()))
+ .rejects.toThrow(/worktree/i);
+ expect(mocks.executePreRunHook).not.toHaveBeenCalled();
+ });
+
+ it.each(['archived', 'deleted'])('does not restore files when a managed target becomes %s while acquiring its route lock', async (status) => {
+ const workingDir = '/repo/.cindy-worktrees/task';
+ mocks.getSessionRowSnapshot.mockResolvedValueOnce({ status: 'active', workingDir })
+ .mockResolvedValue({ status, workingDir });
+ const { runner } = createRunner(vi.fn() as never);
+ await expect(runner.fire(baseSchedule({ targetSessionId: 'owner' }), createFireContext()))
+ .rejects.toThrow(/unavailable/i);
+ expect(mocks.restoreArchivedSessionForSend).not.toHaveBeenCalled();
+ expect(mocks.getManagedWorktreeReadinessForSession).not.toHaveBeenCalled();
+ expect(mocks.executePreRunHook).not.toHaveBeenCalled();
+ });
+
it('no change starts no model and emits no chat or completion notification', async () => {
const { runner, maker, notifier } = createRunner(vi.fn(async () => null) as never);
const context = createFireContext();
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
index f59f3b0f85..92505a9bf4 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
@@ -18,6 +18,7 @@ import type {
const mocks = vi.hoisted(() => ({
createMessage: vi.fn(),
getSessionRowSnapshot: vi.fn(),
+ restoreArchivedSessionForSend: vi.fn(),
ensureDialogueWorkspaceDir: vi.fn(),
wireSessionToIpc: vi.fn(),
isSessionInTurn: vi.fn(() => false),
@@ -31,6 +32,7 @@ vi.mock('../../localDb/ipc/messages.js', () => ({
vi.mock('../../localDb/ipc/sessions.js', () => ({
getSessionRowSnapshot: mocks.getSessionRowSnapshot,
+ restoreArchivedSessionForSend: mocks.restoreArchivedSessionForSend,
touchUserSendInDb: vi.fn().mockResolvedValue(undefined),
}));
@@ -421,7 +423,7 @@ describe('MakerScheduleRunner send outcome policy', () => {
expect(h.send).not.toHaveBeenCalled();
});
- it.each([false, true])('retires an archived target and releases an acquired lock (racing=%s)', async (racing) => {
+ it.each([false, true])('retires a deleted target and releases an acquired lock (racing=%s)', async (racing) => {
const order: string[] = [];
const h = createSessionHarness(async () => ({ accepted: true }));
const releaseAgentSwitchLock = vi.fn(() => {
@@ -433,7 +435,7 @@ describe('MakerScheduleRunner send outcome policy', () => {
order.push('notify');
});
mocks.getSessionRowSnapshot.mockResolvedValue({
- status: 'archived',
+ status: 'deleted',
userSendAt: null,
providerId: null,
});
@@ -455,6 +457,56 @@ describe('MakerScheduleRunner send outcome policy', () => {
expect(h.send).not.toHaveBeenCalled();
});
+ // Scheduled input must keep both the business task and native history after
+ // restoration; the old archived-target test only covered pausing. Unit fixture.
+ it.each([false, true])('restores and completes in the original task without rearchiving (persistent=%s)', async (persistentSession) => {
+ const target = { status: 'archived', providerId: null, agentDeviceId: 'other-computer' };
+ mocks.getSessionRowSnapshot.mockImplementation(async () => ({ ...target }));
+ mocks.restoreArchivedSessionForSend.mockImplementation(async () => { target.status = 'active'; });
+ const h = createSessionHarness(async (_message, options) => {
+ await options?.onAccepted?.();
+ h.emit({ type: 'done', sessionId: h.session.id, data: {} } as AgentEvent);
+ return { accepted: true };
+ });
+ const { runner, maker } = createRunnerHarness(h.session, {
+ acquirePendingAgentSwitch: async () => {
+ expect(target.status).toBe('active');
+ return vi.fn();
+ },
+ });
+ vi.mocked(maker.getSessionMeta).mockResolvedValue({ workDir: '/work', sdkSessionId: 'native-history', model: 'gpt-6-astra' } as never);
+ const pause = vi.fn();
+ const update = vi.fn();
+ runner.attachScheduler({ pause, update, isRunSilenced: () => false } as never);
+ await expect(runner.fire(baseSchedule({ targetSessionId: h.session.id, persistentSession }), createFireContext()))
+ .resolves.toMatchObject({ sessionId: h.session.id });
+ expect(maker.createSession).toHaveBeenCalledWith(expect.objectContaining({
+ id: h.session.id, resumeSessionId: 'native-history', agentDeviceId: 'other-computer',
+ }));
+ expect(h.send).toHaveBeenCalledOnce();
+ expect(target.status).toBe('active');
+ expect(mocks.restoreArchivedSessionForSend).toHaveBeenCalledOnce();
+ expect(pause).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ });
+
+ it('keeps the schedule active when the target is archived again during preparation', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ mocks.getSessionRowSnapshot.mockResolvedValueOnce({ status: 'active' })
+ .mockResolvedValue({ status: 'archived' });
+ const release = vi.fn();
+ const { runner } = createRunnerHarness(h.session, { acquirePendingAgentSwitch: async () => release });
+ const pause = vi.fn();
+ const update = vi.fn();
+ runner.attachScheduler({ pause, update } as never);
+ await expect(runner.fire(baseSchedule({ targetSessionId: h.session.id, persistentSession: true }), createFireContext()))
+ .resolves.toMatchObject({ skipped: true, sessionId: h.session.id });
+ expect(release).toHaveBeenCalledOnce();
+ expect(pause).not.toHaveBeenCalled();
+ expect(update).not.toHaveBeenCalled();
+ expect(h.send).not.toHaveBeenCalled();
+ });
+
it.each(['archived', 'deleted'])('keeps unavailable %s bot targets in the routine failure lifecycle', async (status) => {
const order: string[] = [];
const h = createSessionHarness(async () => ({ accepted: true }));
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
index 5af4a0e79b..6ea5a0b1ba 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
@@ -14,6 +14,8 @@ import { installedGhostStoragePart, resolveInstalledGhost } from '../../../share
import { SchedulerScriptCapabilityBroker } from '../script-capability-broker';
const sendToSessionMock = vi.hoisted(() => vi.fn());
+const restoreArchivedSessionForSend = vi.hoisted(() => vi.fn());
+vi.mock('../../localDb/ipc/sessions', () => ({ restoreArchivedSessionForSend }));
// ghost pipe 统一入口:缺省回显请求(jira/feishu 用例断言请求形状),
// 单个用例可 mockResolvedValueOnce 覆盖返回(断言 data 解包 / 错误映射)。
const callGhostToolMock = vi.hoisted(() =>
@@ -79,6 +81,7 @@ function schedule(overrides: Partial<Schedule> = {}): Schedule {
describe('SchedulerScriptCapabilityBroker', () => {
beforeEach(() => {
sendToSessionMock.mockReset();
+ restoreArchivedSessionForSend.mockReset();
callGhostToolMock.mockReset();
callGhostToolMock.mockImplementation(async (request: unknown) => ({ ok: true, result: request }));
registerCallMock.mockReset();
@@ -504,6 +507,23 @@ describe('SchedulerScriptCapabilityBroker', () => {
expect(sendToSessionMock.mock.calls[0]?.[0][AUTO_REVIEW_DELEGATED_CONTINUATION]).toBe(true);
});
+ // User decision 2026-10-23: unbound scripts select a target only at dispatch;
+ // they must restore it before the normal sender rejects ARCHIVED. Unit, no I/O.
+ it('restores an explicitly selected archived target before delivering the message', async () => {
+ let status = 'archived';
+ restoreArchivedSessionForSend.mockImplementation(async () => { status = 'active'; });
+ sendToSessionMock.mockImplementation(async () => {
+ expect(status).toBe('active');
+ return { ok: true, targetSessionId: 'owner', agentKind: 'codex', wakeKind: 'queued' };
+ });
+ const result = await new SchedulerScriptCapabilityBroker().call(
+ { method: 'sessions.dispatch', params: { target_session_id: 'owner', message: 'update' } },
+ new Set(['sessions.dispatch']), { schedule: schedule() },
+ );
+ expect(result).toMatchObject({ target_session_id: 'owner', wake_kind: 'queued' });
+ expect(status).toBe('active');
+ });
+
it('dispatches sessions with host-owned create defaults from the schedule', async () => {
sendToSessionMock.mockResolvedValue({
ok: true,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
index e16fcc8e73..bbf0bd640c 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
@@ -5,6 +5,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const spawnMock = vi.fn();
const executePreRunHookMock = vi.hoisted(() => vi.fn());
+const restoreArchivedSessionForSend = vi.hoisted(() => vi.fn());
+vi.mock('../../localDb/ipc/sessions', () => ({ restoreArchivedSessionForSend }));
vi.mock('node:child_process', () => ({
spawn: (...args: unknown[]) => spawnMock(...args),
@@ -97,10 +99,11 @@ describe('ScriptScheduleRunner', () => {
beforeEach(() => {
spawnMock.mockReset();
executePreRunHookMock.mockReset();
+ restoreArchivedSessionForSend.mockReset();
killProcessTreeMock.mockClear();
});
- it.each(['archived', 'deleted', 'missing'])('pauses a bound script with a %s owner before any hook or process', async (status) => {
+ it.each(['deleted', 'missing'])('pauses a bound script with a %s owner before any hook or process', async (status) => {
const pause = vi.fn(async () => undefined);
const db = { select: () => ({ from: () => ({ where: () => ({
limit: async () => status === 'missing' ? [] : [{ status }],
@@ -133,7 +136,7 @@ describe('ScriptScheduleRunner', () => {
expect(pause).not.toHaveBeenCalled();
});
- it.each(['active', 'archived'])('rechecks durable %s owner after a dispatch NOT_FOUND race', async (status) => {
+ it.each(['active', 'archived', 'deleted'])('rechecks durable %s owner after a dispatch NOT_FOUND race', async (status) => {
const child = childProcess();
spawnMock.mockReturnValue(child);
const pause = vi.fn(async () => undefined);
@@ -152,7 +155,27 @@ describe('ScriptScheduleRunner', () => {
child.stdout.write(JSON.stringify({ protocol: 'cindy-script/1', type: 'complete', resultText: 'not delivered' }) + '\n');
child.emit('close', 0);
await result;
- expect(pause).toHaveBeenCalledTimes(status === 'archived' ? 1 : 0);
+ expect(pause).toHaveBeenCalledTimes(status === 'deleted' ? 1 : 0);
+ });
+
+ // Archived script owners used to pause before any check. Run the production
+ // fire entry with an archived row and an idle hook; restore persists, no model runs.
+ it('restores an archived script owner and leaves it active after an idle check', async () => {
+ const owner = { status: 'archived' };
+ const db = { select: () => ({ from: () => ({ where: () => ({ limit: async () => [owner] }) }) }) };
+ restoreArchivedSessionForSend.mockImplementation(async () => { owner.status = 'active'; });
+ executePreRunHookMock.mockImplementation(async () => {
+ expect(owner.status).toBe('active');
+ return { decision: 'skip', exitCode: 2 };
+ });
+ const pause = vi.fn();
+ const runner = new ScriptScheduleRunner({ broker: { call: vi.fn() }, logger: {},
+ getDb: () => db as never, scheduler: { pause } as never });
+ await expect(runner.fire({ ...schedule(), targetSessionId: 'owner', preRunHook: { command: 'idle' } }, {
+ runId: 'run-owner', firedAt: 1, signal: new AbortController().signal,
+ })).resolves.toMatchObject({ skipped: true });
+ expect(owner.status).toBe('active');
+ expect(pause).not.toHaveBeenCalled();
});
it('pre-run hook exit 2 skips without creating a session or spawning the script', async () => {
diff --git a/apps/desktop/src/main/scheduler-host/restore-target.ts b/apps/desktop/src/main/scheduler-host/restore-target.ts
new file mode 100644
index 0000000000..cb67e4167f
--- /dev/null
+++ b/apps/desktop/src/main/scheduler-host/restore-target.ts
@@ -0,0 +1,41 @@
+import path from 'node:path';
+
+import { getManagedWorktreeBasePath } from '../../shared/managedWorktreePaths';
+import {
+ getSessionRowSnapshotStrict,
+ restoreArchivedSessionForSend,
+ type SessionRowSnapshot,
+} from '../localDb/ipc/sessions';
+import { withSessionRouteLock } from '../localDb/sessionRouteLock';
+
+/** Scheduled input uses the ordinary restore boundary, including its managed-task
+ * exclusions and multi-device status broadcast. Never archive again after a run. */
+export async function restoreScheduledTarget(
+ sessionId: string,
+ target: Pick<SessionRowSnapshot, 'status' | 'workingDir' | 'remoteHostId'>,
+ signal?: AbortSignal,
+): Promise<void> {
+ signal?.throwIfAborted();
+ const dir = target.workingDir;
+ const managed = !target.remoteHostId && dir && getManagedWorktreeBasePath(path.resolve(dir).replace(/\\/g, '/'));
+ if (target.status !== 'archived' && !managed) return;
+ await withSessionRouteLock(sessionId, async () => {
+ signal?.throwIfAborted();
+ if (target.status === 'archived') {
+ await restoreArchivedSessionForSend(sessionId, { routeLockHeld: true, signal });
+ } else {
+ const current = await getSessionRowSnapshotStrict(sessionId);
+ if (!current || current.status === 'archived' || current.status === 'deleted') {
+ throw new Error('Scheduled target became unavailable during preparation');
+ }
+ }
+ // Hooks run before native session startup. Reuse send-time snapshot recovery
+ // before either a hook or an Agent can touch a recycled managed worktree.
+ if (managed && dir) {
+ const { getManagedWorktreeReadinessForSession } = await import('../worktree/restore');
+ const ready = await getManagedWorktreeReadinessForSession(sessionId, dir);
+ if (ready !== 'ready') throw new Error('Scheduled task worktree could not be restored');
+ }
+ signal?.throwIfAborted();
+ });
+}
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 903118ff3e..a970f445a1 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -23,12 +23,8 @@ import {
* 一次 fire 的工作流:
* 1. effort 白名单校验 — 防止 user-input 把非法 effort 透传给 maker.createSession
* (Phase 2 mapper 没有运行时校验,runner 是最后一道关卡)。
- * 2. heartbeat 模式(schedule.targetSessionId 存在):并行查
- * a) maker.getSessionMeta → 拿 sdkSessionId 做 SDK resume
- * b) desktop sessions 表的 status 列 → 判断是否 archived/deleted
- * 命中兜底 → scheduler.pause(scheduleId) + notify failure + throw
- * (maker-core SessionMeta 已删 status 字段——archived 是 desktop 产品语义,
- * 存在 sessions.status enum,必须直查;详见 plan 文件 §「关键事实 #3」)
+ * 2. 绑定普通任务时,先按用户发送入口恢复已归档任务,再执行前置检查。
+ * 沿用原 sdkSessionId 恢复上下文;删除/丢失目标与 Bot 生命周期仍按各自规则处理。
* 3. workingDir:useWorktree=true 走 workdir-resolver 建 ephemeral worktree
* (绝不手动注册清理,maker-host:116-122 onClose 会自动清)
* 4. maker.createSession(heartbeat 模式不传 title,让现有 row 标题保留)
@@ -61,7 +57,6 @@ import type {
Effort,
PermissionMode,
Session,
- TurnContinuationState,
} from '@cindy/maker-core';
import { clampEffortToSupported } from '@cindy/model-providers';
import {
@@ -123,6 +118,7 @@ import { backfillSessionMeta } from './runners/_shared';
import { buildSkipResultText, executePreRunHook, formatPreRunHookFailure } from './pre-run-hook';
import { beginHeadlessGhostSetupTurn } from '../mcp-integrations/ghostSetupInteractionSurface.js';
import { terminalErrorText } from '../im/shared/turnRetryNotice.js';
+import { restoreScheduledTarget } from './restore-target';
const ALLOWED_EFFORT = new Set<string>([
'minimal',
@@ -808,14 +804,17 @@ export class MakerScheduleRunner implements ScheduleRunner {
throw new Error(errMsg);
}
- // Explicit retirement is checked before hooks: a broken external check must not
- // keep an archived task's heartbeat alive. Persistent automations still rebind;
- // bot routines retain their service-owned canonical-session lifecycle.
- if (schedule.source !== 'bot' && schedule.targetSessionId && !schedule.persistentSession) {
+ // A scheduled message restores its ordinary target just like user input.
+ // Do this before hooks/model selection, while keeping deleted-target behavior
+ // and service-owned Bot lifecycle separate.
+ if (schedule.source !== 'bot' && schedule.targetSessionId) {
const target = await getSessionRowSnapshot(schedule.targetSessionId);
- if (target?.status === 'archived' || target?.status === 'deleted') {
+ if (target?.status === 'deleted' && !schedule.persistentSession) {
return this.retireHeartbeat(schedule, ctx, target.status);
}
+ if (target && target.status !== 'deleted') {
+ await restoreScheduledTarget(schedule.targetSessionId, target, ctx.signal);
+ }
}
// 1.5 前置检查脚本(Pre-run Hook):放在 worktree 创建 / session 创建
@@ -995,12 +994,16 @@ export class MakerScheduleRunner implements ScheduleRunner {
if (archived) {
holder.releaseAgentSwitchLock?.();
holder.releaseAgentSwitchLock = undefined;
- // persistentSession=true:自我续命。清空死的 targetSessionId,本次 fire 走新建分支,
- // session 创建成功后 4.7.1 会重新绑定到新 sessionId。这样用户即便手动归档/删除
- // 了之前持续会话的 session,自动化也不会卡死,而是无感开新的继续跑。
+ // The user archived again during preparation. Consume this occurrence;
+ // do not undo that newer action or pause the recurring automation.
+ if (row?.status === 'archived' && schedule.source !== 'bot') {
+ return { sessionId, skipped: true, resultText: 'Scheduled target archived during preparation' };
+ }
+ // 持续任务的目标已删除/丢失时重新绑定;Bot 保留原有服务侧生命周期。
+ // 普通已归档任务已在入口恢复,不因归档创建替代任务。
if (schedule.persistentSession && this.scheduler) {
this.deps.logger.info?.(
- `[runner] persistent session ${sessionId} archived; auto-rebinding`,
+ `[runner] persistent session ${sessionId} unavailable; auto-rebinding`,
);
try {
await this.scheduler.update(schedule.id, { targetSessionId: undefined });
diff --git a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
index 7ec02d3ba1..ea98b40235 100644
--- a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
+++ b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
@@ -13,6 +13,7 @@ import {
} from '../cindy-brain/index.js';
import { validateFsRelPath } from '../cindy-brain/fsSlot.js';
import { tryGetOrcaCollabService } from '../maker-ipc/register.js';
+import { restoreArchivedSessionForSend } from '../localDb/ipc/sessions';
import type { ScriptCapabilityBroker, ScriptCapabilityCall } from './script-runner';
// model 兜底与 runner 同源(2026-06 曾因多份拷贝不同步导致 UI 显示与实跑模型不一致)
@@ -396,9 +397,15 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
fail('INVALID_ARGS', 'bound scripts can only dispatch to their target session');
}
const targetSessionId = schedule.targetSessionId ?? requestedTarget;
+ const message = requireString(params, 'message');
+ // Bound owners are restored once at fire admission. A later archive must
+ // not be undone by the same run. Unbound scripts first choose their target here.
+ if (targetSessionId && !schedule.targetSessionId) {
+ await restoreArchivedSessionForSend(targetSessionId);
+ }
const result = await service.sendToSession({
targetSessionId,
- message: requireString(params, 'message'),
+ message,
title: typeof params.title === 'string' ? params.title : undefined,
useWorktree: false,
// 投递到已有任务时沿用该任务自己的配置,只有新建任务才需要默认路由。
diff --git a/apps/desktop/src/main/scheduler-host/script-runner.ts b/apps/desktop/src/main/scheduler-host/script-runner.ts
index 6186e0da88..b95296d3fc 100644
--- a/apps/desktop/src/main/scheduler-host/script-runner.ts
+++ b/apps/desktop/src/main/scheduler-host/script-runner.ts
@@ -18,6 +18,7 @@ import { sessions } from '../localDb/schema';
import { buildSkipResultText, executePreRunHook, formatPreRunHookFailure } from './pre-run-hook';
import { capAppend, killProcessTree } from './proc-util';
import type { SchedulerDrizzleDb } from './storage';
+import { restoreScheduledTarget } from './restore-target';
const PROTOCOL = 'cindy-script/1' as const;
const LEGACY_PROTOCOL = 'xdt-maker-script/1' as const;
@@ -163,7 +164,7 @@ export class ScriptScheduleRunner {
}
}
- private async retireUnavailableOwner(schedule: Schedule, ctx: FireContext): Promise<FireResult | null> {
+ private async retireUnavailableOwner(schedule: Schedule, ctx: FireContext, restore = false): Promise<FireResult | null> {
// The owner is a lifecycle binding, not an agent execution mode. Check before
// hooks so idle scripts stop too, even when they have no event to dispatch.
if (schedule.targetSessionId) {
@@ -171,13 +172,14 @@ export class ScriptScheduleRunner {
throw new Error('bound script execution requires session storage and scheduler');
}
const [owner] = await this.deps.getDb()
- .select({ status: sessions.status }).from(sessions)
+ .select({ status: sessions.status, workingDir: sessions.workingDir, remoteHostId: sessions.remoteHostId }).from(sessions)
.where(eq(sessions.id, schedule.targetSessionId)).limit(1);
- if (!owner || owner.status === 'archived' || owner.status === 'deleted') {
+ if (!owner || owner.status === 'deleted') {
await this.deps.scheduler.pause(schedule.id, { exemptRunId: ctx.runId });
return { sessionId: '', skipped: true,
resultText: `Script stopped: target session ${owner?.status ?? 'missing'}` };
}
+ if (restore) await restoreScheduledTarget(schedule.targetSessionId, owner, ctx.signal);
}
return null;
@@ -196,7 +198,7 @@ export class ScriptScheduleRunner {
}
if (schedule.targetSessionId) {
- const retired = await this.retireUnavailableOwner(schedule, ctx);
+ const retired = await this.retireUnavailableOwner(schedule, ctx, true);
if (retired) return retired;
}
@@ -388,9 +390,9 @@ export class ScriptScheduleRunner {
: result;
writeFrame({ type: 'call_result', id: frame.id, ok: true, result: responseResult });
} catch (error) {
- // The owner may be archived after the pre-run check. Only a typed
- // dispatch rejection for this bound owner retires the schedule; transient
- // failures and unbound multi-target scripts keep their normal lifecycle.
+ // Recheck typed owner rejections after preparation. Only deleted/missing
+ // owners retire the schedule; archiving and transient dispatch failures
+ // leave the automation active for its next occurrence.
const failure = safeError(error);
if (schedule.targetSessionId && frame.method === 'sessions.dispatch'
&& (!frame.params?.target_session_id || frame.params.target_session_id === schedule.targetSessionId)
diff --git a/apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx b/apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx
index b5bae1acd9..e8af765408 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/BoundSessionCard.tsx
@@ -5,7 +5,7 @@ import { Button } from '@/components/ui/button';
* 仅用于 persistent 已绑(runner 回写 targetSessionId):该形态没有会话选择器,
* 需要卡片承载绑定信息。bound(手绑)形态由 ThreadPickerInline 单行选择器
* 承担,不用本卡片。内容:会话标题 + vendor 图标 + 打开会话 + 解除绑定 +
- * "归档后自动重建续绑"说明。
+ * "归档后恢复原任务"说明。
*
* 标题与生命周期由 main 层批量解析。project 自动化模式不传 onUnbind
* (loader 的 update input 不含 targetSessionId key,解绑无法落库,提供按钮只会
diff --git a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
index 88dad740f6..2f915b711b 100644
--- a/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/components/ScheduleFormDialog.tsx
@@ -853,8 +853,8 @@ export function ScheduleFormDialog({
<div className="flex flex-col gap-2.5">
<div className="flex flex-wrap items-center gap-2.5">
{/* "运行会话"三态:合并了旧 persistentSession 开关与手绑会话两个概念。
- fresh = 每次新建;persistent = 持续会话(首次 fire 创建后续绑,归档自动重建);
- bound = 绑定已有会话(picker 选,会话不可用时任务自动 pause)。
+ fresh = 每次新建;persistent = 持续会话(首次 fire 创建后续绑,归档后恢复原任务);
+ bound = 绑定已有会话(picker 选,归档后恢复,删除/丢失时自动 pause)。
project 自动化模式只显 fresh/persistent —— schedules.json 没有
targetSessionId 通道,bound 在该模式无法落库。 */}
<span className="text-13 leading-none text-[var(--settings-btn-secondary-text)]">
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.ts
index bc505c7796..92a6c658b8 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/archiveScheduleWarning.test.ts
@@ -100,7 +100,7 @@ describe('loadActiveBoundScheduleNames', () => {
}
});
- it('持续会话归档后会换绑新任务继续跑,不提示', async () => {
+ it('持续任务与普通绑定任务都会恢复原任务,均提示', async () => {
mocks.ensure.mockResolvedValue([
{
id: 'p',
@@ -114,7 +114,7 @@ describe('loadActiveBoundScheduleNames', () => {
const result = await loadActiveBoundScheduleNames([{ id: 'task' }]);
- expect(result.get('task')).toEqual(['Heartbeat']);
+ expect(result.get('task')).toEqual(['Persistent', 'Heartbeat']);
});
it('有缓存时直接使用,不等列表请求', async () => {
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.ts b/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.ts
index 3c9825e4f5..1526ac50cc 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/archiveScheduleWarning.ts
@@ -1,6 +1,5 @@
/**
- * 归档前的自动化提醒:绑定到已归档任务的自动化在下次触发时会被调度器暂停(持续会话
- * 除外,它会换绑新任务继续跑),归档入口据此升级到确认弹窗,让用户先知道。本机读
+ * 归档前的自动化提醒:绑定的自动化仍会运行,并像用户发送消息一样恢复原任务。本机读
* schedulesStore,远程任务读 remoteProjectsStore 的绑定分片;读取失败按「无绑定」处理。
*/
import type { Schedule } from '@cindy/maker-scheduler';
@@ -55,7 +54,7 @@ async function readRemoteBindingsOnce(
return Promise.race([load, timeout]);
}
-/** 每个任务归档后会停掉的自动化名称(active、非持续会话);没有的任务不出现在结果里。 */
+/** 每个任务绑定的 active 自动化名称;包含持续任务,没有的任务不出现在结果里。 */
export async function loadActiveBoundScheduleNames(
targets: readonly ArchiveTarget[],
): Promise<Map<string, string[]>> {
@@ -88,7 +87,7 @@ export async function loadActiveBoundScheduleNames(
: remoteProjectsStore.getSessionScheduleBindings(deviceId, target.id);
}
const names = bindings
- .filter((schedule) => schedule.status === 'active' && !schedule.persistentSession)
+ .filter((schedule) => schedule.status === 'active')
.map((schedule) => schedule.name);
if (names.length > 0) result.set(target.id, names);
}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts
index 33f7a73d50..58237c63b9 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleBindingIndex.ts
@@ -61,7 +61,7 @@ export function parseScheduleBindings(raw: unknown): ScheduleBinding[] {
manual: s.manual === true,
recurring: s.recurring as boolean | undefined,
intervalMs: s.intervalMs as number | undefined,
- // 持续会话在任务归档后会换绑新任务继续跑,归档确认据此不提示。
+ // 保留运行模式;持续与手动绑定的自动任务都会恢复已归档的普通任务。
...(s.persistentSession === true ? { persistentSession: true } : {}),
});
}
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
index b1ce997ad9..8ae0388bfe 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
@@ -8,9 +8,9 @@
* - RunMode 三态("运行会话"概念,合并 persistentSession 与手绑会话):
* fresh 每次新建会话(persistentSession=false, targetSessionId='')
* persistent 持续会话·自动创建(persistentSession=true;首次 fire 后
- * runner 回写 targetSessionId,归档自动重建续绑)
+ * runner 回写 targetSessionId,归档后恢复原任务)
* bound 绑定已有会话(targetSessionId=<id>, persistentSession=false;
- * 会话不可用时 runner 自动 pause)
+ * 归档后恢复原任务,删除/丢失时 runner 自动 pause)
* - buildScheduleInput:表单 → CreateScheduleInput(原 toInput 迁入)
*/
@@ -164,7 +164,7 @@ export interface ScheduleFormState {
targetSessionId: string;
/**
* 持续会话:true → runner 首次 fire 完把新建 sessionId 回写 targetSessionId,
- * 后续每次 fire 都在同一 session 中接着跑;会话被归档后自动重建续绑。
+ * 后续每次 fire 都在同一 session 中接着跑;归档后恢复原任务,删除/丢失后重建续绑。
* RunMode 三态中它是 persistent 与 bound 的判别器(bound 恒为 false)。
*/
persistentSession: boolean;
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 4962aaa5f6..374c9835b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -12893,10 +12893,10 @@
"title": "Archive session",
"description": "Archive this session? It will be removed from the list.",
"dirtyWorktreeWarning": "This session's worktree has uncommitted changes; they will be saved as a git snapshot before archiving and can be restored from the session later.",
- "scheduleWarning_one": "The automation {{names}} linked to this session will be paused after archiving.",
- "scheduleWarning_other": "The automations {{names}} linked to this session will be paused after archiving.",
- "scheduleWarningMany_one": "{{count}} of them has linked automations, which will be paused after archiving.",
- "scheduleWarningMany_other": "{{count}} of them have linked automations, which will be paused after archiving.",
+ "scheduleWarning_one": "The linked automation {{names}} will keep running and restore this session.",
+ "scheduleWarning_other": "The linked automations {{names}} will keep running and restore this session.",
+ "scheduleWarningMany_one": "{{count}} of these sessions has linked automations that will restore it when they run.",
+ "scheduleWarningMany_other": "{{count}} of these sessions have linked automations that will restore them when they run.",
"scheduleName": "“{{name}}”",
"scheduleNameSeparator": ", ",
"confirm": "Confirm",
@@ -13739,7 +13739,7 @@
"card": {
"open": "Open session",
"unbind": "Unbind",
- "persistentNote": "Recreates and rebinds automatically if the session is archived",
+ "persistentNote": "If archived, the same session is restored on the next run",
"deleted": "Bound session deleted",
"deletedPersistentNote": "Creates and binds a new session on the next run",
"fallbackTitle": "Session {{id}}"
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c1b89149a9..301bf3f133 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -12845,10 +12845,10 @@
"title": "セッションをアーカイブ",
"description": "このセッションをアーカイブしますか?アーカイブ後はリストから消えます。",
"dirtyWorktreeWarning": "このセッションのワークツリーには未コミットの変更があります。アーカイブ前に git スナップショットとして自動保存され、後でセッションから復元できます。",
- "scheduleWarning_one": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",
- "scheduleWarning_other": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",
- "scheduleWarningMany_one": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",
- "scheduleWarningMany_other": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",
+ "scheduleWarning_one": "関連する自動化{{names}}は引き続き実行され、その際にこのセッションを復元します。",
+ "scheduleWarning_other": "関連する自動化{{names}}は引き続き実行され、その際にこのセッションを復元します。",
+ "scheduleWarningMany_one": "{{count}} 件のセッションに自動化が紐づいており、次回実行時にセッションが復元されます。",
+ "scheduleWarningMany_other": "{{count}} 件のセッションに自動化が紐づいており、次回実行時にセッションが復元されます。",
"scheduleName": "「{{name}}」",
"scheduleNameSeparator": "、",
"confirm": "確認",
@@ -13691,7 +13691,7 @@
"card": {
"open": "セッションを開く",
"unbind": "連携を解除",
- "persistentNote": "セッションがアーカイブされると自動的に再作成して連携を継続します",
+ "persistentNote": "アーカイブ後も、次回実行時に元のセッションが復元されます",
"deleted": "連携先セッションは削除されました",
"deletedPersistentNote": "次回の実行時に新しいセッションを作成して再連携します",
"fallbackTitle": "セッション {{id}}"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a1381d3215..4abdb5395e 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -12845,10 +12845,10 @@
"title": "세션 보관",
"description": "이 세션을 보관하시겠습니까? 보관 후 목록에서 사라집니다.",
"dirtyWorktreeWarning": "이 세션의 워크트리에 커밋되지 않은 변경 사항이 있습니다. 보관 전에 git 스냅샷으로 자동 저장되며 나중에 세션에서 복원할 수 있습니다.",
- "scheduleWarning_one": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",
- "scheduleWarning_other": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",
- "scheduleWarningMany_one": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",
- "scheduleWarningMany_other": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",
+ "scheduleWarning_one": "연결된 자동화 {{names}}은(는) 계속 실행되며 이 세션을 복원합니다.",
+ "scheduleWarning_other": "연결된 자동화 {{names}}은(는) 계속 실행되며 이 세션을 복원합니다.",
+ "scheduleWarningMany_one": "{{count}}개 세션에 자동화가 연결되어 있으며, 다음 실행 시 해당 세션이 복원됩니다.",
+ "scheduleWarningMany_other": "{{count}}개 세션에 자동화가 연결되어 있으며, 다음 실행 시 해당 세션이 복원됩니다.",
"scheduleName": "\"{{name}}\"",
"scheduleNameSeparator": ", ",
"confirm": "확인",
@@ -13691,7 +13691,7 @@
"card": {
"open": "세션 열기",
"unbind": "연결 해제",
- "persistentNote": "세션이 보관되면 자동으로 다시 만들어 연결을 이어갑니다",
+ "persistentNote": "보관된 세션은 다음 실행 시 같은 세션으로 복원됩니다",
"deleted": "연결된 세션이 삭제되었습니다",
"deletedPersistentNote": "다음 실행 시 새 세션을 만들어 다시 연결합니다",
"fallbackTitle": "세션 {{id}}"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 3869f09855..3ac53e0a20 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -12845,10 +12845,10 @@
"title": "归档任务",
"description": "确定要归档这个任务吗?归档后将从列表中移除。",
"dirtyWorktreeWarning": "该任务的 worktree 有未提交的更改;归档前会自动保存为 git 快照,之后可在任务内一键恢复。",
- "scheduleWarning_one": "该任务绑定了自动化{{names}},归档后将暂停。",
- "scheduleWarning_other": "该任务绑定了自动化{{names}},归档后将暂停。",
- "scheduleWarningMany_one": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",
- "scheduleWarningMany_other": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",
+ "scheduleWarning_one": "关联的自动化{{names}}仍会运行,并恢复此任务。",
+ "scheduleWarning_other": "关联的自动化{{names}}仍会运行,并恢复此任务。",
+ "scheduleWarningMany_one": "其中 {{count}} 个任务关联了自动化,后续运行时会恢复这些任务。",
+ "scheduleWarningMany_other": "其中 {{count}} 个任务关联了自动化,后续运行时会恢复这些任务。",
"scheduleName": "「{{name}}」",
"scheduleNameSeparator": "、",
"confirm": "确认",
@@ -13691,7 +13691,7 @@
"card": {
"open": "打开任务",
"unbind": "解除绑定",
- "persistentNote": "任务归档后会自动重建并续绑",
+ "persistentNote": "任务归档后,下次运行会恢复原任务",
"deleted": "绑定任务已删除",
"deletedPersistentNote": "下次运行时会自动创建新任务并续绑",
"fallbackTitle": "任务 {{id}}"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 69980f9bef..98dea0f174 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -12845,10 +12845,10 @@
"title": "歸檔任務",
"description": "確定要歸檔這個任務嗎?歸檔後將從列表中移除。",
"dirtyWorktreeWarning": "該任務的 worktree 有未提交的更改;歸檔前會自動儲存為 git 快照,之後可在任務內一鍵恢復。",
- "scheduleWarning_one": "該任務繫結了自動化{{names}},歸檔後將暫停。",
- "scheduleWarning_other": "該任務繫結了自動化{{names}},歸檔後將暫停。",
- "scheduleWarningMany_one": "其中 {{count}} 個任務繫結了自動化,歸檔後這些自動化將暫停。",
- "scheduleWarningMany_other": "其中 {{count}} 個任務繫結了自動化,歸檔後這些自動化將暫停。",
+ "scheduleWarning_one": "關聯的自動化{{names}}仍會執行,並恢復此任務。",
+ "scheduleWarning_other": "關聯的自動化{{names}}仍會執行,並恢復此任務。",
+ "scheduleWarningMany_one": "其中 {{count}} 個任務關聯了自動化,後續執行時會恢復這些任務。",
+ "scheduleWarningMany_other": "其中 {{count}} 個任務關聯了自動化,後續執行時會恢復這些任務。",
"scheduleName": "「{{name}}」",
"scheduleNameSeparator": "、",
"confirm": "確認",
@@ -13691,7 +13691,7 @@
"card": {
"open": "開啟任務",
"unbind": "解除繫結",
- "persistentNote": "任務歸檔後會自動重建並續綁",
+ "persistentNote": "任務歸檔後,下次執行會恢復原任務",
"deleted": "繫結任務已刪除",
"deletedPersistentNote": "下次執行時會自動建立新任務並續綁",
"fallbackTitle": "任務 {{id}}"
diff --git a/apps/mobile/src/__tests__/archiveScheduleConfirm.test.ts b/apps/mobile/src/__tests__/archiveScheduleConfirm.test.ts
index 6dd7e32a66..a80bf539e0 100644
--- a/apps/mobile/src/__tests__/archiveScheduleConfirm.test.ts
+++ b/apps/mobile/src/__tests__/archiveScheduleConfirm.test.ts
@@ -35,13 +35,13 @@ describe('archive schedule lookup deadline', () => {
await expect(bulk).resolves.toBe(0);
});
- it('still reports active non-persistent bindings that arrive in time', async () => {
+ it('reports both ordinary and persistent active bindings that will restore the task', async () => {
mocks.list.mockResolvedValue([
{ id: 'a', name: 'Daily', status: 'active', targetSessionId: 'task' },
{ id: 'b', name: 'Persistent', status: 'active', targetSessionId: 'task', persistentSession: true },
]);
- await expect(loadActiveBoundScheduleNames(args)).resolves.toEqual(['Daily']);
+ await expect(loadActiveBoundScheduleNames(args)).resolves.toEqual(['Daily', 'Persistent']);
});
it('asks only for the binding projection so a large list cannot overflow the frame', async () => {
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index e39ad3ce50..6a6482e555 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -439,12 +439,12 @@
"deleteConfirmTitle": "Delete session?",
"deleteConfirmBody": "This can't be undone.",
"archiveScheduleConfirmTitle": "Archive session?",
- "archiveScheduleConfirmBody_one": "The automation {{names}} linked to this session will be paused after archiving.",
- "archiveScheduleConfirmBody_other": "The automations {{names}} linked to this session will be paused after archiving.",
+ "archiveScheduleConfirmBody_one": "The linked automation {{names}} will keep running and restore this session.",
+ "archiveScheduleConfirmBody_other": "The linked automations {{names}} will keep running and restore this session.",
"archiveScheduleName": "“{{name}}”",
"archiveScheduleNameSeparator": ", ",
- "archiveScheduleBulkNotice_one": "{{count}} of them has linked automations, which will be paused after archiving.",
- "archiveScheduleBulkNotice_other": "{{count}} of them have linked automations, which will be paused after archiving.",
+ "archiveScheduleBulkNotice_one": "{{count}} of these sessions has linked automations that will restore it when they run.",
+ "archiveScheduleBulkNotice_other": "{{count}} of these sessions have linked automations that will restore them when they run.",
"dirAlreadyAdded": "This directory is already in the list.",
"resetCodexTitle": "Reset Codex usage?",
"resetCodexBody": "This uses 1 reset for {{account}}. The quota window reopens immediately and this can't be undone.",
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index 1f4e1e8101..68e0db8e21 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -439,12 +439,12 @@
"deleteConfirmTitle": "セッションを削除しますか?",
"deleteConfirmBody": "削除すると元に戻せません。",
"archiveScheduleConfirmTitle": "セッションをアーカイブしますか?",
- "archiveScheduleConfirmBody_one": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",
- "archiveScheduleConfirmBody_other": "このセッションに紐づく自動化{{names}}は、アーカイブ後に一時停止されます。",
+ "archiveScheduleConfirmBody_one": "関連する自動化{{names}}は引き続き実行され、その際にこのセッションを復元します。",
+ "archiveScheduleConfirmBody_other": "関連する自動化{{names}}は引き続き実行され、その際にこのセッションを復元します。",
"archiveScheduleName": "「{{name}}」",
"archiveScheduleNameSeparator": "、",
- "archiveScheduleBulkNotice_one": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",
- "archiveScheduleBulkNotice_other": "そのうち {{count}} 件のセッションに自動化が紐づいており、アーカイブ後に一時停止されます。",
+ "archiveScheduleBulkNotice_one": "{{count}} 件のセッションに自動化が紐づいており、次回実行時にセッションが復元されます。",
+ "archiveScheduleBulkNotice_other": "{{count}} 件のセッションに自動化が紐づいており、次回実行時にセッションが復元されます。",
"dirAlreadyAdded": "このディレクトリはすでにリストにあります。",
"resetCodexTitle": "Codex の使用量をリセットしますか?",
"resetCodexBody": "{{account}} のリセットを 1 回消費します。クォータウィンドウはすぐに再開され、この操作は取り消せません。",
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index 47304e9f25..2762e89bad 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -435,12 +435,12 @@
"deleteConfirmTitle": "세션을 삭제할까요?",
"deleteConfirmBody": "삭제하면 되돌릴 수 없습니다.",
"archiveScheduleConfirmTitle": "세션을 보관할까요?",
- "archiveScheduleConfirmBody_one": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",
- "archiveScheduleConfirmBody_other": "이 세션에 연결된 자동화 {{names}}은(는) 보관 후 일시중지됩니다.",
+ "archiveScheduleConfirmBody_one": "연결된 자동화 {{names}}은(는) 계속 실행되며 이 세션을 복원합니다.",
+ "archiveScheduleConfirmBody_other": "연결된 자동화 {{names}}은(는) 계속 실행되며 이 세션을 복원합니다.",
"archiveScheduleName": "\"{{name}}\"",
"archiveScheduleNameSeparator": ", ",
- "archiveScheduleBulkNotice_one": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",
- "archiveScheduleBulkNotice_other": "그중 {{count}}개 세션에 자동화가 연결되어 있으며, 보관 후 일시중지됩니다.",
+ "archiveScheduleBulkNotice_one": "{{count}}개 세션에 자동화가 연결되어 있으며, 다음 실행 시 해당 세션이 복원됩니다.",
+ "archiveScheduleBulkNotice_other": "{{count}}개 세션에 자동화가 연결되어 있으며, 다음 실행 시 해당 세션이 복원됩니다.",
"dirAlreadyAdded": "이 디렉터리는 이미 목록에 있습니다.",
"resetCodexTitle": "Codex 사용량을 재설정할까요?",
"resetCodexBody": "{{account}}에 대해 재설정 1회를 사용합니다. 사용량 창이 즉시 다시 열리며 이 작업은 취소할 수 없습니다.",
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index 235e076082..032cbf2047 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -435,12 +435,12 @@
"deleteConfirmTitle": "删除任务?",
"deleteConfirmBody": "删除后不可恢复。",
"archiveScheduleConfirmTitle": "归档任务?",
- "archiveScheduleConfirmBody_one": "该任务绑定了自动化{{names}},归档后将暂停。",
- "archiveScheduleConfirmBody_other": "该任务绑定了自动化{{names}},归档后将暂停。",
+ "archiveScheduleConfirmBody_one": "关联的自动化{{names}}仍会运行,并恢复此任务。",
+ "archiveScheduleConfirmBody_other": "关联的自动化{{names}}仍会运行,并恢复此任务。",
"archiveScheduleName": "「{{name}}」",
"archiveScheduleNameSeparator": "、",
- "archiveScheduleBulkNotice_one": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",
- "archiveScheduleBulkNotice_other": "其中 {{count}} 个任务绑定了自动化,归档后这些自动化将暂停。",
+ "archiveScheduleBulkNotice_one": "其中 {{count}} 个任务关联了自动化,后续运行时会恢复这些任务。",
+ "archiveScheduleBulkNotice_other": "其中 {{count}} 个任务关联了自动化,后续运行时会恢复这些任务。",
"dirAlreadyAdded": "这个目录已经在列表里。",
"resetCodexTitle": "重置 Codex 用量?",
"resetCodexBody": "将为 {{account}} 消耗 1 次重置。配额窗口会立即重开,此操作不能撤销。",
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index aebfeb1044..2beee6a54d 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -439,12 +439,12 @@
"deleteConfirmTitle": "刪除任務?",
"deleteConfirmBody": "刪除後不可恢復。",
"archiveScheduleConfirmTitle": "歸檔任務?",
- "archiveScheduleConfirmBody_one": "該任務繫結了自動化{{names}},歸檔後將暫停。",
- "archiveScheduleConfirmBody_other": "該任務繫結了自動化{{names}},歸檔後將暫停。",
+ "archiveScheduleConfirmBody_one": "關聯的自動化{{names}}仍會執行,並恢復此任務。",
+ "archiveScheduleConfirmBody_other": "關聯的自動化{{names}}仍會執行,並恢復此任務。",
"archiveScheduleName": "「{{name}}」",
"archiveScheduleNameSeparator": "、",
- "archiveScheduleBulkNotice_one": "其中 {{count}} 個任務繫結了自動化,歸檔後這些自動化將暫停。",
- "archiveScheduleBulkNotice_other": "其中 {{count}} 個任務繫結了自動化,歸檔後這些自動化將暫停。",
+ "archiveScheduleBulkNotice_one": "其中 {{count}} 個任務關聯了自動化,後續執行時會恢復這些任務。",
+ "archiveScheduleBulkNotice_other": "其中 {{count}} 個任務關聯了自動化,後續執行時會恢復這些任務。",
"dirAlreadyAdded": "這個目錄已經在列表裡。",
"resetCodexTitle": "重置 Codex 用量?",
"resetCodexBody": "將為 {{account}} 消耗 1 次重置。配額視窗會立即重開,此操作不能撤銷。",
diff --git a/apps/mobile/src/session/archiveScheduleConfirm.ts b/apps/mobile/src/session/archiveScheduleConfirm.ts
index 89f143fafe..9bdc39f187 100644
--- a/apps/mobile/src/session/archiveScheduleConfirm.ts
+++ b/apps/mobile/src/session/archiveScheduleConfirm.ts
@@ -6,8 +6,8 @@ import type { RemoteInvoke } from '@/device-link/mobileMakerTransport';
import { sessionMayHaveScheduleRuns } from '@/session/scheduleIndex';
/**
- * 归档前的自动化提醒:绑定到已归档任务的自动化在下次触发时会被电脑暂停(持续会话除外,
- * 它会换绑新任务继续跑),归档前先让用户知道。已知未绑定的普通任务直接放行,不额外请求;
+ * 归档前的自动化提醒:绑定的自动化仍会运行,并像用户发送消息一样恢复原任务。
+ * 已知未绑定的普通任务直接放行,不额外请求;
* 读取失败或超过等待上限按无绑定处理。
*/
/** 查询自动化列表的等待上限:超时按「无绑定」处理,不让归档卡在远程请求上(通道超时预算可达 40 秒)。 */
@@ -31,8 +31,8 @@ function listBindingSchedules(deviceId: string, invoke: RemoteInvoke): Promise<u
return invoke(deviceId, 'maker:schedule:list', [null, { sessionBindings: true }]);
}
-function stopsWhenTargetArchived(schedule: RemoteSchedule): boolean {
- return schedule.status === 'active' && !schedule.persistentSession && !!schedule.targetSessionId;
+function hasActiveTarget(schedule: RemoteSchedule): boolean {
+ return schedule.status === 'active' && !!schedule.targetSessionId;
}
export interface BulkArchiveCandidate {
@@ -48,7 +48,7 @@ export function anyMayHaveBoundSchedules(
return candidates.some((c) => sessionMayHaveScheduleRuns(deviceId, c.id, c.source));
}
-/** 批量归档:所选任务里归档后会停掉自动化的任务数(最多一次列表请求;全部已知无绑定则不请求;失败按 0)。 */
+/** 批量归档:所选任务里绑定了 active 自动化的任务数(最多一次列表请求;全部已知无绑定则不请求;失败按 0)。 */
export async function countSessionsWithActiveBoundSchedules(
deviceId: string,
invoke: RemoteInvoke,
@@ -59,7 +59,7 @@ export async function countSessionsWithActiveBoundSchedules(
const ids = new Set(candidates.map((c) => c.id));
const bound = new Set(
normalizeScheduleList(await withLookupDeadline(listBindingSchedules(deviceId, invoke), []))
- .filter((schedule) => stopsWhenTargetArchived(schedule) && ids.has(schedule.targetSessionId!))
+ .filter((schedule) => hasActiveTarget(schedule) && ids.has(schedule.targetSessionId!))
.map((schedule) => schedule.targetSessionId),
);
return bound.size;
@@ -85,14 +85,14 @@ export async function loadActiveBoundScheduleNames({
await withLookupDeadline(listBindingSchedules(deviceId, invoke), []),
);
return schedules
- .filter((schedule) => schedule.targetSessionId === sessionId && stopsWhenTargetArchived(schedule))
+ .filter((schedule) => schedule.targetSessionId === sessionId && hasActiveTarget(schedule))
.map((schedule) => schedule.name || schedule.id);
} catch {
return [];
}
}
-/** 有会停掉的自动化时弹系统确认;没有直接返回 true。 */
+/** 有 active 自动化时提示后续会恢复任务;没有直接返回 true。 */
export function confirmArchiveWithSchedules(t: TFunction, names: readonly string[]): Promise<boolean> {
if (names.length === 0) return Promise.resolve(true);
return new Promise((resolve) => {
diff --git a/docs/product-rules/core-product-principles.md b/docs/product-rules/core-product-principles.md
index b792592aa5..f4759c514b 100644
--- a/docs/product-rules/core-product-principles.md
+++ b/docs/product-rules/core-product-principles.md
@@ -123,6 +123,13 @@ Cindy 应让用户方便地接入、选择和使用不同 Agent 与模型,同
- 切换设备或断线重连后,用户不需要重新解释已经存在的上下文。
- 多端状态冲突、权限与操作归属必须有确定规则,不能依赖用户猜测。
+#### 自动任务与归档
+
+自动任务向已归档的普通任务发送输入,等同于用户向该任务发送消息:先恢复原任务,
+沿用其会话历史与工作目录,再按普通任务流程运行,完成后保持恢复状态。
+归档不代表暂停自动任务,也不应仅因归档而另建替代任务;停止后续运行应使用自动任务的暂停入口。
+删除目标以及伙伴、协作工作任务的服务侧生命周期仍遵循各自规则。
+
#### 目标模式与补充消息
目标运行期间,普通补充、问进度、排队消息与同轮插话优先处理,结束后继续原目标。
diff --git a/packages/lizi-mcps/src/scheduler/create.ts b/packages/lizi-mcps/src/scheduler/create.ts
index a81b75e39e..dfaca11c9c 100644
--- a/packages/lizi-mcps/src/scheduler/create.ts
+++ b/packages/lizi-mcps/src/scheduler/create.ts
@@ -43,7 +43,7 @@ export function registerScheduleCreateTool(
'(7) 确定是检查时显式设 silentWhenIdle=true(无变化不播报);提醒/定时发送设 false,保留用户选择。省略此字段会按 false 处理,避免旧调用方的提醒被吞。如果用户定义了提醒条件,把条件保留在 prompt 里(如 CI 失败/新评论时提醒),有结果时用 schedule_notify_current_run 主动上报;' +
'(8) 轮询型任务("有新 PR 才 review / CI 挂了才处理")优先配 preRunHook 前置检查(exit 0=放行、exit 2=跳过本轮不烧 token;报错/超时 fail-closed 阻止本轮并记录失败)。**脚本一律经 schedule_set_pre_run_hook 创建/修改**(落盘路径、协议、自测由宿主代码统一保证),不要自己写脚本文件再手填 preRunHook.command——先调它拿 command 再来创建,或创建后传 scheduleId 让它直接挂载;' +
'(9) 既有工作流程中的自动跟进,沿用该流程明确的频率、执行引擎、静默与通知默认值;用户在线也不需要为这些默认值另行确认。用户主动新建独立任务时,若关键实体或会实质改变目标的参数缺失,先询问,不盲猜;用户已明确说明或已有流程定义的参数不重复问。' +
- '(10) **仅运行脚本模式(零 token)**:executionMode="script" 时不启动 agent,宿主直接执行 scriptConfig.command(cwd=workingDir,必填本地项目目录);脚本经 stdout/stdin 的 cindy-script/1 JSONL 协议回调宿主受限能力,能力按 scriptConfig.capabilities 白名单授予(默认全拒)。script 模式不需要 prompt(可省),不支持 useWorktree / persistentSession。单任务跟进应传 bindToCurrentSession=true 或 targetSessionId:它是脚本的生命周期绑定及唯一投递目标,目标归档、删除或不存在时自动暂停,恢复任务不会自动恢复调度。未绑定脚本保留独立任务语义。与 preRunHook 的分工:preRunHook 只是"要不要跑"的闸门,script 模式是"任务本体就是脚本"。',
+ '(10) **仅运行脚本模式(零 token)**:executionMode="script" 时不启动 agent,宿主直接执行 scriptConfig.command(cwd=workingDir,必填本地项目目录);脚本经 stdout/stdin 的 cindy-script/1 JSONL 协议回调宿主受限能力,能力按 scriptConfig.capabilities 白名单授予(默认全拒)。script 模式不需要 prompt(可省),不支持 useWorktree / persistentSession。单任务跟进应传 bindToCurrentSession=true 或 targetSessionId:它是脚本的生命周期绑定及唯一投递目标,普通目标归档后会像用户发消息一样恢复原任务,完成后保持激活;目标删除或不存在时自动暂停,恢复任务不会自动恢复已暂停的调度。未绑定脚本保留独立任务语义。与 preRunHook 的分工:preRunHook 只是"要不要跑"的闸门,script 模式是"任务本体就是脚本"。',
inputShape: {
name: z.string().min(1).describe('展示名(GUI / 通知里出现)'),
prompt: z
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index be7c2bf2d8..fe38911e3e 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -256,9 +256,9 @@ export interface Schedule {
*
* 与 MCP 显式指定 `targetSessionId` 的"手绑 session"模式正交:显式绑定本身已经
* 达到等效效果,`persistentSession=true` 在那种 schedule 上是 no-op;
- * 绑定的 session 若被归档/删除:persistentSession=true → runner 自动清空
- * targetSessionId 并本次 fire 走新建分支(自我续命);persistentSession=false
- * → 维持旧行为 pause 整条 schedule。
+ * 绑定的普通任务被归档时,自动输入与用户发送一样恢复原任务,完成后不重新归档。
+ * 仅当任务被删除或不存在时:persistentSession=true → runner 清空
+ * targetSessionId 并走新建分支;persistentSession=false → pause 整条 schedule。
*/
persistentSession?: boolean;
/**