diff --git a/docs/usage.md b/docs/usage.md index f718a59..548defa 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -2,18 +2,15 @@ ## Getting started -1. Select **Managed folders → Add folder…**. Choose a local fixed NTFS folder, such as `C:\zipxp-test`. Adding a folder starts read-only analysis. A WSL/UNC folder is not supported. -2. Inspect the overview and storage insights. Folder rows show their policy, known logical/allocation totals, candidate bytes, status, scan time, and native directory-default count. Double-click a folder in Insights to drill down, or choose **Largest files**. -3. Select **Folder settings** and turn on automatic compression. Subfolder inclusion and battery behavior are on the first screen; file exclusions, size/benefit thresholds, quiet period, cooldown, schedule, and free-space reserve are under **Advanced options**. -4. Eligible existing files are queued. New, copied-in, replaced, and changed files are discovered through notifications and periodic scans. The recommended quiet period is 60 seconds; reconciliation runs every two minutes. Busy files retry with backoff. Poor-benefit files stay excluded until their content fingerprint changes or a failed job is explicitly retried. -5. Close the window to keep the tray worker running. Reopen it from the tray. **Start when I sign in** explicitly registers this user's current launch command. **Pause all** / **Pause folder** stops new operations after the current one. **Quit ZipXP** finishes the file in progress, then ends the worker and leaves pending work persisted. -6. Use Activity to search/filter outcomes, copy diagnostics, and retry selected failures. Retry does not re-enable disabled automatic policies. - -Adding a folder for analysis does not compress it. **Compress now** is an explicit one-off job; it does not turn on future automation. Each recursive action shows a scope preview first. Ordinary automatic files have no per-file confirmation dialog. +1. Select **Add folder** and choose a folder on a local NTFS drive, such as `C:\zipxp-test`. ZipXP selects it in **Managed folders** and scans it without changing files. +2. Check the folder’s estimated savings. **Compress once** previews a one-time job. **Turn on auto-compression** asks you to confirm before ZipXP starts handling eligible existing, new, copied and changed files in the background. +3. In **Overview**, **Estimated savings** comes from the latest scans. **Space saved by ZipXP** counts the net disk space change ZipXP measured from its own compression and restores. **Folder size on disk** shows how much space the measured files currently use. +4. Use **Folder settings** to choose subfolders, exclusions and when ZipXP can work. Use **Browse files** to inspect a folder and **Activity** to track progress or retry failed work. +5. Close the window to keep ZipXP running in the tray. Enable **Start when I sign in** if you want ZipXP to start with Windows. **Pause all folders** or **More actions → Pause folder** pauses work after the current file. **Quit ZipXP** stops background work and keeps the queue for next time. ### Decompression and stopping management -- **Restore original size…** (Overview for all folders, Managed folders toolbar per folder, or Storage insights for selected files) uncompresses files so they take their full space again; no files are deleted. It first disables automatic compression for that managed root and cancels pending compression. Re-enabling automation while decompression is pending is rejected. +- **Restore files** in Managed folders or **Restore selected** in Storage insights uncompresses files so they take their full space again; no files are deleted. It first disables automatic compression for that managed root and cancels pending compression. Re-enabling automation while decompression is pending is rejected. - Decompression does not clear existing NTFS directory defaults. The preview reports those defaults, incomplete coverage, omitted entries, and the largest sequential operation's required headroom. - **Turn off Windows' own folder compression** (More menu) is a separate recursive directory-only job within the current policy scope. Existing files stay compressed. Excluded/unreadable/unsupported directories may retain defaults; inspect the next scan. - **Stop managing this folder** (More menu) removes the root, observations, and future jobs. Existing files and native defaults remain unchanged. Historical job measurements are retained. diff --git a/src/ZipXP.App/Web/DesktopBridge.cs b/src/ZipXP.App/Web/DesktopBridge.cs index caaa998..cf4e356 100644 --- a/src/ZipXP.App/Web/DesktopBridge.cs +++ b/src/ZipXP.App/Web/DesktopBridge.cs @@ -17,7 +17,23 @@ private ManagedFolder Root(JsonElement args) => Engine.Store.Roots().FirstOrDefa private static string Text(JsonElement args, string key) => args.TryGetProperty(key, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString()! : throw new ArgumentException($"Missing {key}."); private static bool Flag(JsonElement args, string key) => args.GetProperty(key).GetBoolean(); - private bool Confirm(string text, string title) => !App.Instance.Exiting && MessageBox.Show(owner, text, title, MessageBoxButton.YesNo, title.Contains("Restore", StringComparison.Ordinal) || title.Contains("Stop managing", StringComparison.Ordinal) ? MessageBoxImage.Warning : MessageBoxImage.Information) == MessageBoxResult.Yes; + private bool Confirm(string text, string title) => !App.Instance.Exiting && + MessageBox.Show(owner, text, title, MessageBoxButton.YesNo, + title.Contains("Restore", StringComparison.Ordinal) || title.Contains("Stop managing", StringComparison.Ordinal) ? MessageBoxImage.Warning : MessageBoxImage.Information, + MessageBoxResult.No) == MessageBoxResult.Yes; + + private string PendingWorkNotice(ManagedFolder root) => + Engine.Store.ActiveJobs().Any(j => j.RootId == root.Id) + ? "\n\nThis will cancel the work still queued for this folder." : ""; + + private async Task SavePolicyAsync(ManagedFolder root, FolderPolicy policy) + { + await Engine.SavePolicyAsync(root, policy); + if (!policy.Enabled) return "Settings saved. Auto-compression is off. Compressed files stay compressed."; + return "Settings saved. Auto-compression is on for existing, new and changed files." + + (Engine.Paused ? " Choose Resume all folders to continue." : + policy.Paused ? " Choose Resume folder from More actions to continue." : ""); + } public async Task ExecuteAsync(string command, JsonElement args) { @@ -32,25 +48,40 @@ private static string Text(JsonElement args, string key) => args.TryGetProperty( case "pause": await Engine.SetPausedAsync(Flag(args, "paused")); return Engine.Paused ? "Paused. The current file will finish first." : "Background work resumed."; case "pauseFolder": await Engine.SetFolderPausedAsync(Root(args).Id, Flag(args, "paused")); return "Folder pause setting updated."; case "startup": StartupRegistration.Enabled = Flag(args, "enabled"); return "Sign-in preference saved."; + case "setAutoCompression": + var folder = Root(args); + var enabled = Flag(args, "enabled"); + if (enabled == folder.Policy.Enabled) return "No changes made."; + var title = enabled ? "Turn on auto-compression" : "Turn off auto-compression"; + var detail = enabled + ? "ZipXP will compress eligible existing, new and changed files while it runs. Files will open as usual." + : "ZipXP will stop compressing files automatically here. Compressed files will stay compressed."; + if (!Confirm($"{title} for {folder.Name}?\n\n{detail}" + PendingWorkNotice(folder), title)) return "No changes made."; + return await SavePolicyAsync(folder, folder.Policy with { Enabled = enabled }); case "savePolicy": - var policy = args.GetProperty("policy").Deserialize(Json) ?? throw new ArgumentException("Missing folder settings."); - // Pause is a separate action and cannot be accidentally overwritten by an open settings form. + var submitted = args.GetProperty("policy").Deserialize(Json) ?? throw new ArgumentException("Missing folder settings."); var root = Root(args); - await Engine.SavePolicyAsync(root, policy with { Paused = root.Policy.Paused }); - return "Settings saved. Files already compressed stay compressed until you restore them."; + // Pause is a separate action and cannot be accidentally overwritten by an open settings form. + var policy = submitted with { Paused = root.Policy.Paused }; + if (policy == root.Policy) return "No changes made."; + var pendingNotice = PendingWorkNotice(root); + if (pendingNotice.Length > 0 && !Confirm("Save changes to this folder’s settings?" + pendingNotice, "Save folder settings")) + return "No changes made."; + return await SavePolicyAsync(root, policy); case "queue": return await QueueAsync(args); case "restoreSelected": var selectedRoot = Root(args); var paths = args.GetProperty("paths").Deserialize(Json) ?? []; var wanted = paths.ToHashSet(StringComparer.OrdinalIgnoreCase); - var selected = Engine.Store.Observations(selectedRoot.Id).Where(o => wanted.Contains(o.Path) && o.File is { Directory: false, Compressed: true }).ToArray(); - if (selected.Length == 0) return "No compressed files selected."; - var headroom = checked(selectedRoot.Policy.ReserveBytes + selected.Max(o => o.File!.Logical)); - if (!Confirm($"Restore the original size of {selected.Length} selected files?\n\nNeeds at least {Display.Bytes(headroom)} free on the drive. Automatic compression for this folder will be turned off. No files are deleted.", "Restore selected files")) return "No changes made."; + var selected = Engine.Store.Observations(selectedRoot.Id).Where(o => wanted.Contains(o.Path)).ToArray(); + var restorable = Engine.RestorableFiles(selectedRoot, selected).ToArray(); + if (restorable.Length == 0) return "ZipXP found no selected files it can restore."; + var headroom = checked(selectedRoot.Policy.ReserveBytes + restorable.Max(f => f.Logical)); + if (!Confirm($"Restore the original size of {Plain.Count(restorable.Length, "selected file")}?\n\nNeeds at least {Display.Bytes(headroom)} free on the drive. Automatic compression for this folder will be turned off. No files are deleted.", "Restore selected files")) return "No changes made."; return Queued(await Engine.QueueSelectedAsync(selectedRoot.Id, selected)); case "remove": var removing = Root(args); - if (!Confirm($"Stop managing {removing.Path}?\n\nFiles stay exactly as they are, including any existing compression. To uncompress them first, cancel and choose Restore original size.", "Stop managing folder")) return "No changes made."; + if (!Confirm($"Stop managing {removing.Path}?\n\nFiles stay exactly as they are, including any existing compression. To uncompress them first, cancel and choose Restore files.", "Stop managing folder")) return "No changes made."; await Engine.RemoveAsync(removing.Id); return "Folder removed from ZipXP. Its files stay as they are."; case "retry": var retry = Engine.Store.Jobs().FirstOrDefault(j => j.Id == Text(args, "jobId")) ?? throw new ArgumentException("Activity item no longer exists."); @@ -72,9 +103,11 @@ private object Snapshot() { var roots = Engine.Store.Roots(); var scans = Engine.Store.Scans(); - var entries = roots.SelectMany(r => Engine.Store.Observations(r.Id)).ToArray(); - var files = entries.Where(o => o.File is { Directory: false }).Select(o => o.File!).DistinctBy(f => f.Identity).ToArray(); - var measured = files.Where(f => f.Allocated != null).ToArray(); + var observations = roots.ToDictionary(r => r.Id, r => Engine.Store.Observations(r.Id)); + var entries = observations.Values.SelectMany(items => items).ToArray(); + var measured = entries.Where(o => o.File is { Directory: false, Allocated: not null }) + .Select(o => o.File!).DistinctBy(f => f.Identity); + var savings = Engine.Store.MeasuredSince(DateTime.MinValue); var volumes = new List(); foreach (var name in roots.Select(r => Path.GetPathRoot(r.Path)!).Distinct(StringComparer.OrdinalIgnoreCase)) { @@ -83,10 +116,19 @@ private object Snapshot() } return new { - Folders = roots.Select(r => new { r.Id, r.Name, r.Path, r.Policy, Scan = scans.FirstOrDefault(s => s.RootId == r.Id), Status = Plain.Message(Engine.FolderStatus(r.Id)) }), + Folders = roots.Select(r => new + { + r.Id, r.Name, r.Path, r.Policy, + Scan = scans.FirstOrDefault(s => s.RootId == r.Id), + Status = Plain.Message(Engine.FolderStatus(r.Id)), + CanRestore = Engine.RestorableFiles(r, observations[r.Id]).Any() + }), Jobs = Engine.Store.Jobs().Select(j => new { j.Id, j.RootId, j.Path, FileName = Path.GetFileName(j.Path), j.State, StateText = Plain.JobState(j.State).Text, Action = Plain.Action(j.Operation), Message = Plain.Message(j.Message), j.Delta, Utc = j.FinishedUtc ?? j.CreatedUtc, j.Pending }), Engine.Paused, Startup = StartupRegistration.Enabled, Status = Plain.Message(Engine.Status), Engine.CurrentFile, - Original = measured.Sum(f => f.Logical), Allocated = measured.Sum(f => f.Allocated ?? 0), Unknown = entries.Count(e => e.File == null || (e.File.Directory == false && e.File.Allocated == null)), Volumes = volumes + Savings = new { savings.Delta, savings.Measured }, + Allocated = measured.Sum(f => f.Allocated!.Value), + Unknown = entries.Count(e => e.File == null || (e.File.Directory == false && e.File.Allocated == null)), + Volumes = volumes }; } @@ -129,7 +171,7 @@ private object Insights(JsonElement args) return new { Path = path, Parent = string.Equals(path, root.Path, StringComparison.OrdinalIgnoreCase) ? null : Path.GetDirectoryName(path), page.Rows, page.TotalRows }; } - private string Queued(int count) => $"{count} items queued." + (Engine.Paused ? " Choose Resume all to start." : " See Activity for progress."); + private string Queued(int count) => $"{count} items queued." + (Engine.Paused ? " Choose Resume all folders to start." : " See Activity for progress."); private async Task QueueAsync(JsonElement args) { @@ -140,19 +182,28 @@ private async Task QueueAsync(JsonElement args) : Engine.Store.Roots().Where(r => operation != "Compress" || !r.Policy.Paused).ToArray(); if (roots.Length == 0) return "Add a folder first."; var previews = new List<(ManagedFolder Root, JobPreview Preview)>(); - foreach (var root in roots) previews.Add((root, await Engine.PreviewAsync(root, operation))); - // A restore with zero eligible files still disables automatic compression, matching the native UI. + foreach (var root in roots) + { + var preview = await Engine.PreviewAsync(root, operation); + if (preview.Files > 0) previews.Add((root, preview)); + } + if (previews.Count == 0) return operation switch + { + "Decompress" => "ZipXP found no compressed files it can restore.", + "ClearDefault" => "ZipXP found no folders with Windows compression to turn off.", + _ => "ZipXP found no files it can compress right now." + }; var count = previews.Sum(p => p.Preview.Files); var headroom = previews.Max(p => p.Preview.RequiredHeadroom); var explanation = operation switch { "Decompress" => "Files will take their original space again. Automatic compression will be turned off for these folders. No files are deleted. Windows folder compression, if enabled, can still compress new files independently.", "ClearDefault" => "Windows will stop compressing new files in these folders by itself. Existing compressed files stay compressed.", - _ => "Files will be compressed once in the background. Automatic compression will not be enabled. You can restore their original size later." + _ => "ZipXP will compress these files once. Your auto-compression settings stay as they are. Use Restore files to undo." }; - var title = operation switch { "Decompress" => "Restore original size", "ClearDefault" => "Turn off Windows compression", _ => "Compress preview" }; - var coverage = previews.All(p => p.Preview.Coverage == "Complete primary-stream scan") ? "Everything in these folders was checked." : "Partial scan: items that couldn't be read are left out."; - var scope = roots.Length == 1 ? roots[0].Path : $"{roots.Length} managed folders"; + var title = operation switch { "Decompress" => "Restore original size", "ClearDefault" => "Turn off Windows compression", _ => "Compress once" }; + var coverage = previews.All(p => p.Preview.Coverage == "Complete primary-stream scan") ? "The scan covered the files within your folder settings." : "Some items were skipped or could not be checked."; + var scope = previews.Count == 1 ? previews[0].Root.Path : $"{previews.Count} managed folders"; if (!Confirm($"{scope}\n\n{count} eligible items · {Display.Bytes(previews.Sum(p => p.Preview.LogicalBytes))} in total\nNeeds at least {Display.Bytes(headroom)} free on each affected drive while it works.\n{coverage}\n\n{explanation}\n\nGo ahead?", title)) return "No changes made."; var queued = 0; foreach (var (root, _) in previews) queued += await Engine.QueueScopeAsync(root.Id, operation); diff --git a/src/ZipXP.Core/Services/Engine.cs b/src/ZipXP.Core/Services/Engine.cs index 962ae10..64fcb08 100644 --- a/src/ZipXP.Core/Services/Engine.cs +++ b/src/ZipXP.Core/Services/Engine.cs @@ -110,12 +110,17 @@ public Task PreviewAsync(ManagedFolder root, string operation) => Ex scan.Summary.NativeDefaults, scan.Summary.Coverage); }); + public static IEnumerable RestorableFiles(ManagedFolder root, IEnumerable entries) => + Eligible(entries, root, "Decompress"); + private static IEnumerable Eligible(IEnumerable entries, ManagedFolder root, string operation) => - entries.Where(o => o.File != null && !Rules.Excluded(Path.GetRelativePath(root.Path, o.Path), root.Policy)) - .Select(o => o.File!).Where(f => operation == "ClearDefault" - ? f.Directory && f.Compressed && Rules.AttributeReason(f.Attributes) == null - : !f.Directory && f.Compressed == (operation == "Decompress") && - Rules.Eligibility(f, root.Policy, operation == "Compress", DateTime.UtcNow) == null); + entries.Where(o => o.File is { } f && + (operation == "ClearDefault" + ? f.Directory && f.Compressed && Rules.AttributeReason(f.Attributes) == null + : !f.Directory && f.Compressed == (operation == "Decompress") && + Rules.Eligibility(f, root.Policy, operation == "Compress", DateTime.UtcNow) == null) && + !Rules.Excluded(Path.GetRelativePath(root.Path, o.Path), root.Policy)) + .Select(o => o.File!); private static string DecisionKey(FileRecord file, string operation) => operation == "Compress" ? file.Fingerprint : file.Fingerprint + ":" + operation; diff --git a/src/ZipXP.UI/e2e/desktop.ts b/src/ZipXP.UI/e2e/desktop.ts index 43c9267..9393a7b 100644 --- a/src/ZipXP.UI/e2e/desktop.ts +++ b/src/ZipXP.UI/e2e/desktop.ts @@ -35,7 +35,7 @@ export async function openApp(page: Page, scenario: Scenario = {}) { snapshot.folders = []; snapshot.jobs = []; snapshot.volumes = []; - snapshot.original = 0; + snapshot.savings = { delta: 0, measured: 0 }; snapshot.allocated = 0; } if (scenario.folderCount) { diff --git a/src/ZipXP.UI/e2e/fixtures.ts b/src/ZipXP.UI/e2e/fixtures.ts index b476c18..1c02c87 100644 --- a/src/ZipXP.UI/e2e/fixtures.ts +++ b/src/ZipXP.UI/e2e/fixtures.ts @@ -22,6 +22,7 @@ export const snapshot: Snapshot = { path: `C:\\Users\\Kiran\\${name}`, policy: { ...policy, enabled: i === 0, paused: i === 2 }, status: i === 2 ? "Paused" : "Watching for changes", + canRestore: i === 0, scan: { utc: new Date().toISOString(), logical: (10 - i * 2) * gb, @@ -61,7 +62,7 @@ export const snapshot: Snapshot = { startup: false, status: "Watching for changes", currentFile: null, - original: 24 * gb, + savings: { delta: 1478656 * 2, measured: 4 }, allocated: 15 * gb, unknown: 0, volumes: [{ name: "Local Disk (C:)", total: 512 * gb, free: 124.8 * gb }], diff --git a/src/ZipXP.UI/e2e/interactions.spec.ts b/src/ZipXP.UI/e2e/interactions.spec.ts index d04479d..b0593db 100644 --- a/src/ZipXP.UI/e2e/interactions.spec.ts +++ b/src/ZipXP.UI/e2e/interactions.spec.ts @@ -11,6 +11,52 @@ const nav = (page: import("@playwright/test").Page, name: string) => .getByRole("navigation", { name: "Main navigation" }) .getByRole("button", { name, exact: name !== "Activity" }); +test("narrow screens keep savings and navigation labels visible", async ({ + page, +}) => { + await page.setViewportSize({ width: 390, height: 800 }); + await openApp(page); + await expect( + page.getByRole("heading", { name: "Estimated savings" }), + ).toBeVisible(); + await expect( + page.getByRole("heading", { name: "Space saved by ZipXP" }), + ).toBeVisible(); + await expect( + nav(page, "Managed folders").getByText("Managed folders"), + ).toBeVisible(); + await expect( + nav(page, "Storage insights").getByText("Storage insights"), + ).toBeVisible(); + await expect + .poll(() => + page.evaluate(() => { + const root = document.documentElement; + return root.scrollWidth - root.clientWidth; + }), + ) + .toBeLessThanOrEqual(0); + await page.getByRole("button", { name: "Manage compression" }).click(); + await expect( + page.getByRole("heading", { name: "Managed folders" }), + ).toBeFocused(); + await expect( + page.getByRole("button", { name: "Restore files" }), + ).toBeVisible(); + await page.getByText("More actions", { exact: true }).click(); + await expect( + page.getByRole("button", { name: "Scan again" }), + ).toBeVisible(); + await expect + .poll(() => + page.evaluate(() => { + const root = document.documentElement; + return root.scrollWidth - root.clientWidth; + }), + ) + .toBeLessThanOrEqual(0); +}); + test("settings keep actions visible, validate blanks, and restore keyboard focus", async ({ page, }) => { @@ -18,7 +64,7 @@ test("settings keep actions visible, validate blanks, and restore keyboard focus await openApp(page); await nav(page, "Managed folders").click(); const opener = page.getByRole("button", { - name: "Settings for Work projects", + name: "Folder settings for Work projects", }); await opener.click(); await page.getByText("Advanced settings", { exact: true }).click(); @@ -91,7 +137,7 @@ test("busy operations preserve focus and allow navigation and search", async ({ }) => { await openApp(page, { delay: { queue: 1800 } }); const compress = page.getByRole("button", { - name: "Compress all eligible", + name: "Compress all once", exact: true, }); await compress.click(); @@ -122,7 +168,7 @@ test("action failures are dismissible and do not offer connection recovery", asy queue: "Not enough free space. Restore needs more room on the drive.", }, }); - await page.getByRole("button", { name: "Compress all eligible" }).click(); + await page.getByRole("button", { name: "Compress all once" }).click(); await expect(page.getByRole("alert")).toContainText( "Not enough free space", ); @@ -203,7 +249,7 @@ test("global pause is visible and attention links filter failed activity", async await page.screenshot({ path: `${artifacts}/paused.png`, fullPage: false }); await nav(page, "Managed folders").click(); await expect( - page.getByText("Paused globally", { exact: true }), + page.getByText("Auto on · paused", { exact: true }), ).toBeVisible(); await nav(page, "Overview").click(); await page.getByRole("button", { name: "Review activity" }).click(); @@ -253,7 +299,7 @@ test("minimum desktop size keeps settings actions reachable, including high cont await openApp(page); await nav(page, "Managed folders").click(); await page - .getByRole("button", { name: "Settings for Work projects" }) + .getByRole("button", { name: "Folder settings for Work projects" }) .click(); await page.getByText("Advanced settings", { exact: true }).click(); await expect( @@ -352,7 +398,7 @@ test("many folders keep the selected folder actions nearby", async ({ page.getByRole("heading", { name: "Archive 20", exact: true }), ).toBeInViewport(); await expect( - page.getByRole("button", { name: "Compress now", exact: true }), + page.getByRole("button", { name: "Compress once", exact: true }), ).toBeInViewport(); const dimensions = await page.evaluate(() => ({ doc: document.documentElement.scrollHeight, @@ -429,7 +475,7 @@ test("Quit and startup remain independent of a pending engine action", async ({ }) => { await openApp(page, { delay: { queue: 1800 } }); await page - .getByRole("button", { name: "Compress all eligible", exact: true }) + .getByRole("button", { name: "Compress all once", exact: true }) .click(); const startup = page.getByRole("checkbox", { name: "Start when I sign in", @@ -462,7 +508,6 @@ test("menu actions announce concise labels and return keyboard focus to their tr await nav(page, "Managed folders").click(); const trigger = page.locator(".more-actions > summary"); for (const label of [ - "Restore original size", "Stop managing this folder", "Turn off Windows compression", ]) { @@ -521,7 +566,7 @@ test("advanced settings expose a working scroll cue and persistent save controls await openApp(page); await nav(page, "Managed folders").click(); await page - .getByRole("button", { name: "Settings for Work projects" }) + .getByRole("button", { name: "Folder settings for Work projects" }) .click(); await page.getByText("Advanced settings", { exact: true }).click(); const cue = page.getByRole("button", { @@ -543,7 +588,7 @@ test("the requested monochrome theme uses neutral text, surfaces, borders and fo }) => { await openApp(page); await expect( - page.getByRole("button", { name: "Compress all eligible" }), + page.getByRole("button", { name: "Compress all once" }), ).toBeVisible(); const offPalette = await page.evaluate(() => { const found = new Set(); @@ -624,7 +669,7 @@ test("monochrome error, attention and operational feedback retain separate hiera errors: { queue: "The folder could not be processed." }, }); await page - .getByRole("button", { name: "Compress all eligible", exact: true }) + .getByRole("button", { name: "Compress all once", exact: true }) .click(); await expect(page.locator(".progress-strip")).toBeVisible(); await expect(page.locator(".attention-card")).toHaveCount(0); @@ -692,7 +737,7 @@ test("settings contain scrolling and expose live errors through the footer", asy await openApp(page); await nav(page, "Managed folders").click(); await page - .getByRole("button", { name: "Settings for Work projects" }) + .getByRole("button", { name: "Folder settings for Work projects" }) .click(); await page.getByText("Advanced settings", { exact: true }).click(); const originalY = await page.evaluate(() => scrollY); @@ -837,7 +882,7 @@ test("modal backdrop covers the scrollbar gutter and forced-color primaries use () => document.documentElement.clientWidth, ); await page - .getByRole("button", { name: "Settings for Work projects" }) + .getByRole("button", { name: "Folder settings for Work projects" }) .click(); const modalHeight = await page .getByRole("dialog") @@ -1052,7 +1097,7 @@ test("high-contrast navigation keeps selection and keyboard focus distinct on ev await openApp(page); await expect( page.getByRole("button", { - name: "Compress all eligible", + name: "Compress all once", exact: true, }), ).toBeVisible(); diff --git a/src/ZipXP.UI/e2e/ui.spec.ts b/src/ZipXP.UI/e2e/ui.spec.ts index cb8c17c..c0d6a14 100644 --- a/src/ZipXP.UI/e2e/ui.spec.ts +++ b/src/ZipXP.UI/e2e/ui.spec.ts @@ -11,7 +11,7 @@ test("review all screens with realistic desktop data", async ({ page }) => { await openApp(page); await expect( page.getByRole("button", { - name: "Compress all eligible", + name: "Compress all once", exact: true, }), ).toBeVisible(); @@ -73,7 +73,7 @@ test("review all screens with realistic desktop data", async ({ page }) => { }); await page.keyboard.press("Escape"); await page - .getByRole("button", { name: "Settings for Work projects" }) + .getByRole("button", { name: "Folder settings for Work projects" }) .click(); await page.getByText("Advanced settings", { exact: true }).click(); await expect( diff --git a/src/ZipXP.UI/src/App.test.tsx b/src/ZipXP.UI/src/App.test.tsx index eb57940..d9056cd 100644 --- a/src/ZipXP.UI/src/App.test.tsx +++ b/src/ZipXP.UI/src/App.test.tsx @@ -19,6 +19,7 @@ const fixture: Snapshot = { name: "Work", path: "C:\\Work", status: "Watching", + canRestore: true, scan: { utc: "2026-01-01T12:00:00Z", logical: 1048576, @@ -67,7 +68,7 @@ const fixture: Snapshot = { startup: false, status: "Ready", currentFile: null, - original: 1048576, + savings: { delta: 0, measured: 0 }, allocated: 524288, unknown: 0, volumes: [], @@ -88,33 +89,98 @@ afterEach(() => { cleanup(); vi.resetAllMocks(); }); -it("keeps adding a folder separate from enabling compression", async () => { - vi.mocked(request).mockImplementation(async (command) => - command === "snapshot" - ? ({ ...fixture, folders: [], jobs: [] } as never) - : ("new-folder" as never), - ); +it("selects the newly added folder and keeps the scan separate from compression", async () => { + const added = { + ...fixture.folders[0], + id: "new-folder", + name: "New folder", + path: "C:\\New folder", + scan: null, + canRestore: false, + }; + let folderAdded = false; + vi.mocked(request).mockImplementation(async (command) => { + if (command === "addFolder") { + folderAdded = true; + return added.id as never; + } + if (command === "snapshot") + return { + ...fixture, + folders: folderAdded + ? [...fixture.folders, added] + : fixture.folders, + } as never; + throw new Error(`Unexpected command: ${command}`); + }); render(); await userEvent.click( - await screen.findByRole("button", { name: "Choose your first folder" }), + await screen.findByRole("button", { name: "Add folder" }), ); - expect(request).toHaveBeenCalledWith("addFolder", {}); + const heading = await screen.findByRole("heading", { name: "New folder" }); + expect(document.activeElement).toBe(heading); + expect(screen.getByText("Auto-compression is off.")).toBeTruthy(); + expect( + screen.getByText(/An estimate will appear after the first scan/), + ).toBeTruthy(); + expect( + ( + screen.getByRole("button", { + name: "Compress once", + }) as HTMLButtonElement + ).disabled, + ).toBe(true); + expect(screen.queryByRole("button", { name: "Restore files" })).toBeNull(); expect( vi .mocked(request) - .mock.calls.some(([command]) => - ["queue", "savePolicy"].includes(command), + .mock.calls.every(([command]) => + ["snapshot", "addFolder"].includes(command), ), - ).toBe(false); + ).toBe(true); +}); + +it("keeps the estimate and ZipXP's measured savings separate", async () => { + render(); + const estimate = ( + await screen.findByRole("heading", { name: "Estimated savings" }) + ).parentElement!; + const actual = screen.getByRole("heading", { + name: "Space saved by ZipXP", + }).parentElement!; + expect(within(estimate).getByText("128 KB")).toBeTruthy(); + expect(within(actual).getByText("None recorded")).toBeTruthy(); + await userEvent.click( + screen.getByRole("button", { name: "Manage compression" }), + ); + expect(screen.getByRole("heading", { name: "Managed folders" })).toBe( + document.activeElement, + ); + expect(screen.getByRole("button", { name: "Restore files" })).toBeTruthy(); +}); + +it("offers an explicit auto-compression action for the selected folder", async () => { + render(); + await userEvent.click( + await screen.findByRole("button", { name: "Manage compression" }), + ); + const enable = screen.getByRole("button", { + name: "Turn on auto-compression", + }); + await userEvent.click(enable); + expect(request).toHaveBeenCalledWith("setAutoCompression", { + rootId: "work", + enabled: true, + }); }); it("saves an explicitly enabled folder policy", async () => { render(); - await screen.findByRole("button", { name: "Compress all eligible" }); + await screen.findByRole("button", { name: "Compress all once" }); await userEvent.click( screen.getByRole("button", { name: "Managed folders" }), ); await userEvent.click( - screen.getByRole("button", { name: "Settings for Work" }), + screen.getByRole("button", { name: "Folder settings for Work" }), ); const dialog = screen.getByRole("dialog"); await userEvent.click( @@ -137,7 +203,7 @@ it("keeps a rejected operation visible to the user", async () => { }); render(); await userEvent.click( - await screen.findByRole("button", { name: "Compress all eligible" }), + await screen.findByRole("button", { name: "Compress all once" }), ); await waitFor(() => expect(screen.getByRole("alert").textContent).toContain( @@ -151,7 +217,7 @@ it("keeps a rejected operation visible to the user", async () => { }); it("filters activity and retries the selected failed item", async () => { render(); - await screen.findByRole("button", { name: "Compress all eligible" }); + await screen.findByRole("button", { name: "Compress all once" }); await userEvent.click(screen.getByRole("button", { name: /Activity/ })); await userEvent.type( screen.getByRole("textbox", { name: "Search activity" }), @@ -175,7 +241,7 @@ it("updates the sign-in checkbox immediately and restores it if Windows rejects return structuredClone(fixture) as never; }); render(); - await screen.findByRole("button", { name: "Compress all eligible" }); + await screen.findByRole("button", { name: "Compress all once" }); const checkbox = screen.getByRole("checkbox", { name: "Start when I sign in", }) as HTMLInputElement; diff --git a/src/ZipXP.UI/src/App.tsx b/src/ZipXP.UI/src/App.tsx index cdede64..b1bfafb 100644 --- a/src/ZipXP.UI/src/App.tsx +++ b/src/ZipXP.UI/src/App.tsx @@ -58,9 +58,9 @@ const pages = [ { name: "Activity", icon: Activity }, ] as const; const hints: Record = { - Overview: "Your storage, savings, and background activity.", + Overview: "See what you could save and what ZipXP has already saved.", "Managed folders": - "Choose which folders to watch and how to compress them.", + "Choose a folder to compress once, turn on auto-compression, or restore files.", "Storage insights": "Find the files and folders using the most space.", Activity: "Track work and resolve files that need attention.", }; @@ -231,6 +231,8 @@ function useScrollEdges(contentKey?: string | number) { export default function App() { const [page, setPage] = useState("Overview"); + const heading = useRef(null); + const focusPageHeading = useRef(false); const [data, setData] = useState(null); const [actionError, setError] = useState(""); const [connectionError, setConnectionError] = useState(""); @@ -244,6 +246,7 @@ export default function App() { const [actionLabel, setActionLabel] = useState(""); const [confirmation, setConfirmation] = useState(false); const [selectedId, setSelectedId] = useState(""); + const [addedFolderId, setAddedFolderId] = useState(""); const [editing, setEditing] = useState(null); const [activityFilter, setActivityFilter] = useState("All"); const loading = useRef(false), @@ -276,9 +279,32 @@ export default function App() { }, [refresh]); useEffect(() => { document.scrollingElement?.scrollTo?.({ top: 0, left: 0 }); + if (focusPageHeading.current) { + focusPageHeading.current = false; + heading.current?.focus({ preventScroll: true }); + } }, [page]); + const openPage = (next: Page) => { + if (next === page) return; + focusPageHeading.current = true; + setPage(next); + }; const folders = data?.folders ?? []; - const selected = folders.find((f) => f.id === selectedId) ?? folders[0]; + const selected = + folders.find((f) => f.id === selectedId) ?? + (addedFolderId ? undefined : folders[0]); + const selectFolder = (id: string) => { + setAddedFolderId(""); + setSelectedId(id); + }; + const newFolderReady = Boolean( + addedFolderId && selected?.id === addedFolderId, + ); + useEffect(() => { + if (!newFolderReady || page !== "Managed folders") return; + document.getElementById("selected-folder-title")?.focus(); + setAddedFolderId(""); + }, [newFolderReady, page]); async function act(action: () => Promise, announce = true) { if (command.current || connectionError || exitRequested.current) return; command.current = true; @@ -310,9 +336,10 @@ export default function App() { act(async () => { const id = await request("addFolder", {}); if (id) { + setAddedFolderId(id); setSelectedId(id); - setPage("Managed folders"); - return "Folder added. The first scan only reads your files. Open Settings to turn on automatic compression."; + openPage("Managed folders"); + return "Folder added. ZipXP scans for possible savings and leaves your files as they are."; } }); const queue = ( @@ -365,7 +392,7 @@ export default function App() { const failed = data?.jobs.filter((j) => j.state === "Failed").length ?? 0; const openFailures = () => { setActivityFilter("Failed"); - setPage("Activity"); + openPage("Activity"); }; const footerStatus = quitting ? { Icon: Power, text: "Quitting ZipXP…" } @@ -407,7 +434,6 @@ export default function App() { ZipXPLocal storage manager -
WORKSPACE