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>
125 lines
4.3 KiB
TypeScript
125 lines
4.3 KiB
TypeScript
/**
|
|
* Sequential tree writer — docs/05 §6.
|
|
*
|
|
* Purpose: create an `ImportPlan`'s nodes in order, with live progress and a
|
|
* working cancel button.
|
|
* Inputs: a plan, an AbortSignal, a progress callback.
|
|
* Guarantees: parents before children, siblings in order, one `done` counter
|
|
* across all segments, and an abort that stops before the next create.
|
|
*
|
|
* `chrome.bookmarks` has no bulk insert, so this is one awaited call per node.
|
|
* Order is preserved by creating in order and letting Chrome append.
|
|
*/
|
|
import type { BookmarkNode, ImportPlan } from '../core/model';
|
|
import { create as createNode, type LiveNode } from './bookmarks';
|
|
import { BmAborted, BmPartialWrite } from './errors';
|
|
|
|
/** Emitted every PROGRESS_EVERY creates and once at the end. */
|
|
export interface WriteProgress {
|
|
done: number;
|
|
total: number;
|
|
/** Folder path of the node just written, for the "Importing… <path>" line. */
|
|
currentPath: string;
|
|
}
|
|
|
|
export interface WriteOptions {
|
|
signal?: AbortSignal;
|
|
onProgress?: (progress: WriteProgress) => void;
|
|
/** Injectable for tests; defaults to the real adapter. */
|
|
create?: (details: { parentId: string; title: string; url?: string }) => Promise<LiveNode>;
|
|
}
|
|
|
|
const PROGRESS_EVERY = 50;
|
|
const YIELD_EVERY = 200;
|
|
|
|
/**
|
|
* Hand the event loop back so the tab stays responsive during a long import.
|
|
*
|
|
* The parentheses are load-bearing. Written as
|
|
* `await scheduler.yield?.() ?? new Promise(...)` this parses as
|
|
* `(await scheduler.yield?.()) ?? new Promise(...)`, which never yields: below
|
|
* Chrome 129 it awaits `undefined` and discards an un-awaited Promise, and on
|
|
* 129+ `yield()` resolves with `undefined` so it leaks a stray timer each call.
|
|
*/
|
|
export async function yieldToEventLoop(): Promise<void> {
|
|
const scheduler = (globalThis as { scheduler?: { yield?: () => Promise<void> } }).scheduler;
|
|
await (scheduler?.yield?.() ?? new Promise<void>((resolve) => setTimeout(resolve)));
|
|
}
|
|
|
|
export interface WriteResult {
|
|
created: number;
|
|
}
|
|
|
|
/**
|
|
* Write every segment of a plan.
|
|
*
|
|
* @throws {BmAborted} when the signal fires — carrying the exact number of
|
|
* nodes already created, so the report can tell the user what landed.
|
|
* @throws {BmPartialWrite} when a create rejects, carrying the same count. A
|
|
* rejection half-way through leaves real bookmarks in the user's tree; a bare
|
|
* "the browser refused" gives them no way to know how many.
|
|
*/
|
|
export async function writeTree(
|
|
plan: ImportPlan,
|
|
options: WriteOptions = {},
|
|
): Promise<WriteResult> {
|
|
const { signal, onProgress } = options;
|
|
const create = options.create ?? createNode;
|
|
const total = plan.stats.toCreate;
|
|
|
|
// Declared out here on purpose: progress, abort and the final report are
|
|
// whole-import scoped, not per segment.
|
|
let done = 0;
|
|
let sinceYield = 0;
|
|
|
|
const report = (currentPath: string): void => {
|
|
onProgress?.({ done, total, currentPath });
|
|
};
|
|
|
|
const dfs = async (
|
|
nodes: readonly BookmarkNode[],
|
|
parentId: string,
|
|
trail: readonly string[],
|
|
): Promise<void> => {
|
|
for (const node of nodes) {
|
|
if (signal?.aborted === true) throw new BmAborted(done);
|
|
|
|
let created: LiveNode;
|
|
try {
|
|
created = await create({
|
|
parentId,
|
|
title: node.title,
|
|
...(node.url !== undefined && { url: node.url }),
|
|
});
|
|
} catch (cause) {
|
|
// Order matters. The abort check above throws from inside this same
|
|
// loop, and wrapping it would relabel every user cancellation as a
|
|
// failure — making `cancelled` unreachable and its copy dead.
|
|
if (cause instanceof BmAborted) throw cause;
|
|
throw new BmPartialWrite('writing', done, cause);
|
|
}
|
|
|
|
done++;
|
|
sinceYield++;
|
|
if (done % PROGRESS_EVERY === 0 || done === total) report(trail.join(' / '));
|
|
if (sinceYield >= YIELD_EVERY) {
|
|
sinceYield = 0;
|
|
await yieldToEventLoop();
|
|
}
|
|
|
|
if (node.children !== undefined && node.children.length > 0) {
|
|
await dfs(node.children, created.id, [...trail, node.title]);
|
|
}
|
|
}
|
|
};
|
|
|
|
for (const segment of plan.segments) {
|
|
await dfs(segment.nodes, segment.rootId, []);
|
|
}
|
|
|
|
// Guarantee a final event even when the total was not a multiple of 50 and
|
|
// the plan turned out empty.
|
|
if (done !== total || total === 0) report('');
|
|
return { created: done };
|
|
}
|