From 215f51f63fa03912f3c96595e1fe6ff91ba55cb1 Mon Sep 17 00:00:00 2001 From: raaneem Date: Tue, 28 Jul 2026 16:45:55 +0500 Subject: [PATCH] feat(release): prepare 1.0.4 - remove runtime performance admission and add diagnostics - improve reader and Cloud browser lifecycle and mobile UX - restore broad Markdown PDF viewer compatibility --- CHANGELOG.md | 11 + benchmarks/README.md | 37 ++- benchmarks/harness.ts | 58 ++++ benchmarks/run.ts | 166 ++++++++++- benchmarks/scenarios.ts | 188 ++++++++++-- manifest.json | 2 +- package.json | 2 +- src/export/markdown-pdf.ts | 6 +- src/main.ts | 135 +++++++-- src/note/notebook-service.ts | 300 ++++--------------- src/ocr/api-ocr.ts | 32 --- src/onboarding/diagnostics.ts | 10 + src/onboarding/performance-diagnostics.ts | 289 +++++++++++++++++++ src/sync/instance-state.ts | 9 + src/sync/sync-service.ts | 19 +- src/ui/cloud-browser-presentation.ts | 40 +++ src/ui/folder-picker-modal.ts | 336 ++++++++++++++++++---- src/viewer/fixed-page-embed.ts | 14 +- src/viewer/note-reader.ts | 152 +++------- src/viewer/note-view.ts | 127 ++++++-- src/viewer/notebook-embed.ts | 20 +- src/viewer/pager-motion.ts | 6 +- src/viewer/reader-toolbar.ts | 20 ++ styles.css | 315 ++++++++++++++++---- tests/api-ocr.test.ts | 18 +- tests/cloud-browser-presentation.test.ts | 29 ++ tests/diagnostics.test.ts | 44 +++ tests/fixed-page-embed.test.ts | 18 +- tests/instance-state.test.ts | 13 +- tests/markdown-pdf.test.ts | 4 +- tests/notebook-embed.test.ts | 6 +- tests/notebook-service.test.ts | 267 ++++++++--------- tests/pager-motion.test.ts | 18 +- tests/performance-diagnostics.test.ts | 162 +++++++++++ tests/performance-harness.test.ts | 103 ++++++- tests/reader-toolbar.test.ts | 39 +++ tests/submission-polish.test.ts | 34 +++ tests/sync-service.test.ts | 1 - tests/worker-ownership-lifecycle.test.ts | 13 +- versions.json | 3 +- 40 files changed, 2281 insertions(+), 785 deletions(-) create mode 100644 src/onboarding/performance-diagnostics.ts create mode 100644 src/ui/cloud-browser-presentation.ts create mode 100644 tests/cloud-browser-presentation.test.ts create mode 100644 tests/performance-diagnostics.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index db9c0bb..734e58c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ All notable changes to Supernote Cloud Sync are documented here. The project uses Semantic Versioning. +## 1.0.4 - 2026-07-28 + +- Let large notebooks open beyond benchmark targets and add privacy-safe + performance diagnostics and retry guidance. +- Improve mobile and desktop Cloud browsing with safe-area-aware layouts, + animated transitions, and loading feedback. +- Suspend inactive readers, refine notebook controls, and add desktop toolbar + zoom actions while preserving mobile gestures. +- Restore complete embedded fonts so Markdown PDFs render correctly in Supernote + Partner and other PDF viewers. + ## 1.0.3 - 2026-07-28 - Add Ko-fi support links to the README and Obsidian plugin metadata. diff --git a/benchmarks/README.md b/benchmarks/README.md index 24178e0..3099f91 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -1,7 +1,9 @@ # Performance and quality harness The harness gives each performance ticket a stable workload, JSON schema, and -budget result before optimization begins. Run commands from `plugin/`. +Performance budget result before optimization begins. These budgets are +benchmark and CI regression evidence; they never authorize production code to +reject a user operation. Run commands from `plugin/`. ## Quality gate @@ -24,9 +26,11 @@ pnpm run build:bundle pnpm perf -- --record --output benchmarks/results/local.json ``` -Without `--record`, a failed budget makes the command exit nonzero. A recorded -run still writes every pass/fail result but exits successfully so an existing -baseline can be captured. Check the failure path independently: +Legacy absolute targets remain visible as informational migration evidence, but +they do not fail the command or control production behavior. A command fails +only for the harness self-test or a matching-baseline regression beyond the +explicit tolerance. A recorded run writes the evidence and exits successfully so +a baseline can be reviewed. Check the harness failure path independently: ```sh pnpm perf -- --profile smoke --scenario run-log-streaming --force-budget-failure @@ -37,6 +41,7 @@ Run one or more scenarios with `--scenario`: ```sh pnpm perf -- --record --scenario cold-activation pnpm perf -- --record --scenario page-rendering,viewer-interaction +pnpm perf -- --record --scenario notebook-opening,settled-viewing,page-navigation,page-grid,concurrent-notebooks,notebook-cleanup pnpm perf -- --record --scenario run-log-streaming pnpm perf -- --record --scenario writable-sync-memory pnpm perf -- --record --scenario export-preparation @@ -58,10 +63,32 @@ Label mobile evidence explicitly: pnpm perf -- --record --platform mobile --device iphone-15-pro ``` +The Node runner labels `--platform mobile` as a `desktop-mobile-simulation`. It +is useful for checking the mobile concurrency and workload contract, but it is +not physical-device evidence. Record actual iOS or Android Obsidian measurements +separately rather than relabelling a desktop run. + The runner identifies the selected desktop/mobile contract, device label, OS, architecture, CPU, memory, Node version, plugin/Obsidian versions, Git commit, and dirty state. Each scenario reports workload details, timing summaries, long -tasks over 50 ms, memory deltas, counters, and individual budget decisions. +tasks over 50 ms, memory deltas, counters, informational legacy target +comparisons, and a normalized evidence summary with peak, settled, +responsiveness, and cleanup values. Page rendering reports opening burst, +settled viewing, and three-visible-notebook workloads separately. + +Compare a run only with a reviewed result from the same device, platform +contract, and workload profile: + +```sh +pnpm perf -- --device local-reference --profile standard \ + --baseline benchmarks/baselines/reviewed-local-standard.json \ + --tolerance 0.20 +``` + +The runner rejects mismatched baseline identities. A matching metric that +regresses beyond the explicit tolerance fails the benchmark command unless +`--record` is present. `--record` is for collecting evidence, not waiving a CI +regression. ## Fixtures and privacy diff --git a/benchmarks/harness.ts b/benchmarks/harness.ts index 03016dd..0472986 100644 --- a/benchmarks/harness.ts +++ b/benchmarks/harness.ts @@ -47,6 +47,64 @@ export interface ScenarioResult passed: boolean; } +export interface ScenarioBaseline { + readonly name: string; + readonly metrics: Readonly>; +} + +export interface RegressionResult { + readonly metric: string; + readonly baseline: number; + readonly actual: number; + readonly toleranceFraction: number; + readonly limit: number; + readonly passed: boolean; +} + +export const regressionGatePassed = ( + baselineProvided: boolean, + comparisons: readonly RegressionResult[], + forceFailure = false, +): boolean => + !forceFailure && + (!baselineProvided || comparisons.every((comparison) => comparison.passed)); + +export const compareScenarioToBaseline = ( + scenario: Pick, + baseline: ScenarioBaseline, + toleranceFraction: number, +): RegressionResult[] => { + if (scenario.name !== baseline.name) { + throw new Error( + `Cannot compare scenario ${scenario.name} with baseline ${baseline.name}`, + ); + } + if (!Number.isFinite(toleranceFraction) || toleranceFraction < 0) { + throw new Error("Regression tolerance must be a nonnegative number"); + } + return Object.entries(baseline.metrics).flatMap( + ([metric, baselineValue]): RegressionResult[] => { + const actual = scenario.metrics[metric]; + if (actual === undefined) { + throw new Error( + `Scenario ${scenario.name} did not report baseline metric ${metric}`, + ); + } + const limit = baselineValue * (1 + toleranceFraction); + return [ + { + metric, + baseline: baselineValue, + actual, + toleranceFraction, + limit, + passed: actual <= limit, + }, + ]; + }, + ); +}; + export const percentile = ( samples: readonly number[], percentileValue: number, diff --git a/benchmarks/run.ts b/benchmarks/run.ts index 15681f8..5c8ab72 100644 --- a/benchmarks/run.ts +++ b/benchmarks/run.ts @@ -7,13 +7,15 @@ import { release, totalmem, } from "node:os"; -import { dirname, resolve } from "node:path"; +import { basename, dirname, resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { type BenchmarkPlatform, type BenchmarkProfile, + compareScenarioToBaseline, evaluateScenario, + regressionGatePassed, roundResult, type ScenarioResult, } from "./harness"; @@ -26,6 +28,7 @@ import { } from "./workloads"; interface CliOptions { + baseline?: string; device: string; forceBudgetFailure: boolean; note?: string; @@ -34,6 +37,20 @@ interface CliOptions { profile: BenchmarkProfile; record: boolean; scenarios: ScenarioName[]; + tolerance: number; +} + +interface BaselineReport { + environment: { + device: string; + platform: BenchmarkPlatform; + }; + profile: BenchmarkProfile; + scenarios: Array<{ + name: string; + workload: Record; + metrics: Record; + }>; } const pluginRoot = resolve(import.meta.dirname, ".."); @@ -73,6 +90,7 @@ export const parseArguments = (arguments_: readonly string[]): CliOptions => { profile: "standard", record: false, scenarios: [...scenarioNames], + tolerance: 0.2, }; for (let index = 0; index < arguments_.length; index += 1) { const argument = arguments_[index]!; @@ -83,6 +101,10 @@ export const parseArguments = (arguments_: readonly string[]): CliOptions => { options.device = readValue(arguments_, index, argument); index += 1; break; + case "--baseline": + options.baseline = resolve(readValue(arguments_, index, argument)); + index += 1; + break; case "--force-budget-failure": options.forceBudgetFailure = true; break; @@ -125,6 +147,15 @@ export const parseArguments = (arguments_: readonly string[]): CliOptions => { ); index += 1; break; + case "--tolerance": { + const value = Number(readValue(arguments_, index, argument)); + if (!Number.isFinite(value) || value < 0) { + throw new Error("--tolerance must be a nonnegative number"); + } + options.tolerance = value; + index += 1; + break; + } default: throw new Error(`Unknown benchmark argument: ${argument}`); } @@ -132,9 +163,44 @@ export const parseArguments = (arguments_: readonly string[]): CliOptions => { if (options.note && !existsSync(options.note)) { throw new Error("Private benchmark note does not exist"); } + if (options.baseline && !existsSync(options.baseline)) { + throw new Error("Benchmark baseline does not exist"); + } return options; }; +export const validateBaselineIdentity = ( + options: Pick, + baseline: BaselineReport, +): void => { + if ( + baseline.environment.device !== options.device || + baseline.environment.platform !== options.platform || + baseline.profile !== options.profile + ) { + throw new Error( + "Benchmark baseline must match device, platform contract, and workload profile", + ); + } +}; + +export const validateBaselineWorkload = ( + current: { + name: string; + workload: Record; + }, + baseline: BaselineReport["scenarios"][number], +): void => { + if ( + current.name !== baseline.name || + JSON.stringify(current.workload) !== JSON.stringify(baseline.workload) + ) { + throw new Error( + `Benchmark baseline workload does not match scenario ${current.name}`, + ); + } +}; + const git = (...arguments_: string[]): string => { const result = spawnSync("git", arguments_, { cwd: pluginRoot, @@ -152,6 +218,12 @@ const obsidianManifest = JSON.parse( const main = async (): Promise => { const options = parseArguments(process.argv.slice(2)); + const baseline = options.baseline + ? (JSON.parse(readFileSync(options.baseline, "utf8")) as BaselineReport) + : null; + if (baseline) { + validateBaselineIdentity(options, baseline); + } if ( options.scenarios.includes("cold-activation") && !existsSync(resolve(pluginRoot, "main.js")) @@ -174,8 +246,35 @@ const main = async (): Promise => { ), ); } + const scenarioComparisons = new Map( + scenarios.map((scenario) => { + const matchingBaseline = baseline?.scenarios.find( + (candidate) => candidate.name === scenario.name, + ); + if (baseline && !matchingBaseline) { + throw new Error( + `Matching baseline does not include scenario ${scenario.name}`, + ); + } + if (matchingBaseline) { + validateBaselineWorkload(scenario, matchingBaseline); + } + const regressions = matchingBaseline + ? compareScenarioToBaseline( + scenario, + matchingBaseline, + options.tolerance, + ) + : []; + return [scenario.name, regressions] as const; + }), + ); + const evidenceKind = + options.platform === "mobile" + ? "desktop-mobile-simulation" + : "native-desktop"; const report = roundResult({ - schemaVersion: 1, + schemaVersion: 2, generatedAt: new Date().toISOString(), environment: { architecture: arch(), @@ -191,6 +290,7 @@ const main = async (): Promise => { packageVersion: packageManifest.version, platform: options.platform, totalMemoryBytes: totalmem(), + evidenceKind, }, profile: options.profile, referenceWorkloads: { @@ -199,17 +299,59 @@ const main = async (): Promise => { syncFiles: REFERENCE_SYNC_FILES, syncTotalBytes: REFERENCE_SYNC_BYTES, }, - scenarios: scenarios.map(({ timings, ...scenario }) => ({ - ...scenario, - timings: { - maxMs: timings.maxMs, - p50Ms: timings.p50Ms, - p95Ms: timings.p95Ms, - sampleCount: timings.samplesMs.length, - totalMs: timings.samplesMs.reduce((total, sample) => total + sample, 0), + scenarios: scenarios.map( + ({ timings, budgets, passed: _passed, ...scenario }) => { + const regressions = scenarioComparisons.get(scenario.name) ?? []; + return { + ...scenario, + informationalTargets: budgets.map(({ passed, ...target }) => ({ + ...target, + withinTarget: passed, + })), + passed: regressionGatePassed(baseline !== null, regressions), + evidence: { + scenario: scenario.name, + executionKind: evidenceKind, + platformContract: options.platform, + device: options.device, + runtime: `${operatingSystem()} ${release()}; ${process.version}`, + peakResourceBytes: Math.max( + scenario.metrics.peakResourceBytes ?? 0, + scenario.memory.peakWorkingBytes, + scenario.metrics.trackedRenderBytes ?? 0, + scenario.metrics.peakWorkingBytes ?? 0, + ), + settledResourceBytes: + scenario.metrics.settledResourceBytes ?? + scenario.metrics.settledViewingRetainedBytes ?? + scenario.memory.retainedBytes, + responsivenessP95Ms: timings.p95Ms, + cleanupRetainedBytes: + scenario.metrics.cleanupRetainedBytes ?? + scenario.metrics.releasedRenderBytes ?? + scenario.memory.retainedBytes, + baseline: options.baseline ? basename(options.baseline) : null, + toleranceFraction: options.tolerance, + regressions, + }, + timings: { + maxMs: timings.maxMs, + p50Ms: timings.p50Ms, + p95Ms: timings.p95Ms, + sampleCount: timings.samplesMs.length, + totalMs: timings.samplesMs.reduce( + (total, sample) => total + sample, + 0, + ), + }, + }; }, - })), - passed: scenarios.every((scenario) => scenario.passed), + ), + passed: regressionGatePassed( + baseline !== null, + [...scenarioComparisons.values()].flat(), + options.forceBudgetFailure, + ), }); const json = `${JSON.stringify(report, null, 2)}\n`; if (options.output) { diff --git a/benchmarks/scenarios.ts b/benchmarks/scenarios.ts index 4d6a48b..42ed483 100644 --- a/benchmarks/scenarios.ts +++ b/benchmarks/scenarios.ts @@ -13,17 +13,11 @@ import { decodeEmbeddedFont } from "../src/export/font-codec"; import { PdfLibExporter } from "../src/export/pdf-export"; import { encodeOpaqueNotebookPng } from "../src/note/notebook-png"; import { rasterizeNotebookPage } from "../src/note/notebook-rasterizer"; -import { - DESKTOP_RENDER_BUDGET_BYTES, - MOBILE_RENDER_BUDGET_BYTES, - NotebookService, -} from "../src/note/notebook-service"; +import { NotebookService } from "../src/note/notebook-service"; import { ApiOcrService, BASE64_CHUNK_BYTES, BASE64_ENCODED_CHUNK_BYTES, - DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT, - MOBILE_DOCUMENT_REQUEST_BYTE_LIMIT, } from "../src/ocr/api-ocr"; import type { NotebookWorkerRequest, @@ -77,6 +71,10 @@ import { import { NodeNotebookImageCodec } from "./node-notebook-image-codec"; const MIB = 1_024 ** 2; +const DESKTOP_RENDER_BUDGET_BYTES = 128 * MIB; +const MOBILE_RENDER_BUDGET_BYTES = 96 * MIB; +const DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT = 64 * MIB; +const MOBILE_DOCUMENT_REQUEST_BYTE_LIMIT = 32 * MIB; interface ScenarioOptions { platform: BenchmarkPlatform; profile: BenchmarkProfile; @@ -164,10 +162,17 @@ const fillHandwritingLikePage = ( interface RenderBudgetObservation { cachedFlipP95Ms: number; cancelledRenders: number; + cleanupMs: number; + concurrentMs: number; + concurrentNotebookRetainedBytes: number; + gridMs: number; maxObservedInFlightRenders: number; maxObservedQueueDepth: number; + openingRetainedBytes: number; + openingMs: number; peakRetainedBytes: number; releasedRetainedBytes: number; + settledViewingRetainedBytes: number; } class RenderBudgetWorker { @@ -308,24 +313,24 @@ const renderBudgetContract = async ( ): Promise => { const service = new NotebookService({ createWorker: () => new RenderBudgetWorker() as unknown as Worker, - resourceBudgetBytes: - options.platform === "mobile" - ? MOBILE_RENDER_BUDGET_BYTES - : DESKTOP_RENDER_BUDGET_BYTES, maxConcurrentRenders: options.platform === "mobile" ? 1 : 2, }); + const openingStartedAt = performance.now(); const lease = await service.open({ path: "generated-budget.note", revision: "benchmark", bytes: new Uint8Array(7 * MIB), }); - let peakRetainedBytes = service.snapshot().retainedBytes; + const openingMs = performance.now() - openingStartedAt; + const openingRetainedBytes = service.snapshot().retainedBytes; + let peakRetainedBytes = openingRetainedBytes; const flipSamples: number[] = []; for (let page = 1; page <= 10; page += 1) { lease.updateView({ visible: true, currentPage: page, gridOpen: false, + canvasBytes: 960 * 1_280 * 4, }); const start = performance.now(); const handles = await Promise.all( @@ -350,6 +355,7 @@ const renderBudgetContract = async ( currentPage: null, gridOpen: true, }); + const gridStartedAt = performance.now(); const thumbnailHandles = await Promise.all( Array.from({ length: 40 }, (_, index) => lease.thumbnailBitmap(index + 1, 240), @@ -358,6 +364,7 @@ const renderBudgetContract = async ( for (const handle of thumbnailHandles) { handle.release(); } + const gridMs = performance.now() - gridStartedAt; peakRetainedBytes = Math.max( peakRetainedBytes, service.snapshot().retainedBytes, @@ -366,7 +373,9 @@ const renderBudgetContract = async ( visible: true, currentPage: 10, gridOpen: false, + canvasBytes: 960 * 1_280 * 4, }); + const settledViewingRetainedBytes = service.snapshot().retainedBytes; lease.updateView({ visible: true, @@ -380,6 +389,7 @@ const renderBudgetContract = async ( visible: true, currentPage: 10, gridOpen: false, + canvasBytes: 960 * 1_280 * 4, }); const staleResults = await Promise.allSettled(staleGrid); for (const result of staleResults) { @@ -388,17 +398,127 @@ const renderBudgetContract = async ( } } const active = service.snapshot(); + const concurrentStartedAt = performance.now(); + const otherLeases = await Promise.all( + [5, 9].map((sourceMib, index) => + service.open({ + path: `concurrent-${index + 1}.note`, + revision: "benchmark", + bytes: new Uint8Array(sourceMib * MIB), + }), + ), + ); + const concurrentHandles = await Promise.all( + otherLeases.map((other, index) => { + other.updateView({ + visible: true, + currentPage: index + 1, + gridOpen: false, + canvasBytes: 960 * 1_280 * 4, + }); + return other.bitmap(index + 1); + }), + ); + for (const handle of concurrentHandles) { + handle.release(); + } + const concurrentNotebookRetainedBytes = service.snapshot().retainedBytes; + const concurrentMs = performance.now() - concurrentStartedAt; + peakRetainedBytes = Math.max( + peakRetainedBytes, + concurrentNotebookRetainedBytes, + ); + for (const other of otherLeases) { + other.close(); + } + const cleanupStartedAt = performance.now(); lease.close(); await Promise.resolve(); const released = service.snapshot(); + const cleanupMs = performance.now() - cleanupStartedAt; service.dispose(); return { cachedFlipP95Ms: summarizeTimings(flipSamples.slice(1)).p95Ms, cancelledRenders: active.cancelledRenders, + cleanupMs, + concurrentMs, + concurrentNotebookRetainedBytes, + gridMs, maxObservedInFlightRenders: active.maxObservedInFlightRenders, maxObservedQueueDepth: active.maxObservedQueueDepth, + openingRetainedBytes, + openingMs, peakRetainedBytes, releasedRetainedBytes: released.retainedBytes, + settledViewingRetainedBytes, + }; +}; + +type NotebookLifecycleScenarioName = + | "notebook-opening" + | "settled-viewing" + | "page-navigation" + | "page-grid" + | "concurrent-notebooks" + | "notebook-cleanup"; + +const notebookLifecycleScenario = async ( + options: ScenarioOptions, + name: NotebookLifecycleScenarioName, +): Promise => { + const resources = await renderBudgetContract(options); + const responsivenessMs = + name === "notebook-opening" + ? resources.openingMs + : name === "page-grid" + ? resources.gridMs + : name === "concurrent-notebooks" + ? resources.concurrentMs + : name === "notebook-cleanup" + ? resources.cleanupMs + : resources.cachedFlipP95Ms; + const settledResourceBytes = + name === "notebook-opening" + ? resources.openingRetainedBytes + : name === "concurrent-notebooks" + ? resources.concurrentNotebookRetainedBytes + : name === "notebook-cleanup" + ? resources.releasedRetainedBytes + : resources.settledViewingRetainedBytes; + const peakResourceBytes = + name === "notebook-opening" + ? resources.openingRetainedBytes + : name === "concurrent-notebooks" + ? resources.concurrentNotebookRetainedBytes + : resources.peakRetainedBytes; + return { + name, + workload: { + fixture: "generated-notebook-service-contract", + notebookPages: REFERENCE_GRID_PAGES, + visibleNotebooks: name === "concurrent-notebooks" ? 3 : 1, + }, + timings: summarizeTimings([responsivenessMs]), + memory: memorySummary( + 0, + peakResourceBytes, + resources.releasedRetainedBytes, + ), + metrics: { + peakResourceBytes, + settledResourceBytes, + responsivenessP95Ms: responsivenessMs, + cleanupRetainedBytes: resources.releasedRetainedBytes, + }, + budgets: [], + counters: { + cancelledRenders: resources.cancelledRenders, + maxObservedInFlightRenders: resources.maxObservedInFlightRenders, + maxObservedQueueDepth: resources.maxObservedQueueDepth, + }, + notes: [ + "Scenario-specific NotebookService evidence; compare only with a matching device and workload baseline.", + ], }; }; @@ -570,6 +690,10 @@ const generatedPageRendering = async ( peakWorkingBytes: memory.peakWorkingBytes, cachedFlipP95Ms: resources.cachedFlipP95Ms, trackedRenderBytes: resources.peakRetainedBytes, + openingRetainedBytes: resources.openingRetainedBytes, + settledViewingRetainedBytes: resources.settledViewingRetainedBytes, + concurrentNotebookRetainedBytes: + resources.concurrentNotebookRetainedBytes, releasedRenderBytes: resources.releasedRetainedBytes, }, budgets: [ @@ -601,6 +725,24 @@ const generatedPageRendering = async ( unit: "bytes", description: "Tracked render resource ceiling", }, + { + metric: "openingRetainedBytes", + limit: platformLimit(options.platform, 128 * MIB, 96 * MIB), + unit: "bytes", + description: "Opening-burst benchmark profile target", + }, + { + metric: "settledViewingRetainedBytes", + limit: platformLimit(options.platform, 128 * MIB, 96 * MIB), + unit: "bytes", + description: "Settled-viewing benchmark profile target", + }, + { + metric: "concurrentNotebookRetainedBytes", + limit: platformLimit(options.platform, 256 * MIB, 192 * MIB), + unit: "bytes", + description: "Three-visible-notebook benchmark profile target", + }, { metric: "releasedRenderBytes", limit: 0, @@ -617,10 +759,14 @@ const generatedPageRendering = async ( counters: { checksum, cancelledRenders: resources.cancelledRenders, + concurrentNotebookRetainedBytes: + resources.concurrentNotebookRetainedBytes, decodedBytes, encodedFixtureBytes: rle.byteLength, maxObservedInFlightRenders: resources.maxObservedInFlightRenders, maxObservedQueueDepth: resources.maxObservedQueueDepth, + openingRetainedBytes: resources.openingRetainedBytes, + settledViewingRetainedBytes: resources.settledViewingRetainedBytes, peakTrackedRenderBytes: resources.peakRetainedBytes, releasedTrackedRenderBytes: resources.releasedRetainedBytes, }, @@ -1586,11 +1732,6 @@ const exportTranscriptionPipeline = async ( apiKey: "benchmark", model: "benchmark-vision", extraInstructions: "", - documentRequestByteLimit: platformLimit( - options.platform, - DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT, - MOBILE_DOCUMENT_REQUEST_BYTE_LIMIT, - ), request: async (request) => { documentRequests += 1; finalRequestBytes = Buffer.byteLength(request.body); @@ -1780,6 +1921,12 @@ const exportTranscriptionPipeline = async ( export const scenarioNames = [ "cold-activation", + "notebook-opening", + "settled-viewing", + "page-navigation", + "page-grid", + "concurrent-notebooks", + "notebook-cleanup", "page-rendering", "viewer-interaction", "run-log-streaming", @@ -1798,6 +1945,13 @@ export const runScenario = async ( switch (name) { case "cold-activation": return startup(options); + case "notebook-opening": + case "settled-viewing": + case "page-navigation": + case "page-grid": + case "concurrent-notebooks": + case "notebook-cleanup": + return notebookLifecycleScenario(options, name); case "page-rendering": return options.privateNote ? privateNoteRendering(options) diff --git a/manifest.json b/manifest.json index 610a612..defd323 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "supernote-cloud-sync", "name": "Supernote Cloud Sync", - "version": "1.0.3", + "version": "1.0.4", "minAppVersion": "1.7.2", "description": "Sync Supernote Cloud, read and embed notebooks, export or transcribe pages, automate changes, and optionally send files back.", "author": "raaneem", diff --git a/package.json b/package.json index f74bdb6..8aff516 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "supernote-cloud-sync", - "version": "1.0.3", + "version": "1.0.4", "description": "Sync Supernote Cloud, read and embed notebooks, export or transcribe pages, automate changes, and optionally send files back", "type": "module", "main": "main.js", diff --git a/src/export/markdown-pdf.ts b/src/export/markdown-pdf.ts index b217f4c..b93f90d 100644 --- a/src/export/markdown-pdf.ts +++ b/src/export/markdown-pdf.ts @@ -330,10 +330,8 @@ export class MarkdownPdfRenderer { async render(markdown: string): Promise { const pdf = await PDFDocument.create(); pdf.registerFontkit(fontkit); - const regular = await pdf.embedFont(this.regularFontBytes, { - subset: true, - }); - const bold = await pdf.embedFont(this.boldFontBytes, { subset: true }); + const regular = await pdf.embedFont(this.regularFontBytes); + const bold = await pdf.embedFont(this.boldFontBytes); const tokens = Lexer.lex(stripFrontmatter(markdown), { gfm: true, }); diff --git a/src/main.ts b/src/main.ts index 82a883b..840fc5d 100644 --- a/src/main.ts +++ b/src/main.ts @@ -30,20 +30,11 @@ import { import type { PdfExporter } from "./export/pdf-export"; import PdfWorker from "./export/pdf.worker.ts?worker&inline"; import { - DESKTOP_RENDER_BUDGET_BYTES, - DESKTOP_TRANSIENT_SYNC_BUDGET_BYTES, - MOBILE_RENDER_BUDGET_BYTES, - MOBILE_TRANSIENT_SYNC_BUDGET_BYTES, NotebookService, type NotebookSessionLease, } from "./note/notebook-service"; import NotebookWorker from "./note/notebook.worker.ts?worker&inline"; -import { - ApiOcrService, - DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT, - MOBILE_DOCUMENT_REQUEST_BYTE_LIMIT, - type ChatCompletionExecutor, -} from "./ocr/api-ocr"; +import { ApiOcrService, type ChatCompletionExecutor } from "./ocr/api-ocr"; import { AgentOcrService } from "./ocr/agent-ocr"; import { CommandOcrService } from "./ocr/command-ocr"; import { ApiModelCatalog, type ApiModelOption } from "./ocr/api-models"; @@ -58,6 +49,13 @@ import { renderDiagnosticsReport, type LastSyncOutcome, } from "./onboarding/diagnostics"; +import { + PerformanceDiagnostics, + performanceFailureCategory, + type ActivePerformanceOperation, + type FinishPerformanceOperation, + type PerformanceOperationKind, +} from "./onboarding/performance-diagnostics"; import { setupPrerequisites as buildSetupPrerequisites, shouldShowSetupNotice, @@ -340,6 +338,8 @@ export default class SupernoteSyncPlugin extends Plugin { private watchHooksRerunRequested = false; private registeredWatchCommands: string[] = []; private lastAutoSyncAttempt = 0; + private workspaceLayoutReady = false; + private performanceDiagnostics!: PerformanceDiagnostics; get settings(): Readonly { return this.data.settings; @@ -415,6 +415,9 @@ export default class SupernoteSyncPlugin extends Plugin { } async onload(): Promise { + this.app.workspace.onLayoutReady(() => { + this.workspaceLayoutReady = true; + }); const stored = (await this.loadData()) as | (Partial & { writableSubtreeConfigured?: boolean; @@ -497,6 +500,10 @@ export default class SupernoteSyncPlugin extends Plugin { ? stored.missingCloudNotes : [], }; + this.performanceDiagnostics = new PerformanceDiagnostics( + this.instanceState.performanceDiagnostics, + ); + this.persistPerformanceDiagnostics(); if ( stored?.token !== undefined || storedSettings?.autoSyncMinutes !== undefined @@ -546,6 +553,19 @@ export default class SupernoteSyncPlugin extends Plugin { (leaf) => new SupernoteNoteView(leaf, { notebooks: this.getNotebookService(), + beginNotebookOpen: (scope) => + this.beginPerformanceOperation("notebook-open", scope), + finishNotebookOpen: (operation, result) => + this.finishPerformanceOperation(operation, result), + consumeInterruptedNotebookOpen: (scope) => + this.performanceDiagnostics.consumeInterrupted( + "notebook-open", + scope, + ), + isAutomaticWorkspaceRestore: () => !this.workspaceLayoutReady, + trackedNotebookBytes: () => + this.notebookService?.snapshot().retainedBytes ?? 0, + copyDiagnostics: () => this.copyDiagnostics(), getTranscriptionAvailability: () => this.getTranscriptionAvailability(), getTargetFolder: () => this.data.settings.targetFolder, @@ -682,6 +702,8 @@ export default class SupernoteSyncPlugin extends Plugin { } onunload(): void { + this.performanceDiagnostics.cancelActive(); + this.persistPerformanceDiagnostics(); this.runConsole?.dispose(); this.runConsole = null; this.notebookService?.dispose(); @@ -808,6 +830,33 @@ export default class SupernoteSyncPlugin extends Plugin { await this.saveData({ ...persisted, settings }); } + private async beginPerformanceOperation( + kind: PerformanceOperationKind, + scope: string | null = null, + ): Promise { + const operation = this.performanceDiagnostics.begin(kind, scope); + this.persistPerformanceDiagnostics(); + return operation; + } + + private async finishPerformanceOperation( + operation: ActivePerformanceOperation, + result: FinishPerformanceOperation, + ): Promise { + this.performanceDiagnostics.finish(operation, result); + this.persistPerformanceDiagnostics(); + } + + private persistPerformanceDiagnostics(): void { + this.instanceState.performanceDiagnostics = + this.performanceDiagnostics.snapshot(); + try { + this.instanceStateStore.save(this.instanceState); + } catch { + // Diagnostic persistence must never deny the operation being observed. + } + } + getMirroredNotePaths(): string[] { const mirror = normalizeRelativePath(this.data.settings.targetFolder); return indexedFilePathsBelow( @@ -1316,6 +1365,7 @@ export default class SupernoteSyncPlugin extends Plugin { prerequisites: this.setupPrerequisites(), mirroredFileCount, lastSyncOutcome: this.data.lastSyncOutcome, + performance: this.performanceDiagnostics.snapshot().recent, homeDirectory: desktop.homeDirectory, paths: { vault: vaultPath, @@ -1735,6 +1785,18 @@ export default class SupernoteSyncPlugin extends Plugin { return false; } + this.syncInProgress = true; + const diagnosticOperation = await this.beginPerformanceOperation("sync"); + let diagnosticPeakBytes = + this.notebookService?.snapshot().retainedBytes ?? 0; + const diagnosticSampler = window.setInterval(() => { + diagnosticPeakBytes = Math.max( + diagnosticPeakBytes, + this.notebookService?.snapshot().retainedBytes ?? 0, + ); + }, 50); + let diagnosticOutcome: "succeeded" | "failed" = "failed"; + let diagnosticFailureCategory: string | null = null; let completed = false; const activity = this.runs.start({ kind: "sync", @@ -1743,7 +1805,6 @@ export default class SupernoteSyncPlugin extends Plugin { model: "mirror", }); activity.append("stdout", "Checking Supernote Cloud for changes.\n"); - this.syncInProgress = true; try { const manifestService = this.createSyncService(); const transaction = await SyncManifestTransaction.open( @@ -2076,8 +2137,10 @@ export default class SupernoteSyncPlugin extends Plugin { activity.append("stdout", `${summary}.\n`); activity.finish(outcome); completed = true; + diagnosticOutcome = "succeeded"; return true; } catch (error) { + diagnosticFailureCategory = performanceFailureCategory(error); activity.append("stderr", `${errorMessage(error)}\n`); activity.finish("failed"); this.data.lastSyncOutcome = "failed"; @@ -2086,6 +2149,15 @@ export default class SupernoteSyncPlugin extends Plugin { return false; } finally { this.syncInProgress = false; + window.clearInterval(diagnosticSampler); + const diagnosticSettledBytes = + this.notebookService?.snapshot().retainedBytes ?? 0; + await this.finishPerformanceOperation(diagnosticOperation, { + outcome: diagnosticOutcome, + peakTrackedBytes: Math.max(diagnosticPeakBytes, diagnosticSettledBytes), + settledTrackedBytes: diagnosticSettledBytes, + failureCategory: diagnosticFailureCategory, + }); if ( completed && runAutomations && @@ -2204,6 +2276,17 @@ export default class SupernoteSyncPlugin extends Plugin { throw new Error("A Mirror move is already running"); } this.syncInProgress = true; + const diagnosticOperation = await this.beginPerformanceOperation("export"); + let diagnosticPeakBytes = + this.notebookService?.snapshot().retainedBytes ?? 0; + const diagnosticSampler = window.setInterval(() => { + diagnosticPeakBytes = Math.max( + diagnosticPeakBytes, + this.notebookService?.snapshot().retainedBytes ?? 0, + ); + }, 50); + let diagnosticOutcome: "succeeded" | "failed" | "cancelled" = "failed"; + let diagnosticFailureCategory: string | null = null; try { const selection = this.transcriptionSelection(options.transcription); if ( @@ -2231,19 +2314,36 @@ export default class SupernoteSyncPlugin extends Plugin { overwrite, }); try { - return await run(false); + const result = await run(false); + diagnosticOutcome = "succeeded"; + return result; } catch (error) { if (!(error instanceof ExportCollisionError)) { throw error; } const overwrite = await confirmExportOverwrite(this.app, error.paths); if (!overwrite) { + diagnosticOutcome = "cancelled"; return null; } - return await run(true); + const result = await run(true); + diagnosticOutcome = "succeeded"; + return result; } + } catch (error) { + diagnosticFailureCategory = performanceFailureCategory(error); + throw error; } finally { this.syncInProgress = false; + window.clearInterval(diagnosticSampler); + const diagnosticSettledBytes = + this.notebookService?.snapshot().retainedBytes ?? 0; + await this.finishPerformanceOperation(diagnosticOperation, { + outcome: diagnosticOutcome, + peakTrackedBytes: Math.max(diagnosticPeakBytes, diagnosticSettledBytes), + settledTrackedBytes: diagnosticSettledBytes, + failureCategory: diagnosticFailureCategory, + }); } } @@ -2625,9 +2725,6 @@ export default class SupernoteSyncPlugin extends Plugin { extraInstructions: settings.transcriptionExtraInstructions, request, runs: this.runs, - documentRequestByteLimit: Platform.isDesktopApp - ? DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT - : MOBILE_DOCUMENT_REQUEST_BYTE_LIMIT, }); } @@ -2812,12 +2909,6 @@ export default class SupernoteSyncPlugin extends Plugin { this.notebookService ??= new NotebookService({ createWorker: () => new NotebookWorker(), notifyRenderingUnavailable: (message) => new Notice(message, 12_000), - resourceBudgetBytes: Platform.isMobile - ? MOBILE_RENDER_BUDGET_BYTES - : DESKTOP_RENDER_BUDGET_BYTES, - transientResourceBudgetBytes: Platform.isMobile - ? MOBILE_TRANSIENT_SYNC_BUDGET_BYTES - : DESKTOP_TRANSIENT_SYNC_BUDGET_BYTES, maxConcurrentRenders: Platform.isMobile ? 1 : 2, }); return this.notebookService; diff --git a/src/note/notebook-service.ts b/src/note/notebook-service.ts index efd6ea6..8982b23 100644 --- a/src/note/notebook-service.ts +++ b/src/note/notebook-service.ts @@ -14,12 +14,7 @@ export type { RenderedNotebookPage, } from "./notebook-types"; -const MIB = 1_024 * 1_024; const PARSE_WORKING_BYTES_PER_SOURCE_BYTE = 4; -export const DESKTOP_RENDER_BUDGET_BYTES = 128 * MIB; -export const MOBILE_RENDER_BUDGET_BYTES = 96 * MIB; -export const DESKTOP_TRANSIENT_SYNC_BUDGET_BYTES = 192 * MIB; -export const MOBILE_TRANSIENT_SYNC_BUDGET_BYTES = 128 * MIB; export interface NotebookViewResourceState { readonly visible: boolean; @@ -28,11 +23,11 @@ export interface NotebookViewResourceState { readonly canvasBytes?: number; } -export type NotebookViewAdmissionResult = - | { readonly admitted: true } +export type NotebookViewUpdateResult = + | { readonly updated: true } | { - readonly admitted: false; - readonly reason: "resource-budget" | "unavailable"; + readonly updated: false; + readonly reason: "unavailable"; }; export interface NotebookBitmapHandle { @@ -59,21 +54,11 @@ export interface NotebookSessionLease { scale?: number, encoding?: "opaque-rgb", ): Promise; - updateView(state: NotebookViewResourceState): NotebookViewAdmissionResult; + updateView(state: NotebookViewResourceState): NotebookViewUpdateResult; close(): void; } export interface NotebookOpenOptions { - /** - * `reloadable` allows short-lived inspection work to suspend a visible - * reader's worker source while leaving its already-drawn canvas intact. - */ - reclaim?: "inactive" | "reloadable"; - /** - * `transient` admits short-lived sync parsing against the separately bounded - * transient ceiling instead of the steady interactive-reader ceiling. - */ - budget?: "interactive" | "transient"; /** Cancels only this caller's pending lease claim. */ signal?: AbortSignal; } @@ -99,8 +84,6 @@ export interface NotebookServiceSnapshot { activeSessions: number; activeLeases: number; sessionOpens: number; - budgetBytes: number; - transientBudgetBytes: number; retainedBytes: number; retainedSourceBytes: number; retainedParsedBytes: number; @@ -123,8 +106,6 @@ export interface NotebookServiceSnapshot { export interface NotebookServiceOptions { createWorker: () => Worker; - resourceBudgetBytes?: number; - transientResourceBudgetBytes?: number; maxConcurrentRenders?: number; maxQueuedRenders?: number; notifyRenderingUnavailable?: (message: string) => void; @@ -154,8 +135,6 @@ interface SessionRecord { sourceBytes: number; parsedBytes: number; descriptorBytes: number; - admissionBudgetBytes: number; - reclaimVisibleSourcesDuringAdmission: boolean; pagePixelBytes: number; pageWidth: number; pageHeight: number; @@ -296,8 +275,6 @@ export class NotebookService implements NotebookSessionProvider { private readonly retiredResourceSessions = new Set(); private readonly pendingRenders = new Map(); private readonly renderQueue: PendingRender[] = []; - private readonly resourceBudgetBytes: number; - private readonly transientResourceBudgetBytes: number; private readonly maxConcurrentRenders: number; private readonly maxQueuedRenders: number; private nextSessionId = 1; @@ -316,14 +293,6 @@ export class NotebookService implements NotebookSessionProvider { private evictedBitmaps = 0; constructor(private readonly options: NotebookServiceOptions) { - this.resourceBudgetBytes = Math.max( - 1, - options.resourceBudgetBytes ?? DESKTOP_RENDER_BUDGET_BYTES, - ); - this.transientResourceBudgetBytes = Math.max( - this.resourceBudgetBytes, - options.transientResourceBudgetBytes ?? this.resourceBudgetBytes, - ); this.maxConcurrentRenders = Math.max( 1, Math.trunc(options.maxConcurrentRenders ?? 2), @@ -342,16 +311,12 @@ export class NotebookService implements NotebookSessionProvider { throw this.abortError(); } const worker = this.ensureWorker(); - const admissionBudgetBytes = - options.budget === "transient" - ? this.transientResourceBudgetBytes - : this.resourceBudgetBytes; const identity = notebookIdentity(source.path, source.revision); const existing = this.sessionsByIdentity.get(identity); if (existing && !existing.closed) { existing.leases += 1; existing.lastUsed = ++this.resourceClock; - return this.openClaim(existing, options, admissionBudgetBytes); + return this.openClaim(existing, options); } const opened = deferred(); @@ -365,8 +330,6 @@ export class NotebookService implements NotebookSessionProvider { sourceBytes: 0, parsedBytes: 0, descriptorBytes: 0, - admissionBudgetBytes, - reclaimVisibleSourcesDuringAdmission: options.reclaim === "reloadable", pagePixelBytes: 0, pageWidth: 0, pageHeight: 0, @@ -388,29 +351,23 @@ export class NotebookService implements NotebookSessionProvider { }; this.sessionsByIdentity.set(identity, record); this.sessionsById.set(record.id, record); - void this.initializeRecord( - record, - source, - worker, - options, - admissionBudgetBytes, - ).catch((error: unknown) => { - this.closeSession( - record, - error instanceof Error - ? error - : new Error("Could not open Supernote notebook session"), - ); - }); - return this.openClaim(record, options, admissionBudgetBytes); + void this.initializeRecord(record, source, worker).catch( + (error: unknown) => { + this.closeSession( + record, + error instanceof Error + ? error + : new Error("Could not open Supernote notebook session"), + ); + }, + ); + return this.openClaim(record, options); } private async initializeRecord( record: SessionRecord, source: NotebookSource, worker: Worker, - options: NotebookOpenOptions, - admissionBudgetBytes: number, ): Promise { let bytes: Uint8Array; try { @@ -433,22 +390,16 @@ export class NotebookService implements NotebookSessionProvider { bytes, "bytes" in source && source.transfer === "copy", worker, - options.reclaim, - admissionBudgetBytes, ); } private async openClaim( record: SessionRecord, options: NotebookOpenOptions, - admissionBudgetBytes: number, ): Promise { try { const descriptor = await this.withAbort(record.opened, options.signal); - await this.withAbort( - this.ensureResident(record, options.reclaim, admissionBudgetBytes), - options.signal, - ); + await this.withAbort(this.ensureResident(record), options.signal); return this.createLease(record, descriptor); } catch (error) { if (!record.closed) { @@ -557,8 +508,6 @@ export class NotebookService implements NotebookSessionProvider { 0, ), sessionOpens: this.sessionOpens, - budgetBytes: this.resourceBudgetBytes, - transientBudgetBytes: this.transientResourceBudgetBytes, retainedBytes: retainedSourceBytes + retainedParsedBytes + @@ -616,25 +565,9 @@ export class NotebookService implements NotebookSessionProvider { bytes: Uint8Array, copy: boolean, worker = this.ensureWorker(), - reclaim: NotebookOpenOptions["reclaim"] = "inactive", - admissionBudgetBytes = this.resourceBudgetBytes, ): Promise { const parseWorkingBytes = bytes.byteLength * PARSE_WORKING_BYTES_PER_SOURCE_BYTE; - if ( - !this.evictToFit( - bytes.byteLength + parseWorkingBytes, - record, - reclaim === "reloadable", - admissionBudgetBytes, - ) - ) { - throw new Error( - `Supernote source exceeds the ${admissionBudgetBytes}-byte resource budget`, - ); - } - record.admissionBudgetBytes = admissionBudgetBytes; - record.reclaimVisibleSourcesDuringAdmission = reclaim === "reloadable"; const opening = deferred(); record.opening = opening.promise; record.resolveOpening = opening.resolve; @@ -667,11 +600,7 @@ export class NotebookService implements NotebookSessionProvider { } } - private ensureResident( - record: SessionRecord, - reclaim: NotebookOpenOptions["reclaim"] = "inactive", - admissionBudgetBytes = this.resourceBudgetBytes, - ): Promise { + private ensureResident(record: SessionRecord): Promise { if (record.closed) { return Promise.reject(new Error("Notebook source changed")); } @@ -694,14 +623,7 @@ export class NotebookService implements NotebookSessionProvider { throw new Error("Notebook source changed"); } this.sessionOpens += 1; - await this.openWorkerSession( - record, - bytes, - false, - this.ensureWorker(), - reclaim, - admissionBudgetBytes, - ); + await this.openWorkerSession(record, bytes, false, this.ensureWorker()); })(); record.restoring = restoring; const clearRestoring = (): void => { @@ -729,22 +651,6 @@ export class NotebookService implements NotebookSessionProvider { } record.parsedBytes = record.descriptorBytes + response.parsedMetadataBytes; - if ( - !this.evictToFit( - 0, - record, - record.reclaimVisibleSourcesDuringAdmission, - record.admissionBudgetBytes, - ) - ) { - this.closeSession( - record, - new Error( - `Supernote parsed source exceeds the ${record.admissionBudgetBytes}-byte resource budget`, - ), - ); - return; - } record.opening = null; record.resolveOpening?.(); record.resolveOpening = null; @@ -787,17 +693,7 @@ export class NotebookService implements NotebookSessionProvider { ); } else if (response.output === "bitmap" && pending.output === "bitmap") { const cached = this.cacheBitmap(pending, response.bitmap); - if (cached) { - this.resolveBitmap(pending, cached); - } else { - response.bitmap.close(); - this.rejectRender( - pending, - new Error( - `Supernote bitmap exceeds the ${this.resourceBudgetBytes}-byte resource budget`, - ), - ); - } + this.resolveBitmap(pending, cached); } else if (response.output === "png" && pending.output === "png") { pending.settled = true; pending.resolve({ @@ -869,6 +765,7 @@ export class NotebookService implements NotebookSessionProvider { this.closeSession(record); } else { this.releaseUnneededResources(record); + this.suspendIfInactive(record); } }, }; @@ -879,10 +776,10 @@ export class NotebookService implements NotebookSessionProvider { descriptor: NotebookDescriptor, lease: LeaseState, view: NotebookViewResourceState, - ): NotebookViewAdmissionResult { + ): NotebookViewUpdateResult { if (lease.closed || record.closed) { return { - admitted: false, + updated: false, reason: "unavailable", }; } @@ -902,20 +799,11 @@ export class NotebookService implements NotebookSessionProvider { ? Math.max(0, Math.trunc(view.canvasBytes ?? 0)) : 0, }; - const additionalCanvasBytes = Math.max( - 0, - (nextView.canvasBytes ?? 0) - (lease.view.canvasBytes ?? 0), - ); - if (!this.evictToFit(additionalCanvasBytes)) { - return { - admitted: false, - reason: "resource-budget", - }; - } lease.view = nextView; this.releaseUnneededResources(record); + this.suspendIfInactive(record); this.pumpQueue(); - return { admitted: true }; + return { updated: true }; } private canvasBytes(record: SessionRecord): number { @@ -1163,25 +1051,7 @@ export class NotebookService implements NotebookSessionProvider { } const index = this.renderQueue.indexOf(next); this.renderQueue.splice(index, 1); - if (!this.reserve(next)) { - if ( - this.fixedRetainedBytes() + next.estimatedBytes <= - this.resourceBudgetBytes - ) { - this.renderQueue.push(next); - return; - } - this.pendingRenders.delete(next.id); - this.removePendingBitmap(next); - this.rejectRender( - next, - new Error( - `Supernote render exceeds the ${this.resourceBudgetBytes}-byte resource budget`, - ), - ); - next.state = "completed"; - continue; - } + this.reserve(next); next.state = "in-flight"; this.activeRenders += 1; this.maxObservedInFlightRenders = Math.max( @@ -1202,24 +1072,9 @@ export class NotebookService implements NotebookSessionProvider { } } - private reserve(render: PendingRender): boolean { - if (!this.evictToFit(render.estimatedBytes)) { - return false; - } + private reserve(render: PendingRender): void { render.reservationActive = true; this.inFlightBytes += render.estimatedBytes; - return true; - } - - private fixedRetainedBytes(): number { - return [...this.sessionsById.values()].reduce( - (total, session) => - total + - session.sourceBytes + - session.parsedBytes + - this.canvasBytes(session), - 0, - ); } private finishRender(render: PendingRender): void { @@ -1229,6 +1084,7 @@ export class NotebookService implements NotebookSessionProvider { this.releaseReservation(render); this.pendingRenders.delete(render.id); this.removePendingBitmap(render); + this.suspendIfInactive(render.record); if (render.state !== "cancelled") { render.state = "completed"; } @@ -1257,10 +1113,17 @@ export class NotebookService implements NotebookSessionProvider { private lowestPriorityQueued(): PendingRender | undefined { return this.renderQueue.reduce( - (selected, render) => - !selected || compareRenderOrder(render, selected) > 0 + (selected, render) => { + const speculative = + render.output === "bitmap" && + render.priority !== RENDER_PRIORITY.currentPage; + if (!speculative) { + return selected; + } + return !selected || compareRenderOrder(render, selected) > 0 ? render - : selected, + : selected; + }, undefined, ); } @@ -1382,11 +1245,8 @@ export class NotebookService implements NotebookSessionProvider { private cacheBitmap( render: PendingBitmap, bitmap: ImageBitmap, - ): CachedBitmap | null { + ): CachedBitmap { const bytes = bitmapBytes(bitmap); - if (!this.evictToFit(bytes)) { - return null; - } const prior = render.record.bitmaps.get(render.key); if (prior) { this.evictBitmap(render.record, prior); @@ -1430,73 +1290,21 @@ export class NotebookService implements NotebookSessionProvider { }; } - private evictToFit( - additionalBytes: number, - excludedSession?: SessionRecord, - includeVisibleSessions = false, - budgetBytes = this.resourceBudgetBytes, - ): boolean { - while (this.retainedBytes() + additionalBytes > budgetBytes) { - const candidate = this.oldestUnpinnedBitmap(); - if (candidate) { - this.evictBitmap(candidate.record, candidate.bitmap); - continue; - } - const source = this.oldestSuspendableSession( - excludedSession, - includeVisibleSessions, - ); - if (!source) { - return false; - } - this.suspendSession(source); - } - return true; - } - - private oldestUnpinnedBitmap(): - | { record: SessionRecord; bitmap: CachedBitmap } - | undefined { - let selected: { record: SessionRecord; bitmap: CachedBitmap } | undefined; - for (const record of this.sessionsById.values()) { - for (const bitmap of record.bitmaps.values()) { - if ( - !this.isPinned(record, bitmap) && - (!selected || bitmap.lastUsed < selected.bitmap.lastUsed) - ) { - selected = { record, bitmap }; - } - } - } - return selected; - } - - private oldestSuspendableSession( - excludedSession?: SessionRecord, - includeVisibleSessions = false, - ): SessionRecord | undefined { - let selected: SessionRecord | undefined; - for (const record of this.sessionsById.values()) { - const hasPendingRender = [...this.pendingRenders.values()].some( - (render) => render.record === record, - ); - const visible = [...record.leaseStates].some( - (lease) => lease.view.visible, - ); - if ( - record !== excludedSession && - record.resident && - !record.opening && - record.sourceBytes > 0 && - record.sourceLoader && - !hasPendingRender && - (!visible || includeVisibleSessions) && - (!selected || record.lastUsed < selected.lastUsed) - ) { - selected = record; - } + private suspendIfInactive(record: SessionRecord): void { + const visible = [...record.leaseStates].some((lease) => lease.view.visible); + const hasPendingRender = [...this.pendingRenders.values()].some( + (render) => render.record === record, + ); + if ( + visible || + hasPendingRender || + !record.resident || + record.opening || + !record.sourceLoader + ) { + return; } - return selected; + this.suspendSession(record); } private suspendSession(record: SessionRecord): void { diff --git a/src/ocr/api-ocr.ts b/src/ocr/api-ocr.ts index 9f6754e..f637c30 100644 --- a/src/ocr/api-ocr.ts +++ b/src/ocr/api-ocr.ts @@ -32,7 +32,6 @@ interface ApiOcrOptions { extraInstructions: string; request: ChatCompletionExecutor; concurrency?: number; - documentRequestByteLimit?: number; runs?: RunRegistry; } @@ -54,14 +53,10 @@ const asObject = (value: unknown): JsonObject | null => ? (value as JsonObject) : null; -export const DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT = 64 * 1024 * 1024; -export const MOBILE_DOCUMENT_REQUEST_BYTE_LIMIT = 32 * 1024 * 1024; - export const BASE64_CHUNK_BYTES = 3 * 8192; export const BASE64_ENCODED_CHUNK_BYTES = (BASE64_CHUNK_BYTES / 3) * 4; const DATA_URL_PREFIX = "data:image/png;base64,"; const BASE64_PLACEHOLDER = "__SUPERNOTE_BASE64_PAYLOAD__"; -const encoder = new TextEncoder(); const appendBase64 = ( bytes: Uint8Array, @@ -93,15 +88,6 @@ const imagePart = (base64: string): JsonObject => ({ }, }); -const encodedLength = (bytes: number): number => 4 * Math.ceil(bytes / 3); - -const utf8Bytes = (value: string): number => encoder.encode(value).byteLength; - -const formatBytes = (bytes: number): string => - bytes < 1024 * 1024 - ? `${Math.ceil(bytes / 1024)} KiB` - : `${(bytes / (1024 * 1024)).toFixed(1)} MiB`; - const responseError = (response: ChatCompletionResponse): string => { const json = asObject(response.json); const error = asObject(json?.error); @@ -116,7 +102,6 @@ export class ApiOcrService implements OcrPort { private readonly instructions: string; private readonly request: ChatCompletionExecutor; private readonly concurrency: number; - private readonly documentRequestByteLimit: number; private readonly runs: RunRegistry | undefined; constructor(options: ApiOcrOptions) { @@ -128,12 +113,6 @@ export class ApiOcrService implements OcrPort { .join("\n\nAdditional instructions:\n"); this.request = options.request; this.runs = options.runs; - this.documentRequestByteLimit = Math.max( - 1, - Math.trunc( - options.documentRequestByteLimit ?? DESKTOP_DOCUMENT_REQUEST_BYTE_LIMIT, - ), - ); this.concurrency = Math.max( 1, Math.min(3, Math.trunc(options.concurrency ?? 3)), @@ -374,20 +353,9 @@ export class ApiOcrService implements OcrPort { payloadIndex + BASE64_PLACEHOLDER.length, ); let body = bodyPrefix; - let estimatedBytes = utf8Bytes(bodyPrefix) + utf8Bytes(bodySuffix); let imageIndex = 0; for (const pageNumber of request.pages.pageNumbers) { const image = await request.pages.render(pageNumber); - estimatedBytes += - (imageIndex === 0 ? 0 : 1) + - utf8Bytes(imagePrefix) + - encodedLength(image.byteLength) + - utf8Bytes(imageSuffix); - if (estimatedBytes > this.documentRequestByteLimit) { - throw new Error( - `Document transcription request would be ${formatBytes(estimatedBytes)}, above the ${formatBytes(this.documentRequestByteLimit)} limit. Use page mode or select fewer pages. The document was not silently split.`, - ); - } if (imageIndex > 0) { body += ","; } diff --git a/src/onboarding/diagnostics.ts b/src/onboarding/diagnostics.ts index fe52831..93fcbea 100644 --- a/src/onboarding/diagnostics.ts +++ b/src/onboarding/diagnostics.ts @@ -3,6 +3,7 @@ import type { DesktopAgentBinary, DesktopBinaryStatus, } from "../shared/desktop-command"; +import type { PerformanceDiagnosticRecord } from "./performance-diagnostics"; import type { SetupPrerequisite } from "./setup"; export type LastSyncOutcome = "never" | "succeeded" | "failed"; @@ -26,6 +27,7 @@ export interface DiagnosticsReportInput { prerequisites: readonly SetupPrerequisite[]; mirroredFileCount: number; lastSyncOutcome: LastSyncOutcome; + performance?: readonly PerformanceDiagnosticRecord[]; homeDirectory: string | null; paths: DiagnosticsPaths; } @@ -130,6 +132,14 @@ export const renderDiagnosticsReport = ( `mirroredFiles: ${input.mirroredFileCount}`, `lastSync: ${input.lastSyncOutcome}`, "", + "performance:", + ...(input.performance?.length + ? input.performance.map( + (record) => + ` ${record.kind}: ${record.outcome}, duration=${record.durationMs}ms, peak=${record.peakTrackedBytes ?? "unknown"}, settled=${record.settledTrackedBytes ?? "unknown"}, cleanup=${record.cleanup}, failure=${record.failureCategory ?? "none"}`, + ) + : [" recent: none"]), + "", "paths:", ` vault: ${homeRelativePath( input.paths.vault, diff --git a/src/onboarding/performance-diagnostics.ts b/src/onboarding/performance-diagnostics.ts new file mode 100644 index 0000000..e3b332b --- /dev/null +++ b/src/onboarding/performance-diagnostics.ts @@ -0,0 +1,289 @@ +export type PerformanceOperationKind = + | "notebook-open" + | "sync" + | "export" + | "transcription"; + +export type PerformanceOperationOutcome = + | "succeeded" + | "failed" + | "cancelled" + | "interrupted"; + +export interface ActivePerformanceOperation { + readonly id: string; + readonly kind: PerformanceOperationKind; + readonly scope: string | null; + readonly startedAtMs: number; +} + +export interface PerformanceDiagnosticRecord { + readonly kind: PerformanceOperationKind; + readonly outcome: PerformanceOperationOutcome; + readonly durationMs: number; + readonly peakTrackedBytes: number | null; + readonly settledTrackedBytes: number | null; + readonly cleanup: "released" | "retained" | "unknown"; + readonly failureCategory: string | null; +} + +export interface PerformanceDiagnosticsSnapshot { + readonly active: readonly ActivePerformanceOperation[]; + readonly recent: readonly PerformanceDiagnosticRecord[]; +} + +interface PerformanceDiagnosticsOptions { + readonly now?: () => number; + readonly capacity?: number; +} + +export interface FinishPerformanceOperation { + readonly outcome: Exclude; + readonly peakTrackedBytes: number | null; + readonly settledTrackedBytes: number | null; + readonly failureCategory?: string | null; +} + +const operationKinds = new Set([ + "notebook-open", + "sync", + "export", + "transcription", +]); + +const operationOutcomes = new Set([ + "succeeded", + "failed", + "cancelled", + "interrupted", +]); + +const finiteNonnegative = (value: unknown): number | null => + typeof value === "number" && Number.isFinite(value) && value >= 0 + ? value + : null; + +export const normalizePerformanceDiagnostics = ( + value: unknown, +): PerformanceDiagnosticsSnapshot => { + if (typeof value !== "object" || value === null) { + return { active: [], recent: [] }; + } + const candidate = value as { + active?: unknown; + recent?: unknown; + }; + const active = Array.isArray(candidate.active) + ? candidate.active.flatMap((item): ActivePerformanceOperation[] => { + if (typeof item !== "object" || item === null) { + return []; + } + const operation = item as { + id?: unknown; + kind?: unknown; + scope?: unknown; + startedAtMs?: unknown; + }; + return typeof operation.id === "string" && + operationKinds.has(operation.kind as PerformanceOperationKind) && + finiteNonnegative(operation.startedAtMs) !== null + ? [ + { + id: operation.id, + kind: operation.kind as PerformanceOperationKind, + scope: + typeof operation.scope === "string" ? operation.scope : null, + startedAtMs: operation.startedAtMs as number, + }, + ] + : []; + }) + : []; + const recent = Array.isArray(candidate.recent) + ? candidate.recent.flatMap((item): PerformanceDiagnosticRecord[] => { + if (typeof item !== "object" || item === null) { + return []; + } + const record = item as Record; + const durationMs = finiteNonnegative(record.durationMs); + if ( + !operationKinds.has(record.kind as PerformanceOperationKind) || + !operationOutcomes.has( + record.outcome as PerformanceOperationOutcome, + ) || + durationMs === null || + (record.cleanup !== "released" && + record.cleanup !== "retained" && + record.cleanup !== "unknown") + ) { + return []; + } + return [ + { + kind: record.kind as PerformanceOperationKind, + outcome: record.outcome as PerformanceOperationOutcome, + durationMs, + peakTrackedBytes: finiteNonnegative(record.peakTrackedBytes), + settledTrackedBytes: finiteNonnegative(record.settledTrackedBytes), + cleanup: record.cleanup, + failureCategory: + typeof record.failureCategory === "string" + ? record.failureCategory + : null, + }, + ]; + }) + : []; + return { active, recent }; +}; + +export class PerformanceDiagnostics { + private readonly now: () => number; + private readonly capacity: number; + private readonly active: ActivePerformanceOperation[]; + private readonly recent: PerformanceDiagnosticRecord[]; + private readonly interrupted = new Map(); + private sequence = 0; + + constructor( + snapshot?: PerformanceDiagnosticsSnapshot, + options: PerformanceDiagnosticsOptions = {}, + ) { + this.now = options.now ?? (() => Date.now()); + this.capacity = Math.max(1, Math.trunc(options.capacity ?? 10)); + const normalized = normalizePerformanceDiagnostics(snapshot); + this.active = []; + this.recent = [...normalized.recent].slice(-this.capacity); + const interruptedAt = this.now(); + for (const operation of normalized.active) { + const key = this.interruptionKey(operation.kind, operation.scope); + this.interrupted.set(key, (this.interrupted.get(key) ?? 0) + 1); + this.append({ + kind: operation.kind, + outcome: "interrupted", + durationMs: Math.max(0, interruptedAt - operation.startedAtMs), + peakTrackedBytes: null, + settledTrackedBytes: null, + cleanup: "unknown", + failureCategory: "host-interrupted", + }); + } + } + + begin( + kind: PerformanceOperationKind, + scope: string | null = null, + ): ActivePerformanceOperation { + const startedAtMs = this.now(); + const operation = { + id: `${kind}-${startedAtMs}-${++this.sequence}`, + kind, + scope, + startedAtMs, + }; + this.active.push(operation); + return operation; + } + + finish( + operation: ActivePerformanceOperation, + result: FinishPerformanceOperation, + ): void { + const index = this.active.findIndex( + (candidate) => candidate.id === operation.id, + ); + if (index < 0) { + return; + } + this.active.splice(index, 1); + const settled = finiteNonnegative(result.settledTrackedBytes); + this.append({ + kind: operation.kind, + outcome: result.outcome, + durationMs: Math.max(0, this.now() - operation.startedAtMs), + peakTrackedBytes: finiteNonnegative(result.peakTrackedBytes), + settledTrackedBytes: settled, + cleanup: + settled === null ? "unknown" : settled === 0 ? "released" : "retained", + failureCategory: result.failureCategory ?? null, + }); + } + + consumeInterrupted( + kind: PerformanceOperationKind, + scope: string | null = null, + ): boolean { + const key = this.interruptionKey(kind, scope); + const count = this.interrupted.get(key) ?? 0; + if (count === 0) { + return false; + } + if (count === 1) { + this.interrupted.delete(key); + } else { + this.interrupted.set(key, count - 1); + } + return true; + } + + cancelActive(): void { + for (const operation of [...this.active]) { + this.finish(operation, { + outcome: "cancelled", + peakTrackedBytes: null, + settledTrackedBytes: null, + }); + } + } + + snapshot(): PerformanceDiagnosticsSnapshot { + return { + active: this.active.map((operation) => ({ ...operation })), + recent: this.recent.map((record) => ({ ...record })), + }; + } + + private append(record: PerformanceDiagnosticRecord): void { + this.recent.push(record); + this.recent.splice(0, Math.max(0, this.recent.length - this.capacity)); + } + + private interruptionKey( + kind: PerformanceOperationKind, + scope: string | null, + ): string { + return `${kind}:${scope ?? ""}`; + } +} + +export const performanceFailureCategory = (error: unknown): string => { + if (error instanceof DOMException && error.name === "AbortError") { + return "cancelled"; + } + const name = error instanceof Error ? error.name.toLocaleLowerCase() : ""; + const message = + error instanceof Error ? error.message.toLocaleLowerCase() : String(error); + const evidence = `${name} ${message}`; + if (/timeout|timed out/.test(evidence)) { + return "timeout"; + } + if (/memory|allocation|out of memory/.test(evidence)) { + return "allocation"; + } + if (/worker/.test(evidence)) { + return "worker"; + } + if (/parse|decode|invalid|corrupt|malformed/.test(evidence)) { + return "parse-or-decode"; + } + if (/canvas|bitmap|image|render/.test(evidence)) { + return "rendering"; + } + if (/network|fetch|http|api|auth|unauthor|forbidden/.test(evidence)) { + return "network-or-api"; + } + if (/permission|denied|not allowed/.test(evidence)) { + return "permission"; + } + return "unexpected"; +}; diff --git a/src/sync/instance-state.ts b/src/sync/instance-state.ts index a8f802b..ff62c29 100644 --- a/src/sync/instance-state.ts +++ b/src/sync/instance-state.ts @@ -1,4 +1,8 @@ import type { PairBaseline } from "./pair-sync-service"; +import { + normalizePerformanceDiagnostics, + type PerformanceDiagnosticsSnapshot, +} from "../onboarding/performance-diagnostics"; interface DeviceLocalStorage { loadLocalStorage(key: string): unknown | null; @@ -24,6 +28,7 @@ export interface InstanceState { pairBaselines: Record; mirrorDirectories: Record; lastSendDestination: SendDestination | null; + performanceDiagnostics: PerformanceDiagnosticsSnapshot; } export interface LegacyInstanceState { @@ -42,6 +47,7 @@ export const emptyInstanceState = (): InstanceState => ({ pairBaselines: {}, mirrorDirectories: {}, lastSendDestination: null, + performanceDiagnostics: { active: [], recent: [] }, }); const isRecord = (value: unknown): value is Record => @@ -134,6 +140,9 @@ const parseInstanceState = (value: unknown): InstanceState | null => { const state = JSON.parse(JSON.stringify(value)) as InstanceState; state.lastFullSyncAt ??= null; state.mirrorDirectories ??= {}; + state.performanceDiagnostics = normalizePerformanceDiagnostics( + value.performanceDiagnostics, + ); for (const baseline of Object.values(state.pairBaselines)) { baseline.directories ??= {}; } diff --git a/src/sync/sync-service.ts b/src/sync/sync-service.ts index 24af8f3..5d24363 100644 --- a/src/sync/sync-service.ts +++ b/src/sync/sync-service.ts @@ -291,17 +291,14 @@ export class SyncService { const isNote = input.file.fileName.toLocaleLowerCase().endsWith(".note"); let pageCount: number | undefined; if (isNote) { - const session = await this.notebooks.open( - { - // These bytes have not entered the Mirror yet, so they are a - // candidate source rather than a revision of the mirrored path. - path: `candidate:${descriptor.md5}:${vaultPath}`, - revision: descriptor.md5, - bytes, - transfer: "copy", - }, - { reclaim: "reloadable", budget: "transient" }, - ); + const session = await this.notebooks.open({ + // These bytes have not entered the Mirror yet, so they are a + // candidate source rather than a revision of the mirrored path. + path: `candidate:${descriptor.md5}:${vaultPath}`, + revision: descriptor.md5, + bytes, + transfer: "copy", + }); pageCount = session.descriptor.pageCount; session.close(); } diff --git a/src/ui/cloud-browser-presentation.ts b/src/ui/cloud-browser-presentation.ts new file mode 100644 index 0000000..77842c9 --- /dev/null +++ b/src/ui/cloud-browser-presentation.ts @@ -0,0 +1,40 @@ +import type { CloudBrowserSyncStatus } from "./cloud-browser-status"; + +export interface CloudBrowserFilePresentation { + statusLabel: string; + actionLabel: string; + trailingIcon: "chevron-right" | "download" | "refresh-cw"; +} + +export const cloudBrowserFilePresentation = ( + status: CloudBrowserSyncStatus, +): CloudBrowserFilePresentation => { + switch (status) { + case "downloaded": + case "mirrored": + case "writable-sync": + return { + statusLabel: + status === "downloaded" + ? "Downloaded" + : status === "mirrored" + ? "Mirrored" + : "Paired", + actionLabel: "Open", + trailingIcon: "chevron-right", + }; + case "update-available": + return { + statusLabel: "Update available", + actionLabel: "Update and open", + trailingIcon: "refresh-cw", + }; + case "included": + case "not-synced": + return { + statusLabel: status === "included" ? "Mirrored" : "Cloud only", + actionLabel: "Download and open", + trailingIcon: "download", + }; + } +}; diff --git a/src/ui/folder-picker-modal.ts b/src/ui/folder-picker-modal.ts index 5c815a3..668f6fb 100644 --- a/src/ui/folder-picker-modal.ts +++ b/src/ui/folder-picker-modal.ts @@ -1,7 +1,15 @@ -import { ButtonComponent, Menu, Modal, setIcon, type App } from "obsidian"; +import { + ButtonComponent, + Menu, + Modal, + Platform, + setIcon, + type App, +} from "obsidian"; import type { SupernoteCloudClient } from "../cloud/client"; import type { CloudFile, CloudItem } from "../cloud/types"; +import { cloudBrowserFilePresentation } from "./cloud-browser-presentation"; import type { CloudBrowserSyncStatus } from "./cloud-browser-status"; export type OpenCloudFile = ( @@ -65,6 +73,7 @@ interface FolderPickerModalOptions { } type RetryKind = "download" | "mirror" | "stop"; +type NavigationDirection = "forward" | "back" | "replace"; interface OperationError { kind: RetryKind; @@ -180,6 +189,7 @@ export class FolderPickerModal extends Modal { onOpen(): void { this.closed = false; this.modalEl.addClass("supernote-sync-browser-modal"); + this.modalEl.toggleClass("is-mobile", Platform.isMobile); this.contentEl.empty(); this.contentEl.addClass("supernote-sync-browser"); this.setTitle("Supernote Cloud"); @@ -213,22 +223,24 @@ export class FolderPickerModal extends Modal { this.contentEl.empty(); } - private async renderDirectory(): Promise { + private async renderDirectory( + direction: NavigationDirection = "replace", + ): Promise { const generation = ++this.renderGeneration; const location = this.currentLocation; this.renderBreadcrumbs(); this.renderCurrentAction(location); - this.listEl.empty(); - const loading = this.listEl.createEl("p", { - text: "Loading folder…", - cls: "supernote-sync-muted", - }); + this.renderLoadingState(direction); try { const items = await this.cloud.listDirectory(location.id); if (generation !== this.renderGeneration) { return; } - loading.remove(); + this.listEl.empty(); + this.listEl.setAttr("aria-busy", "false"); + const results = this.listEl.createDiv({ + cls: `supernote-sync-browser-results ${this.transitionClass(direction)}`, + }); const visibleItems = items .filter((item) => !this.options.foldersOnly || item.isFolder) .sort( @@ -237,7 +249,7 @@ export class FolderPickerModal extends Modal { left.fileName.localeCompare(right.fileName), ); if (visibleItems.length === 0) { - this.listEl.createEl("p", { + results.createEl("p", { text: this.options.foldersOnly ? "No folders are in this location." : "No folders or files are in this location.", @@ -246,13 +258,14 @@ export class FolderPickerModal extends Modal { return; } for (const item of visibleItems) { - this.renderItem(item, location); + this.renderItem(results, item, location); } } catch (error) { if (generation !== this.renderGeneration) { return; } - loading.remove(); + this.listEl.empty(); + this.listEl.setAttr("aria-busy", "false"); const failure = this.listEl.createDiv({ cls: "supernote-sync-browser-load-error", }); @@ -272,13 +285,31 @@ export class FolderPickerModal extends Modal { if (this.locations.length === 1) { return; } + if (Platform.isMobile) { + const parent = this.locations.at(-2)!; + this.createIconButton( + this.breadcrumbsEl, + "chevron-left", + `Back to ${parent.label}`, + () => { + this.locations.pop(); + void this.renderDirectory("back"); + }, + ); + this.breadcrumbsEl.createSpan({ + text: this.currentLocation.label, + cls: "supernote-sync-browser-mobile-location", + attr: { "aria-current": "location" }, + }); + return; + } const rootButton = this.createIconButton( this.breadcrumbsEl, "cloud", "Supernote Cloud", () => { this.locations.splice(1); - void this.renderDirectory(); + void this.renderDirectory("back"); }, ); rootButton.addClass("supernote-sync-browser-breadcrumb-root"); @@ -300,7 +331,7 @@ export class FolderPickerModal extends Modal { location.label, () => { this.locations.splice(index + 1); - void this.renderDirectory(); + void this.renderDirectory("back"); }, "supernote-sync-browser-breadcrumb", ); @@ -343,19 +374,117 @@ export class FolderPickerModal extends Modal { this.renderErrorState(this.currentActionEl, location, operationError); return; } + if (Platform.isMobile) { + this.renderMobileCurrentFolderMenu(location, state); + return; + } this.renderFolderStateControls(this.currentActionEl, location, state, true); } - private renderItem(item: CloudItem, location: Location): void { + private renderMobileCurrentFolderMenu( + location: Location, + state: CloudBrowserItemState, + ): void { + const canMirror = + state.status !== "mirrored" && + state.status !== "included" && + state.status !== "writable-sync"; + const canStopMirroring = + state.status === "mirrored" && + this.options.previewStopMirroringFolder && + this.options.stopMirroringFolder; + if (!canMirror && !canStopMirroring) { + return; + } + const button = this.currentActionEl.createEl("button", { + cls: "clickable-icon supernote-sync-browser-more", + attr: { + type: "button", + "aria-label": `Actions for ${location.label}`, + title: `Actions for ${location.label}`, + }, + }); + setIcon(button, "more-horizontal"); + button.disabled = this.operationInProgress; + button.addEventListener("click", (event) => { + event.stopPropagation(); + const menu = new Menu(); + if (canMirror) { + menu.addItem((item) => + item + .setTitle("Mirror this folder") + .setIcon("cloud-download") + .onClick(() => { + void this.runOperation( + location.path, + "mirror", + `Mirroring ${location.label}…`, + () => this.mirrorFolder(location.id, location.path), + ); + }), + ); + } + if (canStopMirroring) { + menu.addItem((item) => + item + .setTitle("Stop mirroring…") + .setIcon("trash-2") + .onClick(() => { + void this.confirmAndStopMirroring(location); + }), + ); + } + menu.showAtMouseEvent(event); + }); + } + + private renderLoadingState(direction: NavigationDirection): void { + this.listEl.empty(); + this.listEl.setAttr("aria-busy", "true"); + const skeletons = this.listEl.createDiv({ + cls: `supernote-sync-browser-skeletons ${this.transitionClass(direction)}`, + attr: { "aria-label": "Loading folder" }, + }); + for (let index = 0; index < 5; index += 1) { + const row = skeletons.createDiv({ + cls: "supernote-sync-browser-skeleton-row", + }); + row.createSpan({ cls: "supernote-sync-browser-skeleton-icon" }); + const text = row.createDiv({ + cls: "supernote-sync-browser-skeleton-text", + }); + text.createSpan({ cls: "supernote-sync-browser-skeleton-name" }); + text.createSpan({ cls: "supernote-sync-browser-skeleton-subtitle" }); + } + } + + private transitionClass(direction: NavigationDirection): string { + return direction === "forward" + ? "is-entering-forward" + : direction === "back" + ? "is-entering-back" + : "is-entering"; + } + + private renderItem( + container: HTMLElement, + item: CloudItem, + location: Location, + ): void { const remotePath = `${location.path}/${item.fileName}`; - const row = this.listEl.createDiv({ + const state = this.resolveState?.(item, remotePath) ?? { + status: "not-synced" as const, + }; + const row = container.createDiv({ cls: "supernote-sync-file-row", }); const primary = row.createDiv({ cls: "supernote-sync-file-primary", - attr: { role: "button" }, + ...(!Platform.isMobile ? { attr: { role: "button" } } : {}), }); - primary.tabIndex = 0; + if (!Platform.isMobile) { + primary.tabIndex = 0; + } const icon = primary.createSpan({ cls: "supernote-sync-file-icon" }); setIcon( icon, @@ -365,15 +494,19 @@ export class FolderPickerModal extends Modal { ? "notebook-tabs" : "file", ); - primary.createSpan({ + const description = primary.createDiv({ + cls: "supernote-sync-file-description", + }); + description.createSpan({ text: item.fileName, cls: "supernote-sync-file-name", }); + const subtitle = description.createSpan({ + text: this.itemStatusLabel(item, state), + cls: "supernote-sync-file-subtitle", + }); const controls = row.createDiv({ cls: "supernote-sync-file-controls" }); const operationError = this.operationErrors.get(remotePath); - const state = this.resolveState?.(item, remotePath) ?? { - status: "not-synced" as const, - }; if (item.isFolder) { const openFolder = (): void => { @@ -382,10 +515,12 @@ export class FolderPickerModal extends Modal { path: remotePath, label: item.fileName, }); - void this.renderDirectory(); + void this.renderDirectory("forward"); }; - this.makeKeyboardClickable(primary, openFolder); - if (!this.options.foldersOnly) { + this.makeKeyboardClickable(Platform.isMobile ? row : primary, openFolder); + if (Platform.isMobile) { + this.addTrailingIcon(controls, "chevron-right"); + } else if (!this.options.foldersOnly) { if (operationError) { this.renderErrorState( controls, @@ -405,25 +540,112 @@ export class FolderPickerModal extends Modal { } const file = item as CloudFile; + const openStatus = operationError?.retryStatus ?? state.status; const open = (): void => { - void this.openCloudFile(file, remotePath, state.status); + if (this.operationInProgress) { + return; + } + this.showRowProgress(row, openStatus); + void this.openCloudFile(file, remotePath, openStatus); }; - this.makeKeyboardClickable(primary, open); if (operationError) { - this.renderFileError(controls, file, remotePath, operationError); + if (Platform.isMobile) { + subtitle.setText(operationError.message); + subtitle.addClass("is-error"); + row.setAttr( + "aria-label", + `${item.fileName}. ${operationError.message}. Retry.`, + ); + this.makeKeyboardClickable(row, open); + this.addTrailingIcon(controls, "refresh-cw"); + return; + } + this.makeKeyboardClickable(primary, open); + this.renderFileError(controls, operationError, open); return; } - this.addStatus(controls, this.statusLabel(state), false, state.status); - const label = - state.status === "downloaded" || - state.status === "mirrored" || - state.status === "writable-sync" - ? "Open" - : state.status === "update-available" - ? "Update and open" - : "Download"; - this.createTextButton(controls, label, open).disabled = - this.operationInProgress; + this.makeKeyboardClickable(Platform.isMobile ? row : primary, open); + if (Platform.isMobile) { + const presentation = cloudBrowserFilePresentation(state.status); + row.setAttr( + "aria-label", + `${item.fileName}. ${presentation.statusLabel}. ${presentation.actionLabel}.`, + ); + this.addTrailingIcon(controls, presentation.trailingIcon); + return; + } + this.createTextButton( + controls, + cloudBrowserFilePresentation(state.status).actionLabel.replace( + "Download and open", + "Download", + ), + open, + "supernote-sync-file-action", + ).disabled = this.operationInProgress; + } + + private itemStatusLabel( + item: CloudItem, + state: CloudBrowserItemState, + ): string { + if (!item.isFolder) { + return cloudBrowserFilePresentation(state.status).statusLabel; + } + if (state.status === "not-synced") { + return "Cloud folder"; + } + return this.statusLabel(state); + } + + private addTrailingIcon( + container: HTMLElement, + icon: Parameters[1], + ): void { + const trailing = container.createSpan({ + cls: "supernote-sync-file-trailing-icon", + attr: { "aria-hidden": "true" }, + }); + setIcon(trailing, icon); + } + + private showRowProgress( + row: HTMLElement, + status: CloudBrowserSyncStatus, + ): void { + row.addClass("is-working"); + row.setAttr("aria-busy", "true"); + const progressLabel = + status === "downloaded" || + status === "mirrored" || + status === "writable-sync" + ? "Opening…" + : "Downloading…"; + row + .querySelector(".supernote-sync-file-subtitle") + ?.setText(progressLabel); + const trailing = row.querySelector( + ".supernote-sync-file-trailing-icon", + ); + if (trailing) { + trailing.empty(); + trailing.addClass("is-spinning"); + setIcon(trailing, "loader-circle"); + } + const action = row.querySelector( + ".supernote-sync-file-action", + ); + if (action) { + action.disabled = true; + action.empty(); + const spinner = action.createSpan({ + cls: "supernote-sync-file-action-spinner is-spinning", + }); + setIcon(spinner, "loader-circle"); + action.createSpan({ + text: progressLabel, + }); + } } private renderFolderStateControls( @@ -433,21 +655,27 @@ export class FolderPickerModal extends Modal { currentFolder: boolean, ): void { if (state.status === "mirrored") { - this.addStatus(container, "Mirrored", false, state.status); + if (currentFolder) { + this.addStatus(container, "Mirrored", false, state.status); + } this.addStopMirroringMenu(container, location); return; } if (state.status === "included") { - this.addStatus(container, this.statusLabel(state), false, state.status); + if (currentFolder) { + this.addStatus(container, this.statusLabel(state), false, state.status); + } return; } if (state.status === "writable-sync") { - this.addStatus( - container, - STATUS_LABELS[state.status], - false, - state.status, - ); + if (currentFolder) { + this.addStatus( + container, + STATUS_LABELS[state.status], + false, + state.status, + ); + } return; } const mirror = (): void => { @@ -576,18 +804,12 @@ export class FolderPickerModal extends Modal { private renderFileError( container: HTMLElement, - file: CloudFile, - remotePath: string, error: OperationError, + retry: () => void, ): void { this.addStatus(container, error.message, true); - this.createTextButton(container, "Retry", () => { - void this.openCloudFile( - file, - remotePath, - error.retryStatus ?? "not-synced", - ); - }).disabled = this.operationInProgress; + this.createTextButton(container, "Retry", retry).disabled = + this.operationInProgress; } private renderErrorState( @@ -737,6 +959,10 @@ export class FolderPickerModal extends Modal { element: HTMLElement, onActivate: () => void, ): void { + element.tabIndex = 0; + if (!element.hasAttribute("role")) { + element.setAttr("role", "button"); + } element.addEventListener("click", onActivate); element.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { diff --git a/src/viewer/fixed-page-embed.ts b/src/viewer/fixed-page-embed.ts index 23aa232..4074a16 100644 --- a/src/viewer/fixed-page-embed.ts +++ b/src/viewer/fixed-page-embed.ts @@ -257,11 +257,9 @@ export class FixedPageEmbedRenderer { currentPage: this.options.pageNumber, gridOpen: false, canvasBytes: 0, - }).admitted + }).updated ) { - this.fail( - `Not enough display memory to render page ${this.options.pageNumber}.`, - ); + this.fail("Supernote rendering is unavailable."); return; } await this.render(opened); @@ -326,16 +324,14 @@ export class FixedPageEmbedRenderer { displayHeight: box.height, devicePixelRatio: box.devicePixelRatio, }); - const admission = session.updateView({ + const update = session.updateView({ visible: true, currentPage: this.options.pageNumber, gridOpen: false, canvasBytes: backing.bytes, }); - if (!admission.admitted) { - this.fail( - `Not enough display memory to render page ${this.options.pageNumber}.`, - ); + if (!update.updated) { + this.fail("Supernote rendering is unavailable."); return; } this.options.target.draw(handle.bitmap, backing); diff --git a/src/viewer/note-reader.ts b/src/viewer/note-reader.ts index 48b494d..d65321a 100644 --- a/src/viewer/note-reader.ts +++ b/src/viewer/note-reader.ts @@ -41,7 +41,7 @@ import { import { fixedPageEmbedMarkdown } from "./fixed-page-embed"; import { notebookEmbedMarkdown } from "./notebook-embed"; import { - admittedPageTransition, + preparedPageTransition, navigationTarget, pageTransitionCommitDecision, pageTransitionRenderTarget, @@ -160,11 +160,7 @@ export class NoteReader { private surfaces: PageSurfaces | null = null; private chrome: HTMLElement | null = null; private counter: HTMLElement | null = null; - private zoomControl: HTMLElement | null = null; - private zoomOutButton: HTMLButtonElement | null = null; - private zoomValueButton: HTMLButtonElement | null = null; - private zoomInButton: HTMLButtonElement | null = null; - private committedZoomControlKey: string | null = null; + private committedZoomToolbarKey: string | null = null; private chromeTimer: number | null = null; private chromeLastActivity = 0; private transformAnimationTimer: number | null = null; @@ -213,8 +209,7 @@ export class NoteReader { private swipeOffset = 0; private pinchDistance: number | null = null; private dragging: { x: number; y: number } | null = null; - private resourceBudgetNoticeShown = false; - private initialPageAdmissionRejected = false; + private initialPagePreparationDidFail = false; private pageDisplayBounds: { width: number; height: number } | null = null; private toolbarNotificationsEnabled = false; @@ -302,8 +297,8 @@ export class NoteReader { return this.options.session.descriptor.revision; } - get rejectedInitialPageAdmission(): boolean { - return this.initialPageAdmissionRejected; + get initialPagePreparationFailed(): boolean { + return this.initialPagePreparationDidFail; } get toolbarContext(): ReaderToolbarContext { @@ -311,6 +306,8 @@ export class NoteReader { mode: this.viewMode, selecting: this.gridSelecting, selectedPages: this.state.selectedPages.length, + canZoomOut: this.viewportTransform.canZoomOut, + canZoomIn: this.viewportTransform.canZoomIn, }; } @@ -333,6 +330,12 @@ export class NoteReader { case "pages": this.renderGrid(); break; + case "zoom-out": + this.changeZoomByStep(-1); + break; + case "zoom-in": + this.changeZoomByStep(1); + break; case "copy-page": void this.copyCurrentPageEmbed(); break; @@ -446,11 +449,7 @@ export class NoteReader { this.root.removeClass("is-selecting", "is-motion-active"); this.chrome = null; this.counter = null; - this.zoomControl = null; - this.zoomOutButton = null; - this.zoomValueButton = null; - this.zoomInButton = null; - this.committedZoomControlKey = null; + this.committedZoomToolbarKey = null; this.viewportTransform.reset(); const chrome = this.root.createDiv({ @@ -492,12 +491,9 @@ export class NoteReader { iconButton(bottom, "chevron-right", "Next page", () => { this.navigateBy(1); }); - this.createZoomControl(chrome); - this.updateCounter(); this.syncTransformGeometry(); - this.syncZoomControl(); - this.notifyToolbarChanged(); + this.syncZoomToolbar(); this.revealChrome(); this.root.focus(); if ( @@ -627,12 +623,12 @@ export class NoteReader { return; } - const transition = admittedPageTransition( + const transition = preparedPageTransition( this.state.currentPage, targetPage, this.isRtl(), (page) => - this.admitSessionView({ + this.updateSessionViewState({ visible: this.visible, currentPage: this.visible ? page : null, gridOpen: false, @@ -700,7 +696,7 @@ export class NoteReader { this.initialPageHandle = undefined; try { if (!this.drawSurfaceBitmap(surface, pageNumber, handle.bitmap)) { - this.initialPageAdmissionRejected = true; + this.initialPagePreparationDidFail = true; } } finally { handle.release(); @@ -853,7 +849,7 @@ export class NoteReader { this.clearTransitionTimer(); const { targetPage, direction } = transition; if ( - !this.admitSessionView({ + !this.updateSessionViewState({ visible: this.visible, currentPage: this.visible ? targetPage : null, gridOpen: false, @@ -1092,7 +1088,7 @@ export class NoteReader { } private updateSessionView(): boolean { - return this.admitSessionView({ + return this.updateSessionViewState({ visible: this.visible, currentPage: this.visible && this.viewMode === "pager" @@ -1106,54 +1102,33 @@ export class NoteReader { }); } - private admitSessionView( + private updateSessionViewState( view: Parameters[0], - notifyRejection = true, ): boolean { - const admission = this.options.session.updateView(view); - if (admission.admitted) { - return true; - } - if ( - notifyRejection && - this.visible && - admission.reason === "resource-budget" && - !this.resourceBudgetNoticeShown - ) { - this.resourceBudgetNoticeShown = true; - new Notice( - "This Supernote view needs more display memory. Close another reader or the page grid, then try again.", - 10_000, - ); - } - return false; + return this.options.session.updateView(view).updated; } private resizeCanvas( canvas: HTMLCanvasElement, width: number, height: number, - notifyRejection = true, ): boolean { const bytes = width * height * 4; const previous = this.canvasAllocations.get(canvas) ?? 0; const retainedCanvasBytes = this.retainedCanvasBytes - previous + bytes; if ( - !this.admitSessionView( - { - visible: this.visible, - currentPage: - this.visible && this.viewMode === "pager" - ? pageTransitionRenderTarget( - this.state.currentPage, - this.activeTransition?.targetPage ?? null, - ) - : null, - gridOpen: this.visible && this.viewMode === "grid", - canvasBytes: retainedCanvasBytes, - }, - notifyRejection, - ) + !this.updateSessionViewState({ + visible: this.visible, + currentPage: + this.visible && this.viewMode === "pager" + ? pageTransitionRenderTarget( + this.state.currentPage, + this.activeTransition?.targetPage ?? null, + ) + : null, + gridOpen: this.visible && this.viewMode === "grid", + canvasBytes: retainedCanvasBytes, + }) ) { return false; } @@ -1301,7 +1276,7 @@ export class NoteReader { handle.release(); } } catch { - // A layout refresh is opportunistic; keep the last admitted canvas. + // A layout refresh is opportunistic; keep the last prepared canvas. } } @@ -1311,37 +1286,6 @@ export class NoteReader { ); } - private createZoomControl(parent: HTMLElement): void { - const control = parent.createDiv({ - cls: "supernote-reader-zoom-control", - attr: { - role: "group", - "aria-label": "Zoom, 100 percent", - }, - }); - this.zoomControl = control; - this.zoomOutButton = iconButton(control, "minus", "Zoom out", () => { - this.changeZoomByStep(-1); - }); - this.zoomOutButton.addClass("supernote-reader-zoom-button"); - this.zoomValueButton = control.createEl("button", { - cls: "supernote-reader-zoom-value", - text: "100%", - attr: { - type: "button", - "aria-label": "Current zoom 100 percent. Return to fit.", - }, - }); - this.zoomValueButton.addEventListener("click", (event) => { - event.stopPropagation(); - this.returnToFit(); - }); - this.zoomInButton = iconButton(control, "plus", "Zoom in", () => { - this.changeZoomByStep(1); - }); - this.zoomInButton.addClass("supernote-reader-zoom-button"); - } - private changeZoomByStep(direction: -1 | 1): void { if (this.activeTransition !== null) { return; @@ -1361,27 +1305,15 @@ export class NoteReader { } } - private syncZoomControl(zoom = this.viewportTransform.snapshot.zoom): void { - const percentage = Math.round(zoom * 100); + private syncZoomToolbar(): void { const atMinimum = !this.viewportTransform.canZoomOut; const atMaximum = !this.viewportTransform.canZoomIn; - const controlKey = `${percentage}:${atMinimum}:${atMaximum}`; - if (this.committedZoomControlKey === controlKey) { + const toolbarKey = `${atMinimum}:${atMaximum}`; + if (this.committedZoomToolbarKey === toolbarKey) { return; } - this.committedZoomControlKey = controlKey; - this.zoomControl?.setAttr("aria-label", `Zoom, ${percentage} percent`); - this.zoomValueButton?.setText(`${percentage}%`); - this.zoomValueButton?.setAttr( - "aria-label", - `Current zoom ${percentage} percent. Return to fit.`, - ); - if (this.zoomOutButton) { - this.zoomOutButton.disabled = atMinimum; - } - if (this.zoomInButton) { - this.zoomInButton.disabled = atMaximum; - } + this.committedZoomToolbarKey = toolbarKey; + this.notifyToolbarChanged(); } private notifyToolbarChanged(): void { @@ -1467,7 +1399,7 @@ export class NoteReader { writes.canvas.animate === true && !this.prefersReducedMotion(), ); canvas.style.transform = `translate(${writes.canvas.panX}px, ${writes.canvas.panY}px) scale(${writes.canvas.zoom})`; - this.syncZoomControl(writes.canvas.zoom); + this.syncZoomToolbar(); } } } @@ -2036,7 +1968,7 @@ export class NoteReader { attr: { width: "1", height: "1" }, }); canvas.dataset.pageNumber = String(pageNumber); - this.resizeCanvas(canvas, 1, 1, false); + this.resizeCanvas(canvas, 1, 1); card.createSpan({ cls: "supernote-reader-thumbnail-label", text: `Page ${pageNumber}`, diff --git a/src/viewer/note-view.ts b/src/viewer/note-view.ts index 362ec23..aefa7d4 100644 --- a/src/viewer/note-view.ts +++ b/src/viewer/note-view.ts @@ -13,6 +13,11 @@ import type { NotebookBitmapHandle, NotebookSessionProvider, } from "../note/notebook-service"; +import { + performanceFailureCategory, + type ActivePerformanceOperation, + type PerformanceOperationOutcome, +} from "../onboarding/performance-diagnostics"; import { NoteReader, type ViewerExporter, @@ -41,6 +46,20 @@ const mobileReaderNavbarVisibility = interface NoteViewDependencies { notebooks: NotebookSessionProvider; + beginNotebookOpen: (scope: string) => Promise; + finishNotebookOpen: ( + operation: ActivePerformanceOperation, + result: { + outcome: Exclude; + peakTrackedBytes: number | null; + settledTrackedBytes: number | null; + failureCategory?: string | null; + }, + ) => Promise; + consumeInterruptedNotebookOpen: (scope: string) => boolean; + isAutomaticWorkspaceRestore: () => boolean; + trackedNotebookBytes: () => number; + copyDiagnostics: () => Promise; getTranscriptionAvailability: () => TranscriptionAvailability; getTargetFolder: () => string; exportPages: ViewerExporter; @@ -144,6 +163,7 @@ export class SupernoteNoteView extends FileView { const presentation = readerToolbarPresentation({ ...context, compact: this.readerToolbarCompact, + showZoomControls: !Platform.isMobile, }); this.currentReaderToolbarPresentation = presentation; for (const action of presentation.visibleActions) { @@ -278,14 +298,90 @@ export class SupernoteNoteView extends FileView { async onLoadFile(file: TFile): Promise { await super.onLoadFile(file); - await this.loadRevision(file); + const scope = `${file.stat.size}:${file.stat.mtime}`; + const interrupted = this.dependencies.consumeInterruptedNotebookOpen(scope); + if (interrupted && this.dependencies.isAutomaticWorkspaceRestore()) { + this.renderOpenFailure( + file, + "The previous notebook open did not finish. Retry when ready.", + ); + return; + } + await this.openWithDiagnostics(file); + } + + private async openWithDiagnostics(file: TFile): Promise { + const scope = `${file.stat.size}:${file.stat.mtime}`; + const operation = await this.dependencies.beginNotebookOpen(scope); + const beforeBytes = this.dependencies.trackedNotebookBytes(); + let peakBytes = beforeBytes; + const viewWindow = this.contentEl.ownerDocument.defaultView; + const sampler = viewWindow?.setInterval(() => { + peakBytes = Math.max(peakBytes, this.dependencies.trackedNotebookBytes()); + }, 50); + try { + const presented = await this.loadRevision(file); + const settledBytes = this.dependencies.trackedNotebookBytes(); + peakBytes = Math.max(peakBytes, settledBytes); + await this.dependencies.finishNotebookOpen(operation, { + outcome: presented ? "succeeded" : "cancelled", + peakTrackedBytes: peakBytes, + settledTrackedBytes: settledBytes, + }); + } catch (error) { + const settledBytes = this.dependencies.trackedNotebookBytes(); + peakBytes = Math.max(peakBytes, settledBytes); + await this.dependencies.finishNotebookOpen(operation, { + outcome: "failed", + peakTrackedBytes: peakBytes, + settledTrackedBytes: settledBytes, + failureCategory: performanceFailureCategory(error), + }); + this.renderOpenFailure( + file, + error instanceof Error + ? error.message + : "The notebook could not be opened.", + ); + } finally { + if (viewWindow && sampler !== undefined) { + viewWindow.clearInterval(sampler); + } + } } - private async loadRevision(file: TFile): Promise { + private renderOpenFailure(file: TFile, message: string): void { + this.contentEl.empty(); + this.contentEl.addClass("supernote-note-view"); + this.contentEl.createEl("h2", { + text: "Could not open Supernote notebook", + }); + this.contentEl.createEl("p", { + text: message, + }); + const actions = this.contentEl.createDiv({ + cls: "supernote-reader-failure-actions", + }); + const retry = actions.createEl("button", { text: "Retry" }); + retry.addEventListener("click", () => { + retry.disabled = true; + void this.openWithDiagnostics(file).finally(() => { + retry.disabled = false; + }); + }); + const copy = actions.createEl("button", { + text: "Copy diagnostics", + }); + copy.addEventListener("click", () => { + void this.dependencies.copyDiagnostics(); + }); + } + + private async loadRevision(file: TFile): Promise { const revision = `${file.stat.mtime}:${file.stat.size}`; const previous = this.reader; if (previous?.sourcePath === file.path && previous.revision === revision) { - return; + return true; } const generation = ++this.loadGeneration; const sameNotebook = previous?.sourcePath === file.path; @@ -306,13 +402,13 @@ export class SupernoteNoteView extends FileView { }); } catch (error) { if (generation !== this.loadGeneration) { - return; + return false; } throw error; } if (generation !== this.loadGeneration) { session.close(); - return; + return false; } const pageOpen = planPageOpen( this.pendingPage, @@ -328,17 +424,15 @@ export class SupernoteNoteView extends FileView { ); let replacementHandle: NotebookBitmapHandle | null = null; try { - const admission = session.updateView({ + const update = session.updateView({ visible: true, currentPage: handoff.currentPage, gridOpen: false, canvasBytes: 0, }); - if (!admission.admitted) { + if (!update.updated) { throw new Error( - admission.reason === "resource-budget" - ? "Could not reserve memory for the updated Supernote notebook." - : "Supernote rendering is unavailable for the updated notebook.", + "Supernote rendering is unavailable for the updated notebook.", ); } replacementHandle = await session.bitmap(handoff.currentPage); @@ -346,7 +440,7 @@ export class SupernoteNoteView extends FileView { replacementHandle?.release(); session.close(); if (generation !== this.loadGeneration) { - return; + return false; } if (sameNotebook && previous) { new Notice( @@ -357,14 +451,14 @@ export class SupernoteNoteView extends FileView { } Reopen the note or sync again to retry.`, 10_000, ); - return; + return true; } throw error; } if (generation !== this.loadGeneration) { replacementHandle.release(); session.close(); - return; + return false; } const staging = this.contentEl.createDiv({ cls: "supernote-reader-staging", @@ -406,14 +500,14 @@ export class SupernoteNoteView extends FileView { } Reopen the note or sync again to retry.`, 10_000, ); - return; + return true; } throw error; } - if (sameNotebook && previous && replacement.rejectedInitialPageAdmission) { + if (sameNotebook && previous && replacement.initialPagePreparationFailed) { replacement.destroy(); staging.remove(); - return; + return true; } previous?.destroy(); replacement.attachTo(this.contentEl); @@ -436,6 +530,7 @@ export class SupernoteNoteView extends FileView { session.descriptor.pageCount, ); } + return true; } private reportUnavailablePage( diff --git a/src/viewer/notebook-embed.ts b/src/viewer/notebook-embed.ts index 3f7b2cb..3632fef 100644 --- a/src/viewer/notebook-embed.ts +++ b/src/viewer/notebook-embed.ts @@ -201,16 +201,14 @@ export class NotebookEmbedRenderer { this.displayedPage = this.clamp(this.displayedPage); this.desiredPage = this.displayedPage; this.options.target.pageChanged(this.displayedPage, this.totalPages); - const admission = opened.updateView({ + const update = opened.updateView({ visible: true, currentPage: this.displayedPage, gridOpen: false, canvasBytes: 0, }); - if (!admission.admitted) { - this.fail( - `Not enough display memory to open ${this.options.path.split("/").at(-1) ?? this.options.path}.`, - ); + if (!update.updated) { + this.fail("Supernote rendering is unavailable."); return; } await this.renderPage(opened, this.displayedPage); @@ -243,18 +241,18 @@ export class NotebookEmbedRenderer { this.cancelRender(); const previousPage = this.displayedPage; const previousBytes = this.canvasBytes; - const currentAdmission = session.updateView({ + const currentUpdate = session.updateView({ visible: true, currentPage: pageNumber, gridOpen: false, canvasBytes: previousBytes, }); - if (!currentAdmission.admitted) { + if (!currentUpdate.updated) { this.rejectNavigation( session, previousPage, previousBytes, - `Not enough display memory to render page ${pageNumber}.`, + "Supernote rendering is unavailable.", ); return; } @@ -294,18 +292,18 @@ export class NotebookEmbedRenderer { displayHeight: box.height, devicePixelRatio: box.devicePixelRatio, }); - const admission = session.updateView({ + const update = session.updateView({ visible: true, currentPage: pageNumber, gridOpen: false, canvasBytes: backing.bytes, }); - if (!admission.admitted) { + if (!update.updated) { this.rejectNavigation( session, previousPage, previousBytes, - `Not enough display memory to render page ${pageNumber}.`, + "Supernote rendering is unavailable.", ); return; } diff --git a/src/viewer/pager-motion.ts b/src/viewer/pager-motion.ts index c8bb707..c3f1cd4 100644 --- a/src/viewer/pager-motion.ts +++ b/src/viewer/pager-motion.ts @@ -52,14 +52,14 @@ export const pageTransition = ( }; }; -export const admittedPageTransition = ( +export const preparedPageTransition = ( currentPage: number, targetPage: number, rtl: boolean, - admitTarget: (pageNumber: number) => boolean, + prepareTarget: (pageNumber: number) => boolean, ): PageTransition | null => { const transition = pageTransition(currentPage, targetPage, rtl); - return transition && admitTarget(targetPage) ? transition : null; + return transition && prepareTarget(targetPage) ? transition : null; }; export const pageTransitionRenderTarget = ( diff --git a/src/viewer/reader-toolbar.ts b/src/viewer/reader-toolbar.ts index 29c5d8c..6f76e18 100644 --- a/src/viewer/reader-toolbar.ts +++ b/src/viewer/reader-toolbar.ts @@ -2,6 +2,8 @@ export type ReaderToolbarMode = "pager" | "grid"; export type ReaderToolbarActionId = | "pages" + | "zoom-out" + | "zoom-in" | "copy-page" | "copy-notebook" | "export-current" @@ -13,10 +15,13 @@ export interface ReaderToolbarContext { mode: ReaderToolbarMode; selecting: boolean; selectedPages: number; + canZoomOut: boolean; + canZoomIn: boolean; } export interface ReaderToolbarState extends ReaderToolbarContext { compact: boolean; + showZoomControls: boolean; } export interface ReaderToolbarAction { @@ -36,6 +41,8 @@ export const READER_TOOLBAR_ACTION_CATALOG: Readonly< Record > = { pages: { icon: "layout-grid", label: "Pages" }, + "zoom-out": { icon: "zoom-out", label: "Zoom out" }, + "zoom-in": { icon: "zoom-in", label: "Zoom in" }, "copy-page": { icon: "copy", label: "Copy current page embed" }, "copy-notebook": { icon: "notebook", label: "Copy notebook embed" }, "export-current": { icon: "download", label: "Export current page" }, @@ -103,8 +110,21 @@ const catalogAction = (id: ReaderToolbarActionId): ReaderToolbarAction => { export const readerToolbarPresentation = ( state: ReaderToolbarState, ): ReaderToolbarPresentation => { + const zoomActions = state.showZoomControls + ? [ + { + ...catalogAction("zoom-out"), + disabled: !state.canZoomOut, + }, + { + ...catalogAction("zoom-in"), + disabled: !state.canZoomIn, + }, + ] + : []; const pagerActions = [ catalogAction("pages"), + ...zoomActions, catalogAction("copy-page"), catalogAction("copy-notebook"), catalogAction("export-current"), diff --git a/styles.css b/styles.css index f960b5a..07aaf9f 100644 --- a/styles.css +++ b/styles.css @@ -28,12 +28,28 @@ } .supernote-sync-file-name { + display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.supernote-sync-file-description { + min-width: 0; +} + +.supernote-sync-file-subtitle { + color: var(--text-muted); + display: block; + font-size: var(--font-ui-smaller); + margin-block-start: 2px; +} + +.supernote-sync-file-subtitle.is-error { + color: var(--text-error); +} + .supernote-sync-status { background: var(--background-modifier-hover); border-radius: var(--radius-s); @@ -161,6 +177,10 @@ width: 100%; } +.supernote-sync-browser-results { + width: 100%; +} + .supernote-sync-file-primary { align-items: center; color: var(--text-normal); @@ -219,19 +239,232 @@ padding-inline-start: var(--size-4-2); } -@media (max-width: 600px) { - .supernote-sync-browser-modal { - height: calc(100vh - 24px); - width: calc(100vw - 16px); +.supernote-sync-browser-modal.is-mobile { + bottom: auto; + height: calc( + 100vh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - + 16px + ); + height: calc( + 100dvh - env(safe-area-inset-top, 0px) - env(safe-area-inset-bottom, 0px) - + 16px + ); + left: 8px; + margin: 0; + max-height: none; + max-width: none; + position: absolute; + right: 8px; + top: calc(env(safe-area-inset-top, 0px) + 8px); + transform: none; + width: auto; +} + +.supernote-sync-browser-modal.is-mobile .modal-title { + min-height: 44px; + padding-inline-end: 56px; +} + +.supernote-sync-browser-modal.is-mobile .modal-close-button { + height: 44px; + right: var(--size-4-2); + top: var(--size-4-2); + width: 44px; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-browser-navigation { + margin-block-end: var(--size-4-2); + min-height: 44px; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-browser-breadcrumbs { + gap: var(--size-4-2); + overflow: hidden; +} + +.supernote-sync-browser-mobile-location { + font-size: var(--font-ui-medium); + font-weight: var(--font-semibold); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-browser-current-action { + min-width: 44px; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-browser-list { + border-block-start: 0; + padding-block-start: 0; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-row { + align-items: center; + border-block-end: 1px solid var(--background-modifier-border); + border-radius: 0; + gap: var(--size-4-2); + min-height: 68px; + padding: var(--size-4-2) var(--size-4-1); +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-row:active { + background: var(--background-modifier-hover); +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-primary { + pointer-events: none; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-icon { + align-items: center; + display: inline-flex; + height: 36px; + justify-content: center; + width: 36px; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-description { + flex: 1; +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-name { + font-size: var(--font-ui-medium); +} + +.supernote-sync-browser-modal.is-mobile .supernote-sync-file-controls { + align-items: center; + min-height: 44px; + min-width: 44px; +} + +.supernote-sync-file-trailing-icon { + align-items: center; + color: var(--text-muted); + display: inline-flex; + justify-content: center; + min-height: 44px; + min-width: 44px; +} + +.supernote-sync-file-trailing-icon.is-spinning { + animation: supernote-sync-spin 900ms linear infinite; +} + +.supernote-sync-file-action-spinner { + align-items: center; + display: inline-flex; + margin-inline-end: var(--size-4-1); +} + +.supernote-sync-file-action-spinner.is-spinning { + animation: supernote-sync-spin 900ms linear infinite; +} + +.supernote-sync-browser-skeletons { + width: 100%; +} + +.supernote-sync-browser-skeleton-row { + align-items: center; + border-block-end: 1px solid var(--background-modifier-border); + display: flex; + gap: var(--size-4-2); + min-height: 68px; + padding: var(--size-4-2) var(--size-4-1); +} + +.supernote-sync-browser-skeleton-icon, +.supernote-sync-browser-skeleton-name, +.supernote-sync-browser-skeleton-subtitle { + animation: supernote-sync-skeleton 1.2s ease-in-out infinite; + background: color-mix( + in srgb, + var(--background-modifier-hover) 78%, + var(--text-faint) + ); + border-radius: var(--radius-s); + display: block; +} + +.supernote-sync-browser-skeleton-icon { + border-radius: var(--radius-m); + height: 32px; + width: 32px; +} + +.supernote-sync-browser-skeleton-text { + flex: 1; +} + +.supernote-sync-browser-skeleton-name { + height: 12px; + max-width: 240px; + width: 64%; +} + +.supernote-sync-browser-skeleton-subtitle { + height: 9px; + margin-block-start: 8px; + width: 34%; +} + +.supernote-sync-browser-results.is-entering-forward, +.supernote-sync-browser-skeletons.is-entering-forward { + animation: supernote-sync-enter-forward 180ms ease-out; +} + +.supernote-sync-browser-results.is-entering-back, +.supernote-sync-browser-skeletons.is-entering-back { + animation: supernote-sync-enter-back 180ms ease-out; +} + +.supernote-sync-browser-results.is-entering, +.supernote-sync-browser-skeletons.is-entering { + animation: supernote-sync-enter 150ms ease-out; +} + +@keyframes supernote-sync-enter-forward { + from { + opacity: 0; + transform: translateX(14px); + } +} + +@keyframes supernote-sync-enter-back { + from { + opacity: 0; + transform: translateX(-14px); } +} - .supernote-sync-file-row { - align-items: flex-start; +@keyframes supernote-sync-enter { + from { + opacity: 0; } +} - .supernote-sync-file-controls { - align-items: flex-end; - flex-direction: column; +@keyframes supernote-sync-skeleton { + 50% { + opacity: 0.48; + } +} + +@keyframes supernote-sync-spin { + to { + transform: rotate(360deg); + } +} + +@media (prefers-reduced-motion: reduce) { + .supernote-sync-browser-results, + .supernote-sync-browser-skeletons, + .supernote-sync-file-trailing-icon.is-spinning, + .supernote-sync-file-action-spinner.is-spinning, + .supernote-sync-browser-skeleton-icon, + .supernote-sync-browser-skeleton-name, + .supernote-sync-browser-skeleton-subtitle { + animation: none; } } @@ -385,13 +618,11 @@ visibility: hidden; } -.supernote-reader.is-chrome-hidden .supernote-reader-bottombar, -.supernote-reader.is-chrome-hidden .supernote-reader-zoom-control { +.supernote-reader.is-chrome-hidden .supernote-reader-bottombar { pointer-events: none; } -.supernote-reader-bottombar, -.supernote-reader-zoom-control { +.supernote-reader-bottombar { align-items: center; backdrop-filter: blur(14px); background: var(--supernote-reader-chrome); @@ -410,57 +641,43 @@ transform: translateX(-50%); } -.supernote-reader-zoom-control { - border-radius: var(--radius-l); - bottom: var(--size-4-3); - direction: ltr; - right: var(--size-4-3); +.supernote-reader-icon { + color: inherit; } -.supernote-reader-zoom-button, -.supernote-reader-zoom-value { - align-items: center; - display: inline-flex; - justify-content: center; - min-height: 44px; +.supernote-reader-counter { + min-width: 72px; + text-align: center; } -.supernote-reader-zoom-button { - min-width: 44px; +.is-mobile .supernote-reader-bottombar { + border: 1px solid var(--background-modifier-border); + bottom: calc(env(safe-area-inset-bottom, 0px) + var(--size-4-2)); + box-shadow: var(--shadow-s); + gap: 0; + min-height: 52px; + padding: var(--size-2-2); } -.supernote-reader-zoom-value { +.is-mobile .supernote-reader-bottombar button { background: transparent; border: 0; box-shadow: none; - color: inherit; - font: inherit; - min-width: 58px; - padding: 0 var(--size-4-1); + min-height: 44px; + min-width: 44px; + padding: var(--size-4-2); } -.supernote-reader-zoom-value:hover, -.supernote-reader-zoom-value:focus-visible { +.is-mobile .supernote-reader-bottombar button:hover, +.is-mobile .supernote-reader-bottombar button:focus-visible { background: var(--background-modifier-hover); box-shadow: none; } -.supernote-reader-icon { - color: inherit; -} - -.supernote-reader-counter { - min-width: 72px; - text-align: center; -} - -@media (max-width: 600px) { - .supernote-reader-zoom-control { - bottom: calc(var(--size-4-3) + 60px); - left: 50%; - right: auto; - transform: translateX(-50%); - } +.is-mobile .supernote-reader-counter { + font-size: var(--font-ui-medium); + min-width: 76px; + padding-inline: var(--size-4-1); } .supernote-reader.is-grid { diff --git a/tests/api-ocr.test.ts b/tests/api-ocr.test.ts index 38f32c7..6281bfd 100644 --- a/tests/api-ocr.test.ts +++ b/tests/api-ocr.test.ts @@ -168,8 +168,11 @@ describe("ApiOcrService", () => { expect(result.documentText).toBe("# Heading\n\n- one\n- two"); }); - it("rejects an oversized document before constructing or sending its body", async () => { - const request = vi.fn(); + it("does not use a Performance budget to reject a document request", async () => { + const request = vi.fn(async () => ({ + status: 200, + json: { choices: [{ message: { content: "complete document" } }] }, + })); const render = vi.fn(async () => new Uint8Array(100_000)); const service = new ApiOcrService({ baseUrl: "https://openrouter.ai/api/v1", @@ -177,7 +180,6 @@ describe("ApiOcrService", () => { model: "vision/model", extraInstructions: "", request, - documentRequestByteLimit: 1_000, }); const result = await service.transcribe({ @@ -189,11 +191,11 @@ describe("ApiOcrService", () => { }, }); - expect(render).toHaveBeenCalledTimes(1); - expect(request).not.toHaveBeenCalled(); - expect(result.failedPages).toEqual([1, 2]); - expect(result.errors[0]).toContain("page mode"); - expect(result.errors[0]).toContain("fewer pages"); + expect(render).toHaveBeenCalledTimes(2); + expect(request).toHaveBeenCalledOnce(); + expect(result.documentText).toBe("complete document"); + expect(result.failedPages).toEqual([]); + expect(result.errors).toEqual([]); }); it("encodes multi-chunk image bytes without changing the request payload", async () => { diff --git a/tests/cloud-browser-presentation.test.ts b/tests/cloud-browser-presentation.test.ts new file mode 100644 index 0000000..159aaa3 --- /dev/null +++ b/tests/cloud-browser-presentation.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; + +import { cloudBrowserFilePresentation } from "../src/ui/cloud-browser-presentation"; + +describe("Cloud browser file presentation", () => { + it("describes the action a user gets by opening a file", () => { + expect(cloudBrowserFilePresentation("not-synced")).toEqual({ + statusLabel: "Cloud only", + actionLabel: "Download and open", + trailingIcon: "download", + }); + expect(cloudBrowserFilePresentation("downloaded")).toEqual({ + statusLabel: "Downloaded", + actionLabel: "Open", + trailingIcon: "chevron-right", + }); + expect(cloudBrowserFilePresentation("update-available")).toEqual({ + statusLabel: "Update available", + actionLabel: "Update and open", + trailingIcon: "refresh-cw", + }); + expect(cloudBrowserFilePresentation("included").statusLabel).toBe( + "Mirrored", + ); + expect(cloudBrowserFilePresentation("writable-sync").statusLabel).toBe( + "Paired", + ); + }); +}); diff --git a/tests/diagnostics.test.ts b/tests/diagnostics.test.ts index 3f5c05b..7c7e370 100644 --- a/tests/diagnostics.test.ts +++ b/tests/diagnostics.test.ts @@ -138,4 +138,48 @@ describe("diagnostics report", () => { homeRelativePath("/Users/alice-other/tool", "/Users/alice", "darwin"), ).toBe("[absolute path outside home omitted]"); }); + + it("includes bounded allowlisted performance evidence without operation paths", () => { + const report = renderDiagnosticsReport({ + pluginVersion: "0.1.0", + obsidianVersion: "1.12.7", + platform: "ios", + architecture: "unknown", + mode: "mobile", + engine: "api", + sessionActive: true, + apiKeySet: false, + agentStatuses: { + claude: { state: "unavailable", reason: "not-found" }, + codex: { state: "unavailable", reason: "not-found" }, + }, + prerequisites, + mirroredFileCount: 13, + lastSyncOutcome: "succeeded", + homeDirectory: null, + paths: { + vault: "not available", + transcriptionCommand: "", + temporaryBatches: [], + }, + performance: [ + { + kind: "notebook-open", + outcome: "failed", + durationMs: 42, + peakTrackedBytes: 106_527_410, + settledTrackedBytes: 0, + cleanup: "released", + failureCategory: "allocation", + }, + ], + }); + + expect(report).toContain("performance:"); + expect(report).toContain( + "notebook-open: failed, duration=42ms, peak=106527410, settled=0, cleanup=released, failure=allocation", + ); + expect(report).not.toContain("Journal"); + expect(report).not.toContain(".note"); + }); }); diff --git a/tests/fixed-page-embed.test.ts b/tests/fixed-page-embed.test.ts index 5734f9f..b26ef55 100644 --- a/tests/fixed-page-embed.test.ts +++ b/tests/fixed-page-embed.test.ts @@ -44,7 +44,7 @@ const bitmap = { const createLease = ( options: { pageCount?: number; - admission?: "admitted" | "rejected"; + viewUpdate?: "updated" | "unavailable"; bitmapPromise?: Promise; } = {}, ): NotebookSessionLease => { @@ -63,9 +63,9 @@ const createLease = ( updateView: vi .fn() .mockImplementation(() => - options.admission === "rejected" - ? { admitted: false, reason: "resource-budget" } - : { admitted: true }, + options.viewUpdate === "unavailable" + ? { updated: false, reason: "unavailable" } + : { updated: true }, ), close: vi.fn(), }; @@ -216,7 +216,7 @@ describe("fixed page embed authoring and accessibility", () => { }); describe("fixed page embed render lifecycle", () => { - it("does no notebook work until admitted near the viewport", async () => { + it("does no notebook work until activated near the viewport", async () => { const lease = createLease(); const notebooks: NotebookSessionProvider = { open: vi.fn().mockResolvedValue(lease), @@ -368,8 +368,8 @@ describe("fixed page embed render lifecycle", () => { expect(shorter.close).toHaveBeenCalledOnce(); }); - it("keeps an admission failure local and never allocates the canvas", async () => { - const lease = createLease({ admission: "rejected" }); + it("keeps an unavailable session local and never allocates the canvas", async () => { + const lease = createLease({ viewUpdate: "unavailable" }); const target = createTarget(); const renderer = new FixedPageEmbedRenderer({ notebooks: { open: vi.fn().mockResolvedValue(lease) }, @@ -383,7 +383,7 @@ describe("fixed page embed render lifecycle", () => { await vi.waitFor(() => expect(target.show).toHaveBeenCalledWith( "unavailable", - "Not enough display memory to render page 12.", + "Supernote rendering is unavailable.", ), ); @@ -391,7 +391,7 @@ describe("fixed page embed render lifecycle", () => { expect(lease.close).toHaveBeenCalledOnce(); }); - it("opens only admitted members of a 100-embed fixture", async () => { + it("opens only activated members of a 100-embed fixture", async () => { const notebooks: NotebookSessionProvider = { open: vi.fn().mockImplementation(() => Promise.resolve(createLease())), }; diff --git a/tests/instance-state.test.ts b/tests/instance-state.test.ts index 3d8ad11..301e2d4 100644 --- a/tests/instance-state.test.ts +++ b/tests/instance-state.test.ts @@ -23,7 +23,7 @@ describe("InstanceStateStore", () => { ); }); - it("round-trips the session, controls, Pair baseline, and last Send destination", () => { + it("round-trips session, controls, Pair state, and device-local diagnostics", () => { const storage = new MemoryLocalStorage(); const store = new InstanceStateStore(storage); const state = { @@ -41,6 +41,17 @@ describe("InstanceStateStore", () => { initialized: true, }, }, + performanceDiagnostics: { + active: [ + { + id: "notebook-open-1", + kind: "notebook-open" as const, + scope: "opaque-scope", + startedAtMs: 100, + }, + ], + recent: [], + }, }; store.save(state); diff --git a/tests/markdown-pdf.test.ts b/tests/markdown-pdf.test.ts index dae048f..241a171 100644 --- a/tests/markdown-pdf.test.ts +++ b/tests/markdown-pdf.test.ts @@ -5,13 +5,13 @@ import { MarkdownPdfRenderer } from "../src/export/markdown-pdf"; import { pdfBoldFontBytes, pdfRegularFontBytes } from "./pdf-font-fixture"; describe("MarkdownPdfRenderer", () => { - it("subsets fonts while preserving selectable Unicode text", async () => { + it("embeds complete fonts for broad PDF viewer compatibility", async () => { const bytes = await new MarkdownPdfRenderer( pdfRegularFontBytes, pdfBoldFontBytes, ).render("# Résumé • Codex Markdown"); - expect(bytes.byteLength).toBeLessThan(100_000); + expect(bytes.byteLength).toBeGreaterThan(500_000); const pdf = await getDocument({ data: bytes }).promise; const content = await (await pdf.getPage(1)).getTextContent(); expect( diff --git a/tests/notebook-embed.test.ts b/tests/notebook-embed.test.ts index 6590320..1b14e97 100644 --- a/tests/notebook-embed.test.ts +++ b/tests/notebook-embed.test.ts @@ -64,7 +64,7 @@ const createLease = ( Promise.resolve(createHandle(pageNumber)), ), renderPng: vi.fn(), - updateView: vi.fn().mockReturnValue({ admitted: true }), + updateView: vi.fn().mockReturnValue({ updated: true }), close: vi.fn(), }); @@ -334,7 +334,7 @@ describe("bounded notebook embed render lifecycle", () => { expect(target.draw).toHaveBeenCalledTimes(2); }); - it("never retains more than one admitted canvas allocation", async () => { + it("never retains more than one prepared canvas allocation", async () => { const lease = createLease(); const { renderer, target } = createRenderer({ open: vi.fn().mockResolvedValue(lease), @@ -355,7 +355,7 @@ describe("bounded notebook embed render lifecycle", () => { }); }); - it("opens only admitted members of a 100-embed fixture", async () => { + it("opens only activated members of a 100-embed fixture", async () => { const notebooks: NotebookSessionProvider = { open: vi.fn().mockImplementation(() => Promise.resolve(createLease())), }; diff --git a/tests/notebook-service.test.ts b/tests/notebook-service.test.ts index 3a0bff1..76d31b9 100644 --- a/tests/notebook-service.test.ts +++ b/tests/notebook-service.test.ts @@ -176,12 +176,12 @@ describe("NotebookService", () => { first.close(); expect( worker.requests.filter((request) => request.type === "close"), - ).toHaveLength(0); + ).toHaveLength(1); second.close(); expect( worker.requests.filter((request) => request.type === "close"), - ).toHaveLength(0); + ).toHaveLength(1); retained.close(); expect( worker.requests.filter((request) => request.type === "close"), @@ -429,7 +429,7 @@ describe("NotebookService", () => { canvasBytes: 0, }), ).toMatchObject({ - admitted: false, + updated: false, reason: "unavailable", }); expect(() => lease.close()).not.toThrow(); @@ -439,11 +439,10 @@ describe("NotebookService", () => { expect(notifyRenderingUnavailable).toHaveBeenCalledOnce(); }); - it("rejects a larger canvas allocation without changing the admitted view", async () => { + it("tracks a larger canvas allocation without rejecting the view", async () => { const worker = new ScriptedWorker(); const service = new NotebookService({ createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 20, }); const lease = await service.open({ path: descriptor.path, @@ -458,7 +457,7 @@ describe("NotebookService", () => { gridOpen: false, canvasBytes: 4, }), - ).toEqual({ admitted: true }); + ).toEqual({ updated: true }); expect(service.snapshot().retainedCanvasBytes).toBe(4); expect( @@ -468,13 +467,10 @@ describe("NotebookService", () => { gridOpen: false, canvasBytes: 18, }), - ).toMatchObject({ - admitted: false, - reason: "resource-budget", - }); + ).toEqual({ updated: true }); expect(service.snapshot()).toMatchObject({ - retainedCanvasBytes: 4, - retainedBytes: 7, + retainedCanvasBytes: 18, + retainedBytes: 21, }); lease.close(); @@ -771,6 +767,76 @@ describe("NotebookService", () => { lease.close(); }); + it("keeps explicit exports queued beyond speculative backpressure", async () => { + const worker = new ScriptedWorker(); + const service = new NotebookService({ + createWorker: () => worker as unknown as Worker, + maxConcurrentRenders: 1, + maxQueuedRenders: 1, + }); + const lease = await service.open({ + path: descriptor.path, + revision: descriptor.revision, + bytes: new Uint8Array([1, 2, 3]), + }); + lease.updateView({ + visible: true, + currentPage: 1, + gridOpen: false, + }); + + const display = lease.bitmap(1); + const firstExport = lease.renderPng(1); + const secondExport = lease.renderPng(2); + + expect(service.snapshot()).toMatchObject({ + queuedRenders: 2, + cancelledRenders: 0, + }); + + const displayRequest = worker.requests.find( + ( + request, + ): request is Extract => + request.type === "render", + )!; + worker.respondBitmap(displayRequest); + (await display).release(); + + for (const expectedPage of [1, 2]) { + await vi.waitFor(() => { + expect( + worker.requests.filter((request) => request.type === "render"), + ).toHaveLength(expectedPage + 1); + }); + const request = worker.requests.filter( + ( + candidate, + ): candidate is Extract => + candidate.type === "render", + )[expectedPage]!; + expect(request).toMatchObject({ + output: "png", + pageNumber: expectedPage, + }); + worker.onmessage?.({ + data: { + type: "rendered", + id: request.id, + sessionId: request.sessionId, + generation: request.generation, + output: "png", + page: { png: new Uint8Array([expectedPage]), width: 5, height: 1 }, + }, + } as MessageEvent); + } + + await expect(firstExport).resolves.toMatchObject({ width: 5, height: 1 }); + await expect(secondExport).resolves.toMatchObject({ width: 5, height: 1 }); + expect(service.snapshot().cancelledRenders).toBe(0); + lease.close(); + }); + it("cancels a bitmap render when its final waiter aborts", async () => { const worker = new ScriptedWorker(); const service = new NotebookService({ @@ -892,63 +958,59 @@ describe("NotebookService", () => { lease.close(); }); - it("evicts and reloads hidden worker sources to enforce the global budget", async () => { + it("suspends and reloads an inactive worker source", async () => { const worker = new ScriptedWorker(); worker.descriptorMetadataBytes = 2; const service = new NotebookService({ createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 24, }); const loadFirst = vi.fn(async () => new Uint8Array([1, 2, 3, 4])); - const loadSecond = vi.fn(async () => new Uint8Array([5, 6, 7, 8])); const firstSource = { path: "supernote/First.note", revision: "mtime:1", load: loadFirst, }; - const secondSource = { - path: "supernote/Second.note", - revision: "mtime:1", - load: loadSecond, - }; const first = await service.open(firstSource); - const second = await service.open(secondSource); - - expect(service.snapshot()).toMatchObject({ - activeSessions: 2, - retainedSourceBytes: 4, - retainedParsedBytes: 4, - retainedBytes: 8, - sessions: [ - expect.objectContaining({ path: firstSource.path, parsedBytes: 2 }), - expect.objectContaining({ path: secondSource.path, parsedBytes: 2 }), - ], + first.updateView({ + visible: true, + currentPage: 1, + gridOpen: false, + }); + first.updateView({ + visible: false, + currentPage: null, + gridOpen: false, }); + expect( worker.requests.filter((request) => request.type === "close"), ).toHaveLength(1); + expect(service.snapshot()).toMatchObject({ + activeSessions: 1, + retainedSourceBytes: 0, + retainedParsedBytes: 2, + }); const sharedFirst = await service.open(firstSource); expect(loadFirst).toHaveBeenCalledTimes(2); - expect(loadSecond).toHaveBeenCalledTimes(1); - expect(service.snapshot().retainedBytes).toBeLessThanOrEqual(24); + expect(service.snapshot()).toMatchObject({ + retainedSourceBytes: 4, + retainedParsedBytes: 2, + }); expect( worker.requests.filter((request) => request.type === "open"), - ).toHaveLength(3); + ).toHaveLength(2); sharedFirst.close(); first.close(); - second.close(); }); - it("reclaims a visible reloadable source for bounded notebook inspection", async () => { + it("keeps a visible source resident during notebook inspection", async () => { const worker = new ScriptedWorker(); worker.descriptorMetadataBytes = 2; const service = new NotebookService({ createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 24, - transientResourceBudgetBytes: 32, }); const loadVisible = vi.fn(async () => new Uint8Array([1, 2, 3, 4])); const visibleSource = { @@ -963,19 +1025,14 @@ describe("NotebookService", () => { gridOpen: false, }); - const inspection = await service.open( - { - path: "candidate:changed:supernote/Changed.note", - revision: "changed", - bytes: new Uint8Array([5, 6, 7, 8]), - transfer: "copy", - }, - { reclaim: "reloadable", budget: "transient" }, - ); + const inspection = await service.open({ + path: "candidate:changed:supernote/Changed.note", + revision: "changed", + bytes: new Uint8Array([5, 6, 7, 8]), + transfer: "copy", + }); expect(service.snapshot()).toMatchObject({ - budgetBytes: 24, - transientBudgetBytes: 32, retainedBytes: 12, sessions: [ expect.objectContaining({ @@ -1001,48 +1058,28 @@ describe("NotebookService", () => { visible.close(); }); - it("keeps transient notebook inspection within its separate ceiling", async () => { + it("opens a source beyond the former global resource budget boundary", async () => { const worker = new ScriptedWorker(); const service = new NotebookService({ createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 24, - transientResourceBudgetBytes: 32, }); + const sourceBytes = 26 * 1024 * 1024; - await expect( - service.open( - { - path: "candidate:oversized:supernote/Oversized.note", - revision: "oversized", - bytes: new Uint8Array(7), - transfer: "copy", - }, - { reclaim: "reloadable", budget: "transient" }, - ), - ).rejects.toThrow("source exceeds the 32-byte resource budget"); - expect(service.snapshot().retainedBytes).toBe(0); - }); - - it("rejects a source that cannot fit inside the global resource budget", async () => { - const worker = new ScriptedWorker(); - const service = new NotebookService({ - createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 3, + const lease = await service.open({ + path: descriptor.path, + revision: descriptor.revision, + bytes: new Uint8Array(sourceBytes), }); - await expect( - service.open({ - path: descriptor.path, - revision: descriptor.revision, - bytes: new Uint8Array([1, 2, 3, 4]), - }), - ).rejects.toThrow("source exceeds the 3-byte resource budget"); expect(service.snapshot()).toMatchObject({ - activeSessions: 0, - retainedSourceBytes: 0, - retainedBytes: 0, + activeSessions: 1, + retainedSourceBytes: sourceBytes, + retainedParsedBytes: 0, }); - expect(worker.requests).toHaveLength(0); + expect(worker.requests).toHaveLength(1); + + lease.close(); + expect(service.snapshot().retainedBytes).toBe(0); }); it("reserves the bitmap-background decode peak", async () => { @@ -1061,7 +1098,6 @@ describe("NotebookService", () => { }; const service = new NotebookService({ createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 88, }); const lease = await service.open({ path: descriptor.path, @@ -1082,7 +1118,7 @@ describe("NotebookService", () => { lease.close(); }); - it("accounts mobile canvases and admits native PDF PNG export without duplicate bitmaps", async () => { + it("accounts mobile canvases and renders native PDF PNG without duplicate bitmaps", async () => { const worker = new ScriptedWorker(); worker.autoRender = true; worker.pageWidth = 1_920; @@ -1111,7 +1147,6 @@ describe("NotebookService", () => { }); const service = new NotebookService({ createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 96 * 1_024 * 1_024, maxConcurrentRenders: 1, }); const lease = await service.open({ @@ -1161,63 +1196,6 @@ describe("NotebookService", () => { lease.close(); }); - it("evicts least-recently-used unpinned bitmaps to stay inside the byte budget", async () => { - const worker = new ScriptedWorker(); - worker.autoRender = true; - let bitmapId = 0; - Object.defineProperty(worker, "bitmap", { - get: () => - ({ - id: ++bitmapId, - width: 5, - height: 2, - close: vi.fn(), - }) as unknown as ImageBitmap, - }); - const service = new NotebookService({ - createWorker: () => worker as unknown as Worker, - resourceBudgetBytes: 163, - }); - const lease = await service.open({ - path: descriptor.path, - revision: descriptor.revision, - bytes: new Uint8Array([1, 2, 3]), - }); - lease.updateView({ - visible: true, - currentPage: 1, - gridOpen: false, - }); - - (await lease.bitmap(1)).release(); - lease.updateView({ - visible: true, - currentPage: 1, - gridOpen: true, - }); - (await lease.thumbnailBitmap(1, 5)).release(); - (await lease.thumbnailBitmap(2, 5)).release(); - - expect(service.snapshot()).toMatchObject({ - budgetBytes: 163, - retainedSourceBytes: 3, - retainedBitmapBytes: 120, - retainedBytes: 123, - evictedBitmaps: 0, - }); - - (await lease.thumbnailBitmap(1, 4)).release(); - const snapshot = service.snapshot(); - expect(snapshot.retainedBytes).toBeLessThanOrEqual(163); - expect(snapshot.evictedBitmaps).toBe(1); - expect(snapshot.retainedBytes).toBe( - snapshot.retainedSourceBytes + - snapshot.retainedBitmapBytes + - snapshot.inFlightBytes, - ); - lease.close(); - }); - it("reuses one faithful display bitmap across presentation changes", async () => { const bitmap = { width: 5, @@ -1319,7 +1297,6 @@ describe("NotebookService", () => { const service = new NotebookService({ createWorker: () => worker as unknown as Worker, maxConcurrentRenders: 1, - resourceBudgetBytes: 80, }); const lease = await service.open({ path: descriptor.path, @@ -1353,7 +1330,7 @@ describe("NotebookService", () => { worker.requests.filter((request) => request.type === "render"), ).toHaveLength(2); }); - expect(firstBitmap.close).toHaveBeenCalledTimes(1); + expect(firstBitmap.close).not.toHaveBeenCalled(); const secondRequest = worker.requests.filter( ( request, @@ -1363,5 +1340,7 @@ describe("NotebookService", () => { worker.respondBitmap(secondRequest, secondBitmap); (await second).release(); lease.close(); + expect(firstBitmap.close).toHaveBeenCalledTimes(1); + expect(secondBitmap.close).toHaveBeenCalledTimes(1); }); }); diff --git a/tests/pager-motion.test.ts b/tests/pager-motion.test.ts index 394e0a6..4c909da 100644 --- a/tests/pager-motion.test.ts +++ b/tests/pager-motion.test.ts @@ -1,35 +1,35 @@ import { describe, expect, it } from "vitest"; import { - admittedPageTransition, navigationTarget, pageTransitionCommitDecision, pageTransitionRenderTarget, PagerSwipeGesture, pageTransition, + preparedPageTransition, reducedMotionRequested, } from "../src/viewer/pager-motion"; -describe("page transition admission", () => { - it("admits a non-adjacent target before rendering it", () => { - const admitted: number[] = []; +describe("page transition preparation", () => { + it("prepares a non-adjacent target before rendering it", () => { + const prepared: number[] = []; expect( - admittedPageTransition(2, 12, false, (pageNumber) => { - admitted.push(pageNumber); + preparedPageTransition(2, 12, false, (pageNumber) => { + prepared.push(pageNumber); return true; }), ).toEqual({ direction: "next", trackPercent: -200, }); - expect(admitted).toEqual([12]); + expect(prepared).toEqual([12]); expect(pageTransitionRenderTarget(2, 12)).toBe(12); expect(pageTransitionRenderTarget(2, null)).toBe(2); }); - it("does not begin a transition when target admission is rejected", () => { - expect(admittedPageTransition(2, 12, false, () => false)).toBeNull(); + it("does not begin a transition when target preparation fails", () => { + expect(preparedPageTransition(2, 12, false, () => false)).toBeNull(); }); it.each([ diff --git a/tests/performance-diagnostics.test.ts b/tests/performance-diagnostics.test.ts new file mode 100644 index 0000000..2b1ff32 --- /dev/null +++ b/tests/performance-diagnostics.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from "vitest"; + +import { + PerformanceDiagnostics, + performanceFailureCategory, + type PerformanceDiagnosticsSnapshot, +} from "../src/onboarding/performance-diagnostics"; + +describe("PerformanceDiagnostics", () => { + it("bounds completed operation evidence without storing user paths", () => { + let now = 1_000; + const diagnostics = new PerformanceDiagnostics(undefined, { + now: () => now, + capacity: 2, + }); + + for (const kind of ["notebook-open", "sync", "export"] as const) { + const operation = diagnostics.begin(kind); + now += 25; + diagnostics.finish(operation, { + outcome: "succeeded", + peakTrackedBytes: 100, + settledTrackedBytes: 10, + }); + } + + expect(diagnostics.snapshot()).toEqual({ + active: [], + recent: [ + { + kind: "sync", + outcome: "succeeded", + durationMs: 25, + peakTrackedBytes: 100, + settledTrackedBytes: 10, + cleanup: "retained", + failureCategory: null, + }, + { + kind: "export", + outcome: "succeeded", + durationMs: 25, + peakTrackedBytes: 100, + settledTrackedBytes: 10, + cleanup: "retained", + failureCategory: null, + }, + ], + }); + expect(JSON.stringify(diagnostics.snapshot())).not.toContain("/"); + }); + + it("turns unfinished persisted work into one consumable interruption", () => { + const persisted: PerformanceDiagnosticsSnapshot = { + active: [ + { + id: "operation-1", + kind: "notebook-open", + scope: "scope-1", + startedAtMs: 900, + }, + ], + recent: [], + }; + const diagnostics = new PerformanceDiagnostics(persisted, { + now: () => 1_000, + }); + + expect(diagnostics.consumeInterrupted("notebook-open", "scope-1")).toBe( + true, + ); + expect(diagnostics.consumeInterrupted("notebook-open", "scope-1")).toBe( + false, + ); + expect(diagnostics.snapshot()).toEqual({ + active: [], + recent: [ + { + kind: "notebook-open", + outcome: "interrupted", + durationMs: 100, + peakTrackedBytes: null, + settledTrackedBytes: null, + cleanup: "unknown", + failureCategory: "host-interrupted", + }, + ], + }); + }); + + it("does not consume an interrupted marker for a different notebook scope", () => { + const diagnostics = new PerformanceDiagnostics( + { + active: [ + { + id: "operation-1", + kind: "notebook-open", + scope: "scope-1", + startedAtMs: 900, + }, + ], + recent: [], + }, + { now: () => 1_000 }, + ); + + expect(diagnostics.consumeInterrupted("notebook-open", "scope-2")).toBe( + false, + ); + expect(diagnostics.consumeInterrupted("notebook-open", "scope-1")).toBe( + true, + ); + }); + + it("does not classify an explicitly cancelled operation as interrupted", () => { + const diagnostics = new PerformanceDiagnostics(undefined, { + now: () => 1_000, + }); + const operation = diagnostics.begin("notebook-open"); + + diagnostics.finish(operation, { + outcome: "cancelled", + peakTrackedBytes: null, + settledTrackedBytes: null, + }); + + expect(diagnostics.consumeInterrupted("notebook-open")).toBe(false); + expect(diagnostics.snapshot().recent[0]).toMatchObject({ + outcome: "cancelled", + failureCategory: null, + }); + }); + + it("clears active markers during a normal plugin shutdown", () => { + const diagnostics = new PerformanceDiagnostics(undefined, { + now: () => 1_000, + }); + diagnostics.begin("notebook-open"); + diagnostics.begin("sync"); + + diagnostics.cancelActive(); + + expect(diagnostics.snapshot().active).toEqual([]); + expect( + new PerformanceDiagnostics(diagnostics.snapshot(), { + now: () => 2_000, + }).consumeInterrupted("notebook-open"), + ).toBe(false); + }); + + it("classifies failures without persisting their message", () => { + expect(performanceFailureCategory(new Error("worker crashed"))).toBe( + "worker", + ); + expect(performanceFailureCategory(new Error("HTTP 503"))).toBe( + "network-or-api", + ); + expect(performanceFailureCategory(new Error("secret notebook title"))).toBe( + "unexpected", + ); + }); +}); diff --git a/tests/performance-harness.test.ts b/tests/performance-harness.test.ts index 00ec635..c6bd40e 100644 --- a/tests/performance-harness.test.ts +++ b/tests/performance-harness.test.ts @@ -1,13 +1,21 @@ +import { readFile } from "node:fs/promises"; + import { describe, expect, it } from "vitest"; import { + compareScenarioToBaseline, evaluateScenario, memorySummary, percentile, + regressionGatePassed, summarizeTimings, type ScenarioObservation, } from "../benchmarks/harness"; -import { parseArguments } from "../benchmarks/run"; +import { + parseArguments, + validateBaselineIdentity, + validateBaselineWorkload, +} from "../benchmarks/run"; import { blankRlePage, REFERENCE_GRID_PAGES, @@ -36,6 +44,22 @@ const observation = (): ScenarioObservation => ({ }); describe("performance harness", () => { + it("keeps numeric Performance-budget policy out of production operations", async () => { + const production = ( + await Promise.all( + [ + "../src/main.ts", + "../src/note/notebook-service.ts", + "../src/ocr/api-ocr.ts", + ].map((path) => readFile(new URL(path, import.meta.url), "utf8")), + ) + ).join("\n"); + + expect(production).not.toMatch( + /MOBILE_RENDER_BUDGET|DESKTOP_RENDER_BUDGET|DOCUMENT_REQUEST_BYTE_LIMIT|resource budget/i, + ); + }); + it("uses nearest-rank percentiles and keeps raw samples", () => { expect(percentile([5, 1, 4, 2, 3], 50)).toBe(3); expect(percentile([5, 1, 4, 2, 3], 95)).toBe(5); @@ -67,6 +91,52 @@ describe("performance harness", () => { }); }); + it("gates CI only on matching-baseline regressions, not absolute targets", () => { + expect(regressionGatePassed(false, [])).toBe(true); + expect( + regressionGatePassed(true, [ + { + metric: "duration", + baseline: 2, + actual: 3, + toleranceFraction: 0.2, + limit: 2.4, + passed: false, + }, + ]), + ).toBe(false); + }); + + it("fails a meaningful regression against a matching scenario baseline", () => { + const current = evaluateScenario(observation()); + const comparisons = compareScenarioToBaseline( + current, + { name: "test", metrics: { duration: 2 } }, + 0.2, + ); + + expect(comparisons).toEqual([ + { + metric: "duration", + baseline: 2, + actual: 3, + toleranceFraction: 0.2, + limit: 2.4, + passed: false, + }, + ]); + }); + + it("does not silently drop a metric required by the reviewed baseline", () => { + expect(() => + compareScenarioToBaseline( + evaluateScenario(observation()), + { name: "test", metrics: { missing: 2 } }, + 0.2, + ), + ).toThrow(/did not report baseline metric missing/); + }); + it("uses component timings for split startup long tasks", () => { const split = observation(); split.timings = summarizeTimings([50.1]); @@ -110,6 +180,37 @@ describe("performance harness", () => { profile: "smoke", record: true, scenarios: ["page-rendering", "run-log-streaming"], + tolerance: 0.2, }); }); + + it("rejects a baseline captured for a different execution profile", () => { + expect(() => + validateBaselineIdentity( + { + device: "iphone", + platform: "mobile", + profile: "standard", + }, + { + environment: { device: "desktop", platform: "desktop" }, + profile: "standard", + scenarios: [], + }, + ), + ).toThrow(/must match device, platform contract, and workload profile/); + }); + + it("rejects a same-profile baseline with a different scenario workload", () => { + expect(() => + validateBaselineWorkload( + { name: "page-rendering", workload: { pages: 20 } }, + { + name: "page-rendering", + workload: { pages: 10 }, + metrics: {}, + }, + ), + ).toThrow(/baseline workload does not match/); + }); }); diff --git a/tests/reader-toolbar.test.ts b/tests/reader-toolbar.test.ts index 119296b..7a78752 100644 --- a/tests/reader-toolbar.test.ts +++ b/tests/reader-toolbar.test.ts @@ -14,28 +14,61 @@ describe("Reader toolbar presentation", () => { compact: false, selecting: false, selectedPages: 0, + canZoomOut: false, + canZoomIn: true, + showZoomControls: true, }); expect(presentation.visibleActions.map((action) => action.id)).toEqual([ "pages", + "zoom-out", + "zoom-in", "copy-page", "copy-notebook", "export-current", ]); + expect(presentation.visibleActions.slice(1, 3)).toMatchObject([ + { id: "zoom-out", disabled: true }, + { id: "zoom-in", disabled: false }, + ]); expect(presentation.menuActions).toEqual([]); }); + it("leaves zoom entirely to gestures on mobile", () => { + const presentation = readerToolbarPresentation({ + mode: "pager", + compact: true, + selecting: false, + selectedPages: 0, + canZoomOut: true, + canZoomIn: true, + showZoomControls: false, + }); + + expect(presentation.menuActions.map((action) => action.id)).not.toContain( + "zoom-out", + ); + expect(presentation.menuActions.map((action) => action.id)).not.toContain( + "zoom-in", + ); + }); + it("moves the complete pager action group into the compact menu", () => { const presentation = readerToolbarPresentation({ mode: "pager", compact: true, selecting: false, selectedPages: 0, + canZoomOut: false, + canZoomIn: true, + showZoomControls: true, }); expect(presentation.visibleActions).toEqual([]); expect(presentation.menuActions.map((action) => action.id)).toEqual([ "pages", + "zoom-out", + "zoom-in", "copy-page", "copy-notebook", "export-current", @@ -48,6 +81,9 @@ describe("Reader toolbar presentation", () => { compact: false, selecting: true, selectedPages: 3, + canZoomOut: false, + canZoomIn: true, + showZoomControls: true, }); expect(presentation.visibleActions).toEqual([ @@ -82,6 +118,9 @@ describe("Reader toolbar presentation", () => { compact: false, selecting: false, selectedPages: 0, + canZoomOut: false, + canZoomIn: true, + showZoomControls: true, }); expect(presentation.visibleActions.at(-1)).toMatchObject({ diff --git a/tests/submission-polish.test.ts b/tests/submission-polish.test.ts index 6447f54..9933d61 100644 --- a/tests/submission-polish.test.ts +++ b/tests/submission-polish.test.ts @@ -36,4 +36,38 @@ describe("submission polish", () => { /#111|#f5f5f5|#333|rgb\(20 20 20\s*\/\s*72%\)/, ); }); + + it("keeps the mobile Cloud browser and close control inside iOS safe areas", async () => { + const browser = await source("../src/ui/folder-picker-modal.ts"); + const styles = await source("../styles.css"); + const mobileBrowserStyles = styles.slice( + styles.indexOf(".supernote-sync-browser-modal.is-mobile"), + styles.indexOf(".supernote-note-view"), + ); + + expect(browser).toContain( + 'this.modalEl.toggleClass("is-mobile", Platform.isMobile)', + ); + expect(mobileBrowserStyles).toContain("100dvh"); + expect(mobileBrowserStyles).toContain("env(safe-area-inset-top, 0px)"); + expect(mobileBrowserStyles).toContain("env(safe-area-inset-bottom, 0px)"); + expect(mobileBrowserStyles).toContain( + ".supernote-sync-browser-modal.is-mobile .modal-close-button", + ); + }); + + it("shares animated Cloud folder loading feedback across platforms", async () => { + const browser = await source("../src/ui/folder-picker-modal.ts"); + const loadingState = browser.slice( + browser.indexOf("private renderLoadingState("), + browser.indexOf("private transitionClass("), + ); + const styles = await source("../styles.css"); + + expect(loadingState).toContain("supernote-sync-browser-skeleton-row"); + expect(loadingState).not.toContain("Platform.isMobile"); + expect(styles).toContain("@keyframes supernote-sync-enter-forward"); + expect(styles).toContain("@keyframes supernote-sync-enter-back"); + expect(styles).toContain("@media (prefers-reduced-motion: reduce)"); + }); }); diff --git a/tests/sync-service.test.ts b/tests/sync-service.test.ts index b4ce747..e897409 100644 --- a/tests/sync-service.test.ts +++ b/tests/sync-service.test.ts @@ -330,7 +330,6 @@ describe("SyncService mirror", () => { ]); expect(notebooks.open).toHaveBeenCalledWith( expect.objectContaining({ transfer: "copy" }), - { reclaim: "reloadable", budget: "transient" }, ); expect( JSON.parse(vault.text.get("supernote/.sync-manifest.json") ?? "{}"), diff --git a/tests/worker-ownership-lifecycle.test.ts b/tests/worker-ownership-lifecycle.test.ts index 54c2bd9..5a44a21 100644 --- a/tests/worker-ownership-lifecycle.test.ts +++ b/tests/worker-ownership-lifecycle.test.ts @@ -56,7 +56,16 @@ describe("worker-owned notebook boundary", () => { expect(reader).not.toContain("canvas.getBoundingClientRect()"); expect(noteView).toContain('cls: "supernote-reader-staging"'); expect(noteView).not.toContain("staging.hidden = true"); - expect(noteView).toContain("replacement.rejectedInitialPageAdmission"); + expect(noteView).toContain("replacement.initialPagePreparationFailed"); + expect(noteView).toContain('text: "Retry"'); + expect(noteView).toContain('text: "Copy diagnostics"'); + expect(noteView).not.toContain("[DEBUG-ios-note-open]"); + expect( + noteView.slice( + noteView.indexOf("private renderOpenFailure"), + noteView.indexOf("private async loadRevision"), + ), + ).not.toContain("file.path"); expect(runtime).not.toContain("applyDarkDisplayTheme"); expect(runtime).not.toContain("decodedPages"); expect(styles).toContain(".theme-dark .supernote-reader-canvas"); @@ -67,7 +76,7 @@ describe("worker-owned notebook boundary", () => { expect(styles).toContain( ".supernote-generated-preview img.supernote-page-reader-trigger", ); - expect(main).toContain("MOBILE_RENDER_BUDGET_BYTES"); + expect(main).not.toContain("MOBILE_RENDER_BUDGET_BYTES"); expect(main).toContain("maxConcurrentRenders: Platform.isMobile ? 1 : 2"); }); }); diff --git a/versions.json b/versions.json index 3dee4a8..e8187f6 100644 --- a/versions.json +++ b/versions.json @@ -3,5 +3,6 @@ "1.0.0": "1.7.2", "1.0.1": "1.7.2", "1.0.2": "1.7.2", - "1.0.3": "1.7.2" + "1.0.3": "1.7.2", + "1.0.4": "1.7.2" }