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: 重试保留排序时维持定时任务活跃礼让

Cindy445c2d65a615
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 12748109d9..00a3000f94 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -4691,6 +4691,7 @@ describe('AgentInputCoordinator send transaction', () => {
// 于是那条续跑跑成了却不回流。
const h = createHarness();
const sid = 'enqueue-continue-exempt';
+ const now = Date.now();
h.coordinator.enqueue(sid, makeItem('q-continue', CONTINUE_AFTER_APP_EXIT_PROMPT));
await flush();
expect(h.onUserEnqueue).not.toHaveBeenCalled();
@@ -4698,6 +4699,7 @@ describe('AgentInputCoordinator send transaction', () => {
// 排序回归:恢复已有消息保留发送时间,但仍通知真人接手(unit)。
expect(mocks.touchUserSendInDb).not.toHaveBeenCalled();
expect(h.onUserAction).toHaveBeenCalledWith(sid);
+ expect(h.coordinator.getLastUserActionAt(sid)).toBeGreaterThanOrEqual(now);
// 普通消息照常上报。
h.coordinator.enqueue(sid, makeItem('q-normal', '顺手问个别的'));
@@ -6566,6 +6568,7 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {
});
it('resumes a paused queue-head recovery from the original head without reordering the tail', async () => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
const h = createHarness();
const sid = 'resume-paused-queue-head-recovery';
const first = makeItem('q-1', 'first');
@@ -6580,6 +6583,7 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {
h.coordinator.enqueue(sid, second);
await flush();
mocks.touchUserSendInDb.mockClear();
+ clock.mockReturnValue(2_000_000);
// A mechanical duplicate resume must not retry an unpaused recovery. Only
// the visible paused-queue Continue action owns the recovery transition.
@@ -6589,6 +6593,7 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {
expect(h.sendToAgent).toHaveBeenCalledTimes(1);
expect(mocks.touchUserSendInDb).not.toHaveBeenCalled();
expect(projection.recovery).toEqual({ kind: 'queue-head', clientId: 'q-1' });
+ expect(h.coordinator.getLastUserActionAt(sid)).toBe(1_000_000);
projection = h.coordinator.pausePendingQueueForRewind(sid);
expect(projection).toMatchObject({
@@ -6620,6 +6625,7 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {
expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'first' });
expect(mocks.touchUserSendInDb).not.toHaveBeenCalled();
expect(h.onUserAction).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.getLastUserActionAt(sid)).toBe(2_000_000);
expect(projection.recovery).toBeNull();
expect(projection.error).toBeNull();
expect(projection.pendingQueue.map((item) => item.clientId)).toEqual(['q-2']);
@@ -13377,11 +13383,13 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
});
it.each([false, true])('人工 retryLastError 保留排序时间与真人接手(已有产出=%s)', async (hasProgress) => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
const h = createHarness();
const sid = 'manual-retry-no-auto-flag';
h.setHasAssistantProgressAfter(async () => hasProgress);
await failAfterDispatch(h, sid);
+ clock.mockReturnValue(2_000_000);
await h.coordinator.retryLastError(sid);
await flush();
@@ -13389,6 +13397,10 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
expect(h.sendToAgent.mock.calls[1]?.[3]?.persistUserMessage?.autoResume).toBeUndefined();
expect(mocks.touchUserSendInDb).toHaveBeenCalledTimes(1);
expect(h.onUserAction).toHaveBeenCalledTimes(2);
+ expect(h.coordinator.getLastUserActionAt(sid)).toBe(2_000_000);
+ expect(h.coordinator.getLastUserActionAt('unrelated-session')).toBeNull();
+ h.coordinator.clearSession(sid);
+ expect(h.coordinator.getLastUserActionAt(sid)).toBeNull();
});
it('自动续跑再次失败后,人工 Retry 会清掉上一轮隐藏标记并重置真人额度', async () => {
@@ -14663,6 +14675,7 @@ describe('usage-limit wait (ordinary tasks)', () => {
// Drive both production owners with injected timers: three failed auto attempts,
// then a human action must start a fresh budget without reopening a channel turn.
it.each(['retry', 'continue', 'new-input'] as const)('starts a fresh quota episode on queue-head %s before persistence', async action => {
+ const clock = vi.spyOn(Date, 'now').mockReturnValue(1_000_000);
const h = createHarness();
const sid = 'quota-manual-episode';
const timers: Array<() => void> = [];
@@ -14699,16 +14712,21 @@ describe('usage-limit wait (ordinary tasks)', () => {
expect(timers).toHaveLength(0);
expect(h.coordinator.getProjection(sid).usageLimitWait).toBeNull();
expect(h.onUserMessagePersisted).not.toHaveBeenCalled();
+ expect(h.coordinator.getLastUserActionAt(sid)).toBe(1_000_000);
+ clock.mockReturnValue(2_000_000);
if (action === 'retry') await h.coordinator.retryLastError(sid);
else h.coordinator.enqueue(sid, makeItem('next', action === 'continue' ? CONTINUE_AFTER_ERROR_PROMPT : 'new task'));
await flush();
expect(timers).toHaveLength(1);
expect(h.coordinator.getProjection(sid).usageLimitWait).not.toBeNull();
expect(h.onUiRetry).not.toHaveBeenCalled();
+ expect(h.coordinator.getLastUserActionAt(sid)).toBe(2_000_000);
+ clock.mockReturnValue(3_000_000);
timers.shift()!();
await flush();
await flush();
expect(attempts).toEqual([1, 2, 3, 1]);
+ expect(h.coordinator.getLastUserActionAt(sid)).toBe(2_000_000);
expect(h.sendToAgent.mock.calls.at(-1)?.[3].persistUserMessage?.clientId)
.toBe(action === 'new-input' ? 'next' : 'original');
} finally {
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index bf59b872db..d25c045055 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -738,6 +738,8 @@ type AgentInputSendFailure = Extract<
>;
interface SessionInputState {
+ /** Runtime courtesy clock; never persisted or used for list ordering. */
+ lastUserActionAt: number | null;
pendingQueue: AgentInputQueuedMessage[];
pendingCompacts: PendingCompactRequest[];
steeringQueueClientIds: string[];
@@ -885,6 +887,7 @@ function createInitialInputState(
fencedStaleTerminal: { instanceId: string; generation: number } | null = null,
): SessionInputState {
return {
+ lastUserActionAt: null,
pendingQueue: [],
pendingCompacts: [],
steeringQueueClientIds: [],
@@ -1973,7 +1976,7 @@ export class AgentInputCoordinator {
clientId: abandonedClientId,
});
// 继续原消息仍是真人接手,但不是新消息,不推进列表排序时间。
- this.deps.onUserAction?.(sessionId);
+ this.noteUserAction(sessionId);
this.emit(sessionId);
this.scheduleDrain(sessionId, 'ui-continue-queue-head-unlock');
return this.getProjection(sessionId);
@@ -2019,7 +2022,7 @@ export class AgentInputCoordinator {
// 而静默顺延(PR #972 review P2)。侧栏排序的 bump 语义保留在派发时刻 ——
// runner 的 accepted 回调按直发路径同款调 touchUserSendInDb(ctx.firedAt)。
if (!automaticOrigin) {
- if (isUiContinuationItem(item)) this.deps.onUserAction?.(sessionId);
+ if (isUiContinuationItem(item)) this.noteUserAction(sessionId);
else this.touchUserSend(sessionId, opts?.sendAtMs);
}
// 视觉连续性: 当这条入队后立即可派发(agent 空闲、队列此前为空、无暂停/锁/恢复
@@ -3132,7 +3135,7 @@ export class AgentInputCoordinator {
sessionId,
clientId: pausedQueueHeadRecoveryClientId,
});
- this.deps.onUserAction?.(sessionId);
+ this.noteUserAction(sessionId);
} else {
this.clearErrorUnlessQueueHeadBlocked(state);
}
@@ -3459,7 +3462,7 @@ export class AgentInputCoordinator {
attemptToken ?? undefined,
);
}
- if (!automatic) this.deps.onUserAction?.(sessionId);
+ if (!automatic) this.noteUserAction(sessionId);
this.emit(sessionId);
this.scheduleDrain(sessionId, 'retry');
this.scheduleExternalTurnRetryIfNeeded(sessionId, state, 'retry');
@@ -6443,9 +6446,20 @@ export class AgentInputCoordinator {
if (byClientId.size === 0) this.steerRequestLineages.delete(sessionId);
}
+ getLastUserActionAt(sessionId: string): number | null {
+ return this.states.get(sessionId)?.lastUserActionAt ?? null;
+ }
+
+ private noteUserAction(sessionId: string): void {
+ // Use host time, not a remote sender's clock. State clear/owner teardown also
+ // clears this clock; an app restart has no running turn to yield to.
+ this.getState(sessionId).lastUserActionAt = Date.now();
+ this.deps.onUserAction?.(sessionId);
+ }
+
private touchUserSend(sessionId: string, atMs?: number): void {
// 真人接手在派发/落库失败时也成立;限额预算与渠道 turn 的认领分别通知。
- this.deps.onUserAction?.(sessionId);
+ this.noteUserAction(sessionId);
void touchUserSendInDb(sessionId, atMs).catch((err) => {
log.warn('touchUserSend failed', { sessionId, error: errorMessage(err) });
});
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index bd3eae1e67..c9c45ef20b 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -4769,6 +4769,10 @@ export function isSessionInTurn(sessionId: string): boolean {
return sessionTurnActivityTracker.isSessionInTurn(sessionId);
}
+export function getSessionLastUserActionAt(sessionId: string): number | null {
+ return agentInputCoordinatorHolder?.getLastUserActionAt(sessionId) ?? null;
+}
+
/** Runtime-only attribution; queued or rejected steering cannot take ownership. */
export function getSessionActiveInputClientIds(sessionId: string): string[] {
return agentInputCoordinatorHolder?.getActiveInputClientIds(sessionId) ?? [];
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
index b030071bd8..968ac083e4 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -499,6 +499,37 @@ beforeEach(() => {
});
describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
+ // PR #7104 / unit: retrying an old message must still yield to the human,
+ // even though its persisted send-time sorting key no longer advances.
+ it('defers a heartbeat after recent human recovery instead of enqueueing it', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ queue.deps.getLastUserActionAt = () => Date.now();
+ const { runner, logger } = createRunnerHarness(h.session, queue.deps);
+ mocks.isSessionInTurn.mockReturnValue(true);
+ mocks.getSessionRowSnapshot.mockResolvedValue({
+ status: 'active', userSendAt: Date.now() - 30 * 60_000, providerId: null,
+ });
+ await expect(runner.fire(heartbeatSchedule(), createFireContext()))
+ .resolves.toMatchObject({ deferred: true });
+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('defer fire (user-active)'));
+ expect(queue.enqueueCalls).toHaveLength(0);
+ expect(h.session.send).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { age: 10 * 60_000, inTurn: true },
+ { age: 0, inTurn: false },
+ ])('does not yield for expired recovery or an idle turn: %j', async ({ age, inTurn }) => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true, hasQueued: true });
+ queue.deps.getLastUserActionAt = () => Date.now() - age;
+ const { runner, logger } = createRunnerHarness(h.session, queue.deps);
+ mocks.isSessionInTurn.mockReturnValue(inTurn);
+ await runner.fire(heartbeatSchedule(), createFireContext());
+ expect(logger.info).not.toHaveBeenCalledWith(expect.stringContaining('defer fire (user-active)'));
+ });
+
// #7044 / unit: the backing schedule is manual, but RoutineEngine owns its
// retries. Unlike existing queue-busy cases, a recent user turn must yield
// after a passed precheck without queuing a prompt or starting the model.
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index 57d7e4bbab..e4ffee3cbe 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -46,6 +46,7 @@ import {
enqueueSchedulerPrompt,
ensureSchedulerQueueRestored,
findSchedulerUsageLimitWait,
+ getSessionLastUserActionAt,
hasQueuedSchedulerPrompt,
isSchedulerAutoResumePending,
isSchedulerPromptTracked,
@@ -153,6 +154,7 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedul
// 心跳撞忙排队桥:实现挂在 maker-ipc/register.ts 的 coordinator 装配处
// 先恢复快照再判忙闲;holder 未就绪时恢复返回 false,由 runner 顺延。
schedulerQueue: {
+ getLastUserActionAt: getSessionLastUserActionAt,
ensureQueueRestored: ensureSchedulerQueueRestored,
isSessionBusy: isSchedulerTargetSessionBusy,
hasQueuedPrompt: hasQueuedSchedulerPrompt,
diff --git a/apps/desktop/src/main/scheduler-host/runner.ts b/apps/desktop/src/main/scheduler-host/runner.ts
index ff864017ed..3b2f10d021 100644
--- a/apps/desktop/src/main/scheduler-host/runner.ts
+++ b/apps/desktop/src/main/scheduler-host/runner.ts
@@ -220,6 +220,8 @@ function defaultPermissionModeForSchedule(): PermissionMode {
* 降级)时回退直发 + 顺延的旧行为。
*/
export interface SchedulerQueueDeps {
+ /** Host-local human activity, including retries that preserve send-time sorting. */
+ getLastUserActionAt?(sessionId: string): number | null;
/** 目标会话当前是否忙(turn 运行中 / 队列有积压 / 凭证切换等待中)。 */
isSessionBusy(sessionId: string): boolean;
/**
@@ -1046,17 +1048,23 @@ export class MakerScheduleRunner implements ScheduleRunner {
fastMode: resolvedSelection.fastMode,
};
}
- // B1 活跃礼让:最近有人往这个 session 发过输入(userSendAt 在窗口内)且
+ // B1 活跃礼让:最近有人发送或手动恢复这个 session,且
// session 正跑 turn → 本轮不抢,顺延。两条件都满足才让:仅"刚发过"
// 但 turn 已结束属正常 heartbeat 时机;仅"在跑"但非最近有输入多半是上轮
- // 心跳没跑完,交给 B2 的撞忙顺延。零新增查询(复用已取的 row.userSendAt
- // + 内存 tracker)。
+ // 心跳没跑完,沿用下方撞忙处理。零新增查询(复用 row.userSendAt
+ // + coordinator 的真人操作时间与 turn tracker)。
// 注:userSendAt 现在也被 scheduler 自身 fire bump(见 onAccepted),所以窗口内
// 命中可能来自上一次自动 fire 而非真人。这只会让 B1 更保守——但唯一效果是"正在
// 跑 turn 时顺延",而正在跑 turn 的 send 本就会被 B2(SESSION_RUNNING)顺延,两者
// 落点一致,无功能回退,仅 telemetry reason 偏"user-active"。
+ // Retry/Continue preserve userSendAt for list ordering. The coordinator
+ // separately records human takeover; retain the DB fallback for direct sends.
+ const lastUserActionAt = Math.max(
+ row?.userSendAt ?? 0,
+ this.deps.schedulerQueue?.getLastUserActionAt?.(sessionId) ?? 0,
+ );
const recentlyUserDriven =
- row?.userSendAt != null && Date.now() - row.userSendAt < ACTIVE_YIELD_WINDOW_MS;
+ lastUserActionAt > 0 && Date.now() - lastUserActionAt < ACTIVE_YIELD_WINDOW_MS;
if (recentlyUserDriven && isSessionInTurn(sessionId) && this.canDefer(schedule, ctx)) {
holder.releaseAgentSwitchLock?.();
holder.releaseAgentSwitchLock = undefined;