The best way to control Claude Code, Codex and more from any computer or phone
feat(web,mobile): move a scheduled task to another thread (#31379)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
ABDUL RAHMAN JAMSHID NASSER AL RASHDI committed
Nov 8, 2026 at 13:30 UTC
8e6a7323050ea8d2891f745f7e624e84f9fd8d9a
13 files changed
+652
-54
apps/mobile/src/Stack.tsx
+5
@@ -110,6 +110,7 @@ import {
110
import {
111
ScheduledTaskModelPickerRouteScreen,
112
ScheduledTaskBranchPickerRouteScreen,
113
+ ScheduledTaskThreadPickerRouteScreen,
114
} from "./features/settings/ScheduledTaskPickerScreens";
115
import { SettingsKeyboardRouteScreen } from "./features/settings/SettingsKeyboardRouteScreen";
116
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
@@ -301,6 +302,10 @@ const SETTINGS_SCREENS = {
302
screen: ScheduledTaskBranchPickerRouteScreen,
303
options: settingsPage("Base branch"),
304
}),
305
+ SettingsScheduledTaskThread: createNativeStackScreen({
306
+ screen: ScheduledTaskThreadPickerRouteScreen,
307
+ options: settingsPage("Destination"),
308
+ }),
309
SettingsScheduledTaskModel: createNativeStackScreen({
310
screen: ScheduledTaskModelPickerRouteScreen,
311
options: THREAD_SETTINGS_ROUTE,
apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx
+171
-4
@@ -1,16 +1,37 @@
1
import { useNavigation } from "@react-navigation/native";
2
+import { isListedThreadLineage } from "@t3tools/contracts";
3
import * as Haptics from "expo-haptics";
3
-import { useMemo, useState } from "react";
4
+import { useMemo, useRef, useState } from "react";
5
+import { FlatList, Platform, type TextInputInstance, View } from "react-native";
6
+import { useSafeAreaInsets } from "react-native-safe-area-context";
7
8
import { AppText as Text } from "../../components/ui/AppText";
9
+import { SearchField } from "../../components/ui/SearchField";
10
+import { SelectionRow } from "../../components/ui/SelectionRow";
11
+import { Toolbar } from "../../components/ui/Toolbar";
12
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
13
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
8
-import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
9
-import { useDebouncedValue, usePaginatedBranches } from "../../state/queries";
14
+import { NativeStackScreenOptions } from "../../native/StackHeader";
15
+import { useNativeMailSearchToolbar } from "../../native/use-native-mail-search-toolbar";
16
+import {
17
+ useEnvironmentServerConfig,
18
+ useProjects,
19
+ useVisibleThreadShells,
20
+} from "../../state/entities";
21
+import { useDebouncedValue, usePaginatedBranches, useThreadSearch } from "../../state/queries";
22
+import {
23
+ createNativeMailSearchToolbarItem,
24
+ NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET,
25
+} from "../layout/native-mail-search-toolbar";
26
import { BranchPickerScreen } from "../threads/NewTaskContextPickerScreens";
27
import { ThreadSettingsPickerScreen } from "../threads/ThreadSettingsSheet";
28
import { SettingsScreen } from "./components/SettingsScreen";
13
-import { useScheduledTaskEditor } from "./scheduled-task-editor";
29
+import {
30
+ NEW_THREAD_DESTINATION_LABEL,
31
+ useScheduledTaskDestinationLabel,
32
+ useScheduledTaskEditor,
33
+} from "./scheduled-task-editor";
34
+import { moveDraftToThread, unbindDraftFromThread } from "./scheduledTaskDraft";
35
36
function MissingTaskDraft() {
37
return (
@@ -164,3 +185,149 @@ export function ScheduledTaskBranchPickerRouteScreen() {
185
/>
186
);
187
}
188
+
189
+const THREAD_SEARCH_PLACEHOLDER = "Search threads, including older ones";
190
+
191
+export function ScheduledTaskThreadPickerRouteScreen() {
192
+ const navigation = useNavigation();
193
+ const insets = useSafeAreaInsets();
194
+ const usesNativeMailSearchToolbar = useNativeMailSearchToolbar();
195
+ const searchRef = useRef<TextInputInstance>(null);
196
+ const { editor, setEditor } = useScheduledTaskEditor();
197
+ const environmentId = editor?.environmentId ?? null;
198
+ const projectId = editor?.draft.projectId ?? null;
199
+ const threadId = editor?.draft.threadId ?? null;
200
+ const currentLabel = useScheduledTaskDestinationLabel(environmentId, threadId);
201
+ const shells = useVisibleThreadShells();
202
+ const [query, setQuery] = useState("");
203
+ // Mounts older settled threads matching the query, which shells may leave out.
204
+ useThreadSearch(
205
+ environmentId !== null && projectId !== null ? [environmentId] : [],
206
+ query,
207
+ projectId === null ? { titlesOnly: true } : { titlesOnly: true, projectIds: [projectId] },
208
+ );
209
+
210
+ if (!editor) return <MissingTaskDraft />;
211
+
212
+ const search = query.trim().toLocaleLowerCase();
213
+ const rows = [
214
+ ...(search ? [] : [{ key: "new-thread", title: NEW_THREAD_DESTINATION_LABEL, thread: null }]),
215
+ ...(threadId !== null && currentLabel.toLocaleLowerCase().includes(search)
216
+ ? [{ key: threadId, title: currentLabel, thread: null }]
217
+ : []),
218
+ ...shells
219
+ .filter(
220
+ (thread) =>
221
+ thread.environmentId === environmentId &&
222
+ thread.projectId === projectId &&
223
+ thread.id !== threadId &&
224
+ thread.archivedAt === null &&
225
+ isListedThreadLineage(thread.lineage) &&
226
+ thread.title.toLocaleLowerCase().includes(search),
227
+ )
228
+ .sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))
229
+ .map((thread) => ({
230
+ key: thread.id,
231
+ title: thread.title.trim() || "Untitled thread",
232
+ thread,
233
+ })),
234
+ ];
235
+ const selectedKey = threadId ?? (editor.draft.threadMode === "new_thread" ? "new-thread" : null);
236
+
237
+ return (
238
+ <SettingsScreen title="Destination">
239
+ {Platform.OS === "ios" ? (
240
+ <NativeStackScreenOptions
241
+ options={{
242
+ unstable_headerToolbarItems: usesNativeMailSearchToolbar
243
+ ? () => [
244
+ createNativeMailSearchToolbarItem({
245
+ onSearchTextChange: setQuery,
246
+ placeholder: THREAD_SEARCH_PLACEHOLDER,
247
+ searchTextChangeId: "scheduled-task-thread-search-text",
248
+ showsSearchDismissButton: true,
249
+ }),
250
+ ]
251
+ : undefined,
252
+ headerSearchBarOptions: usesNativeMailSearchToolbar
253
+ ? undefined
254
+ : {
255
+ allowToolbarIntegration: true,
256
+ autoCapitalize: "none",
257
+ hideNavigationBar: false,
258
+ hideWhenScrolling: false,
259
+ obscureBackground: false,
260
+ onCancelButtonPress: () => setQuery(""),
261
+ onChangeText: (event) => setQuery(event.nativeEvent.text),
262
+ placeholder: THREAD_SEARCH_PLACEHOLDER,
263
+ },
264
+ }}
265
+ />
266
+ ) : null}
267
+ {Platform.OS === "ios" && !usesNativeMailSearchToolbar ? (
268
+ <Toolbar placement="bottom">
269
+ <Toolbar.SearchBarSlot />
270
+ </Toolbar>
271
+ ) : null}
272
+ <FlatList
273
+ data={rows}
274
+ keyExtractor={(row) => row.key}
275
+ className="flex-1"
276
+ contentInsetAdjustmentBehavior="automatic"
277
+ automaticallyAdjustKeyboardInsets={Platform.OS === "ios"}
278
+ keyboardDismissMode={Platform.OS === "ios" ? "interactive" : "on-drag"}
279
+ keyboardShouldPersistTaps="handled"
280
+ showsVerticalScrollIndicator={false}
281
+ contentContainerStyle={{
282
+ paddingHorizontal: 16,
283
+ paddingTop: 16,
284
+ paddingBottom: usesNativeMailSearchToolbar
285
+ ? NATIVE_MAIL_SEARCH_TOOLBAR_CONTENT_INSET + 16
286
+ : Math.max(insets.bottom, 16) + 16,
287
+ }}
288
+ ListHeaderComponent={
289
+ Platform.OS === "ios" ? undefined : (
290
+ <View className="pb-4">
291
+ <SearchField
292
+ inputRef={searchRef}
293
+ autoFocus={false}
294
+ accessibilityLabel="Search threads"
295
+ clearAccessibilityLabel="Clear thread search"
296
+ onChangeText={setQuery}
297
+ placeholder={THREAD_SEARCH_PLACEHOLDER}
298
+ value={query}
299
+ />
300
+ </View>
301
+ )
302
+ }
303
+ ListEmptyComponent={
304
+ <Text className="p-5 text-center text-sm text-foreground-muted">No matching threads</Text>
305
+ }
306
+ renderItem={({ item, index }) => (
307
+ <SelectionRow
308
+ title={item.title}
309
+ selected={item.key === selectedKey}
310
+ isFirst={index === 0}
311
+ isLast={index === rows.length - 1}
312
+ onPress={() => {
313
+ void Haptics.selectionAsync();
314
+ if (item.key !== selectedKey) {
315
+ setEditor((current) =>
316
+ current
317
+ ? {
318
+ ...current,
319
+ draft: item.thread
320
+ ? moveDraftToThread(current.draft, item.thread)
321
+ : { ...unbindDraftFromThread(current.draft), threadMode: "new_thread" },
322
+ }
323
+ : current,
324
+ );
325
+ }
326
+ navigation.goBack();
327
+ }}
328
+ />
329
+ )}
330
+ />
331
+ </SettingsScreen>
332
+ );
333
+}
apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx
+40
-20
@@ -72,14 +72,16 @@ import { SettingsScreen } from "./components/SettingsScreen";
72
import { SettingsSection } from "./components/SettingsSection";
73
import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
74
import {
75
+ changeDraftProject,
76
editDraft,
77
parseIntervalMinutes,
78
scheduledTaskDefaultModel,
79
scheduleFromDraft,
80
+ unbindDraftFromThread,
81
type ScheduledTaskDraft as Draft,
82
} from "./scheduledTaskDraft";
83
import { settingsTargetsForProject } from "./settings-environment-filter.logic";
82
-import { useScheduledTaskEditor } from "./scheduled-task-editor";
84
+import { useScheduledTaskDestinationLabel, useScheduledTaskEditor } from "./scheduled-task-editor";
85
import {
86
discardScheduledTaskEditor,
87
markScheduledTaskEditorSaved,
@@ -96,6 +98,7 @@ type ScheduledTaskRoutes = {
98
SettingsScheduledTaskEdit: undefined;
99
SettingsScheduledTaskModel: undefined;
100
SettingsScheduledTaskBranch: undefined;
101
+ SettingsScheduledTaskThread: undefined;
102
};
103
104
const DAYS = [
@@ -663,6 +666,7 @@ function TaskForm({
666
)
667
.sort((left, right) => Number(right.pinnedAt != null) - Number(left.pinnedAt != null));
668
const config = useEnvironmentServerConfig(environmentId);
669
+ const destinationLabel = useScheduledTaskDestinationLabel(environmentId, draft.threadId);
670
const modelOptions = buildModelOptions(config, null, undefined, draft.projectId);
671
// Existing webhook tasks keep the option so they can still switch to a timer.
672
const webhookDenial = managedCapabilityDenial(config?.managedPolicy, "webhookTasks");
@@ -766,7 +770,7 @@ function TaskForm({
770
modelSelection: draft.modelSelection,
771
schedule,
772
enabled: draft.enabled,
769
- threadId: draft.task?.threadId ?? null,
773
+ threadId: draft.threadId,
774
...(offersThreadModes ? { threadMode: draft.threadMode } : {}),
775
workspaceStrategy:
776
draft.workspace === "root"
@@ -879,8 +883,7 @@ function TaskForm({
883
draft.modelSelection.instanceId,
884
));
885
setDraft({
882
- ...draft,
883
- projectId: project.id,
886
+ ...changeDraftProject(draft, project.id),
887
modelSelection: keepsExplicitModel
888
? draft.modelSelection
889
: scheduledTaskDefaultModel(config, project),
@@ -905,19 +908,21 @@ function TaskForm({
908
/>
909
</SettingsSection>
910
908
- {offersThreadModes ? (
909
- <SettingsSection
910
- title="Destination"
911
- footer={
912
- draft.threadMode === "new_thread"
913
- ? "Each run starts a new thread."
914
- : `${
915
- draft.threadMode === "continue"
916
- ? "Runs continue one conversation."
917
- : "Runs share one thread, each in a fresh session without earlier runs' context."
918
- } The first run starts the thread. Deleting it also deletes this task.`
919
- }
920
- >
911
+ <SettingsSection
912
+ title="Destination"
913
+ footer={
914
+ draft.threadMode === "new_thread"
915
+ ? "Each run starts a new thread."
916
+ : `${
917
+ draft.threadMode === "continue"
918
+ ? "Runs continue one conversation."
919
+ : "Runs share one thread, each in a fresh session without earlier runs' context."
920
+ }${
921
+ draft.threadId === null ? " The first run starts the thread." : ""
922
+ } Deleting it also deletes this task.`
923
+ }
924
+ >
925
+ {offersThreadModes ? (
926
<SelectRow
927
label="Runs go to"
928
value={THREAD_MODE_LABELS[draft.threadMode]}
@@ -929,12 +934,27 @@ function TaskForm({
934
}),
935
)}
936
onSelect={(id) => {
932
- if (id === "new_thread" || id === "continue" || id === "fresh_session")
937
+ if (id === "new_thread")
938
+ setDraft({ ...unbindDraftFromThread(draft), threadMode: id });
939
+ else if (id === "continue" || id === "fresh_session")
940
setDraft({ ...draft, threadMode: id });
941
}}
942
/>
936
- </SettingsSection>
937
- ) : null}
943
+ ) : null}
944
+ {!offersThreadModes || draft.threadMode !== "new_thread" ? (
945
+ <PickerRow
946
+ label="Thread"
947
+ borderTop={offersThreadModes}
948
+ value={
949
+ draft.threadId === null && draft.threadMode !== "new_thread"
950
+ ? "Started by the first run"
951
+ : destinationLabel
952
+ }
953
+ onPress={() => navigation.navigate("SettingsScheduledTaskThread")}
954
+ disabled={!draft.projectId || saving || dictationPending || environmentUnavailable}
955
+ />
956
+ ) : null}
957
+ </SettingsSection>
958
959
<SettingsSection title="Workspace">
960
<SelectRow
apps/mobile/src/features/settings/scheduled-task-editor.tsx
+25
-2
@@ -1,8 +1,11 @@
1
import { useAtomValue } from "@effect/atom-react";
2
-import type { EnvironmentId } from "@t3tools/contracts";
2
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3
+import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
import { useMemo, useCallback, type Dispatch, type SetStateAction } from "react";
5
5
-import { useProjects, useServerConfigs } from "../../state/entities";
6
+import { useProjects, useServerConfigs, useThreadShell } from "../../state/entities";
7
+import { useEnvironmentQuery } from "../../state/query";
8
+import { threadFamilies } from "../../state/threads";
9
import { createDraft, scheduledTaskDefaultModel } from "./scheduledTaskDraft";
10
import { useSettingsEnvironmentFilter } from "./settings-environment-filter";
11
import { settingsTargetsForProject } from "./settings-environment-filter.logic";
@@ -16,6 +19,26 @@ import {
19
type ScheduledTaskEditor,
20
} from "./scheduled-task-editor-state";
21
22
+export const NEW_THREAD_DESTINATION_LABEL = "New thread each run";
23
+
24
+export function useScheduledTaskDestinationLabel(
25
+ environmentId: EnvironmentId | null,
26
+ threadId: ThreadId | null,
27
+): string {
28
+ const ref =
29
+ environmentId === null || threadId === null ? null : scopeThreadRef(environmentId, threadId);
30
+ const shell = useThreadShell(ref);
31
+ // The shell can omit older settled threads; their family read still carries the title.
32
+ const family = useEnvironmentQuery(
33
+ ref !== null && shell === null
34
+ ? threadFamilies.familyAtom(ref.environmentId, ref.threadId)
35
+ : null,
36
+ );
37
+ const thread = shell ?? family.data?.threads.find((row) => row.id === threadId);
38
+ if (ref === null) return NEW_THREAD_DESTINATION_LABEL;
39
+ return thread?.title.trim() || `Thread ${ref.threadId}`;
40
+}
41
+
42
/** The form draft lives in an atom, so it survives while its native picker routes are on top. */
43
export function useScheduledTaskEditor() {
44
const { selectedTargets, selectedProjectKey, projectGroups } = useSettingsEnvironmentFilter();
apps/mobile/src/features/settings/scheduledTaskDraft.ts
+37
@@ -8,6 +8,7 @@ import type {
8
ScheduledTaskThreadMode,
9
ScheduledTaskUpsertSchedule,
10
ScheduledTaskWebhookSignature,
11
+ ThreadId,
12
} from "@t3tools/contracts";
13
14
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
@@ -202,6 +203,7 @@ export type ScheduledTaskDraft = {
203
readonly title: string;
204
readonly prompt: string;
205
readonly projectId: ProjectId | null;
206
+ readonly threadId: ThreadId | null;
207
readonly modelSelection: ModelSelection | null;
208
readonly modelSelectionIsExplicit: boolean;
209
readonly schedule: ScheduleDraft;
@@ -219,6 +221,7 @@ function draftSignature(draft: ScheduledTaskDraft): string {
221
draft.title,
222
draft.prompt,
223
draft.projectId,
224
+ draft.threadId,
225
draft.modelSelection?.instanceId,
226
draft.modelSelection?.model,
227
[...(draft.modelSelection?.options ?? [])]
@@ -251,6 +254,38 @@ export function hasScheduledTaskDraftChanges(
254
return draftSignature(initial) !== draftSignature(current);
255
}
256
257
+export function moveDraftToThread(
258
+ draft: ScheduledTaskDraft,
259
+ thread: { readonly id: ThreadId; readonly projectId: ProjectId },
260
+): ScheduledTaskDraft {
261
+ return {
262
+ ...draft,
263
+ threadId: thread.id,
264
+ projectId: thread.projectId,
265
+ threadMode: draft.threadMode === "new_thread" ? "continue" : draft.threadMode,
266
+ };
267
+}
268
+
269
+/** Leaves the thread but keeps the mode. Matches MCP: new threads stay out of the shared checkout. */
270
+export function unbindDraftFromThread(draft: ScheduledTaskDraft): ScheduledTaskDraft {
271
+ if (draft.threadId === null) return draft;
272
+ return {
273
+ ...draft,
274
+ threadId: null,
275
+ ...(draft.workspace === "root"
276
+ ? { workspace: "worktree" as const, startFromOrigin: true }
277
+ : {}),
278
+ };
279
+}
280
+
281
+export function changeDraftProject(
282
+ draft: ScheduledTaskDraft,
283
+ projectId: ProjectId,
284
+): ScheduledTaskDraft {
285
+ if (projectId === draft.projectId) return draft;
286
+ return { ...unbindDraftFromThread(draft), projectId };
287
+}
288
+
289
export function createDraft(
290
projectId: ProjectId | null,
291
modelSelection: ModelSelection | null,
@@ -260,6 +295,7 @@ export function createDraft(
295
title: "",
296
prompt: "",
297
projectId,
298
+ threadId: null,
299
modelSelection,
300
modelSelectionIsExplicit: false,
301
schedule: DEFAULT_SCHEDULE,
@@ -279,6 +315,7 @@ export function editDraft(task: ScheduledTask): ScheduledTaskDraft {
315
title: task.title,
316
prompt: task.prompt,
317
projectId: task.projectId,
318
+ threadId: task.threadId,
319
modelSelection: task.modelSelection,
320
modelSelectionIsExplicit: true,
321
schedule: scheduleDraftForTask(task),
apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+10
-1
@@ -412,7 +412,11 @@ it.effect(
412
);
413
return Effect.gen(function* () {
414
const tasks = yield* ScheduledTasks.ScheduledTaskService;
415
- const threadId = ThreadId.make("thread:missing");
415
+ const launches = yield* ThreadLaunch.ThreadLaunchService;
416
+ const threads = yield* ThreadManagement.ThreadManagementService;
417
+ const { threadId } = yield* launches.launch(
418
+ launchInput({ command: "command:missing", thread: "thread:missing" }),
419
+ );
420
const { task } = yield* tasks.upsert({
421
title: "Daily audit",
422
prompt: "Audit performance and crashes.",
@@ -427,6 +431,11 @@ it.effect(
431
createdBy: "user",
432
creationSource: "web",
433
});
434
+ yield* threads.dispatch({
435
+ type: "thread.delete",
436
+ commandId: CommandId.make("command:missing:delete"),
437
+ threadId,
438
+ });
439
const result = yield* tasks.runNow({ id: task.id });
440
assert.equal(result.task.lastRunStatus, "failed");
441
assert.isNull(result.threadId);
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+18
-8
@@ -330,7 +330,16 @@ const layerScheduledTasksTest = ScheduledTaskService.layer.pipe(
330
Layer.mergeAll(
331
ManagedPolicy.layerTest(),
332
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
333
- Layer.mock(ThreadManagementService.ThreadManagementService)({}),
333
+ // The orchestrator depends on this layer, so read the shell from its projection.
334
+ Layer.unwrap(
335
+ ProjectionStore.ProjectionStoreV2.pipe(
336
+ Effect.map(({ getThreadShell }) =>
337
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
338
+ getThreadShell: (threadId) => getThreadShell(threadId).pipe(Effect.orDie),
339
+ }),
340
+ ),
341
+ ),
342
+ ).pipe(Layer.provide(ProjectionStore.layer)),
343
Layer.mock(SecretRequests.SecretRequests)({}),
344
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
345
namedProjectsRoot: "/projects",
@@ -402,6 +411,7 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
411
const projectId = ProjectId.make(`automation-delete-project:${deletion}`);
412
const threadId = ThreadId.make(`automation-delete-thread:${deletion}`);
413
const otherThreadId = ThreadId.make(`automation-surviving-thread:${deletion}`);
414
+ const otherProjectId = ProjectId.make("automation-other-project");
415
yield* projects.create({
416
commandId: CommandId.make(`automation-create-project:${deletion}`),
417
projectId,
@@ -415,7 +425,7 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
425
createdBy: "user",
426
creationSource: "web",
427
threadId: id,
418
- projectId: id === threadId ? projectId : ProjectId.make("automation-other-project"),
428
+ projectId: id === threadId ? projectId : otherProjectId,
429
title: "Automation target",
430
modelSelection,
431
runtimeMode: "full-access",
@@ -433,7 +443,7 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
443
prompt: "Check orchestration progress",
444
enabled: !webhook,
445
schedule: webhook ? { type: "webhook" } : { type: "interval", everyMs: 60_000 },
436
- projectId,
446
+ projectId: target === otherThreadId ? otherProjectId : projectId,
447
threadId: target,
448
workspaceStrategy: { type: "root" },
449
modelSelection,
@@ -7191,11 +7201,6 @@ it.layer(layerScratchPromotionTest)("turning a No project thread into a project"
7201
const threadId = yield* createThread("main", folder);
7202
const siblingId = yield* createThread("sibling", folder);
7203
const otherId = yield* createThread("other", `${SCRATCH_ROOT}/2026-01-01-elsewhere`);
7194
- yield* orchestrator.dispatch({
7195
- type: "thread.archive",
7196
- commandId: CommandId.make("promotion-moves-sibling-archive"),
7197
- threadId: siblingId,
7198
- });
7204
const { task } = yield* tasks.upsert({
7205
id: ScheduledTaskId.make("promotion-moves-bound"),
7206
title: "Bound",
@@ -7211,6 +7216,11 @@ it.layer(layerScratchPromotionTest)("turning a No project thread into a project"
7216
createdBy: "user",
7217
creationSource: "web",
7218
});
7219
+ yield* orchestrator.dispatch({
7220
+ type: "thread.archive",
7221
+ commandId: CommandId.make("promotion-moves-sibling-archive"),
7222
+ threadId: siblingId,
7223
+ });
7224
7225
const { projectId } = yield* promotion.promote({ threadId });
7226
apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+105
-7
@@ -8,6 +8,8 @@ import {
8
ProviderInstanceId,
9
ScheduledTaskError,
10
ScheduledTaskId,
11
+ type ScheduledTaskUpsertInput,
12
+ SecretRef,
13
ThreadId,
14
} from "@t3tools/contracts";
15
import * as DateTime from "effect/DateTime";
@@ -34,6 +36,11 @@ import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
36
37
const isScheduledTaskError = Schema.is(ScheduledTaskError);
38
39
+const threadShell = (
40
+ projectId: ProjectId,
41
+ state: { archivedAt?: string | null; deletedAt?: string | null } = {},
42
+) => ({ projectId, archivedAt: null, deletedAt: null, ...state }) as never;
43
+
44
const insertRow = (
45
sql: SqlClient.SqlClient,
46
row: {
@@ -358,6 +365,7 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea
365
Effect.andThen(Deferred.await(release)),
366
Effect.andThen(Effect.die("test dispatch failure")),
367
),
368
+ getThreadShell: () => Effect.succeed(threadShell(ProjectId.make("project:test"))),
369
}),
370
Layer.mock(SecretRequests.SecretRequests)({}),
371
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
@@ -415,8 +423,9 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
423
const scratch = ProjectId.make("project:scratch");
424
const promoted = ProjectId.make("project:promoted");
425
const sends = yield* Ref.make<Array<{ projectId: ProjectId; commandId: string }>>([]);
418
- // Rebind lands first, then the promotion commits between the shell read and the retry.
419
- const shellProjects = yield* Ref.make([scratch, promoted]);
426
+ // Saving reads it first. Then the rebind lands, and the promotion commits between the shell
427
+ // read and the retry.
428
+ const shellProjects = yield* Ref.make([promoted, scratch, promoted]);
429
const layer = ScheduledTaskService.layer.pipe(
430
Layer.provide(
431
Layer.mergeAll(
@@ -440,10 +449,7 @@ it.effect("a bound run follows its thread when promotion moves it mid-send", ()
449
),
450
),
451
getThreadShell: () =>
443
- Ref.modify(shellProjects, ([next, ...rest]) => [
444
- { projectId: next ?? promoted } as never,
445
- rest,
446
- ]),
452
+ Ref.modify(shellProjects, ([next, ...rest]) => [threadShell(next ?? promoted), rest]),
453
}),
454
Layer.mock(SecretRequests.SecretRequests)({}),
455
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
@@ -693,7 +699,9 @@ it.effect("refuses saving an enabled task above the policy ceiling", () =>
699
limits: { maxRuntimeMode: "auto-accept-edits" },
700
}),
701
Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
696
- Layer.mock(ThreadManagementService.ThreadManagementService)({}),
702
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
703
+ getThreadShell: () => Effect.succeed(threadShell(ProjectId.make("project:test"))),
704
+ }),
705
Layer.mock(SecretRequests.SecretRequests)({}),
706
Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
707
namedProjectsRoot: "/projects",
@@ -750,6 +758,96 @@ it.effect("refuses saving an enabled task above the policy ceiling", () =>
758
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
759
);
760
761
+it.effect("checks a task's destination thread only when the destination changes", () =>
762
+ Effect.gen(function* () {
763
+ const project = ProjectId.make("project:test");
764
+ const otherProject = ProjectId.make("project:other");
765
+ const destination = ThreadId.make("thread:destination");
766
+ const archivedAt = "2026-11-05T00:00:00.000Z";
767
+ const shells = yield* Ref.make<ReadonlyMap<ThreadId, never>>(
768
+ new Map([
769
+ [destination, threadShell(project)],
770
+ [ThreadId.make("thread:archived"), threadShell(project, { archivedAt })],
771
+ [ThreadId.make("thread:deleted"), threadShell(project, { deletedAt: archivedAt })],
772
+ [ThreadId.make("thread:other-project"), threadShell(otherProject)],
773
+ ]),
774
+ );
775
+ const consumed = yield* Ref.make(0);
776
+ const layer = ScheduledTaskService.layer.pipe(
777
+ Layer.provide(
778
+ Layer.mergeAll(
779
+ ManagedPolicy.layerTest(),
780
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
781
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
782
+ getThreadShell: (threadId) =>
783
+ Ref.get(shells).pipe(Effect.map((all) => all.get(threadId) ?? null)),
784
+ }),
785
+ Layer.mock(SecretRequests.SecretRequests)({
786
+ consume: () => Ref.update(consumed, (count) => count + 1).pipe(Effect.as("secret")),
787
+ }),
788
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
789
+ namedProjectsRoot: "/projects",
790
+ isScratchProject: () => Effect.succeed(false),
791
+ }),
792
+ NodeCrypto.layer,
793
+ Scheduler.layer,
794
+ ),
795
+ ),
796
+ );
797
+ yield* Effect.gen(function* () {
798
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
799
+ const id = ScheduledTaskId.make("task:destination");
800
+ const save = (
801
+ threadId: ThreadId,
802
+ schedule: ScheduledTaskUpsertInput["schedule"] = { type: "interval", everyMs: 60_000 },
803
+ ) =>
804
+ service.upsert({
805
+ id,
806
+ title: "Follow up",
807
+ prompt: "Check progress",
808
+ enabled: true,
809
+ schedule,
810
+ projectId: project,
811
+ threadId,
812
+ workspaceStrategy: { type: "root" },
813
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
814
+ runtimeMode: "full-access",
815
+ interactionMode: "default",
816
+ });
817
+
818
+ for (const [threadId, message] of [
819
+ ["thread:missing", "That thread no longer exists."],
820
+ ["thread:deleted", "That thread no longer exists."],
821
+ ["thread:archived", "That thread is archived. Unarchive it or pick another destination."],
822
+ ["thread:other-project", "That thread belongs to a different project."],
823
+ ] as const) {
824
+ const refused = yield* save(ThreadId.make(threadId)).pipe(Effect.flip);
825
+ assert.equal(refused.message, message);
826
+ }
827
+ assert.lengthOf((yield* service.list()).tasks, 0);
828
+
829
+ // A rejected save must not burn a one-shot secret.
830
+ yield* save(ThreadId.make("thread:missing"), {
831
+ type: "webhook",
832
+ signature: {
833
+ header: "x-signature",
834
+ encoding: "hex",
835
+ prefix: "",
836
+ secretRef: SecretRef.make("secret-ref:00000000000000000000000000000001"),
837
+ },
838
+ }).pipe(Effect.flip);
839
+ assert.equal(yield* Ref.get(consumed), 0);
840
+
841
+ yield* save(destination);
842
+ // A task whose thread was archived later stays editable.
843
+ yield* Ref.update(shells, (all) =>
844
+ new Map(all).set(destination, threadShell(project, { archivedAt })),
845
+ );
846
+ assert.equal((yield* save(destination)).task.threadId, destination);
847
+ }).pipe(Effect.provide(layer));
848
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
849
+);
850
+
851
it.effect("a run interrupted right after it reserves the task does not block the next run", () =>
852
Effect.gen(function* () {
853
const launches = yield* Ref.make(0);
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+28
@@ -1253,6 +1253,30 @@ export const layer = Layer.effect(
1253
}),
1254
);
1255
1256
+ const requireDestinationThread = Effect.fn("ScheduledTaskService.requireDestinationThread")(
1257
+ function* (threadId: ThreadId, projectId: ProjectId, taskId: ScheduledTaskId) {
1258
+ const thread = yield* threadManagement
1259
+ .getThreadShell(threadId)
1260
+ .pipe(
1261
+ Effect.mapError((cause) =>
1262
+ taskError("Could not read the destination thread.", { taskId, cause }),
1263
+ ),
1264
+ );
1265
+ if (thread === null || thread.deletedAt !== null) {
1266
+ return yield* taskError("That thread no longer exists.", { taskId });
1267
+ }
1268
+ if (thread.archivedAt !== null) {
1269
+ return yield* taskError(
1270
+ "That thread is archived. Unarchive it or pick another destination.",
1271
+ { taskId },
1272
+ );
1273
+ }
1274
+ if (thread.projectId !== projectId) {
1275
+ return yield* taskError("That thread belongs to a different project.", { taskId });
1276
+ }
1277
+ },
1278
+ );
1279
+
1280
const upsert: ScheduledTaskService["Service"]["upsert"] = Effect.fn(
1281
"ScheduledTaskService.upsert",
1282
)(function* (input) {
@@ -1291,6 +1315,10 @@ export const layer = Layer.effect(
1315
existingTask.projectId !== input.projectId &&
1316
keptThreadId === existingTask.threadId;
1317
const threadId = threadMode === "new_thread" || movedOffThread ? null : keptThreadId;
1318
+ // An unchanged destination is not rechecked, so a task on an archived thread stays editable.
1319
+ if (threadId !== null && threadId !== existingTask?.threadId) {
1320
+ yield* requireDestinationThread(threadId, input.projectId, id);
1321
+ }
1322
// Refused on save rather than at run time; a disabled task can still be saved, so one
1323
// stored above the ceiling can be turned off before its mode is lowered. A task bound to a
1324
// thread runs in that thread's mode, which the orchestrator checks instead. Checked before
apps/web/src/components/settings/ScheduledTasksSettings.tsx
+137
-9
@@ -2,9 +2,11 @@ import { useAtomValue } from "@effect/atom-react";
2
import { connectionStatusTitle } from "@t3tools/client-runtime/connection";
3
import { AsyncResult } from "effect/reactivity";
4
import {
5
+ ChevronDownIcon,
6
Clock3Icon,
7
CopyIcon,
8
InboxIcon,
9
+ MessageSquareIcon,
10
MoreHorizontalIcon,
11
PencilIcon,
12
PlayIcon,
@@ -61,10 +63,16 @@ import {
63
useEnvironmentHttpBaseUrl,
64
type EnvironmentPresentation,
65
} from "../../state/environments";
64
-import { useProjects, useQuietThreadShell, useThreadShell } from "../../state/entities";
66
+import {
67
+ useProjects,
68
+ useQuietThreadShell,
69
+ useThreadShell,
70
+ useVisibleThreadShells,
71
+} from "../../state/entities";
72
import { buildThreadRouteParams } from "../../threadRoutes";
73
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
74
import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
75
+import { useThreadSearch } from "../../state/queries";
76
import { formatEnvironmentQueryError, useEnvironmentQuery } from "../../state/query";
77
import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
78
import { threadFamilies } from "../../state/threads";
@@ -87,7 +95,10 @@ import { SettingsGroup } from "./SettingsGroup";
95
import { settingsScopeEnvironmentLabel, settingsScopeEnvironmentLabels } from "./settingsScopeAxis";
96
import {
97
WEBHOOK_SIGNATURE_DEFAULTS,
98
+ changeDraftProject,
99
+ moveDraftToThread,
100
scheduleDraftErrors,
101
+ scheduledTaskDestinationThreads,
102
toDateTimeLocalValue,
103
webhookDeliveryLabel,
104
defaultScheduledTaskProjectId,
@@ -95,6 +106,7 @@ import {
106
scheduleFromDraft,
107
scheduledTaskDefaultModel,
108
taskToDraft,
109
+ unbindDraftFromThread,
110
type DraftState,
111
type ScheduleMode,
112
type WorkspaceMode,
@@ -106,6 +118,15 @@ import { Empty, EmptyHeader, EmptyTitle, EmptyDescription, EmptyMedia } from "..
118
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
119
import { Badge } from "../ui/badge";
120
import { Button } from "../ui/button";
121
+import {
122
+ Combobox,
123
+ ComboboxEmpty,
124
+ ComboboxItem,
125
+ ComboboxList,
126
+ ComboboxPopup,
127
+ ComboboxSearchInput,
128
+ ComboboxTrigger,
129
+} from "../ui/combobox";
130
import {
131
Dialog,
132
DialogClose,
@@ -133,6 +154,9 @@ const WEEKDAY_ORDER = [1, 2, 3, 4, 5, 6, 0] as const;
154
const WEEKDAY_LABELS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
155
const WEEKDAY_SHORT = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"] as const;
156
157
+// Thread ids are trimmed, so the leading space keeps this from matching one.
158
+const NEW_THREAD_DESTINATION = " new-thread";
159
+
160
const WORKSPACE_MODE_LABELS: Record<WorkspaceMode, string> = {
161
worktree: "Create a new worktree",
162
root: "Use the project checkout",
@@ -1176,16 +1200,24 @@ const THREAD_MODE_LABELS: Record<ScheduledTaskThreadMode, string> = {
1200
1201
function ScheduledTaskDestination({
1202
environmentId,
1203
+ projectId,
1204
threadId,
1205
threadMode,
1206
+ disabled,
1207
+ onSelect,
1208
onThreadModeChange,
1209
}: {
1210
readonly environmentId: EnvironmentId;
1211
+ readonly projectId: string;
1212
readonly threadId: ThreadId | null;
1213
readonly threadMode: ScheduledTaskThreadMode;
1214
+ readonly disabled: boolean;
1215
+ readonly onSelect: (thread: { id: ThreadId; projectId: ProjectId } | null) => void;
1216
/** Absent on servers that predate thread modes. */
1217
readonly onThreadModeChange: ((mode: ScheduledTaskThreadMode) => void) | undefined;
1218
}) {
1219
+ const [open, setOpen] = useState(false);
1220
+ const [query, setQuery] = useState("");
1221
const ref = threadId === null ? null : scopeThreadRef(environmentId, threadId);
1222
const shell = useThreadShell(ref);
1223
// The shell can omit older settled threads; their family read still carries the title.
@@ -1193,11 +1225,38 @@ function ScheduledTaskDestination({
1225
ref !== null && shell === null ? threadFamilies.familyAtom(environmentId, ref.threadId) : null,
1226
);
1227
const thread = shell ?? family.data?.threads.find((row) => row.id === threadId);
1196
- const bound = ref !== null && threadMode !== "new_thread";
1228
+ const currentLabel =
1229
+ ref !== null
1230
+ ? thread?.title.trim() || `Thread ${ref.threadId}`
1231
+ : threadMode === "new_thread"
1232
+ ? "New thread each run"
1233
+ : "Started by the first run";
1234
+ const shells = useVisibleThreadShells(open);
1235
+ // Mounts older settled threads matching the query, which shells may leave out.
1236
+ useThreadSearch(open && projectId ? [environmentId] : [], query, {
1237
+ titlesOnly: true,
1238
+ projectIds: [projectId as ProjectId],
1239
+ });
1240
+ const threads = scheduledTaskDestinationThreads(shells, {
1241
+ environmentId,
1242
+ projectId,
1243
+ currentThreadId: threadId,
1244
+ query,
1245
+ });
1246
+ const search = query.trim().toLocaleLowerCase();
1247
+ const items: ReadonlyArray<string> = [
1248
+ ...(search ? [] : [NEW_THREAD_DESTINATION]),
1249
+ ...(threadId !== null && currentLabel.toLocaleLowerCase().includes(search) ? [threadId] : []),
1250
+ ...threads.map((row) => row.id),
1251
+ ];
1252
+ const handleOpenChange = (next: boolean) => {
1253
+ setOpen(next);
1254
+ if (!next) setQuery("");
1255
+ };
1256
const detail =
1257
threadMode === "new_thread"
1258
? "Each run starts a new thread with the workspace and model below."
1200
- : !bound
1259
+ : ref === null
1260
? threadMode === "continue"
1261
? "The first run starts a thread with the workspace and model below. Later runs continue that conversation."
1262
: "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."
@@ -1223,10 +1282,66 @@ function ScheduledTaskDestination({
1282
</SelectPopup>
1283
</Select>
1284
) : null}
1285
+ {!onThreadModeChange || threadMode !== "new_thread" ? (
1286
+ <Combobox
1287
+ items={items}
1288
+ filteredItems={items}
1289
+ filter={null}
1290
+ autoHighlight
1291
+ open={open && !disabled}
1292
+ onOpenChange={handleOpenChange}
1293
+ value={threadId ?? (threadMode === "new_thread" ? NEW_THREAD_DESTINATION : null)}
1294
+ onValueChange={(value) => {
1295
+ if (value === NEW_THREAD_DESTINATION) {
1296
+ onSelect(null);
1297
+ handleOpenChange(false);
1298
+ return;
1299
+ }
1300
+ const picked = threads.find((row) => row.id === value);
1301
+ if (picked) onSelect(picked);
1302
+ handleOpenChange(false);
1303
+ }}
1304
+ >
1305
+ <ComboboxTrigger
1306
+ id={
1307
+ onThreadModeChange
1308
+ ? "scheduled-task-destination-thread"
1309
+ : "scheduled-task-destination"
1310
+ }
1311
+ aria-label={onThreadModeChange ? "Destination thread" : undefined}
1312
+ disabled={disabled}
1313
+ render={<Button variant="outline" size="sm" />}
1314
+ className="w-full justify-between"
1315
+ >
1316
+ <MessageSquareIcon className="size-3.5 shrink-0 text-muted-foreground" />
1317
+ <span className="min-w-0 flex-1 truncate text-left">{currentLabel}</span>
1318
+ <ChevronDownIcon className="size-3.5 shrink-0 text-muted-foreground" />
1319
+ </ComboboxTrigger>
1320
+ <ComboboxPopup align="start" side="bottom" className="w-80">
1321
+ <ComboboxSearchInput
1322
+ aria-label="Search threads"
1323
+ placeholder="Search all threads..."
1324
+ value={query}
1325
+ onChange={(event) => setQuery(event.target.value)}
1326
+ />
1327
+ <ComboboxEmpty>No threads found.</ComboboxEmpty>
1328
+ <ComboboxList className="max-h-72">
1329
+ {items.map((value, index) => (
1330
+ <ComboboxItem key={value} index={index} value={value}>
1331
+ <span className="block truncate">
1332
+ {value === NEW_THREAD_DESTINATION
1333
+ ? "New thread each run"
1334
+ : value === threadId
1335
+ ? currentLabel
1336
+ : threads.find((row) => row.id === value)?.title || "Untitled thread"}
1337
+ </span>
1338
+ </ComboboxItem>
1339
+ ))}
1340
+ </ComboboxList>
1341
+ </ComboboxPopup>
1342
+ </Combobox>
1343
+ ) : null}
1344
<div className="space-y-1 text-sm">
1227
- {bound ? (
1228
- <p className="wrap-anywhere">{thread?.title.trim() || `Thread ${ref.threadId}`}</p>
1229
- ) : null}
1345
<p className="text-muted-foreground">{detail}</p>
1346
{threadMode !== "new_thread" ? (
1347
<p className="text-muted-foreground">Deleting the thread also deletes this task.</p>
@@ -1471,7 +1586,7 @@ function ScheduledTaskEditorForm({
1586
if (!next) return;
1587
setEnvironmentId(next.environmentId);
1588
setDraft((current) => ({
1474
- ...current,
1589
+ ...unbindDraftFromThread(current),
1590
projectId: defaultScheduledTaskProjectId(projectsOn(next.environmentId), scope),
1591
modelKey: "",
1592
baseModelSelection: null,
@@ -1547,11 +1662,24 @@ function ScheduledTaskEditorForm({
1662
1663
<ScheduledTaskDestination
1664
environmentId={environmentId}
1665
+ projectId={selectedProjectId}
1666
threadId={draft.threadId ? (draft.threadId as ThreadId) : null}
1667
threadMode={draft.threadMode}
1668
+ disabled={saving || !connected}
1669
+ onSelect={(thread) =>
1670
+ setDraft((current) =>
1671
+ thread === null
1672
+ ? { ...unbindDraftFromThread(current), threadMode: "new_thread" }
1673
+ : moveDraftToThread(current, thread),
1674
+ )
1675
+ }
1676
onThreadModeChange={
1677
offersThreadModes
1554
- ? (threadMode) => setDraft((current) => ({ ...current, threadMode }))
1678
+ ? (threadMode) =>
1679
+ setDraft((current) => ({
1680
+ ...(threadMode === "new_thread" ? unbindDraftFromThread(current) : current),
1681
+ threadMode,
1682
+ }))
1683
: undefined
1684
}
1685
/>
@@ -1561,7 +1689,7 @@ function ScheduledTaskEditorForm({
1689
<Select
1690
value={selectedProjectId}
1691
onValueChange={(projectId) =>
1564
- setDraft((current) => ({ ...current, projectId: projectId ?? "" }))
1692
+ setDraft((current) => changeDraftProject(current, projectId ?? ""))
1693
}
1694
>
1695
<SelectTrigger size="sm" id="scheduled-task-project">
apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts
+17
@@ -6,6 +6,7 @@ import {
6
ProviderInstanceId,
7
ScheduledTaskId,
8
type ScheduledTask,
9
+ ThreadId,
10
} from "@t3tools/contracts";
11
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
12
@@ -22,6 +23,7 @@ import {
23
matchesScheduledTaskScope,
24
scheduleFromDraft,
25
taskToDraft,
26
+ unbindDraftFromThread,
27
} from "./scheduledTasksSettings.logic";
28
29
const laptopId = EnvironmentId.make("laptop");
@@ -170,6 +172,21 @@ describe("editing scheduled task branch settings", () => {
172
});
173
});
174
175
+describe("scheduled task destination", () => {
176
+ it("unbinding leaves the shared checkout for a new worktree from the remote", () => {
177
+ const rootBound = taskToDraft({
178
+ ...legacyTask,
179
+ threadId: ThreadId.make("thread:bound"),
180
+ workspaceStrategy: { type: "root" },
181
+ });
182
+ expect(unbindDraftFromThread(rootBound)).toMatchObject({
183
+ threadId: "",
184
+ workspaceMode: "worktree",
185
+ startFromOrigin: true,
186
+ });
187
+ });
188
+});
189
+
190
describe("one-time scheduled tasks", () => {
191
afterEach(() => vi.unstubAllEnvs());
192
apps/web/src/components/settings/scheduledTasksSettings.logic.ts
+56
-1
@@ -1,4 +1,4 @@
1
-import { isWebhookDedupeTemplate } from "@t3tools/contracts";
1
+import { isListedThreadLineage, isWebhookDedupeTemplate } from "@t3tools/contracts";
2
import {
3
EnvironmentId,
4
MAX_WEBHOOK_DELIVERY_AGE_MINUTES,
@@ -12,7 +12,9 @@ import {
12
type RuntimeMode,
13
type ProviderInteractionMode,
14
type ServerSettings,
15
+ type ThreadId,
16
} from "@t3tools/contracts";
17
+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
18
import {
19
parseMaxDeliveryAge,
20
parseWebhookFilterDrafts,
@@ -296,6 +298,59 @@ export function taskToDraft(task: ScheduledTask): DraftState {
298
};
299
}
300
301
+export function moveDraftToThread(
302
+ draft: DraftState,
303
+ thread: { readonly id: ThreadId; readonly projectId: ProjectId },
304
+): DraftState {
305
+ return {
306
+ ...draft,
307
+ threadId: thread.id,
308
+ projectId: thread.projectId,
309
+ threadMode: draft.threadMode === "new_thread" ? "continue" : draft.threadMode,
310
+ };
311
+}
312
+
313
+/** Leaves the thread but keeps the mode. Matches MCP: new threads stay out of the shared checkout. */
314
+export function unbindDraftFromThread(draft: DraftState): DraftState {
315
+ if (!draft.threadId) return draft;
316
+ return {
317
+ ...draft,
318
+ threadId: "",
319
+ ...(draft.workspaceMode === "root"
320
+ ? { workspaceMode: "worktree" as const, startFromOrigin: true }
321
+ : {}),
322
+ };
323
+}
324
+
325
+export function changeDraftProject(draft: DraftState, projectId: string): DraftState {
326
+ if (projectId === draft.projectId) return draft;
327
+ return { ...unbindDraftFromThread(draft), projectId };
328
+}
329
+
330
+/** Threads a task can move to. The current one is left out; the picker always shows it. */
331
+export function scheduledTaskDestinationThreads(
332
+ threads: ReadonlyArray<EnvironmentThreadShell>,
333
+ target: {
334
+ readonly environmentId: EnvironmentId;
335
+ readonly projectId: string;
336
+ readonly currentThreadId: ThreadId | null;
337
+ readonly query: string;
338
+ },
339
+): ReadonlyArray<EnvironmentThreadShell> {
340
+ const search = target.query.trim().toLocaleLowerCase();
341
+ return threads
342
+ .filter(
343
+ (thread) =>
344
+ thread.environmentId === target.environmentId &&
345
+ thread.projectId === target.projectId &&
346
+ thread.id !== target.currentThreadId &&
347
+ thread.archivedAt === null &&
348
+ isListedThreadLineage(thread.lineage) &&
349
+ thread.title.toLocaleLowerCase().includes(search),
350
+ )
351
+ .toSorted((left, right) => right.updatedAt.localeCompare(left.updatedAt));
352
+}
353
+
354
export function scheduledTaskDefaultModel(
355
settings: ServerSettings,
356
project: (LegacyProjectSettingsFields & { readonly id: ProjectId }) | null,
docs/user/project-settings.md
+3
-2
@@ -90,8 +90,9 @@ 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.
93
+without the agent's context growing. To move a one-thread task, pick another
94
+thread in its project under **Destination**. Moving such a task to another
95
+project starts a new thread there on its next run.
96
97
Deleting a thread also deletes tasks that post into that thread. Tasks that start
98
a new thread on each run survive deletion of their previous threads.