Three defects on the paths that touch a user's real bookmarks.
**A mid-import rejection used to lose everything needed to recover.**
writeTree awaited create() and let a rejection propagate bare — while the
bookmarks it had already written sat in the user's tree, uncounted. The
neighbouring BmAborted has always carried `done` for exactly this reason.
clearRoots was worse: it is the one path that deletes, and it reported nothing
at all, plus threw BmAborted(0) on cancellation regardless of how many root
children were already gone. Both now throw BmPartialWrite{phase, done}, and the
error state carries the safety backup's filename — which `attesting` knew and
`error` threw away, so the one string that lets someone restore a half-replaced
tree was the one thing not on screen. Only when a backup was actually produced:
on a BmBackupError the file may never have been written, and sending a
frightened user to look for a backup that does not exist is worse than silence.
BmAborted is re-thrown before the wrap, with a test pinning it. Wrapping it
would relabel every user cancellation as a failure and make the `cancelled`
state — and its copy in three languages — unreachable.
**Browser Back during the backup attestation deadlocked the Manager
permanently.** The attestation resolver was a component-local `let`, so Back
unmounted ImportTab, stranded the promise runImport was awaiting, and left
isWriting() true forever: every tab and footer control disabled, beforeunload
prompting, and a remounted tab rendering two inert buttons against a fresh empty
resolver. Closing the tab was the only escape. Phase 4 closed this same hole for
the footer and the tab bar; hashchange was the door left open.
Two independent fixes, because one is not enough: startRouting now takes an
injected isBlocked predicate (injected, not imported, so route stays uncoupled
from the import session), and the resolver moved into the store where it
outlives any component. A stale or reset resolver settles **false** — an
unanswered attestation is not consent, and this is the last gate before deleting
every bookmark someone has. The restore-the-hash path has an explicit test for
not recursing; an infinite hashchange loop in a released extension, on the path
a panicking user takes, is not a defect worth discovering from a review.
**Nothing told users their imported bookmarks are re-dated to today.** docs/05
§6 instructs saying so in the import report and docs/00 §8 repeats it as a
success criterion; no string ever did. The README and store listing say it to
prospective users, and the product never said it to actual ones — so someone
migrating a decade-old archive finds every bookmark dated today with no
explanation and no way to tell it from corruption. Now shown before the import
as well as after: telling someone before they commit is worth more.
Also: a profile whose every root is policy-managed now reports
NO_WRITABLE_ROOTS rather than "the browser refused a bookmark operation". The
browser refused nothing; it is an absence, not a refusal, and the old wording
sent people looking for a permission problem that was not there.
describeError moves out of ImportTab into browser/describe-error.ts so #edit and
#export can share it next, with tests asserting the two properties that have
been defects before: it returns a key rather than a resolved sentence, and it
omits `detail` rather than setting it to undefined.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
275 lines
9.6 KiB
TypeScript
275 lines
9.6 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest';
|
|
import { BmAborted, BmPartialWrite } from '@/lib/browser/errors';
|
|
import { type WriteProgress, writeTree } from '@/lib/browser/write-queue';
|
|
import type { BookmarkNode, ImportPlan } from '@/lib/core/model';
|
|
import { FakeBookmarks } from '../../helpers/fake-bookmarks';
|
|
|
|
/** Build a plan whose stats match its segments, the way buildImportPlan does. */
|
|
function planOf(segments: ImportPlan['segments']): ImportPlan {
|
|
const count = (nodes: readonly BookmarkNode[]): number =>
|
|
nodes.reduce((n, node) => n + 1 + count(node.children ?? []), 0);
|
|
const toCreate = segments.reduce((n, s) => n + count(s.nodes), 0);
|
|
return {
|
|
mode: 'merge',
|
|
dedupe: false,
|
|
segments,
|
|
stats: { toCreate, bookmarkCount: 0, skippedExisting: 0, skippedInFile: 0 },
|
|
};
|
|
}
|
|
|
|
const TREE: BookmarkNode[] = [
|
|
{
|
|
title: 'Folder',
|
|
children: [
|
|
{ title: 'a', url: 'https://a.example/' },
|
|
{ title: 'Nested', children: [{ title: 'b', url: 'https://b.example/' }] },
|
|
],
|
|
},
|
|
{ title: 'c', url: 'https://c.example/' },
|
|
];
|
|
|
|
describe('writeTree — ordering', () => {
|
|
it('creates parents before children and siblings in order', async () => {
|
|
const fake = new FakeBookmarks();
|
|
await writeTree(planOf([{ rootId: '2', nodes: TREE }]), { create: fake.create });
|
|
|
|
expect(fake.calls).toEqual([
|
|
'create:2:Folder',
|
|
'create:100:a',
|
|
'create:100:Nested',
|
|
'create:102:b',
|
|
'create:2:c',
|
|
]);
|
|
});
|
|
|
|
it('writes each segment under its own root', async () => {
|
|
const fake = new FakeBookmarks();
|
|
await writeTree(
|
|
planOf([
|
|
{ rootId: '1', nodes: [{ title: 'bar item', url: 'https://bar.example/' }] },
|
|
{ rootId: '2', nodes: [{ title: 'other item', url: 'https://other.example/' }] },
|
|
]),
|
|
{ create: fake.create },
|
|
);
|
|
|
|
expect(fake.childTitles('1')).toEqual(['bar item']);
|
|
expect(fake.childTitles('2')).toEqual(['other item']);
|
|
});
|
|
|
|
it('appends rather than prepending — no explicit index is passed', async () => {
|
|
const fake = new FakeBookmarks();
|
|
fake.seed('2', { title: 'existing', url: 'https://existing.example/' });
|
|
await writeTree(
|
|
planOf([{ rootId: '2', nodes: [{ title: 'new', url: 'https://new.example/' }] }]),
|
|
{
|
|
create: fake.create,
|
|
},
|
|
);
|
|
expect(fake.childTitles('2')).toEqual(['existing', 'new']);
|
|
});
|
|
});
|
|
|
|
describe('writeTree — progress', () => {
|
|
const wideTree = (n: number): BookmarkNode[] =>
|
|
Array.from({ length: n }, (_, i) => ({ title: `b${i}`, url: `https://e${i}.example/` }));
|
|
|
|
it('reports every 50 creates and once at the end', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const events: WriteProgress[] = [];
|
|
await writeTree(planOf([{ rootId: '2', nodes: wideTree(120) }]), {
|
|
create: fake.create,
|
|
onProgress: (p) => events.push({ ...p }),
|
|
});
|
|
|
|
expect(events.map((e) => e.done)).toEqual([50, 100, 120]);
|
|
expect(events.every((e) => e.total === 120)).toBe(true);
|
|
});
|
|
|
|
it('still emits a final event when the total is under the cadence', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const events: WriteProgress[] = [];
|
|
await writeTree(planOf([{ rootId: '2', nodes: wideTree(3) }]), {
|
|
create: fake.create,
|
|
onProgress: (p) => events.push({ ...p }),
|
|
});
|
|
expect(events.at(-1)).toMatchObject({ done: 3, total: 3 });
|
|
});
|
|
|
|
it('emits one event even for an empty plan', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const events: WriteProgress[] = [];
|
|
await writeTree(planOf([]), { create: fake.create, onProgress: (p) => events.push({ ...p }) });
|
|
expect(events).toEqual([{ done: 0, total: 0, currentPath: '' }]);
|
|
});
|
|
|
|
it('carries the folder path of the node being written', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const events: WriteProgress[] = [];
|
|
const deep: BookmarkNode[] = [
|
|
{ title: 'L1', children: [{ title: 'L2', children: wideTree(50) }] },
|
|
];
|
|
await writeTree(planOf([{ rootId: '2', nodes: deep }]), {
|
|
create: fake.create,
|
|
onProgress: (p) => events.push({ ...p }),
|
|
});
|
|
expect(events[0]?.currentPath).toBe('L1 / L2');
|
|
});
|
|
|
|
it('counts progress across segments with one shared denominator', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const events: WriteProgress[] = [];
|
|
await writeTree(
|
|
planOf([
|
|
{ rootId: '1', nodes: wideTree(30) },
|
|
{ rootId: '2', nodes: wideTree(30) },
|
|
]),
|
|
{ create: fake.create, onProgress: (p) => events.push({ ...p }) },
|
|
);
|
|
// 60 total, so the 50th create reports across the segment boundary.
|
|
expect(events.map((e) => e.done)).toEqual([50, 60]);
|
|
expect(events[0]?.total).toBe(60);
|
|
});
|
|
});
|
|
|
|
describe('writeTree — abort', () => {
|
|
it('throws BmAborted carrying the exact created count and stops calling', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const controller = new AbortController();
|
|
const nodes = Array.from({ length: 20 }, (_, i) => ({
|
|
title: `b${i}`,
|
|
url: `https://e${i}.example/`,
|
|
}));
|
|
|
|
const create: typeof fake.create = async (details) => {
|
|
const node = await fake.create(details);
|
|
if (fake.countCalls('create') === 5) controller.abort();
|
|
return node;
|
|
};
|
|
|
|
await expect(
|
|
writeTree(planOf([{ rootId: '2', nodes }]), { signal: controller.signal, create }),
|
|
).rejects.toBeInstanceOf(BmAborted);
|
|
|
|
expect(fake.countCalls('create')).toBe(5);
|
|
expect(fake.childTitles('2')).toEqual(['b0', 'b1', 'b2', 'b3', 'b4']);
|
|
});
|
|
|
|
it('reports done === the number actually written', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const controller = new AbortController();
|
|
const create: typeof fake.create = async (details) => {
|
|
const node = await fake.create(details);
|
|
if (fake.countCalls('create') === 3) controller.abort();
|
|
return node;
|
|
};
|
|
try {
|
|
await writeTree(
|
|
planOf([
|
|
{
|
|
rootId: '2',
|
|
nodes: Array.from({ length: 9 }, (_, i) => ({
|
|
title: `b${i}`,
|
|
url: `https://e${i}.example/`,
|
|
})),
|
|
},
|
|
]),
|
|
{ signal: controller.signal, create },
|
|
);
|
|
expect.unreachable('should have aborted');
|
|
} catch (err) {
|
|
expect((err as BmAborted).done).toBe(3);
|
|
}
|
|
});
|
|
|
|
it('aborts before the first create when the signal is already set', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
await expect(
|
|
writeTree(planOf([{ rootId: '2', nodes: [{ title: 'a', url: 'https://a.example/' }] }]), {
|
|
signal: controller.signal,
|
|
create: fake.create,
|
|
}),
|
|
).rejects.toBeInstanceOf(BmAborted);
|
|
expect(fake.countCalls('create')).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe('writeTree — API failure', () => {
|
|
const sixNodes = (): { title: string; url: string }[] =>
|
|
Array.from({ length: 6 }, (_, i) => ({ title: `b${i}`, url: `https://e${i}.example/` }));
|
|
|
|
it('propagates a create failure with the earlier successes already written', async () => {
|
|
const fake = new FakeBookmarks({ failOnCreate: 4 });
|
|
|
|
await expect(
|
|
writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), { create: fake.create }),
|
|
).rejects.toThrow(/injected failure/);
|
|
|
|
expect(fake.childTitles('2')).toEqual(['b0', 'b1', 'b2']);
|
|
});
|
|
|
|
it('reports how many nodes landed, because they are still in the user tree', async () => {
|
|
// Without this the report says only "the browser refused a bookmark
|
|
// operation" — while three real bookmarks sit in the tree, and the user has
|
|
// no way to learn how many. BmAborted has always carried this; a failure
|
|
// needs it at least as much, because nobody chose it.
|
|
const fake = new FakeBookmarks({ failOnCreate: 4 });
|
|
|
|
const err = await writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), {
|
|
create: fake.create,
|
|
}).catch((e: unknown) => e);
|
|
|
|
expect(err).toBeInstanceOf(BmPartialWrite);
|
|
const partial = err as BmPartialWrite;
|
|
expect(partial.phase).toBe('writing');
|
|
expect(partial.done).toBe(3);
|
|
expect(partial.detail).toMatch(/injected failure/);
|
|
});
|
|
|
|
it('lets a cancellation stay a cancellation', async () => {
|
|
// The abort check throws from inside the same loop as the create. Wrapping
|
|
// it would relabel every user cancellation as a failure and make the
|
|
// `cancelled` state — and its copy in three languages — unreachable.
|
|
const fake = new FakeBookmarks();
|
|
const controller = new AbortController();
|
|
|
|
const err = await writeTree(planOf([{ rootId: '2', nodes: sixNodes() }]), {
|
|
create: async (details) => {
|
|
controller.abort();
|
|
return fake.create(details);
|
|
},
|
|
signal: controller.signal,
|
|
}).catch((e: unknown) => e);
|
|
|
|
expect(err).toBeInstanceOf(BmAborted);
|
|
expect(err).not.toBeInstanceOf(BmPartialWrite);
|
|
});
|
|
});
|
|
|
|
describe('writeTree — responsiveness', () => {
|
|
it('yields to the event loop periodically on a large import', async () => {
|
|
const fake = new FakeBookmarks();
|
|
const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');
|
|
const before = setTimeoutSpy.mock.calls.length;
|
|
|
|
await writeTree(
|
|
planOf([
|
|
{
|
|
rootId: '2',
|
|
nodes: Array.from({ length: 450 }, (_, i) => ({
|
|
title: `b${i}`,
|
|
url: `https://e${i}.example/`,
|
|
})),
|
|
},
|
|
]),
|
|
{ create: fake.create },
|
|
);
|
|
|
|
// 450 creates → yields at 200 and 400. jsdom exposes no scheduler.yield,
|
|
// so the fallback path must actually run (and actually be awaited).
|
|
expect(setTimeoutSpy.mock.calls.length - before).toBeGreaterThanOrEqual(2);
|
|
setTimeoutSpy.mockRestore();
|
|
});
|
|
});
|