Open History to see the last commit
1import { RegistryProvider } from "@effect/atom-react";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 ProjectId,
5 ThreadId,
6 type StorageCleanupReport,
7} from "@t3tools/contracts";
8import { act, type ReactNode } from "react";
9import { createRoot, type Root } from "react-dom/client";
10import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
11import { page } from "vite-plus/test/browser";
12
13const state = vi.hoisted(() => ({
14 settings: {} as typeof DEFAULT_SERVER_SETTINGS,
15 run: vi.fn(),
16 report: null as StorageCleanupReport | null,
17}));
18
19vi.mock(import("../../state/server"), async (original) => {
20 const actual = await original();
21 const { Atom } = await import("effect/reactivity");
22 const report = Atom.make(() => ({ _tag: "Success", value: state.report, waiting: false }));
23 const allowed = Atom.make(true);
24 return {
25 ...actual,
26 serverEnvironment: {
27 ...actual.serverEnvironment,
28 storageCleanupReport: (() => report) as never,
29 runStorageCleanup: {
30 ...actual.serverEnvironment.runStorageCleanup,
31 permissionAtom: () => allowed,
32 },
33 },
34 };
35});
36vi.mock(import("../../state/use-atom-command"), async (original) => ({
37 ...(await original()),
38 useAtomCommand: (() => state.run) as never,
39}));
40vi.mock(import("./SettingsScopeContext"), async (original) => ({
41 ...(await original()),
42 useSettingsScope: (() => {
43 const environment = {
44 environmentId: "env",
45 label: "Build workstation",
46 serverConfig: {
47 settings: state.settings,
48 environment: {
49 capabilities: {
50 storageCleanup: true,
51 storageCleanupRun: true,
52 settledWorktreeCleanup: true,
53 },
54 },
55 },
56 };
57 return {
58 scope: { kind: "environment" },
59 environments: [environment],
60 connectedEnvironments: [environment],
61 targets: [],
62 target: null,
63 };
64 }) as never,
65}));
66vi.mock(import("./useScopedSettings"), async (original) => ({
67 ...(await original()),
68 useScopedSettings: (() => state.settings) as never,
69 useScopedSettingsMixed: () => false,
70 useUpdateScopedSettings: () => vi.fn(),
71 useClearScopedSettings: () => vi.fn(),
72}));
73// The real page container needs a router and the real row reads write permission and
74// overrides from live environment state; this suite is about the cleanup panel.
75vi.mock(import("./settingsLayout"), async (original) => ({
76 ...(await original()),
77 SettingsPageContainer: (({ children }: { children: ReactNode }) => children) as never,
78 SettingsRow: ({ title, description, control, children }) => (
79 <div>
80 <h3>{title}</h3>
81 {description}
82 {control}
83 {children}
84 </div>
85 ),
86 SettingResetButton: (() => null) as never,
87}));
88vi.mock(import("../ui/toast"), async (original) => {
89 const actual = await original();
90 return { ...actual, toastManager: { ...actual.toastManager, add: vi.fn() } };
91});
92
93import { StorageSettingsPanel } from "./StorageSettings";
94
95let root: Root;
96let container: HTMLDivElement;
97
98beforeEach(() => {
99 state.settings = {
100 ...DEFAULT_SERVER_SETTINGS,
101 storageCleanup: {
102 worktreeKeepWhen: "uncommitted-changes",
103 worktreeAfterDays: null,
104 worktreeSettledAfterDays: null,
105 worktreeOnMerge: false,
106 worktreeOnDelete: false,
107 worktreeUnchanged: false,
108 browserArtifactsAfterDays: null,
109 logsAfterDays: null,
110 },
111 projectSettingsOverrides: {},
112 };
113 state.report = null;
114 state.run.mockReset();
115 container = document.createElement("div");
116 document.body.append(container);
117 root = createRoot(container);
118});
119
120afterEach(async () => {
121 await act(async () => root.unmount());
122 container.remove();
123});
124
125async function render() {
126 await act(async () =>
127 root.render(
128 <RegistryProvider>
129 <StorageSettingsPanel />
130 </RegistryProvider>,
131 ),
132 );
133 return Array.from(container.querySelectorAll("button")).find(
134 (button) => button.textContent === "Delete now",
135 )!;
136}
137
138it.each(["machine-wide immediate", "project custom"])(
139 "runs cleanup when only %s settled retention is enabled",
140 async (scope) => {
141 if (scope === "machine-wide immediate") {
142 state.settings = {
143 ...state.settings,
144 storageCleanup: { ...state.settings.storageCleanup, worktreeSettledAfterDays: 0 },
145 };
146 } else {
147 state.settings = {
148 ...state.settings,
149 projectSettingsOverrides: {
150 [ProjectId.make("project")]: {
151 worktreeCleanup: {
152 mode: "custom",
153 rules: { ...state.settings.storageCleanup, worktreeSettledAfterDays: 7 },
154 },
155 },
156 },
157 };
158 }
159 const report: StorageCleanupReport = {
160 trigger: "manual",
161 startedAt: "2026-10-14T12:00:00.000Z",
162 finishedAt: "2026-10-14T12:00:01.000Z",
163 entries: [],
164 counts: { removed: 0, kept: 0, failed: 0 },
165 omittedCount: 0,
166 bytesFreed: 0,
167 };
168 let complete!: (result: { _tag: "Success"; value: StorageCleanupReport }) => void;
169 state.run.mockImplementation(() => new Promise((resolve) => (complete = resolve)));
170 const button = await render();
171
172 expect(button.disabled).toBe(false);
173 await act(async () => button.click());
174 expect(state.run).toHaveBeenCalledExactlyOnceWith({ environmentId: "env", input: {} });
175 expect(button.disabled).toBe(true);
176 expect(button.textContent).toBe("Deleting…");
177
178 await act(async () => complete({ _tag: "Success", value: report }));
179 expect(button.disabled).toBe(false);
180 expect(button.textContent).toBe("Delete now");
181 },
182);
183
184it("keeps cleanup disabled when settled retention and all other rules are off", async () => {
185 const button = await render();
186
187 expect(button.disabled).toBe(true);
188 await act(async () => button.click());
189 expect(state.run).not.toHaveBeenCalled();
190});
191
192it("shows orphan sizes and identifies failed worktrees with one connected machine", async () => {
193 state.settings = {
194 ...state.settings,
195 storageCleanup: { ...state.settings.storageCleanup, worktreeSettledAfterDays: 0 },
196 };
197 state.report = {
198 trigger: "manual",
199 startedAt: "2026-10-14T12:00:00.000Z",
200 finishedAt: "2026-10-14T12:00:01.000Z",
201 entries: [
202 {
203 kind: "worktree",
204 outcome: "kept",
205 path: "/worktrees/repo/orphan",
206 projectPath: null,
207 threadId: null,
208 threadTitle: null,
209 reason: "No thread uses this folder, and it isn't a git worktree",
210 bytes: 6600000,
211 files: null,
212 },
213 {
214 kind: "worktree",
215 outcome: "failed",
216 path: "/worktrees/repo/thread-checkout",
217 projectPath: "/projects/repo",
218 threadId: ThreadId.make("thread"),
219 threadTitle: "Thread title",
220 reason: "Git index is locked. Status will resume when the index lock is removed.",
221 bytes: null,
222 files: null,
223 },
224 ],
225 counts: { removed: 0, kept: 1, failed: 1 },
226 omittedCount: 0,
227 bytesFreed: 0,
228 };
229 await render();
230 const lastRun = Array.from(container.querySelectorAll("button")).find((button) =>
231 button.textContent?.includes("Last run"),
232 )!;
233 await act(async () => lastRun.click());
234 const titles = Array.from(container.querySelectorAll("h3"), (heading) => heading.textContent);
235 expect(titles).toContain("/worktrees/repo/orphan");
236 expect(titles).toContain("thread-checkout");
237 const failedRow = page.elementLocator(
238 page.getByRole("heading", { name: "thread-checkout", exact: true }).element().parentElement!,
239 );
240 await expect.element(failedRow.getByText("Build workstation", { exact: true })).toBeVisible();
241 await expect.element(failedRow.getByText("/projects/repo", { exact: true })).toBeVisible();
242 await expect
243 .element(failedRow.getByText("/worktrees/repo/thread-checkout", { exact: true }))
244 .toBeVisible();
245 await expect.element(failedRow.getByText("Thread title", { exact: true })).toBeVisible();
246 await expect
247 .element(
248 failedRow.getByText(
249 "Git index is locked. Status will resume when the index lock is removed.",
250 { exact: true },
251 ),
252 )
253 .toBeVisible();
254 expect(titles).not.toContain("/worktrees/repo/thread-checkout");
255 expect(container.textContent).toContain(
256 "No thread uses this folder, and it isn't a git worktree",
257 );
258 expect(container.textContent).toContain("6.29 MB");
259 expect(container.textContent).toContain("0 B recovered.");
260});