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
186describe("scheduled task destination", () => {
187 it("unbinding leaves the shared checkout for a new worktree from the remote", () => {
188 const rootBound = taskToDraft({
189 ...legacyTask,
190 threadId: ThreadId.make("thread:bound"),
191 workspaceStrategy: { type: "root" },
192 });
193 expect(unbindDraftFromThread(rootBound)).toMatchObject({
194 threadId: "",
195 workspaceMode: "worktree",
196 startFromOrigin: true,
197 });
198 });
199});
200
201describe("one-time scheduled tasks", () => {
202 afterEach(() => vi.unstubAllEnvs());
203
204 it("round-trips the run time through the local date-time input", () => {
205 const runAt = "2026-11-03T17:00:42.000Z";
206 const draft = taskToDraft({ ...legacyTask, schedule: { type: "once", runAt } });
207 expect(draft.scheduleMode).toBe("once");
208 expect(scheduleFromDraft(draft)).toEqual({ type: "once", runAt });
209 const moved = scheduleFromDraft({ ...draft, runAt: "2026-11-04T09:30" });
210 expect(moved).toEqual({ type: "once", runAt: new Date("2026-11-04T09:30").toISOString() });
211 expect(scheduleFromDraft({ ...draft, runAt: "" })).toBeNull();
212 });
213
214 it("rejects a time skipped by daylight saving", () => {
215 vi.stubEnv("TZ", "America/Los_Angeles");
216 const draft = taskToDraft({
217 ...legacyTask,
218 schedule: { type: "once", runAt: "2027-03-14T18:00:00.000Z" },
219 });
220 expect(scheduleFromDraft({ ...draft, runAt: "2027-03-14T02:30" })).toBeNull();
221 });
222
223 it("keeps the saved offset when an edit stays in an hour that repeats", () => {
224 vi.stubEnv("TZ", "America/Los_Angeles");
225 // 01:30 PST, the second 01:30 on 2026-11-01.
226 const draft = taskToDraft({
227 ...legacyTask,
228 schedule: { type: "once", runAt: "2026-11-01T09:30:00.000Z" },
229 });
230 expect(scheduleFromDraft({ ...draft, runAt: "2026-11-01T01:35" })).toEqual({
231 type: "once",
232 runAt: "2026-11-01T09:35:00.000Z",
233 });
234 });
235});
236
237describe("webhook scheduled tasks", () => {
238 const signature = { header: "x-signature", encoding: "base64", prefix: "" } as const;
239 const webhookTask: ScheduledTask = {
240 ...legacyTask,
241 schedule: { type: "webhook", signature },
242 webhook: { path: "/api/hooks/legacy-task/token", url: null, hasSecret: true },
243 };
244
245 it("round-trips dedupe settings, clears them, and rejects invalid windows", () => {
246 const dedupe = {
247 replayKey: "{{headers.delivery-id}}",
248 coalesceKey: "{{body.id}}",
249 coalesceWindowSeconds: 10,
250 };
251 const draft = taskToDraft({
252 ...webhookTask,
253 schedule: { type: "webhook", signature: null, dedupe },
254 });
255 expect(scheduleFromDraft(draft)).toMatchObject({ dedupe });
256 expect(
257 scheduleFromDraft({
258 ...draft,
259 replayKey: " \n ",
260 coalesceKey: " \t ",
261 coalesceWindowSeconds: "",
262 }),
263 ).toMatchObject({ dedupe: {} });
264 expect(
265 scheduleFromDraft({
266 ...draft,
267 replayKey: ` ${dedupe.replayKey} `,
268 coalesceKey: `\t${dedupe.coalesceKey}\n`,
269 }),
270 ).toMatchObject({ dedupe });
271 expect(
272 scheduleFromDraft({ ...draft, replayKey: "", coalesceKey: "", coalesceWindowSeconds: "" }),
273 ).toMatchObject({ dedupe: {} });
274 expect(scheduleFromDraft({ ...draft, coalesceWindowSeconds: "" })).toMatchObject({
275 dedupe: { replayKey: dedupe.replayKey, coalesceKey: dedupe.coalesceKey },
276 });
277 for (const coalesceWindowSeconds of ["9", "3601", "1.5", "abc"]) {
278 expect(scheduleFromDraft({ ...draft, coalesceWindowSeconds })).toBeNull();
279 }
280 });
281
282 it("keeps a stored secret when the secret field is left blank", () => {
283 const draft = taskToDraft(webhookTask);
284 expect(draft.scheduleMode).toBe("webhook");
285 expect(draft.signatureSecret).toBe("");
286 expect(scheduleFromDraft(draft)).toEqual({
287 type: "webhook",
288 signature,
289 maxDeliveryAgeMinutes: null,
290 dedupe: {},
291 });
292 expect(scheduleFromDraft({ ...draft, signatureSecret: " new " })).toEqual({
293 type: "webhook",
294 signature: { ...signature, secret: "new" },
295 maxDeliveryAgeMinutes: null,
296 dedupe: {},
297 });
298 });
299
300 it("round-trips the max age, treats blank as no limit, and rejects an invalid limit", () => {
301 const draft = taskToDraft({
302 ...webhookTask,
303 schedule: { type: "webhook", signature: null, maxDeliveryAgeMinutes: 90 },
304 });
305 expect(draft.maxDeliveryAgeMinutes).toBe("90");
306 expect(scheduleFromDraft(draft)).toMatchObject({ maxDeliveryAgeMinutes: 90 });
307 for (const blank of ["", " "]) {
308 expect(scheduleFromDraft({ ...draft, maxDeliveryAgeMinutes: blank })).toMatchObject({
309 maxDeliveryAgeMinutes: null,
310 dedupe: {},
311 });
312 }
313 for (const invalid of ["0", "-5", "1.5", "abc", "1441"]) {
314 expect(scheduleFromDraft({ ...draft, maxDeliveryAgeMinutes: invalid })).toBeNull();
315 }
316 });
317
318 it("sends filters only when the form changed them", () => {
319 const filters = [
320 { path: "headers.x-github-event", op: "equals", value: "pull_request" },
321 { path: "body.action", op: "in", value: ["opened", "reopened"] },
322 ] as const;
323 const draft = taskToDraft({
324 ...webhookTask,
325 schedule: { type: "webhook", signature, filters },
326 });
327 expect(draft.filters.map((filter) => filter.op)).toEqual(["equals", "in"]);
328 // A title-only save leaves the key out, so the server keeps whatever is stored now.
329 expect(scheduleFromDraft({ ...draft, title: "Renamed" })).not.toHaveProperty("filters");
330 expect(scheduleFromDraft({ ...draft, filters: draft.filters.slice(0, 1) })).toMatchObject({
331 filters: filters.slice(0, 1),
332 });
333 // Removing every row is a change, so it clears the stored filters.
334 expect(scheduleFromDraft({ ...draft, filters: [] })).toMatchObject({ filters: [] });
335 expect(
336 scheduleFromDraft({
337 ...draft,
338 filters: [{ id: "f1", path: "body.action", op: "in", value: " , " }],
339 }),
340 ).toBeNull();
341 });
342});
343
344describe("scheduled task model defaults", () => {
345 const instanceId = ProviderInstanceId.make("codex");
346 const projectId = ProjectId.make("project");
347 const environmentSelection = {
348 instanceId,
349 model: "environment-model",
350 options: [{ id: "reasoning", value: "high" }],
351 };
352 const projectSelection = { instanceId, model: "project-model" };
353 const config = {
354 settings: { ...DEFAULT_SERVER_SETTINGS, defaultModelSelection: environmentSelection },
355 providers: [
356 {
357 instanceId,
358 driver: "codex",
359 displayName: "Codex",
360 enabled: true,
361 installed: true,
362 status: "ready",
363 auth: { status: "authenticated" },
364 models: [
365 { slug: "first-model", name: "First", isCustom: false, capabilities: null },
366 {
367 slug: "catalog-default",
368 name: "Default",
369 isDefault: true,
370 isCustom: false,
371 capabilities: null,
372 },
373 { slug: "environment-model", name: "Environment", isCustom: false, capabilities: null },
374 { slug: "project-model", name: "Project", isCustom: false, capabilities: null },
375 ],
376 },
377 ],
378 } as unknown as ServerConfig;
379 const resolve = (
380 value: ServerConfig,
381 project: { id: typeof projectId; defaultModelSelection?: typeof projectSelection } | null,
382 ) =>
383 scheduledTaskDefaultModel(
384 value.settings,
385 project,
386 deriveProviderInstanceEntries(value.providers),
387 );
388 it("uses the advertised default instead of catalog order when no default is configured", () => {
389 expect(
390 resolve({ ...config, settings: { ...config.settings, defaultModelSelection: null } }, null),
391 ).toEqual({ instanceId, model: "catalog-default" });
392 });
393 it("falls back to the environment default when the project provider is unavailable", () => {
394 expect(
395 resolve(config, {
396 id: projectId,
397 defaultModelSelection: {
398 instanceId: ProviderInstanceId.make("unavailable"),
399 model: "missing",
400 },
401 }),
402 ).toEqual(environmentSelection);
403 });
404});
405
406it("rejects dedupe templates without a request placeholder", () => {
407 const draft = taskToDraft({ ...legacyTask, schedule: { type: "webhook", signature: null } });
408 expect(scheduleFromDraft({ ...draft, replayKey: "literal" })).toBeNull();
409 expect(scheduleFromDraft({ ...draft, coalesceKey: "{{body.bad" })).toBeNull();
410});
411
412it("appends the server zone only to fixed-time schedule labels", () => {
413 expect(scheduleLabel({ type: "fixed_time", timeOfDay: "16:31" }, "Etc/UTC")).toBe(
414 "Daily at 16:31 UTC",
415 );
416 expect(scheduleLabel({ type: "fixed_time", timeOfDay: "09:00" })).toBe("Daily at 09:00");
417 expect(scheduleLabel({ type: "interval", everyMs: 60_000 }, "Etc/UTC")).toBe("Every 1 min");
418 expect(scheduleLabel({ type: "webhook", signature: null }, "Etc/UTC")).toBe("On webhook");
419});