Open History to see the last commit
1import {
2 EnvironmentId,
3 ProjectId,
4 DEFAULT_SERVER_SETTINGS,
5 type ServerConfig,
6 ProviderInstanceId,
7 ScheduledTaskId,
8 type ScheduledTask,
9 ThreadId,
10} from "@t3tools/contracts";
11import { afterEach, describe, expect, it, vi } from "vite-plus/test";
12
13import type {
14 SidebarProjectGroupMember,
15 SidebarProjectSnapshot,
16} from "../../sidebarProjectGrouping";
17import { resolveSettingsScope, type SettingsScopeSearch } from "./settingsScope";
18
19import { deriveProviderInstanceEntries } from "../../providerInstances";
20import {
21 scheduledTaskDefaultModel,
22 defaultScheduledTaskProjectId,
23 matchesScheduledTaskScope,
24 scheduleFromDraft,
25 scheduleLabel,
26 taskToDraft,
27 unbindDraftFromThread,
28} from "./scheduledTasksSettings.logic";
29
30const laptopId = EnvironmentId.make("laptop");
31const serverId = EnvironmentId.make("server");
32const environments = [
33 { environmentId: laptopId, label: "Laptop" },
34 { environmentId: serverId, label: "Server" },
35];
36
37function member(id: string, environmentId: EnvironmentId): SidebarProjectGroupMember {
38 return {
39 id: ProjectId.make(id),
40 environmentId,
41 title: "T3 Code",
42 workspaceRoot: `/repos/${id}`,
43 physicalProjectKey: `${environmentId}:/repos/${id}`,
44 environmentLabel:
45 environments.find((environment) => environment.environmentId === environmentId)?.label ??
46 null,
47 defaultModelSelection: null,
48 scripts: [],
49 createdAt: "2026-09-07T00:00:00.000Z",
50 updatedAt: "2026-09-07T00:00:00.000Z",
51 };
52}
53
54const first = member("first", laptopId);
55const second = member("second", laptopId);
56const third = member("third", serverId);
57const other = member("other", serverId);
58
59function group(
60 projectKey: string,
61 members: readonly SidebarProjectGroupMember[],
62): SidebarProjectSnapshot {
63 return {
64 ...members[0]!,
65 projectKey,
66 displayName: projectKey,
67 memberProjects: members,
68 memberProjectRefs: members.map((project) => ({
69 environmentId: project.environmentId,
70 projectId: project.id,
71 })),
72 groupedProjectCount: members.length,
73 environmentPresence: "mixed",
74 allRemoteMembersAreDesktopLocal: false,
75 allRemoteMembersAreWsl: false,
76 remoteEnvironmentLabels: [],
77 pinned: false,
78 archived: false,
79 };
80}
81
82const sameIdElsewhere = member("first", serverId);
83const groups = [group("t3code", [first, second, third]), group("other", [other, sameIdElsewhere])];
84const tasks = [first, second, third, other, sameIdElsewhere].map((project, index) => ({
85 id: `task-${index}`,
86 environmentId: project.environmentId,
87 projectId: project.id,
88}));
89
90describe("scheduled task settings scope", () => {
91 it.each<{ search: SettingsScopeSearch; expected: string[] }>([
92 { search: {}, expected: ["task-0", "task-1", "task-2", "task-3", "task-4"] },
93 { search: { machine: laptopId }, expected: ["task-0", "task-1"] },
94 { search: { project: "t3code" }, expected: ["task-0", "task-1", "task-2"] },
95 { search: { project: "t3code", machine: serverId }, expected: ["task-2"] },
96 { search: { project: "t3code", checkout: second.physicalProjectKey }, expected: ["task-1"] },
97 { search: { project: "missing" }, expected: [] },
98 { search: { machine: "removed" }, expected: [] },
99 { search: { project: "t3code", checkout: "removed" }, expected: [] },
100 { search: { project: "other", machine: laptopId }, expected: [] },
101 ])("lists only matching tasks for $search", ({ search, expected }) => {
102 const scope = resolveSettingsScope(search, groups, environments);
103 expect(
104 tasks
105 .filter((task) => matchesScheduledTaskScope(scope, task.environmentId, task.projectId))
106 .map((task) => task.id),
107 ).toEqual(expected);
108 });
109
110 it("defaults a new task to a pinned open project, and to an archived one only when scoped to it", () => {
111 const at = "2026-01-01T00:00:00.000Z";
112 const project = (id: string, pinnedAt: string | null, archivedAt: string | null) => ({
113 id: ProjectId.make(id),
114 pinnedAt,
115 archivedAt,
116 });
117 const all = resolveSettingsScope({}, groups, environments);
118 const scoped = resolveSettingsScope({ project: "t3code" }, groups, environments);
119 expect(
120 defaultScheduledTaskProjectId([project("a", null, null), project("b", at, null)], all),
121 ).toBe("b");
122 expect(defaultScheduledTaskProjectId([project("x", null, at)], all)).toBe("");
123 expect(defaultScheduledTaskProjectId([project("x", null, at)], scoped)).toBe("x");
124 });
125
126 it("keeps tasks with removed projects manageable at environment scope", () => {
127 const removedProject = ProjectId.make("removed");
128 expect(
129 matchesScheduledTaskScope(
130 resolveSettingsScope({}, groups, environments),
131 laptopId,
132 removedProject,
133 ),
134 ).toBe(true);
135 expect(
136 matchesScheduledTaskScope(
137 resolveSettingsScope({ project: "t3code" }, groups, environments),
138 laptopId,
139 removedProject,
140 ),
141 ).toBe(false);
142 });
143});
144
145const legacyTask: ScheduledTask = {
146 id: ScheduledTaskId.make("legacy-task"),
147 title: "Review issues",
148 prompt: "Review open issues",
149 enabled: true,
150 schedule: { type: "interval", everyMs: 60_000 },
151 projectId: ProjectId.make("project"),
152 threadId: null,
153 workspaceStrategy: { type: "worktree", baseRef: "release" },
154 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
155 runtimeMode: "full-access",
156 interactionMode: "default",
157 createdBy: "user",
158 creationSource: "web",
159 createdAt: "2026-09-17T00:00:00.000Z",
160 updatedAt: "2026-09-17T00:00:00.000Z",
161 nextRunAt: null,
162 lastRunAt: null,
163 lastRunStatus: "never",
164 lastRunError: null,
165 runCount: 0,
166};
167
168describe("editing scheduled task branch settings", () => {
169 it("keeps an omitted origin flag on the local base branch", () => {
170 const draft = taskToDraft(legacyTask);
171 expect(draft.baseRef).toBe("release");
172 expect(draft.startFromOrigin).toBe(false);
173 });
174});
175
176describe("fixed-time scheduled tasks", () => {
177 it("pads a stored single-digit hour so the time input shows it", () => {
178 const draft = taskToDraft({
179 ...legacyTask,
180 schedule: { type: "fixed_time", timeOfDay: "9:05" },
181 });
182 expect(draft.timeOfDay).toBe("09:05");
183 });
184
185 it("keeps a fixed run time and rejects a cleared one", () => {
186 const draft = taskToDraft({
187 ...legacyTask,
188 schedule: { type: "fixed_time", timeOfDay: "14:30" },
189 });
190 expect(scheduleFromDraft(draft)).toEqual({ type: "fixed_time", timeOfDay: "14:30" });
191 // A native time input reports "" when it is cleared or only partly filled.
192 expect(scheduleFromDraft({ ...draft, timeOfDay: "" })).toBeNull();
193 });
194});
195
196describe("scheduled task destination", () => {
197 it("unbinding leaves the shared checkout for a new worktree from the remote", () => {
198 const rootBound = taskToDraft({
199 ...legacyTask,
200 threadId: ThreadId.make("thread:bound"),
201 workspaceStrategy: { type: "root" },
202 });
203 expect(unbindDraftFromThread(rootBound)).toMatchObject({
204 threadId: "",
205 workspaceMode: "worktree",
206 startFromOrigin: true,
207 });
208 });
209});
210
211describe("one-time scheduled tasks", () => {
212 afterEach(() => vi.unstubAllEnvs());
213
214 it("round-trips the run time through the local date-time input", () => {
215 const runAt = "2026-11-03T17:00:42.000Z";
216 const draft = taskToDraft({ ...legacyTask, schedule: { type: "once", runAt } });
217 expect(draft.scheduleMode).toBe("once");
218 expect(scheduleFromDraft(draft)).toEqual({ type: "once", runAt });
219 const moved = scheduleFromDraft({ ...draft, runAt: "2026-11-04T09:30" });
220 expect(moved).toEqual({ type: "once", runAt: new Date("2026-11-04T09:30").toISOString() });
221 expect(scheduleFromDraft({ ...draft, runAt: "" })).toBeNull();
222 });
223
224 it("rejects a time skipped by daylight saving", () => {
225 vi.stubEnv("TZ", "America/Los_Angeles");
226 const draft = taskToDraft({
227 ...legacyTask,
228 schedule: { type: "once", runAt: "2027-03-14T18:00:00.000Z" },
229 });
230 expect(scheduleFromDraft({ ...draft, runAt: "2027-03-14T02:30" })).toBeNull();
231 });
232
233 it("keeps the saved offset when an edit stays in an hour that repeats", () => {
234 vi.stubEnv("TZ", "America/Los_Angeles");
235 // 01:30 PST, the second 01:30 on 2026-11-01.
236 const draft = taskToDraft({
237 ...legacyTask,
238 schedule: { type: "once", runAt: "2026-11-01T09:30:00.000Z" },
239 });
240 expect(scheduleFromDraft({ ...draft, runAt: "2026-11-01T01:35" })).toEqual({
241 type: "once",
242 runAt: "2026-11-01T09:35:00.000Z",
243 });
244 });
245});
246
247describe("webhook scheduled tasks", () => {
248 const signature = { header: "x-signature", encoding: "base64", prefix: "" } as const;
249 const webhookTask: ScheduledTask = {
250 ...legacyTask,
251 schedule: { type: "webhook", signature },
252 webhook: { path: "/api/hooks/legacy-task/token", url: null, hasSecret: true },
253 };
254
255 it("round-trips dedupe settings, clears them, and rejects invalid windows", () => {
256 const dedupe = {
257 replayKey: "{{headers.delivery-id}}",
258 coalesceKey: "{{body.id}}",
259 coalesceWindowSeconds: 10,
260 };
261 const draft = taskToDraft({
262 ...webhookTask,
263 schedule: { type: "webhook", signature: null, dedupe },
264 });
265 expect(scheduleFromDraft(draft)).toMatchObject({ dedupe });
266 expect(
267 scheduleFromDraft({
268 ...draft,
269 replayKey: " \n ",
270 coalesceKey: " \t ",
271 coalesceWindowSeconds: "",
272 }),
273 ).toMatchObject({ dedupe: {} });
274 expect(
275 scheduleFromDraft({
276 ...draft,
277 replayKey: ` ${dedupe.replayKey} `,
278 coalesceKey: `\t${dedupe.coalesceKey}\n`,
279 }),
280 ).toMatchObject({ dedupe });
281 expect(
282 scheduleFromDraft({ ...draft, replayKey: "", coalesceKey: "", coalesceWindowSeconds: "" }),
283 ).toMatchObject({ dedupe: {} });
284 expect(scheduleFromDraft({ ...draft, coalesceWindowSeconds: "" })).toMatchObject({
285 dedupe: { replayKey: dedupe.replayKey, coalesceKey: dedupe.coalesceKey },
286 });
287 for (const coalesceWindowSeconds of ["9", "3601", "1.5", "abc"]) {
288 expect(scheduleFromDraft({ ...draft, coalesceWindowSeconds })).toBeNull();
289 }
290 });
291
292 it("keeps a stored secret when the secret field is left blank", () => {
293 const draft = taskToDraft(webhookTask);
294 expect(draft.scheduleMode).toBe("webhook");
295 expect(draft.signatureSecret).toBe("");
296 expect(scheduleFromDraft(draft)).toEqual({
297 type: "webhook",
298 signature,
299 maxDeliveryAgeMinutes: null,
300 dedupe: {},
301 });
302 expect(scheduleFromDraft({ ...draft, signatureSecret: " new " })).toEqual({
303 type: "webhook",
304 signature: { ...signature, secret: "new" },
305 maxDeliveryAgeMinutes: null,
306 dedupe: {},
307 });
308 });
309
310 it("round-trips the max age, treats blank as no limit, and rejects an invalid limit", () => {
311 const draft = taskToDraft({
312 ...webhookTask,
313 schedule: { type: "webhook", signature: null, maxDeliveryAgeMinutes: 90 },
314 });
315 expect(draft.maxDeliveryAgeMinutes).toBe("90");
316 expect(scheduleFromDraft(draft)).toMatchObject({ maxDeliveryAgeMinutes: 90 });
317 for (const blank of ["", " "]) {
318 expect(scheduleFromDraft({ ...draft, maxDeliveryAgeMinutes: blank })).toMatchObject({
319 maxDeliveryAgeMinutes: null,
320 dedupe: {},
321 });
322 }
323 for (const invalid of ["0", "-5", "1.5", "abc", "1441"]) {
324 expect(scheduleFromDraft({ ...draft, maxDeliveryAgeMinutes: invalid })).toBeNull();
325 }
326 });
327
328 it("sends filters only when the form changed them", () => {
329 const filters = [
330 { path: "headers.x-github-event", op: "equals", value: "pull_request" },
331 { path: "body.action", op: "in", value: ["opened", "reopened"] },
332 ] as const;
333 const draft = taskToDraft({
334 ...webhookTask,
335 schedule: { type: "webhook", signature, filters },
336 });
337 expect(draft.filters.map((filter) => filter.op)).toEqual(["equals", "in"]);
338 // A title-only save leaves the key out, so the server keeps whatever is stored now.
339 expect(scheduleFromDraft({ ...draft, title: "Renamed" })).not.toHaveProperty("filters");
340 expect(scheduleFromDraft({ ...draft, filters: draft.filters.slice(0, 1) })).toMatchObject({
341 filters: filters.slice(0, 1),
342 });
343 // Removing every row is a change, so it clears the stored filters.
344 expect(scheduleFromDraft({ ...draft, filters: [] })).toMatchObject({ filters: [] });
345 expect(
346 scheduleFromDraft({
347 ...draft,
348 filters: [{ id: "f1", path: "body.action", op: "in", value: " , " }],
349 }),
350 ).toBeNull();
351 });
352});
353
354describe("scheduled task model defaults", () => {
355 const instanceId = ProviderInstanceId.make("codex");
356 const projectId = ProjectId.make("project");
357 const environmentSelection = {
358 instanceId,
359 model: "environment-model",
360 options: [{ id: "reasoning", value: "high" }],
361 };
362 const projectSelection = { instanceId, model: "project-model" };
363 const config = {
364 settings: { ...DEFAULT_SERVER_SETTINGS, defaultModelSelection: environmentSelection },
365 providers: [
366 {
367 instanceId,
368 driver: "codex",
369 displayName: "Codex",
370 enabled: true,
371 installed: true,
372 status: "ready",
373 auth: { status: "authenticated" },
374 models: [
375 { slug: "first-model", name: "First", isCustom: false, capabilities: null },
376 {
377 slug: "catalog-default",
378 name: "Default",
379 isDefault: true,
380 isCustom: false,
381 capabilities: null,
382 },
383 { slug: "environment-model", name: "Environment", isCustom: false, capabilities: null },
384 { slug: "project-model", name: "Project", isCustom: false, capabilities: null },
385 ],
386 },
387 ],
388 } as unknown as ServerConfig;
389 const resolve = (
390 value: ServerConfig,
391 project: { id: typeof projectId; defaultModelSelection?: typeof projectSelection } | null,
392 ) =>
393 scheduledTaskDefaultModel(
394 value.settings,
395 project,
396 deriveProviderInstanceEntries(value.providers),
397 );
398 it("uses the advertised default instead of catalog order when no default is configured", () => {
399 expect(
400 resolve({ ...config, settings: { ...config.settings, defaultModelSelection: null } }, null),
401 ).toEqual({ instanceId, model: "catalog-default" });
402 });
403 it("falls back to the environment default when the project provider is unavailable", () => {
404 expect(
405 resolve(config, {
406 id: projectId,
407 defaultModelSelection: {
408 instanceId: ProviderInstanceId.make("unavailable"),
409 model: "missing",
410 },
411 }),
412 ).toEqual(environmentSelection);
413 });
414});
415
416it("rejects dedupe templates without a request placeholder", () => {
417 const draft = taskToDraft({ ...legacyTask, schedule: { type: "webhook", signature: null } });
418 expect(scheduleFromDraft({ ...draft, replayKey: "literal" })).toBeNull();
419 expect(scheduleFromDraft({ ...draft, coalesceKey: "{{body.bad" })).toBeNull();
420});
421
422it("appends the server zone only to fixed-time schedule labels", () => {
423 expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "Etc/UTC")).toBe(
424 "Daily at 16:31 UTC",
425 );
426 expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" })).toBe("Daily at 09:00");
427 expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "Etc/UTC")).toBe("Every 1 min");
428 expect(scheduleLabel({ type: "webhook", signature: null }, "Etc/UTC")).toBe("On webhook");
429});