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 support to cancel the operation
Adorian Doran8a8d41ff5601
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 53374db2ed..fc0e0cbd85 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2978,11 +2978,15 @@"compress_cancel": "Cancel","compress_running": "Compressing images…","compress_running_progress": "Compressing image {{done}} of {{total}}…",+ "compress_cancel_run": "Stop","compress_result_one": "{{count}} image processed, reducing the size from {{before}} to {{after}}.","compress_result_other": "{{count}} images processed, reducing the size from {{before}} to {{after}}.","compress_result_no_gain_one": "{{count}} image processed, but it could not be made any smaller.","compress_result_no_gain_other": "{{count}} images processed, but none of them could be made any smaller.",- "compress_result_none": "There are no images to compress."+ "compress_result_none": "There are no images to compress.",+ "compress_result_stopped": "Stopped after {{done}} of {{total}} images, reducing their size from {{before}} to {{after}}.",+ "compress_result_stopped_no_gain": "Stopped after {{done}} of {{total}} images, none of which could be made any smaller.",+ "compress_result_stopped_none": "Stopped before any image was processed."},"note_language": {"not_set": "No language set",diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsxindex 911bb66b33..f2f09746ab 100644--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.spec.tsx@@ -22,6 +22,20 @@ function resultOf(count: number, originalSize: number, newSize: number) {};}+/**+ * A run called off part-way: the images it got through, and then the ones it never reached.+ *+ * Those carry no sizes because nothing read them — which is exactly why they cannot be counted+ * alongside the bytes the run does report.+ */+function stoppedRun(done: number, cancelled: number, originalSize: number, newSize: number) {+ const result = resultOf(done, originalSize, newSize);+ const untouched = Array.from({ length: cancelled },+ (_, index) => ({ entityId: `left${index}`, skipReason: "cancelled" }));++ return { ...result, items: [ ...result.items, ...untouched ], skippedCount: cancelled };+}+const mocks = vi.hoisted(() => ({storedOption: "{}",/** URLs the summary asked for, in order, so a re-reading can be told from a first reading. */@@ -766,8 +780,27 @@ describe("running the compression", () => {expect(result?.compressedCount).toBe(10);});+ it("counts out the images a stopped run never reached, instead of claiming it processed them", async () => {+ // The figures a real run produced: a tree of 867, called off after fifteen. Counting the+ // 852 it never opened put the whole tree's number in front of fifteen images' worth of+ // bytes — "867 images processed, reducing the size from 73 MiB to 554 KiB".+ mocks.postWithTimeout.mockResolvedValueOnce(stoppedRun(15, 852, 73 * 1024 * 1024, 554 * 1024));++ const { closed } = await openDialog();+ await click(compressButton());+ await closed;++ expect(reportedMessage()).toBe('space_usage.compress_result_stopped '+ + '{"done":15,"total":867,"before":"73 MiB","after":"554 KiB"}');+ });+it.each([[ "found no images at all", EMPTY_RESULT, "space_usage.compress_result_none" ],+ // Stopped before the first image was read: no count is worth quoting, but "there are no+ // images to compress" would be a plain untruth about a tree full of them.+ [ "was stopped at once", stoppedRun(0, 12, 0, 0), "space_usage.compress_result_stopped_none" ],+ [ "was stopped having gained nothing", stoppedRun(4, 20, 900, 900),+ 'space_usage.compress_result_stopped_no_gain {"done":4,"total":24}' ],// Quoting "from 45 MiB to 45 MiB" would read as a failure to report, where it is in fact a// complete answer: the images were already as small as these settings can make them.[ "made nothing smaller", resultOf(4, 900, 900), 'space_usage.compress_result_no_gain {"count":4}' ]diff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsxindex b09663b363..a873d9596a 100644--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_dialog.tsx@@ -11,10 +11,12 @@ import { Card } from "../../react/Card";import { useTriliumOptionJson } from "../../react/hooks";import Modal from "../../react/Modal";import {+ cancelImageCompression,compressionResultMessage,IMAGE_COMPRESSION_TOAST_ID,type ImageCompressionTarget,isSingleImage,+ newCompressionTaskId,runImageCompression} from "./image_compression_operation";import {@@ -99,14 +101,23 @@ function ImageCompressionDialog({ target, onFinished }: {return;}- // A spinner rather than a bar, and nothing to cancel: the server carries on whatever the- // client does. The message is replaced as the count arrives — one toast throughout, so the- // wording changes in place rather than a second toast appearing beside the first.+ // A spinner rather than a bar: nothing here can say how far along one image is. The message+ // is replaced as the count arrives — one toast throughout, so the wording changes in place+ // rather than a second toast appearing beside the first.+ //+ // Calling it off leaves everything already compressed compressed: the run writes as it goes,+ // and starting it again skips what is done without reading it. So the button says stop, not+ // undo, and the toast stays up until the run answers with what it managed.+ const taskId = newCompressionTaskId();const showProgress = (message: string) => toast.showPersistent({id: IMAGE_COMPRESSION_TOAST_ID,icon: "bx bx-loader-circle bx-spin",message,- dismissible: false+ dismissible: false,+ buttons: [ {+ text: t("space_usage.compress_cancel_run"),+ onClick: () => cancelImageCompression(taskId)+ } ]});showProgress(t("space_usage.compress_running"));@@ -114,7 +125,7 @@ function ImageCompressionDialog({ target, onFinished }: {let result: ImageCompressionResponse | null = null;try {- result = await runImageCompression(target, settings, (done, total) => {+ result = await runImageCompression(target, settings, taskId, (done, total) => {// Until the run has said how many there are, the count on its own would read as a// total; the wording without one says only that it is working through them.showProgress(total === undefineddiff --git a/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts b/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.tsindex f519ea1997..adda3e1373 100644--- a/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts+++ b/apps/client/src/widgets/dialogs/image_compression/image_compression_operation.ts@@ -49,12 +49,12 @@ const COMPRESSION_TIMEOUT_MS = 60 * 60 * 1000;export function runImageCompression(target: ImageCompressionTarget,options: ImageCompressionToolOptions,+ taskId: string,onProgress?: (done: number, total: number | undefined) => void): Promise<ImageCompressionResponse> {const url = target.type === "note"? `notes/${target.noteId}/compress-images`: `attachments/${target.attachmentId}/compress-image`;- const taskId = randomString(12);const listener = onProgress && followProgress(taskId, onProgress);return server.postWithTimeout<ImageCompressionResponse>(url, COMPRESSION_TIMEOUT_MS, {@@ -75,6 +75,21 @@ export function runImageCompression(});}+/** Names a run, so it can be followed and called off by whoever started it. */+export function newCompressionTaskId(): string {+ return randomString(12);+}++/**+ * Calls off a run that is still going.+ *+ * Answers nothing: the images already compressed are already saved, and the run itself reports what+ * it managed as it always does — so there is no second account of it to wait for here.+ */+export function cancelImageCompression(taskId: string): void {+ void server.post(`image-compression/${taskId}/cancel`);+}+/*** Watches one run's progress messages, and only that run's.*@@ -102,21 +117,32 @@ function followProgress(taskId: string, onProgress: (done: number, total: number* A run that saved nothing says so rather than quoting a size that did not move: "from 45 MiB to* 45 MiB" reads as a failure to report, where it is in fact a complete and correct answer — the* images were already as small as these settings can make them.+ *+ * The images a stopped run never reached are counted out of both, because they were never weighed+ * either: they are reported at zero bytes, having not been read. Counting them would claim the+ * whole tree was processed and then quote the sizes of the handful that actually were, which is+ * how "867 images processed, reducing the size from 73.72 MiB to 554.6 KiB" comes about. What the+ * run got through before it was called off is said instead, against the total it set out to visit.*/export function compressionResultMessage(result: ImageCompressionResponse): string {- const count = result.items.length;+ const total = result.items.length;+ const done = total - result.items.filter((item) => item.skipReason === "cancelled").length;+ const stopped = done < total;- if (count === 0) {- return t("space_usage.compress_result_none");+ if (done === 0) {+ return t(stopped ? "space_usage.compress_result_stopped_none" : "space_usage.compress_result_none");}if (result.savedSize <= 0) {- return t("space_usage.compress_result_no_gain", { count });+ return stopped+ ? t("space_usage.compress_result_stopped_no_gain", { done, total })+ : t("space_usage.compress_result_no_gain", { count: done });}- return t("space_usage.compress_result", {- count,- before: formatSize(result.originalSize),- after: formatSize(result.newSize)- });+ const before = formatSize(result.originalSize);+ const after = formatSize(result.newSize);++ return stopped+ ? t("space_usage.compress_result_stopped", { done, total, before, after })+ : t("space_usage.compress_result", { count: done, before, after });}diff --git a/apps/server/src/services/image_compression.spec.ts b/apps/server/src/services/image_compression.spec.tsindex b872c98d45..ee3b489fa3 100644--- a/apps/server/src/services/image_compression.spec.ts+++ b/apps/server/src/services/image_compression.spec.ts@@ -1,6 +1,6 @@import type { ImageCompressionResponse } from "@triliumnext/commons";import { becca, cls, getSql, options } from "@triliumnext/core";-import { collectNoteTargets, HEADER_BYTES, writeImage } from "@triliumnext/core/src/services/image_compression.js";+import { cancelImageCompression, collectNoteTargets, HEADER_BYTES, writeImage } from "@triliumnext/core/src/services/image_compression.js";import { getImageProvider, initImageProvider } from "@triliumnext/core/src/services/image_provider.js";import { createTextNote } from "@triliumnext/core/src/test/api_fixtures.js";import { CoreApiTester } from "@triliumnext/core/src/test/api_tester.js";@@ -495,6 +495,75 @@ describe("compression parameters", () => {}});+ it("stops when called off, keeping what it had already compressed", async () => {+ const { noteId } = await createTextNote(api);+ const taskId = "cancelMe123";+ const images = [+ await addAttachment(noteId, "a.png", noisyPng, { position: 10 }),+ await addAttachment(noteId, "b.png", noisyPng, { position: 20 }),+ await addAttachment(noteId, "c.png", noisyPng, { position: 30 })+ ];++ // Called off while the first image is in the encoder, so the run has started but has not+ // reached the rest: what it manages is real, and what it never got to says so.+ const real = getImageProvider();+ let compressedSoFar = 0;++ initImageProvider({+ getImageType: (buffer) => real.getImageType(buffer),+ processImage: (buffer, name, shrink) => real.processImage(buffer, name, shrink),+ planCompression: (header, req) => real.planCompression(header, req),+ compressionConcurrency: () => 1,+ compressImage: async (buffer, req) => {+ const outcome = await real.compressImage(buffer, req);++ if (++compressedSoFar === 1) {+ cancelImageCompression(taskId);+ }++ return outcome;+ }+ });++ try {+ const res = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { taskId, pngHandling: "jpeg" }+ });++ expect(res.body.compressedCount).toBe(1);+ expect(res.body.items.map((item) => item.skipReason))+ .toEqual([ undefined, "cancelled", "cancelled" ]);++ // The one it finished is written; the two it never reached are untouched, not half-done.+ expect(readAttachment(images[0]).mime).toBe("image/jpeg");+ expect(readAttachment(images[1]).size).toBe(noisyPng.byteLength);+ expect(readAttachment(images[2]).size).toBe(noisyPng.byteLength);+ } finally {+ initImageProvider(real);+ }+ });++ it("forgets a cancellation once the run it stopped is over", async () => {+ const { noteId } = await createTextNote(api);+ const attachmentId = await addAttachment(noteId, "later.png", noisyPng);+ const taskId = "reusedName99";++ cancelImageCompression(taskId);++ const stopped = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { taskId, pngHandling: "jpeg" }+ });+ expect(stopped.body.items[0]).toMatchObject({ skipReason: "cancelled" });++ // The same name again: a run must not inherit the last one's cancellation, or a caller+ // reusing an id would find every later run refusing to start.+ const second = await api.post<ImageCompressionResponse>(`/api/notes/${noteId}/compress-images`, {+ body: { taskId, pngHandling: "jpeg" }+ });+ expect(second.body.items[0]).toMatchObject({ compressed: true });+ expect(readAttachment(attachmentId).mime).toBe("image/jpeg");+ });+it("refuses an image too large to decode rather than failing part-way through one", async () => {const { noteId } = await createTextNote(api);// 400 megapixels by its own header — well past what one decode is allowed. The bytes behinddiff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.tsindex b2b454ffc6..dbcf8661a2 100644--- a/packages/commons/src/lib/server_api.ts+++ b/packages/commons/src/lib/server_api.ts@@ -499,6 +499,12 @@ export type ImageCompressionSkipReason =* it would have put the superseded picture back; the newer one is kept instead.*/| "changed"+ /**+ * The run was called off before reaching this image. Nothing was read and nothing weighed, so+ * it reports no size — it is here to be counted, so that a run stopped half way says so rather+ * than reporting the part it did as the whole.+ */+ | "cancelled"/** Compression failed; the original was kept and the failure logged. */| "error";diff --git a/packages/trilium-core/src/routes/api/image.ts b/packages/trilium-core/src/routes/api/image.tsindex 63341a8a7d..9309f5b82b 100644--- a/packages/trilium-core/src/routes/api/image.ts+++ b/packages/trilium-core/src/routes/api/image.ts@@ -180,6 +180,17 @@ function compressAttachmentImage(req: Request<{ attachmentId: string }>) {return imageCompressionService.compressAttachmentImage(req.params.attachmentId, readCompressionOptions(req));}+/**+ * Calls off a run by the name its caller gave it, and says nothing about whether one was going.+ *+ * There is nothing useful to report either way: a run that has just finished and a name that was+ * never used look the same from here, and neither is a failure — the caller wanted this run stopped+ * and after this it is, or it already was.+ */+function cancelImageCompression(req: Request<{ taskId: string }>) {+ imageCompressionService.cancelImageCompression(req.params.taskId);+}+export default {returnImageFromNote,returnImageFromRevision,@@ -189,7 +200,8 @@ export default {getAttachmentImageInfo,getImageInventory,compressNoteImages,- compressAttachmentImage+ compressAttachmentImage,+ cancelImageCompression};/**diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex c2baa7d1ba..d349e60fdb 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -138,6 +138,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, apiRoute, asyncApiRout// Recompressing decodes and re-encodes each image, so these run outside a transaction and open// one per image written instead of holding a single one across the whole (asynchronous) run.asyncApiRoute(PST, "/api/notes/:noteId/compress-images", imageRoute.compressNoteImages);+ apiRoute(PST, "/api/image-compression/:taskId/cancel", imageRoute.cancelImageCompression);asyncApiRoute(PST, "/api/attachments/:attachmentId/compress-image", imageRoute.compressAttachmentImage);route(PST, "/api/notes/:noteId/attachments/upload", [checkApiAuthOrElectron, uploadMiddlewareWithErrorHandling, csrfMiddleware], attachmentsApiRoute.uploadAttachment, apiResultHandler);diff --git a/packages/trilium-core/src/services/image_compression.ts b/packages/trilium-core/src/services/image_compression.tsindex 5321cffad4..f6cbcc3e99 100644--- a/packages/trilium-core/src/services/image_compression.ts+++ b/packages/trilium-core/src/services/image_compression.ts@@ -41,6 +41,26 @@ const DEFAULT_CONVERSION_QUALITY = 85;/** A one-pixel bound is pointless but harmless; anything below it cannot be resized to. */const MIN_MAX_WIDTH_HEIGHT = 1;+/**+ * Calls off a run that is still going, by the name its caller gave it.+ *+ * Takes effect between images rather than during one: an image already being decoded is finished+ * and written, because stopping a worker mid-decode saves a second and loses the work. Everything+ * committed stays committed — the run writes as it goes — and running the tool again picks up where+ * this left off, since what is already compressed is recognised from its header and skipped.+ */+export function cancelImageCompression(taskId: string) {+ cancelledRuns.add(taskId);+}++/**+ * Runs called off and not yet finished.+ *+ * Emptied by the run itself on its way out, so a name reused by a later run does not arrive+ * pre-cancelled.+ */+const cancelledRuns = new Set<string>();+/** Compresses every image the given note holds: an image note's own content, or its attachments. */export async function compressNoteImages(noteId: string, options?: ImageCompressionOptions): Promise<ImageCompressionResponse> {const note = becca.getNote(noteId);@@ -368,114 +388,132 @@ export function writeImage(entity: WritableImage, buffer: Uint8Array, mime: strientity.mime = mime;try {- entity.setContent(buffer, { forceSave: true });- } catch (e: unknown) {- entity.mime = previousMime;+ entity.setContent(buffer, { forceSave: true });+ } catch (e: unknown) {+ entity.mime = previousMime;- throw e;+ throw e;+ }}-}-/**- * Reads an image's weight and its opening bytes straight out of the blob, leaving the body of it in- * the database. One statement answers both, so the saving is a smaller read rather than a second- * round trip.- *- * `CAST` on both: a blob column can hold text for other kinds of content, where `LENGTH` would- * count characters and `substr` would cut on them. Bytes are what an image header is measured in.- */-function peekBlob(blobId: string | undefined, isProtected: boolean | undefined): TargetPeek | null {- if (!blobId || isProtected) {- return null;- }+ /**+ * Reads an image's weight and its opening bytes straight out of the blob, leaving the body of it in+ * the database. One statement answers both, so the saving is a smaller read rather than a second+ * round trip.+ *+ * `CAST` on both: a blob column can hold text for other kinds of content, where `LENGTH` would+ * count characters and `substr` would cut on them. Bytes are what an image header is measured in.+ */+ function peekBlob(blobId: string | undefined, isProtected: boolean | undefined): TargetPeek | null {+ if (!blobId || isProtected) {+ return null;+ }- const row = getSql().getRow<{ size: number | null; header: string | Uint8Array | null }>(/*sql*/`- SELECT LENGTH(CAST(content AS BLOB)) AS size,- substr(CAST(content AS BLOB), 1, ?) AS header- FROM blobs WHERE blobId = ?`, [ HEADER_BYTES, blobId ]);+ const row = getSql().getRow<{ size: number | null; header: string | Uint8Array | null }>(/*sql*/`+ SELECT LENGTH(CAST(content AS BLOB)) AS size,+ substr(CAST(content AS BLOB), 1, ?) AS header+ FROM blobs WHERE blobId = ?`, [ HEADER_BYTES, blobId ]);- if (!row || row.size === null || row.header === null) {- return null;+ if (!row || row.size === null || row.header === null) {+ return null;+ }++ return { size: row.size, header: wrapStringOrBuffer(row.header) };}- return { size: row.size, header: wrapStringOrBuffer(row.header) };-}+ /**+ * A canvas, mermaid, mind map or spreadsheet note carries its rendered picture in an attachment of+ * a fixed title. Those are regenerated whenever the note is saved, so compressing one buys nothing+ * and lasts until the next save; worse, the route serving the spreadsheet's picture declares it+ * `image/png` unconditionally, so converting it to JPEG would serve bytes under the wrong type.+ */+ function resolveAttachmentSkip(attachment: BAttachment): ImageCompressionSkipReason | undefined {+ if (!attachment.isContentAvailable()) {+ return "protected";+ }-/**- * A canvas, mermaid, mind map or spreadsheet note carries its rendered picture in an attachment of- * a fixed title. Those are regenerated whenever the note is saved, so compressing one buys nothing- * and lasts until the next save; worse, the route serving the spreadsheet's picture declares it- * `image/png` unconditionally, so converting it to JPEG would serve bytes under the wrong type.- */-function resolveAttachmentSkip(attachment: BAttachment): ImageCompressionSkipReason | undefined {- if (!attachment.isContentAvailable()) {- return "protected";- }+ const ownerNote = attachment.getNote();- const ownerNote = attachment.getNote();+ if (ownerNote && attachment.title === getImageAttachmentTitle(ownerNote.type)) {+ return "generated";+ }- if (ownerNote && attachment.title === getImageAttachmentTitle(ownerNote.type)) {- return "generated";+ return undefined;}- return undefined;-}+ /**+ * Visits every image, in two passes.+ *+ * The first settles what it can from headers alone, which over a tree is most of the images there+ * are, and costs a small query each. What survives it has to be read and decoded, which is the+ * expensive part and the only part worth scheduling — so the second pass hands those to the budget,+ * each with what its decode is expected to want.+ *+ * The passes are not an optimization of each other: the first exists because deciding should not+ * cost what doing costs, the second because doing should not be allowed to cost everything at once.+ */+ async function compressTargets(+ targets: CompressionTarget[],+ request: ImageCompressionRequest,+ taskId?: string+ ): Promise<ImageCompressionResponse> {+ const concurrency = getImageProvider().compressionConcurrency();+ const reportProgress = progressReporter(taskId, targets.length);-/**- * Visits every image, in two passes.- *- * The first settles what it can from headers alone, which over a tree is most of the images there- * are, and costs a small query each. What survives it has to be read and decoded, which is the- * expensive part and the only part worth scheduling — so the second pass hands those to the budget,- * each with what its decode is expected to want.- *- * The passes are not an optimization of each other: the first exists because deciding should not- * cost what doing costs, the second because doing should not be allowed to cost everything at once.- */-async function compressTargets(- targets: CompressionTarget[],- request: ImageCompressionRequest,- taskId?: string-): Promise<ImageCompressionResponse> {- const concurrency = getImageProvider().compressionConcurrency();- const reportProgress = progressReporter(taskId, targets.length);+ logRunStart(targets.length, concurrency);- logRunStart(targets.length, concurrency);+ const stopped = () => taskId !== undefined && cancelledRuns.has(taskId);+ const items = new Array<ImageCompressionItem>(targets.length);+ const worthReading: { at: number; target: CompressionTarget; cost: number | null }[] = [];- const items = new Array<ImageCompressionItem>(targets.length);- const worthReading: { at: number; target: CompressionTarget; cost: number | null }[] = [];+ try {+ for (const [ at, target ] of targets.entries()) {+ if (stopped()) {+ items[at] = skippedItem(target, 0, "cancelled");+ reportProgress();+ continue;+ }- for (const [ at, target ] of targets.entries()) {- const foreseen = await foreseeTarget(target, request);+ const foreseen = await foreseeTarget(target, request);- if (foreseen.item) {- items[at] = foreseen.item;- reportProgress();- } else {- worthReading.push({ at, target, cost: foreseen.cost });+ if (foreseen.item) {+ items[at] = foreseen.item;+ reportProgress();+ } else {+ worthReading.push({ at, target, cost: foreseen.cost });+ }}- }- const writes = createWriteBatch();- const compressed = await runWithinBudget(- worthReading.map(({ target, cost }) => ({- cost,- run: () => compressTarget(target, request, writes).finally(reportProgress)- })),- { totalBytes: COMPRESSION_BUDGET_BYTES, maxConcurrent: concurrency }- );-- // Nothing should be left — every write either filled a group or waited out its own timer — but- // saying so costs nothing and a run must not end holding work it has not committed.- writes.flush();-- // Back into the order they were visited in, which is the order they are reported in — the- // schedule above is free to have run them in any other.- worthReading.forEach(({ at }, index) => {- items[at] = compressed[index];- });+ const writes = createWriteBatch();+ const compressed = await runWithinBudget(+ // A cancelled run still drains its queue, but each remaining image is answered rather than+ // worked on — the images go by in milliseconds and the scheduler needs no notion of any of+ // this.+ worthReading.map(({ target, cost }) => ({+ cost,+ run: () => (stopped()+ ? Promise.resolve(skippedItem(target, 0, "cancelled"))+ : compressTarget(target, request, writes)).finally(reportProgress)+ })),+ { totalBytes: COMPRESSION_BUDGET_BYTES, maxConcurrent: concurrency }+ );++ // Nothing should be left — every write either filled a group or waited out its own timer — but+ // saying so costs nothing and a run must not end holding work it has not committed.+ writes.flush();++ // Back into the order they were visited in, which is the order they are reported in — the+ // schedule above is free to have run them in any other.+ worthReading.forEach(({ at }, index) => {+ items[at] = compressed[index];+ });- return logRunEnd(summarize(items));+ return logRunEnd(summarize(items));+ } finally {+ if (taskId !== undefined) {+ cancelledRuns.delete(taskId);+ }+ }}/**@@ -816,6 +854,7 @@ function summarize(items: ImageCompressionItem[]): ImageCompressionResponse {export default {compressNoteImages,compressAttachmentImage,+ cancelImageCompression,resolveCompressionRequest,resolveRecursive};