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