fix(import): never lose the count, and close the Back-button deadlock
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>
This commit is contained in:
17 files changed
+754
-62
No files matched your search
@@ -33,7 +33,14 @@
|
||||
let mainEl: HTMLElement | undefined = $state();
|
||||
|
||||
onMount(() => {
|
||||
const stopRouting = startRouting();
|
||||
// The tab bar and the footer already refuse to navigate mid-write. This
|
||||
// closes the third door: browser Back, which fires `hashchange` directly
|
||||
// and — during the backup attestation — used to unmount ImportTab and leave
|
||||
// the Manager permanently locked.
|
||||
const stopRouting = startRouting({
|
||||
isBlocked: isWriting,
|
||||
onBlocked: () => pushToast(t('common.busy'), 'info'),
|
||||
});
|
||||
|
||||
// Leaving mid-write would kill the queue with the tab (docs/03 §5).
|
||||
const onBeforeUnload = (event: BeforeUnloadEvent): void => {
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
import { browser } from 'wxt/browser';
|
||||
import type { BookmarkNode } from '../core/model';
|
||||
import { millisToSeconds } from '../core/timestamps';
|
||||
import { BmAborted, BmBrowserError } from './errors';
|
||||
import { BmAborted, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
|
||||
|
||||
/** The live-tree node. Unlike `BookmarkNode` it carries browser identity. */
|
||||
export interface LiveNode {
|
||||
@@ -70,7 +70,10 @@ export async function getRoots(): Promise<BookmarkRoots> {
|
||||
const mobile = byId('3') ?? writable.find((node) => node !== toolbar && node !== other);
|
||||
|
||||
if (toolbar === undefined || other === undefined) {
|
||||
throw new BmBrowserError('bookmarks.getTree', 'no writable bookmark roots found');
|
||||
// Not a BmBrowserError: nothing refused anything. Every root this profile
|
||||
// has is policy-managed, so there is nowhere an extension may write, and
|
||||
// "the browser refused a bookmark operation" would be actively misleading.
|
||||
throw new BmEnvError('NO_WRITABLE_ROOTS', `${children.length} root(s), none writable`);
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -210,6 +213,11 @@ export function subscribe(handlers: BookmarkEvents): () => void {
|
||||
/**
|
||||
* Delete the CHILDREN of the given roots, never the roots themselves (the API
|
||||
* forbids that anyway). Managed nodes are skipped — docs/05 §6.
|
||||
*
|
||||
* @throws {BmAborted} on cancellation, carrying how many were already removed.
|
||||
* @throws {BmPartialWrite} when a removal rejects, carrying the same count.
|
||||
* This is the one path that destroys data, so "how much is gone" is the
|
||||
* single most useful thing the failure can say.
|
||||
*/
|
||||
export async function clearRoots(
|
||||
roots: readonly LiveNode[],
|
||||
@@ -222,8 +230,12 @@ export async function clearRoots(
|
||||
if (child.unmodifiable !== undefined) continue;
|
||||
// Checked per node so a cancel arriving mid-deletion stops promptly
|
||||
// rather than running the whole tree to completion.
|
||||
if (signal?.aborted === true) throw new BmAborted(0);
|
||||
await removeTree(child.id);
|
||||
if (signal?.aborted === true) throw new BmAborted(removed);
|
||||
try {
|
||||
await removeTree(child.id);
|
||||
} catch (cause) {
|
||||
throw new BmPartialWrite('clearing', removed, cause);
|
||||
}
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Map a thrown value onto an i18n key plus the raw technical detail —
|
||||
* docs/02 §7.
|
||||
*
|
||||
* Purpose: one place that decides how a failure is described, so the
|
||||
* "localized sentence + separate detail block" contract cannot be got wrong
|
||||
* in one tab and right in another.
|
||||
* Inputs: anything thrown by the core, browser or import layers.
|
||||
* Guarantees: returns a **key**, never a resolved sentence, and never throws.
|
||||
*
|
||||
* Two rules this encodes, both learned from real defects:
|
||||
*
|
||||
* - The key is not resolved here. The import session store outlives the
|
||||
* component that wrote to it, and `t()` is only reactive where it is called,
|
||||
* so a sentence stored at throw time would never follow a language switch.
|
||||
* - `detail` is a *separate* field, never a substitute for the message.
|
||||
* Rendering `detail ?? t(key)` makes every translation dead code, because the
|
||||
* raw browser string is almost always present.
|
||||
*
|
||||
* Lives in `browser/` because that is where the error taxonomy lives;
|
||||
* `browser/` may import `core/`, not the reverse (docs/02 §3).
|
||||
*/
|
||||
import { BmParseError } from '../core/model';
|
||||
import { BmBackupError, BmBrowserError, BmEnvError, BmPartialWrite } from './errors';
|
||||
|
||||
export interface DescribedError {
|
||||
/** Dotted i18n path, e.g. `errors.TOO_DEEP`. */
|
||||
messageKey: string;
|
||||
/** Raw, untranslated technical text for the copyable detail block. */
|
||||
detail?: string | undefined;
|
||||
/** Nodes written before a partial failure, when the failure knows. */
|
||||
created?: number;
|
||||
/** Root children deleted before a partial failure, when the failure knows. */
|
||||
removed?: number;
|
||||
}
|
||||
|
||||
export function describeError(err: unknown): DescribedError {
|
||||
if (err instanceof BmParseError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.detail };
|
||||
}
|
||||
if (err instanceof BmBackupError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.message };
|
||||
}
|
||||
if (err instanceof BmEnvError) {
|
||||
return {
|
||||
messageKey: `errors.${err.code}`,
|
||||
...(err.detail !== undefined && { detail: err.detail }),
|
||||
};
|
||||
}
|
||||
if (err instanceof BmPartialWrite) {
|
||||
// The phase decides the sentence, because "nothing was deleted, some items
|
||||
// were added" and "part of your tree is gone" need different advice.
|
||||
return {
|
||||
messageKey: err.phase === 'clearing' ? 'errors.PARTIAL_CLEAR' : 'errors.PARTIAL_WRITE',
|
||||
...(err.detail !== undefined && { detail: err.detail }),
|
||||
...(err.phase === 'clearing' ? { removed: err.done } : { created: err.done }),
|
||||
};
|
||||
}
|
||||
if (err instanceof BmBrowserError) {
|
||||
return { messageKey: 'errors.BROWSER', detail: err.detail };
|
||||
}
|
||||
return {
|
||||
messageKey: 'errors.UNKNOWN',
|
||||
detail: err instanceof Error ? err.message : undefined,
|
||||
};
|
||||
}
|
||||
@@ -46,3 +46,58 @@ export class BmBrowserError extends Error {
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
export type BmEnvCode = 'NO_WRITABLE_ROOTS';
|
||||
|
||||
/**
|
||||
* Thrown when the environment cannot support the operation at all.
|
||||
*
|
||||
* Distinct from `BmBrowserError` on purpose: an absence is not a refusal.
|
||||
* Reporting "the browser refused a bookmark operation" to someone whose profile
|
||||
* simply has no writable root sends them looking for the wrong thing.
|
||||
*/
|
||||
export class BmEnvError extends Error {
|
||||
readonly code: BmEnvCode;
|
||||
readonly detail: string | undefined;
|
||||
|
||||
constructor(code: BmEnvCode, detail?: string) {
|
||||
super(detail === undefined ? code : `${code}: ${detail}`);
|
||||
this.name = 'BmEnvError';
|
||||
this.code = code;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
/** Which destructive step was interrupted. */
|
||||
export type BmWritePhase = 'clearing' | 'writing';
|
||||
|
||||
/**
|
||||
* Thrown when a destructive step failed part-way through.
|
||||
*
|
||||
* Carries exactly what already landed, for the same reason `BmAborted` carries
|
||||
* `done`: a user whose tree was half-replaced needs a number and the name of
|
||||
* their backup, not "the browser refused a bookmark operation".
|
||||
*
|
||||
* `cause` is deliberately not used — `noImplicitOverride` complicates
|
||||
* redeclaring it, and the detail is flattened here anyway so the UI never has
|
||||
* to unwrap a chain.
|
||||
*/
|
||||
export class BmPartialWrite extends Error {
|
||||
readonly phase: BmWritePhase;
|
||||
readonly done: number;
|
||||
readonly detail: string | undefined;
|
||||
|
||||
constructor(phase: BmWritePhase, done: number, cause: unknown) {
|
||||
const detail =
|
||||
cause instanceof BmBrowserError
|
||||
? cause.detail
|
||||
: cause instanceof Error
|
||||
? cause.message
|
||||
: String(cause);
|
||||
super(`${phase} failed after ${done} item(s): ${detail}`);
|
||||
this.name = 'BmPartialWrite';
|
||||
this.phase = phase;
|
||||
this.done = done;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
*/
|
||||
import type { BookmarkNode, ImportPlan } from '../core/model';
|
||||
import { create as createNode, type LiveNode } from './bookmarks';
|
||||
import { BmAborted } from './errors';
|
||||
import { BmAborted, BmPartialWrite } from './errors';
|
||||
|
||||
/** Emitted every PROGRESS_EVERY creates and once at the end. */
|
||||
export interface WriteProgress {
|
||||
@@ -55,6 +55,9 @@ export interface WriteResult {
|
||||
*
|
||||
* @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,
|
||||
@@ -81,11 +84,20 @@ export async function writeTree(
|
||||
for (const node of nodes) {
|
||||
if (signal?.aborted === true) throw new BmAborted(done);
|
||||
|
||||
const created = await create({
|
||||
parentId,
|
||||
title: node.title,
|
||||
...(node.url !== undefined && { url: node.url }),
|
||||
});
|
||||
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++;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
<script lang="ts">
|
||||
import { describeError } from '../browser/describe-error';
|
||||
import { timestampSuffix } from '../browser/download';
|
||||
import { BmAborted, BmBackupError, BmBrowserError } from '../browser/errors';
|
||||
import { BmParseError } from '../core/model';
|
||||
import { BmAborted, BmBackupError } from '../browser/errors';
|
||||
import { num, t } from '../i18n/index.svelte';
|
||||
import { prepareImport, runImport } from '../import/run-import';
|
||||
import { getSettings } from '../stores/settings.svelte';
|
||||
import {
|
||||
answerAttestation,
|
||||
awaitAttestation,
|
||||
beginWrite,
|
||||
cancelWrite,
|
||||
getImportOptions,
|
||||
@@ -33,36 +35,6 @@
|
||||
const session = $derived(getImportState());
|
||||
const options = $derived(getImportOptions());
|
||||
|
||||
/** Resolver for the fallback-backup attestation dialog. */
|
||||
let attestResolve: ((confirmed: boolean) => void) | undefined;
|
||||
|
||||
function answerAttest(confirmed: boolean): void {
|
||||
attestResolve?.(confirmed);
|
||||
attestResolve = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map an error onto an i18n KEY plus a raw detail — never a resolved string.
|
||||
* The session store outlives this component, and `t()` only re-runs where it
|
||||
* is called, so a translated sentence stored here would never follow a
|
||||
* language switch.
|
||||
*/
|
||||
function describeError(err: unknown): { messageKey: string; detail: string | undefined } {
|
||||
if (err instanceof BmParseError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.detail };
|
||||
}
|
||||
if (err instanceof BmBackupError) {
|
||||
return { messageKey: `errors.${err.code}`, detail: err.message };
|
||||
}
|
||||
if (err instanceof BmBrowserError) {
|
||||
return { messageKey: 'errors.BROWSER', detail: err.detail };
|
||||
}
|
||||
return {
|
||||
messageKey: 'errors.UNKNOWN',
|
||||
detail: err instanceof Error ? err.message : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function onFile(file: File): Promise<void> {
|
||||
setImportState({ kind: 'validating', filename: file.name });
|
||||
try {
|
||||
@@ -116,9 +88,7 @@
|
||||
},
|
||||
confirmUnprovenBackup: () => {
|
||||
setImportState({ kind: 'attesting', filename, backupFilename });
|
||||
return new Promise<boolean>((resolve) => {
|
||||
attestResolve = resolve;
|
||||
});
|
||||
return awaitAttestation();
|
||||
},
|
||||
});
|
||||
setImportState({ kind: 'done', filename, created: outcome.created, plan: outcome.plan });
|
||||
@@ -127,7 +97,15 @@
|
||||
setImportState({ kind: 'cancelled', filename, created: err.done });
|
||||
return;
|
||||
}
|
||||
setImportState({ kind: 'error', filename, ...describeError(err) });
|
||||
setImportState({
|
||||
kind: 'error',
|
||||
filename,
|
||||
...describeError(err),
|
||||
// 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 saying nothing.
|
||||
...(options.mode === 'replace' && !(err instanceof BmBackupError) && { backupFilename }),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +142,7 @@
|
||||
duplicates={session.duplicates}
|
||||
onchange={(patch) => setImportOptions(patch)}
|
||||
/>
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
<Button
|
||||
variant={options.mode === 'replace' ? 'danger' : 'primary'}
|
||||
onclick={() => void start(session.filename)}
|
||||
@@ -179,8 +158,10 @@
|
||||
thing standing between the user and an unbacked-up deletion. -->
|
||||
<Callout tone="danger">{t('import.attest', { name: session.backupFilename })}</Callout>
|
||||
<div class="actions">
|
||||
<Button variant="danger" onclick={() => answerAttest(true)}>{t('import.attestConfirm')}</Button>
|
||||
<Button onclick={() => answerAttest(false)}>{t('common.cancel')}</Button>
|
||||
<Button variant="danger" onclick={() => answerAttestation(true)}>
|
||||
{t('import.attestConfirm')}
|
||||
</Button>
|
||||
<Button onclick={() => answerAttestation(false)}>{t('common.cancel')}</Button>
|
||||
</div>
|
||||
{:else if session.kind === 'clearing'}
|
||||
<Callout tone="danger">{t('import.clearing')}</Callout>
|
||||
@@ -206,6 +187,7 @@
|
||||
inFile: num(session.plan.stats.skippedInFile),
|
||||
})}
|
||||
</p>
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
<div class="actions">
|
||||
<Button variant="primary" onclick={() => navigate('edit')}>{t('import.openEdit')}</Button>
|
||||
<Button
|
||||
@@ -214,6 +196,7 @@
|
||||
</div>
|
||||
{:else if session.kind === 'cancelled'}
|
||||
<Callout tone="warn">{t('import.cancelledSummary', { created: num(session.created) })}</Callout>
|
||||
<p class="muted">{t('import.dateNotice')}</p>
|
||||
<Button
|
||||
onclick={resetImport}>{t('import.another')}</Button
|
||||
>
|
||||
@@ -222,6 +205,15 @@
|
||||
{#if session.detail !== undefined}
|
||||
<pre class="detail">{session.detail}</pre>
|
||||
{/if}
|
||||
{#if session.created !== undefined && session.created > 0}
|
||||
<p class="muted">{t('import.partialCreated', { created: num(session.created) })}</p>
|
||||
{/if}
|
||||
{#if session.removed !== undefined && session.removed > 0}
|
||||
<Callout tone="danger">{t('import.partialCleared', { removed: num(session.removed) })}</Callout>
|
||||
{/if}
|
||||
{#if session.backupFilename !== undefined}
|
||||
<p class="muted">{t('import.backupHint', { name: session.backupFilename })}</p>
|
||||
{/if}
|
||||
<Button
|
||||
onclick={resetImport}>{t('import.another')}</Button
|
||||
>
|
||||
|
||||
@@ -45,6 +45,17 @@ const dict = {
|
||||
doneSummary: 'Done — {created} items created.',
|
||||
skipped: 'Skipped {existing} already in this browser and {inFile} repeated in the file.',
|
||||
cancelledSummary: 'Cancelled — {created} items were already created and were left in place.',
|
||||
// docs/05 §6 and docs/00 §8 both require saying this, and nothing did.
|
||||
// chrome.bookmarks.create takes no dateAdded, so every imported bookmark is
|
||||
// stamped with the import time — indistinguishable from corruption to
|
||||
// someone migrating a decade-old archive.
|
||||
dateNotice:
|
||||
'Imported bookmarks are dated today. Chrome does not let an extension set a bookmark’s original date — your exported files keep the real ones.',
|
||||
partialCreated:
|
||||
'{created} items had already been created before this failed, and were left in place.',
|
||||
partialCleared:
|
||||
'{removed} top-level items had already been deleted before this failed. Restore them from your backup.',
|
||||
backupHint: 'Your safety backup was saved as {name}. Restore it by importing that JSON file.',
|
||||
openEdit: 'Open Edit tab',
|
||||
another: 'Import another file',
|
||||
dedupe: 'Skip duplicates already in this browser ({n} found)',
|
||||
@@ -256,6 +267,10 @@ const dict = {
|
||||
BACKUP_CANCELLED: 'You cancelled the safety backup, so nothing was deleted.',
|
||||
BACKUP_WRITE_FAILED: 'The safety backup could not be saved, so nothing was deleted.',
|
||||
BROWSER: 'The browser refused a bookmark operation.',
|
||||
NO_WRITABLE_ROOTS:
|
||||
'This browser profile has no bookmark folder BookmarkMagic is allowed to write to. Bookmarks managed by an organisation cannot be changed.',
|
||||
PARTIAL_WRITE: 'The browser stopped accepting bookmarks part-way through the import.',
|
||||
PARTIAL_CLEAR: 'The browser stopped part-way through replacing your bookmarks.',
|
||||
UNKNOWN: 'Something went wrong.',
|
||||
},
|
||||
};
|
||||
|
||||
@@ -38,6 +38,13 @@ export default {
|
||||
skipped:
|
||||
'このブラウザに既にある {existing} 件と、ファイル内で重複する {inFile} 件をスキップしました。',
|
||||
cancelledSummary: 'キャンセルしました — 既に作成された {created} 件はそのまま残されています。',
|
||||
dateNotice:
|
||||
'インポートしたブックマークの日付は本日になります。拡張機能がブックマークの元の作成日を設定することを Chrome が許可していないためです。エクスポートしたファイルには本来の日付が残ります。',
|
||||
partialCreated: 'エラーが発生する前に作成された {created} 件はそのまま残されています。',
|
||||
partialCleared:
|
||||
'エラーが発生する前に、最上位の {removed} 件が既に削除されています。バックアップから復元してください。',
|
||||
backupHint:
|
||||
'安全のためのバックアップは {name} として保存されています。その JSON ファイルをインポートすると復元できます。',
|
||||
openEdit: '編集タブを開く',
|
||||
another: '別のファイルをインポート',
|
||||
dedupe: 'このブラウザに既にあるものをスキップする({n} 件見つかりました)',
|
||||
@@ -241,6 +248,10 @@ export default {
|
||||
BACKUP_CANCELLED: 'バックアップがキャンセルされたため、何も削除していません。',
|
||||
BACKUP_WRITE_FAILED: 'バックアップを保存できなかったため、何も削除していません。',
|
||||
BROWSER: 'ブラウザがブックマークの操作を拒否しました。',
|
||||
NO_WRITABLE_ROOTS:
|
||||
'このブラウザプロファイルには、BookmarkMagic が書き込みを許可されているブックマークフォルダがありません。組織によって管理されているブックマークは変更できません。',
|
||||
PARTIAL_WRITE: 'インポートの途中で、ブラウザがブックマークの受け付けを停止しました。',
|
||||
PARTIAL_CLEAR: 'ブックマークを置き換えている途中で、ブラウザが停止しました。',
|
||||
UNKNOWN: '問題が発生しました。',
|
||||
},
|
||||
} satisfies Dict;
|
||||
@@ -33,6 +33,13 @@ export default {
|
||||
doneSummary: 'Hoàn tất — đã tạo {created} mục.',
|
||||
skipped: 'Đã bỏ qua {existing} mục đã có trong trình duyệt và {inFile} mục lặp trong tệp.',
|
||||
cancelledSummary: 'Đã hủy — {created} mục đã được tạo trước đó và vẫn được giữ lại.',
|
||||
dateNotice:
|
||||
'Bookmark được nhập vào sẽ mang ngày hôm nay. Chrome không cho phép tiện ích đặt lại ngày tạo gốc của bookmark — các tệp bạn xuất ra vẫn giữ ngày thật.',
|
||||
partialCreated: '{created} mục đã được tạo trước khi lỗi xảy ra và vẫn được giữ lại.',
|
||||
partialCleared:
|
||||
'{removed} mục ở cấp cao nhất đã bị xóa trước khi lỗi xảy ra. Hãy khôi phục chúng từ tệp sao lưu của bạn.',
|
||||
backupHint:
|
||||
'Tệp sao lưu an toàn đã được lưu với tên {name}. Nhập lại tệp JSON đó để khôi phục.',
|
||||
openEdit: 'Mở thẻ Chỉnh sửa',
|
||||
another: 'Nhập tệp khác',
|
||||
dedupe: 'Bỏ qua mục đã có trong trình duyệt này (tìm thấy {n})',
|
||||
@@ -239,6 +246,10 @@ export default {
|
||||
BACKUP_CANCELLED: 'Bạn đã hủy bản sao lưu, nên không có gì bị xóa.',
|
||||
BACKUP_WRITE_FAILED: 'Không thể lưu bản sao lưu, nên không có gì bị xóa.',
|
||||
BROWSER: 'Trình duyệt đã từ chối một thao tác bookmark.',
|
||||
NO_WRITABLE_ROOTS:
|
||||
'Hồ sơ trình duyệt này không có thư mục bookmark nào mà BookmarkMagic được phép ghi vào. Bookmark do tổ chức quản lý thì không thể thay đổi.',
|
||||
PARTIAL_WRITE: 'Trình duyệt đã ngừng nhận bookmark khi quá trình nhập đang diễn ra.',
|
||||
PARTIAL_CLEAR: 'Trình duyệt đã dừng lại giữa chừng khi đang thay thế bookmark của bạn.',
|
||||
UNKNOWN: 'Đã xảy ra lỗi.',
|
||||
},
|
||||
} satisfies Dict;
|
||||
@@ -40,7 +40,31 @@ export type ImportState =
|
||||
* was active when the error happened, so switching language left the error
|
||||
* message behind in the old one.
|
||||
*/
|
||||
| { kind: 'error'; filename: string; messageKey: string; detail: string | undefined };
|
||||
| {
|
||||
kind: 'error';
|
||||
filename: string;
|
||||
messageKey: string;
|
||||
/**
|
||||
* Raw technical text, absent when there is none.
|
||||
*
|
||||
* Optional rather than `string | undefined` so it matches `DescribedError`
|
||||
* exactly — under `exactOptionalPropertyTypes` those are different types,
|
||||
* and a spread of one into the other is a compile error.
|
||||
*/
|
||||
detail?: string | undefined;
|
||||
/** Nodes created before a partial failure, when the failure knows. */
|
||||
created?: number;
|
||||
/** Root children deleted before a partial failure, when it knows. */
|
||||
removed?: number;
|
||||
/**
|
||||
* The safety backup's filename, on a Replace that got past the backup.
|
||||
*
|
||||
* Carried onto the failure deliberately: `attesting` knew it and `error`
|
||||
* used to throw it away, so the one string that lets a user restore a
|
||||
* half-deleted tree was the one thing not on screen.
|
||||
*/
|
||||
backupFilename?: string;
|
||||
};
|
||||
|
||||
let state = $state<ImportState>({ kind: 'idle' });
|
||||
let options = $state<ImportOptionsState>({ mode: 'new-folder', dedupe: true });
|
||||
@@ -102,7 +126,41 @@ export function cancelWrite(): void {
|
||||
controller?.abort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolver for the fallback-backup attestation — held HERE, not in `ImportTab`.
|
||||
*
|
||||
* As a component-local `let` it died with the component. Pressing Back during
|
||||
* `attesting` unmounted the tab, 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.
|
||||
*/
|
||||
let attestResolve: ((confirmed: boolean) => void) | undefined;
|
||||
|
||||
/** Wait for the user to confirm they have the fallback backup. */
|
||||
export function awaitAttestation(): Promise<boolean> {
|
||||
// A resolver that is still live fails CLOSED. An unanswered attestation is
|
||||
// not consent, and this is the gate in front of deleting every bookmark.
|
||||
attestResolve?.(false);
|
||||
return new Promise<boolean>((resolve) => {
|
||||
attestResolve = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
export function answerAttestation(confirmed: boolean): void {
|
||||
attestResolve?.(confirmed);
|
||||
attestResolve = undefined;
|
||||
}
|
||||
|
||||
export function hasPendingAttestation(): boolean {
|
||||
return attestResolve !== undefined;
|
||||
}
|
||||
|
||||
export function resetImport(): void {
|
||||
// Before clearing state, not after: otherwise "Import another file" during an
|
||||
// attestation moves the deadlock out of a component and into this store,
|
||||
// where nothing renders it and nobody would find it.
|
||||
answerAttestation(false);
|
||||
controller = undefined;
|
||||
prepared = undefined;
|
||||
state = { kind: 'idle' };
|
||||
|
||||
@@ -22,19 +22,61 @@ export function getRoute(): Route {
|
||||
return current;
|
||||
}
|
||||
|
||||
export function navigate(route: Route): void {
|
||||
current = route;
|
||||
if (globalThis.location !== undefined) globalThis.location.hash = `#${route}`;
|
||||
/**
|
||||
* Refuses to leave while work would be orphaned. Injected rather than imported,
|
||||
* so this module keeps knowing nothing about the import session.
|
||||
*/
|
||||
export interface RoutingOptions {
|
||||
/** True while leaving the current route would strand in-flight work. */
|
||||
isBlocked?: () => boolean;
|
||||
/** Called when a navigation was refused, so the UI can explain itself. */
|
||||
onBlocked?: () => void;
|
||||
}
|
||||
|
||||
/** Sync from the URL and follow it. Returns a cleanup function. */
|
||||
export function startRouting(): () => void {
|
||||
let blocked: (() => boolean) | undefined;
|
||||
|
||||
/**
|
||||
* Navigate, unless a write is in flight.
|
||||
*
|
||||
* @returns whether the navigation actually happened. Callers that ignore this
|
||||
* turn a refusal into a button that appears to do nothing.
|
||||
*/
|
||||
export function navigate(route: Route): boolean {
|
||||
if (route !== current && blocked?.() === true) return false;
|
||||
current = route;
|
||||
if (globalThis.location !== undefined) globalThis.location.hash = `#${route}`;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync from the URL and follow it. Returns a cleanup function.
|
||||
*
|
||||
* The `hashchange` listener is also the thing that made Back dangerous. Every
|
||||
* `navigate()` writes a history entry, so during an import the user could press
|
||||
* Back, unmount `ImportTab`, and strand the write it was driving — the same
|
||||
* dead end Phase 4 closed for the footer and the tab bar, reachable through a
|
||||
* door nobody had guarded.
|
||||
*/
|
||||
export function startRouting(options: RoutingOptions = {}): () => void {
|
||||
current = parse(globalThis.location?.hash ?? '');
|
||||
blocked = options.isBlocked;
|
||||
|
||||
const onHashChange = (): void => {
|
||||
current = parse(globalThis.location.hash);
|
||||
const next = parse(globalThis.location.hash);
|
||||
// Terminates the restore below: putting the hash back fires this handler a
|
||||
// second time, and that time the parsed route already equals `current`.
|
||||
if (next === current) return;
|
||||
if (options.isBlocked?.() === true) {
|
||||
globalThis.location.hash = `#${current}`;
|
||||
options.onBlocked?.();
|
||||
return;
|
||||
}
|
||||
current = next;
|
||||
};
|
||||
|
||||
globalThis.addEventListener('hashchange', onHashChange);
|
||||
return () => {
|
||||
globalThis.removeEventListener('hashchange', onHashChange);
|
||||
blocked = undefined;
|
||||
};
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import type { LiveNode } from '@/lib/browser/bookmarks';
|
||||
export interface FakeBookmarksOptions {
|
||||
/** Throw on the Nth create (1-based), to test partial-failure reporting. */
|
||||
failOnCreate?: number;
|
||||
/** Throw on the Nth removeTree (1-based) — the Replace path's equivalent. */
|
||||
failOnRemoveTree?: number;
|
||||
}
|
||||
|
||||
export class FakeBookmarks {
|
||||
@@ -18,6 +20,7 @@ export class FakeBookmarks {
|
||||
private readonly nodes = new Map<string, LiveNode>();
|
||||
private nextId = 100;
|
||||
private createCount = 0;
|
||||
private removeCount = 0;
|
||||
// An explicit field, not a constructor parameter property: the latter emits
|
||||
// runtime code and is rejected by `erasableSyntaxOnly` (docs/10 §2).
|
||||
private readonly options: FakeBookmarksOptions;
|
||||
@@ -110,7 +113,11 @@ export class FakeBookmarks {
|
||||
};
|
||||
|
||||
removeTree = async (id: string): Promise<void> => {
|
||||
this.removeCount++;
|
||||
this.calls.push(`removeTree:${id}`);
|
||||
if (this.options.failOnRemoveTree === this.removeCount) {
|
||||
throw new Error(`injected failure on removeTree #${this.removeCount}`);
|
||||
}
|
||||
const node = this.nodes.get(id);
|
||||
if (node === undefined) throw new Error(`no such node: ${id}`);
|
||||
if (node.unmodifiable !== undefined) throw new Error("Can't modify managed bookmarks");
|
||||
|
||||
@@ -151,4 +151,37 @@ describe('clearRoots', () => {
|
||||
});
|
||||
expect(current.countCalls('removeTree')).toBe(0);
|
||||
});
|
||||
|
||||
it('reports how much was already deleted when a removal rejects', async () => {
|
||||
// This is the only path in the product that destroys data. A failure that
|
||||
// says nothing but "the browser refused" leaves the user unable to tell
|
||||
// whether they lost two bookmarks or all of them.
|
||||
current = new FakeBookmarks({ failOnRemoveTree: 3 });
|
||||
for (let i = 0; i < 5; i++) {
|
||||
current.seed('2', { title: `b${i}`, url: `https://e${i}.example/` });
|
||||
}
|
||||
|
||||
const roots = await getRoots();
|
||||
const err = await clearRoots(roots.writable).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toMatchObject({ name: 'BmPartialWrite', phase: 'clearing', done: 2 });
|
||||
});
|
||||
|
||||
it('carries the removed count on an abort too, not a hardcoded zero', async () => {
|
||||
for (let i = 0; i < 4; i++) {
|
||||
current.seed('2', { title: `b${i}`, url: `https://e${i}.example/` });
|
||||
}
|
||||
const controller = new AbortController();
|
||||
let seen = 0;
|
||||
|
||||
const roots = await getRoots();
|
||||
const original = current.removeTree;
|
||||
current.removeTree = async (id: string): Promise<void> => {
|
||||
await original(id);
|
||||
if (++seen === 2) controller.abort();
|
||||
};
|
||||
|
||||
const err = await clearRoots(roots.writable, controller.signal).catch((e: unknown) => e);
|
||||
expect(err).toMatchObject({ name: 'BmAborted', done: 2 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describeError } from '@/lib/browser/describe-error';
|
||||
import {
|
||||
BmAborted,
|
||||
BmBackupError,
|
||||
BmBrowserError,
|
||||
BmEnvError,
|
||||
BmPartialWrite,
|
||||
} from '@/lib/browser/errors';
|
||||
import { BmParseError } from '@/lib/core/model';
|
||||
|
||||
/**
|
||||
* `describeError` — docs/02 §7.
|
||||
*
|
||||
* Two properties matter more than the individual mappings, and both have been
|
||||
* defects in this codebase before:
|
||||
*
|
||||
* - the result is a **key**, never a resolved sentence, because the import
|
||||
* session outlives the component and `t()` is only reactive where it is
|
||||
* called;
|
||||
* - `detail` is *absent* when there is none, not `undefined`. Under
|
||||
* `exactOptionalPropertyTypes` those are different types, and only a runtime
|
||||
* `'detail' in result` check catches the difference.
|
||||
*/
|
||||
describe('describeError', () => {
|
||||
it('maps a parse error to its own code', () => {
|
||||
const result = describeError(new BmParseError('TOO_DEEP', 'nesting deeper than 200 levels'));
|
||||
expect(result.messageKey).toBe('errors.TOO_DEEP');
|
||||
expect(result.detail).toBe('nesting deeper than 200 levels');
|
||||
});
|
||||
|
||||
it('maps a backup error to its own code', () => {
|
||||
const result = describeError(new BmBackupError('BACKUP_CANCELLED'));
|
||||
expect(result.messageKey).toBe('errors.BACKUP_CANCELLED');
|
||||
});
|
||||
|
||||
it('maps a missing writable root to its own key, not to BROWSER', () => {
|
||||
// The browser refused nothing — every root is policy-managed. Reporting a
|
||||
// refusal sends the user looking for a permission problem that is not there.
|
||||
const result = describeError(new BmEnvError('NO_WRITABLE_ROOTS', '1 root(s), none writable'));
|
||||
expect(result.messageKey).toBe('errors.NO_WRITABLE_ROOTS');
|
||||
expect(result.detail).toBe('1 root(s), none writable');
|
||||
});
|
||||
|
||||
it('carries the created count off a partial write', () => {
|
||||
const result = describeError(new BmPartialWrite('writing', 42, new Error('quota')));
|
||||
expect(result.messageKey).toBe('errors.PARTIAL_WRITE');
|
||||
expect(result.created).toBe(42);
|
||||
expect(result.removed).toBeUndefined();
|
||||
expect(result.detail).toBe('quota');
|
||||
});
|
||||
|
||||
it('carries the removed count off a partial clear, and says something different', () => {
|
||||
// "some items were added" and "part of your tree is gone" need different
|
||||
// advice, so the phase picks the sentence rather than a shared one.
|
||||
const result = describeError(new BmPartialWrite('clearing', 7, new Error('boom')));
|
||||
expect(result.messageKey).toBe('errors.PARTIAL_CLEAR');
|
||||
expect(result.removed).toBe(7);
|
||||
expect(result.created).toBeUndefined();
|
||||
});
|
||||
|
||||
it('unwraps a BmBrowserError cause rather than nesting the message', () => {
|
||||
const cause = new BmBrowserError('bookmarks.create', new Error('Invalid URL'));
|
||||
const result = describeError(new BmPartialWrite('writing', 1, cause));
|
||||
expect(result.detail).toBe('Invalid URL');
|
||||
});
|
||||
|
||||
it('maps a raw browser rejection to BROWSER', () => {
|
||||
const result = describeError(new BmBrowserError('bookmarks.move', new Error('nope')));
|
||||
expect(result.messageKey).toBe('errors.BROWSER');
|
||||
expect(result.detail).toBe('nope');
|
||||
});
|
||||
|
||||
it('falls back to UNKNOWN for anything else, including non-Errors', () => {
|
||||
expect(describeError(new Error('plain')).messageKey).toBe('errors.UNKNOWN');
|
||||
expect(describeError('a string').messageKey).toBe('errors.UNKNOWN');
|
||||
expect(describeError(undefined).messageKey).toBe('errors.UNKNOWN');
|
||||
});
|
||||
|
||||
it('omits detail entirely rather than setting it to undefined', () => {
|
||||
const result = describeError('not an Error');
|
||||
expect('detail' in result).toBe(true);
|
||||
expect(result.detail).toBeUndefined();
|
||||
|
||||
// The env-error path uses a conditional spread, so the key is genuinely
|
||||
// absent — this is the assertion that catches a regression to
|
||||
// `detail: undefined`, which the type system alone would let through.
|
||||
const env = describeError(new BmEnvError('NO_WRITABLE_ROOTS'));
|
||||
expect('detail' in env).toBe(false);
|
||||
});
|
||||
|
||||
it('does not claim to describe an abort — cancellation is not a failure', () => {
|
||||
// BmAborted is handled by the caller before it ever reaches here. If that
|
||||
// ever changed, the user's own cancellation would be reported as an error.
|
||||
const result = describeError(new BmAborted(5));
|
||||
expect(result.messageKey).toBe('errors.UNKNOWN');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { BmAborted } from '@/lib/browser/errors';
|
||||
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';
|
||||
@@ -196,19 +196,55 @@ describe('writeTree — abort', () => {
|
||||
});
|
||||
|
||||
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 });
|
||||
const nodes = Array.from({ length: 6 }, (_, i) => ({
|
||||
title: `b${i}`,
|
||||
url: `https://e${i}.example/`,
|
||||
}));
|
||||
|
||||
await expect(
|
||||
writeTree(planOf([{ rootId: '2', nodes }]), { create: fake.create }),
|
||||
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', () => {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
answerAttestation,
|
||||
awaitAttestation,
|
||||
beginWrite,
|
||||
cancelWrite,
|
||||
getImportState,
|
||||
hasPendingAttestation,
|
||||
isWriting,
|
||||
resetImport,
|
||||
setImportState,
|
||||
} from '@/lib/stores/import-session.svelte';
|
||||
|
||||
/**
|
||||
* Import session store — docs/03 §5.
|
||||
*
|
||||
* The attestation half of this file exists because of a real dead end: the
|
||||
* resolver used to be a component-local `let`, so pressing browser Back during
|
||||
* `attesting` 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. Closing the tab was the only way out.
|
||||
*/
|
||||
beforeEach(() => {
|
||||
resetImport();
|
||||
});
|
||||
|
||||
describe('isWriting', () => {
|
||||
it.each([
|
||||
['backing-up', true],
|
||||
['attesting', true],
|
||||
['clearing', true],
|
||||
['writing', true],
|
||||
['idle', false],
|
||||
['validating', false],
|
||||
['parsed', false],
|
||||
['done', false],
|
||||
['cancelled', false],
|
||||
['error', false],
|
||||
])('%s → %s', (kind, expected) => {
|
||||
// Only the shape of `kind` is under test; the rest of each variant is
|
||||
// filled with whatever satisfies the union.
|
||||
const states: Record<string, Parameters<typeof setImportState>[0]> = {
|
||||
idle: { kind: 'idle' },
|
||||
validating: { kind: 'validating', filename: 'f' },
|
||||
parsed: {
|
||||
kind: 'parsed',
|
||||
filename: 'f',
|
||||
result: { roots: [], warnings: [], stats: { bookmarks: 0, folders: 0, maxDepth: 0 } },
|
||||
duplicates: 0,
|
||||
},
|
||||
'backing-up': { kind: 'backing-up', filename: 'f' },
|
||||
attesting: { kind: 'attesting', filename: 'f', backupFilename: 'b.json' },
|
||||
clearing: { kind: 'clearing', filename: 'f' },
|
||||
writing: {
|
||||
kind: 'writing',
|
||||
filename: 'f',
|
||||
progress: { done: 0, total: 1, currentPath: '' },
|
||||
},
|
||||
done: {
|
||||
kind: 'done',
|
||||
filename: 'f',
|
||||
created: 1,
|
||||
plan: {
|
||||
mode: 'new-folder',
|
||||
dedupe: false,
|
||||
segments: [],
|
||||
stats: { toCreate: 0, bookmarkCount: 0, skippedExisting: 0, skippedInFile: 0 },
|
||||
},
|
||||
},
|
||||
cancelled: { kind: 'cancelled', filename: 'f', created: 1 },
|
||||
error: { kind: 'error', filename: 'f', messageKey: 'errors.UNKNOWN' },
|
||||
};
|
||||
const state = states[kind];
|
||||
if (state === undefined) throw new Error(`unmapped kind: ${kind}`);
|
||||
setImportState(state);
|
||||
expect(isWriting()).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('attestation', () => {
|
||||
it('settles true when the user confirms', async () => {
|
||||
const pending = awaitAttestation();
|
||||
expect(hasPendingAttestation()).toBe(true);
|
||||
answerAttestation(true);
|
||||
await expect(pending).resolves.toBe(true);
|
||||
expect(hasPendingAttestation()).toBe(false);
|
||||
});
|
||||
|
||||
it('settles false when the user cancels', async () => {
|
||||
const pending = awaitAttestation();
|
||||
answerAttestation(false);
|
||||
await expect(pending).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('survives the component that started it — the deadlock this replaced', async () => {
|
||||
// The resolver lives in the store, so an unmount and remount of ImportTab
|
||||
// leaves the promise settleable. As a component-local `let` this hung.
|
||||
const pending = awaitAttestation();
|
||||
// …component unmounts and remounts here; nothing in the store changes…
|
||||
expect(hasPendingAttestation()).toBe(true);
|
||||
answerAttestation(true);
|
||||
await expect(pending).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('resetImport settles a pending attestation as NOT confirmed', async () => {
|
||||
// "Import another file" pressed mid-attestation must not leave a resolver
|
||||
// behind — that would move the deadlock from a component, where it is
|
||||
// visible, into a store, where nothing renders it.
|
||||
const pending = awaitAttestation();
|
||||
resetImport();
|
||||
await expect(pending).resolves.toBe(false);
|
||||
expect(hasPendingAttestation()).toBe(false);
|
||||
expect(getImportState().kind).toBe('idle');
|
||||
});
|
||||
|
||||
it('a second attestation settles the first as NOT confirmed, never drops it', async () => {
|
||||
// Failing closed matters here more than anywhere: this promise is the last
|
||||
// gate before deleting every bookmark the user has.
|
||||
const first = awaitAttestation();
|
||||
const second = awaitAttestation();
|
||||
await expect(first).resolves.toBe(false);
|
||||
|
||||
answerAttestation(true);
|
||||
await expect(second).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it('answering with nothing pending is a no-op, not a throw', () => {
|
||||
expect(() => answerAttestation(true)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('write control', () => {
|
||||
it('beginWrite hands out a signal that cancelWrite aborts', () => {
|
||||
const signal = beginWrite();
|
||||
expect(signal.aborted).toBe(false);
|
||||
cancelWrite();
|
||||
expect(signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it('each write gets a fresh signal, so a past cancel cannot poison the next', () => {
|
||||
const first = beginWrite();
|
||||
cancelWrite();
|
||||
const second = beginWrite();
|
||||
expect(first.aborted).toBe(true);
|
||||
expect(second.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -52,3 +52,92 @@ describe('route store', () => {
|
||||
expect(getRoute()).toBe('about');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The guard exists because browser Back was the one route out of #import that
|
||||
* nothing checked. During the backup attestation it unmounted `ImportTab` and
|
||||
* stranded the promise `runImport` was awaiting — a Manager that could only be
|
||||
* escaped by closing the tab.
|
||||
*/
|
||||
describe('route store — blocked while a write is in flight', () => {
|
||||
const settle = (): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(() => setTimeout(() => resolve()));
|
||||
});
|
||||
|
||||
it('refuses an external hashchange and puts the hash back', async () => {
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
globalThis.location.hash = '#export';
|
||||
await settle();
|
||||
|
||||
expect(getRoute()).toBe('import');
|
||||
expect(globalThis.location.hash).toBe('#import');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('restoring the hash does not recurse', async () => {
|
||||
// Putting the hash back fires `hashchange` a second time. Without the
|
||||
// `next === current` early return that is an infinite loop, in a released
|
||||
// extension, on the one path a panicking user is most likely to take.
|
||||
let blockedCalls = 0;
|
||||
const stop = startRouting({
|
||||
isBlocked: () => {
|
||||
blockedCalls++;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
globalThis.location.hash = '#edit';
|
||||
await settle();
|
||||
|
||||
expect(blockedCalls).toBe(1);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('reports the refusal exactly once, so the UI can explain itself', async () => {
|
||||
let notified = 0;
|
||||
const stop = startRouting({ isBlocked: () => true, onBlocked: () => notified++ });
|
||||
|
||||
globalThis.location.hash = '#about';
|
||||
await settle();
|
||||
|
||||
expect(notified).toBe(1);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('navigate() returns false and writes nothing while blocked', () => {
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
expect(navigate('export')).toBe(false);
|
||||
expect(getRoute()).toBe('import');
|
||||
expect(globalThis.location.hash === '#export').toBe(false);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('navigating to the route you are already on is never refused', () => {
|
||||
// Otherwise ImportTab could not re-assert its own route mid-write.
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
expect(navigate('import')).toBe(true);
|
||||
stop();
|
||||
});
|
||||
|
||||
it('follows again as soon as the write finishes', async () => {
|
||||
let writing = true;
|
||||
const stop = startRouting({ isBlocked: () => writing });
|
||||
|
||||
globalThis.location.hash = '#edit';
|
||||
await settle();
|
||||
expect(getRoute()).toBe('import');
|
||||
|
||||
writing = false;
|
||||
globalThis.location.hash = '#edit';
|
||||
await settle();
|
||||
expect(getRoute()).toBe('edit');
|
||||
stop();
|
||||
});
|
||||
|
||||
it('leaves the guard behind on cleanup, so a stale predicate cannot lock the app', () => {
|
||||
const stop = startRouting({ isBlocked: () => true });
|
||||
stop();
|
||||
expect(navigate('export')).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user