From d800837d20c9738d4166382e1aff3ee0f7e8c1e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B8=85=E7=A7=8B?= Date: Fri, 20 Nov 2026 01:43:51 -0800 Subject: [PATCH] fix: let a scheduled task start its next run in a new destination thread --- .../SettingsScheduledTasksRouteScreen.tsx | 3 ++ .../src/mcp/OrchestratorMcpService.test.ts | 51 +++++++++---------- apps/server/src/mcp/OrchestratorMcpService.ts | 15 ++---- .../ScheduledTaskService.test.ts | 32 ++++++++++-- .../scheduledTasks/ScheduledTaskService.ts | 13 +++-- .../settings/ScheduledTasksSettings.tsx | 1 + packages/contracts/src/scheduledTask.ts | 2 + .../scheduled-task-reset-destination.e2e.ts | 40 +++++++++++++++ 8 files changed, 110 insertions(+), 47 deletions(-) create mode 100644 scripts/scenarios/scheduled-task-reset-destination.e2e.ts diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx index 94594fa97a8c9..5b3ddf4c87aa8 100644 --- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx @@ -884,6 +884,9 @@ function TaskForm({ schedule, enabled: draft.enabled, threadId: draft.threadId, + ...(draft.threadId === null && draft.task?.threadId + ? { detachFromThreadId: draft.task.threadId } + : {}), ...(offersThreadModes ? { threadMode: draft.threadMode } : {}), workspaceStrategy: draft.workspace === "root" diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index 2dad1fe68ee6d..48b48e49a0159 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -4299,35 +4299,30 @@ describe("OrchestratorMcpService provider resolution", () => { }), ); - it.effect( - "refuses unbinding into fresh sessions in one call, which would keep the thread", - () => - Effect.gen(function* () { - const inputs = yield* Ref.make>([]); - const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( - Effect.provide( - service( - masterRepository, - yield* Ref.make>([]), - { - ...existing, - threadId: ThreadId.make("thread:scheduled-base"), - threadMode: "continue", - }, - inputs, - ), + it.effect("moves a bound task to fresh sessions in a first-run thread", () => + Effect.gen(function* () { + const inputs = yield* Ref.make>([]); + const threadId = ThreadId.make("thread:scheduled-base"); + const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe( + Effect.provide( + service( + masterRepository, + yield* Ref.make>([]), + { ...existing, threadId, threadMode: "continue" }, + inputs, ), - ); - const refused = yield* mcp - .updateScheduledTask(client, { - scheduledTaskId: existing.id, - bindToCurrentThread: false, - freshSession: true, - }) - .pipe(Effect.flip); - assert.include(refused.message, "first unbind it"); - assert.deepEqual(yield* Ref.get(inputs), []); - }), + ), + ); + yield* mcp.updateScheduledTask(client, { + scheduledTaskId: existing.id, + bindToCurrentThread: false, + freshSession: true, + }); + const [input] = yield* Ref.get(inputs); + assert.equal(input?.threadId, null); + assert.equal(input?.detachFromThreadId, threadId); + assert.equal(input?.threadMode, "fresh_session"); + }), ); it.effect("follows the default branch when a task is unbound from its thread", () => diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 7b8c99877d974..b0a874b085127 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -2456,18 +2456,6 @@ const make = Effect.gen(function* () { : "bindToCurrentThread binds to this thread, which belongs to a different project.", ); } - // A save keeps a bound thread unless the task goes back to new threads, so this pair - // would leave runs in the old thread. - if ( - input.bindToCurrentThread === false && - input.freshSession === true && - existing.threadId !== null - ) { - return yield* failure( - "invalid_request", - "To move this task to a new thread with fresh sessions, first unbind it with bindToCurrentThread: false, then set freshSession: true in a second call.", - ); - } const threadId = input.bindToCurrentThread === undefined ? existing.threadId @@ -2487,6 +2475,9 @@ const make = Effect.gen(function* () { schedule: input.schedule ?? existing.schedule, projectId: existing.projectId, threadId, + ...(input.bindToCurrentThread === false && existing.threadId !== null + ? { detachFromThreadId: existing.threadId } + : {}), threadMode: input.freshSession === undefined && input.bindToCurrentThread === undefined ? scheduledTaskThreadMode(existing) diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts index 051aeeac9b693..bf710a8040958 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts @@ -731,14 +731,17 @@ it.effect("a fresh-session task launches one thread, then starts each later run const launches = yield* Ref.make(0); const sends = yield* Ref.make>([]); const launched = ThreadId.make("thread:fresh-session-task"); + const replacement = ThreadId.make("thread:replacement"); const layer = ScheduledTaskService.layer.pipe( Layer.provide( Layer.mergeAll( ManagedPolicy.layerTest(), Layer.mock(ThreadLaunchService.ThreadLaunchService)({ launch: () => - Ref.update(launches, (n) => n + 1).pipe( - Effect.as({ threadId: launched, resumed: false } as never), + Ref.getAndUpdate(launches, (n) => n + 1).pipe( + Effect.map( + (n) => ({ threadId: n === 0 ? launched : replacement, resumed: false }) as never, + ), ), }), Layer.mock(ThreadManagementService.ThreadManagementService)({ @@ -795,14 +798,35 @@ it.effect("a fresh-session task launches one thread, then starts each later run assert.equal(yield* Ref.get(launches), 1); assert.deepEqual(yield* Ref.get(sends), [{ threadId: launched, freshContext: true }]); + const reset = yield* service.upsert({ + ...input, + threadId: null, + detachFromThreadId: launched, + threadMode: "continue", + }); + assert.equal(reset.task.threadId, null); + assert.equal((yield* service.runNow({ id: input.id })).threadId, replacement); + const staleReset = yield* service.upsert({ + ...input, + threadId: null, + detachFromThreadId: launched, + threadMode: "continue", + }); + assert.equal(staleReset.task.threadId, replacement); + yield* service.runNow({ id: input.id }); + assert.equal(yield* Ref.get(launches), 2); + assert.deepEqual(yield* Ref.get(sends), [ + { threadId: launched, freshContext: true }, + { threadId: replacement }, + ]); // Its thread stays in the old project, so moving the task leaves it for a new one. const moved = yield* service.upsert({ ...input, projectId: ProjectId.make("project:moved"), - threadId: launched, + threadId: replacement, }); assert.equal(moved.task.threadId, null); - assert.equal(moved.task.threadMode, "fresh_session"); + assert.equal(moved.task.threadMode, "continue"); const unbound = yield* service.upsert({ ...input, threadMode: "new_thread" }); assert.equal(unbound.task.threadId, null); }).pipe(Effect.provide(layer)); diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts index 4570115a91cec..3329019552fe3 100644 --- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts +++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts @@ -636,6 +636,7 @@ export const layer = Layer.effect( const saveTask = ( task: ScheduledTask, requireExisting: boolean, + detachFromThreadId: ThreadId | null, /** The schedule this save read, when it left the schedule unchanged. */ keptSchedule: ScheduledTask["schedule"] | null, webhook: { @@ -703,11 +704,11 @@ export const layer = Layer.effect( enabled = excluded.enabled, schedule_json = excluded.schedule_json, project_id = excluded.project_id, - -- A first run may bind the thread while this save is in flight; only a - -- switch to new threads unbinds. + -- A first run can bind a thread during a save. Detach only the observed binding. thread_id = CASE WHEN excluded.thread_mode = 'new_thread' THEN NULL WHEN excluded.project_id != scheduled_tasks.project_id THEN excluded.thread_id + WHEN ${detachFromThreadId} IS NOT NULL THEN NULLIF(scheduled_tasks.thread_id, ${detachFromThreadId}) ELSE COALESCE(excluded.thread_id, scheduled_tasks.thread_id) END, thread_mode = excluded.thread_mode, @@ -1484,7 +1485,12 @@ export const layer = Layer.effect( existingTask !== null && existingTask.projectId !== input.projectId && keptThreadId === existingTask.threadId; - const threadId = threadMode === "new_thread" || movedOffThread ? null : keptThreadId; + const detachFromThreadId = + input.threadId === null ? (input.detachFromThreadId ?? null) : null; + const threadId = + threadMode === "new_thread" || movedOffThread || keptThreadId === detachFromThreadId + ? null + : keptThreadId; // An unchanged destination is not rechecked, so a task on an archived thread stays editable. if (threadId !== null && threadId !== existingTask?.threadId) { yield* requireDestinationThread(threadId, input.projectId, id); @@ -1609,6 +1615,7 @@ export const layer = Layer.effect( yield* saveTask( task, input.requireExisting === true, + detachFromThreadId, scheduleUnchanged ? existingTask.schedule : null, webhook, ); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 39670ed266666..4f38510e14f7a 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -1679,6 +1679,7 @@ function ScheduledTaskEditorForm({ schedule, projectId: selectedProjectId as ProjectId, threadId: draft.threadId ? (draft.threadId as ThreadId) : null, + ...(!draft.threadId && task?.threadId ? { detachFromThreadId: task.threadId } : {}), ...(offersThreadModes ? { threadMode: draft.threadMode } : {}), workspaceStrategy, modelSelection, diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts index 4297ad94b73e9..71638098e29af 100644 --- a/packages/contracts/src/scheduledTask.ts +++ b/packages/contracts/src/scheduledTask.ts @@ -288,6 +288,8 @@ export const ScheduledTaskUpsertInput = Schema.Struct({ schedule: ScheduledTaskUpsertSchedule, projectId: ProjectId, threadId: Schema.optional(Schema.NullOr(ThreadId)), + /** Clear this observed binding when saving a null destination. Older forms send null even on untouched edits. */ + detachFromThreadId: Schema.optional(ThreadId), /** Omitted: keep the stored mode, or derive it from `threadId` for a new or rebound task. */ threadMode: Schema.optional(ScheduledTaskThreadMode), workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy, diff --git a/scripts/scenarios/scheduled-task-reset-destination.e2e.ts b/scripts/scenarios/scheduled-task-reset-destination.e2e.ts new file mode 100644 index 0000000000000..26320f2ddab97 --- /dev/null +++ b/scripts/scenarios/scheduled-task-reset-destination.e2e.ts @@ -0,0 +1,40 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A saved scheduled task can leave its thread for one started by its next run", + WEB, + async ({ t3, app, screen }) => { + const project = await t3.project("scheduled-destination"); + await t3.thread({ project, title: "Original conversation", messages: ["Start"] }); + await t3.open("/settings/scheduled-tasks"); + + const mode = screen.getByRole("combobox", "Destination", { exact: true }); + const thread = screen.getByRole("combobox", "Destination thread"); + const continuing = screen.getByRole("option", "One thread, continuing the conversation"); + const actions = screen.getByRole("button", "Actions for Recurring check"); + const edit = screen.getByRole("menuitem", "Edit"); + + await screen.getByRole("button", "New task").tap(); + await screen.getByRole("textbox", "Name").fill("Recurring check"); + await mode.tap(); + await continuing.tap(); + await thread.tap(); + await screen.getByRole("option", "Original conversation").tap(); + await screen.getByRole("textbox", "Prompt").fill("Check for updates"); + await screen.getByRole("button", "Create task").tap(); + + await actions.tap(); + await edit.tap(); + await mode.tap(); + await screen.getByRole("option", "New thread each run").tap(); + await mode.tap(); + await continuing.tap(); + await screen.getByRole("button", "Save task").tap(); + await actions.tap(); + await edit.tap(); + await app.screenshot("saved-destination"); + await expect(thread).toContainText("Started by the first run"); + }, +);