Skip to content

Commit 70ba40b

Browse files
fix(server): preserve atomic schedule edits on current OV2
1 parent 250e052 commit 70ba40b

21 files changed

Lines changed: 3231 additions & 236 deletions

‎apps/mobile/src/features/settings/SettingsScheduledTasksRouteScreen.tsx‎

Lines changed: 58 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { scheduledTaskLegacyUpsert } from "@t3tools/contracts";
12
import type {
23
EnvironmentId,
34
ProjectId,
@@ -55,6 +56,7 @@ import { SettingsScreen } from "./components/SettingsScreen";
5556
import { SettingsSection } from "./components/SettingsSection";
5657
import { useSettingsEnvironmentFilter, type SettingsTarget } from "./settings-environment-filter";
5758
import {
59+
buildScheduledTaskUpdateInput,
5860
editDraft,
5961
scheduledTaskDefaultModel,
6062
scheduleFromDraft,
@@ -573,6 +575,10 @@ function TaskForm({
573575
label: "scheduled task upsert",
574576
reportFailure: false,
575577
});
578+
const update = useAtomCommand(serverEnvironment.updateScheduledTask, {
579+
label: "scheduled task update",
580+
reportFailure: false,
581+
});
576582
const submissionPending = useRef(false);
577583
const [timePickerOpen, setTimePickerOpen] = useState(false);
578584
const taskMissing =
@@ -617,35 +623,62 @@ function TaskForm({
617623
Alert.alert("Project unavailable", "Choose a project in this environment.");
618624
return;
619625
}
620-
const input: ScheduledTaskUpsertInput = {
621-
...(draft.task ? { id: draft.task.id, requireExisting: true } : {}),
622-
title: draft.title.trim(),
623-
prompt: draft.prompt.trim(),
624-
projectId: draft.projectId,
625-
modelSelection: draft.modelSelection,
626-
schedule,
627-
enabled: draft.enabled,
628-
threadId: draft.task?.threadId ?? null,
629-
workspaceStrategy:
630-
draft.workspace === "root"
631-
? { type: "root" }
632-
: draft.workspace === "existing_worktree"
633-
? { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() }
634-
: {
635-
type: "worktree",
636-
baseRef: draft.baseRef.trim() || "main",
637-
startFromOrigin: draft.startFromOrigin,
638-
},
639-
runtimeMode: draft.runtimeMode,
640-
interactionMode: draft.task?.interactionMode ?? "default",
641-
creationSource: draft.task?.creationSource ?? "mobile",
642-
};
643626
// Lock before React renders, and keep successful creates locked until the form closes.
644627
submissionPending.current = true;
645628
setSaving(true);
646-
const result = await upsert({ environmentId, input });
629+
let result: AtomCommandResult<unknown, unknown> | null;
630+
if (draft.task !== null) {
631+
// Existing tasks save as a dirty-field patch through the atomic update
632+
// path: a stale editor can never overwrite fields another client
633+
// changed, and a delete racing the save is a typed not-found, not a
634+
// resurrection. `taskMissing` already guarantees the task is in the
635+
// live list.
636+
const liveTask = tasks.data?.tasks.find((task) => task.id === draft.task?.id);
637+
if (liveTask === undefined) {
638+
// The live list has not returned (or the task vanished between render
639+
// and save) — fail loudly instead of silently discarding the edit.
640+
setSaving(false);
641+
submissionPending.current = false;
642+
Alert.alert(
643+
"Task unavailable",
644+
"The task could not be loaded. Reopen it once the list has loaded and try again.",
645+
);
646+
return;
647+
}
648+
const patch = buildScheduledTaskUpdateInput(draft, liveTask);
649+
result =
650+
patch === null
651+
? null
652+
: config?.environment.capabilities.scheduledTaskUpdate === true
653+
? await update({ environmentId, input: patch })
654+
: await upsert({ environmentId, input: scheduledTaskLegacyUpsert(liveTask, patch) });
655+
} else {
656+
const input: ScheduledTaskUpsertInput = {
657+
title: draft.title.trim(),
658+
prompt: draft.prompt.trim(),
659+
projectId: draft.projectId,
660+
modelSelection: draft.modelSelection,
661+
schedule,
662+
enabled: draft.enabled,
663+
threadId: null,
664+
workspaceStrategy:
665+
draft.workspace === "root"
666+
? { type: "root" }
667+
: draft.workspace === "existing_worktree"
668+
? { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() }
669+
: {
670+
type: "worktree",
671+
baseRef: draft.baseRef.trim() || "main",
672+
startFromOrigin: draft.startFromOrigin,
673+
},
674+
runtimeMode: draft.runtimeMode,
675+
interactionMode: "default",
676+
creationSource: "mobile",
677+
};
678+
result = await upsert({ environmentId, input });
679+
}
647680
setSaving(false);
648-
if (result._tag === "Failure") {
681+
if (result !== null && result._tag === "Failure") {
649682
submissionPending.current = false;
650683
failure("Could not save task", result);
651684
return;

‎apps/mobile/src/features/settings/scheduledTaskDraft.test.ts‎

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
type ScheduledTask,
99
} from "@t3tools/contracts";
1010
import {
11+
buildScheduledTaskUpdateInput,
1112
scheduledTaskDefaultModel,
1213
createDraft,
1314
editDraft,
@@ -309,3 +310,125 @@ describe("scheduled task model defaults", () => {
309310
).toBeNull();
310311
});
311312
});
313+
314+
describe("buildScheduledTaskUpdateInput", () => {
315+
const projectId = ProjectId.make("project:one");
316+
const task: ScheduledTask = {
317+
id: ScheduledTaskId.make("scheduled-task:mobile-fixture"),
318+
title: "Original title",
319+
prompt: "Original prompt",
320+
enabled: true,
321+
schedule: { type: "interval", everyMs: 15 * 60_000 },
322+
projectId,
323+
threadId: null,
324+
workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true },
325+
modelSelection: {
326+
instanceId: ProviderInstanceId.make("codex"),
327+
model: "gpt-5.4",
328+
},
329+
runtimeMode: "full-access",
330+
interactionMode: "default",
331+
createdBy: "user",
332+
creationSource: "mobile",
333+
createdAt: "2026-09-01T00:00:00.000Z",
334+
updatedAt: "2026-09-01T00:00:00.000Z",
335+
nextRunAt: "2026-09-02T00:00:00.000Z",
336+
lastRunAt: null,
337+
lastRunStatus: "never",
338+
lastRunError: null,
339+
runCount: 0,
340+
};
341+
342+
it("returns null when the draft matches the task it opened with", () => {
343+
expect(buildScheduledTaskUpdateInput(editDraft(task), task)).toBeNull();
344+
expect(buildScheduledTaskUpdateInput(createDraft(null, null), task)).toBeNull();
345+
});
346+
347+
it("sends only the fields a stale editor changed, preserving concurrent edits", () => {
348+
// Another client rewrote the prompt and paused the task while this
349+
// editor was open; the mobile save carries only the rename the user
350+
// actually made instead of restoring the stale prompt and enabled flag.
351+
const draft = { ...editDraft(task), title: "Renamed" };
352+
const live: ScheduledTask = {
353+
...task,
354+
prompt: "Rewritten elsewhere",
355+
enabled: false,
356+
};
357+
expect(buildScheduledTaskUpdateInput(draft, live)).toEqual({
358+
id: task.id,
359+
projectId: task.projectId,
360+
title: "Renamed",
361+
});
362+
});
363+
364+
it("patches the editable runtime mode", () => {
365+
const draft = { ...editDraft(task), runtimeMode: "auto" as const };
366+
expect(buildScheduledTaskUpdateInput(draft, task)).toEqual({
367+
id: task.id,
368+
projectId: task.projectId,
369+
runtimeMode: "auto",
370+
});
371+
});
372+
373+
it("detaches the live binding only when the patch itself re-homes the task", () => {
374+
const other = ProjectId.make("project:other");
375+
const bound: ScheduledTask = { ...task, threadId: "thread:bound" as ScheduledTask["threadId"] };
376+
// A real move away from the binding's project must detach it.
377+
const moving = { ...editDraft(bound), projectId: other };
378+
expect(buildScheduledTaskUpdateInput(moving, bound)).toEqual({
379+
id: bound.id,
380+
projectId: bound.projectId,
381+
nextProjectId: other,
382+
threadId: null,
383+
});
384+
// A stale save landing where the task already lives keeps a concurrent
385+
// rebind instead of erasing it.
386+
const liveMoved: ScheduledTask = { ...bound, projectId: other };
387+
expect(buildScheduledTaskUpdateInput(moving, liveMoved)).toEqual({
388+
id: bound.id,
389+
projectId: other,
390+
nextProjectId: other,
391+
});
392+
});
393+
394+
it("emits the normalized schedule for a legacy sub-minute interval", () => {
395+
const legacy: ScheduledTask = {
396+
...task,
397+
schedule: { type: "interval", everyMs: 30_000 },
398+
};
399+
// The draft is untouched — editDraft clamped the baseline to "1" — but
400+
// the stored 30s interval must still be rewritten to the displayed 60s.
401+
expect(buildScheduledTaskUpdateInput(editDraft(legacy), legacy)).toEqual({
402+
id: legacy.id,
403+
projectId: legacy.projectId,
404+
schedule: { type: "interval", everyMs: 60_000 },
405+
});
406+
});
407+
408+
it("does not overwrite a concurrent fix to a legacy sub-minute interval", () => {
409+
const legacy: ScheduledTask = {
410+
...task,
411+
schedule: { type: "interval", everyMs: 30_000 },
412+
};
413+
// Another client already normalized the schedule — an untouched save
414+
// leaves their interval alone instead of forcing the editor's 60s.
415+
const live: ScheduledTask = { ...legacy, schedule: { type: "interval", everyMs: 90_000 } };
416+
expect(buildScheduledTaskUpdateInput(editDraft(legacy), live)).toBeNull();
417+
});
418+
419+
it("sends only the workspace controls the user changed as a sparse patch", () => {
420+
// Another client flipped startFromOrigin while this editor was open;
421+
// the save sends just the edited key and the server merges it into the
422+
// live strategy, so the concurrent toggle survives on both sides.
423+
const draft = { ...editDraft(task), baseRef: "develop" };
424+
const live: ScheduledTask = {
425+
...task,
426+
workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: false },
427+
};
428+
expect(buildScheduledTaskUpdateInput(draft, live)).toEqual({
429+
id: task.id,
430+
projectId: task.projectId,
431+
workspaceStrategyPatch: { baseRef: "develop" },
432+
});
433+
});
434+
});

