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

scheduledTasksSettings.logic.test.ts

409 lines14.3 KB

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