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): 恢复后清除自动运行告警并区分前置检查受阻 (#4355)

Dashee4452b06ab6
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/hookScriptGenerator.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/hookScriptGenerator.test.ts
index 49c16c2433..9f884807b3 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/hookScriptGenerator.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/hookScriptGenerator.test.ts
@@ -150,6 +150,8 @@ describe('buildHookScriptPrompt', () => {
currentScript: 'process.exit(0)',
});
expect(prompt).toContain('Exit code 0');
+ expect(prompt).toContain('CINDY_PRECHECK_OK as a standalone stdout line before exit 0 or 2');
+ expect(prompt).toContain('Never emit it for rate-limit/backoff skips or incomplete/degraded checks');
expect(prompt).toContain('Windows');
expect(prompt).toContain('有新 PR 才跑');
expect(prompt).toContain('C:/repo');
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts
index 15f7f46236..f1a3bcfd2a 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/preRunHook.test.ts
@@ -25,6 +25,13 @@ const payload: PreRunHookStdinPayload = {
};
describe('executePreRunHook', () => {
+ it.each([0, 1, 2])('only successful exits can attest healthy checks (exit %s)', async (exitCode) => {
+ const result = await executePreRunHook({
+ command: `node -e "console.log('CINDY_PRECHECK_OK'); process.exit(${exitCode})"`,
+ stdinPayload: payload,
+ });
+ expect(result.checkSucceeded).toBe(exitCode === 1 ? undefined : true);
+ });
it('exit 0 → decision run', async () => {
const result = await executePreRunHook({
command: 'node -e "process.exit(0)"',
@@ -44,6 +51,7 @@ describe('executePreRunHook', () => {
});
expect(result.decision).toBe('skip');
expect(result.status).toBe('skipped');
+ expect(result.checkSucceeded).toBeUndefined();
expect(result.exitCode).toBe(2);
});
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 1ed01c88df..5bd9635722 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerPreRunHookCwd.test.ts
@@ -104,6 +104,17 @@ 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) => {
+ mocks.getSessionRowSnapshot.mockResolvedValueOnce({ status });
+ const { runner, notifier } = createRunner(vi.fn() as never);
+ const pause = vi.fn(async () => undefined);
+ runner.attachScheduler({ pause } as never);
+ const result = await runner.fire(baseSchedule({ targetSessionId: 'retired-session' }), createFireContext());
+ expect(result).toMatchObject({ skipped: true });
+ expect(pause).toHaveBeenCalledWith('schedule-1', { exemptRunId: 'run-1' });
+ expect(mocks.executePreRunHook).not.toHaveBeenCalled();
+ expect(notifier.notify).not.toHaveBeenCalled();
+ });
beforeEach(() => {
vi.clearAllMocks();
// hook 判 skip → fire 在 hook 分支内早退,不进 session 创建,测试聚焦 cwd 传参
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 37cc535185..4d7d7eb432 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerSendOutcome.test.ts
@@ -419,7 +419,7 @@ describe('MakerScheduleRunner send outcome policy', () => {
expect(h.send).not.toHaveBeenCalled();
});
- it('releases the heartbeat route lock before reporting an archived target', async () => {
+ it.each([false, true])('retires an archived target and releases an acquired lock (racing=%s)', async (racing) => {
const order: string[] = [];
const h = createSessionHarness(async () => ({ accepted: true }));
const releaseAgentSwitchLock = vi.fn(() => {
@@ -435,16 +435,37 @@ describe('MakerScheduleRunner send outcome policy', () => {
userSendAt: null,
providerId: null,
});
+ if (racing) mocks.getSessionRowSnapshot.mockResolvedValueOnce({ status: 'active', userSendAt: null, providerId: null });
+ const pause = vi.fn(async () => { order.push('pause'); });
+ runner.attachScheduler({ pause } as never);
await expect(
runner.fire(
baseSchedule({ targetSessionId: 'scheduler-session' }),
createFireContext(),
),
- ).rejects.toThrow(/target session not available/);
+ ).resolves.toMatchObject({ skipped: true });
- expect(order).toEqual(['release', 'notify']);
- expect(releaseAgentSwitchLock).toHaveBeenCalledTimes(1);
+ expect(order).toEqual(racing ? ['release', 'pause'] : ['pause']);
+ expect(acquirePendingAgentSwitch).toHaveBeenCalledTimes(racing ? 1 : 0);
+ expect(pause).toHaveBeenCalledWith('schedule-1', { exemptRunId: 'run-1' });
+ expect(notifier.notify).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 }));
+ const acquirePendingAgentSwitch = vi.fn(async () => () => { order.push('release'); });
+ const { runner, notifier } = createRunnerHarness(h.session, { acquirePendingAgentSwitch });
+ notifier.notify.mockImplementation(async () => { order.push('notify'); });
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status, userSendAt: null, providerId: null });
+ const pause = vi.fn(async () => { order.push('pause'); throw new Error('Schedule not found: schedule-1'); });
+ runner.attachScheduler({ pause } as never);
+ await expect(runner.fire(baseSchedule({ source: 'bot', manual: true, targetSessionId: 'scheduler-session' }),
+ createFireContext())).rejects.toThrow(`target session not available (${status})`);
+ expect(order).toEqual(['release', 'pause', 'notify']);
+ expect(pause).toHaveBeenCalledWith('schedule-1', { exemptRunId: 'run-1' });
expect(h.send).not.toHaveBeenCalled();
});
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
index 2abf94caf7..986eb07d68 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/storage.db.test.ts
@@ -138,6 +138,7 @@ const SCHEDULER_DDL = [
manual INTEGER NOT NULL DEFAULT 0,
interval_ms INTEGER,
agent_kind TEXT NOT NULL,
+ model_agent_kind TEXT,
model TEXT,
provider_id TEXT,
effort TEXT,
@@ -480,6 +481,70 @@ describe('DrizzleScheduleStorage (in-memory)', () => {
}
});
+ it('recovers warnings per automation without erasing unread history; healthy skips only recover checks', async () => {
+ const harness = createStorageHarness();
+ try {
+ harness.db.run(sql`INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at)
+ VALUES ('recovery-session', 'Recovery', 'desktop', 'dialogue', 1, 1)`);
+ await harness.storage.insert(baseSchedule({ id: 'recovery-a' }));
+ await harness.storage.insert(baseSchedule({ id: 'recovery-b' }));
+ const hook = { status: 'failed', decision: 'block', exitCode: 1, durationMs: 1,
+ stdout: '', stderr: 'API rate limit already exceeded', stdoutTruncated: false,
+ stderrTruncated: false, timedOut: false, aborted: false } as const;
+ const insert = (id: string, scheduleId: string, firedAt: number, status: ScheduleRun['status'], extra: Partial<ScheduleRun> = {}) =>
+ harness.storage.insertRun({ id, scheduleId, firedAt, status, sessionId: 'recovery-session', ...extra });
+ await insert('execution-a', 'recovery-a', 1, 'failed', { readAt: 2 });
+ await insert('check-b', 'recovery-b', 3, 'failed', { preRunHookResult: hook });
+ const before = await harness.storage.listSidebarIndexRuns();
+ expect(before.find((r) => r.runId === 'check-b')).toMatchObject({ failureKind: 'rate-limit', failureRecovered: false });
+ await insert('backoff-b', 'recovery-b', 4, 'skipped');
+ expect((await harness.storage.listSidebarIndexRuns()).find((r) => r.runId === 'check-b')?.failureRecovered).toBe(false);
+ await insert('healthy-b', 'recovery-b', 5, 'skipped', { preRunHookResult: { ...hook, status: 'skipped', decision: 'skip', exitCode: 2, checkSucceeded: true } });
+ const recovered = await harness.storage.listSidebarIndexRuns();
+ expect(recovered.find((r) => r.runId === 'check-b')).toMatchObject({ status: 'failed', readAt: undefined, failureRecovered: true });
+ expect(recovered.find((r) => r.runId === 'execution-a')?.failureRecovered).toBe(false);
+ await insert('healthy-a', 'recovery-a', 6, 'skipped', { preRunHookResult: { ...hook, status: 'skipped', decision: 'skip', exitCode: 2, checkSucceeded: true } });
+ expect((await harness.storage.listSidebarIndexRuns()).find((r) => r.runId === 'execution-a')).toBeDefined();
+ await insert('success-a', 'recovery-a', 7, 'success', { readAt: 8 });
+ expect((await harness.storage.listSidebarIndexRuns()).some((r) => r.runId === 'execution-a')).toBe(false);
+ expect((await harness.storage.listRuns('recovery-a', 50)).some((r) => r.id === 'execution-a')).toBe(true);
+ await insert('new-a', 'recovery-a', 9, 'failed');
+ expect((await harness.storage.listSidebarIndexRuns()).find((r) => r.runId === 'new-a')).toMatchObject({ failureRecovered: false, failureKind: 'execution' });
+ } finally { harness.close(); }
+ });
+
+ it.each([null, '{broken', '{}', '{"decision":"skip"}'])('classifies and recovers legacy precheck errors when hook metadata is %s', async (hookJson) => {
+ const harness = createStorageHarness();
+ try {
+ harness.db.run(sql`INSERT INTO sessions (id, title, source, workspace_kind, created_at, updated_at)
+ VALUES ('legacy-check-session', 'Check', 'desktop', 'dialogue', 1, 1)`);
+ await harness.storage.insert(baseSchedule());
+ await harness.storage.insertRun({ id: 'legacy-check', scheduleId: 'sch-1', firedAt: 1,
+ status: 'failed', sessionId: 'legacy-check-session', errorMsg: 'pre-run hook blocked: unavailable' });
+ harness.db.run(sql`UPDATE schedule_runs SET pre_run_hook_result = ${hookJson} WHERE id = 'legacy-check'`);
+ expect(await harness.storage.listSidebarIndexRuns()).toEqual([
+ expect.objectContaining({ runId: 'legacy-check', failureKind: 'precheck' }),
+ ]);
+ await harness.storage.insertRun({ id: 'execution', scheduleId: 'sch-1', firedAt: 2,
+ status: 'failed', sessionId: 'legacy-check-session', errorMsg: 'agent failed' });
+ await harness.storage.insertRun({ id: 'healthy', scheduleId: 'sch-1', firedAt: 3, status: 'skipped',
+ preRunHookResult: { status: 'skipped', decision: 'skip', exitCode: 2, durationMs: 1,
+ stdout: 'CINDY_PRECHECK_OK', stderr: '', stdoutTruncated: false, stderrTruncated: false,
+ timedOut: false, aborted: false, checkSucceeded: true } });
+ const rows = await harness.storage.listSidebarIndexRuns();
+ expect(rows.find((r) => r.runId === 'legacy-check')).toMatchObject({ failureRecovered: true, readAt: undefined });
+ expect(rows.find((r) => r.runId === 'execution')).toMatchObject({ failureRecovered: false });
+ await harness.storage.updateRun('legacy-check', { readAt: 4 });
+ await harness.storage.updateRun('execution', { readAt: 4 });
+ await harness.storage.insertRun({ id: 'latest', scheduleId: 'sch-1', firedAt: 5,
+ status: 'skipped', sessionId: 'legacy-check-session', readAt: 6 });
+ const readRows = await harness.storage.listSidebarIndexRuns();
+ expect(readRows.some((r) => r.runId === 'legacy-check')).toBe(false);
+ expect(readRows.some((r) => r.runId === 'execution')).toBe(true);
+ expect((await harness.storage.listRuns('sch-1', 50)).some((r) => r.id === 'legacy-check')).toBe(true);
+ } finally { harness.close(); }
+ });
+
it('keeps renamed legacy aliases from the latest-session projection', async () => {
const harness = createStorageHarness();
const schedule = baseSchedule({
diff --git a/apps/desktop/src/main/scheduler-host/hook-script-generator.ts b/apps/desktop/src/main/scheduler-host/hook-script-generator.ts
index 2245b47f7c..a619156805 100644
--- a/apps/desktop/src/main/scheduler-host/hook-script-generator.ts
+++ b/apps/desktop/src/main/scheduler-host/hook-script-generator.ts
@@ -129,6 +129,7 @@ export function buildHookScriptPrompt(input: {
'Hard protocol (must follow exactly):',
'- The script is executed with Node.js (>= 18) as an ES module (.mjs file).',
'- Exit code 0 = let the task run this round. Exit code 2 = skip this round. Any other exit code, crash, or timeout blocks the task (fail-closed), so prefer explicit process.exit(0) / process.exit(2).',
+ '- After a complete, successful check, print CINDY_PRECHECK_OK as a standalone stdout line before exit 0 or 2 (including normal no-work skips). This clears past precheck warnings only, never task execution failures. Never emit it for rate-limit/backoff skips or incomplete/degraded checks; exit 2 alone is not proof of recovery.',
'- The working directory is the task project directory (if any). stdin receives a JSON payload ({ scheduleId, scheduleName, firedAt, workingDir, lastFinishedAt }) — reading it is optional.',
'- CAUTION: lastFinishedAt is also refreshed by rounds this very script skips (exit 2). Never build "run only if enough time passed since the last real run" on top of it — the script would lock itself out forever. Persist your own timestamp file if you need that.',
'- Use only Node.js built-in modules (node:fs, node:child_process, node:https, ...). No npm dependencies.',
diff --git a/apps/desktop/src/main/scheduler-host/pre-run-hook.ts b/apps/desktop/src/main/scheduler-host/pre-run-hook.ts
index a87241da53..51a7a1f13a 100644
--- a/apps/desktop/src/main/scheduler-host/pre-run-hook.ts
+++ b/apps/desktop/src/main/scheduler-host/pre-run-hook.ts
@@ -154,6 +154,8 @@ export async function executePreRunHook(input: PreRunHookInput): Promise<PreRunH
: 'failed';
resolve({
status,
+ ...((status === 'passed' || status === 'skipped') && !stdoutTruncated
+ && stdout.split(/\r?\n/).includes('CINDY_PRECHECK_OK') ? { checkSucceeded: true as const } : {}),
decision: status === 'passed' ? 'run' : status === 'skipped' ? 'skip' : 'block',
exitCode,
durationMs: Date.now() - startedAt,
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index 851cd1ccb3..01cfb29d60 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -381,6 +381,12 @@ export class MakerScheduleRunner implements ScheduleRunner {
this.scheduler = scheduler;
}
+ private async retireHeartbeat(schedule: Schedule, ctx: FireContext, status: string): Promise<FireResult> {
+ // Keep history; pausing is idempotent and must not abort this settling run.
+ await this.scheduler?.pause(schedule.id, { exemptRunId: ctx.runId });
+ return { sessionId: '', skipped: true, resultText: `Heartbeat stopped: target session ${status}` };
+ }
+
/**
* Keep the scheduler's authoritative run id in the host-owned session
* context for the lifetime of the actual turn, including auto-resume
@@ -574,7 +580,17 @@ export class MakerScheduleRunner implements ScheduleRunner {
throw new Error(errMsg);
}
- // 1.5 前置检查脚本(Pre-run Hook):放在一切查询 / worktree 创建 / session 创建
+ // 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) {
+ const target = await getSessionRowSnapshot(schedule.targetSessionId);
+ if (target?.status === 'archived' || target?.status === 'deleted') {
+ return this.retireHeartbeat(schedule, ctx, target.status);
+ }
+ }
+
+ // 1.5 前置检查脚本(Pre-run Hook):放在 worktree 创建 / session 创建
// 之前 —— 被拦截的轮次除了跑一个脚本什么都不做,零 token 零副作用。
// exit 0 放行;exit 2 跳过(写留痕消息后返回 skipped,engine 落 'skipped' run);
// 其它退出码 / 超时 / spawn 失败 fail-closed:持久化检查结果并阻止 agent。
@@ -749,6 +765,9 @@ export class MakerScheduleRunner implements ScheduleRunner {
// resumeSessionId / heartbeatWorkingDir / heartbeatModel 仍是 undefined,
// 下方 workingDir 解析自然走 schedule.workingDir + schedule.useWorktree 分支
} else {
+ if (schedule.source !== 'bot' && (row?.status === 'archived' || row?.status === 'deleted')) {
+ return this.retireHeartbeat(schedule, ctx, row.status);
+ }
const errMsg = `target session not available (${row?.status ?? 'missing'})`;
// exemptRunId=本轮自己:pause 会 abortInflightAndWait,本 run 已在
// inflight 注册,不豁免会 abort 自己的 signal 并白等 5s 超时才返回。
diff --git a/apps/desktop/src/main/scheduler-host/storage.ts b/apps/desktop/src/main/scheduler-host/storage.ts
index 56c2b1ec51..cc8ccee52d 100644
--- a/apps/desktop/src/main/scheduler-host/storage.ts
+++ b/apps/desktop/src/main/scheduler-host/storage.ts
@@ -49,6 +49,36 @@ import { normalizeTurnUsageDetails } from '../../shared/turnUsageDetails.js';
export type SchedulerDrizzleDb = BetterSQLite3Database<typeof schema>;
+/** SQL counterpart of classifyScheduleFailure, shared by display and recovery. */
+function failureKindSql(alias: 'failed' | 'schedule_runs') {
+ const row = sql.raw(alias);
+ return sql<'precheck' | 'rate-limit' | 'execution'>`CASE
+ WHEN CASE WHEN json_valid(${row}.pre_run_hook_result)
+ THEN json_extract(${row}.pre_run_hook_result, '$.decision') = 'block' ELSE 0 END THEN CASE
+ WHEN lower(json_extract(${row}.pre_run_hook_result, '$.stderr')) LIKE '%rate limit%'
+ THEN 'rate-limit' ELSE 'precheck' END
+ WHEN substr(${row}.error_msg, 1, 12) = 'pre-run hook' THEN 'precheck'
+ ELSE 'execution' END`;
+}
+
+/** A success only recovers failures belonging to the same automation. */
+function failureRecoveredSql(alias: 'failed' | 'schedule_runs') {
+ const row = sql.raw(alias);
+ return sql<boolean>`CASE WHEN ${row}.status IN ('failed', 'interrupted') THEN EXISTS (
+ SELECT 1 FROM schedule_runs AS recovered
+ WHERE recovered.schedule_id = ${row}.schedule_id
+ AND recovered.fired_at >= ${row}.fired_at
+ AND (recovered.status = 'success' OR (
+ ${failureKindSql(alias)} != 'execution'
+ AND recovered.status IN ('skipped', 'success', 'failed')
+ AND CASE WHEN json_valid(recovered.pre_run_hook_result)
+ THEN json_extract(recovered.pre_run_hook_result, '$.checkSucceeded') = 1 ELSE 0 END
+ ))
+ AND (recovered.fired_at > ${row}.fired_at
+ OR (recovered.fired_at = ${row}.fired_at AND recovered.id > ${row}.id))
+ ) ELSE 0 END`;
+}
+
export interface ScheduleSidebarIndexRun {
runId: string;
scheduleId: string;
@@ -62,6 +92,8 @@ export interface ScheduleSidebarIndexRun {
status: ScheduleRun['status'];
readAt?: number;
firedAt?: number;
+ failureKind?: 'precheck' | 'rate-limit' | 'execution';
+ failureRecovered?: boolean;
}
export interface ScheduleCostSummary {
@@ -599,7 +631,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
* Sidebar 聚合索引用的轻量 run 列表:
* - 每个 session 只返回最新的 run 映射,读取量不随同一任务的运行次数增长。
* - 额外包含全部 running 与未读终态 run,供运行标记对账和未读计数。
- * - 每个 session 保留最近一次失败/中断,即使已读也能查看历史失败提示。
+ * - 每个 session 保留最近一次尚未恢复的失败/中断;已读不等于恢复。
* - 未读旧 run 先返回以累计 session 红点,最新映射最后返回以裁决 Automation 归属。
* - 非最新 running 不携带 sessionId,只参与运行标记对账。
* - 内部例行任务在 SQL 内排除,避免未读历史随运行次数累积到公共侧栏内存中。
@@ -619,6 +651,8 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
status: scheduleRuns.status,
readAt: scheduleRuns.readAt,
firedAt: scheduleRuns.firedAt,
+ failureRecovered: failureRecoveredSql('schedule_runs'),
+ failureKind: failureKindSql('schedule_runs'),
};
const [latestSessionRows, unreadRows, runningRows, latestFailedRows] = await Promise.all([
db
@@ -648,6 +682,7 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
SELECT failed.id FROM schedule_runs AS failed
WHERE failed.session_id = ${scheduleSessionLatestRuns.sessionId}
AND failed.status IN ('failed', 'interrupted')
+ AND NOT ${failureRecoveredSql('failed')}
ORDER BY failed.fired_at DESC, failed.id DESC LIMIT 1
)`,
),
@@ -681,6 +716,10 @@ export class DrizzleScheduleStorage implements ScheduleStorage {
status: row.status,
readAt: row.readAt ?? undefined,
firedAt: row.firedAt ?? undefined,
+ ...(row.status === 'failed' || row.status === 'interrupted' ? {
+ failureRecovered: Boolean(row.failureRecovered),
+ failureKind: row.failureKind,
+ } : {}),
}));
const linkedSessionIds = new Set(
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index c05339a603..0c475c007d 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -537,8 +537,8 @@ describe('automation-generated sessions', () => {
expect(sessionViewSource).toContain(
'useReadFailedScheduleRuns(unreadFailedScheduleRunIds, viewVisible && historyLoaded, remoteDeviceId ?? undefined)',
);
- expect(bannerSource).toContain("t('chat.unreadFailedScheduleBanner.text')");
- expect(zh.chat.unreadFailedScheduleBanner.text).toBe('此前有定时任务未完成,可查看运行记录。');
+ expect(bannerSource).toContain('scheduleFailureMessageKey(latestFailedRun)');
+ expect(zh.chat.unreadFailedScheduleBanner.text).toBe('此前有自动运行失败。');
expect(sessionViewSource).toContain('latestFailedRun={scheduleSessionInfo.latestFailedRun}');
});
diff --git a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts
index 834b0944d8..0ffbebc11e 100644
--- a/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationScheduleSilenceHook.test.ts
@@ -304,7 +304,7 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
expect(window.electronAPI.maker.schedule.listSidebarIndexRuns).toHaveBeenCalledTimes(1);
});
- it('keeps read failure history without a red dot after a newer success and reopening', async () => {
+ it('keeps a recovered warning cleared after reopening the task', async () => {
stubApiWithRuns([
indexRun({ runId: 'read-failure', status: 'failed', readAt: 30, firedAt: 10 }),
indexRun({ runId: 'latest-success', status: 'success', readAt: 30, firedAt: 20 }),
@@ -312,8 +312,8 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
const view = renderHook(() => useAutomationScheduleSessionIndex());
await waitFor(() => {
expect(view.result.current.get('session-1')).toMatchObject({
- hasFailedRun: true,
- latestFailedRun: { runId: 'read-failure', firedAt: 10 },
+ hasFailedRun: false,
+ latestFailedRun: undefined,
hasUnreadFailedRun: false,
hasUnreadRun: false,
unreadRunIds: [],
@@ -324,7 +324,7 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
const reopened = renderHook(() => useAutomationScheduleSessionIndex());
await waitFor(() => {
expect(reopened.result.current.get('session-1')).toMatchObject({
- hasFailedRun: true,
+ hasFailedRun: false,
hasUnreadFailedRun: false,
});
});
@@ -335,7 +335,7 @@ describe('useAutomationScheduleSessionIndex marker reconciliation', () => {
indexRun({ runId: 'read-z', status: 'interrupted', readAt: 30, firedAt: 20 }),
indexRun({ runId: 'read-a', status: 'failed', readAt: 30, firedAt: 20 }),
indexRun({ runId: 'older-unread', status: 'failed', readAt: undefined, firedAt: 10 }),
- indexRun({ runId: 'success', status: 'success', readAt: 30, firedAt: 25 }),
+ indexRun({ runId: 'success', scheduleId: 'other-schedule', status: 'success', readAt: 30, firedAt: 25 }),
]);
const { result } = renderHook(() => useAutomationScheduleSessionIndex());
await waitFor(() =>
diff --git a/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx b/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx
index dc6afde9db..fd8cf6c706 100644
--- a/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/unreadFailedScheduleBanner.test.tsx
@@ -71,6 +71,12 @@ afterEach(() => {
});
describe('historical failed schedule notice', () => {
+ it('distinguishes precheck failures while preserving the warning', () => {
+ render(<UnreadFailedScheduleBanner dataOwnerId="owner" sessionId="session"
+ latestFailedRun={{ runId: 'failed', firedAt: 1, failureKind: 'rate-limit', scheduleId: 'schedule' }} />);
+ expect(screen.getByText('chat.unreadFailedScheduleBanner.rateLimited')).toBeTruthy();
+ expect(screen.queryByTestId('unread-failed-schedule-banner')).not.toBeNull();
+ });
it('reads on opening even when running or specific errors replace the generic banner', async () => {
render(<View runIds={['old']} showBanner={false} />);
await waitFor(() => expect(readIds.has('old')).toBe(true));
diff --git a/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx b/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx
index 761564fab4..102754a30b 100644
--- a/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/UnreadFailedScheduleBanner.tsx
@@ -3,6 +3,7 @@ import { AlertCircle, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Tip } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
+import { scheduleFailureMessageKey } from '@cindy/maker-shared/schedule-model';
import {
compareFailedScheduleRuns,
dismissScheduleFailure,
@@ -89,7 +90,7 @@ function FailedScheduleNotice({
>
<AlertCircle size={14} className="shrink-0 mt-[2px] text-[var(--error-fg)]" />
<span className="flex-1 min-w-0 text-xs break-all text-[var(--error-fg)]">
- {t('chat.unreadFailedScheduleBanner.text')}
+ {t(`chat.unreadFailedScheduleBanner.${scheduleFailureMessageKey(latestFailedRun)}`)}
</span>
<Tip text={t('chat.unreadFailedScheduleBanner.dismissTitle')}>
<button
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
index 8237663537..b1ff99c6f6 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/projectScheduleSidebarIndex.ts
@@ -1,13 +1,15 @@
import type { AutomationScheduleSessionInfo } from '../../cc-agent/lib/automationSidebarGrouping';
import type { ScheduleSidebarIndexRun } from './scheduleSidebarIndexRuns';
-import { isFailedScheduleRun, isUnreadFailedScheduleRun, isUnreadScheduleRun } from './runUnread';
+import { isUnreadFailedScheduleRun, isUnreadScheduleRun } from './runUnread';
import { compareFailedScheduleRuns } from './failedScheduleDismissal';
+import { activeScheduleFailures } from '@cindy/maker-shared/schedule-model';
/** Local and remote snapshots have the same unread projection. */
export function projectScheduleSidebarIndex(
runs: readonly ScheduleSidebarIndexRun[],
): Map<string, AutomationScheduleSessionInfo> {
const next = new Map<string, AutomationScheduleSessionInfo>();
+ const activeFailures = activeScheduleFailures(runs.map((run) => ({ ...run, id: run.runId })));
const latestUnreadFailedFiredAt = new Map<string, number>();
for (const run of runs) {
if (!run.sessionId) continue;
@@ -19,8 +21,8 @@ export function projectScheduleSidebarIndex(
const isRunUnread = isUnreadScheduleRun(run);
if (isRunUnread) unreadRunIds.push(run.runId);
let latestFailedRun = existing?.latestFailedRun;
- if (isFailedScheduleRun(run)) {
- const candidate = { runId: run.runId, firedAt: run.firedAt ?? 0 };
+ if (activeFailures.has(run.runId)) {
+ const candidate = { runId: run.runId, firedAt: run.firedAt ?? 0, scheduleId: run.scheduleId, failureKind: run.failureKind };
if (!latestFailedRun || compareFailedScheduleRuns(candidate, latestFailedRun) > 0)
latestFailedRun = candidate;
}
@@ -45,7 +47,7 @@ export function projectScheduleSidebarIndex(
unreadFailedRunIds,
latestUnreadFailedRunId,
latestFailedRun,
- hasFailedRun: Boolean(existing?.hasFailedRun || isFailedScheduleRun(run)),
+ hasFailedRun: !!latestFailedRun,
hasUnreadRun: unreadRunIds.length > 0,
hasUnreadFailedRun: unreadFailedRunIds.length > 0,
});
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
index e264437a48..1328ca95e9 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleSidebarIndexRuns.ts
@@ -14,6 +14,8 @@ export interface ScheduleSidebarIndexRun {
status: ScheduleRun['status'];
readAt?: number;
firedAt?: number;
+ failureKind?: 'precheck' | 'rate-limit' | 'execution';
+ failureRecovered?: boolean;
}
/**
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 5152278587..ebb1a4ed6c 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8571,7 +8571,9 @@
"dismissTitle": "Dismiss this interruption notice"
},
"unreadFailedScheduleBanner": {
- "text": "Some scheduled runs did not finish. Check the run history.",
+ "text": "An automatic run failed.",
+ "precheck": "Automatic checks are temporarily blocked.",
+ "rateLimited": "Automatic checks are temporarily blocked by a request rate limit.",
"dismissTitle": "Dismiss past failure notice"
},
"worktreeRestoreBanner": {
@@ -10343,7 +10345,7 @@
"enable": "Enable",
"tooltip": "Runs this script when the task fires: exit code 0 lets the round proceed; exit code 2 skips this round (no agent started, no tokens used); script errors or timeouts block the run and record a failure. The script runs in the task's working directory; on Windows use an explicit interpreter (e.g. node check.mjs).",
"infoAria": "View pre-run check rules",
- "protocol": "How to write it: exit code 0 = run the task this round, exit code 2 = skip this round (no usage cost); other exit codes, errors, or timeouts block the run",
+ "protocol": "How to write it: exit code 0 = run the task this round, exit code 2 = skip this round (no usage cost); other exit codes, errors, or timeouts block the run. After a complete successful check, including a normal no-work skip, print CINDY_PRECHECK_OK on its own stdout line before exit 0 or 2. This clears earlier precheck warnings only, not execution failures. Do not print it during rate-limit backoff or incomplete checks.",
"commandPlaceholder": "node scripts/schedule-checks/check.mjs",
"test": "Test",
"testing": "Testing…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 23ee4a9eb2..a8d04e1059 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8565,7 +8565,9 @@
"dismissTitle": "この中断通知を閉じる"
},
"unreadFailedScheduleBanner": {
- "text": "完了しなかったスケジュール実行があります。実行履歴を確認してください。",
+ "text": "自動実行に失敗した記録があります。",
+ "precheck": "自動チェックが一時的に停止しています。",
+ "rateLimited": "リクエスト制限により自動チェックが一時的に停止しています。",
"dismissTitle": "過去の失敗通知を閉じる"
},
"worktreeRestoreBanner": {
@@ -10328,7 +10330,7 @@
"enable": "有効化",
"tooltip": "タスクの起動時にこのスクリプトを先に実行します。終了コード 0 で今回の実行を許可し、終了コード 2 で今回をスキップします(Agent は起動せず、トークンも消費しません)。スクリプトのエラーやタイムアウト時は実行を阻止し、失敗結果を記録します。スクリプトはタスクの作業ディレクトリで実行されます。Windows では明示的なインタープリタ(例: node check.mjs)を指定してください。",
"infoAria": "事前チェックのルールを表示",
- "protocol": "スクリプトの書き方:終了コード 0 = 今回タスクを実行、終了コード 2 = 今回はスキップ(使用量を消費しません)。その他の終了コード、エラー、タイムアウトは実行を阻止します",
+ "protocol": "スクリプトの書き方:終了コード 0 = 今回タスクを実行、終了コード 2 = 今回はスキップ(使用量を消費しません)。その他の終了コード、エラー、タイムアウトは実行を阻止します。チェックが正常に完了したら(処理対象がない場合も含む)、exit 0/2 の前に stdout の独立した行に CINDY_PRECHECK_OK を出力してください。過去の事前チェックの警告だけを解除し、実行失敗は解除しません。レート制限による待機中やチェックが不完全な場合は出力しないでください。",
"commandPlaceholder": "node scripts/schedule-checks/check.mjs",
"test": "テスト",
"testing": "テスト中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 8be528dc7e..f21ea39794 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8565,7 +8565,9 @@
"dismissTitle": "이 중단 알림 닫기"
},
"unreadFailedScheduleBanner": {
- "text": "완료되지 않은 예약 실행이 있습니다. 실행 기록을 확인하세요.",
+ "text": "실패한 자동 실행이 있습니다.",
+ "precheck": "자동 확인이 일시적으로 차단되었습니다.",
+ "rateLimited": "요청 한도 초과로 자동 확인이 일시적으로 차단되었습니다.",
"dismissTitle": "이전 실패 알림 닫기"
},
"worktreeRestoreBanner": {
@@ -10328,7 +10330,7 @@
"enable": "사용",
"tooltip": "작업이 트리거될 때 이 스크립트를 먼저 실행합니다. 종료 코드 0이면 이번 회차를 진행하고, 종료 코드 2면 이번 회차를 건너뜁니다(Agent를 시작하지 않고 토큰도 사용하지 않음). 스크립트 오류나 시간 초과 시에는 실행을 차단하고 실패 결과를 기록합니다. 스크립트는 작업 디렉터리에서 실행됩니다. Windows에서는 명시적 인터프리터(예: node check.mjs)를 사용하세요.",
"infoAria": "사전 검사 규칙 보기",
- "protocol": "스크립트 작성 규칙: 종료 코드 0 = 이번 회차 실행, 종료 코드 2 = 이번 회차 건너뜀(사용량 소모 없음). 그 외 종료 코드, 오류, 시간 초과는 실행을 차단합니다",
+ "protocol": "스크립트 작성 규칙: 종료 코드 0 = 이번 회차 실행, 종료 코드 2 = 이번 회차 건너뜀(사용량 소모 없음). 그 외 종료 코드, 오류, 시간 초과는 실행을 차단합니다. 확인이 완전히 성공한 경우(처리할 내용이 없어 건너뛰는 경우 포함), exit 0/2 전에 stdout의 별도 줄에 CINDY_PRECHECK_OK를 출력하세요. 이전 사전 확인 경고만 해제하며 실행 실패는 해제하지 않습니다. 요청 제한으로 대기 중이거나 확인이 불완전한 경우에는 출력하지 마세요.",
"commandPlaceholder": "node scripts/schedule-checks/check.mjs",
"test": "테스트",
"testing": "테스트 중…",
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 1348d99f81..06401d050a 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8565,7 +8565,9 @@
"dismissTitle": "关闭此中断提示"
},
"unreadFailedScheduleBanner": {
- "text": "此前有定时任务未完成,可查看运行记录。",
+ "text": "此前有自动运行失败。",
+ "precheck": "自动检查暂时受阻。",
+ "rateLimited": "自动检查暂时受阻:请求限流。",
"dismissTitle": "关闭历史失败提示"
},
"worktreeRestoreBanner": {
@@ -10328,7 +10330,7 @@
"enable": "启用",
"tooltip": "任务触发时先执行该脚本:退出码 0 放行本轮;退出码 2 跳过本轮(不启动 Agent、不消耗 token);脚本报错或超时将阻止执行并记录失败结果。脚本在任务工作目录下执行,Windows 上请写显式解释器(如 node check.mjs)。",
"infoAria": "查看前置检查规则",
- "protocol": "脚本写法:结束时退出码 0 = 本轮执行任务,退出码 2 = 本轮跳过(不消耗用量);其他退出码、报错或超时会阻止执行",
+ "protocol": "脚本写法:结束时退出码 0 = 本轮执行任务,退出码 2 = 本轮跳过(不消耗用量);其他退出码、报错或超时会阻止执行。检查完整成功后(包括正常无事可做),在 exit 0/2 前向 stdout 单独输出一行 CINDY_PRECHECK_OK,仅恢复此前的检查告警,不恢复执行失败;限流退避或检查不完整时不要输出。",
"commandPlaceholder": "node scripts/schedule-checks/check.mjs",
"test": "测试",
"testing": "测试中…",
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 3488248f41..02d4e018b8 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8564,7 +8564,9 @@
"dismissTitle": "關閉此中斷提示"
},
"unreadFailedScheduleBanner": {
- "text": "先前有定時任務未完成,可查看執行記錄。",
+ "text": "先前有自動執行失敗。",
+ "precheck": "自動檢查暫時受阻。",
+ "rateLimited": "自動檢查暫時受阻:請求限流。",
"dismissTitle": "關閉歷史失敗提示"
},
"worktreeRestoreBanner": {
@@ -10328,7 +10330,7 @@
"enable": "啟用",
"tooltip": "任務觸發時先執行該指令碼:退出碼 0 放行本輪;退出碼 2 跳過本輪(不啟動 Agent、不消耗 token);指令碼報錯或超時將阻止執行並記錄失敗結果。指令碼在任務工作目錄下執行,Windows 上請寫顯式直譯器(如 node check.mjs)。",
"infoAria": "檢視前置檢查規則",
- "protocol": "指令碼寫法:結束時退出碼 0 = 本輪執行任務,退出碼 2 = 本輪跳過(不消耗用量);其他退出碼、報錯或超時會阻止執行",
+ "protocol": "指令碼寫法:結束時退出碼 0 = 本輪執行任務,退出碼 2 = 本輪跳過(不消耗用量);其他退出碼、報錯或超時會阻止執行。檢查完整成功後(包括正常無事可做),在 exit 0/2 前向 stdout 單獨輸出一行 CINDY_PRECHECK_OK,僅恢復先前的檢查警告,不恢復執行失敗;限流退避或檢查不完整時不要輸出。",
"commandPlaceholder": "node scripts/schedule-checks/check.mjs",
"test": "測試",
"testing": "測試中…",
diff --git a/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx b/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
index cec02d0780..9e7070ae80 100644
--- a/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
+++ b/apps/mobile/src/__tests__/FailedScheduleNotice.test.tsx
@@ -32,6 +32,11 @@ afterEach(() => act(() => root.unmount()));
async function show(source = 'owner/host/task', value = run) {
await act(async () => root.render(<FailedScheduleNotice key={source} source={source} run={value} />));
}
+it('shows a rate-limit explanation', async () => {
+ await act(async () => root.render(<FailedScheduleNotice source="owner/device/task"
+ run={{ ...run, failureKind: 'rate-limit', scheduleId: 'schedule' }} />));
+ expect(host.textContent).toContain('session.failedScheduleNotice.rateLimited');
+});
it('keeps dismissal local and shows a newer failed run', async () => {
await show(); expect(host.querySelector('button')).not.toBeNull();
await act(async () => host.querySelector('button')!.click());
diff --git a/apps/mobile/src/__tests__/scheduleIndex.test.ts b/apps/mobile/src/__tests__/scheduleIndex.test.ts
index b91699464c..79252474a5 100644
--- a/apps/mobile/src/__tests__/scheduleIndex.test.ts
+++ b/apps/mobile/src/__tests__/scheduleIndex.test.ts
@@ -118,7 +118,7 @@ describe('scheduleIndex', () => {
expect(listRuns).toHaveBeenCalledTimes(visible ? 1 : 0);
expect(markRunRead).toHaveBeenCalledTimes(visible ? 1 : 0);
expect(onIndex).toHaveBeenCalledTimes(visible ? 1 : 0);
- if (visible) expect(onIndex.mock.calls[0][0].get('task').latestFailedRun).toEqual({ runId: 'run', firedAt: 1 });
+ if (visible) expect(onIndex.mock.calls[0][0].get('task').latestFailedRun).toMatchObject({ runId: 'run', firedAt: 1, scheduleId: 'sched-1', failureKind: 'execution' });
} finally {
resetScheduleIndexThrottleForTesting();
vi.useRealTimers();
@@ -145,7 +145,7 @@ describe('scheduleIndex', () => {
loadSharedSessionScheduleIndex('shared-lightweight', maker),
]);
expect(home).toBe(task);
- expect(home.get('current')?.latestFailedRun).toEqual({ runId: 'old-failure', firedAt: 1 });
+ expect(home.get('current')?.latestFailedRun).toMatchObject({ runId: 'old-failure', firedAt: 1, scheduleId: 'sched-1', failureKind: 'execution' });
expect(home.has('previous')).toBe(false);
expect(home.get('zero-task')?.allSchedulesStopped).toBe(true);
expect(list).toHaveBeenCalledTimes(1);
diff --git a/apps/mobile/src/i18n/locales/en/session.json b/apps/mobile/src/i18n/locales/en/session.json
index 80c9764079..398c19255c 100644
--- a/apps/mobile/src/i18n/locales/en/session.json
+++ b/apps/mobile/src/i18n/locales/en/session.json
@@ -1,6 +1,8 @@
{
"failedScheduleNotice": {
- "text": "Some scheduled runs did not finish. Check the run history.",
+ "text": "An automatic run failed.",
+ "precheck": "Automatic checks are temporarily blocked.",
+ "rateLimited": "Automatic checks are temporarily blocked by a request rate limit.",
"dismissTitle": "Dismiss past failure notice"
},
"common": {
diff --git a/apps/mobile/src/i18n/locales/ja/session.json b/apps/mobile/src/i18n/locales/ja/session.json
index b5d83a959f..19253adf3d 100644
--- a/apps/mobile/src/i18n/locales/ja/session.json
+++ b/apps/mobile/src/i18n/locales/ja/session.json
@@ -1,6 +1,8 @@
{
"failedScheduleNotice": {
- "text": "完了しなかったスケジュール実行があります。実行履歴を確認してください。",
+ "text": "自動実行に失敗した記録があります。",
+ "precheck": "自動チェックが一時的に停止しています。",
+ "rateLimited": "リクエスト制限により自動チェックが一時的に停止しています。",
"dismissTitle": "過去の失敗通知を閉じる"
},
"common": {
diff --git a/apps/mobile/src/i18n/locales/ko/session.json b/apps/mobile/src/i18n/locales/ko/session.json
index de65ea4d24..6f720eb144 100644
--- a/apps/mobile/src/i18n/locales/ko/session.json
+++ b/apps/mobile/src/i18n/locales/ko/session.json
@@ -1,6 +1,8 @@
{
"failedScheduleNotice": {
- "text": "완료되지 않은 예약 실행이 있습니다. 실행 기록을 확인하세요.",
+ "text": "실패한 자동 실행이 있습니다.",
+ "precheck": "자동 확인이 일시적으로 차단되었습니다.",
+ "rateLimited": "요청 한도 초과로 자동 확인이 일시적으로 차단되었습니다.",
"dismissTitle": "이전 실패 알림 닫기"
},
"common": {
diff --git a/apps/mobile/src/i18n/locales/zh-CN/session.json b/apps/mobile/src/i18n/locales/zh-CN/session.json
index b9f3972ab6..cf07b66409 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/session.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/session.json
@@ -1,6 +1,8 @@
{
"failedScheduleNotice": {
- "text": "此前有定时任务未完成,可查看运行记录。",
+ "text": "此前有自动运行失败。",
+ "precheck": "自动检查暂时受阻。",
+ "rateLimited": "自动检查暂时受阻:请求限流。",
"dismissTitle": "关闭历史失败提示"
},
"common": {
diff --git a/apps/mobile/src/i18n/locales/zh-TW/session.json b/apps/mobile/src/i18n/locales/zh-TW/session.json
index 046ef14320..bf67de6465 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/session.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/session.json
@@ -1,6 +1,8 @@
{
"failedScheduleNotice": {
- "text": "先前有定時任務未完成,可查看執行記錄。",
+ "text": "先前有自動執行失敗。",
+ "precheck": "自動檢查暫時受阻。",
+ "rateLimited": "自動檢查暫時受阻:請求限流。",
"dismissTitle": "關閉歷史失敗提示"
},
"common": {
diff --git a/apps/mobile/src/session/FailedScheduleNotice.tsx b/apps/mobile/src/session/FailedScheduleNotice.tsx
index 68b94ad6df..b20cdecdb5 100644
--- a/apps/mobile/src/session/FailedScheduleNotice.tsx
+++ b/apps/mobile/src/session/FailedScheduleNotice.tsx
@@ -1,5 +1,5 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
-import { compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
+import { compareFailedScheduleRuns, scheduleFailureMessageKey, type FailedScheduleRunSnapshot } from '@cindy/maker-shared/schedule-model';
import { CircleAlert, X } from 'lucide-react-native';
import { useEffect, useState } from 'react';
import { Pressable, StyleSheet, View } from 'react-native';
@@ -37,7 +37,7 @@ export function FailedScheduleNotice({ source, run }: { source: string; run: Fai
return (
<View style={styles.box} testID="session.failedScheduleNotice">
<CircleAlert color={colors.errorText} size={iconSize.md} strokeWidth={iconStroke.regular} />
- <Text style={styles.text}>{t('session.failedScheduleNotice.text')}</Text>
+ <Text style={styles.text}>{t(`session.failedScheduleNotice.${scheduleFailureMessageKey(run)}`)}</Text>
<Pressable accessibilityRole="button" accessibilityLabel={t('session.failedScheduleNotice.dismissTitle')}
onPress={dismiss} style={({ pressed }) => [styles.close, pressed && styles.pressed]}>
<X color={colors.errorText} size={iconSize.md} strokeWidth={iconStroke.regular} />
diff --git a/apps/mobile/src/session/scheduleIndex.ts b/apps/mobile/src/session/scheduleIndex.ts
index 23d4b60e0f..379abd38fa 100644
--- a/apps/mobile/src/session/scheduleIndex.ts
+++ b/apps/mobile/src/session/scheduleIndex.ts
@@ -349,6 +349,8 @@ function scheduleInfoEqual(a: RemoteSessionScheduleInfo, b: RemoteSessionSchedul
&& !!a.hasUnreadFailedRun === !!b.hasUnreadFailedRun
&& a.latestFailedRun?.runId === b.latestFailedRun?.runId
&& a.latestFailedRun?.firedAt === b.latestFailedRun?.firedAt
+ && a.latestFailedRun?.scheduleId === b.latestFailedRun?.scheduleId
+ && a.latestFailedRun?.failureKind === b.latestFailedRun?.failureKind
&& a.running === b.running
&& a.latestRunAt === b.latestRunAt
&& a.scheduleStatus === b.scheduleStatus
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 681a5798d9..bf2fba3090 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -11,6 +11,18 @@
> **增量适用原则**:wire protocol 兼容对所有跨端改动生效,不因是小改而豁免。
+## 自动化检查恢复投影
+
+运行状态和已读回执保留历史事实。当前警告只保留未被**同一自动化**更新成功运行恢复的失败;
+另一自动化成功不能清除它。检查受阻与实际执行失败分别显示;原有运行历史页面保持不变。
+轻量侧栏协议新增可选 `failureKind` / `failureRecovered`,旧端忽略,新端缺省按普通失败处理。
+
+前置检查仍遵守 exit 0 放行、exit 2 跳过、其他值阻止执行。脚本可在 stdout 单独输出一行
+`CINDY_PRECHECK_OK`,表示检查完整完成(包括正常无事可做的跳过)。只有 exit 0/2 且输出未
+截断时记录可选 `checkSucceeded: true`;错误、超时、取消和退避跳过不构成恢复。
+该标记只恢复此前的检查故障,不恢复 Agent 执行失败;旧脚本不输出、旧客户端不识别均不影响
+原有退出码语义。实现见 `scheduler-host/pre-run-hook.ts` 与 `scheduler-host/storage.ts`。
+
## 事实来源
| 内容 | 权威来源 |
diff --git a/packages/lizi-mcps/src/scheduler/setPreRunHook.ts b/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
index 6392317198..bd744d571f 100644
--- a/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
+++ b/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
@@ -37,6 +37,7 @@ export function registerScheduleSetPreRunHookTool(
category: 'scheduler',
description:
'创建/修改一条 schedule 的前置检查脚本(preRunHook)的**唯一通道**——不要自己写脚本文件再手填 preRunHook.command,本工具由宿主代码统一保证:脚本协议(exit 0 放行 / exit 2 跳过 / 其它异常 fail-closed 阻止本轮)、落盘路径规范(项目任务进 scripts/schedule-checks/,无目录任务进应用数据目录)、落盘后**立即自测**并返回完整结果。' +
+ '检查完整成功后(包括正常无事可做),在 exit 0/2 前向 stdout 单独输出一行 CINDY_PRECHECK_OK,仅恢复此前的检查告警,不恢复执行失败;限流退避或检查不完整时不得输出,exit 2 本身不代表恢复。' +
'用法:(1) 传 scheduleId → 自动继承该任务的目录/名称/现有脚本(修改流覆写同一文件),安装成功后直接挂载到任务;不传则只落盘返回 command,由你随后在 schedule_create 里带上。' +
'(2) script 与 description 至少给一个:你有项目上下文时**优先自己写好 script**(Node ESM,只用 node 内置模块,外部 CLI 用 child_process;意外失败必须非零退出以阻止本轮);只有需求很通用时才用 description 让宿主生成。' +
'(3) 返回的 test 字段是刚跑完的自测结果——决策不符合预期(比如该放行却 skip)就修了再来,不要把没自测通过的脚本留给任务。',
@@ -48,7 +49,7 @@ export function registerScheduleSetPreRunHookTool(
script: z
.string()
.optional()
- .describe('你写好的脚本内容(Node ESM)。协议:exit 0 放行 / exit 2 跳过 / 其它异常阻止本轮;只用 node 内置模块;外部 CLI 意外失败必须非零退出'),
+ .describe('你写好的脚本内容(Node ESM)。协议:exit 0 放行 / exit 2 跳过 / 其它异常阻止本轮;完整成功检查后在 exit 0/2 前向 stdout 单独输出 CINDY_PRECHECK_OK,限流退避或检查不完整时不得输出;只用 node 内置模块;外部 CLI 意外失败必须非零退出'),
description: z
.string()
.optional()
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index e62f5de39a..bde624a42a 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -166,6 +166,8 @@ export type PreRunHookDecision = 'run' | 'skip' | 'block';
* 之前就失败,也可能通过后继续得到正常的 agent 结果。
*/
export interface PreRunHookRunResult {
+ /** Explicit successful check, including a healthy no-work skip. Optional for old hooks. */
+ checkSucceeded?: true;
status: PreRunHookRunStatus;
decision: PreRunHookDecision;
exitCode: number | null;
diff --git a/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts b/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts
index 5788b0364a..8be3663470 100644
--- a/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts
+++ b/packages/maker-shared/src/__tests__/failedScheduleNotice.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { compareFailedScheduleRuns, shouldShowFailedScheduleNotice } from '../scheduleModel';
+import { activeScheduleFailures, compareFailedScheduleRuns, shouldShowFailedScheduleNotice } from '../scheduleModel';
import { buildSessionScheduleIndex } from '../sessionList';
import type { RemoteScheduleRun } from '../scheduleTypes';
const run = { runId: 'b', firedAt: 10 };
@@ -16,9 +16,50 @@ describe('historical schedule failure notice', () => {
{ id: 'd', status: 'aborted', firedAt: 14 },
].map((r) => ({ ...r, sessionId: 's', scheduleId: 'schedule' })) as RemoteScheduleRun[];
const info = buildSessionScheduleIndex([], new Map([['schedule', rows]])).get('s');
- expect(info?.latestFailedRun).toEqual(run);
+ expect(info?.latestFailedRun).toBeUndefined();
expect(info?.hasUnreadFailedRun).toBe(false);
});
+ it('recovers only the same schedule, regardless of input order, and preserves new failures', () => {
+ const rows: RemoteScheduleRun[] = [
+ { id: 'old-a', scheduleId: 'a', status: 'failed', firedAt: 1 },
+ { id: 'old-b', scheduleId: 'b', status: 'failed', firedAt: 2 },
+ { id: 'success-b', scheduleId: 'b', status: 'success', firedAt: 3 },
+ { id: 'new-b', scheduleId: 'b', status: 'failed', firedAt: 4 },
+ { id: 'recovered-on-host', scheduleId: 'c', status: 'failed', firedAt: 5, failureRecovered: true },
+ ];
+ expect([...activeScheduleFailures(rows)]).toEqual(['old-a', 'new-b']);
+ expect([...activeScheduleFailures([...rows].reverse())].sort()).toEqual(['new-b', 'old-a']);
+ });
+ it('only an explicitly healthy check can recover a precheck failure, never an execution failure', () => {
+ const rows: RemoteScheduleRun[] = [
+ { id: 'execution', scheduleId: 'a', status: 'failed', firedAt: 1 },
+ { id: 'check', scheduleId: 'a', status: 'failed', firedAt: 2, preRunHookResult: { decision: 'block' } },
+ { id: 'backoff', scheduleId: 'a', status: 'skipped', firedAt: 3 },
+ ];
+ expect([...activeScheduleFailures(rows)]).toEqual(['execution', 'check']);
+ rows.push({ id: 'healthy', scheduleId: 'a', status: 'skipped', firedAt: 4,
+ preRunHookResult: { decision: 'skip', checkSucceeded: true } });
+ expect([...activeScheduleFailures(rows)]).toEqual(['execution']);
+ });
+ it('uses the displayed classification to recover legacy and projected checks only', () => {
+ const variants: Partial<RemoteScheduleRun>[] = [
+ { errorMsg: 'pre-run hook blocked' },
+ { errorMsg: 'pre-run hook blocked', preRunHookResult: {} },
+ { errorMsg: 'pre-run hook blocked', preRunHookResult: { decision: 'skip' } },
+ { failureKind: 'precheck' },
+ { failureKind: 'rate-limit' },
+ ];
+ const rows: RemoteScheduleRun[] = variants.map((extra, i) => ({
+ id: `legacy-${i}`, scheduleId: 'a', status: 'failed', firedAt: 1, ...extra,
+ }));
+ rows.push({ id: 'execution', scheduleId: 'a', status: 'failed', firedAt: 2, errorMsg: 'agent failed' },
+ { id: 'projected-execution', scheduleId: 'a', status: 'failed', firedAt: 2,
+ failureKind: 'execution', errorMsg: 'pre-run hook blocked' });
+ expect(activeScheduleFailures(rows).size).toBe(7);
+ rows.push({ id: 'healthy', scheduleId: 'a', status: 'skipped', firedAt: 3,
+ preRunHookResult: { decision: 'skip', checkSucceeded: true } });
+ expect([...activeScheduleFailures(rows)]).toEqual(['execution', 'projected-execution']);
+ });
it.each(['readOnly', 'tailError', 'interrupted', 'continuationPending', 'error', 'credentialWait', 'streaming', 'running'])(
'yields to %s', (field) => {
expect(shouldShowFailedScheduleNotice(visible)).toBe(true);
diff --git a/packages/maker-shared/src/scheduleModel.ts b/packages/maker-shared/src/scheduleModel.ts
index ce35701af4..f9cc943031 100644
--- a/packages/maker-shared/src/scheduleModel.ts
+++ b/packages/maker-shared/src/scheduleModel.ts
@@ -598,7 +598,51 @@ function readString(value: Record<string, unknown>, key: string): string | null
}
/** Historical failure notices are independent of read receipts. */
-export interface FailedScheduleRunSnapshot { runId: string; firedAt: number }
+export type ScheduleFailureKind = 'precheck' | 'rate-limit' | 'execution';
+export interface FailedScheduleRunSnapshot {
+ runId: string;
+ firedAt: number;
+ scheduleId?: string;
+ failureKind?: ScheduleFailureKind;
+}
+
+/** Old hosts can omit the classification; keep their warning generic. */
+export function scheduleFailureMessageKey(run: FailedScheduleRunSnapshot): string {
+ return run.failureKind === 'rate-limit' ? 'rateLimited'
+ : run.failureKind === 'precheck' ? 'precheck' : 'text';
+}
+
+export function classifyScheduleFailure(run: RemoteScheduleRun): ScheduleFailureKind {
+ if (run.failureKind) return run.failureKind;
+ if (run.preRunHookResult?.decision === 'block') {
+ return /rate limit/i.test(run.preRunHookResult.stderr ?? '') ? 'rate-limit' : 'precheck';
+ }
+ return run.errorMsg?.startsWith('pre-run hook') ? 'precheck' : 'execution';
+}
+
+/** Full-history callers and lightweight host projections use the same recovery rule. */
+export function activeScheduleFailures(runs: readonly RemoteScheduleRun[]): Set<string> {
+ const successes = new Map<string, FailedScheduleRunSnapshot>();
+ const checks = new Map<string, FailedScheduleRunSnapshot>();
+ for (const run of runs) {
+ const candidate = { runId: run.id, firedAt: toMillis(run.firedAt) };
+ const targets = [
+ ...(run.status === 'success' ? [successes] : []),
+ ...(['success', 'failed', 'skipped'].includes(run.status) && run.preRunHookResult?.checkSucceeded === true ? [checks] : []),
+ ];
+ for (const target of targets) {
+ const previous = target.get(run.scheduleId);
+ if (!previous || compareFailedScheduleRuns(candidate, previous) > 0) target.set(run.scheduleId, candidate);
+ }
+ }
+ return new Set(runs.filter((run) => {
+ if (!isFailedScheduleRun(run) || run.failureRecovered === true) return false;
+ const success = successes.get(run.scheduleId);
+ const check = classifyScheduleFailure(run) !== 'execution' ? checks.get(run.scheduleId) : undefined;
+ return ![success, check].some((recovered) => recovered
+ && compareFailedScheduleRuns(recovered, { runId: run.id, firedAt: toMillis(run.firedAt) }) > 0);
+ }).map((run) => run.id));
+}
export function compareFailedScheduleRuns(a: FailedScheduleRunSnapshot, b: FailedScheduleRunSnapshot): number {
return a.firedAt - b.firedAt || (a.runId > b.runId ? 1 : a.runId < b.runId ? -1 : 0);
}
diff --git a/packages/maker-shared/src/scheduleTypes.ts b/packages/maker-shared/src/scheduleTypes.ts
index 90dd5a91f5..090f2a2ba4 100644
--- a/packages/maker-shared/src/scheduleTypes.ts
+++ b/packages/maker-shared/src/scheduleTypes.ts
@@ -130,6 +130,10 @@ export interface RemoteScheduleRun {
finishedAt?: RemoteTimestamp;
status: RemoteScheduleRunStatus;
errorMsg?: string;
+ /** Optional lightweight host projection; history and read receipts stay unchanged. */
+ failureKind?: 'precheck' | 'rate-limit' | 'execution';
+ failureRecovered?: boolean;
+ preRunHookResult?: { decision?: string; checkSucceeded?: boolean; stderr?: string };
resultText?: string;
costUsd?: number;
estimatedValueUsd?: number;
diff --git a/packages/maker-shared/src/sessionList.ts b/packages/maker-shared/src/sessionList.ts
index 5ffc6c1c0e..64a19ece1d 100644
--- a/packages/maker-shared/src/sessionList.ts
+++ b/packages/maker-shared/src/sessionList.ts
@@ -4,7 +4,7 @@ import { presentationDate, presentationText, type PresentationLocalizer } from '
import { isSyntheticTriggerText } from './syntheticTrigger.js';
import { hasPendingSessionInterruption, type SessionInterruptionState } from './sessionActivity.js';
import type { RemoteSchedule, RemoteScheduleRun } from './scheduleTypes.js';
-import { toMillis, isUnreadScheduleRun, isUnreadFailedScheduleRun, isFailedScheduleRun, compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from './scheduleModel.js';
+import { toMillis, isUnreadScheduleRun, isUnreadFailedScheduleRun, activeScheduleFailures, classifyScheduleFailure, compareFailedScheduleRuns, type FailedScheduleRunSnapshot } from './scheduleModel.js';
import { sessionCollaborationLabel, sessionWorktreeLabel } from './sessionIdentity.js';
import { isDefaultDraftSessionTitle } from './sessionTitle.js';
import { getSessionListCollapseView } from './sessionListCollapse.js';
@@ -608,6 +608,7 @@ export function buildSessionScheduleIndex(
const schedulesById = new Map(schedules.map((schedule) => [schedule.id, schedule]));
const scheduleIdsBySession = new Map<string, Set<string>>();
const index = new Map<string, RemoteSessionScheduleInfo>();
+ const activeFailures = activeScheduleFailures([...runsBySchedule.values()].flat());
const recordScheduleBinding = (sessionId: string, scheduleId: string) => {
const scheduleIds = scheduleIdsBySession.get(sessionId) ?? new Set<string>();
scheduleIds.add(scheduleId);
@@ -641,7 +642,7 @@ export function buildSessionScheduleIndex(
const existing = index.get(run.sessionId);
const unreadRunIds = existing ? [...existing.unreadRunIds] : [];
if (isUnreadScheduleRun(run)) unreadRunIds.push(run.id);
- const candidate = isFailedScheduleRun(run) ? { runId: run.id, firedAt } : undefined;
+ const candidate = activeFailures.has(run.id) ? { runId: run.id, firedAt, scheduleId: run.scheduleId, failureKind: classifyScheduleFailure(run) } : undefined;
const latestFailedRun = candidate && (!existing?.latestFailedRun || compareFailedScheduleRuns(candidate, existing.latestFailedRun) > 0)
? candidate : existing?.latestFailedRun;
const running = (existing?.running ?? false) || run.status === 'running';