Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/image compression tool: add integration into the cleanup tool
Adorian Dorane8ab64b06a75
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex eb8f7fd4a7..3ea9367b76 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2936,6 +2936,7 @@"cleanup_confirm_compacting_title": "Compacting database is a slow operation","cleanup_confirm_compacting": "Compacting the database can take several minutes, depending on its size and on the performance of the machine running Trilium. Also, up to {{space}} of free disk space on the machine is temporarily needed (in the data directory and the system's temporary directory).","cleanup_compact_notice": "This operation may take several minutes and Trilium will not respond until it completes.",+ "cleanup_compress_images_help": "Recompresses every image in the database under the settings below. Unlike the steps above it deletes nothing — it rewrites images to weigh less, which cannot be undone and is not counted in the estimate, since what an image will compress to is only known once it has been. The space it frees is included in the total reported when the cleanup finishes.","compress_summary_reading": "Reading…","compress_summary_failed": "Could not read what is here.","compress_summary_scope_one": "{{title}}, {{count}} descendant note",diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts b/apps/client/src/widgets/dialogs/image_compression/image_compression_options.tsindex ee793c1c27..797e7db5c8 100644--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_options.ts@@ -58,15 +58,16 @@ export const MIN_MAX_WIDTH_HEIGHT = 1;* user did not have in mind.*/export function readImageCompressionOptions(- stored: Partial<ImageCompressionToolOptions> | null | undefined+ stored: Partial<ImageCompressionToolOptions> | null | undefined,+ defaults: ImageCompressionDefaults = IMAGE_COMPRESSION_DEFAULTS): ImageCompressionToolOptions {return {resize: stored?.resize ?? true,maxWidthHeight: isPositiveInteger(stored?.maxWidthHeight)? Number(stored?.maxWidthHeight): DEFAULT_MAX_WIDTH_HEIGHT,- jpegHandling: readHandling(stored?.jpegHandling, IMAGE_JPEG_HANDLINGS, "compress"),- pngHandling: readHandling(stored?.pngHandling, IMAGE_PNG_HANDLINGS, "optimize"),+ jpegHandling: readHandling(stored?.jpegHandling, IMAGE_JPEG_HANDLINGS, defaults.jpegHandling),+ pngHandling: readHandling(stored?.pngHandling, IMAGE_PNG_HANDLINGS, defaults.pngHandling),quality: isQuality(stored?.quality) ? Number(stored?.quality) : DEFAULT_QUALITY,conversionQuality: isQuality(stored?.conversionQuality)? Number(stored?.conversionQuality)@@ -75,6 +76,36 @@ export function readImageCompressionOptions(};}+/**+ * What a host's first run opens on, for the two choices hosts genuinely differ on. Everything else+ * — the bound, the qualities — means the same wherever the rows are shown.+ */+export interface ImageCompressionDefaults {+ jpegHandling: ImageJpegHandling;+ pngHandling: ImagePngHandling;+}++/** The image compression dialog's own: act on both formats, since acting is what it was opened for. */+export const IMAGE_COMPRESSION_DEFAULTS: ImageCompressionDefaults = {+ jpegHandling: "compress",+ pngHandling: "optimize"+};++/**+ * Where the cleanup tool starts instead: scaling only, neither format re-encoded.+ *+ * It runs over every image in the database in one unattended pass, where the dialog is aimed at+ * images the user has just been looking at — so the same setting is a much larger bet here. Scaling+ * is the one step that is bounded by what it finds: an image already within the bound is left+ * exactly as it was, so a database of screenshots and diagrams comes through untouched. Re-encoding+ * is not bounded by anything and costs quality on every image it reaches, which is a choice to make+ * deliberately rather than one to find already ticked.+ */+export const CONSERVATIVE_IMAGE_COMPRESSION_DEFAULTS: ImageCompressionDefaults = {+ jpegHandling: "keep",+ pngHandling: "keep"+};+/** The longest edge the first run offers to scale down to: the width of a Full HD screen. */export const DEFAULT_MAX_WIDTH_HEIGHT = 1920;diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.cssindex 29e45c6296..304dd126b7 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css@@ -117,6 +117,12 @@--cleanup-item-color: var(--cleanup-revisions-color);}+ /* Named like the rows above it, but transparent: recompressing takes no arc in the chart, since+ what it will save is not knowable until it has run. The swatch keeps the row's alignment. */+ .cleanup-item-compress {+ --cleanup-item-color: transparent;+ }+.cleanup-item-compact {--cleanup-item-color: var(--cleanup-compact-color);}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsxindex 61c8f7d989..1c692ffcd3 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx@@ -287,6 +287,34 @@ describe("showCleanupDialog", () => {.toBe(t("space_usage.cleanup_compact_notice") ?? "");});+ it("hangs the compression settings off its switch, and offers a run that only compresses", async () => {+ await openDialog();++ // No arc and no figure of its own: what recompressing will save is not knowable without+ // doing it, so it stays out of both the chart and the estimate.+ const compressRow = document.body.querySelector<HTMLElement>(".cleanup-item-compress");+ expect(compressRow?.querySelector(".cleanup-item-size")).toBeNull();+ // The swatch is still there, transparent, so the title lines up with every row above it.+ expect(compressRow?.querySelector(".cleanup-item-swatch")).not.toBeNull();+ expect(document.body.querySelector(".image-compression-section")).toBeNull();+ // Nothing picked weighs anything, so the button rests on compressing alone being asked for.+ expect(cleanButton()?.disabled).toBe(true);++ await toggle(compressRow ?? undefined);++ // The image dialog's own rows, dropped in beneath the switch: scaling with its bound, then+ // one exclusive choice per format. Both formats open on "keep", so neither brings a quality+ // row with it — the single nested row is the bound belonging to scaling.+ const sections = document.body.querySelectorAll(".image-compression-section");+ expect(sections).toHaveLength(4);+ expect(document.body.querySelectorAll(".image-compression-section-nested")).toHaveLength(1);+ expect(document.body.querySelectorAll(".image-compression-section-choice")).toHaveLength(2);+ // The subtree switch is the one row that never comes: a cleanup has no scope to choose.+ expect(document.body.querySelector(".image-compression-scope")).toBeNull();++ expect(cleanButton()?.disabled).toBe(false);+ });+it("counts a rebuild into the whole, and into the offer once it is picked", async () => {await openDialog();diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsxindex 68fdee037f..0df3ff34b2 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx@@ -9,6 +9,12 @@ import dialogService from "../../../../../services/dialog";import { t } from "../../../../../services/i18n";import toast from "../../../../../services/toast";import { formatSize, isStandalone } from "../../../../../services/utils";+import type { ImageCompressionToolOptions } from "../../../../dialogs/image_compression/image_compression_options";+import {+ JpegHandlingSection,+ PngHandlingSection,+ ResizeImageSection+} from "../../../../dialogs/image_compression/image_compression_sections";import { ExtendedAdmonition } from "../../../../react/Admonition";import Button from "../../../../react/Button";import { Card, CardSection } from "../../../../react/Card";@@ -73,6 +79,12 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)setOptions(next);void setStored(storedCleanupOptions(next));};+ // The compression rows report patches against their own settings, which are one field of these.+ const compressionProps = {+ options: options.imageCompression,+ onChange: (patch: Partial<ImageCompressionToolOptions>) =>+ update({ imageCompression: { ...options.imageCompression, ...patch } })+ };// Measured with the history erased outright: the whole the reading is "of", and fixed for as// long as the dialog is open, since no setting here can reclaim more than that.@@ -252,6 +264,32 @@ function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null)</CardSection>))}+ {/* No swatch and no figure, unlike every row above it: what recompressing will save+ cannot be known without doing it, so there is no arc for it in the chart and+ nothing honest to print here. The settings hang beneath the switch, the same+ rows the image compression dialog is built from. */}+ <CardSection+ className="cleanup-item cleanup-item-compress"+ subSectionsVisible={options.compressImages}+ subSections={[+ <ResizeImageSection key="resize" {...compressionProps} />,+ <JpegHandlingSection key="jpeg" {...compressionProps} />,+ <PngHandlingSection key="png" {...compressionProps} />+ ]}+ >+ {/* Carries no color, having no arc to name — it is here so the title starts+ where every other row's does, rather than half a swatch to its left. */}+ <span className="cleanup-item-swatch" aria-hidden="true" />+ <span className="cleanup-item-title">+ {t("compress-images")}+ <ContextualHelp helpMessage={t("space_usage.cleanup_compress_images_help")} />+ </span>+ <FormToggle+ currentValue={options.compressImages}+ onChange={(value) => update({ compressImages: value })}+ />+ </CardSection>+{/* Its figure is the pages already free inside the file, which only a rebuildreturns — no part of any content figure, and so an arc and a color of its own.Absent where the endpoint is: vacuuming lives in the server build, not in the@@ -339,8 +377,8 @@ const CLEANUP_DONE_TIMEOUT_MS = 15000;/*** The app's in-progress toast, the same one printing raises: a spinning icon rather than a bar,- * since none of this can say how far along it is. Compacting names itself, being the step that can- * hold the server for minutes with nothing at all to show meanwhile.+ * since none of this can say how far along it is. Compressing and compacting each name themselves,+ * being the steps that can hold the server for minutes with nothing at all to show meanwhile.** Raised again per phase rather than replaced — the toast service updates the one already carrying* this id, so the message changes in place instead of stacking a second toast beside the first.@@ -349,13 +387,23 @@ function showCleanupProgress(phase: CleanupPhase) {toast.showPersistent({id: CLEANUP_TOAST_ID,icon: "bx bx-loader-circle bx-spin",- message: t(phase === "compacting" ? "space_usage.cleanup_compacting" : "space_usage.cleanup_running"),+ message: t(CLEANUP_PHASE_MESSAGES[phase]),// Nothing here to cancel: the server carries on whatever the client does, so a close button// would read as a stop that stops nothing.dismissible: false});}+/**+ * Compressing borrows the image tool's own wording rather than keeping a second copy of it: the+ * step is that tool, run from here, and the two would only ever be corrected together.+ */+const CLEANUP_PHASE_MESSAGES: Record<CleanupPhase, Parameters<typeof t>[0]> = {+ erasing: "space_usage.cleanup_running",+ compressing: "space_usage.compress_running",+ compacting: "space_usage.cleanup_compacting"+};+/*** The width the dialog starts at, narrow on purpose: a short list of choices, read top to bottom* rather than scanned across. A floor rather than a size — item titles never wrap, so a long onediff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.tsindex 958278288f..5f99462890 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts@@ -5,9 +5,13 @@ const mocks = vi.hoisted(() => ({getInt: vi.fn<(name: string) => number | null>(() => -1),/** Reads the `revisionIgnoreNamedSnapshots` option, which the named-revisions field follows. */is: vi.fn<(name: string) => boolean>(() => true),- post: vi.fn(async (url: string, _body?: object) => (- url === "database/vacuum-database" ? { sizeBefore: 9000, sizeAfter: 2000 } : undefined- )),+ post: vi.fn(async (url: string, _body?: object) => {+ if (url === "database/vacuum-database") return { sizeBefore: 9000, sizeAfter: 2000 };+ // A saving far larger than any reading here, so a test can prove it is never added on top:+ // the compression step runs between the two readings and is already counted in them.+ if (url === "notes/root/compress-images") return { savedSize: 999999 };+ return undefined;+ }),/** Occupied bytes, read once before the erasures and once after; shifted per test. */occupied: [ 5000, 3000 ],get: vi.fn()@@ -32,9 +36,11 @@ vi.mock("../../../../../services/server", () => ({}}));+import type { ImageCompressionToolOptions } from "../../../../dialogs/image_compression/image_compression_options";import {type CleanupToolOptions,computeCleanupSizes,+ hasWorkToDo,readCleanupOptions,runCleanup,storedCleanupOptions@@ -49,12 +55,28 @@ function usage(revisions: number, deleted = 0, unused = 0) {} as SpaceUsageNoteResponse;}+/**+ * What the compression rows open on here: scaling alone, both formats left exactly as encoded.+ * Deliberately not the image dialog's own defaults — this runs over every image there is.+ */+const CONSERVATIVE_COMPRESSION: ImageCompressionToolOptions = {+ resize: true,+ maxWidthHeight: 1920,+ jpegHandling: "keep",+ pngHandling: "keep",+ quality: 75,+ conversionQuality: 85,+ processChildNotes: false+};+const ALL_PICKED: CleanupToolOptions = {deletedEntities: true,unusedAttachments: true,revisionSnapshots: true,snapshotsToKeep: 3,keepNamedSnapshots: true,+ compressImages: false,+ imageCompression: CONSERVATIVE_COMPRESSION,compactDatabase: false};@@ -78,11 +100,26 @@ describe("readCleanupOptions", () => {revisionSnapshots: false,snapshotsToKeep: 4,keepNamedSnapshots: false,+ compressImages: false,+ imageCompression: CONSERVATIVE_COMPRESSION,compactDatabase: false});}});+ it("opens compression on scaling alone, not on the image tool's own defaults", () => {+ // The dialog's defaults re-encode both formats, which is a far larger bet made across every+ // image in the database than across the one note the user was looking at.+ const { imageCompression } = readCleanupOptions({});+ expect(imageCompression).toMatchObject({+ resize: true, maxWidthHeight: 1920, jpegHandling: "keep", pngHandling: "keep"+ });++ // Answered here, the answer stands — including one that turns scaling off entirely.+ expect(readCleanupOptions({ imageCompression: { ...CONSERVATIVE_COMPRESSION, resize: false, pngHandling: "jpeg" } })+ .imageCompression).toMatchObject({ resize: false, pngHandling: "jpeg" });+ });+it("follows the note revision setting on named revisions until it is answered here", () => {expect(readCleanupOptions({}).keepNamedSnapshots).toBe(true);@@ -118,6 +155,8 @@ describe("readCleanupOptions", () => {revisionSnapshots: true,snapshotsToKeep: 0,keepNamedSnapshots: true,+ compressImages: false,+ imageCompression: CONSERVATIVE_COMPRESSION,compactDatabase: false});@@ -127,17 +166,32 @@ describe("readCleanupOptions", () => {});describe("storedCleanupOptions", () => {- it("remembers every answer but the compacting step", () => {- expect(storedCleanupOptions({ ...ALL_PICKED, compactDatabase: true })).toEqual({+ it("remembers every answer but the compacting step, compression settings included", () => {+ expect(storedCleanupOptions({ ...ALL_PICKED, compressImages: true, compactDatabase: true })).toEqual({deletedEntities: true,unusedAttachments: true,revisionSnapshots: true,snapshotsToKeep: 3,- keepNamedSnapshots: true+ keepNamedSnapshots: true,+ compressImages: true,+ imageCompression: CONSERVATIVE_COMPRESSION});});});+describe("hasWorkToDo", () => {+ const nothingPicked = { ...ALL_PICKED, deletedEntities: false, unusedAttachments: false, revisionSnapshots: false };++ it("counts compressing on its own, which no estimate can speak for", () => {+ // Nothing selected weighs anything, and compressing is not in the estimate at all — so+ // without this the button would be disabled for a run that has plenty to do.+ expect(hasWorkToDo(nothingPicked, 0)).toBe(false);+ expect(hasWorkToDo({ ...nothingPicked, compressImages: true }, 0)).toBe(true);+ expect(hasWorkToDo({ ...nothingPicked, compactDatabase: true }, 0)).toBe(true);+ expect(hasWorkToDo(nothingPicked, 500)).toBe(true);+ });+});+describe("computeCleanupSizes", () => {it("weighs the whole at the most aggressive trim, and the offer at the chosen one", () => {const sizes = computeCleanupSizes(usage(900, 100, 20), usage(300), ALL_PICKED);@@ -190,6 +244,47 @@ describe("runCleanup", () => {expect(mocks.post.mock.calls[0][1]).toEqual({ snapshotsToKeep: 3, keepNamedSnapshots: true });});+ it("recompresses the whole tree after the erasures, and only when asked", async () => {+ await runCleanup(ALL_PICKED);+ expect(mocks.post.mock.calls.map(([ url ]) => url)).not.toContain("notes/root/compress-images");++ mocks.post.mockClear();+ await runCleanup({+ ...ALL_PICKED,+ compressImages: true,+ imageCompression: { ...CONSERVATIVE_COMPRESSION, jpegHandling: "compress", quality: 60 }+ });++ // After the erasures: an original a revision still points at survives being replaced, so+ // erasing the snapshots first is what lets the originals go with them.+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([+ "revisions/erase-all-excess-revisions",+ "notes/erase-unused-attachments-now",+ "notes/erase-deleted-notes-now",+ "notes/root/compress-images",+ "space-usage/cleanup-completed"+ ]);+ // The whole tree, and none of the tool's own scope switch — a cleanup has no scope to choose.+ expect(mocks.post.mock.calls[3][1]).toEqual({+ resize: true,+ maxWidthHeight: 1920,+ jpegHandling: "compress",+ pngHandling: "keep",+ quality: 60,+ conversionQuality: 85,+ recursive: true+ });+ });++ it("counts what compressing freed once, through the readings rather than the endpoint", async () => {+ mocks.occupied = [ 5000, 1200 ];++ // The endpoint answers with a saving of its own; the run must report the 3800 the database+ // actually gave back rather than that figure, or the sum of the two.+ await expect(runCleanup({ ...ALL_PICKED, deletedEntities: false, unusedAttachments: false,+ revisionSnapshots: false, compressImages: true })).resolves.toBe(3800);+ });+it("reports what the database actually gave back, not what was predicted", async () => {mocks.occupied = [ 5000, 1200 ];diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.tsindex f452b0a482..c1a474d18c 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts@@ -1,5 +1,6 @@import type {CompactionEstimateResponse,+ ImageCompressionResponse,SpaceUsageNoteResponse,SpaceUsageOverviewResponse,VacuumDatabaseResponse@@ -7,6 +8,11 @@ import type {import optionService from "../../../../../services/options";import server from "../../../../../services/server";+import {+ CONSERVATIVE_IMAGE_COMPRESSION_DEFAULTS,+ type ImageCompressionToolOptions,+ readImageCompressionOptions+} from "../../../../dialogs/image_compression/image_compression_options";/** The cleanup's items, in the order they are both listed and drawn. */export const CLEANUP_ITEMS = [@@ -18,11 +24,11 @@ export const CLEANUP_ITEMS = [export type CleanupItemId = (typeof CLEANUP_ITEMS)[number]["id"];/**- * What a run is doing, reported as it moves between the two. Erasing is over in seconds on an- * ordinary database; compacting is the one that can hold the server for minutes, so it says so- * rather than leaving the same message up throughout.+ * What a run is doing, reported as it moves between them. Erasing is over in seconds on an ordinary+ * database, where recompressing every image and rebuilding the file are both measured in minutes —+ * so each says so rather than leaving the same message up throughout.*/-export type CleanupPhase = "erasing" | "compacting";+export type CleanupPhase = "erasing" | "compressing" | "compacting";/**@@ -37,6 +43,18 @@ export interface CleanupToolOptions {/** Revision snapshots kept per note; 0 erases the history outright. */snapshotsToKeep: number;keepNamedSnapshots: boolean;+ /**+ * Recompress every image in the database, under {@link imageCompression}. Unlike the erasures,+ * this reclaims space from content that is being *kept* — so it frees bytes without anything+ * leaving the tree.+ */+ compressImages: boolean;+ /**+ * How images are recompressed when {@link compressImages} is on. The same settings the image+ * compression dialog works with, minus the subtree switch: a cleanup always runs over the whole+ * database, so there is no scope left to choose.+ */+ imageCompression: ImageCompressionToolOptions;/*** Rebuild the database file afterwards. Erasing hands pages back to the database, which reuses* them but never shrinks the file; only this returns the space to the disk.@@ -73,6 +91,10 @@ export function readCleanupOptions(stored: Partial<CleanupToolOptions> | null |// Never answered here, the tool follows what the note revision settings say about named// revisions, rather than proposing a harsher trim than the one already configured.keepNamedSnapshots: stored?.keepNamedSnapshots ?? optionService.is("revisionIgnoreNamedSnapshots"),+ compressImages: stored?.compressImages === true,+ // Conservative where the dialog's own defaults are not: this runs over every image there is.+ imageCompression: readImageCompressionOptions(+ stored?.imageCompression, CONSERVATIVE_IMAGE_COMPRESSION_DEFAULTS),// Always starts unpicked, whatever the last run asked for: it is by far the most expensive// step, and one nobody should find themselves running because they forgot it was ticked.compactDatabase: false@@ -93,9 +115,13 @@ export function storedCleanupOptions(options: CleanupToolOptions): Partial<Clean* Whether the settings amount to anything worth running. Compacting counts on its own: it frees no* *accounted* bytes — the figures are about content, and it moves none — but it is the only step* that hands space back to the disk, so a run asking for nothing else is still a run.+ *+ * Compressing counts on its own for the opposite reason: it frees bytes the figures very much are+ * about, but no reading here says how many, since what an encoder will manage on an image is not+ * knowable without doing it. Its absence from the estimate is not evidence of nothing to do.*/export function hasWorkToDo(options: CleanupToolOptions, selectedBytes: number): boolean {- return selectedBytes > 0 || options.compactDatabase;+ return selectedBytes > 0 || options.compactDatabase || options.compressImages;}/**@@ -170,6 +196,11 @@ export function computeCleanupSizes(* orphaned, and there is nothing to be gained by having two of those scan the blobs at the same* time. Their order carries no weight beyond that — every one of them hands its own space back.*+ * Recompressing comes after all of them and before any rebuild. After, because an original a+ * revision still points at survives being replaced, so erasing the snapshots first is what lets the+ * originals go with them; before, because a rebuild has to close around the final state to return+ * the pages this frees.+ ** @returns what the run reclaimed, never negative: a note saved by another client mid-run must not* read as the cleanup having given space back.*/@@ -202,6 +233,11 @@ export async function runCleanup(await server.postWithTimeout("notes/erase-deleted-notes-now", CLEANUP_TIMEOUT_MS);}+ if (options.compressImages) {+ onPhase("compressing");+ await compressAllImages(options.imageCompression);+ }+let compaction: VacuumDatabaseResponse | undefined;if (options.compactDatabase) {@@ -225,6 +261,34 @@ export async function runCleanup(return reclaimedBytes;}+/**+ * Recompresses every image in the tree, as one request against the root note.+ *+ * The endpoint answers with what it saved, and that figure is deliberately *not* added to the run's+ * total. This step happens between the two readings the total is measured from, so those bytes are+ * already counted in it — adding them would report every one of them twice.+ *+ * The measured figure is the truer of the two anyway. What the endpoint reports is the difference+ * between the images it read and the ones it wrote, which is what compression achieved; what the+ * readings show is what the database actually handed back, which is smaller whenever a revision+ * still points at an original. Only the second is a claim about space, and space is what this tool+ * is answering for.+ */+async function compressAllImages(options: ImageCompressionToolOptions): Promise<void> {+ await server.postWithTimeout<ImageCompressionResponse>(+ "notes/root/compress-images", CLEANUP_TIMEOUT_MS, {+ resize: options.resize,+ maxWidthHeight: options.maxWidthHeight,+ jpegHandling: options.jpegHandling,+ pngHandling: options.pngHandling,+ quality: options.quality,+ conversionQuality: options.conversionQuality,+ // Always the whole tree: a cleanup is a database-wide operation, and the root note on+ // its own holds no images at all.+ recursive: true+ });+}+/*** What a rebuild would return, and what the database occupies now.*