Skip to content
TypeScript

feat: scheduled tasks can run in one thread with a fresh session each run (#30326)

Julius Marminge4aab23cd72d7
diff --git a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
index 32f05c21020..888ad2fb1d7 100644
--- a/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+++ b/apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
@@ -11,6 +11,7 @@ import type {
EnvironmentId,
ProjectId,
ScheduledTask,
+ ScheduledTaskThreadMode,
ScheduledTaskUpsertInput,
} from "@t3tools/contracts";
import {
@@ -109,6 +110,12 @@ const DAYS = [
{ index: 0, label: "Sun" },
] as const;
+const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = {
+ new_thread: "New thread each run",
+ continue: "One thread, same conversation",
+ fresh_session: "One thread, fresh session",
+};
+
function describeSchedule(task: ScheduledTask): string {
if (task.schedule.type === "webhook") return "On webhook";
if (task.schedule.type === "once") {
@@ -722,6 +729,7 @@ function TaskForm({
const offersOnce =
config?.environment.capabilities.oneTimeSchedules === true ||
draft.task?.schedule.type === "once";
+ const offersThreadModes = config?.environment.capabilities.scheduledTaskThreadModes === true;
const save = async () => {
if (
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
@@ -795,6 +803,7 @@ function TaskForm({
schedule,
enabled: draft.enabled,
threadId: draft.task?.threadId ?? null,
+ ...(offersThreadModes ? { threadMode: draft.threadMode } : {}),
workspaceStrategy:
draft.workspace === "root"
? { type: "root" }
@@ -932,6 +941,37 @@ function TaskForm({
/>
</SettingsSection>
+ {offersThreadModes ? (
+ <SettingsSection
+ title="Destination"
+ footer={
+ draft.threadMode === "new_thread"
+ ? "Each run starts a new thread."
+ : `${
+ draft.threadMode === "continue"
+ ? "Runs continue one conversation."
+ : "Runs share one thread, each in a fresh session without earlier runs' context."
+ } The first run starts the thread. Deleting it also deletes this task.`
+ }
+ >
+ <SelectRow
+ label="Runs go to"
+ value={THREAD_MODE_LABELS[draft.threadMode]}
+ actions={(Object.keys(THREAD_MODE_LABELS) as ScheduledTaskThreadMode[]).map(
+ (mode) => ({
+ id: mode,
+ title: THREAD_MODE_LABELS[mode],
+ state: draft.threadMode === mode ? "on" : undefined,
+ }),
+ )}
+ onSelect={(id) => {
+ if (id === "new_thread" || id === "continue" || id === "fresh_session")
+ setDraft({ ...draft, threadMode: id });
+ }}
+ />
+ </SettingsSection>
+ ) : null}
+
<SettingsSection title="Workspace">
<SelectRow
label="Run in"
diff --git a/apps/mobile/src/features/settings/scheduledTaskDraft.ts b/apps/mobile/src/features/settings/scheduledTaskDraft.ts
index d89b004a0dc..3a7d9192998 100644
--- a/apps/mobile/src/features/settings/scheduledTaskDraft.ts
+++ b/apps/mobile/src/features/settings/scheduledTaskDraft.ts
@@ -1,10 +1,11 @@
-import { isWebhookDedupeTemplate } from "@t3tools/contracts";
+import { isWebhookDedupeTemplate, scheduledTaskThreadMode } from "@t3tools/contracts";
import type {
ModelSelection,
ServerConfig,
ProjectId,
RuntimeMode,
ScheduledTask,
+ ScheduledTaskThreadMode,
ScheduledTaskUpsertSchedule,
ScheduledTaskWebhookSignature,
} from "@t3tools/contracts";
@@ -204,6 +205,7 @@ export type ScheduledTaskDraft = {
readonly modelSelection: ModelSelection | null;
readonly modelSelectionIsExplicit: boolean;
readonly schedule: ScheduleDraft;
+ readonly threadMode: ScheduledTaskThreadMode;
readonly workspace: Workspace;
readonly baseRef: string;
readonly checkoutPath: string;
@@ -232,6 +234,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
draft.schedule.coalesceKey,
draft.schedule.coalesceWindowSeconds,
draft.schedule.filters.map(({ path, op, value }) => [path, op, value]),
+ draft.threadMode,
draft.workspace,
draft.baseRef,
draft.checkoutPath,
@@ -260,6 +263,7 @@ export function createDraft(
modelSelection,
modelSelectionIsExplicit: false,
schedule: DEFAULT_SCHEDULE,
+ threadMode: "new_thread",
workspace: "worktree",
baseRef: "main",
checkoutPath: "",
@@ -278,6 +282,7 @@ export function editDraft(task: ScheduledTask): ScheduledTaskDraft {
modelSelection: task.modelSelection,
modelSelectionIsExplicit: true,
schedule: scheduleDraftForTask(task),
+ threadMode: scheduledTaskThreadMode(task),
workspace: task.workspaceStrategy.type,
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
checkoutPath:
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 82010efdee8..12a05e48790 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -269,6 +269,7 @@ export const make = Effect.gen(function* () {
triage: true,
oneTimeSchedules: true,
freshContext: true,
+ scheduledTaskThreadModes: true,
npmReleaseLookup: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverInstallation === null ? {} : { serverInstallation }),
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts
index 0faf43acb9d..681f5ae3368 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts
@@ -13,6 +13,7 @@ import {
OrchestratorMcpTarget,
type OrchestrationV2ThreadShell,
type ScheduledTask,
+ type ScheduledTaskUpsertInput,
ScheduledTaskId,
ProjectId,
ProviderDriverKind,
@@ -2776,6 +2777,8 @@ describe("OrchestratorMcpService provider resolution", () => {
const service = (
git: Partial<GitVcsDriver.GitVcsDriver["Service"]>,
saved: Ref.Ref<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>,
+ task: ScheduledTask = existing,
+ modes?: Ref.Ref<ReadonlyArray<ScheduledTaskUpsertInput["threadMode"]>>,
) =>
OrchestratorMcpService.layer.pipe(
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -2784,7 +2787,9 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mergeAll(
NodeServices.layer,
NodeCrypto.layer,
- Layer.mock(ThreadManagementService.ThreadManagementService)({}),
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
+ getThreadShell: () => Effect.succeed(null),
+ }),
ServerSettings.layerTest(),
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
@@ -2801,10 +2806,15 @@ describe("OrchestratorMcpService provider resolution", () => {
Layer.mock(SecretRequests.SecretRequests)({}),
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
- list: () => Effect.succeed({ tasks: [existing] }),
+ list: () => Effect.succeed({ tasks: [task] }),
upsert: (input) =>
Ref.update(saved, (strategies) => [...strategies, input.workspaceStrategy]).pipe(
- Effect.as({ task: existing }),
+ Effect.andThen(
+ modes === undefined
+ ? Effect.void
+ : Ref.update(modes, (all) => [...all, input.threadMode]),
+ ),
+ Effect.as({ task }),
),
}),
),
@@ -2831,6 +2841,62 @@ describe("OrchestratorMcpService provider resolution", () => {
}),
);
+ it.effect("keeps one thread when fresh sessions are turned off before the first run", () =>
+ Effect.gen(function* () {
+ const modes = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput["threadMode"]>>([]);
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
+ Effect.provide(
+ service(
+ masterRepository,
+ yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]),
+ { ...existing, threadMode: "fresh_session" },
+ modes,
+ ),
+ ),
+ );
+ yield* mcp.updateScheduledTask(client, {
+ scheduledTaskId: existing.id,
+ freshSession: false,
+ });
+ yield* mcp.updateScheduledTask(client, {
+ scheduledTaskId: existing.id,
+ bindToCurrentThread: false,
+ });
+ assert.deepEqual(yield* Ref.get(modes), ["continue", "new_thread"]);
+ }),
+ );
+
+ it.effect(
+ "refuses unbinding into fresh sessions in one call, which would keep the thread",
+ () =>
+ Effect.gen(function* () {
+ const modes = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput["threadMode"]>>([]);
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
+ Effect.provide(
+ service(
+ masterRepository,
+ yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]),
+ {
+ ...existing,
+ threadId: ThreadId.make("thread:scheduled-base"),
+ threadMode: "continue",
+ },
+ modes,
+ ),
+ ),
+ );
+ 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(modes), []);
+ }),
+ );
+
it.effect("follows the default branch when a task is unbound from its thread", () =>
Effect.gen(function* () {
const saved = yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]);
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 36fe752eb8f..074b19fad3f 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -58,6 +58,7 @@ import {
type RuntimeMode,
type ScheduledTask,
type ScheduledTaskUpsertInput,
+ scheduledTaskThreadMode,
type ServerProvider,
type ServerProviderModel,
ThreadId,
@@ -266,6 +267,7 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato
enabled: task.enabled,
projectId: task.projectId,
boundThreadId: task.threadId,
+ freshSession: scheduledTaskThreadMode(task) === "fresh_session",
schedule: task.schedule,
nextRunAt: task.nextRunAt,
lastRunStatus: task.lastRunStatus,
@@ -2009,6 +2011,11 @@ const make = Effect.gen(function* () {
schedule: input.schedule,
projectId,
threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,
+ threadMode: input.freshSession
+ ? "fresh_session"
+ : bindToCurrentThread
+ ? "continue"
+ : "new_thread",
workspaceStrategy: yield* scheduledTaskWorkspaceStrategy(bindToCurrentThread, projectId),
modelSelection,
runtimeMode: limits.runtimeMode,
@@ -2071,6 +2078,18 @@ 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
@@ -2090,6 +2109,18 @@ const make = Effect.gen(function* () {
schedule: input.schedule ?? existing.schedule,
projectId: existing.projectId,
threadId,
+ threadMode:
+ input.freshSession === undefined && input.bindToCurrentThread === undefined
+ ? scheduledTaskThreadMode(existing)
+ : (input.freshSession ??
+ (input.bindToCurrentThread !== false &&
+ scheduledTaskThreadMode(existing) === "fresh_session"))
+ ? "fresh_session"
+ : threadId === null &&
+ (input.bindToCurrentThread === false ||
+ scheduledTaskThreadMode(existing) === "new_thread")
+ ? "new_thread"
+ : "continue",
workspaceStrategy,
modelSelection: existing.modelSelection,
runtimeMode: existing.runtimeMode,
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index 54ce798da42..83f77d00730 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -425,6 +425,8 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
}
const save = (name: string, target: ThreadId | null, webhook = false) =>
tasks.upsert({
+ // As schedule_task sends it, so clearing the thread unbinds the task.
+ threadMode: target === null ? "new_thread" : "continue",
id: ScheduledTaskId.make(`automation:${deletion}:${name}`),
title: name,
prompt: "Check orchestration progress",
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 606770d1b65..6a9c57e18cc 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -81,8 +81,8 @@ import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts";
import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts";
-
import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts";
+import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts";
const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -165,6 +165,7 @@ const migrationEntries = [
[77, "RepairBooleanSettledOverride", Migration0077],
[78, "DropOrchestrationEventCorrelationIndex", Migration0078],
[79, "DelegatedRecoveryIndexes", Migration0079],
+ [80, "ScheduledTaskThreadMode", Migration0080],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/080_ScheduledTaskThreadMode.ts b/apps/server/src/persistence/Migrations/080_ScheduledTaskThreadMode.ts
new file mode 100644
index 00000000000..01552b57fd1
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/080_ScheduledTaskThreadMode.ts
@@ -0,0 +1,9 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+
+ yield* sql`ALTER TABLE scheduled_tasks ADD COLUMN thread_mode TEXT NOT NULL DEFAULT 'new_thread'`;
+ yield* sql`UPDATE scheduled_tasks SET thread_mode = 'continue' WHERE thread_id IS NOT NULL`;
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index 5f51c237fd7..84fa4ddb44c 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -59,6 +59,7 @@ describe("V2 preview upgrade", () => {
[77, "RepairBooleanSettledOverride"],
[78, "DropOrchestrationEventCorrelationIndex"],
[79, "DelegatedRecoveryIndexes"],
+ [80, "ScheduledTaskThreadMode"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -161,6 +162,7 @@ describe("V2 preview upgrade", () => {
[77, "RepairBooleanSettledOverride"],
[78, "DropOrchestrationEventCorrelationIndex"],
[79, "DelegatedRecoveryIndexes"],
+ [80, "ScheduledTaskThreadMode"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index de57d486651..0a03b931fcc 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 5133,
"codexAdditionalContextBytes": 6863,
- "mcpToolListJsonBytes": 47642
+ "mcpToolListJsonBytes": 47818
}
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
index c7b0e31f4f0..71454e55a65 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
@@ -485,6 +485,203 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
);
+it.effect("a fresh-session task launches one thread, then starts each later run fresh in it", () =>
+ Effect.gen(function* () {
+ const launches = yield* Ref.make(0);
+ const sends = yield* Ref.make<Array<{ threadId: ThreadId; freshContext?: boolean }>>([]);
+ const launched = ThreadId.make("thread:fresh-session-task");
+ 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),
+ ),
+ }),
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
+ getThreadShell: () => Effect.succeed({ deletedAt: null } as never),
+ sendToThread: (input) =>
+ Ref.update(sends, (all) => [
+ ...all,
+ {
+ threadId: input.threadId,
+ ...(input.freshContext === undefined ? {} : { freshContext: input.freshContext }),
+ },
+ ]).pipe(Effect.as({} as never)),
+ }),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () => Effect.succeed(false),
+ }),
+ NodeCrypto.layer,
+ Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const input = {
+ id: ScheduledTaskId.make("task:fresh-session"),
+ title: "Triage",
+ prompt: "Triage new issues",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: ProjectId.make("project:test"),
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ } as const;
+ yield* service.upsert({ ...input, threadMode: "fresh_session" });
+
+ assert.equal((yield* service.runNow({ id: input.id })).threadId, launched);
+ // A form opened before the first run saves no thread; the binding stays.
+ const { task } = yield* service.upsert({
+ ...input,
+ threadId: null,
+ threadMode: "fresh_session",
+ });
+ assert.equal(task.threadId, launched);
+ assert.equal(task.threadMode, "fresh_session");
+ // A client that predates thread modes sends neither; both stay.
+ const legacy = yield* service.upsert({ ...input, threadId: null });
+ assert.equal(legacy.task.threadId, launched);
+ assert.equal(legacy.task.threadMode, "fresh_session");
+ yield* service.runNow({ id: input.id });
+
+ assert.equal(yield* Ref.get(launches), 1);
+ assert.deepEqual(yield* Ref.get(sends), [{ threadId: launched, freshContext: true }]);
+ // 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,
+ });
+ assert.equal(moved.task.threadId, null);
+ assert.equal(moved.task.threadMode, "fresh_session");
+ const unbound = yield* service.upsert({ ...input, threadMode: "new_thread" });
+ assert.equal(unbound.task.threadId, null);
+ }).pipe(Effect.provide(layer));
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
+);
+
+it.effect("a first run whose thread was deleted before it bound removes the task", () =>
+ Effect.gen(function* () {
+ const layer = ScheduledTaskService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ ManagedPolicy.layerTest(),
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
+ launch: () =>
+ Effect.succeed({
+ threadId: ThreadId.make("thread:deleted"),
+ resumed: false,
+ } as never),
+ }),
+ // Deleted before the binding landed, so its cleanup found no task to remove.
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
+ getThreadShell: () =>
+ Effect.succeed({ deletedAt: DateTime.makeUnsafe("2026-11-03T00:00:00Z") } as never),
+ }),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () => Effect.succeed(false),
+ }),
+ NodeCrypto.layer,
+ Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const { task } = yield* service.upsert({
+ id: ScheduledTaskId.make("task:thread-deleted-mid-launch"),
+ title: "Triage",
+ prompt: "Triage new issues",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: ProjectId.make("project:test"),
+ threadMode: "continue",
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ });
+ yield* service.runNow({ id: task.id });
+ assert.deepEqual((yield* service.list()).tasks, []);
+ }).pipe(Effect.provide(layer));
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
+);
+
+it.effect.each(["recreated under the same id", "moved to another project"] as const)(
+ "a first run never binds its thread to a task %s",
+ (change) =>
+ Effect.gen(function* () {
+ const launching = yield* Deferred.make<void>();
+ const proceed = yield* Deferred.make<void>();
+ const layer = ScheduledTaskService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ ManagedPolicy.layerTest(),
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
+ launch: () =>
+ Deferred.succeed(launching, undefined).pipe(
+ Effect.andThen(Deferred.await(proceed)),
+ Effect.as({
+ threadId: ThreadId.make("thread:old-generation"),
+ resumed: false,
+ } as never),
+ ),
+ }),
+ Layer.mock(ThreadManagementService.ThreadManagementService)({}),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () => Effect.succeed(false),
+ }),
+ NodeCrypto.layer,
+ Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const input = {
+ id: ScheduledTaskId.make("task:recreated-mid-launch"),
+ title: "Triage",
+ prompt: "Triage new issues",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: ProjectId.make("project:test"),
+ threadMode: "fresh_session",
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ } as const;
+ yield* service.upsert(input);
+ const run = yield* Effect.forkChild(service.runNow({ id: input.id }));
+ yield* Deferred.await(launching);
+ if (change === "recreated under the same id") {
+ yield* service.delete({ id: input.id });
+ yield* TestClock.adjust("1 second");
+ yield* service.upsert(input);
+ } else {
+ yield* service.upsert({ ...input, projectId: ProjectId.make("project:moved") });
+ }
+ yield* Deferred.succeed(proceed, undefined);
+ yield* Fiber.await(run);
+
+ const replacement = (yield* service.list()).tasks.find((task) => task.id === input.id);
+ assert.equal(replacement?.threadId, null);
+ }).pipe(Effect.provide(layer));
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
+);
+
it.effect("refuses saving an enabled task above the policy ceiling", () =>
Effect.gen(function* () {
const layer = ScheduledTaskService.layer.pipe(
@@ -534,19 +731,21 @@ it.effect("refuses saving an enabled task above the policy ceiling", () =>
.pipe(Effect.flip);
assert.equal(reenabled.message, "Example Corp limits threads to Auto-accept edits.");
// A task bound to a thread runs in that thread's mode, so its own is not checked.
- yield* service.upsert({
+ const bound = {
id: ScheduledTaskId.make("task:bound"),
title: "Follow up",
prompt: "Check progress",
enabled: true,
schedule: { type: "interval", everyMs: 60_000 },
projectId: ProjectId.make("project:test"),
- threadId: ThreadId.make("thread:bound"),
workspaceStrategy: { type: "root" },
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
- });
+ } as const;
+ yield* service.upsert({ ...bound, threadId: ThreadId.make("thread:bound") });
+ // Nor when an edit omits the thread it stays bound to.
+ yield* service.upsert(bound);
}).pipe(Effect.provide(layer));
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
);
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index 546d68c8ebe..9dd04b41c92 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -22,8 +22,10 @@ import {
type ScheduledTaskRunNowInput,
type ScheduledTaskRunNowResult,
type ScheduledTaskSetEnabledInput,
+ type ScheduledTaskThreadMode,
type ScheduledTaskUpsertInput,
managedPolicyDeniedMessage,
+ scheduledTaskThreadMode,
managedRuntimeModeDenial,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
@@ -191,6 +193,19 @@ const decodeMissingFieldsJson = Schema.decodeUnknownOption(MissingFieldsJson);
const encodeHeadersJson = Schema.encodeSync(HeadersJson);
const encodeMissingFieldsJson = Schema.encodeSync(MissingFieldsJson);
+/**
+ * Clients that predate thread modes send none, and may send a thread loaded before the first run
+ * bound one. An edit keeps the stored mode; binding a thread to a new-thread task continues it.
+ */
+function resolveThreadMode(
+ input: Pick<ScheduledTaskUpsertInput, "threadId" | "threadMode">,
+ existing: Pick<ScheduledTask, "threadId" | "threadMode"> | null,
+): ScheduledTaskThreadMode {
+ if (input.threadMode !== undefined) return input.threadMode;
+ const stored = existing === null ? "new_thread" : scheduledTaskThreadMode(existing);
+ return stored === "new_thread" && input.threadId != null ? "continue" : stored;
+}
+
interface ScheduledTaskRow {
readonly task_id: string;
readonly title: string;
@@ -199,6 +214,7 @@ interface ScheduledTaskRow {
readonly schedule_json: string;
readonly project_id: string;
readonly thread_id: string | null;
+ readonly thread_mode: string;
readonly workspace_strategy_json: string;
readonly model_selection_json: string;
readonly runtime_mode: string;
@@ -372,6 +388,7 @@ const decodeRow = Effect.fnUntraced(
schedule,
projectId: row.project_id,
threadId: row.thread_id,
+ threadMode: row.thread_mode,
workspaceStrategy,
modelSelection,
runtimeMode: row.runtime_mode,
@@ -494,6 +511,7 @@ export const layer = Layer.effect(
schedule_json,
project_id,
thread_id,
+ thread_mode,
workspace_strategy_json,
model_selection_json,
runtime_mode,
@@ -535,6 +553,7 @@ export const layer = Layer.effect(
schedule_json,
project_id,
thread_id,
+ thread_mode,
workspace_strategy_json,
model_selection_json,
runtime_mode,
@@ -612,6 +631,7 @@ export const layer = Layer.effect(
schedule_json,
project_id,
thread_id,
+ thread_mode,
workspace_strategy_json,
model_selection_json,
runtime_mode,
@@ -636,6 +656,7 @@ export const layer = Layer.effect(
${JSON.stringify(task.schedule)},
${task.projectId},
${task.threadId},
+ ${scheduledTaskThreadMode(task)},
${JSON.stringify(task.workspaceStrategy)},
${JSON.stringify(task.modelSelection)},
${task.runtimeMode},
@@ -660,7 +681,14 @@ export const layer = Layer.effect(
enabled = excluded.enabled,
schedule_json = excluded.schedule_json,
project_id = excluded.project_id,
- thread_id = excluded.thread_id,
+ -- A first run may bind the thread while this save is in flight; only a
+ -- switch to new threads unbinds.
+ thread_id = CASE
+ WHEN excluded.thread_mode = 'new_thread' THEN NULL
+ WHEN excluded.project_id != scheduled_tasks.project_id THEN excluded.thread_id
+ ELSE COALESCE(excluded.thread_id, scheduled_tasks.thread_id)
+ END,
+ thread_mode = excluded.thread_mode,
workspace_strategy_json = excluded.workspace_strategy_json,
model_selection_json = excluded.model_selection_json,
runtime_mode = excluded.runtime_mode,
@@ -798,6 +826,25 @@ export const layer = Layer.effect(
),
);
+ // The run already started the thread, so a failed write only costs the binding.
+ // A thread deleted before the binding landed already ran its task cleanup, so apply that
+ // cleanup here; a later deletion finds the binding. An unconfirmed lookup keeps the binding.
+ const bindThread = Effect.fn("ScheduledTaskService.bindThread")(
+ function* (task: ScheduledTask, threadId: ThreadId) {
+ yield* sql`
+ UPDATE scheduled_tasks SET thread_id = ${threadId}
+ WHERE task_id = ${task.id} AND created_at = ${task.createdAt}
+ AND project_id = ${task.projectId}
+ AND thread_id IS NULL AND thread_mode != 'new_thread'
+ `;
+ const shell = yield* threadManagement.getThreadShell(threadId);
+ if (shell === null || shell.deletedAt != null) yield* deleteForThread(threadId);
+ },
+ Effect.catchCause((cause) =>
+ Effect.logWarning("Could not bind a scheduled task to its first thread.", cause),
+ ),
+ );
+
const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
task: ScheduledTask,
trigger: "scheduled" | "manual" | "webhook",
@@ -885,6 +932,7 @@ export const layer = Layer.effect(
const commandId = CommandId.make(`scheduled-task:${fireKey}`);
const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
const prompt = webhook?.prompt ?? active.prompt;
+ const threadMode = scheduledTaskThreadMode(active);
// A bound thread can move to another project (No project to a project) while
// this fires. Follow it; one move needs at most two retries. Same ids replay safely.
@@ -903,6 +951,7 @@ export const layer = Layer.effect(
text: prompt,
attachments: [],
mode: "queue",
+ ...(threadMode === "fresh_session" ? { freshContext: true } : {}),
createdBy: active.createdBy,
creationSource: active.creationSource,
})
@@ -944,7 +993,12 @@ export const layer = Layer.effect(
createdBy: active.createdBy,
creationSource: active.creationSource,
})
- .pipe(Effect.map((launched) => launched.threadId)),
+ .pipe(
+ Effect.map((launched) => launched.threadId),
+ Effect.tap((threadId) =>
+ threadMode === "new_thread" ? Effect.void : bindThread(active, threadId),
+ ),
+ ),
)
: yield* Effect.exit(
// The stored selection only seeds fresh threads. A bound run
@@ -1209,16 +1263,6 @@ export const layer = Layer.effect(
input.id === undefined ? {} : { taskId: input.id },
);
}
- // Refused on save rather than at run time; a disabled task can still be saved, so one
- // stored above the ceiling can be turned off before its mode is lowered. A task bound to a
- // thread runs in that thread's mode, which the orchestrator checks instead.
- const modeDenial =
- input.enabled && input.threadId == null
- ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)
- : undefined;
- if (modeDenial !== undefined) {
- return yield* taskError(modeDenial, input.id === undefined ? {} : { taskId: input.id });
- }
const now = yield* localNow;
const uuid =
input.commandId === undefined
@@ -1239,6 +1283,23 @@ export const layer = Layer.effect(
// keep their run history, and so real load failures propagate instead
// of silently resetting an existing row.
const existingTask = yield* findTask(id);
+ const threadMode = resolveThreadMode(input, existingTask);
+ const keptThreadId = input.threadId ?? existingTask?.threadId ?? null;
+ // A bound thread belongs to its project, so moving the task leaves it for a new one.
+ const movedOffThread =
+ existingTask !== null &&
+ existingTask.projectId !== input.projectId &&
+ keptThreadId === existingTask.threadId;
+ const threadId = threadMode === "new_thread" || movedOffThread ? null : keptThreadId;
+ // Refused on save rather than at run time; a disabled task can still be saved, so one
+ // stored above the ceiling can be turned off before its mode is lowered. A task bound to a
+ // thread runs in that thread's mode, which the orchestrator checks instead. Checked before
+ // the save consumes a webhook secret.
+ const modeDenial =
+ input.enabled && threadId === null
+ ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)
+ : undefined;
+ if (modeDenial !== undefined) return yield* taskError(modeDenial, { taskId: id });
// Keep the existing next_run_at when the schedule itself is untouched:
// editing a title or prompt must not postpone (or resurrect) a due
// run — only schedule/enabled changes restart the clock.
@@ -1327,7 +1388,8 @@ export const layer = Layer.effect(
enabled: input.enabled,
schedule,
projectId: input.projectId,
- threadId: input.threadId ?? null,
+ threadId,
+ threadMode,
workspaceStrategy,
modelSelection: input.modelSelection,
runtimeMode: input.runtimeMode,
diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
index 1c65371cfbd..fbff362b78e 100644
--- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx
+++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx
@@ -20,6 +20,7 @@ import type {
ScheduledTask,
ScheduledTaskId,
ScheduledTaskSchedule,
+ ScheduledTaskThreadMode,
ScheduledTaskUpsertInput,
ScheduledTaskWebhookDeliverySummary,
ThreadId,
@@ -149,6 +150,7 @@ const EMPTY_DRAFT: DraftState = {
weekdays: new Set([1, 2, 3, 4, 5]),
projectId: "",
threadId: "",
+ threadMode: "new_thread",
workspaceMode: "worktree",
baseRef: "main",
startFromOrigin: true,
@@ -1141,12 +1143,23 @@ function ScheduledTaskEditorDialog({
);
}
+const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = {
+ new_thread: "New thread each run",
+ continue: "One thread, continuing the conversation",
+ fresh_session: "One thread, fresh session each run",
+};
+
function ScheduledTaskDestination({
environmentId,
threadId,
+ threadMode,
+ onThreadModeChange,
}: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId | null;
+ readonly threadMode: ScheduledTaskThreadMode;
+ /** Absent on servers that predate thread modes. */
+ readonly onThreadModeChange: ((mode: ScheduledTaskThreadMode) => void) | undefined;
}) {
const ref = threadId === null ? null : scopeThreadRef(environmentId, threadId);
const shell = useThreadShell(ref);
@@ -1155,20 +1168,45 @@ function ScheduledTaskDestination({
ref !== null && shell === null ? threadFamilies.familyAtom(environmentId, ref.threadId) : null,
);
const thread = shell ?? family.data?.threads.find((row) => row.id === threadId);
+ const bound = ref !== null && threadMode !== "new_thread";
+ const detail =
+ threadMode === "new_thread"
+ ? "Each run starts a new thread with the workspace and model below."
+ : !bound
+ ? threadMode === "continue"
+ ? "The first run starts a thread with the workspace and model below. Later runs continue that conversation."
+ : "The first run starts a thread with the workspace and model below. Later runs post there, each in a fresh session without earlier runs' context."
+ : threadMode === "continue"
+ ? "Each run continues this conversation, in its workspace and with its current model."
+ : "Each run starts a fresh session in this thread, without earlier runs' context.";
return (
- <Field label="Destination">
- {ref === null ? (
- <p className="text-sm text-muted-foreground">
- Each run starts a new thread with the workspace and model below.
- </p>
- ) : (
- <div className="space-y-1 text-sm">
+ <Field label="Destination" htmlFor="scheduled-task-destination">
+ {onThreadModeChange ? (
+ <Select
+ value={threadMode}
+ onValueChange={(value) => onThreadModeChange(value as ScheduledTaskThreadMode)}
+ >
+ <SelectTrigger size="sm" id="scheduled-task-destination">
+ <SelectValue>{THREAD_MODE_LABELS[threadMode]}</SelectValue>
+ </SelectTrigger>
+ <SelectPopup>
+ {(Object.keys(THREAD_MODE_LABELS) as ScheduledTaskThreadMode[]).map((mode) => (
+ <SelectItem key={mode} value={mode}>
+ {THREAD_MODE_LABELS[mode]}
+ </SelectItem>
+ ))}
+ </SelectPopup>
+ </Select>
+ ) : null}
+ <div className="space-y-1 text-sm">
+ {bound ? (
<p className="wrap-anywhere">{thread?.title.trim() || `Thread ${ref.threadId}`}</p>
- <p className="text-muted-foreground">
- Each run continues this conversation, in its workspace and with its current model.
- </p>
- </div>
- )}
+ ) : null}
+ <p className="text-muted-foreground">{detail}</p>
+ {threadMode !== "new_thread" ? (
+ <p className="text-muted-foreground">Deleting the thread also deletes this task.</p>
+ ) : null}
+ </div>
</Field>
);
}
@@ -1193,6 +1231,8 @@ function ScheduledTaskEditorForm({
const offersOnce =
environment?.serverConfig?.environment.capabilities.oneTimeSchedules === true ||
task?.schedule.type === "once";
+ const offersThreadModes =
+ environment?.serverConfig?.environment.capabilities.scheduledTaskThreadModes === true;
const connected =
environment?.connection.phase === "connected" && environment.serverConfig !== null;
const tasksQuery = useEnvironmentQuery(
@@ -1356,6 +1396,7 @@ function ScheduledTaskEditorForm({
schedule,
projectId: selectedProjectId as ProjectId,
threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
+ ...(offersThreadModes ? { threadMode: draft.threadMode } : {}),
workspaceStrategy,
modelSelection,
// Tasks have no mode picker; a mode above the administrator's ceiling would fail every run.
@@ -1482,6 +1523,12 @@ function ScheduledTaskEditorForm({
<ScheduledTaskDestination
environmentId={environmentId}
threadId={draft.threadId ? (draft.threadId as ThreadId) : null}
+ threadMode={draft.threadMode}
+ onThreadModeChange={
+ offersThreadModes
+ ? (threadMode) => setDraft((current) => ({ ...current, threadMode }))
+ : undefined
+ }
/>
<div className="grid gap-3 sm:grid-cols-2">
diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts
index 9e0d0dad27c..522554e1cce 100644
--- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts
@@ -5,7 +5,9 @@ import {
type ProjectId,
ScheduledTaskId,
type ScheduledTask,
+ type ScheduledTaskThreadMode,
type ScheduledTaskUpsertSchedule,
+ scheduledTaskThreadMode,
type ModelSelection,
type RuntimeMode,
type ProviderInteractionMode,
@@ -70,6 +72,7 @@ export interface DraftState {
readonly weekdays: ReadonlySet<number>;
readonly projectId: string;
readonly threadId: string;
+ readonly threadMode: ScheduledTaskThreadMode;
readonly workspaceMode: WorkspaceMode;
readonly baseRef: string;
readonly startFromOrigin: boolean;
@@ -254,6 +257,7 @@ export function taskToDraft(task: ScheduledTask): DraftState {
weekdays,
projectId: task.projectId,
threadId: task.threadId ?? "",
+ threadMode: scheduledTaskThreadMode(task),
workspaceMode: task.workspaceStrategy.type,
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
startFromOrigin:
diff --git a/docs/user/project-settings.md b/docs/user/project-settings.md
index ba481be9f5b..671ea14eb3f 100644
--- a/docs/user/project-settings.md
+++ b/docs/user/project-settings.md
@@ -86,6 +86,13 @@ environment's time zone, which may differ from your phone's. Choose **Once**
to run a task a single time at a date and time in your own time zone. If the
environment is offline then, the task runs when it is back.
+Under **Destination**, choose where runs go. **New thread each run** keeps every
+run separate. The two one-thread choices start a thread on the first run and post
+later runs there: one continues the same conversation, the other starts each run
+in a fresh session that doesn't see earlier runs, so the thread stays readable
+without the agent's context growing. Moving such a task to another project starts
+a new thread there on its next run.
+
Deleting a thread also deletes tasks that post into that thread. Tasks that start
a new thread on each run survive deletion of their previous threads.
diff --git a/evals/mcp-tool-use/cases/pull-requests.ndjson b/evals/mcp-tool-use/cases/pull-requests.ndjson
index 997243d873a..e0c71442200 100644
--- a/evals/mcp-tool-use/cases/pull-requests.ndjson
+++ b/evals/mcp-tool-use/cases/pull-requests.ndjson
@@ -21,7 +21,7 @@
{"id": "stack-links-every-layer", "area": "pull-requests", "kind": "guard", "pattern": "stacked PRs: every layer ends up linked", "experience": "Must keep working: for a 2-PR stack, both layers end up linked, not only the top.", "rule": "For a stack, call it for every layer, not just the current branch or the top PR.", "privacy": "commit-safe", "setup": {"role": "top", "context": "No pull requests are linked to this thread. Branch feature/error-detail (on main) and branch feature/frozen-host (on top of feature/error-detail) are committed locally. Nothing is pushed yet.", "mocks": {"link_pull_request": "default"}, "world": {"branch": "feature/frozen-host", "branches": {"feature/error-detail": "e1d2c3b"}, "commits": [{"sha": "f7e6d5c", "subject": "feat(server): detect a frozen host and say so"}, {"sha": "e1d2c3b", "subject": "feat(server): include the failing step in connection errors"}], "nextPullRequests": "The next pull request created on acme/app is #124, and the one after it is #125."}, "shellMocks": [{"match": "gh pr create.*(--base|-B)[= ]['\"]?main\\b", "output": "https://github.com/acme/app/pull/124"}, {"match": "gh pr create.*(--base|-B)[= ]['\"]?feature/error-detail\\b", "output": "https://github.com/acme/app/pull/125"}]}, "prompt": "Open both as stacked PRs: feature/error-detail against main, and feature/frozen-host on top of it.", "expect": {"linked": ["~/pull/124", "~/pull/125"]}, "notes": "No real 'only the top layer linked' miss exists after v2 (checked all stacked creates since Oct 2). The real run used watch because of 'Full stop'. Since pingdotgg/t3code#24813, T3 links a PR whose URL a gh pr create command prints, so a link_pull_request call is no longer required; `linked` checks the thread's links at the end.", "maxSteps": 10}
{"id": "takeover-links-pr", "area": "pull-requests", "kind": "guard", "pattern": "takeover of a pasted PR links it", "experience": "Must keep working: on 'take over this PR and get it in', link the pasted PR before working on it.", "rule": "register every pull request you create or work on for this thread", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"link_pull_request": "default", "watch_pull_request": "default"}, "context": "This worktree has the PR's branch fix/config-snapshot checked out.", "world": {"branch": "fix/config-snapshot", "commits": [{"sha": "abc1234", "subject": "fix(server): stream config snapshots so slow ones keep the socket alive"}], "diff": "diff --git a/apps/server/src/config/snapshot.ts b/apps/server/src/config/snapshot.ts\n--- a/apps/server/src/config/snapshot.ts\n+++ b/apps/server/src/config/snapshot.ts\n@@ -1,6 +1,8 @@\n-import { buildSnapshot, streamSnapshot } from './build';\n+import { streamSnapshot } from './build';\n \n export async function sendSnapshot(socket: Socket, config: Config) {\n- const snapshot = await buildSnapshot(config);\n- socket.send(snapshot);\n+ // Send in chunks so a slow snapshot never blocks the heartbeat.\n+ for await (const chunk of streamSnapshot(config)) {\n+ socket.send(chunk);\n+ }\n }\n", "files": {"apps/server/src/config/snapshot.ts": "import { streamSnapshot } from './build';\n\nexport async function sendSnapshot(socket: Socket, config: Config) {\n // Send in chunks so a slow snapshot never blocks the heartbeat.\n for await (const chunk of streamSnapshot(config)) {\n socket.send(chunk);\n }\n}\n", "apps/server/src/config/build.ts": "export async function buildSnapshot(config: Config) {\n return JSON.stringify(config);\n}\n\nexport async function* streamSnapshot(config: Config) {\n for (const [key, value] of Object.entries(config)) yield JSON.stringify({ key, value });\n}\n"}, "prs": [{"number": 123, "title": "fix(server): slow config snapshots no longer drop connections", "headRefName": "fix/config-snapshot", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Check", "state": "pending"}, {"name": "Test Web", "state": "pending"}], "author": {"login": "contributor"}}]}}, "prompt": "https://github.com/acme/app/pull/123\n\nThis looks legit. Take over and get it in.", "expect": {"calls": [{"tool": "link_pull_request|watch_pull_request", "args": {"url": "~/pull/123"}}]}, "notes": "A run that calls watch_pull_request first (which also links) would fail this check. If the runner treats watch as a link, relax it.", "maxSteps": 14}
{"id": "handback-unwatches", "area": "pull-requests", "kind": "guard", "pattern": "unwatch before handing back", "experience": "Must keep working: when the babysit goal is met and the user merges, call unwatch_pull_request before the hand-back reply.", "rule": "When monitoring is done and you hand the work back to the user, call unwatch_pull_request first", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Make CI setup survive npm registry outages, then open a PR. You are done when CI on the PR is green. I will merge it myself."}, {"role": "assistant", "text": "Opened [#124](https://github.com/acme/app/pull/124). T3 Code is watching it; I will report when CI is green.", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/.github/workflows/ci.yml", "old_string": " - run: pnpm install", "new_string": " - run: pnpm install || pnpm install --registry https://registry.npmmirror.com"}, "result": "The file /home/user/.t3/worktrees/t3code/t3-f8cdd940/.github/workflows/ci.yml has been updated successfully."}, {"tool": "Bash", "input": {"command": "git add -A && git commit -m \"ci: fall back to the registry mirror when npm is down\""}, "result": "[ci/npm-outage abc1234] ci: fall back to the registry mirror when npm is down\n 1 file changed"}, {"tool": "Bash", "input": {"command": "git push -u origin ci/npm-outage"}, "result": "To github.com:acme/app.git\n * [new branch] ci/npm-outage -> ci/npm-outage\nbranch 'ci/npm-outage' set up to track 'origin/ci/npm-outage'."}, {"tool": "Bash", "input": {"command": "gh pr create --base main --title \"ci: fall back to the registry mirror when npm is down\" --fill"}, "result": "https://github.com/acme/app/pull/124"}, {"tool": "link_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "alreadyLinked": false}}, {"tool": "watch_pull_request", "input": {"url": "https://github.com/acme/app/pull/124"}, "result": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "watching": true, "wasWatching": false}}]}], "mocks": {"unwatch_pull_request": "default"}, "world": {"branch": "ci/npm-outage", "commits": [{"sha": "abc1234", "subject": "ci: fall back to the registry mirror when npm is down"}], "diff": "diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml\n--- a/.github/workflows/ci.yml\n+++ b/.github/workflows/ci.yml\n@@ -8,1 +8,1 @@\n- - run: pnpm install\n+ - run: pnpm install || pnpm install --registry https://registry.npmmirror.com\n", "prs": [{"number": 124, "title": "ci: fall back to the registry mirror when npm is down", "headRefName": "ci/npm-outage", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Typecheck", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Update on pull request #124 (https://github.com/acme/app/pull/124), which T3 Code is watching for you:\n- All 12 checks passed on abc1234.\n\nLook into each item and act on it as your task requires. This PR stays linked and watched, so do not link, watch, or list it again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request first so the thread returns to their inbox.", "expect": {"calls": [{"tool": "unwatch_pull_request", "args": {"url": "~/pull/124"}}], "notCalls": ["watch_pull_request"], "shellMustNot": ["gh pr merge"]}, "notes": "Unwatch was followed 7 of 7 times after the fixes. No real 'forgot to unwatch' miss was found, so this is a guard, not a bad case.", "maxSteps": 7}
-{"id": "schedule-one-off-tomorrow", "area": "pull-requests", "kind": "guard", "pattern": "schedule asked: schedule_task, not the job", "experience": "Must keep working: a schedule ask creates a schedule_task with an object schedule and reports the next run, without running the check now.", "rule": "schedule_task creates persistent recurring work in the app scheduler. Pass schedule as a structured object / After scheduling a timer, report the returned cadence and next run time", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Saturday 2026-10-24, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Check app for memory leaks", "schedule": {"type": "once", "runAt": "2026-10-25T23:00:00-07:00"}, "enabled": true, "bindToCurrentThread": true, "nextRunAt": "2026-10-25T23:00:00-07:00"}}, "shellMocks": [{"match": "\\bdate\\b", "output": "Saturday 2026-10-24 10:00 PDT"}]}, "prompt": "Definitely want to schedule something to check the app for memory leaks at some point tomorrow, maybe like 11pm?", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "once"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"], "textMust": ["(11(:00)? ?[Pp]\\.?[Mm]|23:00)"]}, "notes": "A one-off time uses a once schedule. Before once existed, a weekly fixed_time plus a later delete was accepted."}
+{"id": "schedule-one-off-tomorrow", "area": "pull-requests", "kind": "guard", "pattern": "schedule asked: schedule_task, not the job", "experience": "Must keep working: a schedule ask creates a schedule_task with an object schedule and reports the next run, without running the check now.", "rule": "schedule_task creates persistent recurring work in the app scheduler. Pass schedule as a structured object / After scheduling a timer, report the returned cadence and next run time", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Saturday 2026-10-24, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Check app for memory leaks", "schedule": {"type": "once", "runAt": "2026-10-25T23:00:00-07:00"}, "enabled": true, "bindToCurrentThread": true, "nextRunAt": "2026-10-25T23:00:00-07:00"}}, "shellMocks": [{"match": "\\bdate\\b", "output": "Saturday 2026-10-24 10:00 PDT"}]}, "prompt": "Definitely want to schedule something to check the app for memory leaks at some point tomorrow, maybe like 11pm?", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "once"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"], "textMust": ["(11(:00)? ?[Pp]\\.?[Mm]|23:00)"], "callsMustNot": [{"tool": "schedule_task", "args": {"freshSession": true}}]}, "notes": "A one-off time uses a once schedule. Before once existed, a weekly fixed_time plus a later delete was accepted."}
{"id": "control-pr-lookup-question", "area": "pull-requests", "kind": "control", "pattern": "PRs named only as background in a question", "experience": "Asking about PRs must not link, watch, or list them.", "rule": "Do not link unrelated PRs mentioned only as background.", "privacy": "commit-safe", "setup": {"role": "top", "world": {"prs": [{"number": 101, "title": "fix(web): small UI fix", "state": "MERGED", "diff": "diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx\n--- a/apps/web/src/components/Sidebar.tsx\n+++ b/apps/web/src/components/Sidebar.tsx\n@@ -10,1 +10,1 @@\n- <span>{title}</span>\n+ <span className=\"truncate\">{title}</span>\n"}, {"number": 102, "title": "fix(ws): cap reconnect backoff at 30s", "state": "MERGED", "diff": "diff --git a/apps/web/src/ws/backoff.ts b/apps/web/src/ws/backoff.ts\n--- a/apps/web/src/ws/backoff.ts\n+++ b/apps/web/src/ws/backoff.ts\n@@ -4,1 +4,1 @@\n- return Math.min(base * 2 ** attempt, 60_000);\n+ return Math.min(base * 2 ** attempt, 30_000);\n"}, {"number": 103, "title": "chore: update dependencies", "state": "MERGED", "diff": "diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml\n--- a/pnpm-lock.yaml\n+++ b/pnpm-lock.yaml\n@@ -120,1 +120,1 @@\n- vitest: 4.0.1\n+ vitest: 4.0.3\n"}]}}, "prompt": "Did any of #101, #102, or #103 touch the reconnect backoff logic?", "expect": {"notCalls": ["link_pull_request", "link_pull_requests", "watch_pull_request", "list_thread_pull_requests", "unlink_pull_request"]}, "notes": ""}
{"id": "control-link-means-url", "area": "pull-requests", "kind": "control", "pattern": "'link the PR' means show the URL", "experience": "'Link the PR that did this' about a merged culprit PR means give the URL in the reply, not link_pull_request.", "rule": "Do not link unrelated PRs mentioned only as background.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Why isn't the new thread selector grouping projects anymore?"}, {"role": "assistant", "text": "#120, merged yesterday, removed the grouping step when it moved the selector to the new list component.", "toolCalls": [{"tool": "Bash", "input": {"command": "git log --oneline -S groupByProject -- apps/web/src/ThreadSelector.tsx"}, "result": "8e1f2a3 refactor(web): move thread selector to the shared list (#120)"}, {"tool": "Bash", "input": {"command": "git show 8e1f2a3 --stat"}, "result": "commit 8e1f2a3\n\n refactor(web): move thread selector to the shared list (#120)\n\n apps/web/src/ThreadSelector.tsx | 14 ++------------"}]}], "world": {"prs": [{"number": 120, "title": "refactor(web): move thread selector to the shared list", "state": "MERGED", "headRefName": "refactor/selector"}]}}, "prompt": "Link the pr that did this", "expect": {"notCalls": ["link_pull_request", "link_pull_requests", "watch_pull_request"], "textMust": ["github\\.com/acme/app/pull/120"]}, "notes": "Least certain control: 'link' is ambiguous. The user's next message was 'File revert pr', which shows he wanted to see it, not track it."}
{"id": "control-nightly-time-question", "area": "pull-requests", "kind": "control", "pattern": "question about a CI schedule is not a schedule ask", "experience": "'When does the next nightly go out?' is answered from the workflow file, with no scheduler tools.", "rule": "none", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Saturday 2026-10-24, 10:00 local time (UTC-7).", "shellMocks": [{"match": "^date\\b", "output": "Sat Oct 24 10:00:00 PDT 2026"}, {"match": "gh run list", "output": "completed\tsuccess\tnightly\tmain\tschedule\t991\t21m\t2026-10-24T09:00:00Z"}], "world": {"files": {".github/workflows/nightly.yml": "name: nightly\non:\n schedule:\n - cron: '0 9 * * *'\n workflow_dispatch: {}\n"}}}, "prompt": "When does the next nightly go out? Want to start testing this asap", "expect": {"notCalls": ["schedule_task", "list_scheduled_tasks", "run_scheduled_task_now"]}, "notes": ""}
@@ -35,3 +35,4 @@
{"id": "link-pasted-prs", "area": "pull-requests", "privacy": "commit-safe", "kind": "bad", "pattern": "links many PRs one call at a time", "experience": "Given a list of PR URLs to link, the agent linked them one call each.", "rule": "link_pull_request takes one PR per call", "setup": {"role": "top", "context": "No pull requests are linked to this thread.", "world": {"repo": "acme/app", "branch": "main"}}, "prompt": "link these here so i can track them:\nhttps://github.com/acme/app/pull/301\nhttps://github.com/acme/app/pull/302\nhttps://github.com/acme/app/pull/303\nhttps://github.com/acme/app/pull/304\nhttps://github.com/acme/app/pull/305\nhttps://github.com/acme/app/pull/306\nhttps://github.com/acme/app/pull/307\nhttps://github.com/acme/app/pull/308\nhttps://github.com/acme/app/pull/309\nhttps://github.com/acme/app/pull/310\nhttps://github.com/acme/app/pull/311\nhttps://github.com/acme/app/pull/312", "expect": {"calls": [{"tool": "link_pull_requests"}], "linked": ["~/pull/301", "~/pull/302", "~/pull/303", "~/pull/304", "~/pull/305", "~/pull/306", "~/pull/307", "~/pull/308", "~/pull/309", "~/pull/310", "~/pull/311", "~/pull/312"], "maxCalls": {"link_pull_requests": 1, "link_pull_request": 0}}, "maxSteps": 10, "source": {"thread": "Maintainer thread, 2026-10-05: 'can you link all of the stacked prs into this thread?' The agent linked 14 PRs one call each; another run linked 58."}}
{"id": "link-one-pr", "area": "pull-requests", "privacy": "commit-safe", "kind": "control", "pattern": "single link stays single", "experience": "Linking one named PR is ordinary work.", "setup": {"role": "top", "context": "No pull requests are linked to this thread.", "world": {"repo": "acme/app", "branch": "main"}}, "prompt": "link https://github.com/acme/app/pull/130 here", "expect": {"calls": [{"tool": "link_pull_request", "args": {"url": "~/pull/130"}}], "notCalls": ["link_pull_requests"]}, "maxSteps": 6, "source": {"thread": "Synthetic control for batch link"}}
{"id": "schedule-one-time-date", "area": "pull-requests", "kind": "bad", "pattern": "one-off date scheduled as a daily task", "experience": "Theo asked whether a scheduled task can run at a specific date and time. schedule_task only had daily times, intervals, and webhooks, so a one-off request became a daily task.", "source": {"report": "maintainer request, 2026-10-31: scheduled tasks could not run at one date and time"}, "rule": "schedule: {type:'once',runAt} for one date and time", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-4", "title": "Cut 2.0 release branch", "schedule": {"type": "once", "runAt": "2026-11-03T09:00:00.000Z"}, "enabled": true, "nextRunAt": "2026-11-03T09:00:00.000Z"}}}, "prompt": "On November 3rd at 9am UTC, start a new thread that cuts the 2.0 release branch from main in acme/app. Only that one time.", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "once", "schedule.runAt": "~11-03T09:00"}}], "notCalls": ["delegate_task", "run_scheduled_task_now"]}, "notes": "Mock result shape is an approximation."}
+{"id": "schedule-fresh-session-per-run", "area": "pull-requests", "kind": "guard", "pattern": "recurring task that should not accumulate context", "experience": "A recurring triage task kept one thread so the user could read its history, but each run carried every earlier run's context into the next.", "rule": "schedule_task `freshSession: true` keeps runs in one thread while each run starts a fresh session.", "privacy": "commit-safe", "setup": {"role": "top", "context": "Today is Monday 2026-11-02, 10:00 local time.", "mocks": {"schedule_task": {"scheduledTaskId": "scheduled-task-7", "title": "Triage new issues", "enabled": true, "projectId": "project-1", "boundThreadId": null, "freshSession": true, "schedule": {"type": "fixed_time", "timeOfDay": "09:00"}, "nextRunAt": "2026-11-03T09:00:00-08:00", "lastRunStatus": "never"}}}, "prompt": "Every morning at 9, triage new issues in acme/app. Keep all the runs in one thread so I can scroll back, but each run should start clean without remembering the previous days.", "expect": {"calls": [{"tool": "schedule_task", "args": {"schedule.type": "fixed_time", "freshSession": true}}], "notCalls": ["delegate_task", "run_scheduled_task_now"]}, "source": {"request": "juliusmarminge (maintainer) request, 2026-11-03: automations in one thread with separate provider sessions"}, "notes": "schedule-one-off-tomorrow is the control: an ordinary schedule must not set freshSession."}
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index e7a34dfe675..799802bc1c1 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -170,6 +170,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
oneTimeSchedules: Schema.optionalKey(Schema.Boolean),
/** Server honors `freshContext` on sends; older servers ignore it and keep the old context. */
freshContext: Schema.optionalKey(Schema.Boolean),
+ /** Server saves and runs scheduled task `threadMode`; older servers ignore it. */
+ scheduledTaskThreadModes: Schema.optionalKey(Schema.Boolean),
});
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts
index 17f41e9f8d1..c73bbd48e26 100644
--- a/packages/contracts/src/orchestratorMcp.ts
+++ b/packages/contracts/src/orchestratorMcp.ts
@@ -667,6 +667,12 @@ export const OrchestratorMcpScheduleTaskInput = Schema.Struct({
description: "Default true: runs post in this thread. False: new thread per run.",
}),
),
+ freshSession: Schema.optional(
+ Schema.Boolean.annotate({
+ description:
+ "Runs share one thread but each starts a fresh session without earlier runs' context. Unbound: the first run makes the thread.",
+ }),
+ ),
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
});
export type OrchestratorMcpScheduleTaskInput = typeof OrchestratorMcpScheduleTaskInput.Type;
@@ -688,6 +694,7 @@ export const OrchestratorMcpScheduledTask = Schema.Struct({
enabled: Schema.Boolean,
projectId: ProjectId,
boundThreadId: Schema.NullOr(ThreadId),
+ freshSession: Schema.Boolean,
schedule: ScheduledTaskSchedule,
nextRunAt: Schema.NullOr(IsoDateTime),
lastRunStatus: ScheduledTaskRunStatus,
@@ -730,6 +737,7 @@ export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({
schedule: Schema.optional(OrchestratorMcpSchedule),
enabled: Schema.optional(Schema.Boolean),
bindToCurrentThread: Schema.optional(Schema.Boolean),
+ freshSession: Schema.optional(Schema.Boolean),
});
export type OrchestratorMcpUpdateScheduledTaskInput =
typeof OrchestratorMcpUpdateScheduledTaskInput.Type;
diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts
index 6d80c962a1f..2a77777a9c3 100644
--- a/packages/contracts/src/scheduledTask.ts
+++ b/packages/contracts/src/scheduledTask.ts
@@ -224,6 +224,20 @@ export const ScheduledTaskWebhookEndpoint = Schema.Struct({
});
export type ScheduledTaskWebhookEndpoint = typeof ScheduledTaskWebhookEndpoint.Type;
+/**
+ * Where runs go. One-thread modes launch their thread on the first run and keep it; `fresh_session`
+ * starts each later run in a new provider session there.
+ */
+export const ScheduledTaskThreadMode = Schema.Literals(["new_thread", "continue", "fresh_session"]);
+export type ScheduledTaskThreadMode = typeof ScheduledTaskThreadMode.Type;
+
+/** Servers before thread modes omit it; their bound tasks continue the conversation. */
+export function scheduledTaskThreadMode(
+ task: Pick<ScheduledTask, "threadId" | "threadMode">,
+): ScheduledTaskThreadMode {
+ return task.threadMode ?? (task.threadId === null ? "new_thread" : "continue");
+}
+
export const ScheduledTask = Schema.Struct({
id: ScheduledTaskId,
title: TrimmedNonEmptyString,
@@ -232,6 +246,7 @@ export const ScheduledTask = Schema.Struct({
schedule: ScheduledTaskSchedule,
projectId: ProjectId,
threadId: Schema.NullOr(ThreadId),
+ threadMode: Schema.optional(ScheduledTaskThreadMode),
workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
@@ -271,6 +286,8 @@ export const ScheduledTaskUpsertInput = Schema.Struct({
schedule: ScheduledTaskUpsertSchedule,
projectId: ProjectId,
threadId: Schema.optional(Schema.NullOr(ThreadId)),
+ /** Omitted: keep the stored mode, or derive it from `threadId` for a new or rebound task. */
+ threadMode: Schema.optional(ScheduledTaskThreadMode),
workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,