‎apps/mobile/src/features/settings/scheduledTaskDraft.ts‎

Lines changed: 134 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,15 @@
11
import type {
22
ModelSelection,
3+
OrchestrationV2ThreadLaunchWorkspaceStrategy,
34
ServerConfig,
45
ProjectId,
56
RuntimeMode,
67
ScheduledTask,
8+
ScheduledTaskUpdateInput,
79
ScheduledTaskUpsertSchedule,
810
} from "@t3tools/contracts";
911

10-
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
12+
import { DEFAULT_SERVER_SETTINGS, MIN_SCHEDULED_TASK_INTERVAL_MS } from "@t3tools/contracts";
1113
import {
1214
resolveProjectSettings,
1315
type LegacyProjectSettingsFields,
@@ -179,3 +181,134 @@ export function editDraft(task: ScheduledTask): ScheduledTaskDraft {
179181
runtimeMode: task.runtimeMode,
180182
};
181183
}
184+
185+
function sameSchedule(a: ScheduledTaskUpsertSchedule, b: ScheduledTaskUpsertSchedule): boolean {
186+
if (a.type === "interval") {
187+
return b.type === "interval" && a.everyMs === b.everyMs;
188+
}
189+
if (b.type !== "fixed_time") return false;
190+
const key = (weekdays: ReadonlyArray<number> | undefined) => {
191+
const unique = [...new Set(weekdays ?? [])].sort((x, y) => x - y);
192+
return unique.length === 0 || unique.length === 7 ? "daily" : unique.join(",");
193+
};
194+
return a.timeOfDay === b.timeOfDay && key(a.weekdays) === key(b.weekdays);
195+
}
196+
197+
function sameModelSelection(a: ModelSelection | null, b: ModelSelection | null): boolean {
198+
if (a === null || b === null) return a === b;
199+
const key = (selection: ModelSelection) =>
200+
JSON.stringify([
201+
selection.instanceId,
202+
selection.model,
203+
[...(selection.options ?? [])]
204+
.sort((x, y) => x.id.localeCompare(y.id))
205+
.map((option) => [option.id, option.value]),
206+
]);
207+
return key(a) === key(b);
208+
}
209+
210+
function workspaceStrategyFromDraft(
211+
draft: ScheduledTaskDraft,
212+
): OrchestrationV2ThreadLaunchWorkspaceStrategy {
213+
if (draft.workspace === "root") return { type: "root" };
214+
if (draft.workspace === "existing_worktree") {
215+
return { type: "existing_worktree", worktreePath: draft.checkoutPath.trim() };
216+
}
217+
return {
218+
type: "worktree",
219+
baseRef: draft.baseRef.trim() || "main",
220+
startFromOrigin: draft.startFromOrigin,
221+
};
222+
}
223+
224+
/**
225+
* Dirty-field patch for an existing task, scoped to its live project. The
226+
* baseline is the task snapshot the editor opened with (`draft.task`), so a
227+
* concurrent commit landing mid-session is never read as a change the user
228+
* made — and `projectId` tracks the live row, so a save still targets the
229+
* task wherever it currently lives. Returns null when nothing changed.
230+
*/
231+
export function buildScheduledTaskUpdateInput(
232+
draft: ScheduledTaskDraft,
233+
liveTask: ScheduledTask,
234+
): ScheduledTaskUpdateInput | null {
235+
const opening = draft.task;
236+
if (opening === null) return null;
237+
const baseline = editDraft(opening);
238+
const patch: {
239+
-readonly [
240+
K in Exclude<keyof ScheduledTaskUpdateInput, "id" | "projectId">
241+
]?: ScheduledTaskUpdateInput[K];
242+
} = {};
243+
const title = draft.title.trim();
244+
if (title !== baseline.title.trim()) patch.title = title;
245+
const prompt = draft.prompt.trim();
246+
if (prompt !== baseline.prompt.trim()) patch.prompt = prompt;
247+
if (draft.enabled !== baseline.enabled) patch.enabled = draft.enabled;
248+
const schedule = scheduleFromDraft(draft.schedule);
249+
const baselineSchedule = scheduleFromDraft(baseline.schedule);
250+
if (
251+
schedule !== null &&
252+
baselineSchedule !== null &&
253+
(!sameSchedule(schedule, baselineSchedule) ||
254+
// scheduleDraftForTask clamps a legacy sub-minute interval to one
255+
// minute, so the baseline diff cannot see the normalization the
256+
// editor promises. Emit the normalized schedule while the live task
257+
// still carries it — a concurrent write to a valid interval clears
258+
// this condition instead of being overwritten.
259+
(liveTask.schedule.type === "interval" &&
260+
liveTask.schedule.everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS))
261+
) {
262+
patch.schedule = schedule;
263+
}
264+
if (draft.runtimeMode !== baseline.runtimeMode) patch.runtimeMode = draft.runtimeMode;
265+
if (
266+
draft.modelSelection !== null &&
267+
!sameModelSelection(draft.modelSelection, baseline.modelSelection)
268+
) {
269+
patch.modelSelection = draft.modelSelection;
270+
}
271+
const workspaceStrategy = workspaceStrategyFromDraft(draft);
272+
const baselineStrategy = workspaceStrategyFromDraft(baseline);
273+
if (JSON.stringify(workspaceStrategy) !== JSON.stringify(baselineStrategy)) {
274+
if (workspaceStrategy.type !== baselineStrategy.type) {
275+
patch.workspaceStrategy = workspaceStrategy;
276+
} else if (
277+
workspaceStrategy.type === "worktree" &&
278+
baselineStrategy.type === "worktree" &&
279+
liveTask.workspaceStrategy.type === "worktree"
280+
) {
281+
// Send only the controls the user changed: the server merges the
282+
// sparse patch into the live strategy inside the update transaction,
283+
// so a concurrent edit to an untouched control — or to a field the
284+
// editor cannot express (`branch`) — survives on both sides.
285+
patch.workspaceStrategyPatch = {
286+
...(workspaceStrategy.baseRef !== baselineStrategy.baseRef
287+
? { baseRef: workspaceStrategy.baseRef }
288+
: {}),
289+
...(workspaceStrategy.startFromOrigin !== baselineStrategy.startFromOrigin
290+
? { startFromOrigin: workspaceStrategy.startFromOrigin }
291+
: {}),
292+
};
293+
} else if (
294+
workspaceStrategy.type === "existing_worktree" &&
295+
baselineStrategy.type === "existing_worktree" &&
296+
liveTask.workspaceStrategy.type === "existing_worktree"
297+
) {
298+
patch.workspaceStrategyPatch = { worktreePath: workspaceStrategy.worktreePath };
299+
}
300+
// A live kind the draft no longer matches means a concurrent editor
301+
// switched it — drop the stale control edit rather than revert that.
302+
}
303+
if (draft.projectId !== null && draft.projectId !== baseline.projectId) {
304+
patch.nextProjectId = draft.projectId;
305+
// A binding cannot follow a real re-home — the thread stays in the old
306+
// project — so a patch that moves the task detaches it; a stale save
307+
// landing where the task already lives keeps a concurrent rebind.
308+
if (draft.projectId !== liveTask.projectId && liveTask.threadId !== null) {
309+
patch.threadId = null;
310+
}
311+
}
312+
if (Object.keys(patch).length === 0) return null;
313+
return { id: liveTask.id, projectId: liveTask.projectId, ...patch };
314+
}

0 commit comments

Comments
 (0)