The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 04:30 UTC
feat: scheduled tasks can run in one thread with a fresh session each run (#30326)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Nov 5, 2026 at 11:29 UTC
4aab23cd72d71ab3b58878482f3d22f93a088125
19 files changed
+539
-35
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+40
@@ -11,6 +11,7 @@ import type {
11
EnvironmentId,
12
ProjectId,
13
ScheduledTask,
14
+ ScheduledTaskThreadMode,
15
ScheduledTaskUpsertInput,
16
} from "@t3tools/contracts";
17
import {
@@ -109,6 +110,12 @@ const DAYS = [
110
{ index: 0, label: "Sun" },
111
] as const;
112
113
+const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = {
114
+ new_thread: "New thread each run",
115
+ continue: "One thread, same conversation",
116
+ fresh_session: "One thread, fresh session",
117
+};
118
+
119
function describeSchedule(task: ScheduledTask): string {
120
if (task.schedule.type === "webhook") return "On webhook";
121
if (task.schedule.type === "once") {
@@ -722,6 +729,7 @@ function TaskForm({
729
const offersOnce =
730
config?.environment.capabilities.oneTimeSchedules === true ||
731
draft.task?.schedule.type === "once";
732
+ const offersThreadModes = config?.environment.capabilities.scheduledTaskThreadModes === true;
733
const save = async () => {
734
if (
735
!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
@@ -795,6 +803,7 @@ function TaskForm({
803
schedule,
804
enabled: draft.enabled,
805
threadId: draft.task?.threadId ?? null,
806
+ ...(offersThreadModes ? { threadMode: draft.threadMode } : {}),
807
workspaceStrategy:
808
draft.workspace === "root"
809
? { type: "root" }
@@ -932,6 +941,37 @@ function TaskForm({
941
/>
942
</SettingsSection>
943
944
+ {offersThreadModes ? (
945
+ <SettingsSection
946
+ title="Destination"
947
+ footer={
948
+ draft.threadMode === "new_thread"
949
+ ? "Each run starts a new thread."
950
+ : `${
951
+ draft.threadMode === "continue"
952
+ ? "Runs continue one conversation."
953
+ : "Runs share one thread, each in a fresh session without earlier runs' context."
954
+ } The first run starts the thread. Deleting it also deletes this task.`
955
+ }
956
+ >
957
+ <SelectRow
958
+ label="Runs go to"
959
+ value={THREAD_MODE_LABELS[draft.threadMode]}
960
+ actions={(Object.keys(THREAD_MODE_LABELS) as ScheduledTaskThreadMode[]).map(
961
+ (mode) => ({
962
+ id: mode,
963
+ title: THREAD_MODE_LABELS[mode],
964
+ state: draft.threadMode === mode ? "on" : undefined,
965
+ }),
966
+ )}
967
+ onSelect={(id) => {
968
+ if (id === "new_thread" || id === "continue" || id === "fresh_session")
969
+ setDraft({ ...draft, threadMode: id });
970
+ }}
971
+ />
972
+ </SettingsSection>
973
+ ) : null}
974
+
975
<SettingsSection title="Workspace">
976
<SelectRow
977
label="Run in"
apps/mobile/src/features/settings/scheduledTaskDraft.ts
+6
-1
@@ -1,10 +1,11 @@
1
-import { isWebhookDedupeTemplate } from "@t3tools/contracts";
1
+import { isWebhookDedupeTemplate, scheduledTaskThreadMode } from "@t3tools/contracts";
2
import type {
3
ModelSelection,
4
ServerConfig,
5
ProjectId,
6
RuntimeMode,
7
ScheduledTask,
8
+ ScheduledTaskThreadMode,
9
ScheduledTaskUpsertSchedule,
10
ScheduledTaskWebhookSignature,
11
} from "@t3tools/contracts";
@@ -204,6 +205,7 @@ export type ScheduledTaskDraft = {
205
readonly modelSelection: ModelSelection | null;
206
readonly modelSelectionIsExplicit: boolean;
207
readonly schedule: ScheduleDraft;
208
+ readonly threadMode: ScheduledTaskThreadMode;
209
readonly workspace: Workspace;
210
readonly baseRef: string;
211
readonly checkoutPath: string;
@@ -232,6 +234,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
234
draft.schedule.coalesceKey,
235
draft.schedule.coalesceWindowSeconds,
236
draft.schedule.filters.map(({ path, op, value }) => [path, op, value]),
237
+ draft.threadMode,
238
draft.workspace,
239
draft.baseRef,
240
draft.checkoutPath,
@@ -260,6 +263,7 @@ export function createDraft(
263
modelSelection,
264
modelSelectionIsExplicit: false,
265
schedule: DEFAULT_SCHEDULE,
266
+ threadMode: "new_thread",
267
workspace: "worktree",
268
baseRef: "main",
269
checkoutPath: "",
@@ -278,6 +282,7 @@ export function editDraft(task: ScheduledTask): ScheduledTaskDraft {
282
modelSelection: task.modelSelection,
283
modelSelectionIsExplicit: true,
284
schedule: scheduleDraftForTask(task),
285
+ threadMode: scheduledTaskThreadMode(task),
286
workspace: task.workspaceStrategy.type,
287
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
288
checkoutPath:
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -269,6 +269,7 @@ export const make = Effect.gen(function* () {
269
triage: true,
270
oneTimeSchedules: true,
271
freshContext: true,
272
+ scheduledTaskThreadModes: true,
273
npmReleaseLookup: true,
274
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
275
...(serverInstallation === null ? {} : { serverInstallation }),
apps/server/src/mcp/OrchestratorMcpService.test.ts
+69
-3
@@ -13,6 +13,7 @@ import {
13
OrchestratorMcpTarget,
14
type OrchestrationV2ThreadShell,
15
type ScheduledTask,
16
+ type ScheduledTaskUpsertInput,
17
ScheduledTaskId,
18
ProjectId,
19
ProviderDriverKind,
@@ -2776,6 +2777,8 @@ describe("OrchestratorMcpService provider resolution", () => {
2777
const service = (
2778
git: Partial<GitVcsDriver.GitVcsDriver["Service"]>,
2779
saved: Ref.Ref<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>,
2780
+ task: ScheduledTask = existing,
2781
+ modes?: Ref.Ref<ReadonlyArray<ScheduledTaskUpsertInput["threadMode"]>>,
2782
) =>
2783
OrchestratorMcpService.layer.pipe(
2784
Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -2784,7 +2787,9 @@ describe("OrchestratorMcpService provider resolution", () => {
2787
Layer.mergeAll(
2788
NodeServices.layer,
2789
NodeCrypto.layer,
2787
- Layer.mock(ThreadManagementService.ThreadManagementService)({}),
2790
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
2791
+ getThreadShell: () => Effect.succeed(null),
2792
+ }),
2793
ServerSettings.layerTest(),
2794
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
2795
Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
@@ -2801,10 +2806,15 @@ describe("OrchestratorMcpService provider resolution", () => {
2806
Layer.mock(SecretRequests.SecretRequests)({}),
2807
Layer.mock(RemoteDelegation.RemoteDelegation)({}),
2808
Layer.mock(ScheduledTaskService.ScheduledTaskService)({
2804
- list: () => Effect.succeed({ tasks: [existing] }),
2809
+ list: () => Effect.succeed({ tasks: [task] }),
2810
upsert: (input) =>
2811
Ref.update(saved, (strategies) => [...strategies, input.workspaceStrategy]).pipe(
2807
- Effect.as({ task: existing }),
2812
+ Effect.andThen(
2813
+ modes === undefined
2814
+ ? Effect.void
2815
+ : Ref.update(modes, (all) => [...all, input.threadMode]),
2816
+ ),
2817
+ Effect.as({ task }),
2818
),
2819
}),
2820
),
@@ -2831,6 +2841,62 @@ describe("OrchestratorMcpService provider resolution", () => {
2841
}),
2842
);
2843
2844
+ it.effect("keeps one thread when fresh sessions are turned off before the first run", () =>
2845
+ Effect.gen(function* () {
2846
+ const modes = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput["threadMode"]>>([]);
2847
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
2848
+ Effect.provide(
2849
+ service(
2850
+ masterRepository,
2851
+ yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]),
2852
+ { ...existing, threadMode: "fresh_session" },
2853
+ modes,
2854
+ ),
2855
+ ),
2856
+ );
2857
+ yield* mcp.updateScheduledTask(client, {
2858
+ scheduledTaskId: existing.id,
2859
+ freshSession: false,
2860
+ });
2861
+ yield* mcp.updateScheduledTask(client, {
2862
+ scheduledTaskId: existing.id,
2863
+ bindToCurrentThread: false,
2864
+ });
2865
+ assert.deepEqual(yield* Ref.get(modes), ["continue", "new_thread"]);
2866
+ }),
2867
+ );
2868
+
2869
+ it.effect(
2870
+ "refuses unbinding into fresh sessions in one call, which would keep the thread",
2871
+ () =>
2872
+ Effect.gen(function* () {
2873
+ const modes = yield* Ref.make<ReadonlyArray<ScheduledTaskUpsertInput["threadMode"]>>([]);
2874
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService.pipe(
2875
+ Effect.provide(
2876
+ service(
2877
+ masterRepository,
2878
+ yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]),
2879
+ {
2880
+ ...existing,
2881
+ threadId: ThreadId.make("thread:scheduled-base"),
2882
+ threadMode: "continue",
2883
+ },
2884
+ modes,
2885
+ ),
2886
+ ),
2887
+ );
2888
+ const refused = yield* mcp
2889
+ .updateScheduledTask(client, {
2890
+ scheduledTaskId: existing.id,
2891
+ bindToCurrentThread: false,
2892
+ freshSession: true,
2893
+ })
2894
+ .pipe(Effect.flip);
2895
+ assert.include(refused.message, "first unbind it");
2896
+ assert.deepEqual(yield* Ref.get(modes), []);
2897
+ }),
2898
+ );
2899
+
2900
it.effect("follows the default branch when a task is unbound from its thread", () =>
2901
Effect.gen(function* () {
2902
const saved = yield* Ref.make<ReadonlyArray<ScheduledTask["workspaceStrategy"]>>([]);
apps/server/src/mcp/OrchestratorMcpService.ts
+31
@@ -58,6 +58,7 @@ import {
58
type RuntimeMode,
59
type ScheduledTask,
60
type ScheduledTaskUpsertInput,
61
+ scheduledTaskThreadMode,
62
type ServerProvider,
63
type ServerProviderModel,
64
ThreadId,
@@ -266,6 +267,7 @@ function scheduledTaskSummary(task: ScheduledTask, mayRun: boolean): Orchestrato
267
enabled: task.enabled,
268
projectId: task.projectId,
269
boundThreadId: task.threadId,
270
+ freshSession: scheduledTaskThreadMode(task) === "fresh_session",
271
schedule: task.schedule,
272
nextRunAt: task.nextRunAt,
273
lastRunStatus: task.lastRunStatus,
@@ -2009,6 +2011,11 @@ const make = Effect.gen(function* () {
2011
schedule: input.schedule,
2012
projectId,
2013
threadId: bindToCurrentThread && parent !== undefined ? parent.thread.id : null,
2014
+ threadMode: input.freshSession
2015
+ ? "fresh_session"
2016
+ : bindToCurrentThread
2017
+ ? "continue"
2018
+ : "new_thread",
2019
workspaceStrategy: yield* scheduledTaskWorkspaceStrategy(bindToCurrentThread, projectId),
2020
modelSelection,
2021
runtimeMode: limits.runtimeMode,
@@ -2071,6 +2078,18 @@ const make = Effect.gen(function* () {
2078
: "bindToCurrentThread binds to this thread, which belongs to a different project.",
2079
);
2080
}
2081
+ // A save keeps a bound thread unless the task goes back to new threads, so this pair
2082
+ // would leave runs in the old thread.
2083
+ if (
2084
+ input.bindToCurrentThread === false &&
2085
+ input.freshSession === true &&
2086
+ existing.threadId !== null
2087
+ ) {
2088
+ return yield* failure(
2089
+ "invalid_request",
2090
+ "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.",
2091
+ );
2092
+ }
2093
const threadId =
2094
input.bindToCurrentThread === undefined
2095
? existing.threadId
@@ -2090,6 +2109,18 @@ const make = Effect.gen(function* () {
2109
schedule: input.schedule ?? existing.schedule,
2110
projectId: existing.projectId,
2111
threadId,
2112
+ threadMode:
2113
+ input.freshSession === undefined && input.bindToCurrentThread === undefined
2114
+ ? scheduledTaskThreadMode(existing)
2115
+ : (input.freshSession ??
2116
+ (input.bindToCurrentThread !== false &&
2117
+ scheduledTaskThreadMode(existing) === "fresh_session"))
2118
+ ? "fresh_session"
2119
+ : threadId === null &&
2120
+ (input.bindToCurrentThread === false ||
2121
+ scheduledTaskThreadMode(existing) === "new_thread")
2122
+ ? "new_thread"
2123
+ : "continue",
2124
workspaceStrategy,
2125
modelSelection: existing.modelSelection,
2126
runtimeMode: existing.runtimeMode,
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+2
@@ -425,6 +425,8 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
425
}
426
const save = (name: string, target: ThreadId | null, webhook = false) =>
427
tasks.upsert({
428
+ // As schedule_task sends it, so clearing the thread unbinds the task.
429
+ threadMode: target === null ? "new_thread" : "continue",
430
id: ScheduledTaskId.make(`automation:${deletion}:${name}`),
431
title: name,
432
prompt: "Check orchestration progress",
apps/server/src/persistence/Migrations.ts
+2
-1
@@ -81,8 +81,8 @@ import Migration0075 from "./Migrations/075_SubagentDeliveryState.ts";
81
import Migration0076 from "./Migrations/076_ProjectionProjectsPinArchive.ts";
82
import Migration0077 from "./Migrations/077_RepairBooleanSettledOverride.ts";
83
import Migration0078 from "./Migrations/078_DropOrchestrationEventCorrelationIndex.ts";
84
-
84
import Migration0079 from "./Migrations/079_DelegatedRecoveryIndexes.ts";
85
+import Migration0080 from "./Migrations/080_ScheduledTaskThreadMode.ts";
86
87
const migrationEntries = [
88
[1, "OrchestrationEvents", Migration0001],
@@ -165,6 +165,7 @@ const migrationEntries = [
165
[77, "RepairBooleanSettledOverride", Migration0077],
166
[78, "DropOrchestrationEventCorrelationIndex", Migration0078],
167
[79, "DelegatedRecoveryIndexes", Migration0079],
168
+ [80, "ScheduledTaskThreadMode", Migration0080],
169
] as const;
170
171
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
apps/server/src/persistence/Migrations/080_ScheduledTaskThreadMode.ts
new
+9
@@ -0,0 +1,9 @@
1
+import * as Effect from "effect/Effect";
2
+import * as SqlClient from "effect/sql/SqlClient";
3
+
4
+export default Effect.gen(function* () {
5
+ const sql = yield* SqlClient.SqlClient;
6
+
7
+ yield* sql`ALTER TABLE scheduled_tasks ADD COLUMN thread_mode TEXT NOT NULL DEFAULT 'new_thread'`;
8
+ yield* sql`UPDATE scheduled_tasks SET thread_mode = 'continue' WHERE thread_id IS NOT NULL`;
9
+});
apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+2
@@ -59,6 +59,7 @@ describe("V2 preview upgrade", () => {
59
[77, "RepairBooleanSettledOverride"],
60
[78, "DropOrchestrationEventCorrelationIndex"],
61
[79, "DelegatedRecoveryIndexes"],
62
+ [80, "ScheduledTaskThreadMode"],
63
]);
64
assert.deepStrictEqual(yield* runMigrations(), []);
65
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -161,6 +162,7 @@ describe("V2 preview upgrade", () => {
162
[77, "RepairBooleanSettledOverride"],
163
[78, "DropOrchestrationEventCorrelationIndex"],
164
[79, "DelegatedRecoveryIndexes"],
165
+ [80, "ScheduledTaskThreadMode"],
166
]);
167
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
168
);
apps/server/src/provider/agentContextBudget.json
+1
-1
@@ -1,5 +1,5 @@
1
{
2
"claudeSystemAppendBytes": 5133,
3
"codexAdditionalContextBytes": 6863,
4
- "mcpToolListJsonBytes": 47642
4
+ "mcpToolListJsonBytes": 47818
5
}
apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+202
-3
@@ -485,6 +485,203 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
485
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
486
);
487
488
+it.effect("a fresh-session task launches one thread, then starts each later run fresh in it", () =>
489
+ Effect.gen(function* () {
490
+ const launches = yield* Ref.make(0);
491
+ const sends = yield* Ref.make<Array<{ threadId: ThreadId; freshContext?: boolean }>>([]);
492
+ const launched = ThreadId.make("thread:fresh-session-task");
493
+ const layer = ScheduledTaskService.layer.pipe(
494
+ Layer.provide(
495
+ Layer.mergeAll(
496
+ ManagedPolicy.layerTest(),
497
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
498
+ launch: () =>
499
+ Ref.update(launches, (n) => n + 1).pipe(
500
+ Effect.as({ threadId: launched, resumed: false } as never),
501
+ ),
502
+ }),
503
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
504
+ getThreadShell: () => Effect.succeed({ deletedAt: null } as never),
505
+ sendToThread: (input) =>
506
+ Ref.update(sends, (all) => [
507
+ ...all,
508
+ {
509
+ threadId: input.threadId,
510
+ ...(input.freshContext === undefined ? {} : { freshContext: input.freshContext }),
511
+ },
512
+ ]).pipe(Effect.as({} as never)),
513
+ }),
514
+ Layer.mock(SecretRequests.SecretRequests)({}),
515
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
516
+ namedProjectsRoot: "/projects",
517
+ isScratchProject: () => Effect.succeed(false),
518
+ }),
519
+ NodeCrypto.layer,
520
+ Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
521
+ ),
522
+ ),
523
+ );
524
+ yield* Effect.gen(function* () {
525
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
526
+ const input = {
527
+ id: ScheduledTaskId.make("task:fresh-session"),
528
+ title: "Triage",
529
+ prompt: "Triage new issues",
530
+ enabled: true,
531
+ schedule: { type: "interval", everyMs: 60_000 },
532
+ projectId: ProjectId.make("project:test"),
533
+ workspaceStrategy: { type: "root" },
534
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
535
+ runtimeMode: "full-access",
536
+ interactionMode: "default",
537
+ } as const;
538
+ yield* service.upsert({ ...input, threadMode: "fresh_session" });
539
+
540
+ assert.equal((yield* service.runNow({ id: input.id })).threadId, launched);
541
+ // A form opened before the first run saves no thread; the binding stays.
542
+ const { task } = yield* service.upsert({
543
+ ...input,
544
+ threadId: null,
545
+ threadMode: "fresh_session",
546
+ });
547
+ assert.equal(task.threadId, launched);
548
+ assert.equal(task.threadMode, "fresh_session");
549
+ // A client that predates thread modes sends neither; both stay.
550
+ const legacy = yield* service.upsert({ ...input, threadId: null });
551
+ assert.equal(legacy.task.threadId, launched);
552
+ assert.equal(legacy.task.threadMode, "fresh_session");
553
+ yield* service.runNow({ id: input.id });
554
+
555
+ assert.equal(yield* Ref.get(launches), 1);
556
+ assert.deepEqual(yield* Ref.get(sends), [{ threadId: launched, freshContext: true }]);
557
+ // Its thread stays in the old project, so moving the task leaves it for a new one.
558
+ const moved = yield* service.upsert({
559
+ ...input,
560
+ projectId: ProjectId.make("project:moved"),
561
+ threadId: launched,
562
+ });
563
+ assert.equal(moved.task.threadId, null);
564
+ assert.equal(moved.task.threadMode, "fresh_session");
565
+ const unbound = yield* service.upsert({ ...input, threadMode: "new_thread" });
566
+ assert.equal(unbound.task.threadId, null);
567
+ }).pipe(Effect.provide(layer));
568
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
569
+);
570
+
571
+it.effect("a first run whose thread was deleted before it bound removes the task", () =>
572
+ Effect.gen(function* () {
573
+ const layer = ScheduledTaskService.layer.pipe(
574
+ Layer.provide(
575
+ Layer.mergeAll(
576
+ ManagedPolicy.layerTest(),
577
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
578
+ launch: () =>
579
+ Effect.succeed({
580
+ threadId: ThreadId.make("thread:deleted"),
581
+ resumed: false,
582
+ } as never),
583
+ }),
584
+ // Deleted before the binding landed, so its cleanup found no task to remove.
585
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
586
+ getThreadShell: () =>
587
+ Effect.succeed({ deletedAt: DateTime.makeUnsafe("2026-11-03T00:00:00Z") } as never),
588
+ }),
589
+ Layer.mock(SecretRequests.SecretRequests)({}),
590
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
591
+ namedProjectsRoot: "/projects",
592
+ isScratchProject: () => Effect.succeed(false),
593
+ }),
594
+ NodeCrypto.layer,
595
+ Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
596
+ ),
597
+ ),
598
+ );
599
+ yield* Effect.gen(function* () {
600
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
601
+ const { task } = yield* service.upsert({
602
+ id: ScheduledTaskId.make("task:thread-deleted-mid-launch"),
603
+ title: "Triage",
604
+ prompt: "Triage new issues",
605
+ enabled: true,
606
+ schedule: { type: "interval", everyMs: 60_000 },
607
+ projectId: ProjectId.make("project:test"),
608
+ threadMode: "continue",
609
+ workspaceStrategy: { type: "root" },
610
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
611
+ runtimeMode: "full-access",
612
+ interactionMode: "default",
613
+ });
614
+ yield* service.runNow({ id: task.id });
615
+ assert.deepEqual((yield* service.list()).tasks, []);
616
+ }).pipe(Effect.provide(layer));
617
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
618
+);
619
+
620
+it.effect.each(["recreated under the same id", "moved to another project"] as const)(
621
+ "a first run never binds its thread to a task %s",
622
+ (change) =>
623
+ Effect.gen(function* () {
624
+ const launching = yield* Deferred.make<void>();
625
+ const proceed = yield* Deferred.make<void>();
626
+ const layer = ScheduledTaskService.layer.pipe(
627
+ Layer.provide(
628
+ Layer.mergeAll(
629
+ ManagedPolicy.layerTest(),
630
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({
631
+ launch: () =>
632
+ Deferred.succeed(launching, undefined).pipe(
633
+ Effect.andThen(Deferred.await(proceed)),
634
+ Effect.as({
635
+ threadId: ThreadId.make("thread:old-generation"),
636
+ resumed: false,
637
+ } as never),
638
+ ),
639
+ }),
640
+ Layer.mock(ThreadManagementService.ThreadManagementService)({}),
641
+ Layer.mock(SecretRequests.SecretRequests)({}),
642
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
643
+ namedProjectsRoot: "/projects",
644
+ isScratchProject: () => Effect.succeed(false),
645
+ }),
646
+ NodeCrypto.layer,
647
+ Layer.succeed(Scheduler.Scheduler, { register: () => Effect.void }),
648
+ ),
649
+ ),
650
+ );
651
+ yield* Effect.gen(function* () {
652
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
653
+ const input = {
654
+ id: ScheduledTaskId.make("task:recreated-mid-launch"),
655
+ title: "Triage",
656
+ prompt: "Triage new issues",
657
+ enabled: true,
658
+ schedule: { type: "interval", everyMs: 60_000 },
659
+ projectId: ProjectId.make("project:test"),
660
+ threadMode: "fresh_session",
661
+ workspaceStrategy: { type: "root" },
662
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
663
+ runtimeMode: "full-access",
664
+ interactionMode: "default",
665
+ } as const;
666
+ yield* service.upsert(input);
667
+ const run = yield* Effect.forkChild(service.runNow({ id: input.id }));
668
+ yield* Deferred.await(launching);
669
+ if (change === "recreated under the same id") {
670
+ yield* service.delete({ id: input.id });
671
+ yield* TestClock.adjust("1 second");
672
+ yield* service.upsert(input);
673
+ } else {
674
+ yield* service.upsert({ ...input, projectId: ProjectId.make("project:moved") });
675
+ }
676
+ yield* Deferred.succeed(proceed, undefined);
677
+ yield* Fiber.await(run);
678
+
679
+ const replacement = (yield* service.list()).tasks.find((task) => task.id === input.id);
680
+ assert.equal(replacement?.threadId, null);
681
+ }).pipe(Effect.provide(layer));
682
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
683
+);
684
+
685
it.effect("refuses saving an enabled task above the policy ceiling", () =>
686
Effect.gen(function* () {
687
const layer = ScheduledTaskService.layer.pipe(
@@ -534,19 +731,21 @@ it.effect("refuses saving an enabled task above the policy ceiling", () =>
731
.pipe(Effect.flip);
732
assert.equal(reenabled.message, "Example Corp limits threads to Auto-accept edits.");
733
// A task bound to a thread runs in that thread's mode, so its own is not checked.
537
- yield* service.upsert({
734
+ const bound = {
735
id: ScheduledTaskId.make("task:bound"),
736
title: "Follow up",
737
prompt: "Check progress",
738
enabled: true,
739
schedule: { type: "interval", everyMs: 60_000 },
740
projectId: ProjectId.make("project:test"),
544
- threadId: ThreadId.make("thread:bound"),
741
workspaceStrategy: { type: "root" },
742
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
743
runtimeMode: "full-access",
744
interactionMode: "default",
549
- });
745
+ } as const;
746
+ yield* service.upsert({ ...bound, threadId: ThreadId.make("thread:bound") });
747
+ // Nor when an edit omits the thread it stays bound to.
748
+ yield* service.upsert(bound);
749
}).pipe(Effect.provide(layer));
750
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
751
);
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+75
-13
@@ -22,8 +22,10 @@ import {
22
type ScheduledTaskRunNowInput,
23
type ScheduledTaskRunNowResult,
24
type ScheduledTaskSetEnabledInput,
25
+ type ScheduledTaskThreadMode,
26
type ScheduledTaskUpsertInput,
27
managedPolicyDeniedMessage,
28
+ scheduledTaskThreadMode,
29
managedRuntimeModeDenial,
30
} from "@t3tools/contracts";
31
import * as Cause from "effect/Cause";
@@ -191,6 +193,19 @@ const decodeMissingFieldsJson = Schema.decodeUnknownOption(MissingFieldsJson);
193
const encodeHeadersJson = Schema.encodeSync(HeadersJson);
194
const encodeMissingFieldsJson = Schema.encodeSync(MissingFieldsJson);
195
196
+/**
197
+ * Clients that predate thread modes send none, and may send a thread loaded before the first run
198
+ * bound one. An edit keeps the stored mode; binding a thread to a new-thread task continues it.
199
+ */
200
+function resolveThreadMode(
201
+ input: Pick<ScheduledTaskUpsertInput, "threadId" | "threadMode">,
202
+ existing: Pick<ScheduledTask, "threadId" | "threadMode"> | null,
203
+): ScheduledTaskThreadMode {
204
+ if (input.threadMode !== undefined) return input.threadMode;
205
+ const stored = existing === null ? "new_thread" : scheduledTaskThreadMode(existing);
206
+ return stored === "new_thread" && input.threadId != null ? "continue" : stored;
207
+}
208
+
209
interface ScheduledTaskRow {
210
readonly task_id: string;
211
readonly title: string;
@@ -199,6 +214,7 @@ interface ScheduledTaskRow {
214
readonly schedule_json: string;
215
readonly project_id: string;
216
readonly thread_id: string | null;
217
+ readonly thread_mode: string;
218
readonly workspace_strategy_json: string;
219
readonly model_selection_json: string;
220
readonly runtime_mode: string;
@@ -372,6 +388,7 @@ const decodeRow = Effect.fnUntraced(
388
schedule,
389
projectId: row.project_id,
390
threadId: row.thread_id,
391
+ threadMode: row.thread_mode,
392
workspaceStrategy,
393
modelSelection,
394
runtimeMode: row.runtime_mode,
@@ -494,6 +511,7 @@ export const layer = Layer.effect(
511
schedule_json,
512
project_id,
513
thread_id,
514
+ thread_mode,
515
workspace_strategy_json,
516
model_selection_json,
517
runtime_mode,
@@ -535,6 +553,7 @@ export const layer = Layer.effect(
553
schedule_json,
554
project_id,
555
thread_id,
556
+ thread_mode,
557
workspace_strategy_json,
558
model_selection_json,
559
runtime_mode,
@@ -612,6 +631,7 @@ export const layer = Layer.effect(
631
schedule_json,
632
project_id,
633
thread_id,
634
+ thread_mode,
635
workspace_strategy_json,
636
model_selection_json,
637
runtime_mode,
@@ -636,6 +656,7 @@ export const layer = Layer.effect(
656
${JSON.stringify(task.schedule)},
657
${task.projectId},
658
${task.threadId},
659
+ ${scheduledTaskThreadMode(task)},
660
${JSON.stringify(task.workspaceStrategy)},
661
${JSON.stringify(task.modelSelection)},
662
${task.runtimeMode},
@@ -660,7 +681,14 @@ export const layer = Layer.effect(
681
enabled = excluded.enabled,
682
schedule_json = excluded.schedule_json,
683
project_id = excluded.project_id,
663
- thread_id = excluded.thread_id,
684
+ -- A first run may bind the thread while this save is in flight; only a
685
+ -- switch to new threads unbinds.
686
+ thread_id = CASE
687
+ WHEN excluded.thread_mode = 'new_thread' THEN NULL
688
+ WHEN excluded.project_id != scheduled_tasks.project_id THEN excluded.thread_id
689
+ ELSE COALESCE(excluded.thread_id, scheduled_tasks.thread_id)
690
+ END,
691
+ thread_mode = excluded.thread_mode,
692
workspace_strategy_json = excluded.workspace_strategy_json,
693
model_selection_json = excluded.model_selection_json,
694
runtime_mode = excluded.runtime_mode,
@@ -798,6 +826,25 @@ export const layer = Layer.effect(
826
),
827
);
828
829
+ // The run already started the thread, so a failed write only costs the binding.
830
+ // A thread deleted before the binding landed already ran its task cleanup, so apply that
831
+ // cleanup here; a later deletion finds the binding. An unconfirmed lookup keeps the binding.
832
+ const bindThread = Effect.fn("ScheduledTaskService.bindThread")(
833
+ function* (task: ScheduledTask, threadId: ThreadId) {
834
+ yield* sql`
835
+ UPDATE scheduled_tasks SET thread_id = ${threadId}
836
+ WHERE task_id = ${task.id} AND created_at = ${task.createdAt}
837
+ AND project_id = ${task.projectId}
838
+ AND thread_id IS NULL AND thread_mode != 'new_thread'
839
+ `;
840
+ const shell = yield* threadManagement.getThreadShell(threadId);
841
+ if (shell === null || shell.deletedAt != null) yield* deleteForThread(threadId);
842
+ },
843
+ Effect.catchCause((cause) =>
844
+ Effect.logWarning("Could not bind a scheduled task to its first thread.", cause),
845
+ ),
846
+ );
847
+
848
const runTask = Effect.fn("ScheduledTaskService.runTask")(function* (
849
task: ScheduledTask,
850
trigger: "scheduled" | "manual" | "webhook",
@@ -885,6 +932,7 @@ export const layer = Layer.effect(
932
const commandId = CommandId.make(`scheduled-task:${fireKey}`);
933
const messageId = MessageId.make(`scheduled-task-message:${fireKey}`);
934
const prompt = webhook?.prompt ?? active.prompt;
935
+ const threadMode = scheduledTaskThreadMode(active);
936
937
// A bound thread can move to another project (No project to a project) while
938
// this fires. Follow it; one move needs at most two retries. Same ids replay safely.
@@ -903,6 +951,7 @@ export const layer = Layer.effect(
951
text: prompt,
952
attachments: [],
953
mode: "queue",
954
+ ...(threadMode === "fresh_session" ? { freshContext: true } : {}),
955
createdBy: active.createdBy,
956
creationSource: active.creationSource,
957
})
@@ -944,7 +993,12 @@ export const layer = Layer.effect(
993
createdBy: active.createdBy,
994
creationSource: active.creationSource,
995
})
947
- .pipe(Effect.map((launched) => launched.threadId)),
996
+ .pipe(
997
+ Effect.map((launched) => launched.threadId),
998
+ Effect.tap((threadId) =>
999
+ threadMode === "new_thread" ? Effect.void : bindThread(active, threadId),
1000
+ ),
1001
+ ),
1002
)
1003
: yield* Effect.exit(
1004
// The stored selection only seeds fresh threads. A bound run
@@ -1209,16 +1263,6 @@ export const layer = Layer.effect(
1263
input.id === undefined ? {} : { taskId: input.id },
1264
);
1265
}
1212
- // Refused on save rather than at run time; a disabled task can still be saved, so one
1213
- // stored above the ceiling can be turned off before its mode is lowered. A task bound to a
1214
- // thread runs in that thread's mode, which the orchestrator checks instead.
1215
- const modeDenial =
1216
- input.enabled && input.threadId == null
1217
- ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)
1218
- : undefined;
1219
- if (modeDenial !== undefined) {
1220
- return yield* taskError(modeDenial, input.id === undefined ? {} : { taskId: input.id });
1221
- }
1266
const now = yield* localNow;
1267
const uuid =
1268
input.commandId === undefined
@@ -1239,6 +1283,23 @@ export const layer = Layer.effect(
1283
// keep their run history, and so real load failures propagate instead
1284
// of silently resetting an existing row.
1285
const existingTask = yield* findTask(id);
1286
+ const threadMode = resolveThreadMode(input, existingTask);
1287
+ const keptThreadId = input.threadId ?? existingTask?.threadId ?? null;
1288
+ // A bound thread belongs to its project, so moving the task leaves it for a new one.
1289
+ const movedOffThread =
1290
+ existingTask !== null &&
1291
+ existingTask.projectId !== input.projectId &&
1292
+ keptThreadId === existingTask.threadId;
1293
+ const threadId = threadMode === "new_thread" || movedOffThread ? null : keptThreadId;
1294
+ // Refused on save rather than at run time; a disabled task can still be saved, so one
1295
+ // stored above the ceiling can be turned off before its mode is lowered. A task bound to a
1296
+ // thread runs in that thread's mode, which the orchestrator checks instead. Checked before
1297
+ // the save consumes a webhook secret.
1298
+ const modeDenial =
1299
+ input.enabled && threadId === null
1300
+ ? managedRuntimeModeDenial(managedPolicy.summary, input.runtimeMode)
1301
+ : undefined;
1302
+ if (modeDenial !== undefined) return yield* taskError(modeDenial, { taskId: id });
1303
// Keep the existing next_run_at when the schedule itself is untouched:
1304
// editing a title or prompt must not postpone (or resurrect) a due
1305
// run — only schedule/enabled changes restart the clock.
@@ -1327,7 +1388,8 @@ export const layer = Layer.effect(
1388
enabled: input.enabled,
1389
schedule,
1390
projectId: input.projectId,
1330
- threadId: input.threadId ?? null,
1391
+ threadId,
1392
+ threadMode,
1393
workspaceStrategy,
1394
modelSelection: input.modelSelection,
1395
runtimeMode: input.runtimeMode,
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+59
-12
@@ -20,6 +20,7 @@ import type {
20
ScheduledTask,
21
ScheduledTaskId,
22
ScheduledTaskSchedule,
23
+ ScheduledTaskThreadMode,
24
ScheduledTaskUpsertInput,
25
ScheduledTaskWebhookDeliverySummary,
26
ThreadId,
@@ -149,6 +150,7 @@ const EMPTY_DRAFT: DraftState = {
150
weekdays: new Set([1, 2, 3, 4, 5]),
151
projectId: "",
152
threadId: "",
153
+ threadMode: "new_thread",
154
workspaceMode: "worktree",
155
baseRef: "main",
156
startFromOrigin: true,
@@ -1141,12 +1143,23 @@ function ScheduledTaskEditorDialog({
1143
);
1144
}
1145
1146
+const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = {
1147
+ new_thread: "New thread each run",
1148
+ continue: "One thread, continuing the conversation",
1149
+ fresh_session: "One thread, fresh session each run",
1150
+};
1151
+
1152
function ScheduledTaskDestination({
1153
environmentId,
1154
threadId,
1155
+ threadMode,
1156
+ onThreadModeChange,
1157
}: {
1158
readonly environmentId: EnvironmentId;
1159
readonly threadId: ThreadId | null;
1160
+ readonly threadMode: ScheduledTaskThreadMode;
1161
+ /** Absent on servers that predate thread modes. */
1162
+ readonly onThreadModeChange: ((mode: ScheduledTaskThreadMode) => void) | undefined;
1163
}) {
1164
const ref = threadId === null ? null : scopeThreadRef(environmentId, threadId);
1165
const shell = useThreadShell(ref);
@@ -1155,20 +1168,45 @@ function ScheduledTaskDestination({
1168
ref !== null && shell === null ? threadFamilies.familyAtom(environmentId, ref.threadId) : null,
1169
);
1170
const thread = shell ?? family.data?.threads.find((row) => row.id === threadId);
1171
+ const bound = ref !== null && threadMode !== "new_thread";
1172
+ const detail =
1173
+ threadMode === "new_thread"
1174
+ ? "Each run starts a new thread with the workspace and model below."
1175
+ : !bound
1176
+ ? threadMode === "continue"
1177
+ ? "The first run starts a thread with the workspace and model below. Later runs continue that conversation."
1178
+ : "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."
1179
+ : threadMode === "continue"
1180
+ ? "Each run continues this conversation, in its workspace and with its current model."
1181
+ : "Each run starts a fresh session in this thread, without earlier runs' context.";
1182
return (
1159
- <Field label="Destination">
1160
- {ref === null ? (
1161
- <p className="text-sm text-muted-foreground">
1162
- Each run starts a new thread with the workspace and model below.
1163
- </p>
1164
- ) : (
1165
- <div className="space-y-1 text-sm">
1183
+ <Field label="Destination" htmlFor="scheduled-task-destination">
1184
+ {onThreadModeChange ? (
1185
+ <Select
1186
+ value={threadMode}
1187
+ onValueChange={(value) => onThreadModeChange(value as ScheduledTaskThreadMode)}
1188
+ >
1189
+ <SelectTrigger size="sm" id="scheduled-task-destination">
1190
+ <SelectValue>{THREAD_MODE_LABELS[threadMode]}</SelectValue>
1191
+ </SelectTrigger>
1192
+ <SelectPopup>
1193
+ {(Object.keys(THREAD_MODE_LABELS) as ScheduledTaskThreadMode[]).map((mode) => (
1194
+ <SelectItem key={mode} value={mode}>
1195
+ {THREAD_MODE_LABELS[mode]}
1196
+ </SelectItem>
1197
+ ))}
1198
+ </SelectPopup>
1199
+ </Select>
1200
+ ) : null}
1201
+ <div className="space-y-1 text-sm">
1202
+ {bound ? (
1203
<p className="wrap-anywhere">{thread?.title.trim() || `Thread ${ref.threadId}`}</p>
1167
- <p className="text-muted-foreground">
1168
- Each run continues this conversation, in its workspace and with its current model.
1169
- </p>
1170
- </div>
1171
- )}
1204
+ ) : null}
1205
+ <p className="text-muted-foreground">{detail}</p>
1206
+ {threadMode !== "new_thread" ? (
1207
+ <p className="text-muted-foreground">Deleting the thread also deletes this task.</p>
1208
+ ) : null}
1209
+ </div>
1210
</Field>
1211
);
1212
}
@@ -1193,6 +1231,8 @@ function ScheduledTaskEditorForm({
1231
const offersOnce =
1232
environment?.serverConfig?.environment.capabilities.oneTimeSchedules === true ||
1233
task?.schedule.type === "once";
1234
+ const offersThreadModes =
1235
+ environment?.serverConfig?.environment.capabilities.scheduledTaskThreadModes === true;
1236
const connected =
1237
environment?.connection.phase === "connected" && environment.serverConfig !== null;
1238
const tasksQuery = useEnvironmentQuery(
@@ -1356,6 +1396,7 @@ function ScheduledTaskEditorForm({
1396
schedule,
1397
projectId: selectedProjectId as ProjectId,
1398
threadId: draft.threadId ? (draft.threadId as ThreadId) : null,
1399
+ ...(offersThreadModes ? { threadMode: draft.threadMode } : {}),
1400
workspaceStrategy,
1401
modelSelection,
1402
// Tasks have no mode picker; a mode above the administrator's ceiling would fail every run.
@@ -1482,6 +1523,12 @@ function ScheduledTaskEditorForm({
1523
<ScheduledTaskDestination
1524
environmentId={environmentId}
1525
threadId={draft.threadId ? (draft.threadId as ThreadId) : null}
1526
+ threadMode={draft.threadMode}
1527
+ onThreadModeChange={
1528
+ offersThreadModes
1529
+ ? (threadMode) => setDraft((current) => ({ ...current, threadMode }))
1530
+ : undefined
1531
+ }
1532
/>
1533
1534
<div className="grid gap-3 sm:grid-cols-2">
apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+4
@@ -5,7 +5,9 @@ import {
5
type ProjectId,
6
ScheduledTaskId,
7
type ScheduledTask,
8
+ type ScheduledTaskThreadMode,
9
type ScheduledTaskUpsertSchedule,
10
+ scheduledTaskThreadMode,
11
type ModelSelection,
12
type RuntimeMode,
13
type ProviderInteractionMode,
@@ -70,6 +72,7 @@ export interface DraftState {
72
readonly weekdays: ReadonlySet<number>;
73
readonly projectId: string;
74
readonly threadId: string;
75
+ readonly threadMode: ScheduledTaskThreadMode;
76
readonly workspaceMode: WorkspaceMode;
77
readonly baseRef: string;
78
readonly startFromOrigin: boolean;
@@ -254,6 +257,7 @@ export function taskToDraft(task: ScheduledTask): DraftState {
257
weekdays,
258
projectId: task.projectId,
259
threadId: task.threadId ?? "",
260
+ threadMode: scheduledTaskThreadMode(task),
261
workspaceMode: task.workspaceStrategy.type,
262
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
263
startFromOrigin:
docs/user/project-settings.md
+7
@@ -86,6 +86,13 @@ environment's time zone, which may differ from your phone's. Choose **Once**
86
to run a task a single time at a date and time in your own time zone. If the
87
environment is offline then, the task runs when it is back.
88
89
+Under **Destination**, choose where runs go. **New thread each run** keeps every
90
+run separate. The two one-thread choices start a thread on the first run and post
91
+later runs there: one continues the same conversation, the other starts each run
92
+in a fresh session that doesn't see earlier runs, so the thread stays readable
93
+without the agent's context growing. Moving such a task to another project starts
94
+a new thread there on its next run.
95
+
96
Deleting a thread also deletes tasks that post into that thread. Tasks that start
97
a new thread on each run survive deletion of their previous threads.
98
evals/mcp-tool-use/cases/pull-requests.ndjson
+2
-1
@@ -21,7 +21,7 @@
21
{"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}
22
{"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}
23
{"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}
24
-{"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."}
24
+{"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."}
25
{"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": ""}
26
{"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."}
27
{"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 @@
35
{"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."}}
36
{"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"}}
37
{"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."}
38
+{"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."}
packages/contracts/src/environment.ts
+2
@@ -170,6 +170,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
170
oneTimeSchedules: Schema.optionalKey(Schema.Boolean),
171
/** Server honors `freshContext` on sends; older servers ignore it and keep the old context. */
172
freshContext: Schema.optionalKey(Schema.Boolean),
173
+ /** Server saves and runs scheduled task `threadMode`; older servers ignore it. */
174
+ scheduledTaskThreadModes: Schema.optionalKey(Schema.Boolean),
175
});
176
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
177
packages/contracts/src/orchestratorMcp.ts
+8
@@ -667,6 +667,12 @@ export const OrchestratorMcpScheduleTaskInput = Schema.Struct({
667
description: "Default true: runs post in this thread. False: new thread per run.",
668
}),
669
),
670
+ freshSession: Schema.optional(
671
+ Schema.Boolean.annotate({
672
+ description:
673
+ "Runs share one thread but each starts a fresh session without earlier runs' context. Unbound: the first run makes the thread.",
674
+ }),
675
+ ),
676
clientRequestId: Schema.optional(OrchestratorMcpClientRequestId),
677
});
678
export type OrchestratorMcpScheduleTaskInput = typeof OrchestratorMcpScheduleTaskInput.Type;
@@ -688,6 +694,7 @@ export const OrchestratorMcpScheduledTask = Schema.Struct({
694
enabled: Schema.Boolean,
695
projectId: ProjectId,
696
boundThreadId: Schema.NullOr(ThreadId),
697
+ freshSession: Schema.Boolean,
698
schedule: ScheduledTaskSchedule,
699
nextRunAt: Schema.NullOr(IsoDateTime),
700
lastRunStatus: ScheduledTaskRunStatus,
@@ -730,6 +737,7 @@ export const OrchestratorMcpUpdateScheduledTaskInput = Schema.Struct({
737
schedule: Schema.optional(OrchestratorMcpSchedule),
738
enabled: Schema.optional(Schema.Boolean),
739
bindToCurrentThread: Schema.optional(Schema.Boolean),
740
+ freshSession: Schema.optional(Schema.Boolean),
741
});
742
export type OrchestratorMcpUpdateScheduledTaskInput =
743
typeof OrchestratorMcpUpdateScheduledTaskInput.Type;
packages/contracts/src/scheduledTask.ts
+17
@@ -224,6 +224,20 @@ export const ScheduledTaskWebhookEndpoint = Schema.Struct({
224
});
225
export type ScheduledTaskWebhookEndpoint = typeof ScheduledTaskWebhookEndpoint.Type;
226
227
+/**
228
+ * Where runs go. One-thread modes launch their thread on the first run and keep it; `fresh_session`
229
+ * starts each later run in a new provider session there.
230
+ */
231
+export const ScheduledTaskThreadMode = Schema.Literals(["new_thread", "continue", "fresh_session"]);
232
+export type ScheduledTaskThreadMode = typeof ScheduledTaskThreadMode.Type;
233
+
234
+/** Servers before thread modes omit it; their bound tasks continue the conversation. */
235
+export function scheduledTaskThreadMode(
236
+ task: Pick<ScheduledTask, "threadId" | "threadMode">,
237
+): ScheduledTaskThreadMode {
238
+ return task.threadMode ?? (task.threadId === null ? "new_thread" : "continue");
239
+}
240
+
241
export const ScheduledTask = Schema.Struct({
242
id: ScheduledTaskId,
243
title: TrimmedNonEmptyString,
@@ -232,6 +246,7 @@ export const ScheduledTask = Schema.Struct({
246
schedule: ScheduledTaskSchedule,
247
projectId: ProjectId,
248
threadId: Schema.NullOr(ThreadId),
249
+ threadMode: Schema.optional(ScheduledTaskThreadMode),
250
workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
251
modelSelection: ModelSelection,
252
runtimeMode: RuntimeMode,
@@ -271,6 +286,8 @@ export const ScheduledTaskUpsertInput = Schema.Struct({
286
schedule: ScheduledTaskUpsertSchedule,
287
projectId: ProjectId,
288
threadId: Schema.optional(Schema.NullOr(ThreadId)),
289
+ /** Omitted: keep the stored mode, or derive it from `threadId` for a new or rebound task. */
290
+ threadMode: Schema.optional(ScheduledTaskThreadMode),
291
workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
292
modelSelection: ModelSelection,
293
runtimeMode: RuntimeMode,