Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import { Atom, AtomRegistry } from "effect/reactivity";
3import {
4 DEFAULT_UNIFIED_SETTINGS,
5 EnvironmentId,
6 ProjectId,
7 ProviderInstanceId,
8 ScheduledTaskId,
9 ThreadId,
10 type ScheduledTask,
11} from "@t3tools/contracts";
12import { describe, expect, it, vi } from "vite-plus/test";
13import { page, userEvent } from "vite-plus/test/browser";
14
15import "~/index.css";
16import { act, render } from "../../../test/render";
17import { ScheduledTasksSettings } from "./ScheduledTasksSettings";
18import { ConfirmDialogHost } from "../ConfirmDialogHost";
19
20const environmentId = EnvironmentId.make("laptop");
21const projectId = ProjectId.make("project");
22const task: ScheduledTask = {
23 id: ScheduledTaskId.make("nightly"),
24 title: "Review issues",
25 prompt: "Review open issues",
26 enabled: true,
27 schedule: { type: "interval", everyMs: 60_000 },
28 projectId,
29 threadId: ThreadId.make("older-thread"),
30 workspaceStrategy: { type: "root" },
31 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
32 runtimeMode: "full-access",
33 interactionMode: "default",
34 createdBy: "user",
35 creationSource: "web",
36 createdAt: "2026-09-17T00:00:00.000Z",
37 updatedAt: "2026-09-17T00:00:00.000Z",
38 nextRunAt: null,
39 lastRunAt: null,
40 lastRunStatus: "never",
41 lastRunError: null,
42 runCount: 0,
43};
44
45// Stands in for the thread family read the editor makes when the shell lacks the bound thread.
46const threadFamilyRead = {
47 snapshotSequence: 1,
48 threads: [{ id: task.threadId, title: "Fix login bug" }],
49};
50
51const state = vi.hoisted(() => ({
52 connected: true,
53 tasksLoaded: true,
54 secondary: false,
55 remove: vi.fn(),
56}));
57const secondaryId = EnvironmentId.make("secondary");
58const permissions = new Map<string, Atom.Writable<boolean>>();
59
60function setup() {
61 state.connected = true;
62 state.tasksLoaded = true;
63 state.remove.mockReset().mockResolvedValue({ _tag: "Success", value: { id: task.id } });
64 state.secondary = false;
65 permissions.clear();
66 permissions.set(environmentId, Atom.make(true));
67 permissions.set(secondaryId, Atom.make(true));
68 permissions.set("", Atom.make(false));
69}
70
71function secondaryEnvironment() {
72 return { ...environment(), environmentId: secondaryId, label: "Secondary" };
73}
74
75vi.mock(import("../../state/session"), async (original) => ({
76 ...(await original()),
77 readEnvironmentScope: () => true,
78}));
79
80function environment() {
81 return {
82 environmentId,
83 label: "Laptop",
84 connection: { phase: state.connected ? "connected" : "disconnected" },
85 serverConfig: state.connected
86 ? { environment: { platform: "linux", capabilities: { oneTimeSchedules: true } } }
87 : null,
88 };
89}
90
91vi.mock(import("./SettingsScopeContext"), async (original) => {
92 const scope = () => {
93 const entry = environment();
94 return {
95 scope: { kind: "all", label: "All", members: [], environmentIds: [environmentId] },
96 environments: state.secondary ? [entry, secondaryEnvironment()] : [entry],
97 connectedEnvironments: state.connected
98 ? state.secondary
99 ? [entry, secondaryEnvironment()]
100 : [entry]
101 : [],
102 environment: entry,
103 target: null,
104 targets: [],
105 };
106 };
107 return {
108 ...(await original()),
109 useSettingsScope: scope as never,
110 };
111});
112vi.mock(import("../../state/server"), async (original) => {
113 const actual = await original();
114
115 return {
116 ...actual,
117 serverEnvironment: {
118 ...actual.serverEnvironment,
119 deleteScheduledTask: {
120 ...actual.serverEnvironment.deleteScheduledTask,
121 run: state.remove,
122 },
123 upsertScheduledTask: {
124 ...actual.serverEnvironment.upsertScheduledTask,
125 permissionAtom: (id: string | null) => permissions.get(id ?? "")!,
126 },
127 },
128 };
129});
130vi.mock(import("../../state/threads"), async (original) => {
131 const actual = await original();
132 return {
133 ...actual,
134 threadFamilies: { ...actual.threadFamilies, familyAtom: (() => threadFamilyRead) as never },
135 };
136});
137// Mirrors the real query: a null request (disconnected environment) has no data.
138vi.mock(import("../../state/query"), async (original) => ({
139 ...(await original()),
140 useEnvironmentQuery: ((request: unknown) => ({
141 data:
142 request === null || request === threadFamilyRead
143 ? request
144 : { tasks: state.tasksLoaded ? [task] : [] },
145 error: null,
146 isPending: false,
147 refresh: vi.fn(),
148 })) as never,
149}));
150vi.mock(import("../../state/environments"), async (original) => ({
151 ...(await original()),
152 useEnvironment: ((id: EnvironmentId) =>
153 id === secondaryId ? secondaryEnvironment() : environment()) as never,
154}));
155vi.mock(import("../../state/entities"), async (original) => ({
156 ...(await original()),
157 useProjects: (() => [{ id: projectId, environmentId, title: "Project" }]) as never,
158}));
159vi.mock(import("../../hooks/useSettings"), async (original) => ({
160 ...(await original()),
161 useEnvironmentSettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,
162}));
163
164describe("ScheduledTasksSettings", () => {
165 it("only deletes a scheduled task after confirmation, including after cancelling", async () => {
166 setup();
167 await using screen = await render(
168 <>
169 <ScheduledTasksSettings />
170 <ConfirmDialogHost />
171 </>,
172 );
173 await userEvent.click(screen.getByRole("button", { name: "Actions for Review issues" }));
174 await userEvent.click(page.getByRole("menuitem", { name: "Delete", exact: true }));
175 await expect.element(page.getByRole("alertdialog")).toBeVisible();
176 expect(state.remove).not.toHaveBeenCalled();
177 await userEvent.click(page.getByRole("button", { name: "Cancel", exact: true }));
178 expect(state.remove).not.toHaveBeenCalled();
179 await expect
180 .element(screen.getByRole("button", { name: "Actions for Review issues" }))
181 .toBeVisible();
182 await userEvent.click(screen.getByRole("button", { name: "Actions for Review issues" }));
183 await userEvent.click(page.getByRole("menuitem", { name: "Delete", exact: true }));
184 await userEvent.click(page.getByRole("button", { name: "Confirm", exact: true }));
185 await vi.waitFor(() =>
186 expect(state.remove).toHaveBeenCalledExactlyOnceWith(expect.anything(), {
187 environmentId,
188 input: { id: task.id },
189 }),
190 );
191 });
192
193 it("creates on a permitted secondary and reacts to permission changes", async () => {
194 setup();
195 state.secondary = true;
196 const registry = AtomRegistry.make();
197 using _registry = { [Symbol.dispose]: () => registry.dispose() };
198 registry.set(permissions.get(environmentId)!, false);
199 await using screen = await render(
200 <RegistryContext.Provider value={registry}>
201 <ScheduledTasksSettings />
202 </RegistryContext.Provider>,
203 );
204 const create = screen.getByRole("button", { name: "New task" });
205 await expect.element(create).toBeEnabled();
206 await act(() => registry.set(permissions.get(secondaryId)!, false));
207 await expect.element(create).toBeDisabled();
208 await act(() => registry.set(permissions.get(secondaryId)!, true));
209 await expect.element(create).toBeEnabled();
210 await create.click();
211 await expect.element(page.getByLabelText("Runs on")).toHaveTextContent("Secondary");
212 });
213
214 it("keeps the permitted representative as the creation target", async () => {
215 setup();
216 state.secondary = true;
217 await using screen = await render(<ScheduledTasksSettings />);
218 await screen.getByRole("button", { name: "New task" }).click();
219 await expect.element(page.getByLabelText("Runs on")).toHaveTextContent("Laptop");
220 });
221
222 it("disables creation without a connected target", async () => {
223 setup();
224 state.connected = false;
225 await using screen = await render(<ScheduledTasksSettings />);
226 await expect.element(screen.getByRole("button", { name: "New task" })).toBeDisabled();
227 });
228
229 it("keeps a linked task's unsaved edits across a disconnect and reconnect", async () => {
230 setup();
231 await using screen = await render(<ScheduledTasksSettings taskId={task.id} />);
232 await expect.element(page.getByRole("dialog").getByText("Fix login bug")).toBeVisible();
233 const name = page.getByRole("dialog").getByRole("textbox", { name: "Name" });
234 await expect.element(name).toHaveValue("Review issues");
235 await userEvent.fill(name, "Review stale issues");
236
237 state.connected = false;
238 await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);
239
240 await expect.element(name).toHaveValue("Review stale issues");
241
242 state.connected = true;
243 await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);
244 await expect.element(name).toHaveValue("Review stale issues");
245 });
246
247 it("keeps an editor the user opened when the linked task loads later", async () => {
248 setup();
249 state.tasksLoaded = false;
250 await using screen = await render(<ScheduledTasksSettings taskId={task.id} />);
251 await userEvent.click(page.getByRole("button", { name: "New task" }));
252 const dialog = page.getByRole("dialog");
253 const name = dialog.getByRole("textbox", { name: "Name" });
254 await userEvent.fill(name, "My draft");
255
256 state.tasksLoaded = true;
257 await screen.rerender(<ScheduledTasksSettings taskId={task.id} />);
258
259 await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument();
260 await expect.element(name).toHaveValue("My draft");
261 });
262});