Skip to content

Commit 77ed8fe

Browse files
committed
fix(web): keep retention status stable while saves settle
1 parent 96aabaa commit 77ed8fe

3 files changed

Lines changed: 249 additions & 38 deletions

File tree

‎apps/web/src/components/settings/StorageSettings.browser.test.tsx‎

Lines changed: 180 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ import { expect, it, vi } from "vite-plus/test";
66

77
const state = vi.hoisted(() => ({
88
settings: {} as typeof DEFAULT_SERVER_SETTINGS,
9+
targets: [] as {
10+
environmentId: string;
11+
settings: typeof DEFAULT_SERVER_SETTINGS;
12+
}[],
913
run: vi.fn(),
14+
update: vi.fn(),
1015
report: null as StorageCleanupReport | null,
1116
}));
1217

@@ -34,11 +39,11 @@ vi.mock(import("../../state/use-atom-command"), async (original) => ({
3439
vi.mock(import("./SettingsScopeContext"), async (original) => ({
3540
...(await original()),
3641
useSettingsScope: (() => {
37-
const environment = {
38-
environmentId: "env",
39-
label: "Build workstation",
42+
const environments = state.targets.map(({ environmentId, settings }) => ({
43+
environmentId,
44+
label: environmentId,
4045
serverConfig: {
41-
settings: state.settings,
46+
settings,
4247
environment: {
4348
capabilities: {
4449
storageCleanup: true,
@@ -47,30 +52,34 @@ vi.mock(import("./SettingsScopeContext"), async (original) => ({
4752
},
4853
},
4954
},
50-
};
55+
}));
5156
return {
52-
scope: { kind: "environment" },
53-
environments: [environment],
54-
connectedEnvironments: [environment],
55-
targets: [],
56-
target: null,
57+
scope: { kind: "all" },
58+
environments,
59+
connectedEnvironments: environments,
60+
targets: state.targets.map(({ environmentId, settings }) => ({
61+
environmentId,
62+
settings,
63+
})),
64+
target: state.targets[0] ? { settings: state.targets[0].settings } : null,
5765
};
5866
}) as never,
5967
}));
6068
vi.mock(import("./useScopedSettings"), async (original) => ({
6169
...(await original()),
6270
useScopedSettings: (() => state.settings) as never,
6371
useScopedSettingsMixed: () => false,
64-
useUpdateScopedSettings: () => vi.fn(),
72+
useUpdateScopedSettings: () => state.update,
6573
useClearScopedSettings: () => vi.fn(),
6674
}));
6775
vi.mock(import("./settingsLayout"), async (original) => ({
6876
...(await original()),
6977
SettingsPageContainer: (({ children }: { children: ReactNode }) => children) as never,
70-
SettingsRow: ({ title, description, control, children }) => (
78+
SettingsRow: ({ title, description, status, control, children }) => (
7179
<div>
7280
<h3>{title}</h3>
7381
{description}
82+
{status}
7483
{control}
7584
{children}
7685
</div>
@@ -101,6 +110,17 @@ function setup() {
101110
};
102111
state.report = null;
103112
state.run.mockReset();
113+
state.targets = [
114+
{ environmentId: "machine-a", settings: state.settings },
115+
{
116+
environmentId: "machine-b",
117+
settings: {
118+
...state.settings,
119+
storageCleanup: { ...state.settings.storageCleanup },
120+
},
121+
},
122+
];
123+
state.update.mockReset();
104124
}
105125

106126
const panel = () => (
@@ -122,3 +142,151 @@ it("keeps cleanup disabled when settled retention and all other rules are off",
122142
await act(async () => button.click());
123143
expect(state.run).not.toHaveBeenCalled();
124144
});
145+
146+
function setArtifactRetention(machineIndex: number, value: number | null) {
147+
const target = state.targets[machineIndex]!;
148+
target.settings = {
149+
...target.settings,
150+
storageCleanup: { ...target.settings.storageCleanup, browserArtifactsAfterDays: value },
151+
};
152+
if (machineIndex === 0) state.settings = target.settings;
153+
}
154+
155+
function retentionSwitch(container: HTMLElement) {
156+
return Array.from(container.querySelectorAll<HTMLButtonElement>('[role="switch"]')).find(
157+
(control) => control.getAttribute("aria-label") === "Delete old browser artifacts",
158+
)!;
159+
}
160+
161+
function artifactStatus(container: HTMLElement) {
162+
const title = Array.from(container.querySelectorAll("h3")).find(
163+
(heading) => heading.textContent === "Delete old browser artifacts",
164+
);
165+
return title?.parentElement?.querySelector("span[aria-hidden]") as HTMLSpanElement;
166+
}
167+
168+
function logsStatus(container: HTMLElement) {
169+
const title = Array.from(container.querySelectorAll("h3")).find(
170+
(heading) => heading.textContent === "Delete old rotated logs",
171+
);
172+
return title?.parentElement?.querySelector("span[aria-hidden]") as HTMLSpanElement;
173+
}
174+
175+
it("keeps a uniform retention rule free of a transient mixed warning while machines save", async () => {
176+
setup();
177+
setArtifactRetention(0, 9);
178+
setArtifactRetention(1, 9);
179+
let onSettled: (() => void) | undefined;
180+
state.update.mockImplementation((_patch, options) => {
181+
onSettled = options?.onSettled;
182+
});
183+
184+
await using screen = await render(panel());
185+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("true");
186+
187+
await act(async () =>
188+
screen.container
189+
.querySelector<HTMLButtonElement>('[aria-label="Increase Delete old browser artifacts"]')!
190+
.click(),
191+
);
192+
setArtifactRetention(0, 10);
193+
const machineB = state.targets[1]!;
194+
machineB.settings = {
195+
...machineB.settings,
196+
storageCleanup: { ...machineB.settings.storageCleanup, logsAfterDays: 30 },
197+
};
198+
await screen.rerender(panel());
199+
200+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("true");
201+
expect(logsStatus(screen.container).getAttribute("aria-hidden")).toBe("false");
202+
203+
setArtifactRetention(1, 10);
204+
await act(async () => onSettled?.());
205+
await screen.rerender(panel());
206+
207+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("true");
208+
expect(logsStatus(screen.container).getAttribute("aria-hidden")).toBe("false");
209+
});
210+
211+
it.each([14, 30])(
212+
"shows genuine differences after a partial save with a second value of %i",
213+
async (secondValue) => {
214+
setup();
215+
setArtifactRetention(0, 14);
216+
setArtifactRetention(1, secondValue);
217+
let onSettled: (() => void) | undefined;
218+
state.update.mockImplementation((_patch, options) => {
219+
onSettled = options?.onSettled;
220+
});
221+
222+
await using screen = await render(panel());
223+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe(
224+
String(secondValue === 14),
225+
);
226+
227+
await act(async () => retentionSwitch(screen.container).click());
228+
setArtifactRetention(0, null);
229+
await screen.rerender(panel());
230+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe(
231+
String(secondValue === 14),
232+
);
233+
234+
await act(async () => onSettled?.());
235+
await screen.rerender(panel());
236+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("false");
237+
},
238+
);
239+
240+
it("keeps the starting status until overlapping saves for the selected machines settle", async () => {
241+
setup();
242+
const onSettled: (() => void)[] = [];
243+
state.update.mockImplementation((_patch, options) => {
244+
if (options?.onSettled) onSettled.push(options.onSettled);
245+
});
246+
247+
await using screen = await render(panel());
248+
await act(async () => retentionSwitch(screen.container).click());
249+
setArtifactRetention(0, 8);
250+
await screen.rerender(panel());
251+
await act(async () => retentionSwitch(screen.container).click());
252+
setArtifactRetention(0, null);
253+
setArtifactRetention(1, 8);
254+
await screen.rerender(panel());
255+
256+
expect(onSettled).toHaveLength(2);
257+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("true");
258+
await act(async () => onSettled[0]!());
259+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("true");
260+
261+
setArtifactRetention(1, null);
262+
await act(async () => onSettled[1]!());
263+
await screen.rerender(panel());
264+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("true");
265+
});
266+
267+
it("derives mixed status from a newly selected machine set during an older save", async () => {
268+
setup();
269+
let onSettled: (() => void) | undefined;
270+
state.update.mockImplementation((_patch, options) => {
271+
onSettled = options?.onSettled;
272+
});
273+
274+
await using screen = await render(panel());
275+
await act(async () => retentionSwitch(screen.container).click());
276+
setArtifactRetention(0, 8);
277+
state.targets[1] = {
278+
...state.targets[1]!,
279+
environmentId: "machine-c",
280+
settings: {
281+
...state.targets[1]!.settings,
282+
storageCleanup: { ...state.targets[1]!.settings.storageCleanup },
283+
},
284+
};
285+
setArtifactRetention(1, 30);
286+
await screen.rerender(panel());
287+
288+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("false");
289+
await act(async () => onSettled?.());
290+
await screen.rerender(panel());
291+
expect(artifactStatus(screen.container).getAttribute("aria-hidden")).toBe("false");
292+
});

‎apps/web/src/components/settings/StorageSettings.tsx‎

Lines changed: 40 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -694,19 +694,52 @@ export function StorageCleanupSections() {
694694
const { scope, connectedEnvironments, targets } = useSettingsScope();
695695
const scopedSettings = useScopedSettings();
696696
const updateSettings = useUpdateScopedSettings();
697+
const [pendingRules, setPendingRules] = useState(
698+
() => new Map<string, { count: number; mixed: boolean }>(),
699+
);
697700
if (scope.kind === "project" || scope.kind === "checkout") return null;
698701
const settings = scopedSettings.storageCleanup;
702+
const targetSetKey = JSON.stringify(targets.map((target) => target.environmentId).sort());
703+
const currentRuleMixed = (key: "browserArtifactsAfterDays" | "logsAfterDays") =>
704+
targets.length >= 2 &&
705+
targets.some((target) => target.settings.storageCleanup[key] !== settings[key]);
706+
const saveRule = (
707+
key: "browserArtifactsAfterDays" | "logsAfterDays",
708+
patch: Partial<StorageCleanupSettings>,
709+
) => {
710+
const pendingKey = `${targetSetKey}:${key}`;
711+
setPendingRules((current) => {
712+
const active = current.get(pendingKey);
713+
return new Map(current).set(pendingKey, {
714+
count: (active?.count ?? 0) + 1,
715+
mixed: active?.mixed ?? currentRuleMixed(key),
716+
});
717+
});
718+
updateSettings(
719+
{ storageCleanup: patch },
720+
{
721+
onSettled: () => {
722+
setPendingRules((current) => {
723+
const pending = current.get(pendingKey);
724+
if (!pending) return current;
725+
const next = new Map(current);
726+
if (pending.count === 1) next.delete(pendingKey);
727+
else next.set(pendingKey, { ...pending, count: pending.count - 1 });
728+
return next;
729+
});
730+
},
731+
},
732+
);
733+
};
699734
const ruleStatus = (key: "browserArtifactsAfterDays" | "logsAfterDays") => {
700735
if (targets.length < 2) return undefined;
701-
const mixed = targets.some((target) => target.settings.storageCleanup[key] !== settings[key]);
736+
const mixed = pendingRules.get(`${targetSetKey}:${key}`)?.mixed ?? currentRuleMixed(key);
702737
return (
703738
<span className={mixed ? undefined : "invisible"} aria-hidden={!mixed}>
704739
Mixed across selected machines
705740
</span>
706741
);
707742
};
708-
const update = (patch: Partial<StorageCleanupSettings>) =>
709-
updateSettings({ storageCleanup: patch });
710743
const databaseStorageNotice = (
711744
<DatabaseStorageNotice
712745
environments={connectedEnvironments.filter(
@@ -739,7 +772,9 @@ export function StorageCleanupSections() {
739772
<RetentionControl
740773
label="Delete old browser artifacts"
741774
value={settings.browserArtifactsAfterDays}
742-
onChange={(browserArtifactsAfterDays) => update({ browserArtifactsAfterDays })}
775+
onChange={(browserArtifactsAfterDays) =>
776+
saveRule("browserArtifactsAfterDays", { browserArtifactsAfterDays })
777+
}
743778
/>
744779
}
745780
/>
@@ -752,7 +787,7 @@ export function StorageCleanupSections() {
752787
<RetentionControl
753788
label="Delete old rotated logs"
754789
value={settings.logsAfterDays}
755-
onChange={(logsAfterDays) => update({ logsAfterDays })}
790+
onChange={(logsAfterDays) => saveRule("logsAfterDays", { logsAfterDays })}
756791
/>
757792
}
758793
/>

‎apps/web/src/components/settings/useScopedSettings.ts‎

Lines changed: 29 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,18 @@ export function useScopedSettingSource(keys: readonly (keyof ServerSettings)[])
4949

5050
function useRunScopedPlan() {
5151
const persistServer = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
52-
return (plan: ReturnType<typeof planScopedSettingsPatch>, onFailed?: () => void) => {
52+
return (
53+
plan: ReturnType<typeof planScopedSettingsPatch>,
54+
options?: { readonly onFailed?: () => void; readonly onSettled?: () => void },
55+
) => {
5356
if (plan.unavailableReason) {
5457
toastManager.add({
5558
type: "warning",
5659
title: "Setting not saved",
5760
description: plan.unavailableReason,
5861
});
59-
onFailed?.();
62+
options?.onFailed?.();
63+
options?.onSettled?.();
6064
return;
6165
}
6266
void persistScopedSettingsPatch(
@@ -77,32 +81,36 @@ function useRunScopedPlan() {
7781
return persistServer(request);
7882
},
7983
persistClientSettingsPatch,
80-
).then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
81-
if (failedEnvironments.length === 0) return;
82-
onFailed?.();
83-
toastManager.add({
84-
type: "error",
85-
title:
86-
savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
87-
description: [
88-
...failedEnvironments.map(
89-
({ label, message }) => `Could not save on ${label}: ${message}`,
90-
),
91-
...(savedEnvironmentCount > 0
92-
? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
93-
: []),
94-
].join("\n"),
95-
});
96-
});
84+
)
85+
.then(({ failedEnvironments, savedEnvironments, savedEnvironmentCount }) => {
86+
if (failedEnvironments.length === 0) return;
87+
options?.onFailed?.();
88+
toastManager.add({
89+
type: "error",
90+
title:
91+
savedEnvironmentCount > 0 ? "Setting saved on some environments" : "Setting not saved",
92+
description: [
93+
...failedEnvironments.map(
94+
({ label, message }) => `Could not save on ${label}: ${message}`,
95+
),
96+
...(savedEnvironmentCount > 0
97+
? [`Saved on ${savedEnvironments.map(({ label }) => label).join(", ")}.`]
98+
: []),
99+
].join("\n"),
100+
});
101+
})
102+
.finally(options?.onSettled);
97103
};
98104
}
99105

100106
export function useUpdateScopedSettings() {
101107
const { scope, environments } = useSettingsScope();
102108
const run = useRunScopedPlan();
103109
/** `onFailed` runs when any target rejects or drops the patch, so a draft can fall back. */
104-
return (patch: ScopedSettingsPatch, options?: { readonly onFailed?: () => void }) =>
105-
run(planScopedSettingsPatch(scope, environments, patch), options?.onFailed);
110+
return (
111+
patch: ScopedSettingsPatch,
112+
options?: { readonly onFailed?: () => void; readonly onSettled?: () => void },
113+
) => run(planScopedSettingsPatch(scope, environments, patch), options);
106114
}
107115

108116
export function useClearScopedSettings() {

0 commit comments

Comments
 (0)