Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

scheduledTasksSettings.logic.test.ts

382 lines13.5 KB

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