🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(task): stamp schedule arming window on column-only writes (#20684)
Arvin Xu2ab27b4d4b1b
diff --git a/apps/server/src/services/task/armScheduleOnColumnWrite.test.ts b/apps/server/src/services/task/armScheduleOnColumnWrite.test.tsnew file mode 100644index 00000000000..5fb493a3670--- /dev/null+++ b/apps/server/src/services/task/armScheduleOnColumnWrite.test.ts@@ -0,0 +1,69 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest';++import { armScheduleOnColumnWrite } from './armScheduleOnColumnWrite';++describe('armScheduleOnColumnWrite / T-634 arming window', () => {+ const task = (overrides: Record<string, unknown> = {}) => ({+ automationMode: 'schedule' as string | null,+ context: {} as unknown,+ id: 'task-1',+ schedulePattern: '0 10 27 9 *' as string | null,+ status: 'backlog',+ ...overrides,+ });++ it('stamps the window on a backlog task armed without a status transition', () => {+ const result = armScheduleOnColumnWrite(task());++ expect(result.context).toBeDefined();+ const stamped = (result.context as any).scheduler.scheduleStartedAt as string;+ expect(Number.isNaN(Date.parse(stamped))).toBe(false);+ });++ it('keeps the other context pockets', () => {+ const origin = { topicId: 'tpc_1' };++ const result = armScheduleOnColumnWrite(+ task({ context: { origin, scheduler: { consecutiveFailures: 0 } } }),+ );++ expect(result.context).toEqual({+ origin,+ scheduler: { consecutiveFailures: 0, scheduleStartedAt: expect.any(String) },+ });+ });++ it('does not reset an existing quota window on re-arm', () => {+ expect(+ armScheduleOnColumnWrite(+ task({ context: { scheduler: { scheduleStartedAt: '2026-09-20T06:00:00.000Z' } } }),+ ),+ ).toEqual({});+ });++ it('does not arm without a cron pattern or in non-schedule mode', () => {+ expect(armScheduleOnColumnWrite(task({ schedulePattern: null }))).toEqual({});+ expect(armScheduleOnColumnWrite(task({ schedulePattern: '' }))).toEqual({});+ expect(armScheduleOnColumnWrite(task({ automationMode: 'heartbeat' }))).toEqual({});+ expect(armScheduleOnColumnWrite(task({ automationMode: null }))).toEqual({});+ });++ it('stamps a heartbeat→cron switched task still in scheduled status (P1)', () => {+ // A heartbeat task switched to cron via the column-only path keeps status+ // `scheduled`; getScheduledTasks dispatches scheduled rows, so the row+ // must be stamped here, not skipped — otherwise a grace-window occurrence+ // replays and burns a one-shot maxExecutions quota.+ const result = armScheduleOnColumnWrite(task({ status: 'scheduled' }));++ expect(result.context).toBeDefined();+ const stamped = (result.context as any).scheduler.scheduleStartedAt as string;+ expect(Number.isNaN(Date.parse(stamped))).toBe(false);+ });++ it('skips statuses the dispatcher does not fire or that carry their own stamping', () => {+ for (const status of ['running', 'paused', 'completed', 'failed', 'canceled']) {+ expect(armScheduleOnColumnWrite(task({ status })), `status=${status}`).toEqual({});+ }+ });+});diff --git a/apps/server/src/services/task/armScheduleOnColumnWrite.ts b/apps/server/src/services/task/armScheduleOnColumnWrite.tsnew file mode 100644index 00000000000..aa80e3b45f8--- /dev/null+++ b/apps/server/src/services/task/armScheduleOnColumnWrite.ts@@ -0,0 +1,62 @@+import type { TaskStatus } from '@lobechat/types';++/**+ * Arms the run-count window for a schedule write that does not pass through+ * `updateStatus` (T-634).+ *+ * `setTaskSchedule` (agent tool) and REST/SDK patches land in `task.update`+ * without a status, so a backlog task configured this way keeps its status and+ * never reaches the stamping branch inside the status-transition path — the+ * dispatcher then evaluates the task with `armedAt = null`, and a cron slot+ * inside the dispatch grace window fires immediately, consuming a one-shot+ * `maxExecutions` quota before the user ever intended the schedule to go live+ * (vent T-634, David Tai 2026-09-14 / Rex 2026-10-07 / Leon Kwan 2026-10-10).+ *+ * Returns the `context` pocket to persist **in the same atomic write** that+ * makes the schedule dispatchable. The caller must merge this into the row+ * update rather than writing it separately — a stamp landing after the pattern+ * column commit would leave a window where the dispatcher sees an unstamped+ * dispatchable row and replays a grace-window occurrence.+ *+ * Stamps when the resulting task is dispatchable (schedule mode with a cron+ * pattern, not terminal/paused/running) and the task has no stamp yet. A+ * `scheduled` row is dispatched too (`getScheduledTasks` only excludes+ * terminal/paused/running), so it must be stamped here as well: a heartbeat+ * task switched to cron keeps status `scheduled` and never passes the+ * `updateStatus` stamping branch. Re-arming must not reset an existing quota+ * window — the `scheduleStartedAt` check below guards that — and the+ * `updateStatus` path keeps its own stamping, so the two must not double-stamp+ * on a transition that carries schedule columns.+ */+export const armScheduleOnColumnWrite = (task: {+ automationMode: string | null;+ context?: unknown;+ schedulePattern: string | null;+ status: TaskStatus | string;+}): { context?: Record<string, unknown> } => {+ // Without a cron pattern the dispatcher never picks the task up, so it is+ // not live and must not look armed.+ if (task.automationMode !== 'schedule' || !task.schedulePattern) return {};++ const status = task.status;+ if (+ status === 'running' ||+ status === 'paused' ||+ status === 'completed' ||+ status === 'failed' ||+ status === 'canceled'+ ) {+ return {};+ }++ const context = (task.context as Record<string, unknown> | null) ?? {};+ const scheduler = (context.scheduler as { scheduleStartedAt?: string } | null) ?? {};+ if (scheduler.scheduleStartedAt) return {};++ return {+ context: {+ ...context,+ scheduler: { ...scheduler, scheduleStartedAt: new Date().toISOString() },+ },+ };+};diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex 97ce7e73200..97ddf2d32bf 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -2426,6 +2426,129 @@ describe('TaskService', () => {);});+ it('arms the run-count window on a column-only schedule write (T-634)', async () => {+ // Column-only write: schedule columns move without a status, the row+ // keeps `backlog` — exactly the path that used to leave `armedAt = null`+ // and let a grace-window occurrence burn a one-shot maxExecutions quota.+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);+ mockTaskModel.findById.mockResolvedValue({+ automationMode: 'heartbeat',+ context: { origin: { topicId: 'tpc_1' } },+ id: 'task_001',+ schedulePattern: null,+ status: 'backlog',+ });+ mockTaskModel.updateWithLog.mockResolvedValue({ id: 'task_001' });++ await new TaskService(db, userId, 'ws-1').updateTaskWithAssigneeLock(+ 'task_001',+ { automationMode: 'schedule', schedulePattern: '0 9 * * *' },+ { userId },+ );++ // The stamp rides in the SAME updateWithLog write as the schedule+ // columns, decided under the row lock — no separate unlocked+ // read/merge/write may follow (P2: atomicity).+ expect(mockTaskModel.updateContext).not.toHaveBeenCalled();+ const [, written] = mockTaskModel.updateWithLog.mock.calls[0]!;+ expect((written as any).automationMode).toBe('schedule');+ expect((written as any).schedulePattern).toBe('0 9 * * *');+ expect((written as any).context).toMatchObject({+ origin: { topicId: 'tpc_1' },+ scheduler: { scheduleStartedAt: expect.any(String) },+ });+ });++ it('does not arm a column-only write when the resulting task is not dispatchable', async () => {+ // Heartbeat tasks are armed through the lifecycle re-arm path, not the+ // cron window; a schedule write that leaves no pattern is inert too.+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);+ mockTaskModel.findById.mockResolvedValue({+ automationMode: 'schedule',+ context: null,+ id: 'task_001',+ schedulePattern: '0 9 * * *',+ status: 'backlog',+ });+ mockTaskModel.updateWithLog.mockResolvedValue({ id: 'task_001' });++ const service = new TaskService(db, userId, 'ws-1');++ await service.updateTaskWithAssigneeLock(+ 'task_001',+ { automationMode: 'heartbeat', schedulePattern: null },+ { userId },+ );+ expect(mockTaskModel.updateWithLog).toHaveBeenLastCalledWith(+ 'task_001',+ expect.not.objectContaining({ context: expect.anything() }),+ { userId },+ {},+ );++ // No schedule columns in the patch: the arming probe must not even lock.+ const locksBefore = mockTaskModel.lockForUpdate.mock.calls.length;+ await service.updateTaskWithAssigneeLock('task_001', { priority: 3 }, { userId });+ expect(mockTaskModel.lockForUpdate.mock.calls.length).toBe(locksBefore);+ });++ it('does not stamp a window when the write explicitly clears automationMode (P2)', async () => {+ // Explicit `null` clears the mode. Under the old `??` derivation the+ // probe saw the locked row's `schedule` and stamped a window for a row+ // this very write disables; a later re-enable would preserve that stale+ // stamp and replay an occurrence from the disabled interval.+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);+ mockTaskModel.findById.mockResolvedValue({+ automationMode: 'schedule',+ context: null,+ id: 'task_001',+ schedulePattern: '0 9 * * *',+ status: 'backlog',+ });+ mockTaskModel.updateWithLog.mockResolvedValue({ id: 'task_001' });++ await new TaskService(db, userId, 'ws-1').updateTaskWithAssigneeLock(+ 'task_001',+ { automationMode: null },+ { userId },+ );++ expect(mockTaskModel.updateWithLog).toHaveBeenLastCalledWith(+ 'task_001',+ expect.not.objectContaining({ context: expect.anything() }),+ { userId },+ {},+ );+ });++ it('does not stamp a window when the write explicitly clears schedulePattern (P2)', async () => {+ // Pattern-only clear on an unstamped row: the resulting row has no cron+ // pattern, so it is inert and must stay unstamped — the probe must not+ // resurrect the locked row's old pattern.+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);+ mockTaskModel.findById.mockResolvedValue({+ automationMode: 'schedule',+ context: null,+ id: 'task_001',+ schedulePattern: '0 9 * * *',+ status: 'backlog',+ });+ mockTaskModel.updateWithLog.mockResolvedValue({ id: 'task_001' });++ await new TaskService(db, userId, 'ws-1').updateTaskWithAssigneeLock(+ 'task_001',+ { schedulePattern: null },+ { userId },+ );++ expect(mockTaskModel.updateWithLog).toHaveBeenLastCalledWith(+ 'task_001',+ expect.not.objectContaining({ context: expect.anything() }),+ { userId },+ {},+ );+ });+it('renders assignment logs as activities with both sides resolved', async () => {mockTaskModel.resolve.mockResolvedValue({createdAt: null,diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex 4d79c64934d..eebb126b5e2 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -17,6 +17,7 @@ import { type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';import { type ReviewResult, TaskReviewService } from '../taskReview';import { TaskRunnerService } from '../taskRunner';import { writeKeepingArchivedIdle } from './archiveGuard';+import { armScheduleOnColumnWrite } from './armScheduleOnColumnWrite';import { armScheduleOnCreate } from './armScheduleOnCreate';import type { TaskServiceDeps } from './deps';import { TaskDetailService } from './detail';@@ -674,14 +675,45 @@ export class TaskService {options: Parameters<TaskModel['updateWithLog']>[3] = {},): Promise<TaskItem | null> {return this.withAssigneeUserLock(data.assigneeUserId, (db) =>- writeKeepingArchivedIdle(db, (tx) =>- new TaskModel(tx, this.userId, this.workspaceId).updateWithLog(- taskId,- data,- actor,- options,- ),- ),+ writeKeepingArchivedIdle(db, async (tx) => {+ const model = new TaskModel(tx, this.userId, this.workspaceId);+ // A schedule write that carries schedule columns but no status must arm+ // the run-count window in the SAME write that makes the schedule+ // dispatchable (vent T-634). The stamp is decided against the row as it+ // exists right before this update, read under the same row lock the+ // write itself uses, so a concurrent dispatcher can never observe a+ // "pattern set, window unstamped" row and replay a grace-window+ // occurrence. A status transition stamps inside `updateStatus` instead,+ // so the arming is skipped there to avoid double-stamping.+ if (+ !data.status &&+ (data.automationMode !== undefined || data.schedulePattern !== undefined)+ ) {+ await model.lockForUpdate(taskId);+ const current = await model.findById(taskId);+ if (current) {+ // `context` is a whole-column replace: when the caller ships their+ // own pocket it is the base, otherwise the row as locked. The+ // schedule columns must NOT use `??`: the tRPC and REST schemas+ // use an explicit `null` to clear a field, and `??` would swap+ // that clear for the locked row's old value — the probe would+ // stamp a window for a row the write is about to disable, and a+ // later re-enable would preserve that stale stamp and replay an+ // occurrence from the disabled interval. Only `undefined` means+ // "not part of this patch".+ const arming = armScheduleOnColumnWrite({+ automationMode:+ data.automationMode !== undefined ? data.automationMode : current.automationMode,+ context: data.context ?? current.context,+ schedulePattern:+ data.schedulePattern !== undefined ? data.schedulePattern : current.schedulePattern,+ status: current.status,+ });+ if (arming.context) data.context = arming.context;+ }+ }+ return model.updateWithLog(taskId, data, actor, options);+ }),);}