Skip to content

TagSpaces is an offline, open source, document manager with tagging support

chore: added unit and e2e tests for the copy/move functionality

Ilian Sapundshievc9443b403127
diff --git a/src/renderer/components/dialogs/hooks/FileUploadDialogContextProvider.tsx b/src/renderer/components/dialogs/hooks/FileUploadDialogContextProvider.tsx
index 720c25ce2..0fb679086 100644
--- a/src/renderer/components/dialogs/hooks/FileUploadDialogContextProvider.tsx
+++ b/src/renderer/components/dialogs/hooks/FileUploadDialogContextProvider.tsx
@@ -84,16 +84,21 @@ export const FileUploadDialogContextProvider = ({
open.current = true;
forceUpdate();
}
- } else if (len === 0) {
- // Everything cleared (e.g. user clicked "Close and Clear") — reset.
+ } else if (!wasEmpty && len === 0) {
+ // Genuine N→0 transition (e.g. "Close and Clear"). Reset state and
+ // hide the dialog. We deliberately ignore 0→0 here so that callers
+ // like MoveCopyFilesDialog.handleCopy can dispatch resetProgress()
+ // and then synchronously call openFileUploadDialog() without us
+ // racing in to close what they just opened.
userMinimized.current = false;
if (open.current) {
open.current = false;
forceUpdate();
}
}
- // Else: ongoing batch. Don't re-open if the user minimized — the
- // indicator near the search bar continues to surface progress.
+ // Else: ongoing batch (N→M) or no-op 0→0. Don't re-open if the user
+ // minimized — the indicator near the search bar continues to surface
+ // progress.
}, [progress]);
function openDialog(tPath?: string, dTitle?: string) {
diff --git a/src/renderer/services/utils-io.ts b/src/renderer/services/utils-io.ts
index b17048341..224ddf0a5 100644
--- a/src/renderer/services/utils-io.ts
+++ b/src/renderer/services/utils-io.ts
@@ -948,52 +948,10 @@ export async function executePromisesInBatches<T>(
return results;
}
-/**
- * Worker-pool runner with a real concurrency cap. Unlike
- * `executePromisesInBatches`, the items are *factories* that are invoked only
- * when a worker slot becomes free — so the underlying work (IPC invokes, fs
- * ops) is throttled, not just the awaits. Important for big IO fanouts where
- * eager `.map(() => invoke(...))` would queue thousands of in-flight promises
- * and OOM the renderer.
- */
-export async function runConcurrent<I, R>(
- items: I[],
- worker: (item: I, index: number) => Promise<R>,
- concurrency: number,
- onSettled?: (item: I, index: number, result: PromiseSettledResult<R>) => void,
- abortSignal?: AbortSignal,
-): Promise<PromiseSettledResult<R>[]> {
- const results: PromiseSettledResult<R>[] = new Array(items.length);
- let cursor = 0;
- const slots = Math.max(1, Math.min(concurrency, items.length));
-
- const runWorker = async () => {
- while (true) {
- if (abortSignal && abortSignal.aborted) {
- return;
- }
- const idx = cursor++;
- if (idx >= items.length) {
- return;
- }
- const item = items[idx];
- let result: PromiseSettledResult<R>;
- try {
- const value = await worker(item, idx);
- result = { status: 'fulfilled', value };
- } catch (reason) {
- result = { status: 'rejected', reason };
- }
- results[idx] = result;
- if (onSettled) {
- onSettled(item, idx, result);
- }
- }
- };
-
- await Promise.all(Array.from({ length: slots }, runWorker));
- return results;
-}
+// `runConcurrent` lives in a leaf module (no Pro / DOM imports) so it can
+// be unit-tested without dragging in this whole file. Re-exported here so
+// existing callers don't have to change their imports.
+export { runConcurrent } from '-/utils/runConcurrent';
export function setZoomFactorElectron(zoomLevel) {
if (AppConfig.isElectron) {
diff --git a/src/renderer/utils/runConcurrent.ts b/src/renderer/utils/runConcurrent.ts
new file mode 100644
index 000000000..c756b26c7
--- /dev/null
+++ b/src/renderer/utils/runConcurrent.ts
@@ -0,0 +1,63 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2024-present TagSpaces GmbH
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ */
+
+/**
+ * Worker-pool runner with a real concurrency cap. Items are processed in
+ * order by a fixed-size pool of `concurrency` workers, each pulling the
+ * next item only after its previous one settles. Unlike
+ * `executePromisesInBatches`, the items are *factories* invoked only when
+ * a slot becomes free — so the underlying work (IPC invokes, fs ops) is
+ * throttled, not just the awaits.
+ *
+ * Important for big IO fanouts where eager `.map(() => invoke(...))` would
+ * queue thousands of in-flight promises and OOM the renderer. Kept as a
+ * leaf module (no Pro / DOM imports) so unit tests can import it without
+ * dragging in the rest of services/utils-io.ts.
+ */
+export async function runConcurrent<I, R>(
+ items: I[],
+ worker: (item: I, index: number) => Promise<R>,
+ concurrency: number,
+ onSettled?: (item: I, index: number, result: PromiseSettledResult<R>) => void,
+ abortSignal?: AbortSignal,
+): Promise<PromiseSettledResult<R>[]> {
+ const results: PromiseSettledResult<R>[] = new Array(items.length);
+ if (items.length === 0) {
+ return results;
+ }
+ let cursor = 0;
+ const slots = Math.max(1, Math.min(concurrency, items.length));
+
+ const runWorker = async () => {
+ while (true) {
+ if (abortSignal && abortSignal.aborted) {
+ return;
+ }
+ const idx = cursor++;
+ if (idx >= items.length) {
+ return;
+ }
+ const item = items[idx];
+ let result: PromiseSettledResult<R>;
+ try {
+ const value = await worker(item, idx);
+ result = { status: 'fulfilled', value };
+ } catch (reason) {
+ result = { status: 'rejected', reason };
+ }
+ results[idx] = result;
+ if (onSettled) {
+ onSettled(item, idx, result);
+ }
+ }
+ };
+
+ await Promise.all(Array.from({ length: slots }, runWorker));
+ return results;
+}
diff --git a/tests/e2e/move-copy-dialog.pw.e2e.js b/tests/e2e/move-copy-dialog.pw.e2e.js
index eb2346ecd..ecd8ddd76 100644
--- a/tests/e2e/move-copy-dialog.pw.e2e.js
+++ b/tests/e2e/move-copy-dialog.pw.e2e.js
@@ -9,6 +9,7 @@ import {
expectElementExist,
getGridFileSelector,
reloadDirectory,
+ selectAllFiles,
setInputValue,
} from './general.helpers';
import { startTestingApp, stopApp } from './hook';
@@ -220,6 +221,170 @@ test.describe('TST10 - Move/Copy dialog new features', () => {
await closeMoveCopyDialog();
});
+ test('TST1009 - Bulk multi-file copy renders single-row progress and lands on disk (regression) [electron,s3]', async () => {
+ // Regression guard for the bounded-fanout work in copyFilesWithProgress.
+ // Two things must hold for a multi-file copy:
+ // 1. The progress dialog uses the single-row batch-key shape — title
+ // shows `(N%)`, not the misleading per-file `(0/1)`. Asserting on
+ // "%" in the title text is the cheapest way to lock that in.
+ // 2. Every selected file actually arrives at the destination. If
+ // runConcurrent's worker pool ever silently dropped tail items
+ // this assertion would fail.
+ const destName = 'bulkcopy_dest_' + Date.now();
+
+ // Create the destination folder at the root.
+ await createNewDirectory(destName);
+ await expectElementExist(getGridFileSelector(destName), true, 10000);
+
+ // Select all files in the root listing (the supported-filestypes location
+ // ships with ~69 sample files — enough to exercise the pool but small
+ // enough that the copy completes in seconds, not minutes).
+ await selectAllFiles();
+
+ // Open the bulk move/copy dialog via the toolbar action.
+ await clickOn('[data-tid=gridPerspectiveCopySelectedFiles]');
+ // Make sure we're in Copy mode (the toggle is persisted — last test may
+ // have left it on Move).
+ await clickOnIfVisible('[data-tid=mcfModeCopy]');
+ await expectElementExist('[data-tid=confirmCopyFiles]', true, 5000);
+
+ // Pick the destination via the picker.
+ await setInputValue('[data-tid=folderBrowserSearch]', destName);
+ await expectElementExist(
+ '[data-tid=MoveTarget' + destName + ']',
+ true,
+ 5000,
+ );
+ await clickOn('[data-tid=MoveTarget' + destName + ']');
+
+ // Fire the copy.
+ await clickOn('[data-tid=confirmCopyFiles]');
+
+ // Upload dialog should appear.
+ await expectElementExist(
+ '[data-tid=closeFileUploadTID]',
+ true,
+ 15000,
+ );
+
+ // After completion the "Close and Clear" footer button becomes visible
+ // (it only renders when `!haveProgress`). Wait up to 60s — a clean
+ // copy of ~69 small files takes a couple seconds; the slack covers
+ // slower CI machines and S3-backed runs.
+ await expectElementExist(
+ '[data-tid=uploadCloseAndClearTID]',
+ true,
+ 60000,
+ );
+
+ // Pull the actual dialog title text. The title encodes how progress is
+ // dispatched — and the load-bearing regression we want to guard against
+ // is "thousands of per-file rows". Two valid post-fix shapes:
+ // `(N%)` when a single copyFilesWithProgress call dispatched its
+ // stable batch key (one row).
+ // `(K/M)` when copyDirs + copyFiles fanned into a few rows (one per
+ // top-level dir + one per copyFilesWithProgress call). M is
+ // always small here — never the total file count.
+ // Pre-fix this would have been `(N/69)` or similar (one row per file).
+ //
+ // Scope the selector: `#draggable-dialog-title` is reused by every
+ // TsDialogTitle in the app, and `keepMounted` leaves hidden dialogs in
+ // the DOM whose `.innerText()` returns "". Use `:has()` to pick the
+ // title that contains our close button — guaranteed to be the visible
+ // FileUploadDialog.
+ const titleText = await global.client
+ .locator('#draggable-dialog-title:has([data-tid=closeFileUploadTID])')
+ .innerText();
+ const pctMatch = titleText.match(/\((\d+)%\)/);
+ const countMatch = titleText.match(/\((\d+)\/(\d+)\)/);
+ expect(Boolean(pctMatch || countMatch)).toBe(true);
+ if (countMatch) {
+ // The denominator must be tiny (a handful of dispatches) — not the
+ // total number of files we just copied. 20 is generous and still
+ // catches a regression to per-file rows on our ~69-file dataset.
+ expect(parseInt(countMatch[2], 10)).toBeLessThan(20);
+ }
+
+ await clickOn('[data-tid=uploadCloseAndClearTID]');
+
+ // The on-disk assertion: at least one well-known sample file from the
+ // root must now be inside the destination folder. We pick a small,
+ // text-y file so the assertion is cheap and not thumbnail-dependent.
+ await global.client.dblclick(getGridFileSelector(destName));
+ await expectElementExist(getGridFileSelector('sample.txt'), true, 10000);
+ await expectElementExist(getGridFileSelector('sample.json'), true, 5000);
+ });
+
+ test('TST1010 - Minimize hides dialog while indicator stays + reopens on click (regression) [electron,s3]', async () => {
+ // Regression guard for the minimize wiring: clicking the title X must
+ // hide the dialog WITHOUT clearing progress state, so the small
+ // CircularProgress indicator next to the search bar stays up and can
+ // restore the dialog. The pre-fix bug was that any progress dispatch
+ // re-opened the dialog via a useEffect on `progress`, making minimize
+ // visually flicker.
+ const destName = 'mincop_dest_' + Date.now();
+ await createNewDirectory(destName);
+ await expectElementExist(getGridFileSelector(destName), true, 10000);
+
+ await selectAllFiles();
+ await clickOn('[data-tid=gridPerspectiveCopySelectedFiles]');
+ await clickOnIfVisible('[data-tid=mcfModeCopy]');
+ await expectElementExist('[data-tid=confirmCopyFiles]', true, 5000);
+
+ await setInputValue('[data-tid=folderBrowserSearch]', destName);
+ await expectElementExist(
+ '[data-tid=MoveTarget' + destName + ']',
+ true,
+ 5000,
+ );
+ await clickOn('[data-tid=MoveTarget' + destName + ']');
+ await clickOn('[data-tid=confirmCopyFiles]');
+
+ // Wait for the upload dialog (title close button is the minimize gesture).
+ await expectElementExist(
+ '[data-tid=closeFileUploadTID]',
+ true,
+ 15000,
+ );
+
+ // Click the title X — minimizes the dialog. The progress data must
+ // remain in the store so the indicator can read it.
+ await clickOn('[data-tid=closeFileUploadTID]');
+
+ // Dialog is gone (no Close/Clear visible).
+ await expectElementExist(
+ '[data-tid=uploadCloseAndClearTID]',
+ false,
+ 3000,
+ );
+
+ // The background-process indicator next to the search bar is now the
+ // only surface showing progress. It only renders when `progress.length
+ // > 0`, so its presence after minimize is the load-bearing assertion.
+ await expectElementExist('#progressButton', true, 10000);
+
+ // Click the indicator to restore the dialog.
+ await clickOn('#progressButton');
+ // The dialog comes back — title X visible again.
+ await expectElementExist(
+ '[data-tid=closeFileUploadTID]',
+ true,
+ 5000,
+ );
+
+ // Let it finish and dismiss for the next test's clean slate.
+ await expectElementExist(
+ '[data-tid=uploadCloseAndClearTID]',
+ true,
+ 60000,
+ );
+ await clickOn('[data-tid=uploadCloseAndClearTID]');
+
+ // Once the user clicks Close and Clear, the indicator must disappear
+ // (resetProgress empties the array, FolderContainer hides the button).
+ await expectElementExist('#progressButton', false, 5000);
+ });
+
test('TST1008 - Folder move with same-name overwrite removes source on disk (regression) [electron]', async () => {
// Regression guard for the silent-swallow bug in moveDirectoryPromise:
// when the destination already contained a folder with the same name,
diff --git a/tests/unit/indexReflect.test.js b/tests/unit/indexReflect.test.js
index ca542f633..d88ac3e3c 100644
--- a/tests/unit/indexReflect.test.js
+++ b/tests/unit/indexReflect.test.js
@@ -1,6 +1,8 @@
import { describe, expect, test } from '@playwright/test';
import {
+ applyBulkCreateToIndex,
+ applyBulkUpdateToIndex,
applyCreateToIndex,
applyDeleteToIndex,
applyUpdateToIndex,
@@ -129,3 +131,154 @@ describe('applyUpdateToIndex', () => {
expect(index).toEqual(snapshot);
});
});
+
+describe('applyBulkCreateToIndex', () => {
+ test('appends all new entries in a single allocation', () => {
+ const index = [entry('a.txt')];
+ expect(
+ applyBulkCreateToIndex(index, [entry('b.txt'), entry('c.txt')]),
+ ).toEqual([entry('a.txt'), entry('b.txt'), entry('c.txt')]);
+ });
+
+ test('dedups against existing index paths', () => {
+ // Bulk equivalent of the single-entry "already present" no-op. New
+ // entries whose path already exists must be silently dropped.
+ const index = [entry('a.txt'), entry('b.txt')];
+ expect(
+ applyBulkCreateToIndex(index, [
+ entry('a.txt', { size: 999 }), // dup — drop
+ entry('c.txt'),
+ ]),
+ ).toEqual([entry('a.txt'), entry('b.txt'), entry('c.txt')]);
+ });
+
+ test('dedups within the bulk batch itself', () => {
+ // A naive impl would only check against `current`. If the same path
+ // appears twice in `newEntries`, only the first should land — otherwise
+ // a bulk add inserts duplicates the single helper would have refused.
+ const index = [entry('a.txt')];
+ expect(
+ applyBulkCreateToIndex(index, [
+ entry('b.txt'),
+ entry('b.txt', { size: 7 }), // intra-batch dup — drop
+ entry('c.txt'),
+ ]),
+ ).toEqual([entry('a.txt'), entry('b.txt'), entry('c.txt')]);
+ });
+
+ test('returns null when every entry is already present', () => {
+ const index = [entry('a.txt'), entry('b.txt')];
+ expect(
+ applyBulkCreateToIndex(index, [entry('a.txt'), entry('b.txt')]),
+ ).toBeNull();
+ });
+
+ test('returns null for empty or undefined inputs', () => {
+ expect(applyBulkCreateToIndex(undefined, [entry('a.txt')])).toBeNull();
+ expect(applyBulkCreateToIndex([], [entry('a.txt')])).toBeNull();
+ expect(applyBulkCreateToIndex([entry('a.txt')], [])).toBeNull();
+ expect(applyBulkCreateToIndex([entry('a.txt')], undefined)).toBeNull();
+ });
+
+ test('does not mutate inputs', () => {
+ const index = [entry('a.txt')];
+ const incoming = [entry('b.txt'), entry('c.txt')];
+ const indexSnapshot = [...index];
+ const incomingSnapshot = [...incoming];
+ applyBulkCreateToIndex(index, incoming);
+ expect(index).toEqual(indexSnapshot);
+ expect(incoming).toEqual(incomingSnapshot);
+ });
+
+ test('skips falsy entries in the batch', () => {
+ // The caller filters with .filter(Boolean) before passing in, but the
+ // helper should be defensive — a single undefined slot must not throw
+ // or get added.
+ const index = [entry('a.txt')];
+ expect(
+ applyBulkCreateToIndex(index, [entry('b.txt'), undefined, null]),
+ ).toEqual([entry('a.txt'), entry('b.txt')]);
+ });
+});
+
+describe('applyBulkUpdateToIndex', () => {
+ test('replaces all matching entries in a single walk', () => {
+ const index = [
+ entry('a.txt'),
+ entry('b.txt', { size: 10 }),
+ entry('c.txt', { size: 20 }),
+ ];
+ const updatedB = entry('b.txt', { size: 42 });
+ const updatedC = entry('c.txt', { size: 84 });
+ expect(
+ applyBulkUpdateToIndex(index, [
+ { oldPath: 'b.txt', entry: updatedB },
+ { oldPath: 'c.txt', entry: updatedC },
+ ]),
+ ).toEqual([entry('a.txt'), updatedB, updatedC]);
+ });
+
+ test('handles bulk moves — oldPath differs from newEntry.path', () => {
+ // Same rename-semantics contract as the single-entry update helper. A
+ // 3500-file cross-volume move dispatches as a uniform "move" action
+ // batch that lands here.
+ const index = [entry('old1.txt'), entry('old2.txt'), entry('keep.txt')];
+ const new1 = entry('new1.txt');
+ const new2 = entry('new2.txt');
+ expect(
+ applyBulkUpdateToIndex(index, [
+ { oldPath: 'old1.txt', entry: new1 },
+ { oldPath: 'old2.txt', entry: new2 },
+ ]),
+ ).toEqual([new1, new2, entry('keep.txt')]);
+ });
+
+ test('returns null when no oldPath is in the index', () => {
+ const index = [entry('a.txt')];
+ expect(
+ applyBulkUpdateToIndex(index, [
+ { oldPath: 'missing-1.txt', entry: entry('x.txt') },
+ { oldPath: 'missing-2.txt', entry: entry('y.txt') },
+ ]),
+ ).toBeNull();
+ });
+
+ test('returns null for empty or undefined inputs', () => {
+ expect(
+ applyBulkUpdateToIndex(undefined, [
+ { oldPath: 'a.txt', entry: entry('a.txt') },
+ ]),
+ ).toBeNull();
+ expect(
+ applyBulkUpdateToIndex([], [{ oldPath: 'a.txt', entry: entry('a.txt') }]),
+ ).toBeNull();
+ expect(applyBulkUpdateToIndex([entry('a.txt')], [])).toBeNull();
+ expect(applyBulkUpdateToIndex([entry('a.txt')], undefined)).toBeNull();
+ });
+
+ test('ignores malformed update tuples without crashing', () => {
+ // Defensive: the producer in the context provider filters with
+ // .filter((a) => a.oldEntryPath && a.entry) but a regression there
+ // should not blow up the helper.
+ const index = [entry('a.txt')];
+ expect(
+ applyBulkUpdateToIndex(index, [
+ { oldPath: 'a.txt', entry: entry('a.txt', { size: 99 }) },
+ { oldPath: '', entry: entry('x.txt') }, // empty oldPath — skip
+ { oldPath: 'b.txt', entry: null }, // null entry — skip
+ ]),
+ ).toEqual([entry('a.txt', { size: 99 })]);
+ });
+
+ test('does not mutate inputs', () => {
+ const index = [entry('a.txt'), entry('b.txt')];
+ const updates = [
+ { oldPath: 'a.txt', entry: entry('a.txt', { size: 99 }) },
+ ];
+ const indexSnapshot = [...index];
+ const updatesSnapshot = [...updates];
+ applyBulkUpdateToIndex(index, updates);
+ expect(index).toEqual(indexSnapshot);
+ expect(updates).toEqual(updatesSnapshot);
+ });
+});
diff --git a/tests/unit/runConcurrent.test.js b/tests/unit/runConcurrent.test.js
new file mode 100644
index 000000000..d8a7a146f
--- /dev/null
+++ b/tests/unit/runConcurrent.test.js
@@ -0,0 +1,188 @@
+import { describe, expect, test } from '@playwright/test';
+
+import { runConcurrent } from '-/utils/runConcurrent';
+
+// Helper: a worker that resolves after a tunable delay and records its
+// peak observed concurrency via shared counters. Returns the input value.
+function makeTrackingWorker(state, delayMs = 5) {
+ return async (item) => {
+ state.inFlight += 1;
+ state.peak = Math.max(state.peak, state.inFlight);
+ await new Promise((r) => setTimeout(r, delayMs));
+ state.inFlight -= 1;
+ return item;
+ };
+}
+
+describe('runConcurrent', () => {
+ test('settles every item and returns them indexed by input order', async () => {
+ // Workers complete in non-input order — settled[i] must still
+ // correspond to items[i] regardless of who finishes first.
+ const items = [50, 5, 30, 1, 20];
+ const settled = await runConcurrent(
+ items,
+ async (n) => {
+ await new Promise((r) => setTimeout(r, n));
+ return n * 2;
+ },
+ 4,
+ );
+ expect(settled.length).toBe(items.length);
+ expect(settled.map((r) => r.status)).toEqual(
+ Array(items.length).fill('fulfilled'),
+ );
+ expect(settled.map((r) => r.value)).toEqual(items.map((n) => n * 2));
+ });
+
+ test('peak in-flight never exceeds the concurrency cap', async () => {
+ // The load-bearing invariant. The original OOM crashes happened because
+ // copyFilesWithProgress eagerly fired thousands of IPC calls. If this
+ // helper silently exceeded its cap a future regression would re-OOM
+ // the renderer.
+ const state = { inFlight: 0, peak: 0 };
+ const items = new Array(50).fill(0).map((_, i) => i);
+ const cap = 8;
+ await runConcurrent(items, makeTrackingWorker(state, 3), cap);
+ expect(state.peak).toBeGreaterThan(0);
+ expect(state.peak).toBeLessThanOrEqual(cap);
+ });
+
+ test('caps concurrency below the number of items (small batch)', async () => {
+ // When items.length < concurrency, we shouldn't spin up more workers
+ // than there are items to process — wasted promises, wasted budget.
+ const state = { inFlight: 0, peak: 0 };
+ const items = [1, 2, 3];
+ await runConcurrent(items, makeTrackingWorker(state, 5), 16);
+ expect(state.peak).toBeLessThanOrEqual(items.length);
+ });
+
+ test('treats invalid concurrency values as at least 1', async () => {
+ // Defensive: a 0 or negative cap from a buggy caller should still make
+ // forward progress (one-at-a-time), not spin forever or deadlock.
+ const items = [1, 2, 3];
+ const r0 = await runConcurrent(items, async (n) => n, 0);
+ const rNeg = await runConcurrent(items, async (n) => n, -5);
+ expect(r0.map((x) => x.value)).toEqual(items);
+ expect(rNeg.map((x) => x.value)).toEqual(items);
+ });
+
+ test('captures rejections without aborting siblings', async () => {
+ // A failure for one item must not poison the whole batch — the user's
+ // 3500-file copy depends on a single bad file (ENOENT, permission, etc.)
+ // not killing the other 3499.
+ const items = ['ok-a', 'fail-b', 'ok-c', 'fail-d', 'ok-e'];
+ const settled = await runConcurrent(
+ items,
+ async (name) => {
+ if (name.startsWith('fail')) {
+ throw new Error('boom-' + name);
+ }
+ return name.toUpperCase();
+ },
+ 3,
+ );
+ expect(settled.length).toBe(items.length);
+ expect(settled[0]).toEqual({ status: 'fulfilled', value: 'OK-A' });
+ expect(settled[1].status).toBe('rejected');
+ expect(String(settled[1].reason.message)).toBe('boom-fail-b');
+ expect(settled[2]).toEqual({ status: 'fulfilled', value: 'OK-C' });
+ expect(settled[3].status).toBe('rejected');
+ expect(settled[4]).toEqual({ status: 'fulfilled', value: 'OK-E' });
+ });
+
+ test('onSettled fires for every item, exactly once, with the per-item result', async () => {
+ const seen = [];
+ const items = [10, 20, 30, 40];
+ await runConcurrent(
+ items,
+ async (n) => {
+ if (n === 20) throw new Error('twenty');
+ return n + 1;
+ },
+ 2,
+ (item, idx, result) => {
+ seen.push({ item, idx, status: result.status });
+ },
+ );
+ expect(seen.length).toBe(items.length);
+ // Sort by idx for a deterministic assertion regardless of completion order
+ seen.sort((a, b) => a.idx - b.idx);
+ expect(seen).toEqual([
+ { item: 10, idx: 0, status: 'fulfilled' },
+ { item: 20, idx: 1, status: 'rejected' },
+ { item: 30, idx: 2, status: 'fulfilled' },
+ { item: 40, idx: 3, status: 'fulfilled' },
+ ]);
+ });
+
+ test('abort signal stops new items from being picked up', async () => {
+ // Aborting mid-batch is what powers the per-row Cancel button. Workers
+ // already running may finish, but the queue must not advance past the
+ // abort point — otherwise "Cancel" would keep doing work for seconds.
+ const controller = new AbortController();
+ const startedIndices = [];
+ const items = new Array(20).fill(0).map((_, i) => i);
+
+ const settled = await runConcurrent(
+ items,
+ async (i) => {
+ startedIndices.push(i);
+ // Trip the abort after the first 4 items have started.
+ if (i === 3) {
+ controller.abort();
+ }
+ await new Promise((r) => setTimeout(r, 5));
+ return i;
+ },
+ 4,
+ undefined,
+ controller.signal,
+ );
+
+ // Only a bounded number of items should have started — not all 20.
+ expect(startedIndices.length).toBeLessThan(items.length);
+ // The pre-allocated results array still has items.length slots; the
+ // tail items are simply never written. NOTE: settled is a sparse array
+ // (created via `new Array(N)`), and Array.prototype.filter skips empty
+ // slots — so we walk indices manually to count what's actually missing.
+ expect(settled.length).toBe(items.length);
+ let unfilled = 0;
+ for (let i = 0; i < settled.length; i += 1) {
+ if (settled[i] === undefined) unfilled += 1;
+ }
+ expect(unfilled).toBeGreaterThan(0);
+ });
+
+ test('handles an empty input list', async () => {
+ // Edge case: caller may pass [] when the prefilter rejected everything
+ // (e.g. zero sidecars to copy). Must resolve to [] without spinning.
+ const seen = [];
+ const settled = await runConcurrent(
+ [],
+ async () => 'never-called',
+ 8,
+ () => seen.push('settled'),
+ );
+ expect(settled).toEqual([]);
+ expect(seen.length).toBe(0);
+ });
+
+ test('worker receives both the item and its original index', async () => {
+ const calls = [];
+ const items = ['a', 'b', 'c'];
+ await runConcurrent(
+ items,
+ async (item, idx) => {
+ calls.push({ item, idx });
+ return item;
+ },
+ 2,
+ );
+ calls.sort((a, b) => a.idx - b.idx);
+ expect(calls).toEqual([
+ { item: 'a', idx: 0 },
+ { item: 'b', idx: 1 },
+ { item: 'c', idx: 2 },
+ ]);
+ });
+});