From 28bc6e87a17e43d2afea37ff0a52f20237a471c4 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Thu, 29 Oct 2026 14:56:06 +0000 Subject: [PATCH 01/24] Make remote and log resource ownership explicit --- devs.md | 2 + package.json | 1 + src/common/ownedRemoteResource.ts | 10 +- src/common/ownedRemoteResource.unit.spec.ts | 44 +++ src/common/replicatorProviders.ts | 25 +- src/common/replicatorProviders.unit.spec.ts | 31 ++ src/common/replicatorResources/shared.ts | 10 +- .../replicatorResources/shared.unit.spec.ts | 42 ++ src/main.onunload.unit.spec.ts | 114 ++++++ src/main.ts | 17 +- src/modules/features/ModuleLog.ts | 77 ++-- src/modules/features/ModuleLog.unit.spec.ts | 228 +++++++++++ src/serviceFeatures/useJoinedDevices.ts | 17 +- .../useJoinedDevices.unit.spec.ts | 61 +++ test/e2e-obsidian/scripts/log-lifecycle.ts | 373 ++++++++++++++++++ test/e2e-obsidian/scripts/run-focused.ts | 1 + updates.md | 5 + 17 files changed, 987 insertions(+), 71 deletions(-) create mode 100644 src/common/replicatorResources/shared.unit.spec.ts create mode 100644 src/main.onunload.unit.spec.ts create mode 100644 src/modules/features/ModuleLog.unit.spec.ts create mode 100644 test/e2e-obsidian/scripts/log-lifecycle.ts diff --git a/devs.md b/devs.md index a9279f14..788d351b 100644 --- a/devs.md +++ b/devs.md @@ -277,6 +277,8 @@ The scenario uses only fixed in-memory inputs. It does not read or write the Vau - Dev mode creates `ls-debug/` folder in `.obsidian/` for debug outputs (e.g., missing translations) - This causes pretty significant performance overhead. +`ModuleLog` owns an `OwnedResource` for its `API.addLog.setHandler` registration and keeps service log input in a per-instance buffer. The host wraps the complete asynchronous `control.onUnload()` in `withOwnedResource`. On successful shutdown, the handler and its global and per-instance observers remain registered through the final database close and final unload log. If `control.onUnload()` rejects, `withOwnedResource` releases them when the operation settles. Do not release it from an `onBeforeUnload` or module `onUnload` handler; both run before the host's complete unload finishes. The import-time global `Logger` bridge and display and report histories remain shared, while service log calls stay with their owning instance. + #### Diagnostic and notice ownership - A Commonlib or service operation should normally record detailed diagnostics at `LOG_LEVEL_VERBOSE` and return a typed result which lets its caller distinguish complete, partial, and failed outcomes. Do not make callers infer an outcome by parsing log text. diff --git a/package.json b/package.json index 84e21ce5..a9efc5aa 100644 --- a/package.json +++ b/package.json @@ -100,6 +100,7 @@ "test:e2e:obsidian:customisation-sync": "tsx test/e2e-obsidian/scripts/customisation-sync.ts", "test:e2e:obsidian:customisation-catalogue-reload": "tsx test/e2e-obsidian/scripts/customisation-catalogue-reload.ts", "test:e2e:obsidian:optional-file-save-completion": "tsx test/e2e-obsidian/scripts/optional-file-save-completion.ts", + "test:e2e:obsidian:log-lifecycle": "tsx test/e2e-obsidian/scripts/log-lifecycle.ts", "test:e2e:obsidian:livesync-batch": "tsx test/e2e-obsidian/scripts/issue1207-livesync-batch.ts", "test:e2e:obsidian:received-change-readiness": "tsx test/e2e-obsidian/scripts/received-change-readiness.ts", "test:e2e:obsidian:remote-feature-change": "tsx test/e2e-obsidian/scripts/remote-feature-change.ts", diff --git a/src/common/ownedRemoteResource.ts b/src/common/ownedRemoteResource.ts index 60483414..19eaa1a3 100644 --- a/src/common/ownedRemoteResource.ts +++ b/src/common/ownedRemoteResource.ts @@ -1,3 +1,5 @@ +import { withOwnedResource, type DisposableResource } from "octagonal-wheels/resource"; + /** * Run a finite operation with a flow-owned remote resource and release it * after either success or failure. @@ -6,13 +8,9 @@ * caller's ownership boundary explicit and prevents finite flows from leaking * a provider-owned resource when their operation rejects. */ -export async function withOwnedRemoteResource }, TResult>( +export function withOwnedRemoteResource }, TResult>( resource: TResource, operation: (ownedResource: TResource) => Promise ): Promise { - try { - return await operation(resource); - } finally { - await resource.dispose(); - } + return withOwnedResource(resource, operation); } diff --git a/src/common/ownedRemoteResource.unit.spec.ts b/src/common/ownedRemoteResource.unit.spec.ts index 840acf7e..2eb042f9 100644 --- a/src/common/ownedRemoteResource.unit.spec.ts +++ b/src/common/ownedRemoteResource.unit.spec.ts @@ -26,3 +26,47 @@ describe("flow-owned remote resources", () => { expect(dispose).toHaveBeenCalledOnce(); }); }); + +describe("owned remote resource completion", () => { + it("waits for cleanup and preserves its receiver", async () => { + let finish!: () => void; + let started!: () => void; + const disposing = new Promise((resolve) => { + started = resolve; + }); + const cleanup = new Promise((resolve) => { + finish = resolve; + }); + const resource = { + dispose: vi.fn(function (this: unknown) { + expect(this).toBe(resource); + started(); + return cleanup; + }), + }; + let settled = false; + const result = withOwnedRemoteResource(resource, async () => "done"); + void result.then(() => { + settled = true; + }); + await disposing; + expect(settled).toBe(false); + finish(); + await expect(result).resolves.toBe("done"); + expect(resource.dispose).toHaveBeenCalledOnce(); + }); + + it("keeps finally precedence when both the operation and cleanup fail", async () => { + const operationError = new Error("operation"); + const disposalError = new Error("cleanup"); + const dispose = vi.fn(async () => { + throw disposalError; + }); + await expect( + withOwnedRemoteResource({ dispose }, async () => { + throw operationError; + }) + ).rejects.toBe(disposalError); + expect(dispose).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/common/replicatorProviders.ts b/src/common/replicatorProviders.ts index 55fa13b0..19b13d38 100644 --- a/src/common/replicatorProviders.ts +++ b/src/common/replicatorProviders.ts @@ -73,7 +73,7 @@ async function runOneShotWithOutcome( // Manual and unattended wrappers share the provider transfer operation, but // keep interaction authority and result presentation explicit at this boundary. -const couchDBUserInitiatedOneShot: UserInitiatedOneShotRunner = async (instance, setting, request) => { +const userInitiatedOneShot: UserInitiatedOneShotRunner = async (instance, setting, request) => { return await runOneShotWithOutcome( instance, setting, @@ -81,20 +81,7 @@ const couchDBUserInitiatedOneShot: UserInitiatedOneShotRunner = async (instance, ); }; -const couchDBUnattendedOneShot: UnattendedOneShotRunner = async (instance, setting, request) => { - if (request.interaction.kind !== NO_INTERACTION.kind) return replicationBlocked("interaction-required"); - return await runOneShotWithOutcome(instance, setting, false); -}; - -const objectStorageUserInitiatedOneShot: UserInitiatedOneShotRunner = async (instance, setting, request) => { - return await runOneShotWithOutcome( - instance, - setting, - request.progressPresentation === REPLICATION_PROGRESS_PRESENTATIONS.NOTICE - ); -}; - -const objectStorageUnattendedOneShot: UnattendedOneShotRunner = async (instance, setting, request) => { +const unattendedOneShot: UnattendedOneShotRunner = async (instance, setting, request) => { if (request.interaction.kind !== NO_INTERACTION.kind) return replicationBlocked("interaction-required"); return await runOneShotWithOutcome(instance, setting, false); }; @@ -136,8 +123,8 @@ export function createCentralReplicatorProviderDefinitions( ), }, centralRemoteAdministration: COUCHDB_CENTRAL_REMOTE_ADMINISTRATION_CAPABILITY, - userInitiatedOneShot: supportedCapability(couchDBUserInitiatedOneShot), - unattendedOneShot: supportedCapability(couchDBUnattendedOneShot), + userInitiatedOneShot: supportedCapability(userInitiatedOneShot), + unattendedOneShot: supportedCapability(unattendedOneShot), continuous: supportedOpenReplicationContinuous(), stopActiveTransfer: supportedStopActiveTransfer(), }, @@ -166,8 +153,8 @@ export function createCentralReplicatorProviderDefinitions( [REMOTE_RESOURCE_KINDS.INITIAL_FETCH_FAST_FORWARD]: CAPABILITY_NOT_APPLICABLE, }, centralRemoteAdministration: OBJECT_STORAGE_CENTRAL_REMOTE_ADMINISTRATION_CAPABILITY, - userInitiatedOneShot: supportedCapability(objectStorageUserInitiatedOneShot), - unattendedOneShot: supportedCapability(objectStorageUnattendedOneShot), + userInitiatedOneShot: supportedCapability(userInitiatedOneShot), + unattendedOneShot: supportedCapability(unattendedOneShot), continuous: CAPABILITY_NOT_APPLICABLE, stopActiveTransfer: supportedStopActiveTransfer(), }, diff --git a/src/common/replicatorProviders.unit.spec.ts b/src/common/replicatorProviders.unit.spec.ts index 0354537d..8bf02b6d 100644 --- a/src/common/replicatorProviders.unit.spec.ts +++ b/src/common/replicatorProviders.unit.spec.ts @@ -209,6 +209,37 @@ describe("central Replicator provider definitions", () => { expect(openOneShotReplicationWithOutcome).toHaveBeenNthCalledWith(2, setting, true); }); + it.each([REMOTE_COUCHDB, REMOTE_MINIO] as const)( + "keeps unattended %s work quiet and rejects interaction before opening replication", + async (remoteType) => { + const definition = createCentralReplicatorProviderDefinitions({} as never).get(remoteType)!; + if (definition.unattendedOneShot.kind !== CAPABILITY_SUPPORT_KINDS.SUPPORTED) { + throw new Error("Unattended OneShot is unavailable"); + } + const setting = Object.assign(createNewVaultSettings(), { remoteType }); + const instance = { + initializeDatabaseForReplication: vi.fn(async () => true), + openReplication: vi.fn(async () => true), + terminateSync: vi.fn(), + closeReplication: vi.fn(), + openOneShotReplicationWithOutcome: vi.fn(async () => REPLICATION_COMPLETED), + }; + const blocked = await definition.unattendedOneShot.run(instance, setting, { + trigger: "resume", + interaction: USER_INITIATED_REPLICATION_AUTHORITY, + } as never); + expect(blocked).toEqual({ status: "blocked", reason: "interaction-required" }); + expect(instance.openOneShotReplicationWithOutcome).not.toHaveBeenCalled(); + await expect( + definition.unattendedOneShot.run(instance, setting, { + trigger: "resume", + interaction: NO_INTERACTION, + }) + ).resolves.toBe(REPLICATION_COMPLETED); + expect(instance.openOneShotReplicationWithOutcome).toHaveBeenCalledExactlyOnceWith(setting, false); + } + ); + it("dispatches central finite work through the declared operation rather than constructor identity", async () => { const definitions = createCentralReplicatorProviderDefinitions({} as never); const couchDB = definitions.get(REMOTE_COUCHDB)!; diff --git a/src/common/replicatorResources/shared.ts b/src/common/replicatorResources/shared.ts index a88f070a..e2b4b8a1 100644 --- a/src/common/replicatorResources/shared.ts +++ b/src/common/replicatorResources/shared.ts @@ -1,3 +1,4 @@ +import { createOwnedResource } from "octagonal-wheels/resource"; import type { RemoteDBSettings } from "@vrtmrz/livesync-commonlib/compat/common/types"; /** @@ -13,13 +14,8 @@ export interface ResourceReplicator { /** Create one idempotent asynchronous disposer for a private Replicator. */ export function createReplicatorDisposer(replicator: ResourceReplicator): () => Promise { - let disposal: Promise | undefined; - return () => { - if (disposal === undefined) { - disposal = Promise.resolve().then(() => replicator.closeReplication()); - } - return disposal; - }; + const resource = createOwnedResource(replicator, (owned) => Promise.resolve().then(() => owned.closeReplication())); + return () => Promise.resolve(resource.dispose()); } /** Fence a finite resource from later edits to its source settings object. */ diff --git a/src/common/replicatorResources/shared.unit.spec.ts b/src/common/replicatorResources/shared.unit.spec.ts new file mode 100644 index 00000000..e2705440 --- /dev/null +++ b/src/common/replicatorResources/shared.unit.spec.ts @@ -0,0 +1,42 @@ +import { describe, expect, it, vi } from "vitest"; +import { createReplicatorDisposer } from "./shared"; + +describe("Replicator disposal", () => { + it("defers closing, preserves the receiver, and retains one completion promise", async () => { + let finish!: () => void; + const closed = new Promise((resolve) => { + finish = resolve; + }); + const replicator = { + closeReplication: vi.fn(function (this: unknown) { + expect(this).toBe(replicator); + return closed; + }), + }; + const dispose = createReplicatorDisposer(replicator); + const pending = dispose(); + expect(replicator.closeReplication).not.toHaveBeenCalled(); + expect(dispose()).toBe(pending); + await Promise.resolve(); + expect(replicator.closeReplication).toHaveBeenCalledOnce(); + finish(); + await pending; + expect(dispose()).toBe(pending); + expect(replicator.closeReplication).toHaveBeenCalledOnce(); + }); + + it("retains synchronous closing failures as one rejected promise", async () => { + const error = new Error("close"); + const replicator = { + closeReplication: vi.fn(() => { + throw error; + }), + }; + const dispose = createReplicatorDisposer(replicator); + const pending = dispose(); + await expect(pending).rejects.toBe(error); + expect(dispose()).toBe(pending); + await expect(dispose()).rejects.toBe(error); + expect(replicator.closeReplication).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/main.onunload.unit.spec.ts b/src/main.onunload.unit.spec.ts new file mode 100644 index 00000000..3ddb9019 --- /dev/null +++ b/src/main.onunload.unit.spec.ts @@ -0,0 +1,114 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createOwnedResource } from "octagonal-wheels/resource"; +import { LOG_LEVEL_URGENT } from "octagonal-wheels/common/logger"; +import { bindableFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/HandlerUtils"; + +const unusedStartupDependencies: readonly [string, readonly string[]][] = [ + ["@/serviceFeatures/useP2PSettingsPreparation", ["useP2PSettingsPreparation"]], + ["@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions", ["setGetLanguage"]], + ["./features/LiveSyncCommands.ts", ["LiveSyncCommands"]], + ["./features/HiddenFileSync/CmdHiddenFileSync.ts", ["HiddenFileSync"]], + ["./features/ConfigSync/CmdConfigSync.ts", ["ConfigSync"]], + ["./modules/features/ModuleLog.ts", ["ModuleLog"]], + ["./modules/essentialObsidian/ModuleObsidianEvents.ts", ["ModuleObsidianEvents"]], + ["./modules/features/ModuleObsidianSettingTab.ts", ["ModuleObsidianSettingDialogue"]], + ["./modules/features/ModuleObsidianDocumentHistory.ts", ["ModuleObsidianDocumentHistory"]], + ["./modules/features/ModuleGlobalHistory.ts", ["ModuleObsidianGlobalHistory"]], + ["./features/LocalDatabaseMainte/CmdLocalDatabaseMainte.ts", ["LocalDatabaseMaintenance"]], + ["./modules/services/ObsidianServiceHub.ts", ["ObsidianServiceHub"]], + ["@vrtmrz/livesync-commonlib/compat/serviceModules/Rebuilder", ["ServiceRebuilder"]], + ["@/serviceModules/DatabaseFileAccess.ts", ["ServiceDatabaseFileAccess"]], + ["@/serviceModules/ServiceFileAccessImpl.ts", ["ServiceFileAccessObsidian"]], + ["@vrtmrz/livesync-commonlib/compat/managers/StorageProcessingManager", ["StorageAccessManager"]], + ["./serviceModules/FileHandler.ts", ["ServiceFileHandler"]], + ["./serviceModules/FileAccessObsidian.ts", ["FileAccessObsidian"]], + ["./managers/StorageEventManagerObsidian.ts", ["StorageEventManagerObsidian"]], + ["@vrtmrz/livesync-commonlib/compat/mock_and_interop/wrapper", ["setNoticeClass"]], + ["./LiveSyncBaseCore.ts", ["LiveSyncBaseCore"]], + ["./modules/features/ModuleObsidianSettingAsMarkdown.ts", ["ModuleObsidianSettingsAsMarkdown"]], + ["./modules/features/SetupManager.ts", ["SetupManager"]], + ["./serviceFeatures/onLayoutReady/enablei18n.ts", ["enableI18nFeature"]], + ["@vrtmrz/livesync-commonlib/compat/serviceFeatures/offlineScanner", ["useOfflineScanner"]], + ["@vrtmrz/livesync-commonlib/compat/serviceFeatures/remoteConfig", ["useRemoteConfiguration"]], + ["@vrtmrz/livesync-commonlib/compat/serviceFeatures/checkRemoteSize", ["useCheckRemoteSize"]], + ["./serviceFeatures/redFlag.ts", ["useRedFlagFeatures"]], + ["./serviceFeatures/setupObsidian/setupProtocol.ts", ["useSetupProtocolFeature"]], + ["@/serviceFeatures/setupObsidian/qrCode", ["useSetupQRCodeFeature"]], + ["@/serviceFeatures/setupObsidian/setupUri", ["useSetupURIFeature"]], + [ + "./serviceFeatures/setupObsidian/setupManagerHandlers.ts", + ["showOnboardingInvitation", "useSetupManagerHandlersFeature"], + ], + ["@vrtmrz/livesync-commonlib/p2p", ["useP2PReplicatorCommands", "useP2PReplicatorFeature"]], + ["./serviceFeatures/useP2PReplicatorUI.ts", ["useP2PReplicatorUI"]], + ["./serviceFeatures/useReviewHarness.ts", ["useReviewHarness"]], + ["./features/P2PSync/P2PReplicator/P2PReplicationUI.ts", ["createOpenReplicationUI", "createOpenRebuildUI"]], + ["./serviceFeatures/compatibilityReview.ts", ["useCompatibilityReview"]], + ["./serviceFeatures/compatibilityReviewObsidian.ts", ["createObsidianCompatibilityReviewUi"]], + ["./serviceModules/FileReflectionProvenance.ts", ["createFileReflectionProvenance"]], + ["./serviceFeatures/interactiveConflictResolution", ["useInteractiveConflictResolutionFeature"]], + ["./modules/features/InteractiveConflictResolving/ConflictResolveModal.ts", ["ConflictResolveModal"]], + ["./serviceFeatures/obsidianReplicationRibbon.ts", ["useObsidianReplicationRibbonFeature"]], + ["./serviceFeatures/startupLifecycle", ["useStartupLifecycleFeature"]], + ["./serviceFeatures/useJoinedDevices", ["useJoinedDevicesFeature"]], + ["./serviceFeatures/useDatabaseDiagnostics", ["useDatabaseDiagnosticsFeature"]], +]; + +beforeEach(() => { + vi.resetModules(); + vi.doMock("./deps", () => ({ Plugin: class {}, Notice: class {}, getLanguage: () => "en" })); + for (const [specifier, names] of unusedStartupDependencies) { + vi.doMock(specifier, () => Object.fromEntries(names.map((name) => [name, vi.fn()]))); + } +}); + +describe("Obsidian plug-in unload logging", () => { + it.each(["complete", "fail"] as const)( + "retains its log connection through shutdown and retires it afterwards: %s", + async (outcome) => { + const { default: LiveSyncPlugin } = await import("./main.ts"); + const events: string[] = []; + const sink = vi.fn((message: unknown) => events.push(String(message))); + const addLog = bindableFunction<(message: unknown, level?: number, key?: string) => void>("unload log"); + const unregister = addLog.setHandler(sink); + const dispose = vi.fn(() => { + unregister(); + events.push("disposed"); + }); + const logResource = createOwnedResource(sink, dispose); + let finish!: () => void; + let fail!: (reason: Error) => void; + const shutdown = new Promise((resolve, reject) => { + finish = resolve; + fail = reject; + }); + const onUnload = vi.fn(() => shutdown); + const core = { + getModule: vi.fn(() => ({ logResource })), + services: { API: { addLog }, control: { onUnload } }, + }; + + expect(LiveSyncPlugin.prototype.onunload.call({ core } as never)).toBeUndefined(); + expect(onUnload).toHaveBeenCalledTimes(1); + expect(dispose).not.toHaveBeenCalled(); + addLog("during shutdown"); + + const failure = new Error("database close failed"); + if (outcome === "fail") { + fail(failure); + } else { + finish(); + } + await vi.waitFor(() => expect(dispose).toHaveBeenCalledTimes(1)); + + if (outcome === "fail") { + const message = "Failed to unload Self-hosted LiveSync: " + String(failure); + expect(sink).toHaveBeenCalledWith(message, LOG_LEVEL_URGENT, "shutdown"); + expect(events).toEqual(["during shutdown", message, "disposed"]); + } else { + expect(events).toEqual(["during shutdown", "disposed"]); + } + expect(() => addLog("after shutdown")).toThrow("not assigned"); + } + ); +}); diff --git a/src/main.ts b/src/main.ts index d4e7d346..51aba0d1 100644 --- a/src/main.ts +++ b/src/main.ts @@ -9,6 +9,7 @@ import { ConfigSync } from "./features/ConfigSync/CmdConfigSync.ts"; // import { ModuleDev } from "./modules/extras/ModuleDev.ts"; import { ModuleLog } from "./modules/features/ModuleLog.ts"; +import { withOwnedResource } from "octagonal-wheels/resource"; import { ModuleObsidianEvents } from "./modules/essentialObsidian/ModuleObsidianEvents.ts"; import { ModuleObsidianSettingDialogue } from "./modules/features/ModuleObsidianSettingTab.ts"; import { ModuleObsidianDocumentHistory } from "./modules/features/ModuleObsidianDocumentHistory.ts"; @@ -234,12 +235,14 @@ export default class ObsidianLiveSyncPlugin extends Plugin { void this._startUp(); } override onunload(): void { - void this.core.services.control.onUnload().catch((error) => { - this.core.services.API.addLog( - "Failed to unload Self-hosted LiveSync: " + String(error), - LOG_LEVEL_URGENT, - "shutdown" - ); - }); + void withOwnedResource(this.core.getModule(ModuleLog).logResource, () => + this.core.services.control.onUnload().catch((error) => { + this.core.services.API.addLog( + "Failed to unload Self-hosted LiveSync: " + String(error), + LOG_LEVEL_URGENT, + "shutdown" + ); + }) + ); } } diff --git a/src/modules/features/ModuleLog.ts b/src/modules/features/ModuleLog.ts index 0755506b..58f77daf 100644 --- a/src/modules/features/ModuleLog.ts +++ b/src/modules/features/ModuleLog.ts @@ -1,4 +1,10 @@ -import { computed, reactive, reactiveSource, type ReactiveValue } from "octagonal-wheels/dataobject/reactive"; +import { + computed, + reactive, + reactiveSource, + type ReactiveSource, + type ReactiveValue, +} from "octagonal-wheels/dataobject/reactive"; import { LOG_LEVEL_DEBUG, LOG_LEVEL_INFO, @@ -7,6 +13,7 @@ import { type LOG_LEVEL, } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { scheduleTask } from "octagonal-wheels/concurrency/task"; +import { createOwnedResource, type OwnedResource } from "octagonal-wheels/resource"; import { fireAndForget, isDirty, throttle } from "@vrtmrz/livesync-commonlib/compat/common/utils"; import { chunkFetchCounts, @@ -46,7 +53,11 @@ import { isValidFilenameInDarwin, isValidFilenameInWidows, } from "@vrtmrz/livesync-commonlib/compat/string_and_binary/path"; -import { MARK_LOG_NETWORK_ERROR, MARK_LOG_SEPARATOR } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; +import { + MARK_LOG_NETWORK_ERROR, + MARK_LOG_SEPARATOR, + type LogFunction, +} from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; import { NetworkWarningStyles } from "@vrtmrz/livesync-commonlib/compat/common/models/setting.const"; import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { generateReport } from "@/common/reportTool.ts"; @@ -57,20 +68,22 @@ import { // This module cannot be a core module because it depends on the Obsidian UI. -// DI the log again. -const recentLogEntries = reactiveSource([]); -const globalLogFunction = (message: unknown, level?: number, key?: string) => { - const messageX = - message instanceof Error - ? new LiveSyncError("[Error Logged]: " + message.message, { cause: message }) - : typeof message === "string" - ? message - : JSON.stringify(message); - const entry = { message: messageX, level, key } as LogEntry; - recentLogEntries.value = [...recentLogEntries.value, entry]; -}; +function createBufferedLog(entries: ReactiveSource) { + return (message: unknown, level?: number, key?: string) => { + const messageX = + message instanceof Error + ? new LiveSyncError("[Error Logged]: " + message.message, { cause: message }) + : typeof message === "string" + ? message + : JSON.stringify(message); + const entry = { message: messageX, level, key } as LogEntry; + entries.value = [...entries.value, entry]; + }; +} -setGlobalLogFunction(globalLogFunction); +// Legacy Logger calls use this shared buffer; service logs use their owner's buffer. +const recentGlobalLogEntries = reactiveSource([]); +setGlobalLogFunction(createBufferedLog(recentGlobalLogEntries)); // Keep the recent logs in memory for display, but also keep a longer history in logForDump for when the user wants to see more logs. // logForDump is not reactive and is only used for dumping logs when requested, while recentLogs is reactive and is used for displaying logs in the UI. const logForDump = [] as string[]; @@ -113,6 +126,16 @@ function redactLog(log: string) { const showDebugLog = false; export const MARK_DONE = "\u{2009}\u{2009}"; export class ModuleLog extends AbstractObsidianModule { + /** The host releases this connection after the complete asynchronous unload. */ + logResource!: OwnedResource; + private readonly recentLogEntries = reactiveSource([]); + private readonly displayLogEntries = () => { + if (this.recentLogEntries.value.length === 0) return; + const entries = [...this.recentLogEntries.value]; + this.recentLogEntries.value = []; + entries.forEach((entry) => this.__addLog(entry.message, entry.level, entry.key)); + }; + statusBar?: HTMLElement; statusDiv?: HTMLElement; @@ -460,12 +483,7 @@ ${stringifyYaml(info)} return Promise.resolve(true); } private _everyOnloadAfterLoadSettings(): Promise { - recentLogEntries.onChanged((entries) => { - if (entries.value.length === 0) return; - const newEntries = [...entries.value]; - recentLogEntries.value = []; - newEntries.forEach((e) => this.__addLog(e.message, e.level, e.key)); - }); + this.recentLogEntries.onChanged(this.displayLogEntries); eventHub.onEvent(EVENT_FILE_RENAMED, (data) => { void this.setFileStatus(); }); @@ -597,7 +615,22 @@ ${stringifyYaml(info)} } } override onBindFunction(core: LiveSyncCore, services: typeof core.services): void { - services.API.addLog.setHandler(globalLogFunction); + const log = createBufferedLog(this.recentLogEntries); + const unregisterLog = services.API.addLog.setHandler(log); + const collectGlobalLogs = () => { + const entries = recentGlobalLogEntries.value; + if (entries.length === 0) return; + recentGlobalLogEntries.value = []; + this.recentLogEntries.value = [...this.recentLogEntries.value, ...entries]; + }; + this.logResource = createOwnedResource(log, () => { + unregisterLog(); + recentGlobalLogEntries.offChanged(collectGlobalLogs); + this.recentLogEntries.offChanged(this.displayLogEntries); + this.recentLogEntries.value = []; + }); + recentGlobalLogEntries.onChanged(collectGlobalLogs); + collectGlobalLogs(); services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this)); services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this)); services.appLifecycle.onLoaded.addHandler(this._everyOnload.bind(this)); diff --git a/src/modules/features/ModuleLog.unit.spec.ts b/src/modules/features/ModuleLog.unit.spec.ts new file mode 100644 index 00000000..28f48231 --- /dev/null +++ b/src/modules/features/ModuleLog.unit.spec.ts @@ -0,0 +1,228 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/deps.ts", () => ({ + addIcon: vi.fn(), + debounce: (callback: () => void) => callback, + normalizePath: (path: string) => path, + Notice: class {}, + stringifyYaml: vi.fn(), +})); +vi.mock("./Log/LogPaneView.ts", () => ({ LogPaneView: class {}, VIEW_TYPE_LOG: "log" })); +vi.mock("@/common/reportTool.ts", () => ({ generateReport: vi.fn() })); +vi.mock("@/common/utils.ts", () => ({ isValidPath: () => true })); +vi.mock("@/common/translation", () => ({ $msg: (key: string) => key })); +vi.mock("@/common/events.ts", () => ({ + EVENT_FILE_RENAMED: "renamed", + EVENT_LAYOUT_READY: "ready", + EVENT_LEAF_ACTIVE_CHANGED: "active", + EVENT_ON_UNRESOLVED_ERROR: "error", + eventHub: { onEvent: vi.fn() }, +})); +vi.mock("@vrtmrz/livesync-commonlib/compat/replication/trystero/P2PLogCollector", () => ({ + P2PLogCollector: class {}, +})); + +async function createHarness() { + const { ModuleLog } = await import("./ModuleLog.ts"); + const { bindableFunction, allFunction } = + await import("@vrtmrz/livesync-commonlib/compat/services/lib/HandlerUtils"); + const services = { + API: { + addLog: bindableFunction<(message: unknown, level?: number, key?: string) => void>("log"), + addCommand: vi.fn(), + registerWindow: vi.fn(), + addRibbonIcon: vi.fn(), + registerProtocolHandler: vi.fn(), + }, + context: { events: {}, notices: { hide: vi.fn() } }, + appLifecycle: { + onInitialise: allFunction<() => Promise>(), + onSettingLoaded: allFunction<() => Promise>(), + onLoaded: allFunction<() => Promise>(), + onBeforeUnload: allFunction<() => Promise>(), + }, + }; + const core = { services, settings: {} }; + const module = new ModuleLog({ app: {} } as never, core as never); + const sink = vi.spyOn(module, "__addLog").mockImplementation(() => undefined); + vi.spyOn(module, "observeForLogs").mockImplementation(() => undefined); + vi.spyOn(module, "adjustStatusDivPosition").mockImplementation(() => undefined); + module.onBindFunction(core as never, services as never); + const { Logger } = await import("octagonal-wheels/common/logger"); + return { module, services, sink, Logger }; +} + +describe("ModuleLog service connection", () => { + beforeEach(() => { + vi.resetModules(); + vi.stubGlobal("document", { querySelectorAll: () => [] }); + }); + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("buffers startup logs and preserves global and service call order", async () => { + const { services, sink, Logger } = await createHarness(); + Logger("before-global"); + services.API.addLog("before-service", 32, "startup"); + Logger("between-global"); + expect(sink).not.toHaveBeenCalled(); + await services.appLifecycle.onSettingLoaded(); + const messages = sink.mock.calls.map(([message]) => message); + expect(messages.filter((message) => typeof message === "string" && /^(before|between)-/.test(message))).toEqual( + ["before-global", "before-service", "between-global"] + ); + expect(sink).toHaveBeenCalledWith("before-service", 32, "startup"); + }); + + it("delivers service logs only to their own module", async () => { + const first = await createHarness(); + const second = await createHarness(); + await first.services.appLifecycle.onSettingLoaded(); + await second.services.appLifecycle.onSettingLoaded(); + first.sink.mockClear(); + second.sink.mockClear(); + + first.services.API.addLog("first", 32, "first-key"); + second.services.API.addLog("second", 64, "second-key"); + expect(first.sink.mock.calls).toEqual([["first", 32, "first-key"]]); + expect(second.sink.mock.calls).toEqual([["second", 64, "second-key"]]); + }); + + it("preserves message conversion, levels, keys, and error causes", async () => { + const { services, sink } = await createHarness(); + await services.appLifecycle.onSettingLoaded(); + sink.mockClear(); + const error = new Error("failed"); + services.API.addLog(error, 128, "failure"); + services.API.addLog({ result: "value" }, 32, "object"); + services.API.addLog("plain"); + const converted = sink.mock.calls[0][0] as Error & { cause: unknown }; + expect(converted.message).toBe("[Error Logged]: failed"); + expect(converted.cause).toBe(error); + expect(sink.mock.calls[0].slice(1)).toEqual([128, "failure"]); + expect(sink.mock.calls.slice(1)).toEqual([ + ['{"result":"value"}', 32, "object"], + ["plain", undefined, undefined], + ]); + }); + + it("detaches both service registration and legacy subscription on disposal", async () => { + const first = await createHarness(); + const second = await createHarness(); + await first.services.appLifecycle.onSettingLoaded(); + await second.services.appLifecycle.onSettingLoaded(); + first.sink.mockClear(); + second.sink.mockClear(); + + await first.module.logResource.dispose(); + await first.module.logResource.dispose(); + expect(() => first.services.API.addLog("retired")).toThrow("not assigned"); + second.services.API.addLog("active", 32, "service"); + first.Logger("legacy-after-retirement", 32, "legacy"); + expect(first.sink).not.toHaveBeenCalled(); + expect(second.sink.mock.calls).toEqual([ + ["active", 32, "service"], + ["legacy-after-retirement", 32, "legacy"], + ]); + await second.module.logResource.dispose(); + }); + + it("leaves a replacement service handler registered when the old owner is disposed", async () => { + const { services, module, sink, Logger } = await createHarness(); + await services.appLifecycle.onSettingLoaded(); + const replacement = vi.fn(); + services.API.addLog.setHandler(replacement, true); + sink.mockClear(); + + await module.logResource.dispose(); + await module.logResource.dispose(); + services.API.addLog("replacement", 32, "key"); + Logger("detached-legacy"); + expect(replacement).toHaveBeenCalledExactlyOnceWith("replacement", 32, "key"); + expect(sink).not.toHaveBeenCalled(); + }); + + it("releases a connection which never reached the settings-loaded phase", async () => { + const { services, module, sink, Logger } = await createHarness(); + services.API.addLog("pending"); + await module.logResource.dispose(); + Logger("after-disposal"); + expect(sink).not.toHaveBeenCalled(); + expect(() => services.API.addLog("retired")).toThrow("not assigned"); + + const replacement = await createHarness(); + await replacement.services.appLifecycle.onSettingLoaded(); + const messages = replacement.sink.mock.calls.map(([message]) => message); + expect(messages).toContain("after-disposal"); + expect(messages).not.toContain("pending"); + await replacement.module.logResource.dispose(); + }); + + it.each(["complete", "fail"] as const)( + "keeps logging through asynchronous database shutdown and releases after it: %s", + async (outcome) => { + const { services, module, sink, Logger } = await createHarness(); + await services.appLifecycle.onSettingLoaded(); + sink.mockClear(); + const { ControlService } = await import("@vrtmrz/livesync-commonlib/compat/services/base/ControlService"); + const { ServiceContext } = await import("@vrtmrz/livesync-commonlib/context"); + const { withOwnedResource } = await import("octagonal-wheels/resource"); + let finish!: () => void; + let fail!: (reason: Error) => void; + let started!: () => void; + const closing = new Promise((resolve) => { + started = resolve; + }); + const closed = new Promise((resolve, reject) => { + finish = resolve; + fail = reject; + }); + const control = new ControlService(new ServiceContext({ translate: (key) => key }), { + appLifecycleService: { + ...services.appLifecycle, + onAppUnload: vi.fn(async () => []), + onUnload: vi.fn(async () => { + services.API.addLog("lifecycle-unload"); + return true; + }), + }, + APIService: services.API, + databaseService: { + localDatabaseDirect: { + onunload: vi.fn(() => services.API.addLog("database-unload")), + close: vi.fn(() => { + started(); + return closed; + }), + }, + }, + } as never); + + const unloading = withOwnedResource(module.logResource, () => control.onUnload()); + await closing; + services.API.addLog("during-close"); + expect(sink.mock.calls.map(([message]) => message)).toEqual([ + "lifecycle-unload", + "database-unload", + "during-close", + ]); + if (outcome === "fail") { + const failure = new Error("database close failed"); + const rejected = expect(unloading).rejects.toBe(failure); + fail(failure); + await rejected; + } else { + finish(); + await unloading; + expect(sink.mock.calls[sink.mock.calls.length - 1][0]).toContain( + "moduleLiveSyncMain.logUnloadingPlugin" + ); + } + expect(() => services.API.addLog("retired")).toThrow("not assigned"); + sink.mockClear(); + Logger("after-unload"); + expect(sink).not.toHaveBeenCalled(); + } + ); +}); diff --git a/src/serviceFeatures/useJoinedDevices.ts b/src/serviceFeatures/useJoinedDevices.ts index 53b7dbc9..6baa9529 100644 --- a/src/serviceFeatures/useJoinedDevices.ts +++ b/src/serviceFeatures/useJoinedDevices.ts @@ -9,6 +9,7 @@ import { import { REMOTE_RESOURCE_KINDS, type JoinedDevicesSnapshot } from "@vrtmrz/livesync-commonlib/replication"; import type { ObsidianNoticeGroups } from "@/modules/services/ObsidianNoticeGroups"; import JoinedDevicesDialog from "@/modules/services/LiveSyncUI/dialogues/JoinedDevicesDialog.svelte"; +import { withOwnedRemoteResource } from "@/common/ownedRemoteResource"; import { getCouchDBReplicatorConfigurationIdentity, getObjectStorageReplicatorConfigurationIdentity, @@ -119,9 +120,9 @@ export function useJoinedDevicesFeature(host: JoinedDevicesHost, notices: Obsidi settings ); if (!resource) throw new Error("Joined devices are unavailable"); - try { + return withOwnedRemoteResource(resource, async (ownedResource) => { assertCurrent(); - const snapshot = await resource.read(); + const snapshot = await ownedResource.read(); assertCurrent(); notify(snapshot, id, identity!); return joinedDevicesView(snapshot, { @@ -130,9 +131,7 @@ export function useJoinedDevicesFeature(host: JoinedDevicesHost, notices: Obsidi pluginVersion: services.API.getPluginVersion(), appVersion: services.API.getAppVersion(), }); - } finally { - await resource.dispose(); - } + }); }, forget: async (id) => { if (id === (await ownId())) throw new Error("This device cannot be forgotten"); @@ -141,14 +140,12 @@ export function useJoinedDevicesFeature(host: JoinedDevicesHost, notices: Obsidi settings ); if (!resource) throw new Error("Joined devices are unavailable"); - try { + return withOwnedRemoteResource(resource, async (ownedResource) => { assertCurrent(); - const result = await resource.forget(id); + const result = await ownedResource.forget(id); assertCurrent(); return result; - } finally { - await resource.dispose(); - } + }); }, cancel: () => controller.abort(), }; diff --git a/src/serviceFeatures/useJoinedDevices.unit.spec.ts b/src/serviceFeatures/useJoinedDevices.unit.spec.ts index 188afe5a..0c5670c2 100644 --- a/src/serviceFeatures/useJoinedDevices.unit.spec.ts +++ b/src/serviceFeatures/useJoinedDevices.unit.spec.ts @@ -110,6 +110,67 @@ describe("joined devices service feature", () => { expect(await pending).toEqual({ status: "handled", value: "closed" }); await expect(options.refresh()).rejects.toThrow(); }); + it("propagates a failed refresh after releasing its resource", async () => { + const data = fixture(); + const failure = new Error("joined devices read failed"); + data.read.mockRejectedValueOnce(failure); + const { options, pending } = await open(data); + + await expect(options.refresh()).rejects.toBe(failure); + expect(data.dispose).toHaveBeenCalledOnce(); + data.close(); + await pending; + }); + it.each(["refresh", "forget"] as const)( + "waits for resource disposal after %s", + async (operationName) => { + const data = fixture(); + let finishDisposal!: () => void; + data.dispose.mockImplementationOnce( + () => + new Promise((resolve) => { + finishDisposal = resolve; + }) + ); + const { options, pending } = await open(data); + const operation = operationName === "refresh" ? options.refresh() : options.forget("other"); + let settled = false; + void operation.then( + () => { + settled = true; + }, + () => { + settled = true; + } + ); + + await vi.waitFor(() => expect(data.dispose).toHaveBeenCalledOnce()); + expect(settled).toBe(false); + finishDisposal(); + await expect(operation).resolves.toBeDefined(); + expect(settled).toBe(true); + data.close(); + await pending; + } + ); + it.each(["refresh", "forget"] as const)( + "uses disposal failure precedence when %s also fails", + async (operationName) => { + const data = fixture(); + const operationFailure = new Error("joined devices operation failed"); + const disposalFailure = new Error("joined devices disposal failed"); + if (operationName === "refresh") data.read.mockRejectedValueOnce(operationFailure); + else data.forget.mockRejectedValueOnce(operationFailure); + data.dispose.mockRejectedValueOnce(disposalFailure); + const { options, pending } = await open(data); + const operation = operationName === "refresh" ? options.refresh() : options.forget("other"); + + await expect(operation).rejects.toBe(disposalFailure); + expect(data.dispose).toHaveBeenCalledOnce(); + data.close(); + await pending; + } + ); it("prevents self removal and fences an old dialogue after a remote switch", async () => { const data = fixture(); const { options, pending } = await open(data); diff --git a/test/e2e-obsidian/scripts/log-lifecycle.ts b/test/e2e-obsidian/scripts/log-lifecycle.ts new file mode 100644 index 00000000..a126da2d --- /dev/null +++ b/test/e2e-obsidian/scripts/log-lifecycle.ts @@ -0,0 +1,373 @@ +import { createHash, randomUUID } from "node:crypto"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { LOG_LEVEL_URGENT } from "octagonal-wheels/common/logger"; +import { evalObsidianJson } from "../runner/cli.ts"; +import { requireObsidianBinary, requireObsidianCli } from "../runner/environment.ts"; +import { + createE2eCouchDbPluginData, + createE2eObsidianDeviceLocalState, + waitForLiveSyncCoreReady, +} from "../runner/liveSyncWorkflow.ts"; +import { startObsidianLiveSyncSession, type ObsidianLiveSyncSession } from "../runner/session.ts"; +import { createTemporaryVault, type TemporaryVault } from "../runner/vault.ts"; + +process.env.E2E_OBSIDIAN_CLI_TIMEOUT_MS ??= "60000"; + +type FixtureLog = { + message: string; + level?: number; + key?: string; +}; + +type ShutdownObservation = { + closeCalls: number; + disposeCalls: number; + disposeCompleted: boolean; + fixtureLogs: FixtureLog[]; + events: string[]; +}; + +async function evaluate(cliBinary: string, session: ObsidianLiveSyncSession, body: string): Promise { + return await evalObsidianJson( + cliBinary, + `(async()=>{ + const require=(condition,message)=>{if(!condition)throw new Error(message);}; + const waitFor=async(predicate,message)=>{ + const until=Date.now()+15000; + while(!predicate()) { + if(Date.now()>until)throw new Error(message); + await new Promise(resolve=>setTimeout(resolve,20)); + } + }; + ${body} + })()`, + session.cliEnv + ); +} + +function createPluginData(dbName: string): Record { + return createE2eCouchDbPluginData( + { uri: "http://127.0.0.1:1", username: "unused", password: "unused", dbName }, + { + syncInternalFiles: true, + usePluginSync: true, + usePluginSyncV2: true, + deviceAndVaultName: "log-lifecycle-device", + autoSweepPlugins: false, + autoSweepPluginsPeriodic: false, + syncInternalFilesInterval: 0, + liveSync: false, + periodicReplication: false, + syncOnStart: false, + syncOnSave: false, + syncOnFileOpen: false, + syncOnEditorSave: false, + syncAfterMerge: false, + showVerboseLog: true, + } + ); +} + +async function startSession( + binary: string, + cliBinary: string, + vault: TemporaryVault +): Promise { + const session = await startObsidianLiveSyncSession({ + binary, + cliBinary, + vault, + pluginData: createPluginData(`log-lifecycle-${vault.name}`), + localStorageEntries: createE2eObsidianDeviceLocalState(vault.name), + lifecycle: { + beforeLaunch: async () => { + const registryPath = join(vault.userDataPath, "obsidian.json"); + const registry = JSON.parse(await readFile(registryPath, "utf8")); + registry.updateDisabled = true; + await writeFile(registryPath, JSON.stringify(registry)); + }, + }, + }); + return session; +} + +function createShutdownScript(options: { + duringMarker: string; + failureMarker: string; + reloadMarker: string; + injectFailure: boolean; + urgentLevel: number; +}): string { + const fixtures = JSON.stringify(options); + return ` + const fixtures=${fixtures}; + const plugin=app.plugins.plugins["obsidian-livesync"]; + const core=plugin?.core; + require(core,"The LiveSync plug-in did not expose its core"); + const module=core.modules.find(candidate=>candidate.constructor.name==="ModuleLog"); + require(module,"The loaded core did not contain ModuleLog"); + const api=core.services.API; + const database=core.services.database.localDatabaseDirect; + require(database,"The loaded core did not expose its local database"); + + let releaseCloseGate; + const closeGate=new Promise(resolve=>{releaseCloseGate=resolve;}); + const state={ + core, + api, + module, + fixtureLogs:[], + events:[], + closeStarted:false, + closeCalls:0, + disposeCalls:0, + disposeCompleted:false, + closeGateReleased:false, + disableError:"", + }; + app.__livesyncLogLifecycleState=state; + + const originalAddLog=module.__addLog; + module.__addLog=function(message,level,key) { + if(typeof message==="string" && [ + fixtures.duringMarker, + fixtures.failureMarker, + fixtures.reloadMarker + ].some(marker=>marker && message.includes(marker))) { + state.fixtureLogs.push({message,level,key}); + const marker=[fixtures.duringMarker,fixtures.failureMarker,fixtures.reloadMarker] + .find(candidate=>candidate && message.includes(candidate)); + state.events.push("log:"+marker); + } + return originalAddLog.apply(this,arguments); + }; + + const resource=module.logResource; + const originalDispose=resource.dispose; + resource.dispose=async function() { + state.disposeCalls++; + state.events.push("dispose-start"); + try { + return await originalDispose.apply(this,arguments); + } finally { + state.disposeCompleted=true; + state.events.push("dispose-complete"); + } + }; + + const originalClose=database.close; + database.close=async function() { + state.closeCalls++; + if(state.closeCalls===1) { + state.closeStarted=true; + state.events.push("close-start"); + await closeGate; + } + const result=await originalClose.apply(this,arguments); + if(state.closeCalls===1) { + state.events.push("close-finished"); + if(fixtures.injectFailure) { + state.events.push("close-failure-injected"); + throw new Error(fixtures.failureMarker); + } + } + return result; + }; + + state.restore=()=>{ + module.__addLog=originalAddLog; + resource.dispose=originalDispose; + database.close=originalClose; + }; + + const run=async()=>{ + state.disablePromise=app.plugins.disablePlugin("obsidian-livesync"); + state.disablePromise.catch(error=>{state.disableError=String(error);}); + await waitFor(()=>state.closeStarted,"The real local database close did not start"); + require(state.disposeCalls===0 && !state.disposeCompleted, + "The log resource was released before database shutdown completed"); + api.addLog(fixtures.duringMarker,undefined,"e2e-log-lifecycle-during-close"); + await waitFor( + ()=>state.fixtureLogs.some(entry=>entry.message.includes(fixtures.duringMarker)), + "ModuleLog did not receive the during-close log" + ); + require(state.disposeCalls===0,"The log resource was released while database close was gated"); + releaseCloseGate(); + state.closeGateReleased=true; + await waitFor(()=>state.disposeCompleted,"The log resource was not released after database close"); + + require(state.closeCalls===1,"The local database close was not observed exactly once"); + require(state.disposeCalls===1,"The log resource was not disposed exactly once"); + require(state.events.indexOf("close-finished")>=0 && + state.events.indexOf("close-finished")entry.message.includes(fixtures.failureMarker)) + : undefined; + if(fixtures.injectFailure) { + require(failedLog,"The injected post-close failure was not logged"); + require(failedLog.key==="shutdown","The shutdown failure log used the wrong key"); + require(failedLog.level===fixtures.urgentLevel,"The shutdown failure log was not urgent"); + require( + state.events.indexOf("close-finished")state.disposeCompleted,"Cleanup timed out waiting for log resource disposal"); + } catch {} + } + } + `; +} + +async function runCase(options: { + binary: string; + cliBinary: string; + caseName: string; + injectFailure: boolean; +}): Promise> { + const vault = await createTemporaryVault(`obsidian-log-lifecycle-${options.caseName}-`); + let session: ObsidianLiveSyncSession | undefined; + const markers = { + duringMarker: `log-lifecycle-${options.caseName}-during-${randomUUID()}`, + failureMarker: options.injectFailure + ? `log-lifecycle-${options.caseName}-injected-close-failure-${randomUUID()}` + : "", + reloadMarker: options.injectFailure ? "" : `log-lifecycle-${options.caseName}-reload-${randomUUID()}`, + injectFailure: options.injectFailure, + urgentLevel: LOG_LEVEL_URGENT, + }; + + try { + session = await startSession(options.binary, options.cliBinary, vault); + await waitForLiveSyncCoreReady(options.cliBinary, session.cliEnv); + const shutdown = await evaluate(options.cliBinary, session, createShutdownScript(markers)); + if (options.injectFailure) { + return { caseName: options.caseName, shutdown }; + } + + await evaluate( + options.cliBinary, + session, + `await app.plugins.enablePlugin("obsidian-livesync"); return JSON.stringify({enabled:true});` + ); + await waitForLiveSyncCoreReady(options.cliBinary, session.cliEnv); + const reload = await evaluate>( + options.cliBinary, + session, + ` + const state=app.__livesyncLogLifecycleState; + require(state,"The old core observation was not retained across plug-in reload"); + const plugin=app.plugins.plugins["obsidian-livesync"]; + const core=plugin?.core; + require(core && core!==state.core,"Enabling the plug-in did not create a new core"); + const module=core.modules.find(candidate=>candidate.constructor.name==="ModuleLog"); + require(module,"The reloaded core did not contain ModuleLog"); + const originalAddLog=module.__addLog; + const observed=[]; + module.__addLog=function(message,level,key) { + if(typeof message==="string" && message.includes(${JSON.stringify(markers.reloadMarker)})) { + observed.push({message,level,key}); + } + return originalAddLog.apply(this,arguments); + }; + try { + core.services.API.addLog(${JSON.stringify(markers.reloadMarker)},undefined,"e2e-log-lifecycle-reload"); + await waitFor(()=>observed.length>0,"The reloaded ModuleLog did not receive its API log"); + require(observed.length===1,"The reloaded ModuleLog received the fixture log more than once"); + require( + !state.fixtureLogs.some(entry=>entry.message.includes(${JSON.stringify(markers.reloadMarker)})), + "The old ModuleLog observer received the reloaded core's fixture log" + ); + let oldHandlerDetached=false; + try { + state.api.addLog("e2e-log-lifecycle-reloaded-old-api"); + } catch(error) { + oldHandlerDetached=String(error).includes("not assigned"); + } + require(oldHandlerDetached,"The old API log handler was reassigned after reload"); + return JSON.stringify({ + coreChanged:core!==state.core, + observedByNewModule:observed.length, + observedByOldModule:state.fixtureLogs.filter( + entry=>entry.message.includes(${JSON.stringify(markers.reloadMarker)}) + ).length + }); + } finally { + module.__addLog=originalAddLog; + state.restore(); + delete app.__livesyncLogLifecycleState; + } + ` + ); + return { caseName: options.caseName, shutdown, reload }; + } finally { + if (session) { + try { + await evaluate( + options.cliBinary, + session, + ` + const state=app.__livesyncLogLifecycleState; + state?.restore?.(); + delete app.__livesyncLogLifecycleState; + return JSON.stringify({cleaned:true}); + ` + ); + } catch {} + try { + await session.app.stop(); + } finally { + await vault.dispose(); + } + } else { + await vault.dispose(); + } + } +} + +async function main(): Promise { + const binary = requireObsidianBinary(); + const cliBinary = requireObsidianCli(); + const bundleHash = createHash("sha256") + .update(new Uint8Array(await readFile("main.js"))) + .digest("hex"); + + const observations = [ + await runCase({ binary, cliBinary, caseName: "normal", injectFailure: false }), + await runCase({ binary, cliBinary, caseName: "controlled-failure", injectFailure: true }), + ]; + console.log(JSON.stringify({ ok: true, bundleHash, observations }, null, 2)); +} + +await main(); diff --git a/test/e2e-obsidian/scripts/run-focused.ts b/test/e2e-obsidian/scripts/run-focused.ts index ffb805ed..adbfcf03 100644 --- a/test/e2e-obsidian/scripts/run-focused.ts +++ b/test/e2e-obsidian/scripts/run-focused.ts @@ -49,6 +49,7 @@ const focusedScenarios = new Set([ "customisation-sync", "customisation-catalogue-reload", "optional-file-save-completion", + "log-lifecycle", "livesync-batch", "received-change-readiness", "internal-metadata-doctor", diff --git a/updates.md b/updates.md index f5551d3b..c217ef94 100644 --- a/updates.md +++ b/updates.md @@ -12,6 +12,11 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi ## Unreleased +### Diagnostics + +- Service log calls stay with the plug-in instance that registered them. Its log connection is released after the full shutdown, so stale instances cannot receive later service messages. + + ## 1.0.42 27th October, 2026 From cfdc6987751041ae9464fd090eff86fd622d0e67 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Thu, 29 Oct 2026 14:56:56 +0000 Subject: [PATCH 02/24] Reuse scoped content and progress operations --- src/common/pathCompatibility.ts | 10 +- src/common/utils.ts | 9 - .../CmdConfigSync.applyContent.unit.spec.ts | 275 +++++++++++++++++ ...ConfigSync.scanAllConfigFiles.unit.spec.ts | 279 ++++++++++++++++++ src/features/ConfigSync/CmdConfigSync.ts | 109 ++++--- ...iddenFileSync.attemptProgress.unit.spec.ts | 143 +++++++++ .../CmdHiddenFileSync.progress.unit.spec.ts | 219 ++++++++++++++ .../HiddenFileSync/CmdHiddenFileSync.ts | 67 +++-- .../CmdHiddenFileSync.unit.spec.ts | 79 +++++ .../performBatchWithProgress.ts | 49 +++ .../performBatchWithProgress.unit.spec.ts | 93 ++++++ .../StatusBarDisplay.timeout.unit.spec.ts | 142 +++++++++ src/modules/features/StatusBarDisplay.ts | 81 +++-- .../features/StatusBarDisplay.unit.spec.ts | 119 ++++++++ ...icateResultProcessor.counting.unit.spec.ts | 46 +++ .../replication/ReplicateResultProcessor.ts | 8 +- 16 files changed, 1596 insertions(+), 132 deletions(-) create mode 100644 src/features/ConfigSync/CmdConfigSync.applyContent.unit.spec.ts create mode 100644 src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts create mode 100644 src/features/HiddenFileSync/CmdHiddenFileSync.attemptProgress.unit.spec.ts create mode 100644 src/features/HiddenFileSync/CmdHiddenFileSync.progress.unit.spec.ts create mode 100644 src/features/HiddenFileSync/performBatchWithProgress.ts create mode 100644 src/features/HiddenFileSync/performBatchWithProgress.unit.spec.ts create mode 100644 src/modules/features/StatusBarDisplay.timeout.unit.spec.ts create mode 100644 src/serviceFeatures/replication/ReplicateResultProcessor.counting.unit.spec.ts diff --git a/src/common/pathCompatibility.ts b/src/common/pathCompatibility.ts index 69ad7254..b9f3b1ff 100644 --- a/src/common/pathCompatibility.ts +++ b/src/common/pathCompatibility.ts @@ -1,3 +1,5 @@ +import { findPathComponentsExceedingUtf8Limit as findKitPathComponentsExceedingUtf8Limit } from "octagonal-wheels/path"; + export const ANDROID_LINUX_PATH_COMPONENT_UTF8_WARNING_BOUNDARY = 255; export interface OversizedPathComponent { @@ -5,8 +7,6 @@ export interface OversizedPathComponent { utf8Bytes: number; } -const utf8Encoder = new TextEncoder(); - /** * Return path components which exceed the conservative Android/Linux * compatibility boundary. @@ -18,9 +18,5 @@ export function findPathComponentsExceedingUtf8Limit( path: string, maxBytes: number = ANDROID_LINUX_PATH_COMPONENT_UTF8_WARNING_BOUNDARY ): OversizedPathComponent[] { - return path - .split("/") - .filter((component) => component.length > 0) - .map((component) => ({ component, utf8Bytes: utf8Encoder.encode(component).byteLength })) - .filter(({ utf8Bytes }) => utf8Bytes > maxBytes); + return findKitPathComponentsExceedingUtf8Limit(path, maxBytes); } diff --git a/src/common/utils.ts b/src/common/utils.ts index f4bc621d..fc248ff1 100644 --- a/src/common/utils.ts +++ b/src/common/utils.ts @@ -389,13 +389,4 @@ export async function autosaveCache(db: KeyValueDatabase, mapKey: string): }; } -export function onlyInNTimes(n: number, proc: (progress: number) => unknown) { - let counter = 0; - return function () { - if (counter++ % n == 0) { - proc(counter); - } - }; -} - export { displayRev } from "@vrtmrz/livesync-commonlib/compat/common/utils"; diff --git a/src/features/ConfigSync/CmdConfigSync.applyContent.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.applyContent.unit.spec.ts new file mode 100644 index 00000000..95e7cab2 --- /dev/null +++ b/src/features/ConfigSync/CmdConfigSync.applyContent.unit.spec.ts @@ -0,0 +1,275 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@/deps.ts", () => ({ + addIcon: vi.fn(), + diff_match_patch: class DiffMatchPatch {}, + normalizePath: vi.fn((path: string) => path), + parseYaml: vi.fn(), + Platform: {}, +})); +vi.mock("./PluginDialogModal.ts", () => ({ + PluginDialogModal: class PluginDialogModal {}, +})); +vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ + JsonResolveModal: class JsonResolveModal {}, +})); +vi.mock("@/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts", () => ({ + ConflictResolveModal: class ConflictResolveModal {}, +})); +vi.mock("@/features/LiveSyncCommands.ts", () => ({ + LiveSyncCommands: class LiveSyncCommands { + core!: { services: unknown }; + get services() { + return this.core.services; + } + }, +})); +vi.mock("@/common/types.ts", () => ({ + ICXHeader: "ix:", + PERIODIC_PLUGIN_SWEEP: 60, +})); +vi.mock("@/common/utils.ts", () => ({ + cancelTask: vi.fn(), + EVEN: Symbol("even"), + isCustomisationSyncMetadata: vi.fn(), + isPluginMetadata: vi.fn(), + scheduleTask: vi.fn(), +})); +vi.mock("@/common/PeriodicProcessor.ts", () => ({ + PeriodicProcessor: class PeriodicProcessor {}, +})); +vi.mock("@/common/events.ts", () => ({ + EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG: "open-plugin-sync", + eventHub: { + onEvent: vi.fn(), + }, +})); +vi.mock("@/common/translation", () => ({ + $msg: vi.fn((message: string) => message), +})); +vi.mock("@/common/obsidianCommunityPlugins.ts", () => ({ + getObsidianCommunityPluginManager: vi.fn(), +})); + +import { LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "@vrtmrz/livesync-commonlib/compat/common/types"; +import { ConfigSync, type PluginDataExDisplayV2 } from "./CmdConfigSync"; + +const BASE_DIR = ".obsidian"; +const DEVICE_NAME = "test-device"; +const STAT = { mtime: 123456, ctime: 123000 }; + +type ApplyFile = { + filename: string; + datatype: "newnote" | "plain"; + data: string[]; + mtime: number; + ctime: number; +}; + +function makeApplyFile(datatype: ApplyFile["datatype"], data: string[]): ApplyFile { + return { + filename: "plugins/example/data.json", + datatype, + data, + mtime: STAT.mtime, + ctime: STAT.ctime, + }; +} + +function setup(file: ApplyFile, currentText = "before", currentBinary = new ArrayBuffer(0)) { + const path = `${BASE_DIR}/${file.filename}`; + const events: string[] = []; + const storageAccess = { + ensureDir: vi.fn(async (_path: string) => { + events.push("ensure"); + }), + readHiddenFileText: vi.fn(async (_path: string) => { + events.push("read-text"); + return currentText; + }), + readHiddenFileBinary: vi.fn(async (_path: string) => { + events.push("read-binary"); + return currentBinary; + }), + writeHiddenFileAuto: vi.fn( + async (_path: string, _content: string | ArrayBuffer, _stat?: { mtime: number; ctime: number }) => { + events.push("write"); + } + ), + }; + const storeCustomisationFileV2 = vi.fn(async (_path: string, _term: string) => { + events.push("store"); + return true; + }); + const log = vi.fn(); + const configSync = Object.create(ConfigSync.prototype) as ConfigSync; + Object.assign(configSync, { + core: { + services: { + API: { getSystemConfigDir: () => BASE_DIR }, + setting: { getDeviceAndVaultName: () => DEVICE_NAME }, + }, + storageAccess, + }, + _log: log, + storeCustomisationFileV2, + }); + const data = { + displayName: "Example plug-in", + name: "example", + files: [file], + } as unknown as PluginDataExDisplayV2; + return { configSync, data, events, log, path, storageAccess, storeCustomisationFileV2 }; +} + +const changedInputs = [ + { + kind: "text", + file: makeApplyFile("plain", ["replacement text"]), + currentText: "previous text", + expectedText: "replacement text", + }, + { + kind: "binary", + file: makeApplyFile("newnote", ["AQID"]), + currentBinary: new Uint8Array([9]).buffer, + expectedBytes: [1, 2, 3], + }, +] as const; + +const unchangedInputs = [ + { + kind: "text", + file: makeApplyFile("plain", ["unchanged text"]), + currentText: "unchanged text", + }, + { + kind: "binary", + file: makeApplyFile("newnote", ["AQID"]), + currentBinary: new Uint8Array([1, 2, 3]).buffer, + }, +] as const; + +describe("ConfigSync V2 content application", () => { + it.each(changedInputs)("writes changed $kind content, then stores it", async (input) => { + const fixture = setup( + input.file, + input.kind === "text" ? input.currentText : undefined, + input.kind === "binary" ? input.currentBinary : undefined + ); + + await expect(fixture.configSync.applyDataV2(fixture.data)).resolves.toBe(true); + + expect(fixture.storageAccess.ensureDir).toHaveBeenCalledWith(fixture.path); + expect(fixture.storageAccess.writeHiddenFileAuto).toHaveBeenCalledOnce(); + expect(fixture.storageAccess.writeHiddenFileAuto).toHaveBeenCalledWith( + fixture.path, + input.kind === "text" ? input.expectedText : expect.any(ArrayBuffer), + STAT + ); + if (input.kind === "binary") { + const written = fixture.storageAccess.writeHiddenFileAuto.mock.calls[0]?.[1]; + expect(written).toBeInstanceOf(ArrayBuffer); + expect(Array.from(new Uint8Array(written as ArrayBuffer))).toEqual(input.expectedBytes); + } + expect(fixture.events).toEqual([ + "ensure", + input.kind === "text" ? "read-text" : "read-binary", + "write", + "store", + ]); + expect(fixture.storeCustomisationFileV2).toHaveBeenCalledWith(fixture.path, DEVICE_NAME); + }); + + it("writes the file timestamps captured before reading existing content", async () => { + const file = makeApplyFile("plain", ["replacement text"]); + const fixture = setup(file, "previous text"); + fixture.storageAccess.readHiddenFileText.mockImplementation(async () => { + fixture.events.push("read-text"); + file.mtime = STAT.mtime + 1; + file.ctime = STAT.ctime + 1; + return "previous text"; + }); + + await expect(fixture.configSync.applyDataV2(fixture.data)).resolves.toBe(true); + + expect(fixture.storageAccess.writeHiddenFileAuto).toHaveBeenCalledWith(fixture.path, "replacement text", STAT); + }); + + it.each(unchangedInputs)("skips writing and storing unchanged $kind content", async (input) => { + const fixture = setup( + input.file, + input.kind === "text" ? input.currentText : undefined, + input.kind === "binary" ? input.currentBinary : undefined + ); + + await expect(fixture.configSync.applyDataV2(fixture.data)).resolves.toBe(true); + + expect(fixture.storageAccess.writeHiddenFileAuto).not.toHaveBeenCalled(); + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + expect(fixture.events).toEqual(["ensure", input.kind === "text" ? "read-text" : "read-binary"]); + expect(fixture.log).toHaveBeenCalledWith( + `The file ${input.file.filename} is already up-to-date`, + LOG_LEVEL_VERBOSE + ); + }); + + it.each([ + { kind: "text", file: makeApplyFile("plain", ["replacement text"]) }, + { kind: "binary", file: makeApplyFile("newnote", ["AQID"]) }, + ])("uses empty $kind content when reading the existing file fails", async ({ kind, file }) => { + const fixture = setup(file); + const readError = new Error("Could not read existing content"); + if (kind === "text") { + fixture.storageAccess.readHiddenFileText.mockRejectedValueOnce(readError); + } else { + fixture.storageAccess.readHiddenFileBinary.mockRejectedValueOnce(readError); + } + + await expect(fixture.configSync.applyDataV2(fixture.data)).resolves.toBe(true); + + expect(fixture.storageAccess.writeHiddenFileAuto).toHaveBeenCalledOnce(); + expect(fixture.storeCustomisationFileV2).toHaveBeenCalledWith(fixture.path, DEVICE_NAME); + expect(fixture.log).toHaveBeenCalledWith(`Could not read the file ${file.filename}`, LOG_LEVEL_VERBOSE); + expect(fixture.log).toHaveBeenCalledWith(readError, LOG_LEVEL_VERBOSE); + }); + + it("awaits the write before storing the applied content", async () => { + const file = makeApplyFile("plain", ["replacement text"]); + const fixture = setup(file, "previous text"); + let finishWrite!: () => void; + let signalWriteStarted!: () => void; + const writeGate = new Promise((resolve) => { + finishWrite = resolve; + }); + const writeStarted = new Promise((resolve) => { + signalWriteStarted = resolve; + }); + fixture.storageAccess.writeHiddenFileAuto.mockImplementation(async () => { + fixture.events.push("write-start"); + signalWriteStarted(); + await writeGate; + fixture.events.push("write-finished"); + }); + + const applying = fixture.configSync.applyDataV2(fixture.data); + await writeStarted; + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + + finishWrite(); + await expect(applying).resolves.toBe(true); + expect(fixture.events.slice(-3)).toEqual(["write-start", "write-finished", "store"]); + }); + + it("returns false after a write failure and does not store the file", async () => { + const fixture = setup(makeApplyFile("plain", ["replacement text"]), "previous text"); + const writeError = new Error("Write failed"); + fixture.storageAccess.writeHiddenFileAuto.mockRejectedValueOnce(writeError); + + await expect(fixture.configSync.applyDataV2(fixture.data)).resolves.toBe(false); + + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + expect(fixture.log).toHaveBeenCalledWith("Applying Example plug-in.. Failed", LOG_LEVEL_NOTICE); + expect(fixture.log).toHaveBeenCalledWith(writeError, LOG_LEVEL_VERBOSE); + }); +}); diff --git a/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts new file mode 100644 index 00000000..069fdab6 --- /dev/null +++ b/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts @@ -0,0 +1,279 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/deps.ts", () => ({ + addIcon: vi.fn(), + diff_match_patch: class DiffMatchPatch {}, + normalizePath: vi.fn((path: string) => path), + parseYaml: vi.fn(), + Platform: {}, +})); +vi.mock("./PluginDialogModal.ts", () => ({ + PluginDialogModal: class PluginDialogModal {}, +})); +vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ + JsonResolveModal: class JsonResolveModal {}, +})); +vi.mock("@/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts", () => ({ + ConflictResolveModal: class ConflictResolveModal {}, +})); +vi.mock("@/features/LiveSyncCommands.ts", () => ({ + LiveSyncCommands: class LiveSyncCommands { + core!: { services: unknown; localDatabase: unknown }; + get localDatabase() { + return this.core.localDatabase; + } + get services() { + return this.core.services; + } + }, +})); +vi.mock("@/common/types.ts", () => ({ + ICXHeader: "ix:", + PERIODIC_PLUGIN_SWEEP: 60, +})); +vi.mock("@/common/utils.ts", () => ({ + cancelTask: vi.fn(), + EVEN: Symbol("even"), + isCustomisationSyncMetadata: vi.fn(), + isPluginMetadata: vi.fn(), + scheduleTask: vi.fn(), +})); +vi.mock("@/common/PeriodicProcessor.ts", () => ({ + PeriodicProcessor: class PeriodicProcessor {}, +})); +vi.mock("@/common/events.ts", () => ({ + EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG: "open-plugin-sync", + eventHub: { + onEvent: vi.fn(), + }, +})); +vi.mock("@/common/translation", () => ({ + $msg: vi.fn((message: string) => message), +})); +vi.mock("@/common/obsidianCommunityPlugins.ts", () => ({ + getObsidianCommunityPluginManager: vi.fn(), +})); + +vi.mock("octagonal-wheels/concurrency/scopedIteration", { spy: true }); + +import { LOG_LEVEL_VERBOSE, type FilePath } from "@vrtmrz/livesync-commonlib/compat/common/types"; +import * as iterationModule from "octagonal-wheels/concurrency/scopedIteration"; +import { promiseWithResolvers } from "octagonal-wheels/promises"; +import { ConfigSync } from "./CmdConfigSync"; + +const term = "device"; +const prefix = `ix:${term}/`; +const keyOf = (path: string) => prefix + path; +type Row = { _id: string; path: string }; +const row = (name: string, path = name): Row => ({ _id: keyOf(name), path }); + +function setup(files: string[] = [], rows: Row[] = []) { + const events: string[] = []; + const findEntries = vi.fn(async function* () { + yield* rows; + }); + const scanInternalFiles = vi.fn(async () => files as FilePath[]); + const storeCustomisationFileV2 = vi.fn(async (path: string, _term: string) => { + events.push(`store:${path}`); + }); + const deleteConfigOnDatabase = vi.fn(async (key: string) => { + events.push(`delete:${key}`); + }); + const updatePluginList = vi.fn(async (_showMessage: boolean) => {}); + const log = vi.fn(); + const configSync = Object.create(ConfigSync.prototype) as ConfigSync; + Object.assign(configSync, { + core: { + settings: { usePluginSyncV2: true }, + localDatabase: { findEntries }, + services: { setting: { getDeviceAndVaultName: () => term } }, + }, + scanInternalFiles, + isTargetPath: (path: string) => path !== "ignored", + filenameWithUnifiedKey: (path: string, _term: string) => keyOf(path), + unifiedKeyPrefixOfTerminal: (_term: string) => prefix, + storeCustomisationFileV2, + deleteConfigOnDatabase, + updatePluginList, + _log: log, + }); + return { + configSync, + events, + findEntries, + scanInternalFiles, + storeCustomisationFileV2, + deleteConfigOnDatabase, + updatePluginList, + log, + }; +} + +beforeEach(() => { + vi.clearAllMocks(); +}); + +describe("ConfigSync V2 scan behaviour", () => { + it("finishes existing database entries before storing extra files and retains target filtering", async () => { + const fixture = setup( + ["matched", "extra", "ignored"], + [row("matched"), row("stale"), row("encoded", "encoded%path")] + ); + await fixture.configSync.scanAllConfigFiles(false); + + expect(fixture.events).toEqual(["store:matched", `delete:${keyOf("stale")}`, "store:extra"]); + expect(fixture.storeCustomisationFileV2.mock.calls).toEqual([ + ["matched", term], + ["extra", term], + ]); + expect(fixture.deleteConfigOnDatabase).toHaveBeenCalledExactlyOnceWith(keyOf("stale")); + expect(fixture.findEntries).toHaveBeenCalledExactlyOnceWith(prefix, `${prefix}\u{10ffff}`, { + include_docs: true, + }); + expect(fixture.updatePluginList).toHaveBeenCalledExactlyOnceWith(false); + }); + + it("finishes database enumeration before dispatching database work", async () => { + const fixture = setup(); + const enumerationPaused = promiseWithResolvers(); + const continueEnumeration = promiseWithResolvers(); + fixture.findEntries.mockImplementation(async function* () { + yield row("stale"); + enumerationPaused.resolve(); + await continueEnumeration.promise; + }); + + const scan = fixture.configSync.scanAllConfigFiles(false); + try { + await enumerationPaused.promise; + expect(fixture.deleteConfigOnDatabase).not.toHaveBeenCalled(); + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + } finally { + continueEnumeration.resolve(); + await scan; + } + + expect(fixture.deleteConfigOnDatabase).toHaveBeenCalledExactlyOnceWith(keyOf("stale")); + }); + + it("limits actual database operations to ten and completes that batch before the extra batch", async () => { + const fixture = setup( + ["extra"], + Array.from({ length: 11 }, (_, index) => row(String(index))) + ); + const gates = Array.from({ length: 11 }, () => promiseWithResolvers()); + const tenStarted = promiseWithResolvers(); + const lastStarted = promiseWithResolvers(); + let active = 0; + let maximum = 0; + let started = 0; + fixture.deleteConfigOnDatabase.mockImplementation(async (key) => { + const index = Number(key.slice(prefix.length)); + active++; + maximum = Math.max(maximum, active); + started++; + if (started === 10) tenStarted.resolve(); + if (index === 10) lastStarted.resolve(); + try { + await gates[index].promise; + } finally { + active--; + } + }); + const scan = fixture.configSync.scanAllConfigFiles(false); + try { + await tenStarted.promise; + expect(active).toBe(10); + expect(started).toBe(10); + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + gates[0].resolve(); + await lastStarted.promise; + expect(active).toBe(10); + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + } finally { + gates.forEach((gate) => gate.resolve()); + await scan; + } + expect(maximum).toBe(10); + expect(active).toBe(0); + expect(fixture.deleteConfigOnDatabase).toHaveBeenCalledTimes(11); + expect(fixture.storeCustomisationFileV2).toHaveBeenCalledExactlyOnceWith("extra", term); + }); + + it("logs a database processing error and continues through the extra batch", async () => { + const fixture = setup(["extra"], [row("bad"), row("other")]); + const error = new Error("delete"); + fixture.deleteConfigOnDatabase.mockRejectedValueOnce(error); + await fixture.configSync.scanAllConfigFiles(false); + + expect(fixture.deleteConfigOnDatabase).toHaveBeenCalledTimes(2); + expect(fixture.log).toHaveBeenCalledWith(`scanAllConfigFiles - Error: ${keyOf("bad")}`, LOG_LEVEL_VERBOSE); + expect(fixture.log).toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(fixture.storeCustomisationFileV2).toHaveBeenCalledExactlyOnceWith("extra", term); + expect(fixture.updatePluginList).toHaveBeenCalledOnce(); + }); + + it("retains a matched local file for the extra batch when its first store fails", async () => { + const fixture = setup(["matched"], [row("matched")]); + const error = new Error("first store"); + fixture.storeCustomisationFileV2.mockRejectedValueOnce(error); + await fixture.configSync.scanAllConfigFiles(false); + + expect(fixture.storeCustomisationFileV2.mock.calls).toEqual([ + ["matched", term], + ["matched", term], + ]); + expect(fixture.log).toHaveBeenCalledWith(`scanAllConfigFiles - Error: ${keyOf("matched")}`, LOG_LEVEL_VERBOSE); + expect(fixture.log).toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(fixture.events).toEqual(["store:matched"]); + expect(fixture.updatePluginList).toHaveBeenCalledOnce(); + }); + + it("logs an extra-file processing error and continues with the remaining files", async () => { + const fixture = setup(["bad", "other"]); + const error = new Error("store"); + fixture.storeCustomisationFileV2.mockRejectedValueOnce(error); + await fixture.configSync.scanAllConfigFiles(false); + + expect(fixture.storeCustomisationFileV2.mock.calls).toEqual([ + ["bad", term], + ["other", term], + ]); + expect(fixture.log).toHaveBeenCalledWith("scanAllConfigFiles - Error: bad", LOG_LEVEL_VERBOSE); + expect(fixture.log).toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(fixture.updatePluginList).toHaveBeenCalledOnce(); + }); +}); + +describe("ConfigSync scoped iteration composition", () => { + it("uses bounded child scopes for both batches with the same shared values", async () => { + const fixture = setup(["matched", "extra"], [row("matched"), row("stale")]); + await fixture.configSync.scanAllConfigFiles(false); + + expect(iterationModule.forEachInScope).toHaveBeenCalledTimes(2); + const [database, extra] = vi.mocked(iterationModule.forEachInScope).mock.calls; + expect(database[0]).toBe(extra[0]); + expect(database[0].value).toEqual({ term, localFileMap: new Map([[keyOf("extra"), "extra"]]) }); + expect(database[2]).toEqual({ concurrency: 10 }); + expect(extra[2]).toEqual({ concurrency: 10 }); + expect(fixture.events).toEqual(["store:matched", `delete:${keyOf("stale")}`, "store:extra"]); + }); + + it.each(["database", "extra"])("propagates a %s runner failure outside per-item recovery", async (batch) => { + const fixture = setup(["extra"], [row("stale")]); + const error = new Error("iteration"); + const actual = await vi.importActual( + "octagonal-wheels/concurrency/scopedIteration" + ); + if (batch === "extra") { + vi.mocked(iterationModule.forEachInScope).mockImplementationOnce(actual.forEachInScope); + } + vi.mocked(iterationModule.forEachInScope).mockRejectedValueOnce(error); + await expect(fixture.configSync.scanAllConfigFiles(false)).rejects.toBe(error); + + expect(fixture.deleteConfigOnDatabase).toHaveBeenCalledTimes(batch === "extra" ? 1 : 0); + expect(fixture.storeCustomisationFileV2).not.toHaveBeenCalled(); + expect(fixture.log).not.toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(fixture.updatePluginList).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/ConfigSync/CmdConfigSync.ts b/src/features/ConfigSync/CmdConfigSync.ts index 68ba9703..1902c590 100644 --- a/src/features/ConfigSync/CmdConfigSync.ts +++ b/src/features/ConfigSync/CmdConfigSync.ts @@ -59,7 +59,8 @@ import { QueueProcessor } from "octagonal-wheels/concurrency/processor"; import { pluginScanningCount } from "@vrtmrz/livesync-commonlib/compat/mock_and_interop/stores"; import { base64ToArrayBuffer, base64ToString } from "octagonal-wheels/binary/base64"; import { ConflictResolveModal } from "@/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts"; -import { Semaphore } from "octagonal-wheels/concurrency/semaphore"; +import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { withScope } from "octagonal-wheels/resource/scope"; import { EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG, eventHub } from "@/common/events.ts"; import { PluginDialogModal } from "./PluginDialogModal.ts"; import { $msg } from "@/common/translation"; @@ -68,6 +69,7 @@ import type { LiveSyncCore } from "@/main.ts"; import { LiveSyncError } from "@vrtmrz/livesync-commonlib/compat/common/LSError"; import type { OptionalSyncFeatureMode } from "@/features/optionalSyncFeatures.ts"; import { getObsidianCommunityPluginManager } from "@/common/obsidianCommunityPlugins.ts"; +import { createContentApplier } from "octagonal-wheels/content"; import type { HandlerOutcome } from "@vrtmrz/livesync-commonlib/compat/services/lib/HandlerUtils"; import type { OptionalFileEventOptions } from "@vrtmrz/livesync-commonlib/compat/services/base/IService"; @@ -285,6 +287,10 @@ export type PluginDataExDisplay = { mtime: number; }; type LoadedEntryPluginDataExFile = LoadedEntry & PluginDataExFile; +type ConfigFileApplicationTarget = { + readonly path: FilePath; + readonly stat: { readonly mtime: number; readonly ctime: number }; +}; function categoryToFolder(category: string, configDir: string = ""): string { switch (category) { @@ -1027,44 +1033,63 @@ export class ConfigSync extends LiveSyncCommands { await this.storeCustomisationFileV2(path, this.services.setting.getDeviceAndVaultName()); } else { const files = data.files; + const applyBinaryContent = createContentApplier< + ConfigFileApplicationTarget, + LoadedEntryPluginDataExFile, + ArrayBuffer, + ArrayBuffer + >({ + read: (target) => this.core.storageAccess.readHiddenFileBinary(target.path), + onReadError: (ex, _path, file) => { + this._log(`Could not read the file ${file.filename}`, LOG_LEVEL_VERBOSE); + this._log(ex, LOG_LEVEL_VERBOSE); + return new ArrayBuffer(0); + }, + decode: (file) => base64ToArrayBuffer(file.data), + isSame: (oldData, content) => isDocContentSame(oldData, content), + write: (target, content) => + this.core.storageAccess.writeHiddenFileAuto(target.path, content, target.stat), + }); + const applyTextContent = createContentApplier< + ConfigFileApplicationTarget, + LoadedEntryPluginDataExFile, + string, + string + >({ + read: (target) => this.core.storageAccess.readHiddenFileText(target.path), + onReadError: (ex, _path, file) => { + this._log(`Could not read the file ${file.filename}`, LOG_LEVEL_VERBOSE); + this._log(ex, LOG_LEVEL_VERBOSE); + return ""; + }, + decode: (file) => getDocData(file.data), + isSame: (oldData, content) => isDocContentSame(oldData, content), + write: (target, content) => + this.core.storageAccess.writeHiddenFileAuto(target.path, content, target.stat), + }); for (const f of files) { // If files have applied, modified time will be updated to the current time. - const stat = { mtime: f.mtime, ctime: f.ctime }; const path = `${baseDir}/${f.filename}` as FilePath; + const target: ConfigFileApplicationTarget = { + path, + stat: { mtime: f.mtime, ctime: f.ctime }, + }; this._log(`Applying ${f.filename} of ${data.displayName || data.name}..`); // const contentEach = createBlob(f.data); await this.core.storageAccess.ensureDir(path); if (f.datatype == "newnote") { - let oldData; - try { - oldData = await this.core.storageAccess.readHiddenFileBinary(path); - } catch (ex) { - this._log(`Could not read the file ${f.filename}`, LOG_LEVEL_VERBOSE); - this._log(ex, LOG_LEVEL_VERBOSE); - oldData = new ArrayBuffer(0); - } - const content = base64ToArrayBuffer(f.data); - if (await isDocContentSame(oldData, content)) { + const result = await applyBinaryContent(target, f); + if (result == "unchanged") { this._log(`The file ${f.filename} is already up-to-date`, LOG_LEVEL_VERBOSE); continue; } - await this.core.storageAccess.writeHiddenFileAuto(path, content, stat); } else { - let oldData; - try { - oldData = await this.core.storageAccess.readHiddenFileText(path); - } catch (ex) { - this._log(`Could not read the file ${f.filename}`, LOG_LEVEL_VERBOSE); - this._log(ex, LOG_LEVEL_VERBOSE); - oldData = ""; - } - const content = getDocData(f.data); - if (await isDocContentSame(oldData, content)) { + const result = await applyTextContent(target, f); + if (result == "unchanged") { this._log(`The file ${f.filename} is already up-to-date`, LOG_LEVEL_VERBOSE); continue; } - await this.core.storageAccess.writeHiddenFileAuto(path, content, stat); } this._log(`Applied ${f.filename} of ${data.displayName || data.name}..`); await this.storeCustomisationFileV2(path, this.services.setting.getDeviceAndVaultName()); @@ -1613,49 +1638,35 @@ export class ConfigSync extends LiveSyncCommands { const entries = this.localDatabase.findEntries(prefix + "", `${prefix}\u{10ffff}`, { include_docs: true, }); - const tasks = [] as (() => Promise)[]; - const concurrency = 10; - const semaphore = Semaphore(concurrency); + const databaseEntries: { _id: string; path: FilePathWithPrefix }[] = []; for await (const item of entries) { - if (item.path.indexOf("%") !== -1) { - continue; - } - tasks.push(async () => { - const releaser = await semaphore.acquire(); + if (item.path.indexOf("%") === -1) databaseEntries.push(item); + } + await withScope({ term, localFileMap }, async (scope) => { + await forEachInScope(scope, databaseEntries, { concurrency: 10 }, async (item, ctx) => { try { const unifiedFilenameWithKey = `${item._id}` as FilePathWithPrefix; - const localPath = localFileMap.get(unifiedFilenameWithKey); + const localPath = ctx.value.localFileMap.get(unifiedFilenameWithKey); if (localPath) { - await this.storeCustomisationFileV2(localPath, term); - localFileMap.delete(unifiedFilenameWithKey); + await this.storeCustomisationFileV2(localPath, ctx.value.term); + ctx.value.localFileMap.delete(unifiedFilenameWithKey); } else { await this.deleteConfigOnDatabase(unifiedFilenameWithKey); } } catch (ex) { this._log(`scanAllConfigFiles - Error: ${item._id}`, LOG_LEVEL_VERBOSE); this._log(ex, LOG_LEVEL_VERBOSE); - } finally { - releaser(); } }); - } - await Promise.all(tasks.map((e) => e())); - // Extra files - const taskExtra = [] as (() => Promise)[]; - for (const [, filePath] of localFileMap) { - taskExtra.push(async () => { - const releaser = await semaphore.acquire(); + await forEachInScope(scope, localFileMap.values(), { concurrency: 10 }, async (filePath, ctx) => { try { - await this.storeCustomisationFileV2(filePath, term); + await this.storeCustomisationFileV2(filePath, ctx.value.term); } catch (ex) { this._log(`scanAllConfigFiles - Error: ${filePath}`, LOG_LEVEL_VERBOSE); this._log(ex, LOG_LEVEL_VERBOSE); - } finally { - releaser(); } }); - } - await Promise.all(taskExtra.map((e) => e())); + }); fireAndForget(() => this.updatePluginList(false)); } else { const files = filesAll diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.attemptProgress.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.attemptProgress.unit.spec.ts new file mode 100644 index 00000000..02b40969 --- /dev/null +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.attemptProgress.unit.spec.ts @@ -0,0 +1,143 @@ +import { describe, expect, it, vi } from "vitest"; +import { + type DocumentID, + type FilePath, + type FilePathWithPrefix, + type MetaEntry, +} from "@vrtmrz/livesync-commonlib/compat/common/types"; + +vi.mock("@/deps.ts", () => ({})); +vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ + JsonResolveModal: class JsonResolveModal {}, +})); +vi.mock("@/features/LiveSyncCommands.ts", () => ({ + LiveSyncCommands: class LiveSyncCommands { + plugin!: { app: unknown }; + core!: { services: unknown; settings: unknown }; + get app() { + return this.plugin.app; + } + get services() { + return this.core.services; + } + get settings() { + return this.core.settings; + } + }, +})); +vi.mock("./configureHiddenFileSyncMode.ts", () => ({ + configureHiddenFileSyncMode: vi.fn(), +})); + +import { HiddenFileSync } from "./CmdHiddenFileSync.ts"; + +function createProgress(events: string[] = []) { + return { + log: vi.fn((message: string) => { + if (/^(?:\d+\/\d+|Checking \d+\/\d+)$/.test(message)) events.push(message); + }), + once: vi.fn(), + done: vi.fn(), + }; +} + +function createStoragePaths(count: number): FilePath[] { + return Array.from({ length: count }, (_, index) => `.obsidian/plugins/example/${index}.json` as FilePath); +} + +function createDatabaseEntries(count: number): MetaEntry[] { + return Array.from( + { length: count }, + (_, index) => + ({ + _id: `i:.obsidian/plugins/example/${index}.json` as DocumentID, + _rev: "1-test", + path: `i:.obsidian/plugins/example/${index}.json` as FilePathWithPrefix, + ctime: 1, + mtime: 1, + size: 0, + type: "plain", + datatype: "plain", + children: [], + eden: {}, + deleted: false, + }) as MetaEntry + ); +} + +function createHiddenFileSync(count: number, events: string[] = []) { + const progress = createProgress(events); + const statHidden = vi.fn(async () => { + events.push(`stat:${statHidden.mock.calls.length}`); + return { mtime: 1 }; + }); + const hiddenFileSync = Object.create(HiddenFileSync.prototype) as HiddenFileSync; + Object.assign(hiddenFileSync, { + _progress: vi.fn(() => progress), + _log: vi.fn(), + _fileInfoLastProcessed: new Map(), + _databaseInfoLastProcessed: new Map(), + scanInternalFileNames: vi.fn(async () => createStoragePaths(count)), + getAllDatabaseFiles: vi.fn(async () => createDatabaseEntries(count)), + getPath: vi.fn((file: MetaEntry) => file.path), + updateLastProcessed: vi.fn(), + scanAllStorageChanges: vi.fn(async () => undefined), + scanAllDatabaseChanges: vi.fn(async () => undefined), + resetLastProcessedDatabase: vi.fn(), + resetLastProcessedFile: vi.fn(), + useStorageFiles: vi.fn(async () => false), + useDatabaseFiles: vi.fn(async () => false), + trackStorageFileModification: vi.fn(async () => false), + trackDatabaseFileModification: vi.fn(async () => false), + core: { storageAccess: { statHidden } }, + }); + return { hiddenFileSync, progress, statHidden }; +} + +describe("HiddenFileSync attempt progress", () => { + it("reports applyOfflineChanges attempts at 1 and each 25 items, without a final partial count", async () => { + const events: string[] = []; + const { hiddenFileSync, progress } = createHiddenFileSync(52, events); + + await hiddenFileSync.applyOfflineChanges(false); + + expect(progress.log.mock.calls.map(([message]) => message).filter((message) => /^\d+\/\d+$/.test(message))).toEqual([ + "1/52", + "26/52", + "51/52", + ]); + expect(events.indexOf("51/52")).toBeLessThan(events.indexOf("stat:1")); + }); + + it("reports rebuildMerging attempts at 1 and each 100 items, without a final partial count", async () => { + const events: string[] = []; + const { hiddenFileSync, progress } = createHiddenFileSync(202, events); + + await hiddenFileSync.rebuildMerging(false); + + expect(progress.log.mock.calls.map(([message]) => message).filter((message) => message.startsWith("Checking "))).toEqual([ + "Checking 1/202", + "Checking 101/202", + "Checking 201/202", + ]); + expect(events.indexOf("Checking 101/202")).toBeLessThan(events.indexOf("stat:101")); + }); + + it("preserves stat failures from applyOfflineChanges", async () => { + const { hiddenFileSync, progress, statHidden } = createHiddenFileSync(1); + const error = new Error("stat failed"); + statHidden.mockRejectedValueOnce(error); + + await expect(hiddenFileSync.applyOfflineChanges(false)).rejects.toBe(error); + expect(progress.done).not.toHaveBeenCalled(); + }); + + it("preserves stat failures from rebuildMerging", async () => { + const { hiddenFileSync, progress, statHidden } = createHiddenFileSync(1); + const error = new Error("stat failed"); + statHidden.mockRejectedValueOnce(error); + + await expect(hiddenFileSync.rebuildMerging(false)).rejects.toBe(error); + expect(progress.done).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.progress.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.progress.unit.spec.ts new file mode 100644 index 00000000..dd301a80 --- /dev/null +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.progress.unit.spec.ts @@ -0,0 +1,219 @@ +import { describe, expect, it, vi } from "vitest"; +import { + LOG_LEVEL_VERBOSE, + type DocumentID, + type FilePath, + type FilePathWithPrefix, + type MetaEntry, +} from "@vrtmrz/livesync-commonlib/compat/common/types"; + +vi.mock("@/deps.ts", () => ({})); +vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ + JsonResolveModal: class JsonResolveModal {}, +})); +vi.mock("@/features/LiveSyncCommands.ts", () => ({ + LiveSyncCommands: class LiveSyncCommands { + plugin!: { app: unknown }; + core!: { services: unknown; settings: unknown }; + get app() { + return this.plugin.app; + } + get services() { + return this.core.services; + } + get settings() { + return this.core.settings; + } + }, +})); +vi.mock("./configureHiddenFileSyncMode.ts", () => ({ + configureHiddenFileSyncMode: vi.fn(), +})); + +import { HiddenFileSync } from "./CmdHiddenFileSync.ts"; + +function createProgress() { + return { + log: vi.fn(), + once: vi.fn(), + done: vi.fn(), + }; +} + +function createHiddenFileSync() { + const progress = createProgress(); + const log = vi.fn(); + const trackStorageFileModification = vi.fn(async (_file: FilePath) => false); + const trackDatabaseFileModification = vi.fn(async (_path: FilePath) => false); + const isTargetFile = vi.fn(async (_path: FilePath) => true); + const getPath = vi.fn((file: MetaEntry) => file.path); + const hiddenFileSync = Object.create(HiddenFileSync.prototype) as HiddenFileSync; + + Object.assign(hiddenFileSync, { + _progress: vi.fn(() => progress), + _log: log, + trackStorageFileModification, + trackDatabaseFileModification, + isTargetFile, + getPath, + }); + + return { + hiddenFileSync, + progress, + log, + trackStorageFileModification, + trackDatabaseFileModification, + isTargetFile, + }; +} + +function createStoragePaths(count: number): FilePath[] { + return Array.from({ length: count }, (_, index) => `.obsidian/plugins/example/${index}.json` as FilePath); +} + +function createDatabaseEntries(count: number): MetaEntry[] { + return Array.from( + { length: count }, + (_, index) => + ({ + _id: `i:.obsidian/plugins/example/${index}.json` as DocumentID, + _rev: "1-test", + path: `i:.obsidian/plugins/example/${index}.json` as FilePathWithPrefix, + ctime: 1, + mtime: 1, + size: 0, + type: "plain", + datatype: "plain", + children: [], + eden: {}, + deleted: false, + }) as MetaEntry + ); +} + +describe("HiddenFileSync batch progress consumers", () => { + it("counts completed storage modifications even when they return false", async () => { + const { hiddenFileSync, progress, trackStorageFileModification } = createHiddenFileSync(); + const files = createStoragePaths(101); + + await hiddenFileSync.trackScannedStorageChanges(files); + + expect(trackStorageFileModification).toHaveBeenCalledTimes(101); + expect(progress.log.mock.calls).toEqual([["1/101"], ["101/101"]]); + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("logs and skips failed storage items when counting progress", async () => { + const { hiddenFileSync, progress, log, trackStorageFileModification } = createHiddenFileSync(); + const files = createStoragePaths(100); + const failingFile = files[50]; + const error = new Error("Storage item failed"); + trackStorageFileModification.mockImplementation(async (file) => { + if (file === failingFile) throw error; + return false; + }); + + await hiddenFileSync.trackScannedStorageChanges(files); + + expect(progress.once).toHaveBeenCalledWith(`Failed to process storage change file:${failingFile}`); + expect(log).toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(progress.log.mock.calls).toEqual([["1/100"]]); + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("counts completed database items, including filtered items and false returns", async () => { + const { hiddenFileSync, progress, trackDatabaseFileModification, isTargetFile } = createHiddenFileSync(); + const files = createDatabaseEntries(101); + const filteredPath = ".obsidian/plugins/example/50.json" as FilePath; + isTargetFile.mockImplementation(async (path) => path !== filteredPath); + + await hiddenFileSync.trackScannedDatabaseChange(files); + + expect(isTargetFile).toHaveBeenCalledTimes(101); + expect(trackDatabaseFileModification).toHaveBeenCalledTimes(100); + expect(progress.log.mock.calls).toEqual([["1/101"], ["101/101"]]); + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("logs and skips failed database scan items when counting progress", async () => { + const { hiddenFileSync, progress, log, trackDatabaseFileModification } = createHiddenFileSync(); + const files = createDatabaseEntries(101); + const failingPath = ".obsidian/plugins/example/50.json" as FilePath; + const error = new Error("Database scan item failed"); + trackDatabaseFileModification.mockImplementation(async (path) => { + if (path === failingPath) throw error; + return false; + }); + + await hiddenFileSync.trackScannedDatabaseChange(files); + + expect(log).toHaveBeenCalledWith( + expect.stringContaining("Failed to process storage change file:"), + expect.anything() + ); + expect(log).toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(progress.log.mock.calls).toEqual([["1/101"]]); + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("uses the database-file progress interval and counts false returns", async () => { + const { hiddenFileSync, progress, trackDatabaseFileModification } = createHiddenFileSync(); + const files = createDatabaseEntries(26); + + await expect(hiddenFileSync.useDatabaseFiles(files)).resolves.toBe(true); + + expect(trackDatabaseFileModification).toHaveBeenCalledTimes(26); + expect(progress.log.mock.calls).toEqual([["Scanning database files..."], ["1/26"], ["26/26"]]); + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("logs and skips failed database-file items when counting progress", async () => { + const { hiddenFileSync, progress, log, trackDatabaseFileModification } = createHiddenFileSync(); + const files = createDatabaseEntries(26); + const failingPath = ".obsidian/plugins/example/12.json" as FilePath; + const error = new Error("Database file item failed"); + trackDatabaseFileModification.mockImplementation(async (path) => { + if (path === failingPath) throw error; + return false; + }); + + await expect(hiddenFileSync.useDatabaseFiles(files)).resolves.toBe(true); + + expect(log).toHaveBeenCalledWith(expect.stringContaining("Failed to process database changes:")); + expect(log).toHaveBeenCalledWith(error, LOG_LEVEL_VERBOSE); + expect(progress.log.mock.calls).toEqual([["Scanning database files..."], ["1/26"]]); + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("starts all storage work eagerly and calls done only after all promises resolve", async () => { + const { hiddenFileSync, progress, trackStorageFileModification } = createHiddenFileSync(); + const files = createStoragePaths(101); + const resolveModifications: Array<(result: boolean) => void> = []; + trackStorageFileModification.mockImplementation( + () => new Promise((resolve) => resolveModifications.push(resolve)) + ); + + const operation = hiddenFileSync.trackScannedStorageChanges(files); + expect(trackStorageFileModification).toHaveBeenCalledTimes(files.length); + expect(progress.done).not.toHaveBeenCalled(); + + for (const resolveModification of resolveModifications) resolveModification(false); + await operation; + + expect(progress.done).toHaveBeenCalledTimes(1); + }); + + it("does not call done when the item error handler rejects the batch", async () => { + const { hiddenFileSync, progress, trackStorageFileModification } = createHiddenFileSync(); + const itemError = new Error("Storage item failed"); + const handlerError = new Error("Progress error handler failed"); + trackStorageFileModification.mockRejectedValueOnce(itemError); + progress.once.mockImplementation(() => { + throw handlerError; + }); + + await expect(hiddenFileSync.trackScannedStorageChanges(createStoragePaths(1))).rejects.toBe(handlerError); + expect(progress.done).not.toHaveBeenCalled(); + }); +}); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.ts index 04588bc1..d3911831 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.ts @@ -35,7 +35,6 @@ import { getLogLevel, autosaveCache, type MapLike, - onlyInNTimes, BASE_IS_NEW, EVEN, displayRev, @@ -45,6 +44,7 @@ import { serialized, skipIfDuplicated } from "octagonal-wheels/concurrency/lock" import { JsonResolveModal } from "@/features/HiddenFileCommon/JsonResolveModal.ts"; import { LiveSyncCommands } from "@/features/LiveSyncCommands.ts"; import { addPrefix, stripAllPrefixes } from "@vrtmrz/livesync-commonlib/compat/string_and_binary/path"; +import { createCoalescingNotifier } from "octagonal-wheels/concurrency/coalescingNotifier"; import { QueueProcessor } from "octagonal-wheels/concurrency/processor"; import { hiddenFilesEventCount, @@ -57,6 +57,7 @@ import { tryGetFilePath } from "@vrtmrz/livesync-commonlib/compat/common/utils.d import type { HandlerOutcome } from "@vrtmrz/livesync-commonlib/compat/services/lib/HandlerUtils"; import type { OptionalFileEventOptions } from "@vrtmrz/livesync-commonlib/compat/services/base/IService"; import { configureHiddenFileSyncMode, type ConfigureHiddenFileSyncResult } from "./configureHiddenFileSyncMode.ts"; +import { performBatchWithProgress } from "./performBatchWithProgress.ts"; import type { OptionalSyncFeatureMode } from "@/features/optionalSyncFeatures.ts"; import { getObsidianCommunityPluginManager } from "@/common/obsidianCommunityPlugins.ts"; import { $msg } from "@/common/translation"; @@ -571,18 +572,15 @@ export class HiddenFileSync extends LiveSyncCommands { ) { const logLevel = getLogLevel(showNotice); const p = this._progress(`[⚙ Storage -> DB ]\n`, logLevel); - const notifyProgress = onlyInNTimes(100, (progress) => p.log(`${progress}/${processFiles.length}`)); - const processes = processFiles.map(async (file, i) => { - try { - await this.trackStorageFileModification(file, onlyNew, forceWriteAll, includeDeleted); - notifyProgress(); - } catch (ex) { + await performBatchWithProgress(processFiles, 100, { + processItem: (file) => this.trackStorageFileModification(file, onlyNew, forceWriteAll, includeDeleted), + onProgress: (progress) => p.log(`${progress}/${processFiles.length}`), + onItemError: (ex, file) => { p.once(`Failed to process storage change file:${file}`); this._log(ex, LOG_LEVEL_VERBOSE); - } + }, + onDone: () => p.done(), }); - await Promise.all(processes); - p.done(); } async scanAllStorageChanges( showNotice: boolean = false, @@ -1134,9 +1132,8 @@ Offline Changed files: ${processFiles.length}`; ) { const logLevel = getLogLevel(showNotice); const p = this._progress(`[⚙ DB -> Storage ]\n`, logLevel); - const notifyProgress = onlyInNTimes(100, (progress) => p.log(`${progress}/${processFiles.length}`)); - const processes = processFiles.map(async (file) => { - try { + await performBatchWithProgress(processFiles, 100, { + processItem: async (file) => { const path = stripAllPrefixes(this.getPath(file)); if (!(await this.isTargetFile(path))) { this._log( @@ -1153,14 +1150,14 @@ Offline Changed files: ${processFiles.length}`; includeDeletion ); } - notifyProgress(); - } catch (ex) { + }, + onProgress: (progress) => p.log(`${progress}/${processFiles.length}`), + onItemError: (ex, file) => { this._log(`Failed to process storage change file:${tryGetFilePath(file)}`, logLevel); this._log(ex, LOG_LEVEL_VERBOSE); - } + }, + onDone: () => p.done(), }); - await Promise.all(processes); - p.done(); } async applyOfflineChanges(showNotice: boolean) { @@ -1188,9 +1185,14 @@ Untracked database files: ${untrackedDatabase.length} Common untracked files: ${bothUntracked.length}`; p.once(stat); const semaphores = Semaphore(10); - const notifyProgress = onlyInNTimes(25, (progress) => p.log(`${progress}/${bothUntracked.length}`)); + const notifyProgress = createCoalescingNotifier({ + everyCount: 25, + leading: true, + onNotify: (progress) => p.log(`${progress}/${bothUntracked.length}`), + }); + let attempted = 0; const allProcesses = bothUntracked.map(async (file) => { - notifyProgress(); + notifyProgress.update(++attempted); const rel = await semaphores.acquire(); try { const fileStat = await this.core.storageAccess.statHidden(file); @@ -1260,20 +1262,18 @@ Offline Changed files: ${files.length}`; const logLevel = getLogLevel(showNotice); const p = this._progress(`[⚙ Scanning DB -> Storage ]\n`, logLevel); p.log("Scanning database files..."); - const notifyProgress = onlyInNTimes(25, (progress) => p.log(`${progress}/${files.length}`)); - const processFiles = files.map(async (file) => { - try { + await performBatchWithProgress(files, 25, { + processItem: async (file) => { const path = stripAllPrefixes(this.getPath(file)); await this.trackDatabaseFileModification(path, "[Scanning]", true, onlyNew, file); - notifyProgress(); - } catch (ex) { + }, + onProgress: (progress) => p.log(`${progress}/${files.length}`), + onItemError: (ex, file) => { this._log(`Failed to process database changes:${tryGetFilePath(file)}`); this._log(ex, LOG_LEVEL_VERBOSE); - } - return; + }, + onDone: () => p.done(), }); - await Promise.all(processFiles); - p.done(); return true; } @@ -1435,9 +1435,14 @@ Offline Changed files: ${files.length}`; const storageToDatabase = [] as FilePath[]; const databaseToStorage = [] as MetaEntry[]; - const eachProgress = onlyInNTimes(100, (progress) => p.log(`Checking ${progress}/${allFileNames.size}`)); + const eachProgress = createCoalescingNotifier({ + everyCount: 100, + leading: true, + onNotify: (progress) => p.log(`Checking ${progress}/${allFileNames.size}`), + }); + let attempted = 0; for (const file of allFileNames) { - eachProgress(); + eachProgress.update(++attempted); const storageMTime = await this.core.storageAccess.statHidden(file); const mtimeStorage = getComparingMTime(storageMTime); const dbEntry = allDatabaseMap.get(file)!; diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.unit.spec.ts index 9018b222..4b3e5543 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.unit.spec.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.unit.spec.ts @@ -98,6 +98,85 @@ function createHiddenRevisionOperation() { }; } +describe("HiddenFileSync storage loading", () => { + function createStorageReader(content: string | ArrayBuffer) { + const path = ".obsidian/plugins/example/data.json" as FilePath; + const stat = { + ctime: 123, + mtime: 456, + size: typeof content === "string" ? new TextEncoder().encode(content).byteLength : content.byteLength, + type: "file" as const, + }; + const storageAccess = { + statHidden: vi.fn(async (): Promise => stat), + readHiddenFileAuto: vi.fn(async () => content), + }; + const hiddenFileSync = Object.create(HiddenFileSync.prototype) as HiddenFileSync; + Object.assign(hiddenFileSync, { core: { storageAccess } }); + return { hiddenFileSync, storageAccess, path, stat }; + } + + it.each([ + { + kind: "text", + content: "first\r\n日本語 🐙", + expected: new TextEncoder().encode("first\r\n日本語 🐙"), + mime: "text/plain", + }, + { + kind: "binary", + content: new Uint8Array([0, 128, 255]).buffer, + expected: new Uint8Array([0, 128, 255]), + mime: "application/octet-stream", + }, + { kind: "empty text", content: "", expected: new Uint8Array(0), mime: "text/plain" }, + { + kind: "empty binary", + content: new ArrayBuffer(0), + expected: new Uint8Array(0), + mime: "application/octet-stream", + }, + ])("preserves $kind content and its file metadata", async ({ content, expected, mime }) => { + const { hiddenFileSync, storageAccess, path, stat } = createStorageReader(content); + + const file = await hiddenFileSync.loadFileWithInfo(path); + + expect(storageAccess.statHidden).toHaveBeenCalledWith(path); + expect(storageAccess.readHiddenFileAuto).toHaveBeenCalledWith(path); + expect(file).toMatchObject({ name: "data.json", path, stat, isInternal: true, deleted: false }); + expect(file.body).toBeInstanceOf(Blob); + expect(file.body.type).toBe(mime); + expect(new Uint8Array(await file.body.arrayBuffer())).toEqual(expected); + }); + + it("represents a missing file as a deletion without reading storage content", async () => { + const { hiddenFileSync, storageAccess, path } = createStorageReader("unavailable"); + storageAccess.statHidden.mockResolvedValue(null); + + const file = await hiddenFileSync.loadFileWithInfo(path); + + expect(storageAccess.readHiddenFileAuto).not.toHaveBeenCalled(); + expect(file).toMatchObject({ + name: "data.json", + path, + stat: { ctime: 0, mtime: 0, size: 0, type: "file" }, + isInternal: true, + deleted: true, + }); + expect(file.body.type).toBe("application/octet-stream"); + expect(file.body.size).toBe(0); + }); + + it("propagates a read failure for an existing file", async () => { + const { hiddenFileSync, storageAccess, path } = createStorageReader("unavailable"); + const error = new Error("Storage read failed"); + storageAccess.readHiddenFileAuto.mockRejectedValue(error); + + await expect(hiddenFileSync.loadFileWithInfo(path)).rejects.toBe(error); + expect(storageAccess.readHiddenFileAuto).toHaveBeenCalledWith(path); + }); +}); + describe("HiddenFileSync configuration-change notices", () => { it.each(["pushForce", "pullForce", "safe"] as const)( "refuses %s initialisation before processing files while Hidden File Sync is disabled", diff --git a/src/features/HiddenFileSync/performBatchWithProgress.ts b/src/features/HiddenFileSync/performBatchWithProgress.ts new file mode 100644 index 00000000..7c0fd2dd --- /dev/null +++ b/src/features/HiddenFileSync/performBatchWithProgress.ts @@ -0,0 +1,49 @@ +import { createCoalescingNotifier } from "octagonal-wheels/concurrency/coalescingNotifier"; + +interface PerformBatchWithProgressCallbacks { + /** Runs one item. Its resolved value is ignored. */ + processItem: (item: T) => Promise; + /** Receives the number of successfully completed items. */ + onProgress: (completed: number) => void; + /** Handles an item or progress callback error. */ + onItemError: (error: unknown, item: T) => void; + /** Runs once after all per-item promises resolve. */ + onDone: () => void; +} + +/** + * Runs an eager batch and coalesces progress notifications by successful item count. + * @internal + * + * @param items - Items to process concurrently. + * @param eachCount - Number of completed items between progress notifications. + * @param callbacks - Item processing, progress, error, and completion callbacks. + * @returns A promise that resolves with no value after the batch and completion callback finish. + * @throws When notifier configuration is invalid, an error handler throws, or the completion callback throws. + * @remarks The first completed item triggers progress immediately. Work and the progress callback share + * one error boundary; errors are passed to `onItemError`. A rejected item operation does not advance + * the count. The batch has no concurrency limit or retry, and pending progress is not flushed when + * processing ends. + */ +export async function performBatchWithProgress( + items: readonly T[], + eachCount: number, + callbacks: PerformBatchWithProgressCallbacks +): Promise { + const notifier = createCoalescingNotifier({ + everyCount: eachCount, + leading: true, + onNotify: callbacks.onProgress, + }); + let completed = 0; + const processes = items.map(async (item) => { + try { + await callbacks.processItem(item); + notifier.update(++completed); + } catch (error) { + callbacks.onItemError(error, item); + } + }); + await Promise.all(processes); + callbacks.onDone(); +} diff --git a/src/features/HiddenFileSync/performBatchWithProgress.unit.spec.ts b/src/features/HiddenFileSync/performBatchWithProgress.unit.spec.ts new file mode 100644 index 00000000..ba0d7167 --- /dev/null +++ b/src/features/HiddenFileSync/performBatchWithProgress.unit.spec.ts @@ -0,0 +1,93 @@ +import { describe, expect, it, vi } from "vitest"; +import { performBatchWithProgress } from "./performBatchWithProgress.ts"; + +describe("performBatchWithProgress", () => { + it("counts resolved false values, continues after item errors, and does not flush partial progress", async () => { + const error = new Error("Item failed"); + const processItem = vi.fn(async (item: number) => { + if (item === 2) throw error; + return false; + }); + const onProgress = vi.fn(); + const onItemError = vi.fn(); + const onDone = vi.fn(); + + const result = await performBatchWithProgress([1, 2, 3, 4, 5, 6, 7], 2, { + processItem, + onProgress, + onItemError, + onDone, + }); + + expect(result).toBeUndefined(); + expect(processItem).toHaveBeenCalledTimes(7); + expect(onItemError).toHaveBeenCalledWith(error, 2); + expect(onProgress.mock.calls).toEqual([[1], [3], [5]]); + expect(onDone).toHaveBeenCalledTimes(1); + }); + + it("starts every item eagerly and calls onDone only after all item promises resolve", async () => { + const items = [1, 2, 3]; + const resolvers: Array<() => void> = []; + const processItem = vi.fn( + () => + new Promise((resolve) => { + resolvers.push(resolve); + }) + ); + const onProgress = vi.fn(); + const onItemError = vi.fn(); + const onDone = vi.fn(); + + const operation = performBatchWithProgress(items, 100, { processItem, onProgress, onItemError, onDone }); + + expect(processItem).toHaveBeenCalledTimes(items.length); + expect(onDone).not.toHaveBeenCalled(); + for (const resolve of resolvers) resolve(); + await operation; + + expect(onDone).toHaveBeenCalledTimes(1); + }); + + it("routes a progress callback error through the item error handler", async () => { + const error = new Error("Progress callback failed"); + const onProgress = vi.fn(() => { + throw error; + }); + const onItemError = vi.fn(); + const onDone = vi.fn(); + + await performBatchWithProgress(["item"], 100, { + processItem: async () => false, + onProgress, + onItemError, + onDone, + }); + + expect(onItemError).toHaveBeenCalledWith(error, "item"); + expect(onDone).toHaveBeenCalledTimes(1); + }); + + it("rejects when the item error handler throws and skips onDone", async () => { + const itemError = new Error("Item failed"); + const handlerError = new Error("Error handler failed"); + const onItemError = vi.fn(() => { + throw handlerError; + }); + const onDone = vi.fn(); + + await expect( + performBatchWithProgress(["item"], 100, { + processItem: async () => { + throw itemError; + }, + onProgress: vi.fn(), + onItemError, + onDone, + }) + ).rejects.toBe(handlerError); + + expect(onItemError).toHaveBeenCalledWith(itemError, "item"); + expect(onDone).not.toHaveBeenCalled(); + }); +}); diff --git a/src/modules/features/StatusBarDisplay.timeout.unit.spec.ts b/src/modules/features/StatusBarDisplay.timeout.unit.spec.ts new file mode 100644 index 00000000..15bda8f1 --- /dev/null +++ b/src/modules/features/StatusBarDisplay.timeout.unit.spec.ts @@ -0,0 +1,142 @@ +import { reactiveSource } from "octagonal-wheels/dataobject/reactive"; +import { createDeferredAction, type TimeoutScheduler } from "octagonal-wheels/concurrency/deferredAction"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + STATUS_COUNTER_INACTIVE_LINGER_MS, + createChunkFetchCounterLabel, + createMinimumVisibleActivityCount, + createPaddedCounterLabel, +} from "./StatusBarDisplay.ts"; + +vi.mock("octagonal-wheels/concurrency/deferredAction", { spy: true }); + +function createdControllers() { + return vi.mocked(createDeferredAction).mock.results.map((result) => { + if (result.type !== "return") throw new Error("Expected a real timeout controller"); + return result.value; + }); +} + +function createScheduler() { + const entries: { callback: () => void; delayMs: number; cancel: ReturnType }[] = []; + const schedule = vi.fn((callback, delayMs) => { + const cancel = vi.fn(); + entries.push({ callback, delayMs, cancel }); + return cancel; + }); + return { schedule, entries }; +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-10-24T00:00:00Z")); +}); + +afterEach(() => { + vi.clearAllTimers(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe("status timeout composition", () => { + it("uses the real shared controller for minimum visibility, resumption, and disposal", () => { + const scheduler = createScheduler(); + const source = reactiveSource(0); + const display = createMinimumVisibleActivityCount(source, 150, scheduler.schedule); + expect(createDeferredAction).toHaveBeenCalledExactlyOnceWith(expect.any(Function), scheduler.schedule); + const controller = createdControllers()[0]; + const schedule = vi.spyOn(controller, "schedule"); + const cancel = vi.spyOn(controller, "cancel"); + const dispose = vi.spyOn(controller, "dispose"); + + source.value = 1; + vi.advanceTimersByTime(50); + source.value = 0; + expect(schedule).toHaveBeenCalledExactlyOnceWith(100); + expect(scheduler.entries[0].delayMs).toBe(100); + source.value = 2; + expect(cancel).toHaveBeenCalledTimes(3); + expect(scheduler.entries[0].cancel).toHaveBeenCalledTimes(1); + scheduler.entries[0].callback(); + expect(display.value).toBe(2); + + source.value = 0; + scheduler.entries[1].callback(); + expect(display.value).toBe(0); + source.value = 3; + source.value = 0; + display.dispose(); + display.dispose(); + scheduler.entries[2].callback(); + expect(display.value).toBe(3); + expect(scheduler.entries[2].cancel).toHaveBeenCalledTimes(1); + expect(dispose).toHaveBeenCalledTimes(1); + }); + + it("uses the shared controller for the counter linger and cancels through it when activity resumes", () => { + const scheduler = createScheduler(); + const source = reactiveSource(0); + const display = createPaddedCounterLabel(source, "A", 25, scheduler.schedule); + expect(createDeferredAction).toHaveBeenCalledExactlyOnceWith(expect.any(Function), scheduler.schedule); + const controller = createdControllers()[0]; + const schedule = vi.spyOn(controller, "schedule"); + const cancel = vi.spyOn(controller, "cancel"); + const dispose = vi.spyOn(controller, "dispose"); + source.value = 1; + source.value = 0; + expect(schedule).toHaveBeenCalledExactlyOnceWith(25); + source.value = 2; + expect(cancel).toHaveBeenCalledTimes(3); + expect(scheduler.entries[0].cancel).toHaveBeenCalledTimes(1); + scheduler.entries[0].callback(); + expect(display.value).toBe(" A\u20072"); + expect(display.count.value).toBe(2); + + source.value = 0; + scheduler.entries[1].callback(); + expect(display.value).toBe(""); + expect(display.count.value).toBeUndefined(); + source.value = 3; + source.value = 0; + display.dispose(); + scheduler.entries[2].callback(); + expect(display.value).toBe(" A\u20070"); + expect(display.count.value).toBe(0); + expect(scheduler.entries[2].cancel).toHaveBeenCalledTimes(1); + expect(dispose).toHaveBeenCalledTimes(1); + }); + + it("passes the scheduler to independent chunk-count controllers and disposes both children", () => { + const scheduler = createScheduler(); + const source = reactiveSource({ initial: 2, retrying: 3 }); + const display = createChunkFetchCounterLabel(source, scheduler.schedule); + expect(display.initialCount.value).toBe(2); + expect(display.retryingCount.value).toBe(3); + expect(createDeferredAction).toHaveBeenCalledTimes(2); + expect(vi.mocked(createDeferredAction).mock.calls.map((args) => args[1])).toEqual([ + scheduler.schedule, + scheduler.schedule, + ]); + const controllers = createdControllers(); + const disposers = controllers.map((controller) => vi.spyOn(controller, "dispose")); + source.value = { initial: 0, retrying: 0 }; + expect(scheduler.entries.map((entry) => entry.delayMs)).toEqual([ + STATUS_COUNTER_INACTIVE_LINGER_MS, + STATUS_COUNTER_INACTIVE_LINGER_MS, + ]); + scheduler.entries[0].callback(); + expect(display.value.replace(/\u2007/g, "")).toBe(" 🔁0"); + expect(display.initialCount.value).toBeUndefined(); + expect(display.retryingCount.value).toBe(0); + display.dispose(); + display.dispose(); + expect(scheduler.entries[0].cancel).not.toHaveBeenCalled(); + expect(scheduler.entries[1].cancel).toHaveBeenCalledTimes(1); + for (const dispose of disposers) expect(dispose).toHaveBeenCalledTimes(1); + scheduler.entries[1].callback(); + expect(display.value.replace(/\u2007/g, "")).toBe(" 🔁0"); + expect(display.initialCount.value).toBeUndefined(); + expect(display.retryingCount.value).toBe(0); + }); +}); diff --git a/src/modules/features/StatusBarDisplay.ts b/src/modules/features/StatusBarDisplay.ts index 9c24a972..cc63aca9 100644 --- a/src/modules/features/StatusBarDisplay.ts +++ b/src/modules/features/StatusBarDisplay.ts @@ -1,7 +1,13 @@ import { reactiveSource, type ReactiveSource, type ReactiveValue } from "octagonal-wheels/dataobject/reactive"; +import { createDeferredAction, type TimeoutScheduler } from "octagonal-wheels/concurrency/deferredAction"; import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; +const scheduleStatusTimeout: TimeoutScheduler = (callback, delayMs) => { + const handle = compatGlobal.setTimeout(callback, delayMs); + return () => compatGlobal.clearTimeout(handle); +}; + const STATUS_COUNTER_PADDING = "\u2007".repeat(10); export const STATUS_COUNTER_INACTIVE_LINGER_MS = 3_000; @@ -37,32 +43,32 @@ function asDisposableReactiveValue(value: ReactiveSource, dispose: () => v /** * Mirrors an activity count while keeping each visible period on screen for a * minimum total lifetime. The delay applies only when the source becomes zero. + * + * @param source - The activity count to observe. + * @param minimumVisibleMs - The minimum visible lifetime, clamped to zero. + * @param scheduleTimeout - The scheduler for this display. Defaults to the + * existing compatible host, preserving its timer method receivers. */ export function createMinimumVisibleActivityCount( source: ReactiveValue, - minimumVisibleMs: number + minimumVisibleMs: number, + scheduleTimeout: TimeoutScheduler = scheduleStatusTimeout ): DisposableReactiveValue { const minimumLifetime = Math.max(0, minimumVisibleMs); const displayed = reactiveSource(Math.max(0, source.value)); let visibleSince = displayed.value > 0 ? Date.now() : undefined; - let hideTimer: number | undefined; let disposed = false; - const cancelHide = () => { - if (hideTimer === undefined) return; - compatGlobal.clearTimeout(hideTimer); - hideTimer = undefined; - }; const hideIfIdle = () => { - hideTimer = undefined; if (disposed || Math.max(0, source.value) > 0) return; displayed.value = 0; visibleSince = undefined; }; + const hideTimeout = createDeferredAction(hideIfIdle, scheduleTimeout); const update = () => { if (disposed) return; const nextCount = Math.max(0, source.value); - cancelHide(); + hideTimeout.cancel(); if (nextCount > 0) { if (displayed.value === 0) { visibleSince = Date.now(); @@ -80,7 +86,7 @@ export function createMinimumVisibleActivityCount( if (remaining === 0) { hideIfIdle(); } else { - hideTimer = compatGlobal.setTimeout(hideIfIdle, remaining); + hideTimeout.schedule(remaining); } }; @@ -88,7 +94,7 @@ export function createMinimumVisibleActivityCount( return asDisposableReactiveValue(displayed, () => { if (disposed) return; disposed = true; - cancelHide(); + hideTimeout.dispose(); source.offChanged(update); }); } @@ -96,24 +102,31 @@ export function createMinimumVisibleActivityCount( /** * Formats a counter with a stable width and briefly retains its zero value so * that the completion of queued work remains visible. + * + * @param source - The counter to observe. + * @param mark - The label prefix before the padded count. + * @param inactiveLingerMs - The delay before clearing a zero count, clamped to zero. + * @param scheduleTimeout - The scheduler for this display. Defaults to the + * existing compatible host, preserving its timer method receivers. */ export function createPaddedCounterLabel( source: ReactiveValue, mark: string, - inactiveLingerMs = STATUS_COUNTER_INACTIVE_LINGER_MS + inactiveLingerMs = STATUS_COUNTER_INACTIVE_LINGER_MS, + scheduleTimeout: TimeoutScheduler = scheduleStatusTimeout ): PaddedCounterLabel { const linger = Math.max(0, inactiveLingerMs); const formatted = reactiveSource(""); const displayedCount = reactiveSource(undefined); let maximumLength = 1; - let clearTimer: number | undefined; let disposed = false; - const cancelClear = () => { - if (clearTimer === undefined) return; - compatGlobal.clearTimeout(clearTimer); - clearTimer = undefined; - }; + const clearLabelTimeout = createDeferredAction(() => { + if (disposed) return; + formatted.value = ""; + displayedCount.value = undefined; + maximumLength = 1; + }, scheduleTimeout); const format = (count: number) => { const requiredLength = `${Math.abs(count)}`.length + 1; maximumLength = Math.max(maximumLength, requiredLength); @@ -121,25 +134,19 @@ export function createPaddedCounterLabel( }; const update = () => { if (disposed) return; - cancelClear(); + clearLabelTimeout.cancel(); const count = source.value; formatted.value = format(count); displayedCount.value = count; if (count !== 0) return; - clearTimer = compatGlobal.setTimeout(() => { - clearTimer = undefined; - if (disposed) return; - formatted.value = ""; - displayedCount.value = undefined; - maximumLength = 1; - }, linger); + clearLabelTimeout.schedule(linger); }; source.onChanged(update); const display = asDisposableReactiveValue(formatted, () => { if (disposed) return; disposed = true; - cancelClear(); + clearLabelTimeout.dispose(); source.offChanged(update); }); return { @@ -162,14 +169,28 @@ export function createPaddedCounterLabel( /** * Displays the disjoint initial and retry chunk-fetch counts with the same * padding and inactive linger behaviour as the other status counters. + * + * @param source - The initial and retrying chunk-fetch counts. + * @param scheduleTimeout - The scheduler passed to each independent child display. */ export function createChunkFetchCounterLabel( - source: ReactiveValue<{ initial: number; retrying: number }> + source: ReactiveValue<{ initial: number; retrying: number }>, + scheduleTimeout: TimeoutScheduler = scheduleStatusTimeout ): ChunkFetchCounterLabel { const initialCount = reactiveSource(0); const retryingCount = reactiveSource(0); - const initialLabel = createPaddedCounterLabel(initialCount, "🛄"); - const retryingLabel = createPaddedCounterLabel(retryingCount, "🔁"); + const initialLabel = createPaddedCounterLabel( + initialCount, + "🛄", + STATUS_COUNTER_INACTIVE_LINGER_MS, + scheduleTimeout + ); + const retryingLabel = createPaddedCounterLabel( + retryingCount, + "🔁", + STATUS_COUNTER_INACTIVE_LINGER_MS, + scheduleTimeout + ); const formatted = reactiveSource(`${initialLabel.value}${retryingLabel.value}`); let updatingCounts = false; let disposed = false; diff --git a/src/modules/features/StatusBarDisplay.unit.spec.ts b/src/modules/features/StatusBarDisplay.unit.spec.ts index 5ce8f69e..c704cce4 100644 --- a/src/modules/features/StatusBarDisplay.unit.spec.ts +++ b/src/modules/features/StatusBarDisplay.unit.spec.ts @@ -1,3 +1,4 @@ +import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { reactive, reactiveSource } from "octagonal-wheels/dataobject/reactive"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -194,3 +195,121 @@ describe("createChunkFetchCounterLabel", () => { expect(withoutPadding()).toBe(" 🔁0"); }); }); + +describe("status timeout ownership", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-10-24T00:00:00Z")); + }); + + afterEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + }); + + it("counts the minimum lifetime from construction when activity is already visible", () => { + const source = reactiveSource(2); + const display = createMinimumVisibleActivityCount(source, 150); + vi.advanceTimersByTime(40); + source.value = 0; + + vi.advanceTimersByTime(109); + expect(display.value).toBe(2); + vi.advanceTimersByTime(1); + expect(display.value).toBe(0); + display.dispose(); + }); + + it("hides immediately for a non-positive minimum lifetime and clamps negative activity", () => { + const source = reactiveSource(-2); + const display = createMinimumVisibleActivityCount(source, -10); + expect(display.value).toBe(0); + source.value = 1; + source.value = -2; + + expect(display.value).toBe(0); + expect(vi.getTimerCount()).toBe(0); + display.dispose(); + }); + + it("keeps a zero-duration counter clear asynchronous", () => { + const source = reactiveSource(0); + const display = createPaddedCounterLabel(source, "A", 0); + source.value = 1; + source.value = 0; + + expect(display.value).toBe(" A\u20070"); + vi.advanceTimersByTime(0); + expect(display.value).toBe(""); + display.dispose(); + }); + + it.each(["activity", "label"] as const)( + "retains timer receivers, zero handles, and idempotent disposal for %s", + (kind) => { + const source = reactiveSource(0); + const offChanged = vi.spyOn(source, "offChanged"); + const setTimer = vi.spyOn(compatGlobal as Window, "setTimeout").mockReturnValue(0); + const clearTimer = vi.spyOn(compatGlobal as Window, "clearTimeout").mockImplementation(() => {}); + const display = + kind === "activity" + ? createMinimumVisibleActivityCount(source, 150) + : createPaddedCounterLabel(source, "A", 150); + + source.value = 1; + source.value = 0; + expect(setTimer).toHaveBeenCalledTimes(1); + expect(setTimer.mock.contexts[0]).toBe(compatGlobal); + expect(setTimer.mock.calls[0][1]).toBe(150); + source.value = 2; + expect(clearTimer).toHaveBeenCalledExactlyOnceWith(0); + source.value = 0; + display.dispose(); + display.dispose(); + source.value = 3; + + expect(setTimer).toHaveBeenCalledTimes(2); + expect(clearTimer).toHaveBeenCalledTimes(2); + expect(clearTimer.mock.calls).toEqual([[0], [0]]); + expect(clearTimer.mock.contexts).toEqual([compatGlobal, compatGlobal]); + expect(offChanged).toHaveBeenCalledTimes(1); + } + ); + + it("keeps pending clears independent between display instances", () => { + const firstSource = reactiveSource(0); + const secondSource = reactiveSource(0); + const first = createPaddedCounterLabel(firstSource, "A", 100); + const second = createPaddedCounterLabel(secondSource, "B", 100); + firstSource.value = 1; + firstSource.value = 0; + secondSource.value = 1; + secondSource.value = 0; + expect(vi.getTimerCount()).toBe(2); + + first.dispose(); + expect(vi.getTimerCount()).toBe(1); + vi.advanceTimersByTime(100); + expect(first.value).toBe(" A\u20070"); + expect(second.value).toBe(""); + second.dispose(); + expect(vi.getTimerCount()).toBe(0); + }); + + it("disposes both child timers and its source subscription for chunk counts", () => { + const source = reactiveSource({ initial: 2, retrying: 3 }); + const offChanged = vi.spyOn(source, "offChanged"); + const display = createChunkFetchCounterLabel(source); + source.value = { initial: 0, retrying: 0 }; + const lastLabel = display.value; + expect(vi.getTimerCount()).toBe(2); + + display.dispose(); + display.dispose(); + expect(vi.getTimerCount()).toBe(0); + vi.advanceTimersByTime(STATUS_COUNTER_INACTIVE_LINGER_MS); + source.value = { initial: 4, retrying: 5 }; + expect(display.value).toBe(lastLabel); + expect(offChanged).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/serviceFeatures/replication/ReplicateResultProcessor.counting.unit.spec.ts b/src/serviceFeatures/replication/ReplicateResultProcessor.counting.unit.spec.ts new file mode 100644 index 00000000..2a76766c --- /dev/null +++ b/src/serviceFeatures/replication/ReplicateResultProcessor.counting.unit.spec.ts @@ -0,0 +1,46 @@ +import { reactiveSource } from "octagonal-wheels/dataobject/reactive"; +import { promiseWithResolvers } from "octagonal-wheels/promises"; +import { describe, expect, it } from "vitest"; +import { ReplicateResultProcessor } from "./ReplicateResultProcessor"; + +describe("ReplicateResultProcessor.withCounting", () => { + it("counts overlapping callbacks until each settles and preserves results and errors", async () => { + const originalCount = 7; + const count = reactiveSource(originalCount); + const processor = new ReplicateResultProcessor({} as never); + const firstResult = { task: "first" }; + const firstResultGate = promiseWithResolvers(); + const secondResultGate = promiseWithResolvers(); + const firstStarted = promiseWithResolvers(); + const secondStarted = promiseWithResolvers(); + const failure = new Error("second callback failed"); + let firstCountAtStart = 0; + let secondCountAtStart = 0; + + const first = processor.withCounting(async () => { + firstCountAtStart = count.value; + firstStarted.resolve(undefined); + return firstResultGate.promise; + }, count); + await firstStarted.promise; + expect(firstCountAtStart).toBe(originalCount + 1); + expect(count.value).toBe(originalCount + 1); + + const second = processor.withCounting(async () => { + secondCountAtStart = count.value; + secondStarted.resolve(undefined); + return secondResultGate.promise; + }, count); + await secondStarted.promise; + expect(secondCountAtStart).toBe(originalCount + 2); + expect(count.value).toBe(originalCount + 2); + + firstResultGate.resolve(firstResult); + await expect(first).resolves.toBe(firstResult); + expect(count.value).toBe(originalCount + 1); + + secondResultGate.reject(failure); + await expect(second).rejects.toBe(failure); + expect(count.value).toBe(originalCount); + }); +}); diff --git a/src/serviceFeatures/replication/ReplicateResultProcessor.ts b/src/serviceFeatures/replication/ReplicateResultProcessor.ts index 523043d9..43310f34 100644 --- a/src/serviceFeatures/replication/ReplicateResultProcessor.ts +++ b/src/serviceFeatures/replication/ReplicateResultProcessor.ts @@ -25,6 +25,7 @@ import { } from "@vrtmrz/livesync-commonlib/compat/common/logger"; import { fireAndForget, isAnyNote, throttle } from "@vrtmrz/livesync-commonlib/compat/common/utils"; import { Semaphore } from "octagonal-wheels/concurrency/semaphore_v2"; +import { withCounting } from "octagonal-wheels/concurrency/counting"; import { serialized } from "octagonal-wheels/concurrency/lock"; import type { ReactiveSource } from "octagonal-wheels/dataobject/reactive_v2"; import type { LiveSyncBaseCore } from "@/LiveSyncBaseCore"; @@ -221,12 +222,7 @@ export class ReplicateResultProcessor { * @returns result of the procedure */ async withCounting(proc: () => Promise, countValue: ReactiveSource) { - countValue.value++; - try { - return await proc(); - } finally { - countValue.value--; - } + return withCounting(countValue, proc); } /** From 273079e8278546b4e0a8b56a3a97b454b244200f Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Thu, 29 Oct 2026 14:58:38 +0000 Subject: [PATCH 03/24] Own browser UI sessions and shared navigation --- devs.md | 12 + package.json | 4 +- src/apps/browser/BrowserConfirm.ts | 21 +- src/apps/browser/BrowserMenu.ts | 113 ++++-- .../browser/BrowserSvelteDialogManager.ts | 41 ++- src/apps/browser/BrowserUiScope.ts | 38 +++ src/apps/browser/LiveSyncBrowserUIService.ts | 21 +- .../createLiveSyncBrowserServiceHub.ts | 26 +- src/common/diffNavigation.ts | 25 ++ ...cumentHistoryModal.navigation.unit.spec.ts | 321 ++++++++++++++++++ .../DocumentHistory/DocumentHistoryModal.ts | 30 +- .../ConflictResolveModal.ts | 20 +- .../ConflictResolveModal.unit.spec.ts | 189 ++++++++++- src/modules/services/SvelteDialogSession.ts | 28 +- test/apps/browser/BrowserConfirm.unit.spec.ts | 73 ++++ test/apps/browser/BrowserMenu.unit.spec.ts | 286 ++++++++++++++++ .../BrowserSvelteDialogManager.unit.spec.ts | 199 +++++++++++ test/apps/browser/BrowserUiScope.unit.spec.ts | 56 +++ .../browser/SvelteDialogSession.unit.spec.ts | 61 ++++ .../ui-lifecycle/browser-ui-lifecycle.test.ts | 202 +++++++++++ test/browser-apps/ui-lifecycle/index.html | 15 + .../src/TestLifecycleDialog.svelte | 16 + test/browser-apps/ui-lifecycle/src/main.ts | 154 +++++++++ test/browser-apps/ui-lifecycle/tsconfig.json | 9 + test/browser-apps/ui-lifecycle/vite.config.ts | 25 ++ .../scripts/conflict-dialog-policy.ts | 36 +- .../scripts/document-history-nav.ts | 44 +++ updates.md | 4 + 28 files changed, 1948 insertions(+), 121 deletions(-) create mode 100644 src/apps/browser/BrowserUiScope.ts create mode 100644 src/common/diffNavigation.ts create mode 100644 src/modules/features/DocumentHistory/DocumentHistoryModal.navigation.unit.spec.ts create mode 100644 test/apps/browser/BrowserConfirm.unit.spec.ts create mode 100644 test/apps/browser/BrowserMenu.unit.spec.ts create mode 100644 test/apps/browser/BrowserSvelteDialogManager.unit.spec.ts create mode 100644 test/apps/browser/BrowserUiScope.unit.spec.ts create mode 100644 test/browser-apps/ui-lifecycle/browser-ui-lifecycle.test.ts create mode 100644 test/browser-apps/ui-lifecycle/index.html create mode 100644 test/browser-apps/ui-lifecycle/src/TestLifecycleDialog.svelte create mode 100644 test/browser-apps/ui-lifecycle/src/main.ts create mode 100644 test/browser-apps/ui-lifecycle/tsconfig.json create mode 100644 test/browser-apps/ui-lifecycle/vite.config.ts diff --git a/devs.md b/devs.md index 788d351b..d618e88c 100644 --- a/devs.md +++ b/devs.md @@ -174,6 +174,18 @@ Declare shared UI requests with `declareUICommand` from `@vrtmr The registry belongs to one UIService instance. Reuse the same declaration object at each call site, and keep active UI cleanup in the feature and dialogue owner. `UIService` disposes the registry when the host's context emits the plug-in-unloaded event. +Each browser service hub creates a local `BrowserUiScope` with a `document` and +`signal`, exposed as readonly `hub.browserUi`. Pass overrides through +the service-hub option `ui: { document, signal }`; when `document` is omitted, +the scope snapshots legacy `_activeDocument`. The scope is bound to +its root `ServiceContext` unload event and optional parent `AbortSignal`, and is +shared by browser confirmation and the Svelte dialogue manager. A dialogue +resolves with its result or `undefined` on ordinary close; cancellation rejects +with the abort reason, including `Error('Plug-in unloaded')` on root-context +unload. A `Menu` can receive `hub.browserUi`; closing, replacing, or aborting it +unmounts its Svelte component, and callbacks from a closed session cannot close +the replacement. + ### Key Architectural Components - **LiveSyncLocalDB** (`@vrtmrz/livesync-commonlib/compat/pouchdb/LiveSyncLocalDB`): Local PouchDB database wrapper diff --git a/package.json b/package.json index a9efc5aa..53bab329 100644 --- a/package.json +++ b/package.json @@ -132,7 +132,9 @@ "version": "node version-bump.mjs && node update-workspaces.mjs && npm run pretty:json && git add manifest.json versions.json src/apps/cli/package.json src/apps/webpeer/package.json src/apps/webapp/package.json", "test:e2e:obsidian:startup-integrity": "tsx test/e2e-obsidian/scripts/startup-integrity.ts", "test:e2e:obsidian:third-party-chunks": "tsx test/e2e-obsidian/scripts/third-party-chunks.ts", - "test:e2e:obsidian:upgrade-livesync-batching": "tsx test/e2e-obsidian/scripts/upgrade-livesync-batching.ts" + "test:e2e:obsidian:upgrade-livesync-batching": "tsx test/e2e-obsidian/scripts/upgrade-livesync-batching.ts", + "pretest:browser-ui-lifecycle": "svelte-check --tsconfig test/browser-apps/ui-lifecycle/tsconfig.json --fail-on-warnings && vite build --config test/browser-apps/ui-lifecycle/vite.config.ts", + "test:browser-ui-lifecycle": "deno test -A --no-check --frozen --config test/browser-apps/deno.json --lock test/browser-apps/deno.lock test/browser-apps/ui-lifecycle/browser-ui-lifecycle.test.ts" }, "keywords": [], "author": "vorotamoroz", diff --git a/src/apps/browser/BrowserConfirm.ts b/src/apps/browser/BrowserConfirm.ts index a7cbc5a7..8f875777 100644 --- a/src/apps/browser/BrowserConfirm.ts +++ b/src/apps/browser/BrowserConfirm.ts @@ -1,11 +1,10 @@ import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context"; -import { _activeDocument } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; -import { EVENT_PLUGIN_UNLOADED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; import { BrowserUiNotifications, createBrowserUi } from "@vrtmrz/browser-ui-kit"; import { createNativeElement } from "@/apps/browserDom"; import { renderMessageMarkdownInto } from "./ui/renderMessageMarkdown"; import { UiInteractionsConfirm } from "./UiInteractionsConfirm"; +import { createBrowserUiScope, type BrowserUiScope } from "./BrowserUiScope"; /** * Compatibility facade consumed by Commonlib while browser presentation is @@ -14,26 +13,26 @@ import { UiInteractionsConfirm } from "./UiInteractionsConfirm"; export class BrowserConfirm extends UiInteractionsConfirm { readonly context: T; - constructor(context: T) { - const dialogueController = new AbortController(); + constructor(context: T, ui: BrowserUiScope = createBrowserUiScope(context)) { const notifications = new BrowserUiNotifications({ - document: _activeDocument, + document: ui.document, }); super({ ui: createBrowserUi({ - document: _activeDocument, - signal: dialogueController.signal, + document: ui.document, + signal: ui.signal, renderMarkdown: ({ container, markdown }) => { renderMessageMarkdownInto(container, markdown); }, }), notifications, - createActionAnchor: () => createNativeElement(_activeDocument, "a"), + createActionAnchor: () => createNativeElement(ui.document, "a"), }); this.context = context; - context.events.onceEvent(EVENT_PLUGIN_UNLOADED, () => { - dialogueController.abort(); + if (ui.signal.aborted) { notifications.dispose(); - }); + } else { + ui.signal.addEventListener("abort", () => notifications.dispose(), { once: true }); + } } } diff --git a/src/apps/browser/BrowserMenu.ts b/src/apps/browser/BrowserMenu.ts index 55af8921..7b9bd8db 100644 --- a/src/apps/browser/BrowserMenu.ts +++ b/src/apps/browser/BrowserMenu.ts @@ -1,9 +1,19 @@ -import { promiseWithResolvers, type PromiseWithResolvers } from "octagonal-wheels/promises"; +import { fireAndForget, promiseWithResolvers, type PromiseWithResolvers } from "octagonal-wheels/promises"; import { createNativeElement } from "@/apps/browserDom"; -import { mount } from "svelte"; +import type { BrowserUiOptions } from "./BrowserUiScope"; +import { mount, unmount } from "svelte"; import MenuView from "./ui/MenuView.svelte"; import { _activeDocument } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; +type MountedMenu = ReturnType; +type MenuSession = { + waitingForClose: PromiseWithResolvers; + element: HTMLElement; + component?: MountedMenu; + abortListener?: () => void; + closed: boolean; +}; + export class MenuItem { type = "item"; title = ""; @@ -29,7 +39,15 @@ export class Menu { type = "menu"; items: (MenuItem | MenuSeparator)[] = []; - constructor() {} + private readonly document: Document; + private readonly signal?: AbortSignal; + private activeSession?: MenuSession; + + constructor(options: BrowserUiOptions = {}) { + this.document = options.document ?? _activeDocument; + this.signal = options.signal; + } + addItem(callback: (item: MenuItem) => void) { const item = new MenuItem(); callback(item); @@ -41,32 +59,75 @@ export class Menu { return this; } waitingForClose?: PromiseWithResolvers; - showAtPosition(pos: { x: number; y: number }) { - const el = createNativeElement(_activeDocument, "div"); - if (this.waitingForClose) { - this.waitingForClose.resolve(); + + showAtPosition(pos: { x: number; y: number }): Promise { + if (this.activeSession) { + this.closeSession(this.activeSession); } - this.waitingForClose = promiseWithResolvers(); - mount(MenuView, { - target: el, - props: { - items: this.items, - closeMenu: () => { - this.waitingForClose?.resolve(); - this.waitingForClose = undefined; + if (this.signal?.aborted) { + this.waitingForClose = undefined; + return Promise.resolve(); + } + + const waitingForClose = promiseWithResolvers(); + const element = createNativeElement(this.document, "div"); + const session: MenuSession = { + waitingForClose, + element, + closed: false, + }; + this.activeSession = session; + this.waitingForClose = waitingForClose; + + const closeMenu = () => this.closeSession(session); + session.abortListener = closeMenu; + this.signal?.addEventListener("abort", closeMenu, { once: true }); + + try { + session.component = mount(MenuView, { + target: element, + props: { + items: this.items, + closeMenu, + x: pos.x, + y: pos.y, }, - x: pos.x, - y: pos.y, - }, - }); - _activeDocument.body.appendChild(el); - void this.waitingForClose.promise.finally(() => { - el.remove(); - }); - return this.waitingForClose.promise; + }); + if (!session.closed) { + this.document.body.appendChild(element); + } else if (session.component) { + fireAndForget(() => unmount(session.component!)); + } + } catch (error) { + this.closeSession(session); + throw error; + } + + return waitingForClose.promise; } + + private closeSession(session: MenuSession): void { + if (session.closed) return; + session.closed = true; + if (session.abortListener) { + this.signal?.removeEventListener("abort", session.abortListener); + session.abortListener = undefined; + } + if (this.activeSession === session) { + this.activeSession = undefined; + this.waitingForClose = undefined; + } + + session.element.remove(); + if (session.component) { + fireAndForget(() => unmount(session.component!)); + } + session.waitingForClose.resolve(); + } + hide() { - this.waitingForClose?.resolve(); - this.waitingForClose = undefined; + if (this.activeSession) { + this.closeSession(this.activeSession); + } } } diff --git a/src/apps/browser/BrowserSvelteDialogManager.ts b/src/apps/browser/BrowserSvelteDialogManager.ts index b0e89a0d..17ae4f8d 100644 --- a/src/apps/browser/BrowserSvelteDialogManager.ts +++ b/src/apps/browser/BrowserSvelteDialogManager.ts @@ -8,6 +8,7 @@ import type { SvelteDialogManagerDependencies } from "@vrtmrz/livesync-commonlib import { _activeDocument } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import DialogHost from "@/modules/services/LiveSyncUI/DialogHost.svelte"; import { SvelteDialogSession } from "@/modules/services/SvelteDialogSession"; +import { createBrowserUiScope, type BrowserUiScope } from "./BrowserUiScope"; export class BrowserModal { contentEl: HTMLElement; @@ -15,14 +16,14 @@ export class BrowserModal { modalEl: HTMLElement; isOpen: boolean = false; baseEl: HTMLElement; - constructor() { - const baseEl = createNativeElement(_activeDocument, "popup"); + constructor(document: Document = _activeDocument) { + const baseEl = createNativeElement(document, "popup"); this.baseEl = baseEl; - this.contentEl = createNativeElement(_activeDocument, "div"); + this.contentEl = createNativeElement(document, "div"); this.contentEl.className = "modal-content"; - this.titleEl = createNativeElement(_activeDocument, "div"); + this.titleEl = createNativeElement(document, "div"); this.titleEl.className = "modal-title"; - this.modalEl = createNativeElement(_activeDocument, "div"); + this.modalEl = createNativeElement(document, "div"); this.modalEl.className = "modal"; this.modalEl.hidden = true; this.modalEl.appendChild(this.titleEl); @@ -33,7 +34,7 @@ export class BrowserModal { this.isOpen = true; this.modalEl.hidden = false; if (!this.baseEl.parentElement) { - _activeDocument.body.appendChild(this.baseEl); + this.baseEl.ownerDocument.body.appendChild(this.baseEl); } this.onOpen(); } @@ -57,9 +58,10 @@ export class LiveSyncBrowserDialog, component: ComponentHasResult, - initialData?: U + initialData?: U, + private readonly ui?: BrowserUiScope ) { - super(); + super(ui?.document ?? _activeDocument); this.session = new SvelteDialogSession({ surface: this, context, @@ -67,9 +69,15 @@ export class LiveSyncBrowserDialog extends SvelteDialogManagerBase { + constructor( + context: T, + dependencies: SvelteDialogManagerDependencies, + private readonly ui: BrowserUiScope = createBrowserUiScope(context) + ) { + super(context, dependencies); + } + override async openSvelteDialog( component: ComponentHasResult, initialData?: TU ): Promise { - const dialog = new LiveSyncBrowserDialog(this.context, this.dependents, component, initialData); + if (this.ui.signal.aborted) throw this.ui.signal.reason ?? new Error("Plug-in unloaded"); + const dialog = new LiveSyncBrowserDialog( + this.context, + this.dependents, + component, + initialData, + this.ui + ); dialog.open(); return await dialog.waitForClose(); } diff --git a/src/apps/browser/BrowserUiScope.ts b/src/apps/browser/BrowserUiScope.ts new file mode 100644 index 00000000..3fbc4439 --- /dev/null +++ b/src/apps/browser/BrowserUiScope.ts @@ -0,0 +1,38 @@ +import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import { EVENT_PLUGIN_UNLOADED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; +import { _activeDocument } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; + +export interface BrowserUiOptions { + readonly document?: Document; + readonly signal?: AbortSignal; +} + +/** Browser presentation target and lifetime owned by one application context. */ +export interface BrowserUiScope { + readonly document: Document; + readonly signal: AbortSignal; +} + +export function createBrowserUiScope( + context: Pick, + options: BrowserUiOptions = {} +): BrowserUiScope { + const controller = new AbortController(); + const parent = options.signal; + let unregisterUnload: (() => void) | undefined; + const end = (reason: unknown): void => { + if (controller.signal.aborted) return; + unregisterUnload?.(); + unregisterUnload = undefined; + parent?.removeEventListener("abort", onParentAbort); + controller.abort(reason); + }; + const onParentAbort = () => end(parent?.reason); + if (parent?.aborted) { + controller.abort(parent.reason); + } else { + unregisterUnload = context.events.onceEvent(EVENT_PLUGIN_UNLOADED, () => end(new Error("Plug-in unloaded"))); + parent?.addEventListener("abort", onParentAbort, { once: true }); + } + return { document: options.document ?? _activeDocument, signal: controller.signal }; +} diff --git a/src/apps/browser/LiveSyncBrowserUIService.ts b/src/apps/browser/LiveSyncBrowserUIService.ts index c0ab9d00..e8be307d 100644 --- a/src/apps/browser/LiveSyncBrowserUIService.ts +++ b/src/apps/browser/LiveSyncBrowserUIService.ts @@ -7,6 +7,7 @@ import type { InjectableAPIService } from "@vrtmrz/livesync-commonlib/compat/ser import { UIService } from "@vrtmrz/livesync-commonlib/compat/services/implements/base/UIService"; import DialogToCopy from "@/modules/services/LiveSyncUI/dialogues/DialogueToCopy.svelte"; import { BrowserSvelteDialogManager } from "./BrowserSvelteDialogManager"; +import type { BrowserUiScope } from "./BrowserUiScope"; export interface LiveSyncBrowserUIServiceDependencies { API: InjectableAPIService; @@ -20,15 +21,19 @@ export class LiveSyncBrowserUIService extends UIServic override get dialogToCopy() { return DialogToCopy; } - constructor(context: T, dependents: LiveSyncBrowserUIServiceDependencies) { + constructor(context: T, dependents: LiveSyncBrowserUIServiceDependencies, ui?: BrowserUiScope) { const browserConfirm = dependents.API.confirm; - const obsidianSvelteDialogManager = new BrowserSvelteDialogManager(context, { - appLifecycle: dependents.appLifecycle, - config: dependents.config, - replicator: dependents.replicator, - confirm: browserConfirm, - control: dependents.control, - }); + const obsidianSvelteDialogManager = new BrowserSvelteDialogManager( + context, + { + appLifecycle: dependents.appLifecycle, + config: dependents.config, + replicator: dependents.replicator, + confirm: browserConfirm, + control: dependents.control, + }, + ui + ); super(context, { dialogManager: obsidianSvelteDialogManager, APIService: dependents.API, diff --git a/src/apps/browser/createLiveSyncBrowserServiceHub.ts b/src/apps/browser/createLiveSyncBrowserServiceHub.ts index 3197114a..cb0e355d 100644 --- a/src/apps/browser/createLiveSyncBrowserServiceHub.ts +++ b/src/apps/browser/createLiveSyncBrowserServiceHub.ts @@ -22,6 +22,7 @@ import { InjectableVaultServiceCompat } from "@vrtmrz/livesync-commonlib/compat/ import { setLang, translateLiveSyncMessage } from "@/common/translation"; import { BrowserConfirm } from "./BrowserConfirm"; +import { createBrowserUiScope, type BrowserUiOptions, type BrowserUiScope } from "./BrowserUiScope"; import { createBrowserKeyValueDatabaseFactory } from "./BrowserKeyValueDatabase"; import { LiveSyncBrowserAPIService, type LiveSyncBrowserAPIServiceOptions } from "./LiveSyncBrowserAPIService"; import { LiveSyncBrowserUIService } from "./LiveSyncBrowserUIService"; @@ -41,6 +42,7 @@ export interface LiveSyncBrowserRestartPolicy { export interface LiveSyncBrowserServiceHubOptions { deviceValues: ValueStore & ValueDeleter; context?: T; + ui?: BrowserUiOptions; getSystemVaultName?: () => string; settings?: LiveSyncBrowserSettingsPersistence; restart?: LiveSyncBrowserRestartPolicy; @@ -56,15 +58,18 @@ class LiveSyncBrowserKeyValueDBService extends KeyValu /** LiveSync-owned service composition shared by WebApp and WebPeer. */ export class LiveSyncBrowserServiceHub extends InjectableServiceHub { + readonly browserUi: BrowserUiScope; + constructor(options: LiveSyncBrowserServiceHubOptions) { const context = options.context ?? (new ServiceContext({ translate: translateLiveSyncMessage, }) as T); + const browserUi = createBrowserUiScope(context, options.ui); const API = new LiveSyncBrowserAPIService(context, { ...options.API, - confirm: new BrowserConfirm(context), + confirm: new BrowserConfirm(context, browserUi), getSystemVaultName: options.getSystemVaultName ?? (() => "livesync-browser"), }); const conflict = new InjectableConflictService(context); @@ -147,13 +152,17 @@ export class LiveSyncBrowserServiceHub extends Injecta APIService: API, replicatorService: replicator, }); - const ui = new LiveSyncBrowserUIService(context, { - API, - appLifecycle, - config, - control, - replicator, - }); + const ui = new LiveSyncBrowserUIService( + context, + { + API, + appLifecycle, + config, + control, + replicator, + }, + browserUi + ); super(context, { API, @@ -175,6 +184,7 @@ export class LiveSyncBrowserServiceHub extends Injecta ui, vault, }); + this.browserUi = browserUi; } } diff --git a/src/common/diffNavigation.ts b/src/common/diffNavigation.ts new file mode 100644 index 00000000..543e8490 --- /dev/null +++ b/src/common/diffNavigation.ts @@ -0,0 +1,25 @@ +import { stepCyclicIndex } from "octagonal-wheels/collection"; + +export function navigateDiffNodes( + root: ParentNode, + selector: string, + navigation: { + currentDiffIndex: number; + diffNavIndicator: { setText(text: string): void }; + }, + direction: "prev" | "next" +): void { + const diffElements = root.querySelectorAll(selector); + if (diffElements.length === 0) return; + + const previousFocused = root.querySelector(".diff-focused"); + if (previousFocused) { + previousFocused.classList.remove("diff-focused"); + } + + navigation.currentDiffIndex = stepCyclicIndex(navigation.currentDiffIndex, diffElements.length, direction); + const target = diffElements[navigation.currentDiffIndex]; + target.classList.add("diff-focused"); + target.scrollIntoView({ behavior: "smooth", block: "center" }); + navigation.diffNavIndicator.setText(`${navigation.currentDiffIndex + 1}/${diffElements.length}`); +} diff --git a/src/modules/features/DocumentHistory/DocumentHistoryModal.navigation.unit.spec.ts b/src/modules/features/DocumentHistory/DocumentHistoryModal.navigation.unit.spec.ts new file mode 100644 index 00000000..bef11ead --- /dev/null +++ b/src/modules/features/DocumentHistory/DocumentHistoryModal.navigation.unit.spec.ts @@ -0,0 +1,321 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@/deps.ts", () => ({ + Modal: class Modal {}, + TFile: class TFile {}, +})); + +vi.mock("@/main.ts", () => ({ + default: class ObsidianLiveSyncPlugin {}, +})); + +vi.mock("@/common/utils.ts", () => ({ + getPathFromTFile: (file: { path: string }) => file.path, + isValidPath: vi.fn(() => true), +})); + +vi.mock("octagonal-wheels/concurrency/lock", () => ({ + scheduleOnceIfDuplicated: vi.fn((_key: string, callback: () => unknown) => callback()), +})); + +import { scheduleOnceIfDuplicated } from "octagonal-wheels/concurrency/lock"; +import { DocumentHistoryModal } from "./DocumentHistoryModal.ts"; + +type NavigationTarget = { + classList: { add: ReturnType; remove: ReturnType }; + scrollIntoView: ReturnType; +}; + +function createDiffView(count: number) { + const focused: { current: NavigationTarget | undefined } = { current: undefined }; + const createTargets = (targetCount: number) => + Array.from({ length: targetCount }, () => { + const target: NavigationTarget = { + classList: { + add: vi.fn(() => { + focused.current = target; + }), + remove: vi.fn(() => { + if (focused.current === target) focused.current = undefined; + }), + }, + scrollIntoView: vi.fn(), + }; + return target; + }); + let targets = createTargets(count); + const contentView = { + querySelectorAll: vi.fn(() => targets), + querySelector: vi.fn(() => (targets.includes(focused.current as NavigationTarget) ? focused.current : null)), + }; + return { + contentView, + targets, + replaceTargets(targetCount: number) { + focused.current = undefined; + targets = createTargets(targetCount); + return targets; + }, + }; +} + +function createHistoryModal() { + return Object.create(DocumentHistoryModal.prototype) as DocumentHistoryModal; +} + +describe("DocumentHistoryModal cyclic navigation", () => { + it("commits the selected index before scrolling, including when scrolling fails", () => { + const modal = createHistoryModal(); + const view = createDiffView(2); + const indicator = { setText: vi.fn() }; + const failure = new Error("fixture scroll failed"); + Object.assign(modal, { contentView: view.contentView, currentDiffIndex: -1, diffNavIndicator: indicator }); + view.targets[0].scrollIntoView.mockImplementation(() => { + expect(modal.currentDiffIndex).toBe(0); + throw failure; + }); + expect(() => modal.navigateDiff("next")).toThrow(failure); + expect(modal.currentDiffIndex).toBe(0); + expect(indicator.setText).not.toHaveBeenCalled(); + }); + + it("starts at the first diff for next and at the last diff for previous", () => { + const nextModal = createHistoryModal(); + const nextView = createDiffView(3); + const nextIndicator = { setText: vi.fn() }; + Object.assign(nextModal, { + contentView: nextView.contentView, + currentDiffIndex: -1, + diffNavIndicator: nextIndicator, + }); + + nextModal.navigateDiff("next"); + + expect(nextModal.currentDiffIndex).toBe(0); + expect(nextView.targets[0].classList.add).toHaveBeenCalledWith("diff-focused"); + expect(nextView.targets[0].scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" }); + expect(nextIndicator.setText).toHaveBeenCalledWith("1/3"); + + const previousModal = createHistoryModal(); + const previousView = createDiffView(3); + const previousIndicator = { setText: vi.fn() }; + Object.assign(previousModal, { + contentView: previousView.contentView, + currentDiffIndex: -1, + diffNavIndicator: previousIndicator, + }); + + previousModal.navigateDiff("prev"); + + expect(previousModal.currentDiffIndex).toBe(2); + expect(previousView.targets[2].classList.add).toHaveBeenCalledWith("diff-focused"); + expect(previousView.targets[2].scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" }); + expect(previousIndicator.setText).toHaveBeenCalledWith("3/3"); + }); + + it("wraps in both directions while moving focus, scrolling, and updating the indicator", () => { + const modal = createHistoryModal(); + const { contentView, targets } = createDiffView(3); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { contentView, currentDiffIndex: -1, diffNavIndicator: indicator }); + + modal.navigateDiff("next"); + modal.navigateDiff("next"); + modal.navigateDiff("next"); + modal.navigateDiff("next"); + modal.navigateDiff("prev"); + + expect(modal.currentDiffIndex).toBe(2); + expect(targets.map((target) => target.classList.add.mock.calls.length)).toEqual([2, 1, 2]); + expect(targets.map((target) => target.classList.remove.mock.calls.length)).toEqual([2, 1, 1]); + expect(targets.map((target) => target.scrollIntoView.mock.calls.length)).toEqual([2, 1, 2]); + expect(indicator.setText.mock.calls.map(([text]) => text)).toEqual(["1/3", "2/3", "3/3", "1/3", "3/3"]); + }); + + it("leaves the current navigation index and content view untouched when no diff exists", () => { + const modal = createHistoryModal(); + const { contentView } = createDiffView(0); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { contentView, currentDiffIndex: 1, diffNavIndicator: indicator }); + + modal.navigateDiff("next"); + + expect(modal.currentDiffIndex).toBe(1); + expect(contentView.querySelector).not.toHaveBeenCalled(); + expect(indicator.setText).not.toHaveBeenCalled(); + }); + + it("looks up diff nodes again after the content view is replaced", () => { + const modal = createHistoryModal(); + const view = createDiffView(2); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { contentView: view.contentView, currentDiffIndex: -1, diffNavIndicator: indicator }); + + modal.navigateDiff("next"); + const replacementTargets = view.replaceTargets(3); + modal.navigateDiff("next"); + + expect(modal.currentDiffIndex).toBe(1); + expect(view.contentView.querySelectorAll).toHaveBeenCalledTimes(2); + expect(view.contentView.querySelector).toHaveBeenCalledTimes(2); + expect(replacementTargets[1].classList.add).toHaveBeenCalledWith("diff-focused"); + expect(replacementTargets[1].scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" }); + expect(indicator.setText.mock.calls.map(([text]) => text)).toEqual(["1/2", "2/3"]); + }); + + it("keeps navigation indices and focus independent between modal instances", () => { + const firstModal = createHistoryModal(); + const secondModal = createHistoryModal(); + const firstView = createDiffView(2); + const secondView = createDiffView(2); + Object.assign(firstModal, { + contentView: firstView.contentView, + currentDiffIndex: -1, + diffNavIndicator: { setText: vi.fn() }, + }); + Object.assign(secondModal, { + contentView: secondView.contentView, + currentDiffIndex: -1, + diffNavIndicator: { setText: vi.fn() }, + }); + + firstModal.navigateDiff("next"); + secondModal.navigateDiff("next"); + firstModal.navigateDiff("next"); + + expect(firstModal.currentDiffIndex).toBe(1); + expect(secondModal.currentDiffIndex).toBe(0); + expect(firstView.targets[0].classList.remove).toHaveBeenCalledWith("diff-focused"); + expect(secondView.targets[0].classList.remove).not.toHaveBeenCalled(); + expect(secondView.targets[0].classList.add).toHaveBeenCalledWith("diff-focused"); + }); + + it("resets the indicator and visibility according to showDiff", () => { + const modal = createHistoryModal(); + const view = createDiffView(2); + const indicator = { setText: vi.fn() }; + const diffNavContainer = { setCssStyles: vi.fn() }; + const diffOnlyLabel = { setCssStyles: vi.fn() }; + Object.assign(modal, { + contentView: view.contentView, + currentDiffIndex: 1, + diffNavIndicator: indicator, + diffNavContainer, + diffOnlyLabel, + showDiff: true, + }); + + modal.resetDiffNavigation(); + + expect(modal.currentDiffIndex).toBe(-1); + expect(view.contentView.querySelectorAll).toHaveBeenCalledWith(".history-added, .history-deleted"); + expect(indicator.setText).toHaveBeenLastCalledWith("0/2"); + expect(diffNavContainer.setCssStyles).toHaveBeenLastCalledWith({ display: "flex" }); + expect(diffOnlyLabel.setCssStyles).toHaveBeenLastCalledWith({ display: "inline-block" }); + + view.replaceTargets(0); + modal.resetDiffNavigation(); + expect(indicator.setText).toHaveBeenLastCalledWith("\u2014"); + + Object.assign(modal, { showDiff: false }); + modal.resetDiffNavigation(); + expect(view.contentView.querySelectorAll).toHaveBeenCalledTimes(2); + expect(indicator.setText).toHaveBeenLastCalledWith("\u2014"); + expect(diffNavContainer.setCssStyles).toHaveBeenLastCalledWith({ display: "none" }); + expect(diffOnlyLabel.setCssStyles).toHaveBeenLastCalledWith({ display: "none" }); + }); + + it("updates visibility without an indicator", () => { + const modal = createHistoryModal(); + const { contentView } = createDiffView(2); + const diffNavContainer = { setCssStyles: vi.fn() }; + Object.assign(modal, { contentView, currentDiffIndex: 1, diffNavContainer, showDiff: true }); + + expect(() => modal.resetDiffNavigation()).not.toThrow(); + + expect(modal.currentDiffIndex).toBe(-1); + expect(contentView.querySelectorAll).not.toHaveBeenCalled(); + expect(diffNavContainer.setCssStyles).toHaveBeenCalledWith({ display: "flex" }); + }); + + it("maps selected search results to the revision slider and loads each wrapped selection", () => { + const modal = createHistoryModal(); + const scheduleLoad = vi.mocked(scheduleOnceIfDuplicated); + scheduleLoad.mockClear(); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { + searchResults: [ + { rev: "newest", index: 0, matchType: "Content" }, + { rev: "middle", index: 2, matchType: "Diff" }, + { rev: "oldest", index: 4, matchType: "Content" }, + ], + currentSearchIndex: -1, + revs_info: Array.from({ length: 5 }, (_, index) => ({ rev: `rev-${index}` })), + range: { value: "" }, + loadRevs: vi.fn(), + searchResultIndicator: indicator, + searchPrevBtn: { disabled: true }, + searchNextBtn: { disabled: true }, + searchKeyword: "needle", + showDiff: false, + }); + + modal.navigateSearch("next"); + expect(modal.currentSearchIndex).toBe(0); + expect(modal.range.value).toBe("4"); + expect(modal.loadRevs).toHaveBeenCalledTimes(1); + expect(scheduleLoad).toHaveBeenCalledWith("loadRevs", expect.any(Function)); + expect(indicator.setText).toHaveBeenLastCalledWith("1/3 matches"); + + modal.navigateSearch("next"); + expect(modal.currentSearchIndex).toBe(1); + expect(modal.range.value).toBe("2"); + expect(modal.loadRevs).toHaveBeenCalledTimes(2); + + modal.navigateSearch("next"); + expect(modal.currentSearchIndex).toBe(2); + expect(modal.range.value).toBe("0"); + + modal.navigateSearch("next"); + expect(modal.currentSearchIndex).toBe(0); + expect(modal.range.value).toBe("4"); + + modal.navigateSearch("prev"); + expect(modal.currentSearchIndex).toBe(2); + expect(modal.range.value).toBe("0"); + expect(indicator.setText.mock.calls.map(([text]) => text)).toEqual([ + "1/3 matches", + "2/3 matches", + "3/3 matches", + "1/3 matches", + "3/3 matches", + ]); + }); + + it("leaves search state and controls untouched when there are no results", () => { + const modal = createHistoryModal(); + const indicator = { setText: vi.fn() }; + const searchPrevBtn = { disabled: true }; + const searchNextBtn = { disabled: true }; + Object.assign(modal, { + searchResults: [], + currentSearchIndex: -1, + range: { value: "unchanged" }, + loadRevs: vi.fn(), + searchResultIndicator: indicator, + searchPrevBtn, + searchNextBtn, + searchKeyword: "needle", + showDiff: false, + }); + + modal.navigateSearch("next"); + + expect(modal.currentSearchIndex).toBe(-1); + expect(modal.range.value).toBe("unchanged"); + expect(modal.loadRevs).not.toHaveBeenCalled(); + expect(indicator.setText).not.toHaveBeenCalled(); + expect(searchPrevBtn.disabled).toBe(true); + expect(searchNextBtn.disabled).toBe(true); + }); +}); diff --git a/src/modules/features/DocumentHistory/DocumentHistoryModal.ts b/src/modules/features/DocumentHistory/DocumentHistoryModal.ts index 57b734ba..1a9b106e 100644 --- a/src/modules/features/DocumentHistory/DocumentHistoryModal.ts +++ b/src/modules/features/DocumentHistory/DocumentHistoryModal.ts @@ -15,6 +15,8 @@ import { isErrorOfMissingDoc } from "@vrtmrz/livesync-commonlib/compat/pouchdb/u import { fireAndForget, getDocData } from "@vrtmrz/livesync-commonlib/compat/common/utils"; import { isPlainText, stripPrefix } from "@vrtmrz/livesync-commonlib/compat/string_and_binary/path"; import { scheduleOnceIfDuplicated } from "octagonal-wheels/concurrency/lock"; +import { stepCyclicIndex } from "octagonal-wheels/collection"; +import { navigateDiffNodes } from "@/common/diffNavigation.ts"; import type { LiveSyncBaseCore } from "@/LiveSyncBaseCore.ts"; import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { @@ -375,26 +377,7 @@ export class DocumentHistoryModal extends Modal { * Only effective when diff highlighting is enabled. */ navigateDiff(direction: "prev" | "next") { - const diffElements = this.contentView.querySelectorAll(".history-added, .history-deleted"); - if (diffElements.length === 0) return; - - // Remove previous focus highlight - const prevFocused = this.contentView.querySelector(".diff-focused"); - if (prevFocused) { - prevFocused.classList.remove("diff-focused"); - } - - if (direction === "next") { - this.currentDiffIndex = (this.currentDiffIndex + 1) % diffElements.length; - } else { - this.currentDiffIndex = this.currentDiffIndex <= 0 ? diffElements.length - 1 : this.currentDiffIndex - 1; - } - - const target = diffElements[this.currentDiffIndex]; - target.classList.add("diff-focused"); - target.scrollIntoView({ behavior: "smooth", block: "center" }); - - this.diffNavIndicator.setText(`${this.currentDiffIndex + 1}/${diffElements.length}`); + navigateDiffNodes(this.contentView, ".history-added, .history-deleted", this, direction); } /** @@ -519,12 +502,7 @@ export class DocumentHistoryModal extends Modal { navigateSearch(direction: "prev" | "next") { if (this.searchResults.length === 0) return; - if (direction === "next") { - this.currentSearchIndex = (this.currentSearchIndex + 1) % this.searchResults.length; - } else { - this.currentSearchIndex = - this.currentSearchIndex <= 0 ? this.searchResults.length - 1 : this.currentSearchIndex - 1; - } + this.currentSearchIndex = stepCyclicIndex(this.currentSearchIndex, this.searchResults.length, direction); const match = this.searchResults[this.currentSearchIndex]; this.range.value = `${this.revs_info.length - 1 - match.index}`; diff --git a/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts b/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts index a5b22068..bc6674d7 100644 --- a/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts +++ b/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts @@ -7,6 +7,7 @@ import { type FilePathWithPrefix, } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { EVENT_CONFLICT_CANCELLED, EVENT_PLUGIN_UNLOADED, eventHub } from "@/common/events.ts"; +import { navigateDiffNodes } from "@/common/diffNavigation.ts"; import { promiseWithResolvers } from "octagonal-wheels/promises"; import { POSTPONED, type MergeDialogResult } from "@/serviceFeatures/interactiveConflictResolution/types"; @@ -83,24 +84,7 @@ export class ConflictResolveModal extends Modal { } navigateDiff(direction: "prev" | "next") { - const diffElements = this.diffView.querySelectorAll(".added, .deleted"); - if (diffElements.length === 0) return; - - const prevFocused = this.diffView.querySelector(".diff-focused"); - if (prevFocused) { - prevFocused.classList.remove("diff-focused"); - } - - if (direction === "next") { - this.currentDiffIndex = (this.currentDiffIndex + 1) % diffElements.length; - } else { - this.currentDiffIndex = this.currentDiffIndex <= 0 ? diffElements.length - 1 : this.currentDiffIndex - 1; - } - - const target = diffElements[this.currentDiffIndex]; - target.classList.add("diff-focused"); - target.scrollIntoView({ behavior: "smooth", block: "center" }); - this.diffNavIndicator.setText(`${this.currentDiffIndex + 1}/${diffElements.length}`); + navigateDiffNodes(this.diffView, ".added, .deleted", this, direction); } resetDiffNavigation() { diff --git a/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.unit.spec.ts b/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.unit.spec.ts index 8e4cfd94..b37fb8d1 100644 --- a/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.unit.spec.ts +++ b/src/modules/features/InteractiveConflictResolving/ConflictResolveModal.unit.spec.ts @@ -106,11 +106,7 @@ describe("ConflictResolveModal result lifecycle", () => { }); it("closes and completes its result when the plug-in unloads", async () => { - const modal = new ConflictResolveModal( - {} as never, - "open-during-unload.md" as FilePathWithPrefix, - conflict - ); + const modal = new ConflictResolveModal({} as never, "open-during-unload.md" as FilePathWithPrefix, conflict); modal.onOpen(); eventHub.emitEvent(EVENT_PLUGIN_UNLOADED); @@ -165,3 +161,186 @@ describe("ConflictResolveModal result lifecycle", () => { expect(previousState).toBe("still-open"); }); }); + +type NavigationTarget = { + classList: { add: ReturnType; remove: ReturnType }; + scrollIntoView: ReturnType; +}; + +function createDiffView(count: number) { + const focused: { current: NavigationTarget | undefined } = { current: undefined }; + const createTargets = (targetCount: number) => + Array.from({ length: targetCount }, () => { + const target: NavigationTarget = { + classList: { + add: vi.fn(() => { + focused.current = target; + }), + remove: vi.fn(() => { + if (focused.current === target) focused.current = undefined; + }), + }, + scrollIntoView: vi.fn(), + }; + return target; + }); + let targets = createTargets(count); + const diffView = { + querySelectorAll: vi.fn(() => targets), + querySelector: vi.fn(() => (targets.includes(focused.current as NavigationTarget) ? focused.current : null)), + }; + return { + diffView, + targets, + replaceTargets(targetCount: number) { + focused.current = undefined; + targets = createTargets(targetCount); + return targets; + }, + }; +} + +describe("ConflictResolveModal cyclic navigation", () => { + it("commits the selected index before scrolling, including when scrolling fails", () => { + const modal = Object.create(ConflictResolveModal.prototype) as ConflictResolveModal; + const view = createDiffView(2); + const indicator = { setText: vi.fn() }; + const failure = new Error("fixture scroll failed"); + Object.assign(modal, { diffView: view.diffView, currentDiffIndex: -1, diffNavIndicator: indicator }); + view.targets[0].scrollIntoView.mockImplementation(() => { + expect(modal.currentDiffIndex).toBe(0); + throw failure; + }); + expect(() => modal.navigateDiff("next")).toThrow(failure); + expect(modal.currentDiffIndex).toBe(0); + expect(indicator.setText).not.toHaveBeenCalled(); + }); + + it("starts at the first diff for next and at the last diff for previous", () => { + const nextModal = new ConflictResolveModal({} as never, "next.md" as FilePathWithPrefix, conflict); + const nextView = createDiffView(3); + const nextIndicator = { setText: vi.fn() }; + Object.assign(nextModal, { + diffView: nextView.diffView, + currentDiffIndex: -1, + diffNavIndicator: nextIndicator, + }); + + nextModal.navigateDiff("next"); + + expect(nextModal.currentDiffIndex).toBe(0); + expect(nextView.targets[0].classList.add).toHaveBeenCalledWith("diff-focused"); + expect(nextView.targets[0].scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" }); + expect(nextIndicator.setText).toHaveBeenCalledWith("1/3"); + + const previousModal = new ConflictResolveModal({} as never, "previous.md" as FilePathWithPrefix, conflict); + const previousView = createDiffView(3); + const previousIndicator = { setText: vi.fn() }; + Object.assign(previousModal, { + diffView: previousView.diffView, + currentDiffIndex: -1, + diffNavIndicator: previousIndicator, + }); + + previousModal.navigateDiff("prev"); + + expect(previousModal.currentDiffIndex).toBe(2); + expect(previousView.targets[2].classList.add).toHaveBeenCalledWith("diff-focused"); + expect(previousView.targets[2].scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" }); + expect(previousIndicator.setText).toHaveBeenCalledWith("3/3"); + }); + + it("wraps in both directions while moving focus, scrolling, and updating the indicator", () => { + const modal = new ConflictResolveModal({} as never, "wrap.md" as FilePathWithPrefix, conflict); + const { diffView, targets } = createDiffView(3); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { diffView, currentDiffIndex: -1, diffNavIndicator: indicator }); + + modal.navigateDiff("next"); + modal.navigateDiff("next"); + modal.navigateDiff("next"); + modal.navigateDiff("next"); + modal.navigateDiff("prev"); + + expect(modal.currentDiffIndex).toBe(2); + expect(targets.map((target) => target.classList.add.mock.calls.length)).toEqual([2, 1, 2]); + expect(targets.map((target) => target.classList.remove.mock.calls.length)).toEqual([2, 1, 1]); + expect(targets.map((target) => target.scrollIntoView.mock.calls.length)).toEqual([2, 1, 2]); + expect(indicator.setText.mock.calls.map(([text]) => text)).toEqual(["1/3", "2/3", "3/3", "1/3", "3/3"]); + }); + + it("leaves the current navigation index and diff view untouched when no diff exists", () => { + const modal = new ConflictResolveModal({} as never, "empty.md" as FilePathWithPrefix, conflict); + const { diffView } = createDiffView(0); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { diffView, currentDiffIndex: 1, diffNavIndicator: indicator }); + + modal.navigateDiff("next"); + + expect(modal.currentDiffIndex).toBe(1); + expect(diffView.querySelector).not.toHaveBeenCalled(); + expect(indicator.setText).not.toHaveBeenCalled(); + }); + + it("looks up diff nodes again after the diff view is replaced", () => { + const modal = new ConflictResolveModal({} as never, "replace.md" as FilePathWithPrefix, conflict); + const view = createDiffView(2); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { diffView: view.diffView, currentDiffIndex: -1, diffNavIndicator: indicator }); + + modal.navigateDiff("next"); + const replacementTargets = view.replaceTargets(3); + modal.navigateDiff("next"); + + expect(modal.currentDiffIndex).toBe(1); + expect(view.diffView.querySelectorAll).toHaveBeenCalledTimes(2); + expect(view.diffView.querySelector).toHaveBeenCalledTimes(2); + expect(replacementTargets[1].classList.add).toHaveBeenCalledWith("diff-focused"); + expect(replacementTargets[1].scrollIntoView).toHaveBeenCalledWith({ behavior: "smooth", block: "center" }); + expect(indicator.setText.mock.calls.map(([text]) => text)).toEqual(["1/2", "2/3"]); + }); + + it("keeps navigation indices and focus independent between modal instances", () => { + const firstModal = new ConflictResolveModal({} as never, "first.md" as FilePathWithPrefix, conflict); + const secondModal = new ConflictResolveModal({} as never, "second.md" as FilePathWithPrefix, conflict); + const firstView = createDiffView(2); + const secondView = createDiffView(2); + Object.assign(firstModal, { + diffView: firstView.diffView, + currentDiffIndex: -1, + diffNavIndicator: { setText: vi.fn() }, + }); + Object.assign(secondModal, { + diffView: secondView.diffView, + currentDiffIndex: -1, + diffNavIndicator: { setText: vi.fn() }, + }); + + firstModal.navigateDiff("next"); + secondModal.navigateDiff("next"); + firstModal.navigateDiff("next"); + + expect(firstModal.currentDiffIndex).toBe(1); + expect(secondModal.currentDiffIndex).toBe(0); + expect(firstView.targets[0].classList.remove).toHaveBeenCalledWith("diff-focused"); + expect(secondView.targets[0].classList.remove).not.toHaveBeenCalled(); + expect(secondView.targets[0].classList.add).toHaveBeenCalledWith("diff-focused"); + }); + + it("always resets the indicator using the current diff count", () => { + const modal = new ConflictResolveModal({} as never, "reset.md" as FilePathWithPrefix, conflict); + const view = createDiffView(2); + const indicator = { setText: vi.fn() }; + Object.assign(modal, { diffView: view.diffView, currentDiffIndex: 1, diffNavIndicator: indicator }); + + modal.resetDiffNavigation(); + + expect(modal.currentDiffIndex).toBe(-1); + expect(view.diffView.querySelectorAll).toHaveBeenCalledWith(".added, .deleted"); + expect(indicator.setText).toHaveBeenLastCalledWith("0/2"); + + view.replaceTargets(0); + modal.resetDiffNavigation(); + expect(indicator.setText).toHaveBeenLastCalledWith("\u2014"); + }); +}); diff --git a/src/modules/services/SvelteDialogSession.ts b/src/modules/services/SvelteDialogSession.ts index 3643aae7..07435b50 100644 --- a/src/modules/services/SvelteDialogSession.ts +++ b/src/modules/services/SvelteDialogSession.ts @@ -34,6 +34,7 @@ export interface SvelteDialogSessionOptions; initialData?: TInitial; renderer?: SvelteDialogRenderer; + signal?: AbortSignal; } const svelteDialogRenderer: SvelteDialogRenderer = { @@ -46,11 +47,7 @@ const svelteDialogRenderer: SvelteDialogRenderer = { }; /** Owns one Svelte dialogue result and mount lifecycle for a concrete host surface. */ -export class SvelteDialogSession< - TResult, - TInitial, - TContext extends ServiceContext = ServiceContext, -> { +export class SvelteDialogSession { private readonly surface: SvelteDialogSurface; private readonly context: TContext; private readonly dependencies: SvelteDialogManagerDependencies; @@ -58,11 +55,13 @@ export class SvelteDialogSession< private readonly component: ComponentHasResult; private readonly initialData?: TInitial; private readonly renderer: SvelteDialogRenderer; + private readonly signal?: AbortSignal; private result?: TResult; private pendingResult?: PromiseWithResolvers; private mountedDialog?: MountedDialog; private unregisterUnload?: () => void; + private unregisterAbort?: () => void; constructor(options: SvelteDialogSessionOptions) { this.surface = options.surface; @@ -72,10 +71,14 @@ export class SvelteDialogSession< this.component = options.component; this.initialData = options.initialData; this.renderer = options.renderer ?? svelteDialogRenderer; + this.signal = options.signal; } onOpen(): void { + if (this.signal?.aborted) throw this.signal.reason ?? new Error("Plug-in unloaded"); this.surface.contentEl.replaceChildren(); + this.unregisterAbort?.(); + this.unregisterAbort = undefined; this.unregisterUnload?.(); this.unregisterUnload = undefined; if (this.pendingResult) { @@ -85,14 +88,23 @@ export class SvelteDialogSession< this.result = undefined; const pendingResult = promiseWithResolvers(); this.pendingResult = pendingResult; - this.unregisterUnload = this.context.events.onceEvent(EVENT_PLUGIN_UNLOADED, () => { + const cancel = (reason: unknown) => { if (this.pendingResult !== pendingResult) { return; } this.pendingResult = undefined; - pendingResult.reject(new Error("Plug-in unloaded")); + pendingResult.reject(reason); this.surface.close(); + }; + this.unregisterUnload = this.context.events.onceEvent(EVENT_PLUGIN_UNLOADED, () => { + cancel(new Error("Plug-in unloaded")); }); + const signal = this.signal; + if (signal) { + const onAbort = () => cancel(signal.reason ?? new Error("Plug-in unloaded")); + signal.addEventListener("abort", onAbort, { once: true }); + this.unregisterAbort = () => signal.removeEventListener("abort", onAbort); + } this.mountedDialog = this.renderer.mount(this.dialogHost, this.surface.contentEl, { onSetupContext: (props: DialogSvelteComponentBaseProps) => { @@ -124,6 +136,8 @@ export class SvelteDialogSession< } onClose(): void { + this.unregisterAbort?.(); + this.unregisterAbort = undefined; this.unregisterUnload?.(); this.unregisterUnload = undefined; this.pendingResult?.resolve(this.result); diff --git a/test/apps/browser/BrowserConfirm.unit.spec.ts b/test/apps/browser/BrowserConfirm.unit.spec.ts new file mode 100644 index 00000000..d279eefd --- /dev/null +++ b/test/apps/browser/BrowserConfirm.unit.spec.ts @@ -0,0 +1,73 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { createServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import { EVENT_PLUGIN_UNLOADED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; + +const kit = vi.hoisted(() => ({ + uiOptions: [] as { document: Document; signal: AbortSignal }[], + notices: [] as { document: Document; dispose: ReturnType; show: ReturnType }[], +})); +vi.mock("@vrtmrz/browser-ui-kit", () => ({ + createBrowserUi(options: { document: Document; signal: AbortSignal }) { + kit.uiOptions.push(options); + return { promptText: vi.fn(async () => "selected") }; + }, + BrowserUiNotifications: class { + dispose = vi.fn(); + show = vi.fn(); + constructor(options: { document: Document }) { + kit.notices.push({ document: options.document, dispose: this.dispose, show: this.show }); + } + }, +})); +import { BrowserConfirm } from "@/apps/browser/BrowserConfirm"; +import { createBrowserUiScope } from "@/apps/browser/BrowserUiScope"; + +beforeEach(() => { + kit.uiOptions.length = 0; + kit.notices.length = 0; +}); + +describe("BrowserConfirm UI owner", () => { + it("passes the same document and lifetime to existing Kit capabilities", async () => { + const context = createServiceContext(); + const anchor = { textContent: "", click: vi.fn() }; + const document = { createElement: vi.fn(() => anchor) } as unknown as Document; + const ui = createBrowserUiScope(context, { document }); + const confirm = new BrowserConfirm(context, ui); + expect(kit.uiOptions[0]).toMatchObject({ document, signal: ui.signal }); + expect(kit.notices[0].document).toBe(document); + await expect(confirm.askString("Title", "Value", "Placeholder")).resolves.toBe("selected"); + confirm.askInPopup("key", "Go {HERE}", (link) => { + link.textContent = "Open"; + }); + expect(document.createElement).toHaveBeenCalledWith("a"); + expect(kit.notices[0].show).toHaveBeenCalledWith( + "key", + expect.objectContaining({ action: expect.objectContaining({ label: "Open" }) }) + ); + context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(ui.signal.aborted).toBe(true); + expect(kit.notices[0].dispose).toHaveBeenCalledOnce(); + }); + it("disposes only the notifications belonging to the unloaded context", () => { + const first = createServiceContext(); + const second = createServiceContext(); + new BrowserConfirm(first, createBrowserUiScope(first, { document: {} as Document })); + new BrowserConfirm(second, createBrowserUiScope(second, { document: {} as Document })); + first.events.emitEvent(EVENT_PLUGIN_UNLOADED); + first.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(kit.notices[0].dispose).toHaveBeenCalledOnce(); + expect(kit.notices[1].dispose).not.toHaveBeenCalled(); + second.events.emitEvent(EVENT_PLUGIN_UNLOADED); + }); + it("disposes notifications immediately for a pre-aborted owner", () => { + const context = createServiceContext(); + const parent = new AbortController(); + parent.abort(); + new BrowserConfirm(context, createBrowserUiScope(context, { signal: parent.signal })); + expect(kit.uiOptions[0].signal.aborted).toBe(true); + expect(kit.notices[0].dispose).toHaveBeenCalledOnce(); + context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(kit.notices[0].dispose).toHaveBeenCalledOnce(); + }); +}); diff --git a/test/apps/browser/BrowserMenu.unit.spec.ts b/test/apps/browser/BrowserMenu.unit.spec.ts new file mode 100644 index 00000000..b0ef0fb6 --- /dev/null +++ b/test/apps/browser/BrowserMenu.unit.spec.ts @@ -0,0 +1,286 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const browserMenuHarness = vi.hoisted(() => { + const createDocument = () => { + const created: { tag: string; removed: boolean; remove: ReturnType }[] = []; + const appended: unknown[] = []; + const document = { + createElement: vi.fn((tag: string) => { + const element: { tag: string; removed: boolean; remove: ReturnType } = { + tag, + removed: false, + remove: vi.fn(() => { + element.removed = true; + }), + }; + created.push(element); + return element; + }), + body: { + appendChild: vi.fn((element: unknown) => { + appended.push(element); + return element; + }), + }, + }; + return { document, created, appended }; + }; + + return { + documents: { + active: createDocument(), + explicit: createDocument(), + }, + mounts: [] as { + component: unknown; + target: unknown; + props: Record; + handle: { id: number }; + }[], + unmounts: [] as unknown[], + }; +}); + +vi.mock("@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions", () => ({ + _activeDocument: browserMenuHarness.documents.active.document, +})); +vi.mock("svelte", () => ({ + mount: vi.fn((component: unknown, options: { target: unknown; props: Record }) => { + const handle = { id: browserMenuHarness.mounts.length }; + browserMenuHarness.mounts.push({ component, target: options.target, props: options.props, handle }); + return handle; + }), + unmount: vi.fn((handle: unknown) => { + browserMenuHarness.unmounts.push(handle); + return Promise.resolve(); + }), +})); + +import { Menu, MenuItem, MenuSeparator } from "@/apps/browser/BrowserMenu"; + +type BrowserMenuOptionsFixture = { document?: Document; signal?: AbortSignal }; + +function menuWithOptions(options: BrowserMenuOptionsFixture): Menu { + const MenuWithOptions = Menu as unknown as new (options: BrowserMenuOptionsFixture) => Menu; + return new MenuWithOptions(options); +} + +function explicitDocument(): Document { + return browserMenuHarness.documents.explicit.document as unknown as Document; +} + +function closeMenu(index: number): () => void { + const close = browserMenuHarness.mounts[index]!.props.closeMenu; + if (typeof close !== "function") throw new Error("Menu mount did not receive a close callback"); + return close as () => void; +} + +async function settlesAfterMicrotask(promise: Promise): Promise { + let settled = false; + void promise.then(() => { + settled = true; + }); + await Promise.resolve(); + return settled; +} + +beforeEach(() => { + browserMenuHarness.documents.active.created.length = 0; + browserMenuHarness.documents.active.appended.length = 0; + browserMenuHarness.documents.explicit.created.length = 0; + browserMenuHarness.documents.explicit.appended.length = 0; + browserMenuHarness.mounts.length = 0; + browserMenuHarness.unmounts.length = 0; + vi.clearAllMocks(); +}); + +afterEach(() => { + for (const mount of browserMenuHarness.mounts) { + const close = mount.props.closeMenu; + if (typeof close === "function") (close as () => void)(); + } +}); + +describe("browser Menu lifecycle", () => { + it("preserves item, separator, chained construction, and positioned display APIs", async () => { + const menu = new Menu(); + const handler = vi.fn(async () => {}); + + expect( + menu.addItem((item) => { + item.setTitle("Open").setIcon("folder").onClick(handler); + }) + ).toBe(menu); + expect(menu.addSeparator()).toBe(menu); + expect(menu.items[0]).toBeInstanceOf(MenuItem); + expect(menu.items[0]).toMatchObject({ type: "item", title: "Open", icon: "folder", handler }); + expect(menu.items[1]).toBeInstanceOf(MenuSeparator); + + const displayed = menu.showAtPosition({ x: 12, y: 34 }); + expect(browserMenuHarness.documents.active.document.createElement).toHaveBeenCalledWith("div"); + expect(browserMenuHarness.documents.active.appended).toEqual([browserMenuHarness.mounts[0]!.target]); + expect(browserMenuHarness.mounts[0]!.props).toMatchObject({ items: menu.items, x: 12, y: 34 }); + expect(browserMenuHarness.mounts[0]!.target).toBe(browserMenuHarness.documents.active.created[0]); + closeMenu(0)(); + await expect(displayed).resolves.toBeUndefined(); + }); + + it("keeps the returned close promise pending until a menu close action", async () => { + const menu = new Menu(); + const displayed = menu.showAtPosition({ x: 1, y: 2 }); + + expect(await settlesAfterMicrotask(displayed)).toBe(false); + closeMenu(0)(); + await expect(displayed).resolves.toBeUndefined(); + }); + + it("resolves the active display promise when hidden without a menu action", async () => { + const menu = new Menu(); + const displayed = menu.showAtPosition({ x: 1, y: 2 }); + + menu.hide(); + + await expect(displayed).resolves.toBeUndefined(); + }); + + it("closes a replaced display while keeping the replacement active", async () => { + const menu = new Menu(); + const first = menu.showAtPosition({ x: 1, y: 2 }); + const staleClose = closeMenu(0); + const firstElement = browserMenuHarness.mounts[0]!.target as { removed: boolean }; + const second = menu.showAtPosition({ x: 3, y: 4 }); + const secondElement = browserMenuHarness.mounts[1]!.target as { removed: boolean }; + + await expect(first).resolves.toBeUndefined(); + expect(firstElement.removed).toBe(true); + expect(secondElement.removed).toBe(false); + expect(menu.waitingForClose?.promise).toBe(second); + expect(await settlesAfterMicrotask(second)).toBe(false); + + try { + staleClose(); + expect(menu.waitingForClose?.promise).toBe(second); + expect(secondElement.removed).toBe(false); + expect(await settlesAfterMicrotask(second)).toBe(false); + } finally { + closeMenu(1)(); + } + await expect(second).resolves.toBeUndefined(); + }); + + it("mounts a menu in its explicitly supplied document", async () => { + const menu = menuWithOptions({ document: explicitDocument() }); + + const displayed = menu.showAtPosition({ x: 5, y: 6 }); + + expect(browserMenuHarness.documents.explicit.document.createElement).toHaveBeenCalledWith("div"); + expect(browserMenuHarness.documents.explicit.appended).toEqual([browserMenuHarness.mounts[0]!.target]); + expect(browserMenuHarness.mounts[0]!.target).toBe(browserMenuHarness.documents.explicit.created[0]); + expect(browserMenuHarness.documents.active.document.createElement).not.toHaveBeenCalled(); + closeMenu(0)(); + await expect(displayed).resolves.toBeUndefined(); + }); + + it("aborting one menu closes only that menu", async () => { + const firstOwner = new AbortController(); + const secondOwner = new AbortController(); + const firstMenu = menuWithOptions({ document: explicitDocument(), signal: firstOwner.signal }); + const secondMenu = menuWithOptions({ document: explicitDocument(), signal: secondOwner.signal }); + const first = firstMenu.showAtPosition({ x: 1, y: 2 }); + const second = secondMenu.showAtPosition({ x: 3, y: 4 }); + let firstSettled = false; + void first.then(() => { + firstSettled = true; + }); + firstOwner.abort(); + + await Promise.resolve(); + expect(firstSettled).toBe(true); + expect(secondMenu.waitingForClose?.promise).toBe(second); + expect(await settlesAfterMicrotask(second)).toBe(false); + closeMenu(1)(); + await expect(second).resolves.toBeUndefined(); + }); + + it("does not mount for an already aborted owner", async () => { + const owner = new AbortController(); + owner.abort(); + const menu = menuWithOptions({ document: explicitDocument(), signal: owner.signal }); + + const displayed = menu.showAtPosition({ x: 1, y: 2 }); + + expect(browserMenuHarness.mounts).toHaveLength(0); + expect(await settlesAfterMicrotask(displayed)).toBe(true); + }); + + it("does not mount again after its owner aborts", async () => { + const owner = new AbortController(); + const menu = menuWithOptions({ document: explicitDocument(), signal: owner.signal }); + const first = menu.showAtPosition({ x: 1, y: 2 }); + owner.abort(); + + expect(await settlesAfterMicrotask(first)).toBe(true); + const reopened = menu.showAtPosition({ x: 3, y: 4 }); + expect(await settlesAfterMicrotask(reopened)).toBe(true); + expect(browserMenuHarness.mounts).toHaveLength(1); + }); + + it.each(["hide", "dismissal", "replacement", "abort"] as const)( + "unmounts each Svelte component exactly once for %s", + async (reason) => { + const owner = new AbortController(); + const menu = menuWithOptions({ document: explicitDocument(), signal: owner.signal }); + const first = menu.showAtPosition({ x: 1, y: 2 }); + let second: Promise | undefined; + + if (reason === "hide") { + menu.hide(); + } else if (reason === "dismissal") { + closeMenu(0)(); + } else if (reason === "replacement") { + second = menu.showAtPosition({ x: 3, y: 4 }); + closeMenu(1)(); + } else { + owner.abort(); + } + + expect(await settlesAfterMicrotask(first)).toBe(true); + if (second) expect(await settlesAfterMicrotask(second)).toBe(true); + for (const mount of browserMenuHarness.mounts) { + expect(browserMenuHarness.unmounts.filter((handle) => handle === mount.handle)).toHaveLength(1); + } + } + ); + + it("removes the menu element before resolving the close promise", async () => { + const menu = new Menu(); + const displayed = menu.showAtPosition({ x: 1, y: 2 }); + const element = browserMenuHarness.mounts[0]!.target as { removed: boolean }; + let removedWhenResolved = false; + void displayed.then(() => { + removedWhenResolved = element.removed; + }); + + menu.hide(); + + await displayed; + expect(removedWhenResolved).toBe(true); + }); + + it("removes its abort listener when closed so a later abort does not unmount it again", async () => { + const owner = new AbortController(); + const addListener = vi.spyOn(owner.signal, "addEventListener"); + const removeListener = vi.spyOn(owner.signal, "removeEventListener"); + const menu = menuWithOptions({ document: explicitDocument(), signal: owner.signal }); + const displayed = menu.showAtPosition({ x: 1, y: 2 }); + const handle = browserMenuHarness.mounts[0]!.handle; + + menu.hide(); + await expect(displayed).resolves.toBeUndefined(); + owner.abort(); + + expect(addListener.mock.calls.map(([type]) => type)).toContain("abort"); + expect(removeListener.mock.calls.map(([type]) => type)).toContain("abort"); + expect(browserMenuHarness.unmounts.filter((unmounted) => unmounted === handle)).toHaveLength(1); + }); +}); diff --git a/test/apps/browser/BrowserSvelteDialogManager.unit.spec.ts b/test/apps/browser/BrowserSvelteDialogManager.unit.spec.ts new file mode 100644 index 00000000..71e8ebad --- /dev/null +++ b/test/apps/browser/BrowserSvelteDialogManager.unit.spec.ts @@ -0,0 +1,199 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import { EVENT_PLUGIN_UNLOADED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; +import type { + ComponentHasResult, + DialogHostProps, + SvelteDialogManagerDependencies, +} from "@vrtmrz/livesync-commonlib/compat/services/implements/base/SvelteDialog"; + +const rendering = vi.hoisted(() => ({ + mount: vi.fn(), + unmount: vi.fn(async (_component: unknown) => {}), + legacy: { document: undefined as Document | undefined }, +})); +vi.mock("svelte", async (importOriginal) => ({ + ...(await importOriginal()), + mount: rendering.mount, + unmount: rendering.unmount, +})); +vi.mock("@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions", () => ({ + get _activeDocument() { + return rendering.legacy.document; + }, +})); +vi.mock("@/modules/services/LiveSyncUI/DialogHost.svelte", () => ({ default: () => {} })); + +import { + BrowserModal, + BrowserSvelteDialogManager, + LiveSyncBrowserDialog, +} from "@/apps/browser/BrowserSvelteDialogManager"; +import { createBrowserUiScope } from "@/apps/browser/BrowserUiScope"; + +class TestElement { + children: TestElement[] = []; + parentElement: TestElement | null = null; + hidden = false; + className = ""; + textContent = ""; + constructor( + readonly ownerDocument: TestDocument, + readonly tagName: string + ) {} + appendChild(child: TestElement) { + child.remove(); + child.parentElement = this; + this.children.push(child); + return child; + } + remove() { + if (this.parentElement) + this.parentElement.children = this.parentElement.children.filter((child) => child !== this); + this.parentElement = null; + } + replaceChildren() { + for (const child of [...this.children]) child.remove(); + } +} +class TestDocument { + body = new TestElement(this, "body"); + createElement(tag: string) { + return new TestElement(this, tag); + } +} +const asDocument = (document: TestDocument) => document as unknown as Document; +const component = (() => {}) as unknown as ComponentHasResult; +type Context = ReturnType; +type UiOptions = { document?: Document; signal?: AbortSignal }; +function createManager(options?: UiOptions) { + const context = createServiceContext(); + return { + context, + manager: new BrowserSvelteDialogManager( + context, + {} as SvelteDialogManagerDependencies, + options ? createBrowserUiScope(context, options) : undefined + ), + }; +} +function lastMount() { + const call = rendering.mount.mock.calls[rendering.mount.mock.calls.length - 1]; + return { target: call[1].target as TestElement, props: call[1].props as DialogHostProps }; +} + +beforeEach(() => { + vi.clearAllMocks(); + rendering.legacy.document = asDocument(new TestDocument()); + rendering.mount.mockImplementation(() => ({})); +}); +afterEach(() => { + rendering.legacy.document = undefined; +}); + +describe("Browser Svelte dialogue ownership", () => { + it("releases every per-dialogue context subscription on legacy direct close", async () => { + const subscriptions: ReturnType[] = []; + const context = { + events: { + onceEvent: vi.fn(() => { + const unregister = vi.fn(); + subscriptions.push(unregister); + return unregister; + }), + }, + } as unknown as Context; + const dialog = new LiveSyncBrowserDialog(context, {} as SvelteDialogManagerDependencies, component); + dialog.open(); + const result = dialog.waitForClose(); + dialog.close(); + await expect(result).resolves.toBeUndefined(); + expect(subscriptions.length).toBeGreaterThan(0); + for (const unsubscribe of subscriptions) expect(unsubscribe).toHaveBeenCalledOnce(); + }); + + it("preserves the legacy document, normal result, and component cleanup", async () => { + const { manager } = createManager(); + const result = manager.openSvelteDialog(component, "initial"); + const { target, props } = lastMount(); + expect(target.ownerDocument).toBe(rendering.legacy.document); + expect(props.getInitialData?.()).toBe("initial"); + props.setResult("selected"); + props.closeDialog(); + await expect(result).resolves.toBe("selected"); + expect((rendering.legacy.document as unknown as TestDocument).body.children).toHaveLength(0); + expect(rendering.unmount).toHaveBeenCalledOnce(); + }); + it("preserves rejection when the owning context unloads", async () => { + const { context, manager } = createManager(); + const result = manager.openSvelteDialog(component); + const rejected = expect(result).rejects.toThrow("Plug-in unloaded"); + context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + await rejected; + expect(rendering.unmount).toHaveBeenCalledOnce(); + expect((rendering.legacy.document as unknown as TestDocument).body.children).toHaveLength(0); + }); + it("uses its supplied document even when the legacy document changes before opening", async () => { + const targetDocument = new TestDocument(); + const { manager } = createManager({ document: asDocument(targetDocument) }); + rendering.legacy.document = asDocument(new TestDocument()); + const result = manager.openSvelteDialog(component); + const { target, props } = lastMount(); + expect(target.ownerDocument).toBe(targetDocument); + expect(targetDocument.body.children).toHaveLength(1); + expect((rendering.legacy.document as unknown as TestDocument).body.children).toHaveLength(0); + props.closeDialog(); + await expect(result).resolves.toBeUndefined(); + }); + it("aborts one owner without closing another owner's dialogue", async () => { + const firstOwner = new AbortController(); + const firstDocument = new TestDocument(); + const secondDocument = new TestDocument(); + const first = createManager({ document: asDocument(firstDocument), signal: firstOwner.signal }); + const second = createManager({ document: asDocument(secondDocument) }); + const firstResult = first.manager.openSvelteDialog(component); + let observedFirst: unknown = "still pending"; + void firstResult.then( + () => { + observedFirst = "resolved"; + }, + (error) => { + observedFirst = error; + } + ); + const secondResult = second.manager.openSvelteDialog(component); + const secondProps = lastMount().props; + const reason = new Error("fixture owner ended"); + firstOwner.abort(reason); + await vi.waitFor(() => expect(observedFirst).toBe(reason), { timeout: 1000, interval: 20 }); + expect(firstDocument.body.children).toHaveLength(0); + expect(secondDocument.body.children).toHaveLength(1); + secondProps.setResult("second"); + secondProps.closeDialog(); + await expect(secondResult).resolves.toBe("second"); + }); + it("does not render for an already aborted owner or reopen after unload", async () => { + const owner = new AbortController(); + const reason = new Error("fixture owner ended"); + owner.abort(reason); + const aborted = createManager({ signal: owner.signal }); + const rejected = aborted.manager.openSvelteDialog(component).catch((error) => error); + expect(rendering.mount).not.toHaveBeenCalled(); + await expect(rejected).resolves.toBe(reason); + const unloaded = createManager(); + unloaded.context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + const afterUnload = unloaded.manager.openSvelteDialog(component).catch((error) => error); + expect(rendering.mount).not.toHaveBeenCalled(); + await expect(afterUnload).resolves.toBeInstanceOf(Error); + }); + it("keeps a native modal in the document which created its elements", () => { + const document = new TestDocument(); + const modal = new BrowserModal(asDocument(document)); + rendering.legacy.document = asDocument(new TestDocument()); + modal.open(); + expect(document.body.children).toEqual([modal.baseEl]); + expect((modal.contentEl as unknown as TestElement).ownerDocument).toBe(document); + modal.close(); + expect(document.body.children).toHaveLength(0); + }); +}); diff --git a/test/apps/browser/BrowserUiScope.unit.spec.ts b/test/apps/browser/BrowserUiScope.unit.spec.ts new file mode 100644 index 00000000..abf32433 --- /dev/null +++ b/test/apps/browser/BrowserUiScope.unit.spec.ts @@ -0,0 +1,56 @@ +import { createServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import { EVENT_PLUGIN_UNLOADED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; +import { describe, expect, it, vi } from "vitest"; +import { createBrowserUiScope } from "@/apps/browser/BrowserUiScope"; + +describe("browser UI scope", () => { + it("owns its document and cancellation independently from another application", () => { + const firstContext = createServiceContext(); + const secondContext = createServiceContext(); + const firstDocument = {} as Document; + const secondDocument = {} as Document; + const first = createBrowserUiScope(firstContext, { document: firstDocument }); + const second = createBrowserUiScope(secondContext, { document: secondDocument }); + const abort = vi.fn(); + first.signal.addEventListener("abort", abort); + firstContext.events.emitEvent(EVENT_PLUGIN_UNLOADED); + firstContext.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(first.document).toBe(firstDocument); + expect(second.document).toBe(secondDocument); + expect(first.signal.aborted).toBe(true); + expect(first.signal.reason).toEqual(new Error("Plug-in unloaded")); + expect(second.signal.aborted).toBe(false); + expect(abort).toHaveBeenCalledOnce(); + secondContext.events.emitEvent(EVENT_PLUGIN_UNLOADED); + }); + it("forwards parent cancellation and unregisters the context subscription", () => { + const context = createServiceContext(); + const parent = new AbortController(); + const unregister = vi.fn(); + const once = vi.spyOn(context.events, "onceEvent").mockReturnValue(unregister); + const scope = createBrowserUiScope(context, { signal: parent.signal }); + const reason = new Error("fixture host ended"); + parent.abort(reason); + expect(scope.signal.aborted).toBe(true); + expect(scope.signal.reason).toBe(reason); + expect(unregister).toHaveBeenCalledOnce(); + once.mockRestore(); + }); + it("removes the parent listener on unload and does not subscribe an already aborted parent", () => { + const context = createServiceContext(); + const parent = new AbortController(); + const remove = vi.spyOn(parent.signal, "removeEventListener"); + const scope = createBrowserUiScope(context, { signal: parent.signal }); + context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(remove).toHaveBeenCalledWith("abort", expect.any(Function)); + const reason = scope.signal.reason; + parent.abort(new Error("later")); + expect(scope.signal.reason).toBe(reason); + const closedContext = createServiceContext(); + const subscribe = vi.spyOn(closedContext.events, "onceEvent"); + const closed = createBrowserUiScope(closedContext, { signal: parent.signal }); + expect(closed.signal.aborted).toBe(true); + expect(closed.signal.reason).toBe(parent.signal.reason); + expect(subscribe).not.toHaveBeenCalled(); + }); +}); diff --git a/test/apps/browser/SvelteDialogSession.unit.spec.ts b/test/apps/browser/SvelteDialogSession.unit.spec.ts index f87fe25f..08b46313 100644 --- a/test/apps/browser/SvelteDialogSession.unit.spec.ts +++ b/test/apps/browser/SvelteDialogSession.unit.spec.ts @@ -86,3 +86,64 @@ describe("SvelteDialogSession", () => { expect(close).toHaveBeenCalledOnce(); }); }); + +describe("SvelteDialogSession owner signal", () => { + it("rejects and releases the mounted dialogue when its owner aborts", async () => { + const context = createServiceContext(); + const controller = new AbortController(); + const lifecycle = { signal: controller.signal }; + const unmount = vi.fn().mockResolvedValue(undefined); + let session: SvelteDialogSession; + const close = vi.fn(() => session.onClose()); + session = new SvelteDialogSession({ + ...lifecycle, + surface: { + contentEl: { replaceChildren: vi.fn() } as unknown as HTMLElement, + close, + setTitle: vi.fn(), + }, + context, + dependencies: {} as SvelteDialogManagerDependencies, + dialogHost: (() => {}) as unknown as Component, + component: (() => {}) as unknown as ComponentHasResult, + renderer: { mount: () => ({}) as never, unmount }, + }); + session.onOpen(); + let observed: unknown = "pending"; + void session.waitForClose().catch((error) => { + observed = error; + }); + const reason = new Error("fixture owner ended"); + controller.abort(reason); + await vi.waitFor(() => expect(observed).toBe(reason), { timeout: 1000, interval: 20 }); + expect(close).toHaveBeenCalledOnce(); + expect(unmount).toHaveBeenCalledOnce(); + context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(close).toHaveBeenCalledOnce(); + }); + + it("detaches an owner signal when normal close has already settled the result", async () => { + const context = createServiceContext(); + const controller = new AbortController(); + const remove = vi.spyOn(controller.signal, "removeEventListener"); + const lifecycle = { signal: controller.signal }; + const close = vi.fn(); + const session = new SvelteDialogSession({ + ...lifecycle, + surface: { contentEl: { replaceChildren: vi.fn() } as unknown as HTMLElement, close, setTitle: vi.fn() }, + context, + dependencies: {} as SvelteDialogManagerDependencies, + dialogHost: (() => {}) as unknown as Component, + component: (() => {}) as unknown as ComponentHasResult, + renderer: { mount: () => ({}) as never, unmount: vi.fn().mockResolvedValue(undefined) }, + }); + session.onOpen(); + const result = session.waitForClose(); + session.onClose(); + await expect(result).resolves.toBeUndefined(); + expect(remove).toHaveBeenCalledWith("abort", expect.any(Function)); + controller.abort(); + context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + expect(close).not.toHaveBeenCalled(); + }); +}); diff --git a/test/browser-apps/ui-lifecycle/browser-ui-lifecycle.test.ts b/test/browser-apps/ui-lifecycle/browser-ui-lifecycle.test.ts new file mode 100644 index 00000000..1376500d --- /dev/null +++ b/test/browser-apps/ui-lifecycle/browser-ui-lifecycle.test.ts @@ -0,0 +1,202 @@ +import { assertEquals } from "@std/assert"; +import { resolve } from "@std/path"; +import { chromium } from "playwright"; + +import { observePageFailures, startStaticServer, waitFor } from "../helpers/browser.ts"; + +type OwnerName = "owner-a" | "owner-b" | "owner-c" | "owner-d"; +type DialogOutcome = + | { readonly kind: "resolved"; readonly value: unknown } + | { readonly kind: "rejected"; readonly message: string }; + +interface BrowserUiLifecycleFixture { + readonly ready: boolean; + startDialog(name: OwnerName, initialData?: string): void; + startMenu(name: OwnerName, title: string): void; + clickSavedBackdrop(name: OwnerName): void; + hideMenu(name: OwnerName): void; + unload(name: OwnerName): void; + abortParent(name: OwnerName): void; + state(name: OwnerName): { + readonly dialogs: readonly DialogOutcome[]; + readonly menus: readonly string[]; + readonly hasSavedBackdrop: boolean; + }; +} + +declare global { + interface Window { + browserUiLifecycle?: BrowserUiLifecycleFixture; + } +} + +const fixtureDist = resolve(import.meta.dirname!, "../../../_testdata/browser-ui-lifecycle"); + +Deno.test({ + name: "Browser UI: dialogue and menu lifecycles remain owned by their document and plug-in scope", + sanitizeOps: false, + sanitizeResources: false, + async fn() { + const server = await startStaticServer(fixtureDist); + const browser = await chromium.launch({ headless: true }); + try { + const page = await browser.newPage(); + const assertNoPageFailures = observePageFailures(page); + await page.goto(server.baseUrl); + await page.waitForFunction(() => window.browserUiLifecycle?.ready === true); + + const startDialog = async (name: OwnerName, initialData?: string) => + await page.evaluate( + ({ name, initialData }) => window.browserUiLifecycle!.startDialog(name, initialData), + { name, initialData } + ); + const startMenu = async (name: OwnerName, title: string) => + await page.evaluate(({ name, title }) => window.browserUiLifecycle!.startMenu(name, title), { + name, + title, + }); + const state = async (name: OwnerName) => + await page.evaluate((ownerName) => window.browserUiLifecycle!.state(ownerName), name); + + const ownerA = page.frameLocator("#owner-a"); + const ownerB = page.frameLocator("#owner-b"); + const ownerC = page.frameLocator("#owner-c"); + const ownerD = page.frameLocator("#owner-d"); + + await startDialog("owner-a", "A-seed"); + await startDialog("owner-b", "B-seed"); + const initial = await page.evaluate(() => ({ + first: window.browserUiLifecycle!.state("owner-a").dialogs, + second: window.browserUiLifecycle!.state("owner-b").dialogs, + })); + assertEquals(initial, { first: [], second: [] }); + assertNoPageFailures(); + await ownerA.getByTestId("lifecycle-dialog").waitFor(); + await ownerB.getByTestId("lifecycle-dialog").waitFor(); + assertEquals(await page.locator(".dialog-host").count(), 0); + assertEquals(await ownerA.locator(".dialog-host").count(), 1); + assertEquals(await ownerB.locator(".dialog-host").count(), 1); + + await ownerA.getByTestId("submit-dialog").click(); + await waitFor(async () => (await state("owner-a")).dialogs.length === 1, "Owner A dialogue did not finish"); + assertEquals((await state("owner-a")).dialogs, [{ kind: "resolved", value: "result:A-seed" }]); + assertEquals(await ownerA.locator(".dialog-host").count(), 0); + assertEquals(await ownerB.locator(".dialog-host").count(), 1); + + await ownerB.getByTestId("close-dialog").click(); + await waitFor(async () => (await state("owner-b")).dialogs.length === 1, "Owner B dialogue did not finish"); + assertEquals((await state("owner-b")).dialogs, [{ kind: "resolved", value: "undefined" }]); + + await startMenu("owner-a", "first menu"); + await ownerA.getByText("first menu", { exact: true }).waitFor(); + assertEquals(await page.locator(".background").count(), 0); + assertEquals(await ownerA.locator(".background").count(), 1); + assertEquals(await ownerB.locator(".background").count(), 0); + + await startMenu("owner-a", "replacement menu"); + await ownerA.getByText("replacement menu", { exact: true }).waitFor(); + await waitFor( + async () => (await state("owner-a")).menus.length === 1, + "Replacing the menu did not close its first promise" + ); + assertEquals((await state("owner-a")).menus, ["resolved"]); + assertEquals((await state("owner-a")).hasSavedBackdrop, true); + + await page.evaluate(() => window.browserUiLifecycle!.clickSavedBackdrop("owner-a")); + assertEquals(await ownerA.locator(".background").count(), 1); + assertEquals((await state("owner-a")).menus, ["resolved"]); + await page.evaluate(() => window.browserUiLifecycle!.hideMenu("owner-a")); + await waitFor( + async () => (await state("owner-a")).menus.length === 2, + "Hiding the replacement menu did not finish" + ); + assertEquals((await state("owner-a")).menus, ["resolved", "resolved"]); + assertEquals(await ownerA.locator(".background").count(), 0); + + await startDialog("owner-a", "unload-A"); + await startMenu("owner-a", "A unload menu"); + await startDialog("owner-b", "still-B"); + await startMenu("owner-b", "B remains open"); + await ownerA.getByTestId("lifecycle-dialog").waitFor(); + await ownerA.getByText("A unload menu", { exact: true }).waitFor(); + await ownerB.getByTestId("lifecycle-dialog").waitFor(); + await ownerB.getByText("B remains open", { exact: true }).waitFor(); + + await page.evaluate(() => window.browserUiLifecycle!.unload("owner-a")); + await waitFor( + async () => + (await state("owner-a")).dialogs.length === 2 && (await state("owner-a")).menus.length === 3, + "Owner A unload did not settle its UI operations" + ); + assertEquals((await state("owner-a")).dialogs[1], { kind: "rejected", message: "Plug-in unloaded" }); + assertEquals(await ownerA.locator(".dialog-host").count(), 0); + assertEquals(await ownerA.locator(".background").count(), 0); + assertEquals(await ownerB.locator(".dialog-host").count(), 1); + assertEquals(await ownerB.locator(".background").count(), 1); + + await startDialog("owner-a", "after-unload"); + await startMenu("owner-a", "after unload menu"); + await waitFor( + async () => + (await state("owner-a")).dialogs.length === 3 && (await state("owner-a")).menus.length === 4, + "Post-unload UI operations did not settle" + ); + assertEquals((await state("owner-a")).dialogs[2], { kind: "rejected", message: "Plug-in unloaded" }); + assertEquals((await state("owner-a")).menus[3], "resolved"); + assertEquals(await ownerA.locator(".dialog-host").count(), 0); + assertEquals(await ownerA.locator(".background").count(), 0); + + await startDialog("owner-c", "parent-abort"); + await startMenu("owner-c", "parent abort menu"); + await ownerC.getByTestId("lifecycle-dialog").waitFor(); + await ownerC.getByText("parent abort menu", { exact: true }).waitFor(); + await page.evaluate(() => window.browserUiLifecycle!.abortParent("owner-c")); + await waitFor( + async () => + (await state("owner-c")).dialogs.length === 1 && (await state("owner-c")).menus.length === 1, + "Parent abort did not settle its UI operations" + ); + assertEquals((await state("owner-c")).dialogs[0], { kind: "rejected", message: "Fixture UI owner ended" }); + assertEquals((await state("owner-c")).menus[0], "resolved"); + assertEquals(await ownerC.locator(".dialog-host").count(), 0); + assertEquals(await ownerC.locator(".background").count(), 0); + assertEquals(await ownerB.locator(".dialog-host").count(), 1); + assertEquals(await ownerB.locator(".background").count(), 1); + + await startDialog("owner-c", "after-parent-abort"); + await startMenu("owner-c", "after parent abort menu"); + await waitFor( + async () => + (await state("owner-c")).dialogs.length === 2 && (await state("owner-c")).menus.length === 2, + "Post-abort UI operations did not settle" + ); + assertEquals((await state("owner-c")).dialogs[1], { kind: "rejected", message: "Fixture UI owner ended" }); + assertEquals((await state("owner-c")).menus[1], "resolved"); + assertEquals(await ownerC.locator(".dialog-host").count(), 0); + assertEquals(await ownerC.locator(".background").count(), 0); + + await startDialog("owner-d", "pre-aborted"); + await startMenu("owner-d", "pre-aborted menu"); + await waitFor( + async () => + (await state("owner-d")).dialogs.length === 1 && (await state("owner-d")).menus.length === 1, + "Pre-aborted UI operations did not settle" + ); + assertEquals((await state("owner-d")).dialogs[0], { kind: "rejected", message: "Fixture UI owner ended" }); + assertEquals((await state("owner-d")).menus[0], "resolved"); + assertEquals(await ownerD.locator(".dialog-host").count(), 0); + assertEquals(await ownerD.locator(".background").count(), 0); + + await page.evaluate(() => window.browserUiLifecycle!.hideMenu("owner-b")); + await waitFor(async () => (await state("owner-b")).menus.length === 1, "Owner B menu did not close"); + await ownerB.getByTestId("close-dialog").click(); + await waitFor(async () => (await state("owner-b")).dialogs.length === 2, "Owner B dialogue did not close"); + assertEquals(await ownerB.locator(".background").count(), 0); + assertEquals(await ownerB.locator(".dialog-host").count(), 0); + assertNoPageFailures(); + } finally { + await browser.close(); + await server.close(); + } + }, +}); diff --git a/test/browser-apps/ui-lifecycle/index.html b/test/browser-apps/ui-lifecycle/index.html new file mode 100644 index 00000000..bbee4dc7 --- /dev/null +++ b/test/browser-apps/ui-lifecycle/index.html @@ -0,0 +1,15 @@ + + + + + + Browser UI lifecycle fixture + + + + + + + + + diff --git a/test/browser-apps/ui-lifecycle/src/TestLifecycleDialog.svelte b/test/browser-apps/ui-lifecycle/src/TestLifecycleDialog.svelte new file mode 100644 index 00000000..22858aaf --- /dev/null +++ b/test/browser-apps/ui-lifecycle/src/TestLifecycleDialog.svelte @@ -0,0 +1,16 @@ + + +
+ + +
diff --git a/test/browser-apps/ui-lifecycle/src/main.ts b/test/browser-apps/ui-lifecycle/src/main.ts new file mode 100644 index 00000000..1f8c3d49 --- /dev/null +++ b/test/browser-apps/ui-lifecycle/src/main.ts @@ -0,0 +1,154 @@ +import { createServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import { EVENT_PLUGIN_UNLOADED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; +import { MemoryValueStore } from "@vrtmrz/value-store"; + +import { Menu } from "@/apps/browser/BrowserMenu"; +import { createLiveSyncBrowserServiceHub } from "@/apps/browser/createLiveSyncBrowserServiceHub"; +import TestLifecycleDialog from "./TestLifecycleDialog.svelte"; + +type OwnerName = "owner-a" | "owner-b" | "owner-c" | "owner-d"; +type DialogOutcome = + | { readonly kind: "resolved"; readonly value: unknown } + | { readonly kind: "rejected"; readonly message: string }; + +interface Owner { + readonly context: ReturnType; + readonly document: Document; + readonly hub: ReturnType; + readonly menu: Menu; + readonly parentAbort?: AbortController; + readonly dialogOutcomes: DialogOutcome[]; + readonly menuOutcomes: string[]; + savedBackdrop?: HTMLElement; +} + +interface BrowserUiLifecycleFixture { + readonly ready: boolean; + startDialog(name: OwnerName, initialData?: string): void; + startMenu(name: OwnerName, title: string): void; + clickSavedBackdrop(name: OwnerName): void; + hideMenu(name: OwnerName): void; + unload(name: OwnerName): void; + abortParent(name: OwnerName): void; + state(name: OwnerName): { + readonly dialogs: readonly DialogOutcome[]; + readonly menus: readonly string[]; + readonly hasSavedBackdrop: boolean; + }; +} + +declare global { + interface Window { + browserUiLifecycle?: BrowserUiLifecycleFixture; + } +} + +const owners = new Map(); + +function ownerDocument(name: OwnerName): Document { + const frame = document.getElementById(name); + if (!(frame instanceof HTMLIFrameElement) || !frame.contentDocument) { + throw new Error(`The ${name} frame is not ready`); + } + return frame.contentDocument; +} + +function createOwner(name: OwnerName, options: { parentAbort?: AbortController; preAborted?: boolean } = {}): Owner { + const frameDocument = ownerDocument(name); + const parentAbort = options.parentAbort; + if (options.preAborted) { + parentAbort?.abort(new Error("Fixture UI owner ended")); + } + const context = createServiceContext(); + const hub = createLiveSyncBrowserServiceHub({ + context, + deviceValues: new MemoryValueStore(), + ui: { + document: frameDocument, + ...(parentAbort ? { signal: parentAbort.signal } : {}), + }, + }); + return { + context, + document: frameDocument, + hub, + menu: new Menu({ document: frameDocument, signal: hub.browserUi.signal }), + ...(parentAbort ? { parentAbort } : {}), + dialogOutcomes: [], + menuOutcomes: [], + }; +} + +const ownerCAbort = new AbortController(); +const ownerDAbort = new AbortController(); +ownerDAbort.abort(new Error("Fixture UI owner ended")); + +owners.set("owner-a", createOwner("owner-a")); +owners.set("owner-b", createOwner("owner-b")); +owners.set("owner-c", createOwner("owner-c", { parentAbort: ownerCAbort })); +owners.set("owner-d", createOwner("owner-d", { parentAbort: ownerDAbort, preAborted: true })); + +const fixture: BrowserUiLifecycleFixture = { + ready: true, + startDialog(name, initialData) { + const owner = owners.get(name)!; + try { + void owner.hub.UI.dialogManager.open(TestLifecycleDialog, initialData).then( + (value) => + owner.dialogOutcomes.push({ kind: "resolved", value: value === undefined ? "undefined" : value }), + (error: unknown) => + owner.dialogOutcomes.push({ + kind: "rejected", + message: error instanceof Error ? error.message : String(error), + }) + ); + } catch (error) { + owner.dialogOutcomes.push({ + kind: "rejected", + message: error instanceof Error ? error.message : String(error), + }); + } + }, + startMenu(name, title) { + const owner = owners.get(name)!; + owner.savedBackdrop = owner.document.querySelector(".background") ?? undefined; + try { + void owner.menu + .addItem((item) => item.setTitle(title)) + .showAtPosition({ x: 12, y: 12 }) + .then( + () => owner.menuOutcomes.push("resolved"), + (error: unknown) => + owner.menuOutcomes.push(`rejected:${error instanceof Error ? error.message : String(error)}`) + ); + } catch (error) { + owner.menuOutcomes.push(`rejected:${error instanceof Error ? error.message : String(error)}`); + } + }, + clickSavedBackdrop(name) { + const owner = owners.get(name)!; + const window = owner.document.defaultView; + if (owner.savedBackdrop && window) { + owner.savedBackdrop.dispatchEvent(new window.MouseEvent("click", { bubbles: true })); + } + }, + hideMenu(name) { + owners.get(name)!.menu.hide(); + }, + unload(name) { + owners.get(name)!.context.events.emitEvent(EVENT_PLUGIN_UNLOADED); + }, + abortParent(name) { + owners.get(name)!.parentAbort?.abort(new Error("Fixture UI owner ended")); + }, + state(name) { + const owner = owners.get(name)!; + return { + dialogs: [...owner.dialogOutcomes], + menus: [...owner.menuOutcomes], + hasSavedBackdrop: owner.savedBackdrop !== undefined, + }; + }, +}; + +window.browserUiLifecycle = fixture; diff --git a/test/browser-apps/ui-lifecycle/tsconfig.json b/test/browser-apps/ui-lifecycle/tsconfig.json new file mode 100644 index 00000000..e83a2d8e --- /dev/null +++ b/test/browser-apps/ui-lifecycle/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"] + }, + "include": ["src/**/*.ts", "src/**/*.svelte"], + "exclude": [] +} diff --git a/test/browser-apps/ui-lifecycle/vite.config.ts b/test/browser-apps/ui-lifecycle/vite.config.ts new file mode 100644 index 00000000..5c10c5b4 --- /dev/null +++ b/test/browser-apps/ui-lifecycle/vite.config.ts @@ -0,0 +1,25 @@ +import { fileURLToPath } from "node:url"; +import { dirname, resolve } from "node:path"; +import { svelte } from "@sveltejs/vite-plugin-svelte"; +import { defineConfig } from "vite"; + +const fixtureDirectory = dirname(fileURLToPath(import.meta.url)); +const repositoryRoot = resolve(fixtureDirectory, "../../.."); + +export default defineConfig({ + root: fixtureDirectory, + plugins: [svelte()], + resolve: { + alias: { + "@": resolve(repositoryRoot, "src"), + }, + }, + base: "./", + build: { + outDir: resolve(repositoryRoot, "_testdata/browser-ui-lifecycle"), + emptyOutDir: true, + rollupOptions: { + input: resolve(fixtureDirectory, "index.html"), + }, + }, +}); diff --git a/test/e2e-obsidian/scripts/conflict-dialog-policy.ts b/test/e2e-obsidian/scripts/conflict-dialog-policy.ts index ed53222a..62638685 100644 --- a/test/e2e-obsidian/scripts/conflict-dialog-policy.ts +++ b/test/e2e-obsidian/scripts/conflict-dialog-policy.ts @@ -38,7 +38,10 @@ type ObsidianTestApp = { | { core?: { services?: { - conflict?: { ensureAllProcessed(): Promise }; + conflict?: { + ensureAllProcessed(): Promise; + conflictProcessQueueCount: { value: number }; + }; }; }; } @@ -607,11 +610,40 @@ async function main(): Promise { await requestRepeatedConflictChecks(cliBinary, repeatedSession.cliEnv, repeatedPath, 3); await page.waitForFunction((element) => !element.isConnected, original, { timeout: uiTimeoutMs }); await modal.waitFor({ state: "visible", timeout: uiTimeoutMs }); - await page.waitForTimeout(250); + // All enqueue calls have settled. Only the final resolver may remain + // while its dialogue waits for a response; earlier checks also count. + await page.waitForFunction( + (targetPath) => { + const conflict = (globalThis as ObsidianTestGlobal).app?.plugins?.plugins?.["obsidian-livesync"] + ?.core?.services?.conflict; + const visible = Array.from(document.querySelectorAll(".modal-container")).filter( + (element) => + element.getClientRects().length > 0 && + element.querySelector(".modal-title")?.textContent?.includes("Conflicting changes") && + element.textContent?.includes(targetPath) + ); + return conflict?.conflictProcessQueueCount.value === 1 && visible.length === 1; + }, + repeatedPath, + { timeout: uiTimeoutMs } + ); const visibleCount = await conflictDialogue(page, repeatedPath).evaluateAll( (elements) => elements.filter((element) => element.getClientRects().length > 0).length ); if (visibleCount !== 1) { + const dialogues = await page.locator(".modal-container").evaluateAll((elements) => + elements.map((element) => ({ + visible: element.getClientRects().length > 0, + text: element.textContent?.slice(0, 1200), + })) + ); + const fixture = await readConflictFixture(cliBinary, repeatedSession.cliEnv, repeatedPath); + console.error(JSON.stringify({ sameFileReplacementFailure: { visibleCount, dialogues, fixture } })); + await captureObsidianPage( + repeatedSession.remoteDebuggingPort, + "conflict-dialog-same-file-replacement.failure.png", + async () => {} + ); throw new Error(`Expected one newest same-file dialogue, but found ${visibleCount}`); } }); diff --git a/test/e2e-obsidian/scripts/document-history-nav.ts b/test/e2e-obsidian/scripts/document-history-nav.ts index 9daf0752..7f25ed1f 100644 --- a/test/e2e-obsidian/scripts/document-history-nav.ts +++ b/test/e2e-obsidian/scripts/document-history-nav.ts @@ -265,7 +265,51 @@ async function main(): Promise { ); screenshotPaths.push(await captureStep(page, "06-after-search-next-match")); + const highlightDiff = modal.locator('.history-highlight-diff-label input[type="checkbox"]'); + await highlightDiff.check(); + const diffBlocks = modal.locator(".history-added, .history-deleted"); + await diffBlocks.first().waitFor({ state: "visible", timeout: 10000 }); + const diffIndicator = modal.locator(".diff-nav-indicator"); + const diffCount = await diffBlocks.count(); + const assertDiffSelection = async (index: number, count: number) => { + assertEqual( + (await diffIndicator.innerText()).trim(), + `${index + 1}/${count}`, + "Unexpected diff indicator." + ); + const focused = await diffBlocks.evaluateAll((elements) => + elements.flatMap((element, index) => (element.classList.contains("diff-focused") ? [index] : [])) + ); + assertEqual( + JSON.stringify(focused), + JSON.stringify([index]), + "Diff focus did not move to exactly one block." + ); + }; + await assertDiffSelection(0, diffCount); + const diffPrev = modal.locator(".diff-nav-btn").first(); + const diffNext = modal.locator(".diff-nav-btn").last(); + await diffPrev.click(); + await assertDiffSelection(diffCount - 1, diffCount); + await diffNext.click(); + await assertDiffSelection(0, diffCount); + for (let index = 0; index < diffCount; index++) await diffNext.click(); + await assertDiffSelection(0, diffCount); + + const oldBlock = await diffBlocks.first().elementHandle(); + if (oldBlock === null) throw new Error("Could not retain the previous revision's diff block"); + const changeRevision = (await nextBtn.isDisabled()) ? prevBtn : nextBtn; + await changeRevision.click(); + await page.waitForFunction((element) => !element.isConnected, oldBlock, { timeout: 10000 }); + await diffBlocks.first().waitFor({ state: "visible", timeout: 10000 }); + const replacementDiffCount = await diffBlocks.count(); + await assertDiffSelection(0, replacementDiffCount); + await diffPrev.click(); + await assertDiffSelection(replacementDiffCount - 1, replacementDiffCount); + screenshotPaths.push(await captureStep(page, "07-diff-navigation-after-revision-change")); + return [ + `diffNavigation: ${diffCount} blocks; replacement revision: ${replacementDiffCount} blocks`, `initialIndicator: ${initialIndicator}`, `afterPrevIndicator: ${afterPrevIndicator}`, `afterNextIndicator: ${afterNextIndicator}`, diff --git a/updates.md b/updates.md index c217ef94..32f0f46a 100644 --- a/updates.md +++ b/updates.md @@ -16,6 +16,10 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi - Service log calls stay with the plug-in instance that registered them. Its log connection is released after the full shutdown, so stale instances cannot receive later service messages. +### Browser applications + +- WebApp and WebPeer dialogues and menus remain with their owning application + and close on shutdown; closing or replacing a menu releases its component. ## 1.0.42 From 4027417bf522f5ec3ba10b5a1eb0e77516b6d6e8 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Thu, 29 Oct 2026 15:00:19 +0000 Subject: [PATCH 04/24] Narrow service and command composition --- devs.md | 4 + ...ce_feature_and_legacy_module_boundaries.md | 52 +++- src/LiveSyncBaseCore.ts | 7 +- .../SettingDialogue/LiveSyncSetting.ts | 46 ++-- .../LiveSyncSetting.wiring.unit.spec.ts | 227 +++++++++++++++++ .../features/SettingDialogue/PaneSelector.ts | 152 ++++++------ .../SettingDialogue/PaneSelector.unit.spec.ts | 229 ++++++++++++++++++ .../features/SettingDialogue/SettingPane.ts | 10 - src/serviceFeatures/basicCommands.ts | 29 +-- .../basicCommands.unit.spec.ts | 43 ++++ src/serviceFeatures/compatibilityReview.ts | 22 +- .../compatibilityReview.unit.spec.ts | 32 ++- .../conflictResolution.unit.spec.ts | 94 ++++++- .../conflictResolution/index.ts | 34 ++- .../onLayoutReady/enablei18n.ts | 6 +- .../onLayoutReady/enablei18n.unit.spec.ts | 10 +- src/serviceFeatures/setupObsidian/setupUri.ts | 42 ++-- .../setupObsidian/setupUri.unit.spec.ts | 11 +- src/serviceFeatures/useDatabaseDiagnostics.ts | 24 +- .../useDatabaseDiagnostics.unit.spec.ts | 20 ++ src/serviceFeatures/useP2PReplicatorUI.ts | 19 +- .../useP2PReplicatorUI.unit.spec.ts | 17 +- 22 files changed, 928 insertions(+), 202 deletions(-) create mode 100644 src/modules/features/SettingDialogue/LiveSyncSetting.wiring.unit.spec.ts create mode 100644 src/modules/features/SettingDialogue/PaneSelector.unit.spec.ts diff --git a/devs.md b/devs.md index d618e88c..a9acec7c 100644 --- a/devs.md +++ b/devs.md @@ -144,6 +144,8 @@ The application is composed from Services, ServiceModules, serviceFeatures, add- The normal composition order is the Service Hub, Replicator provider registration, ServiceModules, serviceFeatures, add-ons, and finally legacy Module binding. A serviceFeature may therefore consume an already constructed ServiceModule. Preferring a serviceFeature for new composition is a dependency-boundary rule, not an initialisation-order rule. +Declare the feature host type explicitly when a narrow dependency contract is intended. `NecessaryServices` selects service keys from `THub` and module keys from `ServiceModules`; it retains `context` only when the selected source provides it, and defaults to `ServiceHub`. `createServiceFeature()` returns the supplied function with its complete signature and result type, but it does not infer dependency keys from the callback body. Unannotated legacy callbacks retain the full default `ServiceHub` contract for compatibility. Put feature-only collaborators, such as a borrowed `LogFunction`, in the feature's own dependency type. + Mutable state is permitted in a serviceFeature. State alone is not a reason to create a class, a ServiceModule, or retain an AbstractModule. Prefer one private context, with module-level functions which receive that context, when identity and polymorphism are not part of the contract. Separate the state, transitions, and invariants from the surrounding function which registers lifecycle handlers and connects downstream effects. Give the stateful boundary narrow collaborators rather than `LiveSyncBaseCore`. Use a class when stable object identity, replaceable implementations, or an explicit external-resource lifecycle such as serialised ownership, `dispose()`, or `abort()` is part of the contract. Use a ServiceModule when that operational capability or resource lifecycle must also be shared explicitly by several consumers. Do not introduce a class merely to group dependencies or make private functions callable. @@ -200,6 +202,8 @@ steps required to add a built-in provider. Commonlib owns one stable `LiveSyncP2PService`, its `P2PRoomSessionOwner`, and the replaceable Trystero room session. Host commands, event handlers, and views consume the focused transport, connection-probe admission, directory, peer-admission, transfer, change-relay, configuration, and diagnostic views returned by the service feature. They must not retain the deprecated compatibility Replicator as an ordinary service locator, close Trystero-owned raw peers, or install another Trystero transport generation at the application root. The exact implemented ownership and shutdown boundaries are recorded in Commonlib's [P2P transport lifecycle](https://github.com/vrtmrz/livesync-commonlib/blob/main/docs/p2p-transport-lifecycle.md) design document. +The Obsidian `useP2PReplicatorUI` feature declares only `API`, `appLifecycle`, `setting`, and `replicator`, and consumes the public `P2PServiceViews` type instead of the broader `UseP2PReplicatorResult`. Its separate `LiveSyncCore` argument and global `eventHub` remain the legacy pane bridge; this type narrowing leaves the existing presentation and lifecycle wiring intact. + The [TURN connection settings design](docs/design_docs/renewable_turn_credentials.md) describes how the host prepares temporary ICE credentials in a connection-only settings copy. It covers room reuse and expiry, replication continuation, profile persistence and sharing, and report redaction. ### Conflict Merge Policy diff --git a/docs/design_docs/service_feature_and_legacy_module_boundaries.md b/docs/design_docs/service_feature_and_legacy_module_boundaries.md index 65ec41ec..8dd3539d 100644 --- a/docs/design_docs/service_feature_and_legacy_module_boundaries.md +++ b/docs/design_docs/service_feature_and_legacy_module_boundaries.md @@ -1,7 +1,7 @@ --- -date: 2026-09-04 -commonlib-version: "0.1.21" -self-hosted-livesync-version: "1.0.24" +date: 2026-10-25 +commonlib-version: "0.2.0" +self-hosted-livesync-version: "1.0.40" status: accepted --- @@ -104,14 +104,22 @@ For new behaviour, keep Obsidian-specific presentation or registration in an Obs ### A small serviceFeature: language initialisation -`src/serviceFeatures/onLayoutReady/enablei18n.ts` declares only `setting`, `API`, and `appLifecycle`: +`src/serviceFeatures/onLayoutReady/enablei18n.ts` declares only `setting`, `API`, and `appLifecycle`, with an explicit dependency type: ```typescript -export const enableI18nFeature = createServiceFeature(async ({ services: { setting, API, appLifecycle } }) => { - // Apply the language, persist a change, and register unload clean-up. -}); +type EnableI18nHost = NecessaryServices<"setting" | "API" | "appLifecycle", never>; + +export const enableI18nFeature = createServiceFeature( + async (host: EnableI18nHost): Promise => { + const { setting, API, appLifecycle } = host.services; + // Apply the language, persist a change, and register unload clean-up. + return true; + } +); ``` +The host annotation keeps the dependency contract visible because `createServiceFeature()` does not infer dependency keys from the callback body. This feature retains its `Promise` result. + The local `ObsidianLanguageAppliedNotice` class is still appropriate. It owns one replaceable Obsidian `Notice` and has an explicit `clear()` lifetime operation. The class is not used as a service locator, and the serviceFeature owns its construction and host binding. ### Operation and composition: database preparation @@ -130,6 +138,22 @@ The operation does not need an application Module identity. ### Ordered start-up composition and registration-only features +Compatibility review uses distinct controller and composer dependencies: + +```typescript +type CompatibilityReviewDependencies = NecessaryServicesInterfaces< + "setting" | "config" | "vault" | "control", + never +>; + +type CompatibilityReviewHost = NecessaryServices< + "setting" | "config" | "vault" | "control" | "appLifecycle" | "API", + never +>; +``` + +The controller receives the four interface-only Services it uses. The composer adds `appLifecycle` and `API` for ordered lifecycle handlers and command registration; the priority-30 compatibility review remains after flag-file recovery. + Configured Vault admission and the checks which follow database preparation are composed by `src/serviceFeatures/startupLifecycle/`. The directory keeps onboarding admission, compromised-chunk inspection, incomplete-document repair, Config Doctor, and the obsolete bulk-send setting migration as separate operations. One feature composer owns their order and receives the compatibility-review wait operation explicitly; an individual operation does not call the composer. The layout-ready admission handler uses priority 1. This preserves ordinary priority-0 host integration before admission, while keeping an unconfigured Vault outside the flag-file recovery handlers at priorities 5, 10, and 20, and the compatibility review at priority 30. Admission belongs to one plug-in process: an initially unconfigured process remains inert until setup restarts it, and declining the requested restart does not trigger an in-process reconfiguration. Changing an admitted process back to unconfigured retires its Config Doctor and incomplete-document repair request handlers. The handlers also recheck the current configured state and database readiness when invoked, so a pending restart cannot expose partially initialised or retired state. The first-initialise handler rechecks admission before retaining the established order after the file watcher has been started: database readiness, compromised chunks, incomplete documents, compatibility review, Config Doctor, and the bulk-send setting migration. @@ -144,7 +168,19 @@ The state remains private to the composed feature. It does not become a `LiveSyn ### Implemented composition: conflict resolution -Conflict checking and resolution are composed for every host by `useConflictResolutionFeature`. The feature owns its `QueueProcessor` privately and registers the conflict Service handlers directly. Its operations receive explicit collaborators for settings, active-file state, database and storage access, replication, logging, and host events. No consumer locates a conflict Module or retains the queue. +Conflict checking and resolution are composed for every host by `useConflictResolutionFeature`. The feature owns its `QueueProcessor` privately and registers the conflict Service handlers directly. Its host type selects the required service and module contracts and adds the borrowed logger explicitly: + +```typescript +type ConflictResolutionHost = NecessaryServices< + "appLifecycle" | "conflict" | "database" | "replication" | "setting" | "vault", + "databaseFileAccess" | "fileHandler" | "storageAccess", + InjectableServiceHub +> & { + readonly log: LogFunction; +}; +``` + +The operations receive explicit collaborators for settings, active-file state, database and storage access, replication, a borrowed `LogFunction`, and host events. `LiveSyncBaseCore` supplies `log` using `createInstanceLogFunction("SF:ConflictResolution", this.services.API)`. Because feature composition precedes legacy Module binding, the host supplies the existing lazy service logger and does not read `logResource.value` before binding. `ModuleLog` and the host retain resource ownership. No consumer locates a conflict Module or retains the queue. The scheduling queue remains one state owner. It publishes `conflictProcessQueueCount`, coalesces pending checks for the same path, and makes `ensureAllProcessed()` wait for conflict resolution to finish. Repeated resolver invocations for one path retain only the newest waiting request and close an active comparison for that path before waiting for the per-file resolver, while comparisons for other paths remain open. Resolution remains host-neutral and communicates dialogue cancellation through `services.context.events`, so CLI, WebApp, and Obsidian compositions use their own selected event channel. diff --git a/src/LiveSyncBaseCore.ts b/src/LiveSyncBaseCore.ts index 9870a448..777bc164 100644 --- a/src/LiveSyncBaseCore.ts +++ b/src/LiveSyncBaseCore.ts @@ -31,6 +31,7 @@ import { useReplicationScheduling, type ReplicationSchedulingControl } from "./s import { createCentralReplicatorProviderDefinitions } from "./common/replicatorProviders"; import { useReplicationFeature } from "./serviceFeatures/replication"; import { useConflictResolutionFeature } from "./serviceFeatures/conflictResolution"; +import { createInstanceLogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; import { useBasicCommandsFeature } from "./serviceFeatures/basicCommands"; /** Focused views returned by serviceFeatures which the host may consume during composition. */ @@ -290,7 +291,11 @@ export class LiveSyncBaseCore< * (Please refer `serviceFeatures` for more details) */ initialiseServiceFeatures(): LiveSyncCoreFeatureViews { - useConflictResolutionFeature(this); + useConflictResolutionFeature({ + services: this.services, + serviceModules: this.serviceModules, + log: createInstanceLogFunction("SF:ConflictResolution", this.services.API), + }); useTargetFilters(this); // enable target filter feature. usePrepareDatabaseForUse(this); diff --git a/src/modules/features/SettingDialogue/LiveSyncSetting.ts b/src/modules/features/SettingDialogue/LiveSyncSetting.ts index 19ff983e..455eebd6 100644 --- a/src/modules/features/SettingDialogue/LiveSyncSetting.ts +++ b/src/modules/features/SettingDialogue/LiveSyncSetting.ts @@ -14,7 +14,7 @@ import { statusDisplay, type ConfigurationItem, } from "@vrtmrz/livesync-commonlib/compat/common/types"; -import { type ObsidianLiveSyncSettingTab } from "./ObsidianLiveSyncSettingTab.ts"; +import type { ObsidianLiveSyncSettingTab } from "./ObsidianLiveSyncSettingTab.ts"; import { type AllSettingItemKey, getConfig, @@ -24,7 +24,8 @@ import { type AllBooleanItemKey, } from "./settingConstants.ts"; import { $msg } from "@/common/translation"; -import { wrapMemo, type AutoWireOption, type OnUpdateResult } from "./SettingPane.ts"; +import type { AutoWireOption, OnUpdateResult } from "./SettingPane.ts"; +import { wrapMemo } from "octagonal-wheels/function"; import { setButtonDestructiveState } from "./settingComponentStyles.ts"; export class LiveSyncSetting extends Setting { @@ -109,9 +110,13 @@ export class LiveSyncSetting extends Setting { } LiveSyncSetting.env.requestUpdate(); } - autoWireText(key: AllStringItemKey, opt?: AutoWireOption) { + private autoWireStringComponent( + key: AllStringItemKey, + addComponent: (callback: (component: TComponent) => void) => void, + opt?: AutoWireOption + ) { const conf = this.autoWireSetting(key, opt); - this.addText((text) => { + addComponent((text) => { this.autoWiredComponent = text; const setValue = wrapMemo((value: string) => { text.setValue(value); @@ -127,26 +132,25 @@ export class LiveSyncSetting extends Setting { } this.autoWireComponent(this.autoWiredComponent, conf, opt); }); + } + autoWireText(key: AllStringItemKey, opt?: AutoWireOption) { + this.autoWireStringComponent( + key, + (callback) => { + this.addText(callback); + }, + opt + ); return this; } autoWireTextArea(key: AllStringItemKey, opt?: AutoWireOption) { - const conf = this.autoWireSetting(key, opt); - this.addTextArea((text) => { - this.autoWiredComponent = text; - const setValue = wrapMemo((value: string) => { - text.setValue(value); - }); - this.invalidateValue = () => setValue(`${LiveSyncSetting.env.editingSettings[key]}`); - this.invalidateValue(); - text.onChange(async (value) => { - await this.commitValue(value); - }); - if (opt?.isPassword) { - text.inputEl.setAttribute("type", "password"); - this.hasPassword = true; - } - this.autoWireComponent(this.autoWiredComponent, conf, opt); - }); + this.autoWireStringComponent( + key, + (callback) => { + this.addTextArea(callback); + }, + opt + ); return this; } autoWireNumeric( diff --git a/src/modules/features/SettingDialogue/LiveSyncSetting.wiring.unit.spec.ts b/src/modules/features/SettingDialogue/LiveSyncSetting.wiring.unit.spec.ts new file mode 100644 index 00000000..5335bc6d --- /dev/null +++ b/src/modules/features/SettingDialogue/LiveSyncSetting.wiring.unit.spec.ts @@ -0,0 +1,227 @@ +import { describe, expect, it, vi } from "vitest"; + +const liveSyncSettingHarness = vi.hoisted(() => ({ + components: [] as unknown[], + settingElements: [] as unknown[], +})); + +vi.mock("@/deps.ts", () => { + class StringComponent { + values: string[] = []; + changeHandler?: (value: string) => Promise; + placeholder?: string; + inputEl = { + attributes: new Map(), + setAttribute(name: string, value: string) { + this.attributes.set(name, value); + }, + toggleClass: (_name: string, _enabled: boolean) => {}, + }; + setValue(value: string) { + this.values.push(value); + } + onChange(handler: (value: string) => Promise) { + this.changeHandler = handler; + return this; + } + setPlaceholder(value: string) { + this.placeholder = value; + return this; + } + constructor() { + liveSyncSettingHarness.components.push(this); + } + } + class TextComponent extends StringComponent {} + class TextAreaComponent extends StringComponent {} + class Setting { + settingEl = { + classes: [] as { name: string; enabled: boolean }[], + toggleClass(name: string, enabled: boolean) { + this.classes.push({ name, enabled }); + }, + }; + constructor(_containerEl: HTMLElement) { + liveSyncSettingHarness.settingElements.push(this.settingEl); + } + setDesc(_description: string | DocumentFragment) { + return this; + } + setName(_name: string | DocumentFragment) { + return this; + } + addText(callback: (component: TextComponent) => void) { + callback(new TextComponent()); + return this; + } + addTextArea(callback: (component: TextAreaComponent) => void) { + callback(new TextAreaComponent()); + return this; + } + setTooltip(_description: string) { + return this; + } + setDisabled(_disabled: boolean) { + return this; + } + } + return { Setting, TextComponent, TextAreaComponent, ButtonComponent: class {} }; +}); +vi.mock("./ObsidianLiveSyncSettingTab.ts", () => ({})); +vi.mock("@/common/translation", () => ({ $msg: (key: string) => key })); +vi.mock("@vrtmrz/livesync-commonlib/compat/common/types", () => ({ + LEVEL_ADVANCED: 1, + LEVEL_POWER_USER: 2, + statusDisplay: () => "", +})); +vi.mock("./settingConstants.ts", () => ({ + getConfig: (key: string) => ({ + name: key, + desc: `description for ${key}`, + placeHolder: `configured placeholder for ${key}`, + }), +})); +vi.mock("./settingComponentStyles.ts", () => ({ setButtonDestructiveState: vi.fn() })); +vi.mock("octagonal-wheels/collection", () => ({ unique: (items: unknown[]) => [...new Set(items)] })); + +import { LiveSyncSetting } from "./LiveSyncSetting.ts"; + +type WireKind = "text" | "textarea"; +type StringComponentHarness = { + values: string[]; + changeHandler?: (value: string) => Promise; + placeholder?: string; + inputEl: { attributes: Map }; +}; +type SettingElementHarness = { classes: { name: string; enabled: boolean }[] }; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +function wireStringSetting( + kind: WireKind, + options: { + holdValue?: boolean; + isPassword?: boolean; + placeHolder?: string; + onUpdate?: () => { visibility?: boolean }; + } = {} +) { + const key = kind === "text" ? "syncOnlyRegEx" : "ignoreFiles"; + const events: string[] = []; + const editingSettings: Record = { [key]: 17 }; + const saveSettings = vi.fn(async (_keys: string[]) => {}); + const requestUpdate = vi.fn(() => events.push("update")); + const env = { + settingComponents: [] as unknown[], + editingSettings, + saveSettings, + requestUpdate, + }; + LiveSyncSetting.env = env as never; + + const setting = new LiveSyncSetting({} as HTMLElement); + const onUpdate = vi.fn(options.onUpdate ?? (() => ({ visibility: false }))); + const wireOptions = { ...options, onUpdate }; + if (kind === "text") { + setting.autoWireText(key as never, wireOptions); + } else { + setting.autoWireTextArea(key as never, wireOptions); + } + + return { + key, + events, + editingSettings, + saveSettings, + requestUpdate, + setting, + component: setting.autoWiredComponent as unknown as StringComponentHarness, + settingElement: setting.settingEl as unknown as SettingElementHarness, + onUpdate, + }; +} + +describe("LiveSyncSetting string controls", () => { + it.each(["text", "textarea"] as const)("wires %s through the shared string commit contract", async (kind) => { + const { + key, + events, + editingSettings, + saveSettings, + requestUpdate, + setting, + component, + settingElement, + onUpdate, + } = wireStringSetting(kind, { isPassword: true, placeHolder: "option placeholder" }); + + expect(component.values).toEqual(["17"]); + setting.invalidateValue?.(); + expect(component.values).toEqual(["17"]); + editingSettings[key] = 18; + setting.invalidateValue?.(); + expect(component.values).toEqual(["17", "18"]); + expect(component.inputEl.attributes.get("type")).toBe("password"); + expect(setting.hasPassword).toBe(true); + expect(setting.updateHandlers.size).toBe(1); + expect(onUpdate).toHaveBeenCalledTimes(1); + expect(setting._getComputedStatus()).toEqual({ visibility: false }); + expect(onUpdate).toHaveBeenCalledTimes(2); + expect(settingElement.classes).toContainEqual({ name: "sls-setting-hidden", enabled: true }); + if (kind === "text") { + expect(component.placeholder).toBe("configured placeholder for syncOnlyRegEx"); + } else { + expect(component.placeholder).toBeUndefined(); + } + + const pendingSave = deferred(); + saveSettings.mockImplementationOnce(async (keys) => { + events.push(`save:${keys.join(",")}`); + await pendingSave.promise; + events.push("saved"); + }); + const commit = component.changeHandler!("changed"); + expect(editingSettings[key]).toBe("changed"); + expect(saveSettings).toHaveBeenCalledWith([key]); + expect(events).toEqual([`save:${key}`]); + expect(requestUpdate).not.toHaveBeenCalled(); + pendingSave.resolve(); + await commit; + expect(events).toEqual([`save:${key}`, "saved", "update"]); + + events.length = 0; + await component.changeHandler!("changed"); + expect(saveSettings).toHaveBeenCalledTimes(1); + expect(events).toEqual(["update"]); + + events.length = 0; + const failure = new Error("setting save failed"); + saveSettings.mockImplementationOnce(async (keys) => { + events.push(`save:${keys.join(",")}`); + throw failure; + }); + await expect(component.changeHandler!("failed")).rejects.toBe(failure); + expect(editingSettings[key]).toBe("failed"); + expect(events).toEqual([`save:${key}`]); + expect(requestUpdate).toHaveBeenCalledTimes(2); + }); + + it.each(["text", "textarea"] as const)("keeps %s held values in the editing copy without saving", async (kind) => { + const { key, editingSettings, saveSettings, requestUpdate, component, events } = wireStringSetting(kind, { + holdValue: true, + }); + + await component.changeHandler!("held value"); + + expect(editingSettings[key]).toBe("held value"); + expect(saveSettings).not.toHaveBeenCalled(); + expect(requestUpdate).toHaveBeenCalledOnce(); + expect(events).toEqual(["update"]); + }); +}); diff --git a/src/modules/features/SettingDialogue/PaneSelector.ts b/src/modules/features/SettingDialogue/PaneSelector.ts index 783d6e99..77a98c0a 100644 --- a/src/modules/features/SettingDialogue/PaneSelector.ts +++ b/src/modules/features/SettingDialogue/PaneSelector.ts @@ -1,4 +1,8 @@ -import { LEVEL_ADVANCED, type CustomRegExpSource } from "@vrtmrz/livesync-commonlib/compat/common/types"; +import { + LEVEL_ADVANCED, + type CustomRegExpSource, + type CustomRegExpSourceList, +} from "@vrtmrz/livesync-commonlib/compat/common/types"; import { constructCustomRegExpList, splitCustomRegExpList } from "@vrtmrz/livesync-commonlib/compat/common/utils"; import MultipleRegExpControl from "./MultipleRegExpControl.svelte"; import { LiveSyncSetting as Setting } from "./LiveSyncSetting.ts"; @@ -7,6 +11,35 @@ import type { ObsidianLiveSyncSettingTab } from "./ObsidianLiveSyncSettingTab.ts import type { PageFunctions } from "./SettingPane.ts"; import { visibleOnly } from "./SettingPane.ts"; import { $msg } from "@/common/translation"; + +type RegExpControlOwner = Pick< + ObsidianLiveSyncSettingTab, + "saveAllDirtySettings" | "requestPageRefresh" | "lifetimeComponent" +>; + +function mountMultipleRegExpControl( + owner: RegExpControlOwner, + target: HTMLElement, + source: CustomRegExpSourceList, + delimiter: D, + assign: (serializedPatterns: CustomRegExpSourceList) => void +): void { + const patterns = splitCustomRegExpList(source, delimiter); + const control = mount(MultipleRegExpControl, { + target, + props: { + patterns, + originals: [...patterns], + apply: async (newPatterns: CustomRegExpSource[]) => { + assign(constructCustomRegExpList(newPatterns, delimiter)); + await owner.saveAllDirtySettings(); + owner.requestPageRefresh(); + }, + }, + }); + owner.lifetimeComponent.register(() => void unmount(control)); +} + export function paneSelector(this: ObsidianLiveSyncSettingTab, paneEl: HTMLElement, { addPanel }: PageFunctions): void { void addPanel(paneEl, $msg("Normal Files")).then((paneEl) => { const syncFilesSetting = new Setting(paneEl) @@ -16,37 +49,29 @@ export function paneSelector(this: ObsidianLiveSyncSettingTab, paneEl: HTMLEleme "(RegExp) Limit normal files to matching paths. Leave empty to allow all normal file paths. Hidden File Sync uses its own target patterns." ) ); - const syncFilesControl = mount(MultipleRegExpControl, { - target: syncFilesSetting.controlEl, - props: { - patterns: splitCustomRegExpList(this.editingSettings.syncOnlyRegEx, "|[]|"), - originals: splitCustomRegExpList(this.editingSettings.syncOnlyRegEx, "|[]|"), - apply: async (newPatterns: CustomRegExpSource[]) => { - this.editingSettings.syncOnlyRegEx = constructCustomRegExpList(newPatterns, "|[]|"); - await this.saveAllDirtySettings(); - this.requestPageRefresh(); - }, - }, - }); - this.lifetimeComponent.register(() => void unmount(syncFilesControl)); + mountMultipleRegExpControl( + this, + syncFilesSetting.controlEl, + this.editingSettings.syncOnlyRegEx, + "|[]|", + (value) => { + this.editingSettings.syncOnlyRegEx = value; + } + ); const nonSyncFilesSetting = new Setting(paneEl) .setName($msg("Non-Synchronising files")) .setDesc($msg("(RegExp) Skip changes to matching normal and hidden files, locally and remotely.")); - const nonSyncFilesControl = mount(MultipleRegExpControl, { - target: nonSyncFilesSetting.controlEl, - props: { - patterns: splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx, "|[]|"), - originals: splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx, "|[]|"), - apply: async (newPatterns: CustomRegExpSource[]) => { - this.editingSettings.syncIgnoreRegEx = constructCustomRegExpList(newPatterns, "|[]|"); - await this.saveAllDirtySettings(); - this.requestPageRefresh(); - }, - }, - }); - this.lifetimeComponent.register(() => void unmount(nonSyncFilesControl)); + mountMultipleRegExpControl( + this, + nonSyncFilesSetting.controlEl, + this.editingSettings.syncIgnoreRegEx, + "|[]|", + (value) => { + this.editingSettings.syncIgnoreRegEx = value; + } + ); new Setting(paneEl).autoWireNumeric("syncMaxSizeInMB", { clampMin: 0 }); new Setting(paneEl).autoWireToggle("useIgnoreFiles"); @@ -58,41 +83,30 @@ export function paneSelector(this: ObsidianLiveSyncSettingTab, paneEl: HTMLEleme const targetPatternSetting = new Setting(paneEl) .setName($msg("Target patterns")) .setDesc($msg("Patterns to match files for syncing")); - const patTarget = splitCustomRegExpList(this.editingSettings.syncInternalFilesTargetPatterns, ","); - const targetPatternControl = mount(MultipleRegExpControl, { - target: targetPatternSetting.controlEl, - props: { - patterns: patTarget, - originals: [...patTarget], - apply: async (newPatterns: CustomRegExpSource[]) => { - this.editingSettings.syncInternalFilesTargetPatterns = constructCustomRegExpList(newPatterns, ","); - await this.saveAllDirtySettings(); - this.requestPageRefresh(); - }, - }, - }); - this.lifetimeComponent.register(() => void unmount(targetPatternControl)); + mountMultipleRegExpControl( + this, + targetPatternSetting.controlEl, + this.editingSettings.syncInternalFilesTargetPatterns, + ",", + (value) => { + this.editingSettings.syncInternalFilesTargetPatterns = value; + } + ); const defaultSkipPattern = "\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/"; const defaultSkipPatternXPlat = defaultSkipPattern + ",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$"; - const pat = splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns, ","); const patSetting = new Setting(paneEl).setName($msg("Ignore patterns")).setDesc(""); - - const ignorePatternControl = mount(MultipleRegExpControl, { - target: patSetting.controlEl, - props: { - patterns: pat, - originals: [...pat], - apply: async (newPatterns: CustomRegExpSource[]) => { - this.editingSettings.syncInternalFilesIgnorePatterns = constructCustomRegExpList(newPatterns, ","); - await this.saveAllDirtySettings(); - this.requestPageRefresh(); - }, - }, - }); - this.lifetimeComponent.register(() => void unmount(ignorePatternControl)); + mountMultipleRegExpControl( + this, + patSetting.controlEl, + this.editingSettings.syncInternalFilesIgnorePatterns, + ",", + (value) => { + this.editingSettings.syncInternalFilesIgnorePatterns = value; + } + ); const addDefaultPatterns = async (patterns: string) => { const oldList = splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns, ","); @@ -122,22 +136,14 @@ export function paneSelector(this: ObsidianLiveSyncSettingTab, paneEl: HTMLEleme const overwritePatterns = new Setting(paneEl) .setName($msg("Overwrite patterns")) .setDesc($msg("Patterns to match files for overwriting instead of merging")); - const patTarget2 = splitCustomRegExpList(this.editingSettings.syncInternalFileOverwritePatterns, ","); - const overwritePatternControl = mount(MultipleRegExpControl, { - target: overwritePatterns.controlEl, - props: { - patterns: patTarget2, - originals: [...patTarget2], - apply: async (newPatterns: CustomRegExpSource[]) => { - this.editingSettings.syncInternalFileOverwritePatterns = constructCustomRegExpList( - newPatterns, - "," - ); - await this.saveAllDirtySettings(); - this.requestPageRefresh(); - }, - }, - }); - this.lifetimeComponent.register(() => void unmount(overwritePatternControl)); + mountMultipleRegExpControl( + this, + overwritePatterns.controlEl, + this.editingSettings.syncInternalFileOverwritePatterns, + ",", + (value) => { + this.editingSettings.syncInternalFileOverwritePatterns = value; + } + ); }); } diff --git a/src/modules/features/SettingDialogue/PaneSelector.unit.spec.ts b/src/modules/features/SettingDialogue/PaneSelector.unit.spec.ts new file mode 100644 index 00000000..a53efdf2 --- /dev/null +++ b/src/modules/features/SettingDialogue/PaneSelector.unit.spec.ts @@ -0,0 +1,229 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const paneSelectorHarness = vi.hoisted(() => ({ + mounts: [] as { component: unknown; target: unknown; props: Record; handle: unknown }[], + unmounted: [] as unknown[], + settings: [] as { containerEl: HTMLElement; controlEl: unknown }[], + buttons: [] as { text: string; handler?: () => void | Promise }[], +})); + +vi.mock("@/common/translation", () => ({ $msg: (value: string) => value })); +vi.mock("./MultipleRegExpControl.svelte", () => ({ default: { name: "MultipleRegExpControl" } })); +vi.mock("svelte", () => ({ + mount: vi.fn((component: unknown, options: { target: unknown; props: Record }) => { + const handle = { id: paneSelectorHarness.mounts.length }; + paneSelectorHarness.mounts.push({ component, target: options.target, props: options.props, handle }); + return handle; + }), + unmount: vi.fn((component: unknown) => { + paneSelectorHarness.unmounted.push(component); + }), +})); +vi.mock("./LiveSyncSetting.ts", () => ({ + LiveSyncSetting: class { + controlEl: { id: number }; + constructor(containerEl: HTMLElement) { + this.controlEl = { id: paneSelectorHarness.settings.length }; + paneSelectorHarness.settings.push({ containerEl, controlEl: this.controlEl }); + } + setName(_name: string) { + return this; + } + setDesc(_description: string) { + return this; + } + autoWireNumeric(_key: string, _options: unknown) { + return this; + } + autoWireToggle(_key: string) { + return this; + } + autoWireTextArea(_key: string, _options: unknown) { + return this; + } + addButton( + callback: (button: { + setButtonText: (text: string) => unknown; + onClick: (handler: () => void | Promise) => unknown; + }) => void + ) { + const button = { + text: "", + handler: undefined as (() => void | Promise) | undefined, + setButtonText(text: string) { + this.text = text; + return this; + }, + onClick(handler: () => void | Promise) { + this.handler = handler; + paneSelectorHarness.buttons.push(this); + return this; + }, + }; + callback(button); + return this; + } + }, +})); + +import { paneSelector } from "./PaneSelector.ts"; + +type PatternControlProps = { + patterns: string[]; + originals: string[]; + apply: (patterns: string[]) => Promise; +}; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((resolvePromise) => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +async function renderSelector() { + const normalPanel = { id: "normal" } as unknown as HTMLElement; + const hiddenPanel = { id: "hidden" } as unknown as HTMLElement; + const addPanel = vi.fn((_parent: HTMLElement, title: string) => + Promise.resolve(title === "Normal Files" ? normalPanel : hiddenPanel) + ); + const disposers: (() => void)[] = []; + const tab = { + editingSettings: { + syncOnlyRegEx: "alpha|[]|beta", + syncIgnoreRegEx: "skip|[]|also-skip", + syncInternalFilesTargetPatterns: "target-a,target-b", + syncInternalFilesIgnorePatterns: "existing,\\/node_modules\\/", + syncInternalFileOverwritePatterns: "overwrite-a,overwrite-b", + }, + saveAllDirtySettings: vi.fn(async () => {}), + requestPageRefresh: vi.fn(), + lifetimeComponent: { register: (dispose: () => void) => disposers.push(dispose) }, + }; + + paneSelector.call(tab as never, {} as HTMLElement, { addPanel } as never); + await vi.waitFor(() => expect(paneSelectorHarness.mounts).toHaveLength(5)); + return { tab, addPanel, disposers }; +} + +function controlProps(index: number): PatternControlProps { + return paneSelectorHarness.mounts[index]!.props as unknown as PatternControlProps; +} + +beforeEach(() => { + paneSelectorHarness.mounts.length = 0; + paneSelectorHarness.unmounted.length = 0; + paneSelectorHarness.settings.length = 0; + paneSelectorHarness.buttons.length = 0; + vi.clearAllMocks(); +}); + +describe("paneSelector multiple-pattern controls", () => { + it("keeps all five bindings, independent originals, delimiter choices, save ordering, and owned cleanup", async () => { + const { tab, addPanel, disposers } = await renderSelector(); + expect(addPanel.mock.calls.map(([, title]) => title)).toEqual(["Normal Files", "Hidden Files"]); + expect(paneSelectorHarness.mounts.map(({ props }) => (props as PatternControlProps).patterns)).toEqual([ + ["alpha", "beta"], + ["skip", "also-skip"], + ["target-a", "target-b"], + ["existing", "\\/node_modules\\/"], + ["overwrite-a", "overwrite-b"], + ]); + + for (let index = 0; index < paneSelectorHarness.mounts.length; index++) { + const { patterns, originals } = controlProps(index); + expect(originals).toEqual(patterns); + expect(originals).not.toBe(patterns); + patterns.push("edited-current-value"); + expect(originals).not.toContain("edited-current-value"); + } + + const cases = [ + { + index: 0, + key: "syncOnlyRegEx", + patterns: ["new-normal-a", "new-normal-b"], + value: "new-normal-a|[]|new-normal-b", + }, + { + index: 1, + key: "syncIgnoreRegEx", + patterns: ["new-skip-a", "new-skip-b"], + value: "new-skip-a|[]|new-skip-b", + }, + { + index: 2, + key: "syncInternalFilesTargetPatterns", + patterns: ["new-target-a", "new-target-b"], + value: "new-target-a,new-target-b", + }, + { + index: 3, + key: "syncInternalFilesIgnorePatterns", + patterns: ["new-ignore-a", "new-ignore-b"], + value: "new-ignore-a,new-ignore-b", + }, + { + index: 4, + key: "syncInternalFileOverwritePatterns", + patterns: ["new-overwrite-a", "new-overwrite-b"], + value: "new-overwrite-a,new-overwrite-b", + }, + ] as const; + const events: string[] = []; + for (let index = 0; index < cases.length; index++) { + const item = cases[index]!; + const pendingSave = deferred(); + events.length = 0; + tab.saveAllDirtySettings.mockImplementationOnce(async () => { + events.push(`save:${item.key}`); + await pendingSave.promise; + events.push("saved"); + }); + tab.requestPageRefresh.mockImplementationOnce(() => { + events.push("refresh"); + }); + + const applying = controlProps(item.index).apply([...item.patterns]); + expect(tab.editingSettings[item.key as keyof typeof tab.editingSettings]).toBe(item.value); + expect(tab.saveAllDirtySettings).toHaveBeenCalledTimes(index + 1); + expect(events).toEqual([`save:${item.key}`]); + expect(tab.requestPageRefresh).toHaveBeenCalledTimes(index); + + pendingSave.resolve(); + await applying; + expect(events).toEqual([`save:${item.key}`, "saved", "refresh"]); + expect(tab.requestPageRefresh).toHaveBeenCalledTimes(index + 1); + } + + const failure = new Error("settings save failed"); + tab.saveAllDirtySettings.mockRejectedValueOnce(failure); + await expect(controlProps(2).apply(["assigned-before-failure"])).rejects.toBe(failure); + expect(tab.editingSettings.syncInternalFilesTargetPatterns).toBe("assigned-before-failure"); + expect(tab.requestPageRefresh).toHaveBeenCalledTimes(cases.length); + + expect(disposers).toHaveLength(5); + disposers.forEach((dispose) => dispose()); + expect(paneSelectorHarness.unmounted).toEqual(paneSelectorHarness.mounts.map(({ handle }) => handle)); + }); + + it("merges default hidden-file ignores with existing patterns and removes duplicates", async () => { + const { tab } = await renderSelector(); + const defaultButton = paneSelectorHarness.buttons.find(({ text }) => text === "Default"); + const crossPlatformButton = paneSelectorHarness.buttons.find(({ text }) => text === "Cross-platform"); + expect(defaultButton?.handler).toBeDefined(); + expect(crossPlatformButton?.handler).toBeDefined(); + + await defaultButton!.handler!(); + expect(tab.editingSettings.syncInternalFilesIgnorePatterns).toBe( + "existing,\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/" + ); + await crossPlatformButton!.handler!(); + expect(tab.editingSettings.syncInternalFilesIgnorePatterns).toBe( + "existing,\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/,\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$" + ); + expect(tab.saveAllDirtySettings).toHaveBeenCalledTimes(2); + expect(tab.requestPageRefresh).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/modules/features/SettingDialogue/SettingPane.ts b/src/modules/features/SettingDialogue/SettingPane.ts index 442c2f93..57bd447c 100644 --- a/src/modules/features/SettingDialogue/SettingPane.ts +++ b/src/modules/features/SettingDialogue/SettingPane.ts @@ -97,16 +97,6 @@ export function findAttrFromParent(el: HTMLElement, attr: string): string { return ""; } -export function wrapMemo(func: (arg: T) => void) { - let buf: T | undefined = undefined; - return (arg: T) => { - if (buf !== arg) { - func(arg); - buf = arg; - } - }; -} - /** * Defers pane construction until the owning settings page can confirm that its * render scope is still active. diff --git a/src/serviceFeatures/basicCommands.ts b/src/serviceFeatures/basicCommands.ts index 2bd622e5..8c6c3095 100644 --- a/src/serviceFeatures/basicCommands.ts +++ b/src/serviceFeatures/basicCommands.ts @@ -1,3 +1,4 @@ +import { createCommandCheck } from "@vrtmrz/obsidian-plugin-kit/command"; import { LOG_LEVEL_NOTICE } from "octagonal-wheels/common/logger"; import { fireAndForget } from "octagonal-wheels/promises"; import type { NecessaryServices } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; @@ -69,14 +70,12 @@ export function useBasicCommandsFeature(host: BasicCommandsHost): void { services.API.addCommand({ id: "livesync-dump", name: $msg("Copy database information for the active file"), - checkCallback: (checking) => { - const file = services.vault.getActiveFilePath(); - if (!file) return false; - if (!checking) { + checkCallback: createCommandCheck( + () => services.vault.getActiveFilePath(), + (file) => { fireAndForget(() => copyFileDatabaseInfo(createFileDatabaseInfoCore(host), file)); } - return true; - }, + ), }); services.API.addCommand({ @@ -115,13 +114,12 @@ export function useBasicCommandsFeature(host: BasicCommandsHost): void { services.API.addCommand({ id: "livesync-scan-files", name: "Scan storage and database again", - checkCallback: (checking) => { - if (!services.setting.currentSettings().useAdvancedMode) return false; - if (!checking) { + checkCallback: createCommandCheck( + () => services.setting.currentSettings().useAdvancedMode, + () => { fireAndForget(() => services.vault.scanVault(true)); } - return true; - }, + ), }); services.API.addCommand({ @@ -135,13 +133,12 @@ export function useBasicCommandsFeature(host: BasicCommandsHost): void { services.API.addCommand({ id: "livesync-abortsync", name: "Abort synchronization immediately", - checkCallback: (checking) => { - if (!services.setting.currentSettings().useAdvancedMode) return false; - if (!checking) { + checkCallback: createCommandCheck( + () => services.setting.currentSettings().useAdvancedMode, + () => { fireAndForget(() => services.replication.stopActiveTransfer()); } - return true; - }, + ), }); return Promise.resolve(true); diff --git a/src/serviceFeatures/basicCommands.unit.spec.ts b/src/serviceFeatures/basicCommands.unit.spec.ts index 356caa2a..0e10adf0 100644 --- a/src/serviceFeatures/basicCommands.unit.spec.ts +++ b/src/serviceFeatures/basicCommands.unit.spec.ts @@ -228,6 +228,49 @@ describe("useBasicCommandsFeature", () => { expect(adapter).not.toBe(fixture.host); }); + it("rechecks availability on execution and captures the current file only once", async () => { + const fixture = createFixture(); + await initialise(fixture); + vi.mocked(copyFileDatabaseInfo).mockClear(); + const dump = fixture.getCommand("livesync-dump"); + expect(dump.checkCallback?.(true)).toBe(true); + fixture.services.vault.getActiveFilePath.mockReturnValue(undefined); + expect(dump.checkCallback?.(false)).toBe(false); + expect(copyFileDatabaseInfo).not.toHaveBeenCalled(); + + fixture.services.vault.getActiveFilePath + .mockReset() + .mockReturnValueOnce("selected.md") + .mockReturnValue("later.md"); + expect(dump.checkCallback?.(false)).toBe(true); + await vi.waitFor(() => expect(copyFileDatabaseInfo).toHaveBeenCalledOnce()); + expect(fixture.services.vault.getActiveFilePath).toHaveBeenCalledOnce(); + expect(vi.mocked(copyFileDatabaseInfo).mock.calls[0][1]).toBe("selected.md"); + + fixture.settings.useAdvancedMode = true; + for (const id of ["livesync-scan-files", "livesync-abortsync"]) { + expect(fixture.getCommand(id).checkCallback?.(true)).toBe(true); + } + fixture.settings.useAdvancedMode = false; + for (const id of ["livesync-scan-files", "livesync-abortsync"]) { + expect(fixture.getCommand(id).checkCallback?.(false)).toBe(false); + } + expect(fixture.services.vault.scanVault).not.toHaveBeenCalled(); + expect(fixture.services.replication.stopActiveTransfer).not.toHaveBeenCalled(); + }); + + it("propagates an availability failure without running the command", async () => { + const fixture = createFixture(); + await initialise(fixture); + vi.mocked(copyFileDatabaseInfo).mockClear(); + const failure = new Error("Vault unavailable"); + fixture.services.vault.getActiveFilePath.mockImplementation(() => { + throw failure; + }); + expect(() => fixture.getCommand("livesync-dump").checkCallback?.(false)).toThrow(failure); + expect(copyFileDatabaseInfo).not.toHaveBeenCalled(); + }); + it("commits pending file events from the batch command", async () => { const fixture = createFixture(); await initialise(fixture); diff --git a/src/serviceFeatures/compatibilityReview.ts b/src/serviceFeatures/compatibilityReview.ts index 7c79f98f..bdc7b90a 100644 --- a/src/serviceFeatures/compatibilityReview.ts +++ b/src/serviceFeatures/compatibilityReview.ts @@ -1,6 +1,9 @@ import { fireAndForget } from "octagonal-wheels/promises"; import { VER } from "@vrtmrz/livesync-commonlib/compat/common/types"; -import type { LiveSyncCore } from "@/main.ts"; +import type { + NecessaryServices, + NecessaryServicesInterfaces, +} from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; import { COMPATIBILITY_PAUSE_SETTING_MESSAGE, DATABASE_COMPATIBILITY_VERSION_KEY, @@ -24,6 +27,16 @@ export interface CompatibilityReviewUi { clearReminder(): void; } +export type CompatibilityReviewDependencies = NecessaryServicesInterfaces< + "setting" | "config" | "vault" | "control", + never +>; + +export type CompatibilityReviewHost = NecessaryServices< + "setting" | "config" | "vault" | "control" | "appLifecycle" | "API", + never +>; + export class CompatibilityReviewController { private pause: CompatibilityPause | undefined; private activeReview: Promise | undefined; @@ -31,7 +44,7 @@ export class CompatibilityReviewController { private disposed = false; constructor( - private readonly core: LiveSyncCore, + private readonly core: CompatibilityReviewDependencies, private readonly ui: CompatibilityReviewUi, private readonly currentVersion: number = VER ) {} @@ -161,7 +174,10 @@ export class CompatibilityReviewController { } } -export function useCompatibilityReview(core: LiveSyncCore, ui: CompatibilityReviewUi): CompatibilityReviewController { +export function useCompatibilityReview( + core: CompatibilityReviewHost, + ui: CompatibilityReviewUi +): CompatibilityReviewController { const controller = new CompatibilityReviewController(core, ui); core.services.appLifecycle.onSettingLoaded.addHandler(() => controller.initialise()); core.services.appLifecycle.onLayoutReady.addHandler(() => { diff --git a/src/serviceFeatures/compatibilityReview.unit.spec.ts b/src/serviceFeatures/compatibilityReview.unit.spec.ts index 44a1b05b..61a508f0 100644 --- a/src/serviceFeatures/compatibilityReview.unit.spec.ts +++ b/src/serviceFeatures/compatibilityReview.unit.spec.ts @@ -1,4 +1,8 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"; +import type { + NecessaryServices, + NecessaryServicesInterfaces, +} from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; import { COMPATIBILITY_PAUSE_SETTING_MESSAGE, DATABASE_COMPATIBILITY_VERSION_KEY, @@ -101,6 +105,32 @@ function createFixture( } describe("compatibility review controller", () => { + it("accepts operation services without retaining an application-core contract", () => { + type Dependencies = NecessaryServicesInterfaces<"setting" | "config" | "vault" | "control", never>; + type ControllerHost = ConstructorParameters[0]; + + expectTypeOf().toExtend(); + expectTypeOf().toEqualTypeOf<"services" | "serviceModules">(); + expectTypeOf().toEqualTypeOf<"setting" | "config" | "vault" | "control">(); + expectTypeOf().toBeNever(); + }); + + it("composes the review from its operation services and lifecycle and command ports", () => { + type Dependencies = NecessaryServices< + "setting" | "config" | "vault" | "control" | "appLifecycle" | "API", + never + >; + type FeatureHost = Parameters[0]; + + expectTypeOf().toExtend(); + expectTypeOf().toEqualTypeOf<"services" | "serviceModules">(); + expectTypeOf().toEqualTypeOf< + "context" | "setting" | "config" | "vault" | "control" | "appLifecycle" | "API" + >(); + expectTypeOf().toBeNever(); + expectTypeOf>().toEqualTypeOf(); + }); + beforeEach(() => { vi.restoreAllMocks(); }); diff --git a/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts b/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts index a3f618d9..b0aa10cf 100644 --- a/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts +++ b/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, expectTypeOf, it, vi } from "vitest"; import { createServiceContext } from "@vrtmrz/livesync-commonlib/context"; import { InjectableConflictService } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableConflictService"; import { @@ -15,6 +15,12 @@ import { } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { EVENT_CONFLICT_CANCELLED } from "@vrtmrz/livesync-commonlib/compat/events/coreEvents"; import { NO_INTERACTION } from "@vrtmrz/livesync-commonlib/replication"; +import type { IAPIService } from "@vrtmrz/livesync-commonlib/compat/services/base/IService"; +import { + createInstanceLogFunction, + MARK_LOG_SEPARATOR, + type LogFunction, +} from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; import type { ConflictResolutionHost } from "./index"; import { createConflictResolutionOperations, useConflictResolutionFeature } from "./index"; import type { ConflictResolutionOperationsDependencies } from "./operations"; @@ -64,13 +70,15 @@ function createHarness(options: HarnessOptions = {}) { vault: { getActiveFilePath: activeFile }, }; const serviceModules = { databaseFileAccess, fileHandler, storageAccess }; + const log = createInstanceLogFunction("SF:ConflictResolution", services.API as unknown as IAPIService); if (options.compose !== false) { - useConflictResolutionFeature({ services, serviceModules } as unknown as ConflictResolutionHost); + useConflictResolutionFeature({ services, serviceModules, log } as unknown as ConflictResolutionHost); } return { addLog, + log, conflict, context, databaseFileAccess, @@ -151,6 +159,87 @@ function createOperationsHarness() { } describe("conflict resolution serviceFeature", () => { + it("declares a borrowed logger and only the services used by conflict resolution", () => { + expectTypeOf().toEqualTypeOf< + "context" | "appLifecycle" | "conflict" | "database" | "replication" | "setting" | "vault" + >(); + expectTypeOf().toEqualTypeOf(); + }); + + it("uses the injected logger for the checker and resolver without an API service", async () => { + const harness = createHarness({ + compose: false, + settings: { checkConflictOnlyOnOpen: true }, + activeFile: "active.md" as FilePathWithPrefix, + }); + const { API, ...services } = harness.services; + const log = vi.fn(); + useConflictResolutionFeature({ + services, + serviceModules: harness.serviceModules, + log, + } as unknown as ConflictResolutionHost); + harness.databaseFileAccess.fetchEntryMeta.mockResolvedValue(false); + + await harness.conflict.queueCheckForIfOpen("other.md" as FilePathWithPrefix); + await harness.conflict.resolveByNewest("missing.md" as FilePathWithPrefix); + + expect(log).toHaveBeenNthCalledWith( + 1, + "other.md is conflicted, merging process has been postponed.", + LOG_LEVEL_NOTICE + ); + expect(log).toHaveBeenNthCalledWith(2, "Could not get current revision of missing.md"); + expect(API.addLog).not.toHaveBeenCalled(); + }); + + it("keeps separately selected loggers isolated when legacy API services are shared", async () => { + const first = createHarness({ compose: false }); + const second = createHarness({ compose: false }); + const firstLog = vi.fn(); + const secondLog = vi.fn(); + const sharedAPI = first.services.API; + useConflictResolutionFeature({ + services: first.services, + serviceModules: first.serviceModules, + log: firstLog, + } as unknown as ConflictResolutionHost); + useConflictResolutionFeature({ + services: { ...second.services, API: sharedAPI }, + serviceModules: second.serviceModules, + log: secondLog, + } as unknown as ConflictResolutionHost); + first.databaseFileAccess.fetchEntryMeta.mockResolvedValue(false); + second.databaseFileAccess.fetchEntryMeta.mockResolvedValue(false); + + await first.conflict.resolveByNewest("first.md" as FilePathWithPrefix); + await second.conflict.resolveByNewest("second.md" as FilePathWithPrefix); + + expect(firstLog).toHaveBeenCalledExactlyOnceWith("Could not get current revision of first.md"); + expect(secondLog).toHaveBeenCalledExactlyOnceWith("Could not get current revision of second.md"); + expect(sharedAPI.addLog).not.toHaveBeenCalled(); + }); + + it("retains the prefix, level, and key selected by the host logger", async () => { + const harness = createHarness({ compose: false }); + const { API, ...services } = harness.services; + useConflictResolutionFeature({ + services, + serviceModules: harness.serviceModules, + log: harness.log, + } as unknown as ConflictResolutionHost); + + await harness.conflict.resolveByDeletingRevision("same.md" as FilePathWithPrefix, "1-old", "same"); + await harness.conflict.resolveAllConflictedFilesByNewerOnes(); + + expect(API.addLog).toHaveBeenCalledWith( + `[SF:ConflictResolution]${MARK_LOG_SEPARATOR} same.md has been merged automatically`, + LOG_LEVEL_INFO, + "" + ); + expect(API.addLog).toHaveBeenLastCalledWith("Done!", LOG_LEVEL_NOTICE, "resolveAllConflictedFilesByNewerOnes"); + }); + it("keeps resolver operations on narrow collaborators and extension seams", async () => { const harness = createOperationsHarness(); const path = "same.md" as FilePathWithPrefix; @@ -557,6 +646,7 @@ describe("conflict resolution serviceFeature", () => { useConflictResolutionFeature({ services: harness.services, serviceModules: harness.serviceModules, + log: harness.log, } as unknown as ConflictResolutionHost); for (const registration of registrations) { diff --git a/src/serviceFeatures/conflictResolution/index.ts b/src/serviceFeatures/conflictResolution/index.ts index 2d446681..62cd7bf1 100644 --- a/src/serviceFeatures/conflictResolution/index.ts +++ b/src/serviceFeatures/conflictResolution/index.ts @@ -1,25 +1,23 @@ -import type { NecessaryServices } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; -import { createInstanceLogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; -import type { InjectableConflictService } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableConflictService"; -import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import { + createServiceFeature, + type NecessaryServices, +} from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; +import type { LogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; +import type { InjectableServiceHub } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableServiceHub"; import { createConflictCheckingHandlers } from "./checker"; import { createConflictResolutionOperations } from "./operations"; -type ConflictResolutionServices = NecessaryServices< - "API" | "appLifecycle" | "conflict" | "database" | "replication" | "setting" | "vault", - "databaseFileAccess" | "fileHandler" | "storageAccess" ->; - -export type ConflictResolutionHost = ConflictResolutionServices & { - readonly services: ConflictResolutionServices["services"] & { - readonly conflict: InjectableConflictService; - }; +export type ConflictResolutionHost = NecessaryServices< + "appLifecycle" | "conflict" | "database" | "replication" | "setting" | "vault", + "databaseFileAccess" | "fileHandler" | "storageAccess", + InjectableServiceHub +> & { + readonly log: LogFunction; }; -/** Compose the host-neutral conflict checker and resolver handlers. */ -export function useConflictResolutionFeature(host: ConflictResolutionHost): void { - const { services, serviceModules } = host; - const log = createInstanceLogFunction("SF:ConflictResolution", services.API); +/** Compose the host-neutral conflict handlers with the host's borrowed logger. */ +export const useConflictResolutionFeature = createServiceFeature((host: ConflictResolutionHost): void => { + const { services, serviceModules, log } = host; const operations = createConflictResolutionOperations({ events: services.context.events, databaseFileAccess: serviceModules.databaseFileAccess, @@ -48,7 +46,7 @@ export function useConflictResolutionFeature(host: ConflictResolutionHost): void services.conflict.resolve.setHandler(operations.resolve); services.conflict.resolveByNewest.setHandler(operations.resolveByNewest); services.conflict.resolveAllConflictedFilesByNewerOnes.setHandler(operations.resolveAllConflictedFilesByNewerOnes); -} +}); export { createConflictCheckingHandlers } from "./checker"; export type { ConflictCheckingDependencies, ConflictCheckingHandlers } from "./checker"; diff --git a/src/serviceFeatures/onLayoutReady/enablei18n.ts b/src/serviceFeatures/onLayoutReady/enablei18n.ts index 5a83eafb..74f367eb 100644 --- a/src/serviceFeatures/onLayoutReady/enablei18n.ts +++ b/src/serviceFeatures/onLayoutReady/enablei18n.ts @@ -1,9 +1,12 @@ import { getLanguage, Notice, requireApiVersion } from "@/deps"; +import type { NecessaryServices } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; import { createServiceFeature } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; import { SUPPORTED_I18N_LANGS, type I18N_LANGS } from "@/common/rosetta"; import { $msg, __onMissingTranslation, setLang } from "@/common/translation"; import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger"; +type EnableI18nHost = NecessaryServices<"setting" | "API" | "appLifecycle", never>; + function tryGetLanguage(onError: (error: unknown) => void) { if (requireApiVersion("1.8.7")) { try { @@ -48,7 +51,8 @@ class ObsidianLanguageAppliedNotice { } } -export const enableI18nFeature = createServiceFeature(async ({ services: { setting, API, appLifecycle } }) => { +export const enableI18nFeature = createServiceFeature(async (host: EnableI18nHost) => { + const { setting, API, appLifecycle } = host.services; // Clear missing translation handler to avoid unnecessary warnings. __onMissingTranslation(() => {}); let isChanged = false; diff --git a/src/serviceFeatures/onLayoutReady/enablei18n.unit.spec.ts b/src/serviceFeatures/onLayoutReady/enablei18n.unit.spec.ts index 8f88eb62..960c414d 100644 --- a/src/serviceFeatures/onLayoutReady/enablei18n.unit.spec.ts +++ b/src/serviceFeatures/onLayoutReady/enablei18n.unit.spec.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from "vitest"; const noticeState = vi.hoisted(() => ({ instances: [] as Array<{ hide: ReturnType; duration: number }>, @@ -63,6 +63,14 @@ describe("automatic display language", () => { vi.restoreAllMocks(); }); + it("declares only the services it needs and returns a boolean promise", () => { + type FeatureHost = Parameters[0]; + + expectTypeOf().toEqualTypeOf<"context" | "setting" | "API" | "appLifecycle">(); + expectTypeOf().toBeNever(); + expectTypeOf>().toEqualTypeOf>(); + }); + it("lets start-up continue and opens translation details only from a persistent Notice", async () => { const settings = { displayLanguage: "" }; const applyPartial = vi.fn(async (partial: Partial) => Object.assign(settings, partial)); diff --git a/src/serviceFeatures/setupObsidian/setupUri.ts b/src/serviceFeatures/setupObsidian/setupUri.ts index 3295c5d3..96b33378 100644 --- a/src/serviceFeatures/setupObsidian/setupUri.ts +++ b/src/serviceFeatures/setupObsidian/setupUri.ts @@ -1,3 +1,4 @@ +import { createCommandCheck } from "@vrtmrz/obsidian-plugin-kit/command"; import { LOG_LEVEL_NOTICE, type ObsidianLiveSyncSettings } from "@vrtmrz/livesync-commonlib/compat/common/types"; import type { LogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; import { createInstanceLogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; @@ -112,33 +113,40 @@ export function useSetupURIFeature(host: NecessaryServices<"API" | "UI" | "setti host.services.API.addCommand({ id: "livesync-copysetupuri", name: "Copy settings as a new setup URI", - checkCallback: (checking) => { - if (!host.services.setting.currentSettings().isConfigured) return false; - if (!checking) fireAndForget(copySetupURI(host, log)); - return true; - }, + checkCallback: createCommandCheck( + () => host.services.setting.currentSettings().isConfigured, + () => { + fireAndForget(copySetupURI(host, log)); + } + ), }); host.services.API.addCommand({ id: "livesync-copysetupuri-short", name: "Copy settings as a new setup URI (With customization sync)", - checkCallback: (checking) => { - const settings = host.services.setting.currentSettings(); - if (!settings.isConfigured || !settings.usePluginSync) return false; - if (!checking) fireAndForget(copySetupURI(host, log, false)); - return true; - }, + checkCallback: createCommandCheck( + () => { + const settings = host.services.setting.currentSettings(); + return settings.isConfigured && settings.usePluginSync; + }, + () => { + fireAndForget(copySetupURI(host, log, false)); + } + ), }); host.services.API.addCommand({ id: "livesync-copysetupurifull", name: "Copy settings as a new setup URI (Full)", - checkCallback: (checking) => { - const settings = host.services.setting.currentSettings(); - if (!settings.isConfigured || !settings.useAdvancedMode) return false; - if (!checking) fireAndForget(copySetupURIFull(host, log)); - return true; - }, + checkCallback: createCommandCheck( + () => { + const settings = host.services.setting.currentSettings(); + return settings.isConfigured && settings.useAdvancedMode; + }, + () => { + fireAndForget(copySetupURIFull(host, log)); + } + ), }); host.services.context.events.onEvent(EVENT_REQUEST_COPY_SETUP_URI, () => diff --git a/src/serviceFeatures/setupObsidian/setupUri.unit.spec.ts b/src/serviceFeatures/setupObsidian/setupUri.unit.spec.ts index 8a23d50a..9f632f67 100644 --- a/src/serviceFeatures/setupObsidian/setupUri.unit.spec.ts +++ b/src/serviceFeatures/setupObsidian/setupUri.unit.spec.ts @@ -221,7 +221,7 @@ describe("setupObsidian/setupUri", () => { }, UI: { confirm: { - askString: vi.fn(() => "pass"), + askString: vi.fn(async () => false), }, promptCopyToClipboard: vi.fn(() => true), }, @@ -269,7 +269,7 @@ describe("setupObsidian/setupUri", () => { }, UI: { confirm: { - askString: vi.fn(() => "pass"), + askString: vi.fn(async () => false), }, promptCopyToClipboard: vi.fn(() => true), }, @@ -292,5 +292,12 @@ describe("setupObsidian/setupUri", () => { settings.useAdvancedMode = true; expect(command("livesync-copysetupuri-short").checkCallback?.(true)).toBe(true); expect(command("livesync-copysetupurifull").checkCallback?.(true)).toBe(true); + expect(host.services.UI.confirm.askString).not.toHaveBeenCalled(); + settings.isConfigured = false; + for (const registered of commands) expect(registered.checkCallback?.(false)).toBe(false); + expect(host.services.UI.confirm.askString).not.toHaveBeenCalled(); + settings.isConfigured = true; + for (const registered of commands) expect(registered.checkCallback?.(false)).toBe(true); + expect(host.services.UI.confirm.askString).toHaveBeenCalledTimes(3); }); }); diff --git a/src/serviceFeatures/useDatabaseDiagnostics.ts b/src/serviceFeatures/useDatabaseDiagnostics.ts index 2fa974c8..85e582b9 100644 --- a/src/serviceFeatures/useDatabaseDiagnostics.ts +++ b/src/serviceFeatures/useDatabaseDiagnostics.ts @@ -1,3 +1,4 @@ +import { createCommandCheck } from "@vrtmrz/obsidian-plugin-kit/command"; import { createServiceFeature, type NecessaryServices, @@ -46,22 +47,23 @@ export const useDatabaseDiagnosticsFeature = createServiceFeature((host: Databas id: "analyse-database", name: "Analyse Database Usage (advanced)", icon: "database-search", - checkCallback: (checking) => { - if (!services.setting.currentSettings().useAdvancedMode || !services.database.isDatabaseReady()) - return false; - if (!checking) void open("usage"); - return true; - }, + checkCallback: createCommandCheck( + () => services.setting.currentSettings().useAdvancedMode && services.database.isDatabaseReady(), + () => { + void open("usage"); + } + ), }); services.API.addCommand({ id: "inspect-database-integrity", name: $msg("Inspect database integrity"), icon: "database-search", - checkCallback: (checking) => { - if (!services.database.isDatabaseReady()) return false; - if (!checking) void open("integrity"); - return true; - }, + checkCallback: createCommandCheck( + () => services.database.isDatabaseReady(), + () => { + void open("integrity"); + } + ), }); return Promise.resolve(true); }); diff --git a/src/serviceFeatures/useDatabaseDiagnostics.unit.spec.ts b/src/serviceFeatures/useDatabaseDiagnostics.unit.spec.ts index 8372b5ef..df948e2a 100644 --- a/src/serviceFeatures/useDatabaseDiagnostics.unit.spec.ts +++ b/src/serviceFeatures/useDatabaseDiagnostics.unit.spec.ts @@ -82,6 +82,26 @@ describe("database diagnostics serviceFeature", () => { expect(data.openDialog).not.toHaveBeenCalled(); }); + it.each(["analyse-database", "inspect-database-integrity"])( + "rechecks database availability before executing %s", + async (id) => { + const data = fixture(); + data.settings.useAdvancedMode = true; + for (const initialise of data.initialise) await initialise(); + const command = data.commands.find((candidate) => candidate.id === id)!; + expect(command.checkCallback(true)).toBe(true); + expect(data.openDialog).not.toHaveBeenCalled(); + data.setReady(false); + expect(command.checkCallback(false)).toBe(false); + expect(data.openDialog).not.toHaveBeenCalled(); + data.setReady(true); + expect(command.checkCallback(false)).toBe(true); + expect(data.openDialog).toHaveBeenCalledOnce(); + expect(data.openDialog.mock.calls[0][1].kind).toBe(id === "analyse-database" ? "usage" : "integrity"); + data.close(); + } + ); + it("uses the existing dialogue manager and performs no analysis until the run choice is submitted", async () => { vi.mocked(runDatabaseDiagnostic).mockClear(); const data = fixture(); diff --git a/src/serviceFeatures/useP2PReplicatorUI.ts b/src/serviceFeatures/useP2PReplicatorUI.ts index afa1b112..09b60fb4 100644 --- a/src/serviceFeatures/useP2PReplicatorUI.ts +++ b/src/serviceFeatures/useP2PReplicatorUI.ts @@ -1,6 +1,6 @@ import { eventHub, EVENT_REQUEST_OPEN_P2P } from "@/common/events"; import type { NecessaryServices } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; -import { type UseP2PReplicatorResult } from "@vrtmrz/livesync-commonlib/compat/replication/trystero/UseP2PReplicatorResult"; +import type { P2PServiceViews } from "@vrtmrz/livesync-commonlib/p2p"; import { P2PServerStatusPaneView, VIEW_TYPE_P2P_SERVER_STATUS, @@ -47,22 +47,9 @@ export function hasP2PConfiguration(settings: Partial) */ export function useP2PReplicatorUI( - host: NecessaryServices< - | "API" - | "appLifecycle" - | "setting" - | "vault" - | "database" - | "databaseEvents" - | "keyValueDB" - | "replication" - | "config" - | "UI" - | "replicator", - never - >, + host: NecessaryServices<"API" | "appLifecycle" | "setting" | "replicator", never>, core: LiveSyncCore, - replicator: UseP2PReplicatorResult, + replicator: P2PServiceViews, openInteractiveReplication: OpenInteractiveP2PReplication ) { const api = host.services.API as { diff --git a/src/serviceFeatures/useP2PReplicatorUI.unit.spec.ts b/src/serviceFeatures/useP2PReplicatorUI.unit.spec.ts index 87e4cf4f..650c864d 100644 --- a/src/serviceFeatures/useP2PReplicatorUI.unit.spec.ts +++ b/src/serviceFeatures/useP2PReplicatorUI.unit.spec.ts @@ -1,4 +1,6 @@ -import { describe, expect, it, vi } from "vitest"; +import { describe, expect, expectTypeOf, it, vi } from "vitest"; +import type { NecessaryServices } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; +import type { P2PServiceViews } from "@vrtmrz/livesync-commonlib/p2p"; import { createServiceContext } from "@vrtmrz/livesync-commonlib/context"; import { eventHub, EVENT_REQUEST_OPEN_P2P } from "@/common/events"; @@ -16,6 +18,19 @@ import { useP2PReplicatorUI } from "./useP2PReplicatorUI"; const noopOpenInteractiveReplication = () => Promise.resolve(false); describe("useP2PReplicatorUI commands", () => { + it("accepts only the UI services and focused P2P views", () => { + type Dependencies = NecessaryServices<"API" | "appLifecycle" | "setting" | "replicator", never>; + type Arguments = Parameters; + + expectTypeOf().toExtend(); + expectTypeOf().toEqualTypeOf< + "context" | "API" | "appLifecycle" | "setting" | "replicator" + >(); + expectTypeOf().toBeNever(); + expectTypeOf().toExtend(); + expectTypeOf().toEqualTypeOf(); + }); + it("waits for settings to load before deciding whether to show the P2P ribbon", async () => { let initialise: (() => Promise) | undefined; let settingLoaded: (() => Promise) | undefined; From b9dcb0d4c7c4f55729f262e252794370d18769ff Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Thu, 29 Oct 2026 15:04:09 +0000 Subject: [PATCH 05/24] Share application adapter and diagnostic helpers --- devs.md | 2 +- src/apps/caseInsensitiveFileLookup.ts | 23 ++ .../cli/adapters/NodeFileSystemAdapter.ts | 28 +- .../NodeFileSystemAdapter.unit.spec.ts | 77 ++++ .../managers/CLIStorageEventManagerAdapter.ts | 30 +- ...CLIStorageEventManagerAdapter.unit.spec.ts | 24 ++ .../cli/serviceModules/CLIServiceModules.ts | 39 +- src/apps/cli/testdeno/test-setup-put-cat.ts | 15 + .../composeSharedServiceModules.ts | 50 +++ .../serviceComposition.unit.spec.ts | 379 ++++++++++++++++++ .../webapp/adapters/FSAPIFileSystemAdapter.ts | 29 +- .../adapters/FSAPIStorageAdapter.unit.spec.ts | 154 +++++++ src/apps/webapp/adapters/FSAPIVaultAdapter.ts | 33 +- .../FSAPIStorageEventManagerAdapter.ts | 28 +- ...APIStorageEventManagerAdapter.unit.spec.ts | 40 ++ .../serviceModules/FSAPIServiceModules.ts | 39 +- src/apps/webpeer/src/WebPeerRuntime.ts | 2 +- .../reviewHarnessFileContentHashBenchmark.ts | 35 +- ...rnessFileContentHashBenchmark.unit.spec.ts | 44 ++ .../reviewHarnessHeapSampling.ts | 34 ++ .../ReviewHarness/reviewHarnessIdBenchmark.ts | 33 +- .../reviewHarnessIdBenchmark.unit.spec.ts | 1 + .../SettingDialogue/utilFixCouchDBSetting.ts | 25 +- .../SetupWizard/dialogs/utilCheckCouchDB.ts | 30 +- .../features/couchDBDiagnosticValues.ts | 19 + .../couchDBDiagnosticValues.unit.spec.ts | 29 ++ 26 files changed, 937 insertions(+), 305 deletions(-) create mode 100644 src/apps/caseInsensitiveFileLookup.ts create mode 100644 src/apps/serviceModules/composeSharedServiceModules.ts create mode 100644 src/apps/serviceModules/serviceComposition.unit.spec.ts create mode 100644 src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.unit.spec.ts create mode 100644 src/features/ReviewHarness/reviewHarnessHeapSampling.ts create mode 100644 src/modules/features/couchDBDiagnosticValues.ts create mode 100644 src/modules/features/couchDBDiagnosticValues.unit.spec.ts diff --git a/devs.md b/devs.md index a9acec7c..034df69c 100644 --- a/devs.md +++ b/devs.md @@ -158,7 +158,7 @@ Commonlib's `targetFilter.ts` and `prepareDatabaseForUse.ts` demonstrate the int Use interaction-based, London School unit tests for the composition boundary. Verify collaborator calls, ordering, failure short-circuiting, and handler registration, then test the focused state owner for its transitions and invariants. If a test needs a broad core fixture, a large class mock, deep mock chains, or unrelated Services, treat that friction as a design-review signal and consider a private context with narrower functions before adding more test machinery. -See [Service feature and legacy Module boundaries](docs/design_docs/service_feature_and_legacy_module_boundaries.md) for the selection criteria, current examples, reasons to avoid new `AbstractModule` subclasses, incremental migration guidance, and test shapes. Commonlib's [service feature composition guide](https://github.com/vrtmrz/livesync-commonlib/blob/main/docs/service-feature-composition.md) defines the shared host-neutral boundary. +See [Service feature and legacy Module boundaries](docs/design_docs/service_feature_and_legacy_module_boundaries.md) for the selection criteria, current examples, reasons to avoid new `AbstractModule` subclasses, incremental migration guidance, and test shapes. Commonlib's [service feature composition guide](https://github.com/vrtmrz/livesync-commonlib/blob/main/docs/service-feature-composition.md) defines the shared host-neutral boundary. Fancy Kit's [shared runtime composition guide](https://github.com/vrtmrz/fancy-kit/blob/main/docs/runtime-composition.md) maps content application, cleanup, progress, and host adapters to their owning APIs, with their unreleased status and consumer responsibilities. Legacy Modules remain grouped by directory: diff --git a/src/apps/caseInsensitiveFileLookup.ts b/src/apps/caseInsensitiveFileLookup.ts new file mode 100644 index 00000000..9be18f36 --- /dev/null +++ b/src/apps/caseInsensitiveFileLookup.ts @@ -0,0 +1,23 @@ +export async function findCaseInsensitiveFile( + requestedPath: string, + findExact: () => Promise, + cachedFiles: ReadonlyMap, + scan: () => Promise +): Promise { + const exact = await findExact(); + if (exact) return exact; + + const lowerPath = requestedPath.toLowerCase(); + const findCached = (): T | null => { + for (const [cachedPath, cachedFile] of cachedFiles) { + if (cachedPath.toLowerCase() === lowerPath) return cachedFile; + } + return null; + }; + + const cached = findCached(); + if (cached) return cached; + + await scan(); + return findCached(); +} diff --git a/src/apps/cli/adapters/NodeFileSystemAdapter.ts b/src/apps/cli/adapters/NodeFileSystemAdapter.ts index 6cb8f458..9ba123e4 100644 --- a/src/apps/cli/adapters/NodeFileSystemAdapter.ts +++ b/src/apps/cli/adapters/NodeFileSystemAdapter.ts @@ -8,6 +8,7 @@ import { NodeVaultAdapter } from "./NodeVaultAdapter"; import type { NodeFile, NodeFolder, NodeStat } from "./NodeTypes"; import { path } from "@vrtmrz/livesync-commonlib/node"; import type { CliDiagnosticReporter } from "@/apps/cli/cliOutput"; +import { findCaseInsensitiveFile } from "@/apps/caseInsensitiveFileLookup"; /** * Complete file system adapter implementation for Node.js @@ -87,27 +88,12 @@ export class NodeFileSystemAdapter implements IFileSystemAdapter this.getAbstractFileByPath(pathStr), + this.fileCache, + () => this.scanDirectory() + ); } async getFiles(): Promise { diff --git a/src/apps/cli/adapters/NodeFileSystemAdapter.unit.spec.ts b/src/apps/cli/adapters/NodeFileSystemAdapter.unit.spec.ts index 7d0fbaae..1791f6d5 100644 --- a/src/apps/cli/adapters/NodeFileSystemAdapter.unit.spec.ts +++ b/src/apps/cli/adapters/NodeFileSystemAdapter.unit.spec.ts @@ -124,6 +124,83 @@ describe("NodeFileSystemAdapter file enumeration", () => { }); }); +describe("NodeFileSystemAdapter case-insensitive path lookup", () => { + const tempDirs: string[] = []; + + async function createVault(files: string[] = []) { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), "livesync-cli-insensitive-")); + tempDirs.push(directory); + for (const file of files) { + await fs.mkdir(path.dirname(path.join(directory, file)), { recursive: true }); + await fs.writeFile(path.join(directory, file), `content of ${file}`); + } + return { directory, adapter: new NodeFileSystemAdapter(directory) }; + } + + afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((directory) => fs.rm(directory, { recursive: true, force: true }))); + }); + + it("returns an exact path without scanning the directory", async () => { + const { adapter } = await createVault(["Calculus.md"]); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("Calculus.md")).resolves.toMatchObject({ + path: "Calculus.md", + }); + + expect(scanDirectory).not.toHaveBeenCalled(); + }); + + it("returns a cached case-insensitive match without rescanning", async () => { + const { adapter } = await createVault(["Calculus.md"]); + await adapter.scanDirectory(); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("calculus.md")).resolves.toMatchObject({ + path: "Calculus.md", + }); + + expect(scanDirectory).not.toHaveBeenCalled(); + }); + + it("rescans once and returns a newly cached case-insensitive match", async () => { + const { adapter } = await createVault(["Calculus.md"]); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("calculus.md")).resolves.toMatchObject({ + path: "Calculus.md", + }); + + expect(scanDirectory).toHaveBeenCalledOnce(); + await expect(adapter.getAbstractFileByPath("Calculus.md")).resolves.toMatchObject({ path: "Calculus.md" }); + }); + + it("returns null after one scan when no cached path matches", async () => { + const { adapter } = await createVault(["other.md"]); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("missing.md")).resolves.toBeNull(); + + expect(scanDirectory).toHaveBeenCalledOnce(); + }); + + it("returns null and reports a directory scan failure", async () => { + const missingDirectory = path.join(os.tmpdir(), `livesync-cli-insensitive-missing-${Date.now()}`); + const reportDiagnostic = vi.fn(); + const adapter = new NodeFileSystemAdapter(missingDirectory, reportDiagnostic); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("missing.md")).resolves.toBeNull(); + + expect(scanDirectory).toHaveBeenCalledOnce(); + expect(reportDiagnostic).toHaveBeenCalledWith( + expect.stringContaining("Error scanning directory"), + expect.any(Error) + ); + }); +}); + describe("NodeFileSystemAdapter Unicode path resolution", () => { const tempDirs: string[] = []; diff --git a/src/apps/cli/managers/CLIStorageEventManagerAdapter.ts b/src/apps/cli/managers/CLIStorageEventManagerAdapter.ts index e6369fce..f4485044 100644 --- a/src/apps/cli/managers/CLIStorageEventManagerAdapter.ts +++ b/src/apps/cli/managers/CLIStorageEventManagerAdapter.ts @@ -2,7 +2,6 @@ import type { FilePath, UXFileInfoStub, UXInternalFileInfoStub } from "@vrtmrz/l import type { FileEventItem } from "@vrtmrz/livesync-commonlib/compat/common/types"; import type { IStorageEventManagerAdapter } from "@vrtmrz/livesync-commonlib/compat/managers/adapters"; import type { - IStorageEventTypeGuardAdapter, IStorageEventPersistenceAdapter, IStorageEventWatchAdapter, IStorageEventStatusAdapter, @@ -15,30 +14,7 @@ import { watch as chokidarWatch, type FSWatcher } from "chokidar"; import type { IgnoreRules } from "@/apps/cli/serviceModules/IgnoreRules"; import { fsPromises as fs, getNodeFileCreationTime, path, type Stats } from "@vrtmrz/livesync-commonlib/node"; import type { CliDiagnosticReporter } from "@/apps/cli/cliOutput"; - -/** - * CLI-specific type guard adapter - */ -class CLITypeGuardAdapter implements IStorageEventTypeGuardAdapter { - isFile(file: unknown): file is NodeFile { - return !!( - file && - typeof file === "object" && - "path" in file && - "stat" in file && - !(file as { isFolder?: boolean }).isFolder - ); - } - - isFolder(item: unknown): item is NodeFolder { - return !!( - item && - typeof item === "object" && - "path" in item && - (item as { isFolder?: boolean }).isFolder === true - ); - } -} +import { NodeTypeGuardAdapter } from "@/apps/cli/adapters/NodeTypeGuardAdapter"; /** * CLI-specific persistence adapter (file-based snapshot) @@ -211,7 +187,7 @@ class CLIWatchAdapter implements IStorageEventWatchAdapter { * Composite adapter for CLI StorageEventManager */ export class CLIStorageEventManagerAdapter implements IStorageEventManagerAdapter { - readonly typeGuard: CLITypeGuardAdapter; + readonly typeGuard: NodeTypeGuardAdapter; readonly persistence: CLIPersistenceAdapter; readonly watch: CLIWatchAdapter; readonly status: CLIStatusAdapter; @@ -223,7 +199,7 @@ export class CLIStorageEventManagerAdapter implements IStorageEventManagerAdapte watchEnabled: boolean = false, reportDiagnostic: CliDiagnosticReporter = () => undefined ) { - this.typeGuard = new CLITypeGuardAdapter(); + this.typeGuard = new NodeTypeGuardAdapter(); this.persistence = new CLIPersistenceAdapter(basePath, reportDiagnostic); this.watch = new CLIWatchAdapter(basePath, ignoreRules, watchEnabled, reportDiagnostic); this.status = new CLIStatusAdapter(); diff --git a/src/apps/cli/managers/CLIStorageEventManagerAdapter.unit.spec.ts b/src/apps/cli/managers/CLIStorageEventManagerAdapter.unit.spec.ts index bf8f6712..d294e817 100644 --- a/src/apps/cli/managers/CLIStorageEventManagerAdapter.unit.spec.ts +++ b/src/apps/cli/managers/CLIStorageEventManagerAdapter.unit.spec.ts @@ -201,3 +201,27 @@ describe("CLIStorageEventManagerAdapter", () => { processExitSpy.mockRestore(); }); }); + +describe("CLIStorageEventManagerAdapter type guard", () => { + const typeGuard = new CLIStorageEventManagerAdapter("/base").typeGuard; + + it.each([ + { label: "null", value: null, expected: false }, + { label: "an object without a path", value: { stat: {} }, expected: false }, + { label: "an object without a stat", value: { path: "note.md" }, expected: false }, + { label: "a file-shaped object", value: { path: "note.md", stat: {} }, expected: true }, + { label: "a folder-shaped object", value: { path: "folder", isFolder: true }, expected: false }, + ])("classifies $label as a file", ({ value, expected }) => { + expect(typeGuard.isFile(value)).toBe(expected); + }); + + it.each([ + { label: "null", value: null, expected: false }, + { label: "an object without a path", value: { isFolder: true }, expected: false }, + { label: "an object without the folder marker", value: { path: "folder" }, expected: false }, + { label: "a folder-shaped object", value: { path: "folder", isFolder: true }, expected: true }, + { label: "a file-shaped object", value: { path: "note.md", stat: {} }, expected: false }, + ])("classifies $label as a folder", ({ value, expected }) => { + expect(typeGuard.isFolder(value)).toBe(expected); + }); +}); diff --git a/src/apps/cli/serviceModules/CLIServiceModules.ts b/src/apps/cli/serviceModules/CLIServiceModules.ts index 29b9df90..53cdf12f 100644 --- a/src/apps/cli/serviceModules/CLIServiceModules.ts +++ b/src/apps/cli/serviceModules/CLIServiceModules.ts @@ -1,6 +1,4 @@ import type { InjectableServiceHub } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableServiceHub"; -import { ServiceRebuilder } from "@vrtmrz/livesync-commonlib/compat/serviceModules/Rebuilder"; -import { ServiceFileHandler } from "@/serviceModules/FileHandler"; import { StorageAccessManager } from "@vrtmrz/livesync-commonlib/compat/managers/StorageProcessingManager"; import type { LiveSyncBaseCore } from "@/LiveSyncBaseCore"; import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context"; @@ -10,7 +8,7 @@ import { ServiceDatabaseFileAccessCLI } from "./DatabaseFileAccess"; import { StorageEventManagerCLI } from "@/apps/cli/managers/StorageEventManagerCLI"; import type { ServiceModules } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; import type { IgnoreRules } from "./IgnoreRules"; -import { createFileReflectionProvenance } from "@/serviceModules/FileReflectionProvenance"; +import { composeSharedServiceModules } from "@/apps/serviceModules/composeSharedServiceModules"; /** * Initialize service modules for CLI version @@ -82,40 +80,7 @@ export function initialiseServiceModulesCLI( vault: services.vault, }); - // File handler (platform-independent) - const fileHandler = new ServiceFileHandler({ - events: services.context.events, - API: services.API, - databaseFileAccess: databaseFileAccess, - conflict: services.conflict, - setting: services.setting, - fileProcessing: services.fileProcessing, - vault: services.vault, - path: services.path, - replication: services.replication, - storageAccess: storageAccess, - fileReflectionProvenance: createFileReflectionProvenance(services.keyValueDB), - }); - - // Rebuilder (platform-independent) - const rebuilder = new ServiceRebuilder({ - path: services.path, - events: services.context.events, - API: services.API, - database: services.database, - appLifecycle: services.appLifecycle, - setting: services.setting, - remote: services.remote, - databaseEvents: services.databaseEvents, - replication: services.replication, - replicator: services.replicator, - UI: services.UI, - vault: services.vault, - fileHandler: fileHandler, - fileProcessing: services.fileProcessing, - storageAccess: storageAccess, - control: services.control, - }); + const { fileHandler, rebuilder } = composeSharedServiceModules(services, databaseFileAccess, storageAccess); return { rebuilder, diff --git a/src/apps/cli/testdeno/test-setup-put-cat.ts b/src/apps/cli/testdeno/test-setup-put-cat.ts index 1df861e4..86f04d9e 100644 --- a/src/apps/cli/testdeno/test-setup-put-cat.ts +++ b/src/apps/cli/testdeno/test-setup-put-cat.ts @@ -70,6 +70,21 @@ Deno.test("CLI file operations: push / cat / ls / info / rm / resolve / cat-rev console.log("[PASS] push/cat roundtrip matched"); }); + await t.step("push/pull binary roundtrip", async () => { + const source = workDir.join("binary-source.bin"); + const restored = workDir.join("binary-restored.bin"); + const remotePath = "test/blob-roundtrip.bin"; + const content = Uint8Array.from({ length: 1025 }, (_, index) => index % 256); + await Deno.writeFile(source, content); + + await run("push", source, remotePath); + await run("pull", remotePath, restored); + + assertEquals(await Deno.readFile(restored), content, "Binary push/pull must preserve every byte"); + const info = JSON.parse(await run("info", remotePath)); + assertEquals(info.size, content.byteLength, "Binary Metadata must retain the original byte length"); + }); + // ------------------------------------------------------------------ // ls: single file // ------------------------------------------------------------------ diff --git a/src/apps/serviceModules/composeSharedServiceModules.ts b/src/apps/serviceModules/composeSharedServiceModules.ts new file mode 100644 index 00000000..c5698106 --- /dev/null +++ b/src/apps/serviceModules/composeSharedServiceModules.ts @@ -0,0 +1,50 @@ +import type { InjectableServiceHub } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableServiceHub"; +import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import type { DatabaseFileAccess } from "@vrtmrz/livesync-commonlib/compat/interfaces/DatabaseFileAccess"; +import type { ServiceModules } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; +import type { StorageAccess } from "@vrtmrz/livesync-commonlib/compat/interfaces/StorageAccess"; +import { ServiceRebuilder } from "@vrtmrz/livesync-commonlib/compat/serviceModules/Rebuilder"; +import { ServiceFileHandler } from "@/serviceModules/FileHandler"; +import { createFileReflectionProvenance } from "@/serviceModules/FileReflectionProvenance"; + +/** Compose the service modules shared by app hosts after their storage setup. */ +export function composeSharedServiceModules( + services: InjectableServiceHub, + databaseFileAccess: DatabaseFileAccess, + storageAccess: StorageAccess +): Pick { + const fileHandler = new ServiceFileHandler({ + events: services.context.events, + API: services.API, + databaseFileAccess, + conflict: services.conflict, + setting: services.setting, + fileProcessing: services.fileProcessing, + vault: services.vault, + path: services.path, + replication: services.replication, + storageAccess, + fileReflectionProvenance: createFileReflectionProvenance(services.keyValueDB), + }); + + const rebuilder = new ServiceRebuilder({ + path: services.path, + events: services.context.events, + API: services.API, + database: services.database, + appLifecycle: services.appLifecycle, + setting: services.setting, + remote: services.remote, + databaseEvents: services.databaseEvents, + replication: services.replication, + replicator: services.replicator, + UI: services.UI, + vault: services.vault, + fileHandler, + fileProcessing: services.fileProcessing, + storageAccess, + control: services.control, + }); + + return { rebuilder, fileHandler }; +} diff --git a/src/apps/serviceModules/serviceComposition.unit.spec.ts b/src/apps/serviceModules/serviceComposition.unit.spec.ts new file mode 100644 index 00000000..0d81413b --- /dev/null +++ b/src/apps/serviceModules/serviceComposition.unit.spec.ts @@ -0,0 +1,379 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { LiveSyncBaseCore } from "@/LiveSyncBaseCore"; +import { initialiseServiceModulesCLI } from "@/apps/cli/serviceModules/CLIServiceModules"; +import { initialiseServiceModulesFSAPI } from "@/apps/webapp/serviceModules/FSAPIServiceModules"; +import { FILE_REFLECTION_PROVENANCE_STORE } from "@/serviceModules/FileReflectionProvenance"; +import type { ServiceContext } from "@vrtmrz/livesync-commonlib/context"; +import type { InjectableServiceHub } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableServiceHub"; + +const composition = vi.hoisted(() => ({ + calls: [] as string[], + dependencies: {} as Record, + instances: {} as Record, + capture(name: string, dependencies: unknown, instance: unknown) { + this.calls.push(name); + this.dependencies[name] = dependencies; + this.instances[name] = instance; + }, +})); + +vi.mock("@vrtmrz/livesync-commonlib/compat/managers/StorageProcessingManager", () => ({ + StorageAccessManager: class { + constructor() { + composition.capture("StorageAccessManager", undefined, this); + } + }, +})); + +vi.mock("@vrtmrz/livesync-commonlib/compat/serviceModules/Rebuilder", () => ({ + ServiceRebuilder: class { + constructor(dependencies: unknown) { + composition.capture("ServiceRebuilder", dependencies, this); + } + }, +})); + +vi.mock("@/serviceModules/FileHandler", () => ({ + ServiceFileHandler: class { + constructor(dependencies: unknown) { + composition.capture("ServiceFileHandler", dependencies, this); + } + }, +})); + +vi.mock("@/apps/cli/serviceModules/FileAccessCLI", () => ({ + FileAccessCLI: class { + constructor(...args: unknown[]) { + composition.capture("FileAccessCLI", args, this); + } + }, +})); + +vi.mock("@/apps/cli/serviceModules/ServiceFileAccessImpl", () => ({ + ServiceFileAccessCLI: class { + constructor(dependencies: unknown) { + composition.capture("ServiceFileAccessCLI", dependencies, this); + } + }, +})); + +vi.mock("@/apps/cli/serviceModules/DatabaseFileAccess", () => ({ + ServiceDatabaseFileAccessCLI: class { + constructor(dependencies: unknown) { + composition.capture("ServiceDatabaseFileAccessCLI", dependencies, this); + } + }, +})); + +vi.mock("@/apps/cli/managers/StorageEventManagerCLI", () => ({ + StorageEventManagerCLI: class { + close = vi.fn(async () => undefined); + + constructor(...args: unknown[]) { + composition.capture("StorageEventManagerCLI", args, this); + } + }, +})); + +vi.mock("@/apps/webapp/serviceModules/FileAccessFSAPI", () => ({ + FileAccessFSAPI: class { + constructor(...args: unknown[]) { + composition.capture("FileAccessFSAPI", args, this); + } + }, +})); + +vi.mock("@/apps/webapp/serviceModules/ServiceFileAccessImpl", () => ({ + ServiceFileAccessFSAPI: class { + constructor(dependencies: unknown) { + composition.capture("ServiceFileAccessFSAPI", dependencies, this); + } + }, +})); + +vi.mock("@/apps/webapp/serviceModules/DatabaseFileAccess", () => ({ + ServiceDatabaseFileAccessFSAPI: class { + constructor(dependencies: unknown) { + composition.capture("ServiceDatabaseFileAccessFSAPI", dependencies, this); + } + }, +})); + +vi.mock("@/apps/webapp/managers/StorageEventManagerFSAPI", () => ({ + StorageEventManagerFSAPI: class { + constructor(...args: unknown[]) { + composition.capture("StorageEventManagerFSAPI", args, this); + } + }, +})); + +function createServices() { + const hostServices = Object.fromEntries( + [ + "API", + "conflict", + "control", + "database", + "databaseEvents", + "fileProcessing", + "path", + "remote", + "replication", + "replicator", + "setting", + "UI", + "vault", + ].map((name) => [name, { name }]) + ); + const events = { label: "host event hub" }; + const addUnloadHandler = vi.fn<(handler: () => Promise) => void>(); + const openSimpleStore = vi.fn((name: string) => { + composition.calls.push("openSimpleStore"); + composition.dependencies.openSimpleStore = name; + return { name }; + }); + + return { + ...hostServices, + appLifecycle: { onUnload: { addHandler: addUnloadHandler } }, + context: { events }, + events, + keyValueDB: { openSimpleStore }, + addUnloadHandler, + }; +} + +function createCore() { + return {} as LiveSyncBaseCore; +} + +beforeEach(() => { + composition.calls.length = 0; + composition.dependencies = {}; + composition.instances = {}; +}); + +describe("app service module composition", () => { + it("preserves CLI host construction, shared wiring, provenance, and watcher shutdown", async () => { + const services = createServices(); + const core = createCore(); + + const modules = initialiseServiceModulesCLI( + "/vault", + core, + services as unknown as InjectableServiceHub + ); + + expect(composition.calls).toEqual([ + "StorageAccessManager", + "FileAccessCLI", + "StorageEventManagerCLI", + "ServiceFileAccessCLI", + "ServiceDatabaseFileAccessCLI", + "openSimpleStore", + "ServiceFileHandler", + "ServiceRebuilder", + ]); + expect(composition.dependencies.openSimpleStore).toBe(FILE_REFLECTION_PROVENANCE_STORE); + + const [basePath, fileAccessOptions] = composition.dependencies.FileAccessCLI as [ + string, + Record, + ]; + const [eventBasePath, eventCore, eventDependencies, ignoreRules, watchEnabled] = composition.dependencies + .StorageEventManagerCLI as [string, unknown, Record, unknown, boolean]; + const storageAccessDependencies = composition.dependencies.ServiceFileAccessCLI as Record; + const databaseAccessDependencies = composition.dependencies.ServiceDatabaseFileAccessCLI as Record< + string, + unknown + >; + const fileHandlerDependencies = composition.dependencies.ServiceFileHandler as Record; + const rebuilderDependencies = composition.dependencies.ServiceRebuilder as Record; + + expect(basePath).toBe("/vault"); + expect(fileAccessOptions).toEqual({ + storageAccessManager: composition.instances.StorageAccessManager, + vaultService: services.vault, + settingService: services.setting, + APIService: services.API, + pathService: services.path, + }); + expect(eventBasePath).toBe("/vault"); + expect(eventCore).toBe(core); + expect(eventDependencies).toEqual({ + fileProcessing: services.fileProcessing, + setting: services.setting, + vaultService: services.vault, + storageAccessManager: composition.instances.StorageAccessManager, + APIService: services.API, + }); + expect(ignoreRules).toBeUndefined(); + expect(watchEnabled).toBe(false); + expect(storageAccessDependencies).toEqual({ + API: services.API, + setting: services.setting, + fileProcessing: services.fileProcessing, + vault: services.vault, + appLifecycle: services.appLifecycle, + storageEventManager: composition.instances.StorageEventManagerCLI, + storageAccessManager: composition.instances.StorageAccessManager, + vaultAccess: composition.instances.FileAccessCLI, + }); + expect(databaseAccessDependencies).toEqual({ + events: services.events, + API: services.API, + database: services.database, + path: services.path, + storageAccess: modules.storageAccess, + vault: services.vault, + }); + expect(modules.databaseFileAccess).toBe(composition.instances.ServiceDatabaseFileAccessCLI); + expect(modules.fileHandler).toBe(composition.instances.ServiceFileHandler); + expect(modules.rebuilder).toBe(composition.instances.ServiceRebuilder); + expect(fileHandlerDependencies).toEqual({ + events: services.events, + API: services.API, + databaseFileAccess: modules.databaseFileAccess, + conflict: services.conflict, + setting: services.setting, + fileProcessing: services.fileProcessing, + vault: services.vault, + path: services.path, + replication: services.replication, + storageAccess: modules.storageAccess, + fileReflectionProvenance: expect.any(Object), + }); + expect(rebuilderDependencies).toEqual({ + path: services.path, + events: services.events, + API: services.API, + database: services.database, + appLifecycle: services.appLifecycle, + setting: services.setting, + remote: services.remote, + databaseEvents: services.databaseEvents, + replication: services.replication, + replicator: services.replicator, + UI: services.UI, + vault: services.vault, + fileHandler: modules.fileHandler, + fileProcessing: services.fileProcessing, + storageAccess: modules.storageAccess, + control: services.control, + }); + + const unloadHandler = services.addUnloadHandler.mock.calls[0]?.[0]; + expect(unloadHandler).toBeDefined(); + await expect(unloadHandler?.()).resolves.toBe(true); + expect( + (composition.instances.StorageEventManagerCLI as { close: ReturnType }).close + ).toHaveBeenCalledOnce(); + }); + + it("preserves WebApp host construction and returns its vault access and event manager", () => { + const services = createServices(); + const core = createCore(); + const rootHandle = {} as FileSystemDirectoryHandle; + + const modules = initialiseServiceModulesFSAPI( + rootHandle, + core, + services as unknown as InjectableServiceHub + ); + + expect(composition.calls).toEqual([ + "StorageAccessManager", + "FileAccessFSAPI", + "StorageEventManagerFSAPI", + "ServiceFileAccessFSAPI", + "ServiceDatabaseFileAccessFSAPI", + "openSimpleStore", + "ServiceFileHandler", + "ServiceRebuilder", + ]); + expect(composition.dependencies.openSimpleStore).toBe(FILE_REFLECTION_PROVENANCE_STORE); + const [fileAccessRoot, fileAccessOptions] = composition.dependencies.FileAccessFSAPI as [ + FileSystemDirectoryHandle, + Record, + ]; + const [eventRoot, eventCore, eventDependencies] = composition.dependencies.StorageEventManagerFSAPI as [ + FileSystemDirectoryHandle, + unknown, + Record, + ]; + const storageAccessDependencies = composition.dependencies.ServiceFileAccessFSAPI as Record; + const databaseAccessDependencies = composition.dependencies.ServiceDatabaseFileAccessFSAPI as Record< + string, + unknown + >; + + expect(fileAccessRoot).toBe(rootHandle); + expect(fileAccessOptions).toEqual({ + storageAccessManager: composition.instances.StorageAccessManager, + vaultService: services.vault, + settingService: services.setting, + APIService: services.API, + pathService: services.path, + }); + expect(eventRoot).toBe(rootHandle); + expect(eventCore).toBe(core); + expect(eventDependencies).toEqual({ + fileProcessing: services.fileProcessing, + setting: services.setting, + vaultService: services.vault, + storageAccessManager: composition.instances.StorageAccessManager, + APIService: services.API, + }); + expect(storageAccessDependencies).toEqual({ + API: services.API, + setting: services.setting, + fileProcessing: services.fileProcessing, + vault: services.vault, + appLifecycle: services.appLifecycle, + storageEventManager: composition.instances.StorageEventManagerFSAPI, + storageAccessManager: composition.instances.StorageAccessManager, + vaultAccess: composition.instances.FileAccessFSAPI, + }); + expect(databaseAccessDependencies).toEqual({ + events: services.events, + API: services.API, + database: services.database, + path: services.path, + storageAccess: modules.storageAccess, + vault: services.vault, + }); + expect(modules.vaultAccess).toBe(composition.instances.FileAccessFSAPI); + expect(modules.storageEventManager).toBe(composition.instances.StorageEventManagerFSAPI); + expect(composition.dependencies.ServiceFileHandler).toEqual({ + events: services.events, + API: services.API, + databaseFileAccess: modules.databaseFileAccess, + conflict: services.conflict, + setting: services.setting, + fileProcessing: services.fileProcessing, + vault: services.vault, + path: services.path, + replication: services.replication, + storageAccess: modules.storageAccess, + fileReflectionProvenance: expect.any(Object), + }); + expect(composition.dependencies.ServiceRebuilder).toEqual({ + path: services.path, + events: services.events, + API: services.API, + database: services.database, + appLifecycle: services.appLifecycle, + setting: services.setting, + remote: services.remote, + databaseEvents: services.databaseEvents, + replication: services.replication, + replicator: services.replicator, + UI: services.UI, + vault: services.vault, + fileHandler: modules.fileHandler, + fileProcessing: services.fileProcessing, + storageAccess: modules.storageAccess, + control: services.control, + }); + }); +}); diff --git a/src/apps/webapp/adapters/FSAPIFileSystemAdapter.ts b/src/apps/webapp/adapters/FSAPIFileSystemAdapter.ts index 432ca0f4..fbf5cfbd 100644 --- a/src/apps/webapp/adapters/FSAPIFileSystemAdapter.ts +++ b/src/apps/webapp/adapters/FSAPIFileSystemAdapter.ts @@ -8,6 +8,7 @@ import { FSAPIVaultAdapter } from "./FSAPIVaultAdapter"; import type { FSAPIFile, FSAPIFolder, FSAPIStat } from "./FSAPITypes"; import { shareRunningResult } from "octagonal-wheels/concurrency/lock_v2"; import type { WebAppLog } from "@/apps/webapp/WebAppLog"; +import { findCaseInsensitiveFile } from "@/apps/caseInsensitiveFileLookup"; /** * Complete file system adapter implementation for FileSystem API @@ -85,28 +86,12 @@ export class FSAPIFileSystemAdapter implements IFileSystemAdapter { const pathStr = this.normalisePath(p); - const exact = await this.getAbstractFileByPath(pathStr); - if (exact) { - return exact; - } - // TODO: Refactor: Very, Very heavy. - - const lowerPath = pathStr.toLowerCase(); - for (const [cachedPath, cachedFile] of this.fileCache.entries()) { - if (cachedPath.toLowerCase() === lowerPath) { - return cachedFile; - } - } - - await this.scanDirectory(); - - for (const [cachedPath, cachedFile] of this.fileCache.entries()) { - if (cachedPath.toLowerCase() === lowerPath) { - return cachedFile; - } - } - - return null; + return await findCaseInsensitiveFile( + pathStr, + () => this.getAbstractFileByPath(pathStr), + this.fileCache, + () => this.scanDirectory() + ); } async getFiles(): Promise { diff --git a/src/apps/webapp/adapters/FSAPIStorageAdapter.unit.spec.ts b/src/apps/webapp/adapters/FSAPIStorageAdapter.unit.spec.ts index 2859023f..399ca7e7 100644 --- a/src/apps/webapp/adapters/FSAPIStorageAdapter.unit.spec.ts +++ b/src/apps/webapp/adapters/FSAPIStorageAdapter.unit.spec.ts @@ -110,6 +110,83 @@ describe("FileSystemAccessStorageAdapter", () => { } }); +describe("FSAPIVaultAdapter creation", () => { + it.each(["text", "binary"] as const)( + "creates nested %s files with exact content and stored metadata", + async (kind) => { + const root = new MemoryDirectoryHandle("root") as unknown as FileSystemDirectoryHandle; + const adapter = new FSAPIVaultAdapter(root); + const data = new Uint8Array([0, 255, 1, 128, 42]).buffer; + const path = "/nested//folder/file.dat"; + const file = + kind === "text" ? await adapter.create(path, "日本語😀") : await adapter.createBinary(path, data); + const expected = kind === "text" ? new TextEncoder().encode("日本語😀") : new Uint8Array(data); + const nested = await root.getDirectoryHandle("nested"); + const folder = await nested.getDirectoryHandle("folder"); + const stored = await folder.getFileHandle("file.dat"); + expect(file.path).toBe(path); + expect(file.handle).toBe(stored); + expect(new Uint8Array(await adapter.readBinary(file))).toEqual(expected); + expect(file.stat).toEqual({ size: expected.byteLength, mtime: 1, ctime: 1, type: "file" }); + } + ); + + it.each(["text", "binary"] as const)("waits for the %s writer to close before reading metadata", async (kind) => { + let releaseClose!: () => void; + const closed = new Promise((resolve) => { + releaseClose = resolve; + }); + const events: string[] = []; + const getFile = vi.fn(async () => { + events.push("metadata"); + return new File(["result"], "file.dat", { lastModified: 123 }); + }); + const close = vi.fn(async () => { + events.push("close-start"); + await closed; + events.push("closed"); + }); + const write = vi.fn(async () => { + events.push("write"); + }); + const fileHandle = { createWritable: vi.fn(async () => ({ write, close })), getFile }; + const root = { getFileHandle: vi.fn(async () => fileHandle) } as unknown as FileSystemDirectoryHandle; + const adapter = new FSAPIVaultAdapter(root); + const data = new Uint8Array([0, 255]).buffer; + const pending = kind === "text" ? adapter.create("file.dat", "text") : adapter.createBinary("file.dat", data); + try { + await vi.waitFor(() => expect(close).toHaveBeenCalledOnce()); + expect(getFile).not.toHaveBeenCalled(); + } finally { + releaseClose(); + } + const file = await pending; + expect(events).toEqual(["write", "close-start", "closed", "metadata"]); + expect(write).toHaveBeenCalledWith(kind === "text" ? "text" : data); + expect(file.stat).toEqual({ size: 6, ctime: 123, mtime: 123, type: "file" }); + }); + + it.each(["text", "binary"] as const)("propagates a %s write failure without returning metadata", async (kind) => { + const failure = new Error("fixture write failed"); + const getFile = vi.fn(); + const fileHandle = { + createWritable: vi.fn(async () => ({ + write: vi.fn(async () => { + throw failure; + }), + close: vi.fn(), + })), + getFile, + }; + const root = { getFileHandle: vi.fn(async () => fileHandle) } as unknown as FileSystemDirectoryHandle; + const adapter = new FSAPIVaultAdapter(root); + const pending = + kind === "text" ? adapter.create("file.dat", "text") : adapter.createBinary("file.dat", new ArrayBuffer(2)); + await expect(pending).rejects.toBe(failure); + expect(getFile).not.toHaveBeenCalled(); + }); +}); + describe("FSAPIVaultAdapter.rename", () => { it("moves the file through a temporary copy while preserving content", async () => { const memoryRoot = new MemoryDirectoryHandle("root"); @@ -142,6 +219,20 @@ describe("FSAPIVaultAdapter.rename", () => { }); describe("FSAPIFileSystemAdapter path case", () => { + it("returns an exact path without scanning the directory", async () => { + const root = new MemoryDirectoryHandle("root") as unknown as FileSystemDirectoryHandle; + const vault = new FSAPIVaultAdapter(root); + await vault.create("Calculus.md", "content"); + const adapter = new FSAPIFileSystemAdapter(root, vi.fn()); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("Calculus.md")).resolves.toMatchObject({ + path: "Calculus.md", + }); + + expect(scanDirectory).not.toHaveBeenCalled(); + }); + it("returns the stored path case from a case-insensitive file system", async () => { const memoryRoot = new MemoryDirectoryHandle("root", true); const root = memoryRoot as unknown as FileSystemDirectoryHandle; @@ -155,6 +246,48 @@ describe("FSAPIFileSystemAdapter path case", () => { ); }); + it("returns a cached case-insensitive match without rescanning", async () => { + const root = new MemoryDirectoryHandle("root") as unknown as FileSystemDirectoryHandle; + const vault = new FSAPIVaultAdapter(root); + await vault.create("Calculus.md", "content"); + const adapter = new FSAPIFileSystemAdapter(root, vi.fn()); + await adapter.scanDirectory(); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("calculus.md")).resolves.toMatchObject({ + path: "Calculus.md", + }); + + expect(scanDirectory).not.toHaveBeenCalled(); + }); + + it("rescans once and returns a newly cached case-insensitive match", async () => { + const root = new MemoryDirectoryHandle("root") as unknown as FileSystemDirectoryHandle; + const vault = new FSAPIVaultAdapter(root); + await vault.create("Calculus.md", "content"); + const adapter = new FSAPIFileSystemAdapter(root, vi.fn()); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("calculus.md")).resolves.toMatchObject({ + path: "Calculus.md", + }); + + expect(scanDirectory).toHaveBeenCalledOnce(); + await expect(adapter.getAbstractFileByPath("Calculus.md")).resolves.toMatchObject({ path: "Calculus.md" }); + }); + + it("returns null after one scan when no cached path matches", async () => { + const root = new MemoryDirectoryHandle("root") as unknown as FileSystemDirectoryHandle; + const vault = new FSAPIVaultAdapter(root); + await vault.create("other.md", "content"); + const adapter = new FSAPIFileSystemAdapter(root, vi.fn()); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("missing.md")).resolves.toBeNull(); + + expect(scanDirectory).toHaveBeenCalledOnce(); + }); + it("reports scan failures through the injected Webapp log", async () => { const root = { name: "root", @@ -173,4 +306,25 @@ describe("FSAPIFileSystemAdapter path case", () => { "fsapi-scan" ); }); + + it("returns null and reports scan failure during case-insensitive lookup", async () => { + const root = { + name: "root", + async *entries(): AsyncIterableIterator<[string, FileSystemHandle]> { + throw new Error("scan failed"); + }, + } as unknown as FileSystemDirectoryHandle; + const addLog = vi.fn(); + const adapter = new FSAPIFileSystemAdapter(root, addLog); + const scanDirectory = vi.spyOn(adapter, "scanDirectory"); + + await expect(adapter.getAbstractFileByPathInsensitive("missing.md")).resolves.toBeNull(); + + expect(scanDirectory).toHaveBeenCalledOnce(); + expect(addLog).toHaveBeenCalledWith( + "Error scanning directory '.': Error: scan failed", + LOG_LEVEL_NOTICE, + "fsapi-scan" + ); + }); }); diff --git a/src/apps/webapp/adapters/FSAPIVaultAdapter.ts b/src/apps/webapp/adapters/FSAPIVaultAdapter.ts index 9e2d8e27..c31e9f27 100644 --- a/src/apps/webapp/adapters/FSAPIVaultAdapter.ts +++ b/src/apps/webapp/adapters/FSAPIVaultAdapter.ts @@ -36,37 +36,14 @@ export class FSAPIVaultAdapter implements IVaultAdapter { } async create(p: string, data: string, options?: UXDataWriteOptions): Promise { - const parts = p.split("/").filter((part) => part !== ""); - const fileName = parts[parts.length - 1]; - - // Navigate to parent directory, creating as needed - let currentHandle = this.rootHandle; - for (let i = 0; i < parts.length - 1; i++) { - currentHandle = await currentHandle.getDirectoryHandle(parts[i], { create: true }); - } - - // Create the file - const fileHandle = await currentHandle.getFileHandle(fileName, { create: true }); - const writable = await fileHandle.createWritable(); - await writable.write(data); - await writable.close(); - - // Get file metadata - const fileObject = await fileHandle.getFile(); - - return { - path: p as FilePath, - stat: { - size: fileObject.size, - mtime: fileObject.lastModified, - ctime: fileObject.lastModified, - type: "file", - }, - handle: fileHandle, - }; + return await this.createFile(p, data); } async createBinary(p: string, data: ArrayBuffer, options?: UXDataWriteOptions): Promise { + return await this.createFile(p, data); + } + + private async createFile(p: string, data: string | ArrayBuffer): Promise { const parts = p.split("/").filter((part) => part !== ""); const fileName = parts[parts.length - 1]; diff --git a/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.ts b/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.ts index 6594b61d..139ebb7d 100644 --- a/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.ts +++ b/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.ts @@ -2,7 +2,6 @@ import type { FilePath, UXFileInfoStub, UXInternalFileInfoStub } from "@vrtmrz/l import type { FileEventItem } from "@vrtmrz/livesync-commonlib/compat/common/types"; import type { IStorageEventManagerAdapter } from "@vrtmrz/livesync-commonlib/compat/managers/adapters"; import type { - IStorageEventTypeGuardAdapter, IStorageEventPersistenceAdapter, IStorageEventWatchAdapter, IStorageEventStatusAdapter, @@ -14,6 +13,7 @@ import type { FSAPIFile, FSAPIFolder } from "@/apps/webapp/adapters/FSAPITypes"; import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, LOG_LEVEL_VERBOSE } from "@vrtmrz/livesync-commonlib/compat/common/types"; import type { WebAppLog } from "@/apps/webapp/WebAppLog"; +import { FSAPITypeGuardAdapter } from "@/apps/webapp/adapters/FSAPITypeGuardAdapter"; type FileSystemObserverRecord = { changedHandle?: FileSystemFileHandle | FileSystemDirectoryHandle; @@ -34,32 +34,6 @@ type GlobalWithFileSystemObserver = typeof compatGlobal & { FileSystemObserver?: FileSystemObserverConstructor; }; -/** - * FileSystem API-specific type guard adapter - */ -class FSAPITypeGuardAdapter implements IStorageEventTypeGuardAdapter { - isFile(file: unknown): file is FSAPIFile { - return !!( - file && - typeof file === "object" && - "path" in file && - "stat" in file && - "handle" in file && - !(file as { isFolder?: boolean }).isFolder - ); - } - - isFolder(item: unknown): item is FSAPIFolder { - return !!( - item && - typeof item === "object" && - "path" in item && - (item as { isFolder?: boolean }).isFolder === true && - "handle" in item - ); - } -} - /** * FileSystem API-specific persistence adapter (IndexedDB-based snapshot) */ diff --git a/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.unit.spec.ts b/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.unit.spec.ts new file mode 100644 index 00000000..881c5b61 --- /dev/null +++ b/src/apps/webapp/managers/FSAPIStorageEventManagerAdapter.unit.spec.ts @@ -0,0 +1,40 @@ +import { describe, expect, it, vi } from "vitest"; +import { FSAPIStorageEventManagerAdapter } from "./FSAPIStorageEventManagerAdapter"; + +describe("FSAPIStorageEventManagerAdapter type guard", () => { + const typeGuard = new FSAPIStorageEventManagerAdapter({} as FileSystemDirectoryHandle, vi.fn()).typeGuard; + + it.each([ + { label: "null", value: null, expected: false }, + { label: "an object without a path", value: { stat: {}, handle: undefined }, expected: false }, + { label: "an object without a stat", value: { path: "note.md", handle: undefined }, expected: false }, + { label: "an object without a handle", value: { path: "note.md", stat: {} }, expected: false }, + { + label: "a file-shaped object with a handle property", + value: { path: "note.md", stat: {}, handle: undefined }, + expected: true, + }, + { + label: "a folder-shaped object", + value: { path: "folder", handle: undefined, isFolder: true }, + expected: false, + }, + ])("classifies $label as a file", ({ value, expected }) => { + expect(typeGuard.isFile(value)).toBe(expected); + }); + + it.each([ + { label: "null", value: null, expected: false }, + { label: "an object without a path", value: { isFolder: true, handle: undefined }, expected: false }, + { label: "an object without the folder marker", value: { path: "folder", handle: undefined }, expected: false }, + { label: "an object without a handle", value: { path: "folder", isFolder: true }, expected: false }, + { + label: "a folder-shaped object with a handle property", + value: { path: "folder", isFolder: true, handle: undefined }, + expected: true, + }, + { label: "a file-shaped object", value: { path: "note.md", stat: {}, handle: undefined }, expected: false }, + ])("classifies $label as a folder", ({ value, expected }) => { + expect(typeGuard.isFolder(value)).toBe(expected); + }); +}); diff --git a/src/apps/webapp/serviceModules/FSAPIServiceModules.ts b/src/apps/webapp/serviceModules/FSAPIServiceModules.ts index bda8059d..fd70825e 100644 --- a/src/apps/webapp/serviceModules/FSAPIServiceModules.ts +++ b/src/apps/webapp/serviceModules/FSAPIServiceModules.ts @@ -1,5 +1,4 @@ import type { InjectableServiceHub } from "@vrtmrz/livesync-commonlib/compat/services/implements/injectable/InjectableServiceHub"; -import { ServiceRebuilder } from "@vrtmrz/livesync-commonlib/compat/serviceModules/Rebuilder"; import { StorageAccessManager } from "@vrtmrz/livesync-commonlib/compat/managers/StorageProcessingManager"; import type { LiveSyncBaseCore } from "@/LiveSyncBaseCore"; @@ -9,8 +8,7 @@ import { ServiceFileAccessFSAPI } from "./ServiceFileAccessImpl"; import { ServiceDatabaseFileAccessFSAPI } from "./DatabaseFileAccess"; import { StorageEventManagerFSAPI } from "@/apps/webapp/managers/StorageEventManagerFSAPI"; import type { ServiceModules } from "@vrtmrz/livesync-commonlib/compat/interfaces/ServiceModule"; -import { ServiceFileHandler } from "@/serviceModules/FileHandler"; -import { createFileReflectionProvenance } from "@/serviceModules/FileReflectionProvenance"; +import { composeSharedServiceModules } from "@/apps/serviceModules/composeSharedServiceModules"; export interface FSAPIServiceModules extends ServiceModules { vaultAccess: FileAccessFSAPI; @@ -73,40 +71,7 @@ export function initialiseServiceModulesFSAPI( vault: services.vault, }); - // File handler (platform-independent) - const fileHandler = new ServiceFileHandler({ - events: services.context.events, - API: services.API, - databaseFileAccess: databaseFileAccess, - conflict: services.conflict, - setting: services.setting, - fileProcessing: services.fileProcessing, - vault: services.vault, - path: services.path, - replication: services.replication, - storageAccess: storageAccess, - fileReflectionProvenance: createFileReflectionProvenance(services.keyValueDB), - }); - - // Rebuilder (platform-independent) - const rebuilder = new ServiceRebuilder({ - path: services.path, - events: services.context.events, - API: services.API, - database: services.database, - appLifecycle: services.appLifecycle, - setting: services.setting, - remote: services.remote, - databaseEvents: services.databaseEvents, - replication: services.replication, - replicator: services.replicator, - UI: services.UI, - vault: services.vault, - fileHandler: fileHandler, - fileProcessing: services.fileProcessing, - storageAccess: storageAccess, - control: services.control, - }); + const { fileHandler, rebuilder } = composeSharedServiceModules(services, databaseFileAccess, storageAccess); return { rebuilder, diff --git a/src/apps/webpeer/src/WebPeerRuntime.ts b/src/apps/webpeer/src/WebPeerRuntime.ts index fd29947a..2b317d6b 100644 --- a/src/apps/webpeer/src/WebPeerRuntime.ts +++ b/src/apps/webpeer/src/WebPeerRuntime.ts @@ -145,7 +145,7 @@ export class WebPeerRuntime { private showPeerMenu(peer: PeerStatus, event: MouseEvent): void { this.menu?.hide(); - this.menu = new Menu() + this.menu = new Menu(this.services.browserUi) .addItem((item) => item.setTitle("📥 Only fetch").onClick(async () => { await this.p2p.targetedTransfer.pullFromPeer(peer.peerId); diff --git a/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.ts b/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.ts index 7ff2d604..36c021df 100644 --- a/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.ts +++ b/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.ts @@ -1,4 +1,5 @@ import type { ReviewHarnessScenarioResult } from "./reviewHarnessTypes"; +import { createReviewHarnessHeapSampler } from "./reviewHarnessHeapSampling"; export const REVIEW_HARNESS_FILE_CONTENT_HASH_INPUTS = [ { label: "4 KiB", bytes: 4 * 1024 }, @@ -23,15 +24,6 @@ type BenchmarkPerformance = Pick & { type HashAlgorithm = "SHA-256" | "xxHash64"; -function readHeap(clock: BenchmarkPerformance): number | undefined { - try { - const bytes = clock.memory?.usedJSHeapSize; - return typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0 ? bytes : undefined; - } catch { - return undefined; - } -} - function summary(samples: readonly number[]): string { const sorted = [...samples].sort((a, b) => a - b); const middle = sorted[Math.floor(sorted.length / 2)]; @@ -63,19 +55,13 @@ export async function runReviewHarnessFileContentHashBenchmark( throw new Error("The xxHash64 initialisation time is invalid."); } - const before = readHeap(clock); - let highest = before; - const sampleHeap = () => { - const value = readHeap(clock); - if (value !== undefined) highest = Math.max(highest ?? value, value); - return value; - }; + const heap = createReviewHarnessHeapSampler(clock); const inputs: { readonly label: string; readonly bytes: number; readonly content: Blob }[] = []; for (const { label, bytes } of REVIEW_HARNESS_FILE_CONTENT_HASH_INPUTS) { await yieldControl(); inputs.push({ label, bytes, content: operations.createInput(bytes) }); - sampleHeap(); + heap.sample(); } const hash = (algorithm: HashAlgorithm, content: Blob) => @@ -99,7 +85,7 @@ export async function runReviewHarnessFileContentHashBenchmark( const elapsed = clock.now() - started; checkHash(algorithm, inputs[0].label, result); warmupTimes.set(algorithm, elapsed); - sampleHeap(); + heap.sample(); } const observations = [ @@ -124,7 +110,7 @@ export async function runReviewHarnessFileContentHashBenchmark( throw new Error(`The ${algorithm} measurement returned an invalid duration.`); } samples[algorithm].push(elapsed); - sampleHeap(); + heap.sample(); } } for (const algorithm of ["SHA-256", "xxHash64"] as const) { @@ -132,16 +118,7 @@ export async function runReviewHarnessFileContentHashBenchmark( } } - const after = sampleHeap(); - if (highest === undefined) { - observations.push("JavaScript heap: unavailable on this device."); - } else { - const mib = (bytes: number | undefined) => - bytes === undefined ? "unavailable" : `${(bytes / 1048576).toFixed(2)} MiB`; - observations.push( - `JavaScript heap: before=${mib(before)}; highest sampled=${mib(highest)}; after=${mib(after)}.` - ); - } + observations.push(heap.finish()); observations.push( "Heap samples are approximate, may include other Obsidian work, and are affected by garbage collection. They are neither total app RAM nor a true peak." ); diff --git a/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.unit.spec.ts b/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.unit.spec.ts index a3ffc39a..1f5e797e 100644 --- a/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.unit.spec.ts +++ b/src/features/ReviewHarness/reviewHarnessFileContentHashBenchmark.unit.spec.ts @@ -74,6 +74,7 @@ describe("Review Harness file content hash measurements", () => { expect(result.status).toBe("passed"); expect(result.detail).toBe("File content hash measurements completed."); + expect(report).toContain("JavaScript heap: unavailable on this device."); expect([...f.inputs().contentBySize.keys()]).toEqual( REVIEW_HARNESS_FILE_CONTENT_HASH_INPUTS.map(({ bytes }) => bytes) ); @@ -107,6 +108,49 @@ describe("Review Harness file content hash measurements", () => { expect(report).not.toContain("4096n"); }); + it("tracks the sampled maximum and reports a lower final heap sample", async () => { + const f = fixture(); + let reads = 0; + const clock = { + now: f.now, + get memory() { + const sample = reads++; + const mebibytes = + sample === 0 ? 2 : sample === 1 ? 5 : sample === 31 ? 1 : 3; + return { usedJSHeapSize: mebibytes * 1048576 }; + }, + }; + const result = await runReviewHarnessFileContentHashBenchmark(f.operations, clock, f.yieldControl); + + expect(result.observations).toContain( + "JavaScript heap: before=2.00 MiB; highest sampled=5.00 MiB; after=1.00 MiB." + ); + expect(result.observations.join("\n")).toContain("neither total app RAM nor a true peak"); + expect(reads).toBe(32); + }); + + it.each([Number.NaN, Number.POSITIVE_INFINITY, -1, "throws"] as const)( + "keeps timings usable when the heap API returns %s", + async (value) => { + const f = fixture(); + const result = await runReviewHarnessFileContentHashBenchmark( + f.operations, + { + now: f.now, + get memory() { + if (value === "throws") throw new Error("Heap API unavailable"); + return { usedJSHeapSize: value as number }; + }, + }, + f.yieldControl + ); + + expect(result.status).toBe("passed"); + expect(result.observations).toContain("JavaScript heap: unavailable on this device."); + expect(result.observations.join("\n")).not.toMatch(/NaN|Infinity/u); + } + ); + it("uses the same deterministic byte sequence for short and long inputs", async () => { const shortInput = createFixedFileContentHashInput(4 * 1024); const longInput = createFixedFileContentHashInput(64 * 1024); diff --git a/src/features/ReviewHarness/reviewHarnessHeapSampling.ts b/src/features/ReviewHarness/reviewHarnessHeapSampling.ts new file mode 100644 index 00000000..1b5d286c --- /dev/null +++ b/src/features/ReviewHarness/reviewHarnessHeapSampling.ts @@ -0,0 +1,34 @@ +type HeapPerformance = { + readonly memory?: { readonly usedJSHeapSize: number }; +}; + +function readHeap(clock: HeapPerformance): number | undefined { + try { + const bytes = clock.memory?.usedJSHeapSize; + return typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0 ? bytes : undefined; + } catch { + return undefined; + } +} + +export function createReviewHarnessHeapSampler(clock: HeapPerformance): { + sample(): void; + finish(): string; +} { + const before = readHeap(clock); + let highest = before; + let after = before; + const sample = () => { + after = readHeap(clock); + if (after !== undefined) highest = Math.max(highest ?? after, after); + }; + const finish = () => { + sample(); + if (highest === undefined) return "JavaScript heap: unavailable on this device."; + const mib = (bytes: number | undefined) => + bytes === undefined ? "unavailable" : `${(bytes / 1048576).toFixed(2)} MiB`; + return `JavaScript heap: before=${mib(before)}; highest sampled=${mib(highest)}; after=${mib(after)}.`; + }; + + return { sample, finish }; +} diff --git a/src/features/ReviewHarness/reviewHarnessIdBenchmark.ts b/src/features/ReviewHarness/reviewHarnessIdBenchmark.ts index f9212724..6422380c 100644 --- a/src/features/ReviewHarness/reviewHarnessIdBenchmark.ts +++ b/src/features/ReviewHarness/reviewHarnessIdBenchmark.ts @@ -1,4 +1,5 @@ import type { ReviewHarnessScenarioResult } from "./reviewHarnessTypes"; +import { createReviewHarnessHeapSampler } from "./reviewHarnessHeapSampling"; export interface IdBenchmarkOperations { deriveKey(): Promise; @@ -15,15 +16,6 @@ const SAMPLES = 3; const BATCH_SIZE = 100; const WARMUP_COUNT = 32; -function readHeap(clock: BenchmarkPerformance): number | undefined { - try { - const bytes = clock.memory?.usedJSHeapSize; - return typeof bytes === "number" && Number.isFinite(bytes) && bytes >= 0 ? bytes : undefined; - } catch { - return undefined; - } -} - function summary(samples: readonly number[]): string { const sorted = [...samples].sort((a, b) => a - b); return `median=${sorted[1].toFixed(2)} ms; range=${sorted[0].toFixed(2)}–${sorted[2].toFixed(2)} ms`; @@ -34,13 +26,7 @@ export async function runReviewHarnessIdBenchmark( clock: BenchmarkPerformance = performance, yieldControl: () => Promise = () => new Promise((resolve) => window.setTimeout(resolve, 0)) ): Promise { - const before = readHeap(clock); - let highest = before; - const sampleHeap = () => { - const value = readHeap(clock); - if (value !== undefined) highest = Math.max(highest ?? value, value); - return value; - }; + const heap = createReviewHarnessHeapSampler(clock); const observations = [ "Fixed synthetic inputs; 3 samples, alternating legacy/independent order; 32 warm-up IDs per sample. Legacy Chunk algorithm: xxhash64.", "Compute timings include input construction and awaited ID generation. Initialisation, warm-up, and pauses between batches are excluded. This does not measure a Rebuild or remote transfer.", @@ -51,7 +37,7 @@ export async function runReviewHarnessIdBenchmark( const started = clock.now(); await operations.deriveKey(); derivationSamples.push(clock.now() - started); - sampleHeap(); + heap.sample(); } observations.push(`ID key derivation at save time: ${summary(derivationSamples)} per derivation.`); @@ -80,7 +66,7 @@ export async function runReviewHarnessIdBenchmark( const started = clock.now(); for (let i = batch; i < batch + BATCH_SIZE; i++) await scenario.run(i, independent); elapsed += clock.now() - started; - sampleHeap(); + heap.sample(); } samples[independent ? 1 : 0].push(elapsed); } @@ -92,16 +78,7 @@ export async function runReviewHarnessIdBenchmark( ); } } - const after = sampleHeap(); - if (highest === undefined) { - observations.push("JavaScript heap: unavailable on this device."); - } else { - const mib = (bytes: number | undefined) => - bytes === undefined ? "unavailable" : `${(bytes / 1048576).toFixed(2)} MiB`; - observations.push( - `JavaScript heap: before=${mib(before)}; highest sampled=${mib(highest)}; after=${mib(after)}.` - ); - } + observations.push(heap.finish()); observations.push( "Heap samples are approximate, may include other Obsidian work, and are affected by garbage collection. They are neither total app RAM nor a true peak." ); diff --git a/src/features/ReviewHarness/reviewHarnessIdBenchmark.unit.spec.ts b/src/features/ReviewHarness/reviewHarnessIdBenchmark.unit.spec.ts index 2e68837a..93bbdedc 100644 --- a/src/features/ReviewHarness/reviewHarnessIdBenchmark.unit.spec.ts +++ b/src/features/ReviewHarness/reviewHarnessIdBenchmark.unit.spec.ts @@ -73,6 +73,7 @@ describe("Review Harness ID measurements", () => { "JavaScript heap: before=2.00 MiB; highest sampled=5.00 MiB; after=1.00 MiB." ); expect(result.observations.join("\n")).toContain("neither total app RAM nor a true peak"); + expect(reads).toBe(245); }); it.each([Number.NaN, Number.POSITIVE_INFINITY, -1, "throws"])( diff --git a/src/modules/features/SettingDialogue/utilFixCouchDBSetting.ts b/src/modules/features/SettingDialogue/utilFixCouchDBSetting.ts index 4a72be8e..246ce622 100644 --- a/src/modules/features/SettingDialogue/utilFixCouchDBSetting.ts +++ b/src/modules/features/SettingDialogue/utilFixCouchDBSetting.ts @@ -13,6 +13,7 @@ import { generateCredentialObject } from "@vrtmrz/livesync-commonlib/compat/repl import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { isUnauthorizedError } from "@vrtmrz/livesync-commonlib/compat/common/utils.doc"; import { normaliseCouchDBConfiguration } from "@/common/couchdbConfiguration"; +import { isCouchDBVersionAtLeast, normaliseResponseHeaderKeys } from "@/modules/features/couchDBDiagnosticValues"; export const checkConfig = async ( checkResultDiv: HTMLDivElement | undefined, @@ -89,19 +90,6 @@ export const checkConfig = async ( addResult($msg("obsidianLiveSyncSettingTab.serverVersion", { info: serverBanner })); const versionMatch = serverBanner.match(/CouchDB(\/([0-9.]+))?/); const versionStr = versionMatch ? versionMatch[2] : "0.0.0"; - const versionParts = `${versionStr}.0.0.0`.split("."); - // Compare version string with the target version. - // version must be a string like "3.2.1" or "3.10.2", and must be two or three parts. - function isGreaterThanOrEqual(version: string) { - const targetParts = version.split("."); - for (let i = 0; i < targetParts.length; i++) { - // compare as number if possible (so 3.10 > 3.2, 3.10.1b > 3.10.1a) - const result = versionParts[i].localeCompare(targetParts[i], undefined, { numeric: true }); - if (result > 0) return true; - if (result < 0) return false; - } - return true; - } // Admin check // for database creation and deletion if (!(editingSettings.couchDB_USER in responseConfig.admins)) { @@ -109,7 +97,7 @@ export const checkConfig = async ( } else { addResult($msg("obsidianLiveSyncSettingTab.okAdminPrivileges")); } - if (isGreaterThanOrEqual("3.2.0")) { + if (isCouchDBVersionAtLeast(versionStr, "3.2.0")) { // HTTP user-authorization check if (responseConfig?.chttpd?.require_valid_user != "true") { isSuccessful = false; @@ -148,7 +136,7 @@ export const checkConfig = async ( } else { addResult($msg("obsidianLiveSyncSettingTab.okWwwAuth")); } - if (isGreaterThanOrEqual("3.2.0")) { + if (isCouchDBVersionAtLeast(versionStr, "3.2.0")) { if (responseConfig?.chttpd?.enable_cors != "true") { isSuccessful = false; addResult($msg("obsidianLiveSyncSettingTab.errEnableCorsChttpd")); @@ -240,12 +228,7 @@ export const checkConfig = async ( undefined, customHeaders ); - const responseHeaders = Object.fromEntries( - Object.entries(rr.headers).map((e) => { - e[0] = `${e[0]}`.toLowerCase(); - return e; - }) - ); + const responseHeaders = normaliseResponseHeaderKeys(rr.headers); addResult($msg("obsidianLiveSyncSettingTab.msgOriginCheck", { org })); if (responseHeaders["access-control-allow-credentials"] != "true") { addResult($msg("obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials")); diff --git a/src/modules/features/SetupWizard/dialogs/utilCheckCouchDB.ts b/src/modules/features/SetupWizard/dialogs/utilCheckCouchDB.ts index ed34d166..507b2da8 100644 --- a/src/modules/features/SetupWizard/dialogs/utilCheckCouchDB.ts +++ b/src/modules/features/SetupWizard/dialogs/utilCheckCouchDB.ts @@ -8,6 +8,7 @@ import { generateCredentialObject } from "@vrtmrz/livesync-commonlib/compat/repl import { compatGlobal } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { isUnauthorizedError } from "@vrtmrz/livesync-commonlib/compat/common/utils.doc"; import { normaliseCouchDBConfiguration } from "@/common/couchdbConfiguration"; +import { isCouchDBVersionAtLeast, normaliseResponseHeaderKeys } from "@/modules/features/couchDBDiagnosticValues"; export type ResultMessage = { message: string; classes: string[] }; export type ResultErrorMessage = { message: string; result: "error"; classes: string[] }; @@ -26,24 +27,6 @@ export type ConfigCheckResult = | ResultError | ResultMessage | ResultErrorMessage; -/** - * Compares two version strings to determine if the baseVersion is greater than or equal to the version. - * @param baseVersion a.b.c format - * @param version a.b.c format - * @returns true if baseVersion is greater than or equal to version, false otherwise - */ -function isGreaterThanOrEqual(baseVersion: string, version: string) { - const versionParts = `${baseVersion}.0.0.0`.split("."); - const targetParts = version.split("."); - for (let i = 0; i < targetParts.length; i++) { - // compare as number if possible (so 3.10 > 3.2, 3.10.1b > 3.10.1a) - const result = versionParts[i].localeCompare(targetParts[i], undefined, { numeric: true }); - if (result > 0) return true; - if (result < 0) return false; - } - return true; -} - /** * Updates the remote CouchDB setting with the given key and value. * @param setting Connection settings @@ -153,7 +136,7 @@ export const checkConfig = async (editingSettings: ObsidianLiveSyncSettings) => } else { addSuccess($msg("obsidianLiveSyncSettingTab.okAdminPrivileges")); } - if (isGreaterThanOrEqual(versionStr, "3.2.0")) { + if (isCouchDBVersionAtLeast(versionStr, "3.2.0")) { // HTTP user-authorization check if (responseConfig?.chttpd?.require_valid_user != "true") { addError( @@ -189,7 +172,7 @@ export const checkConfig = async (editingSettings: ObsidianLiveSyncSettings) => } else { addSuccess($msg("obsidianLiveSyncSettingTab.okWwwAuth")); } - if (isGreaterThanOrEqual(versionStr, "3.2.0")) { + if (isCouchDBVersionAtLeast(versionStr, "3.2.0")) { if (responseConfig?.chttpd?.enable_cors != "true") { addError( $msg("obsidianLiveSyncSettingTab.errEnableCorsChttpd"), @@ -287,12 +270,7 @@ export const checkConfig = async (editingSettings: ObsidianLiveSyncSettings) => undefined, customHeaders ); - const responseHeaders = Object.fromEntries( - Object.entries(rr.headers).map((e) => { - e[0] = `${e[0]}`.toLowerCase(); - return e; - }) - ); + const responseHeaders = normaliseResponseHeaderKeys(rr.headers); addMessage($msg("obsidianLiveSyncSettingTab.msgOriginCheck", { org })); if (responseHeaders["access-control-allow-credentials"] != "true") { addErrorMessage($msg("obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials")); diff --git a/src/modules/features/couchDBDiagnosticValues.ts b/src/modules/features/couchDBDiagnosticValues.ts new file mode 100644 index 00000000..41208ab5 --- /dev/null +++ b/src/modules/features/couchDBDiagnosticValues.ts @@ -0,0 +1,19 @@ +export function isCouchDBVersionAtLeast(baseVersion: string, targetVersion: string) { + const versionParts = `${baseVersion}.0.0.0`.split("."); + const targetParts = targetVersion.split("."); + for (let i = 0; i < targetParts.length; i++) { + const result = versionParts[i].localeCompare(targetParts[i], undefined, { numeric: true }); + if (result > 0) return true; + if (result < 0) return false; + } + return true; +} + +export function normaliseResponseHeaderKeys(headers: Record) { + return Object.fromEntries( + Object.entries(headers).map((entry) => { + entry[0] = `${entry[0]}`.toLowerCase(); + return entry; + }) + ); +} diff --git a/src/modules/features/couchDBDiagnosticValues.unit.spec.ts b/src/modules/features/couchDBDiagnosticValues.unit.spec.ts new file mode 100644 index 00000000..485a7ba7 --- /dev/null +++ b/src/modules/features/couchDBDiagnosticValues.unit.spec.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { isCouchDBVersionAtLeast, normaliseResponseHeaderKeys } from "./couchDBDiagnosticValues"; + +describe("CouchDB diagnostic values", () => { + describe("version comparison", () => { + it.each([ + ["3.10.2", "3.2.0", true], + ["3.2.0", "3.10.0", false], + ["3.2", "3.2.0", true], + ["3.10.1b", "3.10.1a", true], + ["3.10.1a", "3.10.1b", false], + ["3.x", "3.2", true], + ])("compares %s with %s", (baseVersion, targetVersion, expected) => { + expect(isCouchDBVersionAtLeast(baseVersion, targetVersion)).toBe(expected); + }); + }); + + describe("response header keys", () => { + it("lower-cases keys while retaining last collision values and entry order", () => { + const headers = { Server: "first", server: "last", Zed: "z", Alpha: "a" }; + + const normalised = normaliseResponseHeaderKeys(headers); + + expect(normalised).toEqual({ server: "last", zed: "z", alpha: "a" }); + expect(Object.keys(normalised)).toEqual(["server", "zed", "alpha"]); + expect(headers).toEqual({ Server: "first", server: "last", Zed: "z", Alpha: "a" }); + }); + }); +}); From b8d4ff2c16873120f4a99a62fed9ccde86fb8362 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Thu, 29 Oct 2026 15:06:33 +0000 Subject: [PATCH 06/24] Reduce production bundles while preserving host registration --- devs.md | 6 +++ esbuild.config.mjs | 2 +- eslint.config.mjs | 7 ++++ src/apps/cli/vite.config.ts | 11 +----- src/apps/readVersion.ts | 10 +++++ src/apps/readVersion.unit.spec.ts | 36 +++++++++++++++++ src/apps/webapp/vite.config.ts | 11 +----- terser.config.mjs | 7 +++- test/build/terserConfig.unit.spec.ts | 58 ++++++++++++++++++++++++++++ updates.md | 5 +++ 10 files changed, 133 insertions(+), 20 deletions(-) create mode 100644 src/apps/readVersion.ts create mode 100644 src/apps/readVersion.unit.spec.ts create mode 100644 test/build/terserConfig.unit.spec.ts diff --git a/devs.md b/devs.md index 034df69c..a6b2aa77 100644 --- a/devs.md +++ b/devs.md @@ -47,6 +47,12 @@ npm run test:e2e:browser-apps:interop # Run WebApp → WebPeer → CLI in Com npm run test:e2e:obsidian:local-suite # Run the real Obsidian local suite ``` +### Production minification + +Production builds remove unused declarations and shorten local identifiers while retaining class and function names used by module discovery and diagnostic stacks. `terser.config.mjs` also preserves property names, top-level bindings, and identifiers visible to direct `eval` calls. Keep these boundaries when changing compression settings; `test/build/terserConfig.unit.spec.ts` checks the generated code against host properties, persisted keys, reflective names, and exception stacks. + +Compare bundle bytes and gzip bytes from the same source, dependency artefacts, and build inputs. Validate import-time registration and the resulting plug-in in the affected real-runtime workflows. The iOS syntax check is one part of compatibility verification; it does not measure performance or replace physical-device testing. + ### Tips Select the narrowest unit, integration, CLI E2E, or real Obsidian E2E command that owns the behaviour being changed. The obsolete mocked browser Harness has been retired. diff --git a/esbuild.config.mjs b/esbuild.config.mjs index e2e16e8e..ab7684a6 100644 --- a/esbuild.config.mjs +++ b/esbuild.config.mjs @@ -194,7 +194,7 @@ const context = await esbuild.context({ platform: "browser", metafile: true, sourcemap: prod ? false : "inline", - treeShaking: false, + treeShaking: true, outfile: "main_org.js", mainFields: ["browser", "module", "main"], minifyWhitespace: false, diff --git a/eslint.config.mjs b/eslint.config.mjs index bcbd8688..20a5a0dc 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -120,6 +120,13 @@ export default defineConfig([ "@typescript-eslint/restrict-template-expressions": "warn", }, }, + { + files: ["src/apps/cli/vite.config.ts", "src/apps/webapp/vite.config.ts"], + rules: { + // Vite loads these configurations before the application source alias is available. + "livesync-imports/prefer-source-alias": "off", + }, + }, { files: ["src/apps/browser/**/*.{ts,svelte}", "src/apps/webapp/**/*.ts"], rules: { diff --git a/src/apps/cli/vite.config.ts b/src/apps/cli/vite.config.ts index a3212a34..905a016b 100644 --- a/src/apps/cli/vite.config.ts +++ b/src/apps/cli/vite.config.ts @@ -1,18 +1,11 @@ import { defaultServerConditions, defaultServerMainFields, defineConfig } from "vite"; import { svelte } from "@sveltejs/vite-plugin-svelte"; -import { fileURLToPath, fs, isBuiltin, path } from "@vrtmrz/livesync-commonlib/node"; +import { fileURLToPath, isBuiltin, path } from "@vrtmrz/livesync-commonlib/node"; +import { readVersion } from "../readVersion"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const resolve = (...args: string[]) => path.resolve(...args).replace(/\\/g, "/"); const repoRoot = path.resolve(__dirname, "../../.."); -function readVersion(filePath: string): string | undefined { - const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8")); - if (typeof parsed !== "object" || parsed === null || !("version" in parsed)) { - return undefined; - } - return typeof parsed.version === "string" ? parsed.version : undefined; -} - const packageVersion = readVersion(path.resolve(repoRoot, "package.json")); const manifestVersion = readVersion(path.resolve(repoRoot, "manifest.json")); // https://vite.dev/config/ diff --git a/src/apps/readVersion.ts b/src/apps/readVersion.ts new file mode 100644 index 00000000..d6bc09cc --- /dev/null +++ b/src/apps/readVersion.ts @@ -0,0 +1,10 @@ +import { fs } from "@vrtmrz/livesync-commonlib/node"; + +/** Read a string-valued version field from a JSON file during Node builds. */ +export function readVersion(filePath: string): string | undefined { + const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8")); + if (typeof parsed !== "object" || parsed === null || !("version" in parsed)) { + return undefined; + } + return typeof parsed.version === "string" ? parsed.version : undefined; +} diff --git a/src/apps/readVersion.unit.spec.ts b/src/apps/readVersion.unit.spec.ts new file mode 100644 index 00000000..3de40238 --- /dev/null +++ b/src/apps/readVersion.unit.spec.ts @@ -0,0 +1,36 @@ +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { readVersion } from "./readVersion"; + +describe("readVersion", () => { + let directory: string; + + beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "livesync-read-version-")); + }); + + afterEach(() => { + rmSync(directory, { recursive: true, force: true }); + }); + + it("returns only string version values", () => { + const filePath = join(directory, "version.json"); + writeFileSync(filePath, JSON.stringify({ version: "1.2.3" })); + expect(readVersion(filePath)).toBe("1.2.3"); + + for (const contents of ["null", "[]", "{}", '{"version": 42}', '{"version": null}']) { + writeFileSync(filePath, contents); + expect(readVersion(filePath)).toBeUndefined(); + } + }); + + it("preserves file read and JSON parse errors", () => { + expect(() => readVersion(join(directory, "missing.json"))).toThrow(); + + const filePath = join(directory, "invalid.json"); + writeFileSync(filePath, "not JSON"); + expect(() => readVersion(filePath)).toThrow(SyntaxError); + }); +}); diff --git a/src/apps/webapp/vite.config.ts b/src/apps/webapp/vite.config.ts index e48b74d1..4564fd31 100644 --- a/src/apps/webapp/vite.config.ts +++ b/src/apps/webapp/vite.config.ts @@ -1,17 +1,10 @@ import { defineConfig } from "vite"; import { svelte } from "@sveltejs/vite-plugin-svelte"; -import { fileURLToPath, fs, path } from "@vrtmrz/livesync-commonlib/node"; +import { fileURLToPath, path } from "@vrtmrz/livesync-commonlib/node"; +import { readVersion } from "../readVersion"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(__dirname, "../../.."); -function readVersion(filePath: string): string | undefined { - const parsed: unknown = JSON.parse(fs.readFileSync(filePath, "utf-8")); - if (typeof parsed !== "object" || parsed === null || !("version" in parsed)) { - return undefined; - } - return typeof parsed.version === "string" ? parsed.version : undefined; -} - const packageVersion = readVersion(path.resolve(repoRoot, "package.json")); const manifestVersion = readVersion(path.resolve(repoRoot, "manifest.json")); // https://vite.dev/config/ diff --git a/terser.config.mjs b/terser.config.mjs index e15bc67a..feae72e9 100644 --- a/terser.config.mjs +++ b/terser.config.mjs @@ -60,7 +60,12 @@ const terserOption = { hoist_vars: true, // toplevel: "vars", }, - mangle: false, + // Keep property keys, reflective names, and eval-visible bindings stable. + mangle: { + properties: false, + toplevel: false, + eval: false, + }, ecma: 2018, // specify one of: 5, 2015, 2016, etc. enclose: false, // or specify true, or "args:values" diff --git a/test/build/terserConfig.unit.spec.ts b/test/build/terserConfig.unit.spec.ts new file mode 100644 index 00000000..83672bbf --- /dev/null +++ b/test/build/terserConfig.unit.spec.ts @@ -0,0 +1,58 @@ +import { runInNewContext } from "node:vm"; +import { describe, expect, it } from "vitest"; +import { minify } from "terser"; +import { terserOption } from "../../terser.config.mjs"; + +const fixture = ` + const host = require("obsidian"); + class ModuleLog { + constructor(configuration) { this.savedSettings = configuration; } + read(longParameterName) { + const longIntermediateValue = host.prefix + longParameterName; + return { savedSettings: this.savedSettings, message: longIntermediateValue }; + } + } + function renderMessage(inputValue) { return new ModuleLog({ persistedField: "unchanged" }).read(inputValue); } + function readWithEval(longEvalParameter) { return eval("longEvalParameter"); } + function failWithName() { throw new Error("fixture failure"); } + module.exports = { ModuleLog, renderMessage, readWithEval, failWithName }; +`; + +describe("production minifier", () => { + it("shortens local identifiers while preserving host properties, module names, and diagnostics", async () => { + const result = await minify(fixture, { ...terserOption, sourceMap: false }); + expect(result.code).toBeDefined(); + const sandbox = { + module: { + exports: {} as { + ModuleLog: { name: string }; + renderMessage(input: string): unknown; + readWithEval(input: string): string; + failWithName(): never; + }, + }, + require: (name: string) => { + expect(name).toBe("obsidian"); + return { prefix: "host:" }; + }, + }; + runInNewContext(result.code!, sandbox); + const api = sandbox.module.exports; + expect(api.ModuleLog.name).toBe("ModuleLog"); + expect(api.renderMessage.name).toBe("renderMessage"); + expect(api.renderMessage("sample")).toEqual({ + savedSettings: { persistedField: "unchanged" }, + message: "host:sample", + }); + expect(api.readWithEval("evaluated")).toBe("evaluated"); + let failure: Error | undefined; + try { + api.failWithName(); + } catch (error) { + failure = error as Error; + } + expect(failure?.stack).toContain("failWithName"); + expect(result.code).not.toContain("longParameterName"); + expect(result.code).not.toContain("longIntermediateValue"); + }); +}); diff --git a/updates.md b/updates.md index 32f0f46a..6228f032 100644 --- a/updates.md +++ b/updates.md @@ -12,6 +12,11 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi ## Unreleased +### Maintenance + +- The plug-in bundle is smaller, reducing the download for installation and updates. + - Builds remove unused code and shorten local identifiers while retaining class and function names for diagnostics. + ### Diagnostics - Service log calls stay with the plug-in instance that registered them. Its log connection is released after the full shutdown, so stale instances cannot receive later service messages. From 312cbac9339146ca03f2b212b051857852e3404e Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 06:08:07 +0000 Subject: [PATCH 07/24] Adopt refined shared runtime API names --- .../CmdConfigSync.scanAllConfigFiles.unit.spec.ts | 8 ++++---- src/features/ConfigSync/CmdConfigSync.ts | 8 ++++---- .../features/SettingDialogue/LiveSyncSetting.ts | 12 ++++++------ 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts index 069fdab6..85e763f3 100644 --- a/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts +++ b/src/features/ConfigSync/CmdConfigSync.scanAllConfigFiles.unit.spec.ts @@ -54,10 +54,10 @@ vi.mock("@/common/obsidianCommunityPlugins.ts", () => ({ getObsidianCommunityPluginManager: vi.fn(), })); -vi.mock("octagonal-wheels/concurrency/scopedIteration", { spy: true }); +vi.mock("octagonal-wheels/concurrency/scoped.iteration", { spy: true }); import { LOG_LEVEL_VERBOSE, type FilePath } from "@vrtmrz/livesync-commonlib/compat/common/types"; -import * as iterationModule from "octagonal-wheels/concurrency/scopedIteration"; +import * as iterationModule from "octagonal-wheels/concurrency/scoped.iteration"; import { promiseWithResolvers } from "octagonal-wheels/promises"; import { ConfigSync } from "./CmdConfigSync"; @@ -262,8 +262,8 @@ describe("ConfigSync scoped iteration composition", () => { it.each(["database", "extra"])("propagates a %s runner failure outside per-item recovery", async (batch) => { const fixture = setup(["extra"], [row("stale")]); const error = new Error("iteration"); - const actual = await vi.importActual( - "octagonal-wheels/concurrency/scopedIteration" + const actual = await vi.importActual( + "octagonal-wheels/concurrency/scoped.iteration" ); if (batch === "extra") { vi.mocked(iterationModule.forEachInScope).mockImplementationOnce(actual.forEachInScope); diff --git a/src/features/ConfigSync/CmdConfigSync.ts b/src/features/ConfigSync/CmdConfigSync.ts index 1902c590..8a5b8f88 100644 --- a/src/features/ConfigSync/CmdConfigSync.ts +++ b/src/features/ConfigSync/CmdConfigSync.ts @@ -59,7 +59,7 @@ import { QueueProcessor } from "octagonal-wheels/concurrency/processor"; import { pluginScanningCount } from "@vrtmrz/livesync-commonlib/compat/mock_and_interop/stores"; import { base64ToArrayBuffer, base64ToString } from "octagonal-wheels/binary/base64"; import { ConflictResolveModal } from "@/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts"; -import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { forEachInScope } from "octagonal-wheels/concurrency/scoped.iteration"; import { withScope } from "octagonal-wheels/resource/scope"; import { EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG, eventHub } from "@/common/events.ts"; import { PluginDialogModal } from "./PluginDialogModal.ts"; @@ -69,7 +69,7 @@ import type { LiveSyncCore } from "@/main.ts"; import { LiveSyncError } from "@vrtmrz/livesync-commonlib/compat/common/LSError"; import type { OptionalSyncFeatureMode } from "@/features/optionalSyncFeatures.ts"; import { getObsidianCommunityPluginManager } from "@/common/obsidianCommunityPlugins.ts"; -import { createContentApplier } from "octagonal-wheels/content"; +import { createModificationHandler } from "octagonal-wheels/modification"; import type { HandlerOutcome } from "@vrtmrz/livesync-commonlib/compat/services/lib/HandlerUtils"; import type { OptionalFileEventOptions } from "@vrtmrz/livesync-commonlib/compat/services/base/IService"; @@ -1033,7 +1033,7 @@ export class ConfigSync extends LiveSyncCommands { await this.storeCustomisationFileV2(path, this.services.setting.getDeviceAndVaultName()); } else { const files = data.files; - const applyBinaryContent = createContentApplier< + const applyBinaryContent = createModificationHandler< ConfigFileApplicationTarget, LoadedEntryPluginDataExFile, ArrayBuffer, @@ -1050,7 +1050,7 @@ export class ConfigSync extends LiveSyncCommands { write: (target, content) => this.core.storageAccess.writeHiddenFileAuto(target.path, content, target.stat), }); - const applyTextContent = createContentApplier< + const applyTextContent = createModificationHandler< ConfigFileApplicationTarget, LoadedEntryPluginDataExFile, string, diff --git a/src/modules/features/SettingDialogue/LiveSyncSetting.ts b/src/modules/features/SettingDialogue/LiveSyncSetting.ts index 455eebd6..b3b802e4 100644 --- a/src/modules/features/SettingDialogue/LiveSyncSetting.ts +++ b/src/modules/features/SettingDialogue/LiveSyncSetting.ts @@ -25,7 +25,7 @@ import { } from "./settingConstants.ts"; import { $msg } from "@/common/translation"; import type { AutoWireOption, OnUpdateResult } from "./SettingPane.ts"; -import { wrapMemo } from "octagonal-wheels/function"; +import { onlyWhenChanged } from "octagonal-wheels/function"; import { setButtonDestructiveState } from "./settingComponentStyles.ts"; export class LiveSyncSetting extends Setting { @@ -118,7 +118,7 @@ export class LiveSyncSetting extends Setting { const conf = this.autoWireSetting(key, opt); addComponent((text) => { this.autoWiredComponent = text; - const setValue = wrapMemo((value: string) => { + const setValue = onlyWhenChanged((value: string) => { text.setValue(value); }); this.invalidateValue = () => setValue(`${LiveSyncSetting.env.editingSettings[key]}`); @@ -167,7 +167,7 @@ export class LiveSyncSetting extends Setting { text.inputEl.setAttribute("max", `${opt.clampMax}`); } let lastError = false; - const setValue = wrapMemo((value: string) => { + const setValue = onlyWhenChanged((value: string) => { text.setValue(value); }); this.invalidateValue = () => { @@ -213,7 +213,7 @@ export class LiveSyncSetting extends Setting { const conf = this.autoWireSetting(key, opt); this.addToggle((toggle) => { this.autoWiredComponent = toggle; - const setValue = wrapMemo((value: boolean) => { + const setValue = onlyWhenChanged((value: boolean) => { toggle.setValue(opt?.invert ? !value : value); }); this.invalidateValue = () => @@ -232,7 +232,7 @@ export class LiveSyncSetting extends Setting { const conf = this.autoWireSetting(key, opt); this.addDropdown((dropdown) => { this.autoWiredComponent = dropdown; - const setValue = wrapMemo((value: string) => { + const setValue = onlyWhenChanged((value: string) => { dropdown.setValue(value); }); @@ -252,7 +252,7 @@ export class LiveSyncSetting extends Setting { const conf = this.autoWireSetting(key, opt); this.addDropdown((dropdown) => { this.autoWiredComponent = dropdown; - const setValue = wrapMemo((value: string) => { + const setValue = onlyWhenChanged((value: string) => { dropdown.setValue(value); }); From f325d2454d53a1fe54690fd8697e81aa431641d6 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 08:49:49 +0000 Subject: [PATCH 08/24] Verify delayed optional-file queue consumers --- .../CmdConfigSync.queue.unit.spec.ts | 188 +++++++++++++++++ .../CmdHiddenFileSync.queue.unit.spec.ts | 198 ++++++++++++++++++ 2 files changed, 386 insertions(+) create mode 100644 src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts create mode 100644 src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts diff --git a/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts new file mode 100644 index 00000000..5674f803 --- /dev/null +++ b/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts @@ -0,0 +1,188 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/deps.ts", () => ({ + addIcon: vi.fn(), + diff_match_patch: class DiffMatchPatch {}, + normalizePath: (path: string) => path, + parseYaml: vi.fn(), + Platform: {}, +})); +vi.mock("./PluginDialogModal.ts", () => ({ PluginDialogModal: class PluginDialogModal {} })); +vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ JsonResolveModal: class JsonResolveModal {} })); +vi.mock("@/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts", () => ({ + ConflictResolveModal: class ConflictResolveModal {}, +})); +vi.mock("@/modules/features/ModuleLog.ts", () => ({ MARK_DONE: "" })); +vi.mock("@/common/utils.ts", () => ({ + cancelTask: vi.fn(), + EVEN: Symbol("even"), + isCustomisationSyncMetadata: vi.fn(), + isPluginMetadata: vi.fn(), + scheduleTask: vi.fn(), +})); +vi.mock("@/common/PeriodicProcessor.ts", () => ({ PeriodicProcessor: class PeriodicProcessor {} })); +vi.mock("@/common/events.ts", () => ({ + EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG: "open-plugin-sync", + eventHub: { onEvent: vi.fn() }, +})); +vi.mock("@/common/translation", () => ({ $msg: (message: string) => message })); +vi.mock("@/common/obsidianCommunityPlugins.ts", () => ({ getObsidianCommunityPluginManager: vi.fn() })); + +import { get } from "svelte/store"; +import { DEFAULT_SETTINGS, type FilePathWithPrefix } from "@vrtmrz/livesync-commonlib/compat/common/types"; +import { createOptionalFileSyncDatabase, optionalFileEntry } from "../../../test/fixtures/optionalFileSyncDatabase"; +import { ConfigSync, pluginIsEnumerating, pluginList } from "./CmdConfigSync"; + +const queueOwners: ConfigSync[] = []; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +async function waitForCondition(predicate: () => boolean, message: string) { + for (let attempt = 0; attempt < 30; attempt++) { + if (predicate()) return; + await Promise.resolve(); + } + throw new Error(message); +} + +afterEach(() => { + for (const configSync of queueOwners.splice(0)) { + configSync.pluginScanProcessor.terminateAll(); + configSync.pluginScanProcessorV2.terminateAll(); + } + vi.restoreAllMocks(); + pluginList.set([]); + pluginIsEnumerating.set(false); + vi.useRealTimers(); +}); + +describe("ConfigSync legacy catalogue queue", () => { + it("loads legacy catalogue contents through the database with native timers", async () => { + const fixture = await createOptionalFileSyncDatabase(); + const path = "ix:device/PLUGIN_MAIN/native-timers" as FilePathWithPrefix; + const data = { + category: "PLUGIN_MAIN", + name: "native-timers", + term: "device", + mtime: 2_000, + files: [{ filename: "main.js", data: ["stored content"], mtime: 2_000, size: 14, hash: "stored-hash" }], + }; + let configSync: ConfigSync | undefined; + try { + fixture.settings.usePluginSyncV2 = false; + await expect( + fixture.localDatabase.putDBEntry(optionalFileEntry(path, JSON.stringify(data))) + ).resolves.toMatchObject({ ok: true }); + vi.spyOn(ConfigSync.prototype, "onBindFunction").mockImplementation(() => {}); + configSync = new ConfigSync({ + settings: fixture.settings, + localDatabase: fixture.localDatabase, + services: { + ...fixture.services, + API: { ...fixture.services.API, addRibbonIcon: vi.fn() }, + }, + } as unknown as ConstructorParameters[0]); + queueOwners.push(configSync); + await configSync.updatePluginList(false); + expect(await configSync.pluginScanProcessor.waitForAllProcessed(2_000)).toBe(true); + expect(configSync.pluginList).toEqual([ + { + ...data, + documentPath: path, + files: [{ ...data.files[0], data: ["stored-hash"] }], + }, + ]); + expect(get(pluginList)).toEqual(configSync.pluginList); + expect(configSync.pluginScanProcessor.remaining).toBe(0); + } finally { + configSync?.pluginScanProcessor.terminateAll(); + configSync?.pluginScanProcessorV2.terminateAll(); + await fixture.dispose(); + } + }); + + it("returns after enumeration, then loads a queued legacy catalogue item after its configured delay", async () => { + vi.useFakeTimers(); + pluginList.set([]); + pluginIsEnumerating.set(false); + + const path = "ix:device/PLUGIN_MAIN/example" as FilePathWithPrefix; + const catalogueData = { + category: "PLUGIN_MAIN", + name: "example", + term: "device", + mtime: 2_000, + files: [ + { filename: "main.js", data: ["legacy plugin source"], mtime: 2_000, size: 20, hash: "legacy-hash" }, + ], + }; + const entry = { _id: path, path, mtime: 2_000, data: [JSON.stringify(catalogueData)] }; + const readGate = deferred(); + let loadHasStarted = false; + const localDatabase = { + findEntries: vi.fn(async function* () { + yield entry; + }), + getDBEntry: vi.fn(async () => { + loadHasStarted = true; + await readGate.promise; + return entry; + }), + }; + vi.spyOn(ConfigSync.prototype, "onBindFunction").mockImplementation(() => {}); + const configSync = new ConfigSync({ + settings: { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: false }, + localDatabase, + services: { + API: { addLog: vi.fn(), addRibbonIcon: vi.fn() }, + path: { getPath: (document: { path: string }) => document.path }, + }, + } as unknown as ConstructorParameters[0]); + queueOwners.push(configSync); + + let drained = false; + try { + await configSync.updatePluginList(false); + + expect(configSync.pluginScanProcessor.delay).toBe(100); + expect(configSync.pluginScanProcessor.remaining).toBe(1); + expect(configSync.pluginList).toEqual([]); + expect(get(pluginIsEnumerating)).toBe(false); + + await vi.advanceTimersByTimeAsync(99); + expect(loadHasStarted).toBe(false); + + await vi.advanceTimersByTimeAsync(1); + expect(loadHasStarted).toBe(true); + expect(configSync.pluginScanProcessor.remaining).toBe(1); + const drain = configSync.pluginScanProcessor.waitForAllProcessed(); + void drain.then((result) => { + drained = result; + }); + + readGate.resolve(); + await vi.advanceTimersByTimeAsync(1_000); + await waitForCondition(() => drained, "The legacy catalogue queue did not drain"); + + expect(configSync.pluginList).toEqual([ + { + ...catalogueData, + documentPath: path, + files: [{ ...catalogueData.files[0], data: ["legacy-hash"] }], + }, + ]); + expect(get(pluginList)).toEqual(configSync.pluginList); + expect(configSync.pluginScanProcessor.remaining).toBe(0); + expect(get(pluginIsEnumerating)).toBe(false); + } finally { + readGate.resolve(); + await vi.advanceTimersByTimeAsync(1_000); + } + }); +}); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts new file mode 100644 index 00000000..fbf68283 --- /dev/null +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts @@ -0,0 +1,198 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("@/deps.ts", () => ({})); +vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ JsonResolveModal: class JsonResolveModal {} })); +vi.mock("@/modules/features/ModuleLog.ts", () => ({ MARK_DONE: "" })); +vi.mock("@/common/PeriodicProcessor.ts", () => ({ PeriodicProcessor: class PeriodicProcessor {} })); +vi.mock("./configureHiddenFileSyncMode.ts", () => ({ configureHiddenFileSyncMode: vi.fn() })); + +import { + DEFAULT_SETTINGS, + type DocumentID, + type FilePathWithPrefix, + type LoadedEntry, + type MetaEntry, +} from "@vrtmrz/livesync-commonlib/compat/common/types"; +import { HiddenFileSync } from "./CmdHiddenFileSync"; + +const queueOwners: HiddenFileSync[] = []; + +function deferred() { + let resolve!: (value: T | PromiseLike) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +async function waitForCondition(predicate: () => boolean, message: string) { + for (let attempt = 0; attempt < 30; attempt++) { + if (predicate()) return; + await Promise.resolve(); + } + throw new Error(message); +} + +function createHiddenFileSync(localDatabase: object) { + vi.spyOn(HiddenFileSync.prototype, "onBindFunction").mockImplementation(() => {}); + const hiddenFileSync = new HiddenFileSync({ + settings: { + ...DEFAULT_SETTINGS, + syncInternalFiles: true, + syncInternalFileOverwritePatterns: "", + }, + localDatabase, + services: { API: { addLog: vi.fn() }, context: { app: {} } }, + } as unknown as ConstructorParameters[0]); + hiddenFileSync._log = vi.fn(); + queueOwners.push(hiddenFileSync); + return { hiddenFileSync }; +} + +afterEach(() => { + for (const hiddenFileSync of queueOwners.splice(0)) { + hiddenFileSync.conflictResolutionProcessor.terminateAll(); + } + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe("HiddenFileSync conflict queue", () => { + it("keeps a self-requeued conflict check and waits for its follow-up", async () => { + vi.useFakeTimers(); + const path = "i:.obsidian/plugins/example/data.txt" as FilePathWithPrefix; + const id = String(path) as DocumentID; + const conflictDoc = { + _id: id, + _rev: "2-current", + path, + _conflicts: ["2-conflicted"], + } as MetaEntry; + const resolvedDoc = { _id: id, _rev: "3-resolved", path } as MetaEntry; + let rawRead = 0; + const localDatabase = { + findEntries: vi.fn(async function* () { + yield conflictDoc; + }), + getRaw: vi.fn(async () => (rawRead++ === 0 ? conflictDoc : resolvedDoc)), + }; + const { hiddenFileSync } = createHiddenFileSync(localDatabase); + hiddenFileSync.path2id = async () => id; + + let resolutionCalls = 0; + let requeued = false; + hiddenFileSync.resolveByNewerEntry = vi.fn(async () => { + resolutionCalls++; + hiddenFileSync.requeueConflictCheck(path); + requeued = true; + }); + + let completed = false; + hiddenFileSync.queueConflictCheck(path); + try { + expect(hiddenFileSync.conflictResolutionProcessor.delay).toBe(10); + await waitForCondition( + () => hiddenFileSync.conflictResolutionProcessor.remaining === 1, + "The initial conflict check was not queued" + ); + + await vi.advanceTimersByTimeAsync(9); + expect(localDatabase.getRaw).not.toHaveBeenCalled(); + + await vi.advanceTimersByTimeAsync(1); + await waitForCondition( + () => + requeued && + hiddenFileSync.conflictResolutionProcessor.nowProcessing === 0 && + hiddenFileSync.conflictResolutionProcessor.remaining === 1, + "The conflict follow-up was not retained after the first pass" + ); + void hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed().then(() => { + completed = true; + }); + expect(completed).toBe(false); + expect(localDatabase.getRaw).toHaveBeenCalledTimes(1); + + await vi.advanceTimersByTimeAsync(9); + expect(localDatabase.getRaw).toHaveBeenCalledTimes(1); + expect(completed).toBe(false); + + await vi.advanceTimersByTimeAsync(1); + await vi.advanceTimersByTimeAsync(1_000); + await waitForCondition(() => completed, "The conflict pipeline did not await its follow-up"); + + expect(localDatabase.getRaw).toHaveBeenCalledTimes(2); + expect(resolutionCalls).toBe(1); + expect(hiddenFileSync.pendingConflictChecks.has(path)).toBe(false); + expect(hiddenFileSync.conflictResolutionProcessor.remaining).toBe(0); + } finally { + await vi.runAllTimersAsync(); + } + }); + + it("waits for a cancelled manual merge dialogue and then finishes without requeueing", async () => { + vi.useFakeTimers(); + const path = "i:.obsidian/plugins/example/data.json" as FilePathWithPrefix; + const id = String(path) as DocumentID; + const conflictDoc = { + _id: id, + _rev: "2-current", + path, + _conflicts: ["2-conflicted"], + } as MetaEntry; + const historyDoc = {} as unknown as MetaEntry; + const loaded = { _id: id, _rev: "2-current", path } as LoadedEntry; + const dialogue = deferred(); + let dialogueOpened = false; + const localDatabase = { + findEntries: vi.fn(async function* () { + yield conflictDoc; + }), + getRaw: vi.fn(async (_id: DocumentID, options?: { revs_info?: boolean }) => + options?.revs_info ? historyDoc : conflictDoc + ), + getDBEntry: vi.fn(async () => loaded), + managers: { + conflictManager: { + mergeObject: vi.fn(async () => false), + }, + }, + }; + const { hiddenFileSync } = createHiddenFileSync(localDatabase); + hiddenFileSync.path2id = async () => id; + hiddenFileSync.showJSONMergeDialogAndMerge = vi.fn(async () => { + dialogueOpened = true; + return await dialogue.promise; + }); + + let completed = false; + hiddenFileSync.queueConflictCheck(path); + try { + expect(hiddenFileSync.conflictResolutionProcessor.delay).toBe(10); + await waitForCondition( + () => hiddenFileSync.conflictResolutionProcessor.remaining === 1, + "The initial conflict check was not queued" + ); + + await vi.advanceTimersByTimeAsync(100); + expect(dialogueOpened).toBe(true); + void hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed().then(() => { + completed = true; + }); + expect(completed).toBe(false); + expect(hiddenFileSync.conflictResolutionProcessor.totalRemaining).toBeGreaterThan(0); + expect(localDatabase.managers.conflictManager.mergeObject).toHaveBeenCalledOnce(); + expect(localDatabase.getDBEntry).toHaveBeenCalledTimes(2); + + dialogue.resolve(false); + await vi.advanceTimersByTimeAsync(1_000); + await waitForCondition(() => completed, "The cancelled dialogue did not release the pipeline"); + + expect(hiddenFileSync.pendingConflictChecks.has(path)).toBe(false); + expect(hiddenFileSync.conflictResolutionProcessor.totalRemaining).toBe(0); + } finally { + dialogue.resolve(false); + await vi.runAllTimersAsync(); + } + }); +}); From d1af8a5dfab1fb98372117234e23ecf6792e5c5e Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 09:44:02 +0000 Subject: [PATCH 09/24] Retire legacy purge-based cleanup recovery --- .../centralCompatibilityRecovery.ts | 122 +--------- .../centralCompatibilityRecovery.unit.spec.ts | 224 ++++++++++-------- src/serviceFeatures/replication/index.ts | 2 - updates.md | 4 + 4 files changed, 129 insertions(+), 223 deletions(-) diff --git a/src/serviceFeatures/replication/centralCompatibilityRecovery.ts b/src/serviceFeatures/replication/centralCompatibilityRecovery.ts index 19148427..b3753568 100644 --- a/src/serviceFeatures/replication/centralCompatibilityRecovery.ts +++ b/src/serviceFeatures/replication/centralCompatibilityRecovery.ts @@ -1,48 +1,22 @@ -import { - VERSIONING_DOCID, - type EntryDoc, - type ObsidianLiveSyncSettings, -} from "@vrtmrz/livesync-commonlib/compat/common/types"; +import type { ObsidianLiveSyncSettings } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { assessTweakCompatibility } from "@vrtmrz/livesync-commonlib/settings"; import { LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, Logger } from "octagonal-wheels/common/logger"; -import { skipIfDuplicated } from "octagonal-wheels/concurrency/lock"; -import { balanceChunkPurgedDBs, purgeUnreferencedChunks } from "@vrtmrz/livesync-commonlib/compat/pouchdb/chunks"; -import { LiveSyncCouchDBReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator"; import { CENTRAL_COMPATIBILITY_REJECTION_REASONS, - REPLICATION_PROGRESS_PRESENTATIONS, - assessRemoteFeatureDocument, - describeRemoteFeatureRejection, type ReplicatorInstance, type ReplicationFailureRequest, } from "@vrtmrz/livesync-commonlib/replication"; import { $msg } from "@/common/translation"; -import { usesLegacyIndexedDBAdapter } from "@/common/compatibilitySettings"; import type { LiveSyncBaseCore } from "@/LiveSyncBaseCore"; -import type PouchDB from "pouchdb-core"; - -async function canInterpretCleanupDatabase(db: PouchDB.Database): Promise { - try { - const assessment = assessRemoteFeatureDocument(await db.get(VERSIONING_DOCID)); - if (assessment.status === "supported" || assessment.status === "older-generation") return true; - Logger(`Database cleanup cancelled: ${describeRemoteFeatureRejection(assessment)}`, LOG_LEVEL_NOTICE); - } catch (error) { - Logger("Database cleanup cancelled: feature compatibility could not be checked.", LOG_LEVEL_NOTICE); - Logger(error, LOG_LEVEL_INFO); - } - return false; -} type CentralCompatibilityRecoveryServices = Pick< LiveSyncBaseCore["services"], - "API" | "appLifecycle" | "replicator" | "setting" | "tweakValue" + "appLifecycle" | "replicator" | "setting" | "tweakValue" >; /** Collaborators for applying a compatibility decision to its failed publication. */ interface CentralCompatibilityRecoveryContext { readonly confirm: LiveSyncBaseCore["confirm"]; - /** Obtain the database only when recovery runs, after initialisation or reset. */ - readonly getLocalDatabase: () => LiveSyncBaseCore["localDatabase"]; readonly rebuilder: LiveSyncBaseCore["rebuilder"]; readonly services: CentralCompatibilityRecoveryServices; } @@ -72,89 +46,11 @@ function canMarkRemoteResolved(replicator: ReplicatorInstance): replicator is Re * replacement; the failure result is never re-read from the current instance. */ export function createCentralCompatibilityRecovery(context: CentralCompatibilityRecoveryContext) { - async function reconcileCleanedRemote( - showProgress: boolean, - setting: ObsidianLiveSyncSettings, - expectedContext: ReplicationFailureRequest["context"] - ) { - Logger("The remote database has been cleaned.", showProgress ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO); - await skipIfDuplicated("cleanup", async () => { - if (!(await canInterpretCleanupDatabase(context.getLocalDatabase().localDatabase))) return; - const count = await purgeUnreferencedChunks(context.getLocalDatabase().localDatabase, true); - const message = `The remote database has been cleaned up. -To synchronize, this device must be also cleaned up. ${count} chunk(s) will be erased from this device. -However, If there are many chunks to be deleted, maybe fetching again is faster. -We will lose the history of this device if we fetch the remote database again. -Even if you choose to clean up, you will see this option again if you exit Obsidian and then synchronise again.`; - const CHOICE_FETCH = "Fetch again"; - const CHOICE_CLEAN = "Cleanup"; - const CHOICE_DISMISS = "Dismiss"; - const selected = await context.confirm.confirmWithMessage( - "Cleaned", - message, - [CHOICE_FETCH, CHOICE_CLEAN, CHOICE_DISMISS], - CHOICE_DISMISS, - 30 - ); - if (selected == CHOICE_FETCH) { - await context.rebuilder.$performRebuildDB("localOnly"); - } - if (selected != CHOICE_CLEAN) return; - - await context.services.replicator.runBoundedRemoteActivity( - () => - context.services.replicator.runWithActiveReplicatorContext(async (activeContext) => { - if (activeContext !== expectedContext) return; - const replicator = activeContext.replicator; - if (!(replicator instanceof LiveSyncCouchDBReplicator)) return; - const localDatabase = context.getLocalDatabase(); - const remoteDatabase = await replicator.connectRemoteCouchDBWithSetting( - setting, - context.services.API.isMobile(), - true - ); - if (typeof remoteDatabase == "string") { - Logger(remoteDatabase, LOG_LEVEL_NOTICE); - return false; - } - - try { - await purgeUnreferencedChunks(localDatabase.localDatabase, false); - localDatabase.clearCaches(); - const replicated = await context.services.replicator.runFiniteReplicationActivity( - () => replicator.openOneShotReplication(setting, showProgress, false, "sync", true), - { label: "replication" } - ); - if (replicated) { - await balanceChunkPurgedDBs(localDatabase.localDatabase, remoteDatabase.db); - await purgeUnreferencedChunks(localDatabase.localDatabase, false); - localDatabase.clearCaches(); - await replicator.markRemoteResolved(setting); - Logger( - "The local database has been cleaned up.", - showProgress ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO - ); - } else { - Logger( - "Replication has been cancelled. Please try it again.", - showProgress ? LOG_LEVEL_NOTICE : LOG_LEVEL_INFO - ); - } - } finally { - await remoteDatabase.close(); - } - }), - { label: "database-cleanup" } - ); - }); - } - async function handleReplicationFailure(request: ReplicationFailureRequest): Promise { - const { context: failedContext, interaction, outcome, progressPresentation, setting } = request; - const showProgress = progressPresentation === REPLICATION_PROGRESS_PRESENTATIONS.NOTICE; + const { context: failedContext, interaction, outcome, setting } = request; if (interaction.kind === "forbidden") { // Automatic requests may report the failure, but must not enter - // tweak, lock, fetch, unlock, or cleanup dialogues. + // tweak, lock, fetch, or unlock dialogues. Logger("Replication failed on an unattended path.", LOG_LEVEL_INFO); return false; } @@ -198,14 +94,6 @@ Even if you choose to clean up, you will see this option again if you exit Obsid ) { return false; } - if ( - recovery.reason === CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED && - usesLegacyIndexedDBAdapter(setting) - ) { - await reconcileCleanedRemote(showProgress, setting, failedContext); - return false; - } - const message = $msg("Replicator.Dialogue.Locked.Message"); const CHOICE_FETCH = $msg("Replicator.Dialogue.Locked.Action.Fetch"); const CHOICE_DISMISS = $msg("Replicator.Dialogue.Locked.Action.Dismiss"); @@ -240,5 +128,5 @@ Even if you choose to clean up, you will see this option again if you exit Obsid return false; } - return Object.freeze({ handleReplicationFailure, reconcileCleanedRemote }); + return Object.freeze({ handleReplicationFailure }); } diff --git a/src/serviceFeatures/replication/centralCompatibilityRecovery.unit.spec.ts b/src/serviceFeatures/replication/centralCompatibilityRecovery.unit.spec.ts index b4a0de5a..4cb8f587 100644 --- a/src/serviceFeatures/replication/centralCompatibilityRecovery.unit.spec.ts +++ b/src/serviceFeatures/replication/centralCompatibilityRecovery.unit.spec.ts @@ -16,55 +16,86 @@ const chunkMocks = vi.hoisted(() => ({ })); vi.mock("@vrtmrz/livesync-commonlib/compat/pouchdb/chunks", () => chunkMocks); -vi.mock("@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator", () => ({ - LiveSyncCouchDBReplicator: class {}, -})); -import { LiveSyncCouchDBReplicator } from "@vrtmrz/livesync-commonlib/compat/replication/couchdb/LiveSyncReplicator"; import { createCentralCompatibilityRecovery } from "./centralCompatibilityRecovery"; describe("central compatibility recovery", () => { - it("does not count chunks for cleanup when local feature requirements are unknown", async () => { - chunkMocks.purgeUnreferencedChunks.mockClear(); - const confirmWithMessage = vi.fn(async () => "Dismiss"); - const recovery = createCentralCompatibilityRecovery({ - confirm: { confirmWithMessage }, - getLocalDatabase: () => ({ - localDatabase: { - get: vi.fn(async (id: string) => ({ - _id: id, - type: "versioninfo", - version: 13, - used_features: ["future-format-v7"], - })), - }, - }), - services: { replicator: {} }, - } as never); + describe.each([ + { name: "unknown local features", version: 13, used_features: ["future-format-v7"] }, + { name: "a legacy local version", version: 11 }, + { name: "the current local version", version: 12 }, + ])("compatibility: cleaned IndexedDB remote with $name", (localVersion) => { + it.each(["fetch", "unlock", "dismiss"] as const)( + "uses standard recovery for an explicit %s choice without legacy cleanup", + async (choice) => { + chunkMocks.purgeUnreferencedChunks.mockClear(); + chunkMocks.balanceChunkPurgedDBs.mockClear(); + const markRemoteResolved = vi.fn(async (_setting: unknown) => undefined); + const failedContext = { + provider: {}, + replicator: { markRemoteResolved }, + configurationIdentity: "cleaned-remote-test", + }; + const setting = { useIndexedDBAdapter: true } as ObsidianLiveSyncSettings; + const scheduleFetch = vi.fn(async () => undefined); + const scheduleRestart = vi.fn(); + const getLocalDatabase = vi.fn(() => ({ + localDatabase: { + get: vi.fn(async () => ({ _id: VERSIONING_DOCID, type: "versioninfo", ...localVersion })), + }, + })); + const confirmWithMessage = vi.fn(async () => "Dismiss"); + const askSelectStringDialogue = vi.fn( + async (_message: string, choices: string[]) => + choices[choice === "fetch" ? 0 : choice === "unlock" ? 1 : 2] + ); + const recovery = createCentralCompatibilityRecovery({ + confirm: { askSelectStringDialogue, confirmWithMessage }, + getLocalDatabase, + rebuilder: { scheduleFetch }, + services: { + appLifecycle: { scheduleRestart }, + replicator: { + runWithActiveReplicatorContext: async (task: (context: unknown) => unknown) => + await task(failedContext), + }, + }, + } as never); - await recovery.reconcileCleanedRemote(true, {} as ObsidianLiveSyncSettings, {} as never); + const result = await recovery.handleReplicationFailure({ + context: failedContext, + setting, + outcome: replicationFailed(new Error("cleaned"), { + reason: CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED, + }), + progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.NOTICE, + interaction: USER_INITIATED_REPLICATION_AUTHORITY, + } as never); - expect(chunkMocks.purgeUnreferencedChunks).not.toHaveBeenCalled(); - expect(confirmWithMessage).not.toHaveBeenCalled(); - }); - - it("allows cleanup counting for a legacy local version document", async () => { - chunkMocks.purgeUnreferencedChunks.mockClear(); - const confirmWithMessage = vi.fn(async () => "Dismiss"); - const recovery = createCentralCompatibilityRecovery({ - confirm: { confirmWithMessage }, - getLocalDatabase: () => ({ - localDatabase: { - get: vi.fn(async (id: string) => ({ _id: id, type: "versioninfo", version: 11 })), - }, - }), - services: { replicator: {} }, - } as never); - - await recovery.reconcileCleanedRemote(true, {} as ObsidianLiveSyncSettings, {} as never); - - expect(chunkMocks.purgeUnreferencedChunks).toHaveBeenCalledWith(expect.anything(), true); - expect(confirmWithMessage).toHaveBeenCalledOnce(); + expect(result).toBe(false); + expect(askSelectStringDialogue).toHaveBeenCalledOnce(); + const choices = askSelectStringDialogue.mock.calls[0][1]; + expect(choices).toHaveLength(3); + expect(askSelectStringDialogue).toHaveBeenCalledWith(expect.any(String), choices, { + title: expect.any(String), + defaultAction: choices[2], + timeout: 60, + }); + expect(confirmWithMessage).not.toHaveBeenCalled(); + expect(getLocalDatabase).not.toHaveBeenCalled(); + expect(chunkMocks.purgeUnreferencedChunks).not.toHaveBeenCalled(); + expect(chunkMocks.balanceChunkPurgedDBs).not.toHaveBeenCalled(); + expect(scheduleFetch).toHaveBeenCalledTimes(choice === "fetch" ? 1 : 0); + expect(scheduleRestart).toHaveBeenCalledTimes(choice === "fetch" ? 1 : 0); + expect(markRemoteResolved).toHaveBeenCalledTimes(choice === "unlock" ? 1 : 0); + if (choice === "fetch") { + expect(scheduleFetch.mock.invocationCallOrder[0]).toBeLessThan( + scheduleRestart.mock.invocationCallOrder[0] + ); + } + if (choice === "unlock") expect(markRemoteResolved).toHaveBeenCalledWith(setting); + } + ); }); it("passes the failed attempt's exact tweak assessment to mismatch resolution", async () => { @@ -139,7 +170,6 @@ describe("central compatibility recovery", () => { try { const recovery = createCentralCompatibilityRecovery({ confirm: {}, - getLocalDatabase: () => ({}), rebuilder: {}, services: { appLifecycle: {}, @@ -187,7 +217,6 @@ describe("central compatibility recovery", () => { }); const recovery = createCentralCompatibilityRecovery({ confirm: {}, - getLocalDatabase: () => ({}), rebuilder: {}, services: { appLifecycle: {}, @@ -255,7 +284,6 @@ describe("central compatibility recovery", () => { ); const recovery = createCentralCompatibilityRecovery({ confirm: {}, - getLocalDatabase: () => ({}), rebuilder: {}, services: { appLifecycle: {}, @@ -287,7 +315,10 @@ describe("central compatibility recovery", () => { expect(setPreferredRemoteTweakSettings.mock.calls[0][0]).not.toBe(effectiveSetting); }); - it("does not apply an unlock selected for a replaced failed publication", async () => { + it.each([ + CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_LOCKED, + CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED, + ])("does not apply an unlock for a replaced failed publication: %s", async (reason) => { const failedMarkResolved = vi.fn(async () => undefined); const replacementMarkResolved = vi.fn(async () => undefined); const failedContext = { provider: {}, replicator: { markRemoteResolved: failedMarkResolved } }; @@ -299,7 +330,6 @@ describe("central compatibility recovery", () => { confirm: { askSelectStringDialogue: vi.fn(async (_message: string, choices: string[]) => choices[1]), }, - getLocalDatabase: () => ({}), rebuilder: {}, services: { appLifecycle: { scheduleRestart: vi.fn() }, @@ -311,9 +341,9 @@ describe("central compatibility recovery", () => { await recovery.handleReplicationFailure({ context: failedContext, - setting: {}, + setting: { useIndexedDBAdapter: true }, outcome: replicationFailed(new Error("locked"), { - reason: CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_LOCKED, + reason, }), progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.NOTICE, interaction: USER_INITIATED_REPLICATION_AUTHORITY, @@ -324,69 +354,55 @@ describe("central compatibility recovery", () => { expect(replacementMarkResolved).not.toHaveBeenCalled(); }); - it("keeps cleaned-remote replication and balancing inside the shared activity boundary", async () => { - const activityFinished = vi.fn(); - const runBoundedRemoteActivity = vi.fn(async (task: () => unknown) => { - try { - return await task(); - } finally { - activityFinished(); - } - }); - const runFiniteReplicationActivity = vi.fn(async (task: () => unknown) => await task()); - const openOneShotReplication = vi.fn(async () => true); - const remoteDatabase = { - close: vi.fn(async () => undefined), + it.each([ + NO_INTERACTION, + { + kind: "permitted" as const, + permissions: { ...USER_INITIATED_REPLICATION_AUTHORITY.permissions, failureRecovery: false }, + }, + ])("does not recover a cleaned remote without recovery authority: %j", async (interaction) => { + const askSelectStringDialogue = vi.fn(); + const confirmWithMessage = vi.fn(); + const getLocalDatabase = vi.fn(); + const scheduleFetch = vi.fn(); + const scheduleRestart = vi.fn(); + const markRemoteResolved = vi.fn(); + const failedContext = { + provider: {}, + replicator: { markRemoteResolved }, + configurationIdentity: "cleaned-remote-test", }; - const close = vi.fn(async () => undefined); - const activeReplicator = Object.assign(new LiveSyncCouchDBReplicator({} as never), { - connectRemoteCouchDBWithSetting: vi.fn(async () => ({ db: remoteDatabase, close })), - openOneShotReplication, - markRemoteResolved: vi.fn(async () => undefined), - }); - const expectedContext = { provider: {}, replicator: activeReplicator }; const runWithActiveReplicatorContext = vi.fn(async (task: (context: unknown) => unknown) => - task(expectedContext) + task(failedContext) ); - const localDatabase = { - localDatabase: { - get: vi.fn(async () => ({ _id: VERSIONING_DOCID, type: "versioninfo", version: 12 })), - }, - clearCaches: vi.fn(), - }; - const getLocalDatabase = vi.fn(() => localDatabase); const recovery = createCentralCompatibilityRecovery({ - confirm: { confirmWithMessage: vi.fn(async () => "Cleanup") }, + confirm: { askSelectStringDialogue, confirmWithMessage }, getLocalDatabase, - rebuilder: {}, + rebuilder: { scheduleFetch }, services: { - appLifecycle: {}, - API: { isMobile: vi.fn(() => false) }, - replicator: { - runBoundedRemoteActivity, - runFiniteReplicationActivity, - runWithActiveReplicatorContext, - }, - tweakValue: {}, + appLifecycle: { scheduleRestart }, + replicator: { runWithActiveReplicatorContext }, }, } as never); - await recovery.reconcileCleanedRemote(true, {} as ObsidianLiveSyncSettings, expectedContext as never); + await expect( + recovery.handleReplicationFailure({ + context: failedContext, + setting: { useIndexedDBAdapter: true }, + outcome: replicationFailed(new Error("cleaned"), { + reason: CENTRAL_COMPATIBILITY_REJECTION_REASONS.NODE_CLEANED, + }), + progressPresentation: REPLICATION_PROGRESS_PRESENTATIONS.NOTICE, + interaction, + } as never) + ).resolves.toBe(false); - expect(runBoundedRemoteActivity).toHaveBeenCalledWith(expect.any(Function), { - label: "database-cleanup", - }); - expect(runFiniteReplicationActivity).toHaveBeenCalledWith(expect.any(Function), { - label: "replication", - }); - expect(runWithActiveReplicatorContext).toHaveBeenCalledOnce(); - expect(openOneShotReplication).toHaveBeenCalledOnce(); - expect(openOneShotReplication.mock.invocationCallOrder[0]).toBeLessThan( - activityFinished.mock.invocationCallOrder[0] - ); - expect(chunkMocks.balanceChunkPurgedDBs).toHaveBeenCalledOnce(); - expect(getLocalDatabase).toHaveBeenCalled(); - expect(close).toHaveBeenCalledOnce(); - expect(close.mock.invocationCallOrder[0]).toBeLessThan(activityFinished.mock.invocationCallOrder[0]); + expect(askSelectStringDialogue).not.toHaveBeenCalled(); + expect(confirmWithMessage).not.toHaveBeenCalled(); + expect(getLocalDatabase).not.toHaveBeenCalled(); + expect(scheduleFetch).not.toHaveBeenCalled(); + expect(scheduleRestart).not.toHaveBeenCalled(); + expect(runWithActiveReplicatorContext).not.toHaveBeenCalled(); + expect(markRemoteResolved).not.toHaveBeenCalled(); }); }); diff --git a/src/serviceFeatures/replication/index.ts b/src/serviceFeatures/replication/index.ts index 473c7bb7..884822fc 100644 --- a/src/serviceFeatures/replication/index.ts +++ b/src/serviceFeatures/replication/index.ts @@ -83,10 +83,8 @@ export function useReplicationFeature core.localDatabase, rebuilder: core.rebuilder, services: { - API: services.API, appLifecycle: services.appLifecycle, replicator: services.replicator, setting: services.setting, diff --git a/updates.md b/updates.md index 203037d0..e7aa80f8 100644 --- a/updates.md +++ b/updates.md @@ -29,6 +29,10 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi ### Synchronisation +- Devices using the legacy IndexedDB adapter now use the standard recovery dialogue when a remote retains an old cleanup lock. + - The obsolete in-place `Cleanup` option has been removed. We can fetch the remote again, explicitly unlock the device, or dismiss the dialogue; dismissal remains the default. + - Fetch replaces the local database, so preserve unsynchronised work and any required local history first. Unlock only when the local and remote databases are already aligned. Garbage Collection V3 is unchanged. + - Added an optional, device-local editing guard for substantial CouchDB LiveSync catch-up transfers. When enough incoming notes are detected, it covers the workspace until the transfer and local application queues have settled. The overlay can always be bypassed, and ordinary small transfers remain uninterrupted. - We can see CouchDB change-feed comparison progress separately for push and pull. From b5e8aa74857548f2d7ead543870041298ff6904e Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 12:03:57 +0000 Subject: [PATCH 10/24] Use keyed conflict scheduling for normal files --- .../conflictResolution/checker.ts | 37 +++++++------- .../conflictResolution.unit.spec.ts | 51 +++++++++++++++++++ 2 files changed, 68 insertions(+), 20 deletions(-) diff --git a/src/serviceFeatures/conflictResolution/checker.ts b/src/serviceFeatures/conflictResolution/checker.ts index 9882761d..d90263a3 100644 --- a/src/serviceFeatures/conflictResolution/checker.ts +++ b/src/serviceFeatures/conflictResolution/checker.ts @@ -1,5 +1,6 @@ import { LOG_LEVEL_NOTICE, + LOG_LEVEL_VERBOSE, type FilePath, type FilePathWithPrefix, type ObsidianLiveSyncSettings, @@ -7,7 +8,7 @@ import { import type { IConflictService, IVaultService } from "@vrtmrz/livesync-commonlib/compat/services/base/IService"; import type { LogFunction } from "@vrtmrz/livesync-commonlib/compat/services/lib/logUtils"; import type { ReactiveSource } from "octagonal-wheels/dataobject/reactive"; -import { QueueProcessor } from "octagonal-wheels/concurrency/processor"; +import { createConflictCheckQueue } from "@vrtmrz/livesync-commonlib/conflicts"; export type ConflictCheckingSettings = Pick; @@ -30,25 +31,21 @@ export interface ConflictCheckingHandlers { /** Create conflict-checking handlers while retaining scheduling state privately. */ export function createConflictCheckingHandlers(dependencies: ConflictCheckingDependencies): ConflictCheckingHandlers { - const conflictQueue = new QueueProcessor( - async (filenames: FilePathWithPrefix[]) => { - const filename = filenames[0]; - return await dependencies.conflict.resolve(filename); + const conflictQueue = createConflictCheckQueue({ + async process(filename) { + try { + await dependencies.conflict.resolve(filename); + } catch (error) { + dependencies.log(`Conflict check failed: ${filename}`); + dependencies.log(error, LOG_LEVEL_VERBOSE); + } + }, + // The resolver serialises shared user interactions; independent checks + // and automatic merges can use the remaining execution slots. + concurrency: 10, + onProgress(remaining) { + dependencies.conflictProcessQueueCount.value = remaining; }, - { - suspended: false, - batchSize: 1, - // No need to limit concurrency to `1` here, subsequent process will handle it, - // and some cases do not need to be synchronised (for example, auto-merge). - // Global concurrency is limited by the resolver with the UI. - concurrentLimit: 10, - delay: 0, - keepResultUntilDownstreamConnected: false, - totalRemainingReactiveSource: dependencies.conflictProcessQueueCount, - } - ).replaceEnqueueProcessor((queue, newEntity) => { - const newQueue = [...queue].filter((entry) => entry != newEntity); - return [...newQueue, newEntity]; }); const queueCheckForIfOpen = async (file: FilePathWithPrefix): Promise => { @@ -76,7 +73,7 @@ export function createConflictCheckingHandlers(dependencies: ConflictCheckingDep } }; - const ensureAllProcessed = (): Promise => conflictQueue.waitForAllProcessed(); + const ensureAllProcessed = (): Promise => conflictQueue.waitForIdle(); return { queueCheckForIfOpen, diff --git a/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts b/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts index b0aa10cf..57cde733 100644 --- a/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts +++ b/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts @@ -6,6 +6,7 @@ import { DEFAULT_SETTINGS, LOG_LEVEL_INFO, LOG_LEVEL_NOTICE, + LOG_LEVEL_VERBOSE, MISSING_OR_ERROR, NOT_CONFLICTED, type FilePath, @@ -814,6 +815,56 @@ describe("conflict resolution serviceFeature", () => { } }); + it("continues checking accepted and later paths after one resolver rejects", async () => { + const harness = createHarness(); + const failure = new Error("Conflict check failed"); + const resolve = vi.fn().mockRejectedValueOnce(failure).mockResolvedValue(undefined); + harness.conflict.resolve.setHandler(resolve, true); + const first = "failed.md" as FilePathWithPrefix; + const second = "accepted.md" as FilePathWithPrefix; + const later = "later.md" as FilePathWithPrefix; + + await Promise.all([harness.conflict.queueCheckFor(first), harness.conflict.queueCheckFor(second)]); + await expect(harness.conflict.ensureAllProcessed()).resolves.toBe(true); + await harness.conflict.queueCheckFor(later); + await expect(harness.conflict.ensureAllProcessed()).resolves.toBe(true); + + expect(resolve.mock.calls.map(([path]) => path)).toEqual([first, second, later]); + expect(harness.addLog).toHaveBeenCalledWith( + `[SF:ConflictResolution]${MARK_LOG_SEPARATOR} Conflict check failed: ${first}`, + LOG_LEVEL_INFO, + "" + ); + expect(harness.addLog).toHaveBeenCalledWith(failure, LOG_LEVEL_VERBOSE, ""); + expect(harness.conflict.conflictProcessQueueCount.value).toBe(0); + }); + + it("drains requeued automatic checks when every resolver slot is occupied", async () => { + const harness = createHarness({ settings: { syncAfterMerge: false } }); + const paths = Array.from({ length: 10 }, (_, index) => `requeue-${index}.md` as FilePathWithPrefix); + const firstChecks = new Set(); + const finishers: Array<() => void> = []; + harness.tryAutoMerge.mockImplementation(async (path: FilePathWithPrefix) => { + if (firstChecks.has(path)) return { ok: NOT_CONFLICTED }; + firstChecks.add(path); + await new Promise((resolve) => { + finishers.push(resolve); + }); + return { ok: AUTO_MERGED }; + }); + + await Promise.all(paths.map((path) => harness.conflict.queueCheckFor(path))); + await vi.waitFor(() => expect(finishers).toHaveLength(10)); + const completion = harness.conflict.ensureAllProcessed(); + for (const finish of finishers) finish(); + + await expect(completion).resolves.toBe(true); + for (const path of paths) { + expect(harness.tryAutoMerge.mock.calls.filter(([checked]) => checked === path)).toHaveLength(2); + } + expect(harness.conflict.conflictProcessQueueCount.value).toBe(0); + }); + it("honours optional conflict handlers before entering the check queue", async () => { const path = "optional.md" as FilePathWithPrefix; const harness = createHarness(); From 12d3b661fabb7f6c949102772d92d51092bc56ff Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 12:43:51 +0000 Subject: [PATCH 11/24] Remove unused ConfigSync scan processor --- .../CmdConfigSync.queue.unit.spec.ts | 2 -- src/features/ConfigSync/CmdConfigSync.ts | 34 ------------------- 2 files changed, 36 deletions(-) diff --git a/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts index 5674f803..bf93190b 100644 --- a/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts +++ b/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts @@ -54,7 +54,6 @@ async function waitForCondition(predicate: () => boolean, message: string) { afterEach(() => { for (const configSync of queueOwners.splice(0)) { configSync.pluginScanProcessor.terminateAll(); - configSync.pluginScanProcessorV2.terminateAll(); } vi.restoreAllMocks(); pluginList.set([]); @@ -102,7 +101,6 @@ describe("ConfigSync legacy catalogue queue", () => { expect(configSync.pluginScanProcessor.remaining).toBe(0); } finally { configSync?.pluginScanProcessor.terminateAll(); - configSync?.pluginScanProcessorV2.terminateAll(); await fixture.dispose(); } }); diff --git a/src/features/ConfigSync/CmdConfigSync.ts b/src/features/ConfigSync/CmdConfigSync.ts index 8a5b8f88..e6f61f43 100644 --- a/src/features/ConfigSync/CmdConfigSync.ts +++ b/src/features/ConfigSync/CmdConfigSync.ts @@ -619,40 +619,6 @@ export class ConfigSync extends LiveSyncCommands { } ).startPipeline(); - pluginScanProcessorV2 = new QueueProcessor( - async (v: AnyEntry[]) => { - const plugin = v[0]; - const path = plugin.path || this.getPath(plugin); - const oldEntry = this.pluginList.find((e) => e.documentPath == path); - if (oldEntry && oldEntry.mtime == plugin.mtime) return []; - try { - const pluginData = await this.loadPluginData(path); - if (pluginData) { - let newList = [...this.pluginList]; - newList = newList.filter((x) => x.documentPath != pluginData.documentPath); - newList.push(pluginData); - this.pluginList = newList; - pluginList.set(newList); - } - // Failed to load - return []; - } catch (ex) { - this._log(`Something happened at enumerating customization :${path}`, LOG_LEVEL_NOTICE); - this._log(ex, LOG_LEVEL_VERBOSE); - } - return []; - }, - { - suspended: false, - batchSize: 1, - concurrentLimit: 10, - delay: 100, - yieldThreshold: 10, - maintainDelay: false, - totalRemainingReactiveSource: pluginScanningCount, - } - ).startPipeline(); - filenameToUnifiedKey(path: string, termOverRide?: string) { const term = termOverRide || this.services.setting.getDeviceAndVaultName(); const category = this.getFileCategory(path); From de8c2148d1615de9d320abacad5fadb776e1d8c8 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 13:14:25 +0000 Subject: [PATCH 12/24] Replace ConfigSync queue and discard stale catalogue scans --- src/LiveSyncBaseCore.ts | 2 +- .../CmdConfigSync.catalogue.unit.spec.ts | 2 +- .../CmdConfigSync.command.unit.spec.ts | 8 +- .../CmdConfigSync.queue.unit.spec.ts | 427 +++++++++++++++++- src/features/ConfigSync/CmdConfigSync.ts | 91 ++-- src/features/ConfigSync/ConfigScanQueue.ts | 176 ++++++++ .../ConfigSync/ConfigScanQueue.unit.spec.ts | 331 ++++++++++++++ src/features/LiveSyncCommands.ts | 2 +- updates.md | 3 + 9 files changed, 983 insertions(+), 59 deletions(-) create mode 100644 src/features/ConfigSync/ConfigScanQueue.ts create mode 100644 src/features/ConfigSync/ConfigScanQueue.unit.spec.ts diff --git a/src/LiveSyncBaseCore.ts b/src/LiveSyncBaseCore.ts index 777bc164..6255cedf 100644 --- a/src/LiveSyncBaseCore.ts +++ b/src/LiveSyncBaseCore.ts @@ -308,7 +308,7 @@ export class LiveSyncBaseCore< } export interface IMinimumLiveSyncCommands { - onunload(): void; + onunload(): void | Promise; onload(): void | Promise; constructor: { name: string }; } diff --git a/src/features/ConfigSync/CmdConfigSync.catalogue.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.catalogue.unit.spec.ts index 06b04919..ddfce2b0 100644 --- a/src/features/ConfigSync/CmdConfigSync.catalogue.unit.spec.ts +++ b/src/features/ConfigSync/CmdConfigSync.catalogue.unit.spec.ts @@ -84,7 +84,7 @@ async function catalogue() { pluginListGeneration: 0, loadedManifest_mTime: new Map(), updatingV2Count: 0, - pluginScanProcessor: { clearQueue: vi.fn(), enqueue: vi.fn() }, + pluginScanProcessor: { clearPending: vi.fn(), enqueue: vi.fn() }, _log: vi.fn(), storeCustomisationFileV2: vi.fn(async () => true), }); diff --git a/src/features/ConfigSync/CmdConfigSync.command.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.command.unit.spec.ts index 5f524f8a..6124c4bd 100644 --- a/src/features/ConfigSync/CmdConfigSync.command.unit.spec.ts +++ b/src/features/ConfigSync/CmdConfigSync.command.unit.spec.ts @@ -91,7 +91,7 @@ describe("ConfigSync commands", () => { expect(showPluginSyncModal).toHaveBeenCalledOnce(); }); - it("cancels the pending configuration Notice before releasing its owned UI", () => { + it("cancels the pending configuration Notice before releasing its owned UI", async () => { const notices = { hide: vi.fn() }; const periodicPluginSweepProcessor = { disable: vi.fn() }; const configSync = Object.create(ConfigSync.prototype) as ConfigSync; @@ -102,9 +102,13 @@ describe("ConfigSync commands", () => { }, }, periodicPluginSweepProcessor, + pluginList: [], + pluginListGeneration: 0, + loadedManifest_mTime: new Map(), + pluginScanProcessor: { clearPending: vi.fn(), stop: vi.fn(async () => {}) }, }); - configSync.onunload(); + await configSync.onunload(); expect(cancelTask).toHaveBeenCalledWith("config-sync:updated-configuration"); expect(notices.hide).toHaveBeenCalledWith("config-sync:updated-configuration"); diff --git a/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts b/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts index bf93190b..98f4000d 100644 --- a/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts +++ b/src/features/ConfigSync/CmdConfigSync.queue.unit.spec.ts @@ -20,7 +20,11 @@ vi.mock("@/common/utils.ts", () => ({ isPluginMetadata: vi.fn(), scheduleTask: vi.fn(), })); -vi.mock("@/common/PeriodicProcessor.ts", () => ({ PeriodicProcessor: class PeriodicProcessor {} })); +vi.mock("@/common/PeriodicProcessor.ts", () => ({ + PeriodicProcessor: class PeriodicProcessor { + disable = vi.fn(); + }, +})); vi.mock("@/common/events.ts", () => ({ EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG: "open-plugin-sync", eventHub: { onEvent: vi.fn() }, @@ -29,7 +33,12 @@ vi.mock("@/common/translation", () => ({ $msg: (message: string) => message })); vi.mock("@/common/obsidianCommunityPlugins.ts", () => ({ getObsidianCommunityPluginManager: vi.fn() })); import { get } from "svelte/store"; -import { DEFAULT_SETTINGS, type FilePathWithPrefix } from "@vrtmrz/livesync-commonlib/compat/common/types"; +import { getDocData } from "@vrtmrz/livesync-commonlib/compat/common/utils"; +import { + DEFAULT_SETTINGS, + type AnyEntry, + type FilePathWithPrefix, +} from "@vrtmrz/livesync-commonlib/compat/common/types"; import { createOptionalFileSyncDatabase, optionalFileEntry } from "../../../test/fixtures/optionalFileSyncDatabase"; import { ConfigSync, pluginIsEnumerating, pluginList } from "./CmdConfigSync"; @@ -44,16 +53,63 @@ function deferred() { } async function waitForCondition(predicate: () => boolean, message: string) { - for (let attempt = 0; attempt < 30; attempt++) { + for (let attempt = 0; attempt < 100; attempt++) { if (predicate()) return; await Promise.resolve(); } throw new Error(message); } -afterEach(() => { +function queueEntry(path: string, data: unknown = {}): AnyEntry { + const documentPath = path as FilePathWithPrefix; + return { + _id: documentPath, + path: documentPath, + mtime: 2_000, + data: [JSON.stringify(data)], + } as unknown as AnyEntry; +} + +function legacyCatalogueEntry(path: string, name: string, mtime = 2_000): AnyEntry { + return queueEntry(path, { + category: "PLUGIN_MAIN", + name, + term: "device", + mtime, + files: [ + { + filename: `plugins/${name}/main.js`, + data: [`legacy source for ${name}`], + mtime, + size: name.length, + hash: `hash-${name}`, + }, + ], + }); +} + +function createQueueConfigSync( + settings: typeof DEFAULT_SETTINGS, + localDatabase: unknown, + services: unknown = { + API: { addLog: vi.fn(), addRibbonIcon: vi.fn() }, + path: { getPath: (entry: { path: string }) => entry.path }, + context: { notices: { hide: vi.fn() } }, + } +) { + vi.spyOn(ConfigSync.prototype, "onBindFunction").mockImplementation(() => {}); + const configSync = new ConfigSync({ + settings, + localDatabase, + services, + } as unknown as ConstructorParameters[0]); + queueOwners.push(configSync); + return configSync; +} + +afterEach(async () => { for (const configSync of queueOwners.splice(0)) { - configSync.pluginScanProcessor.terminateAll(); + await configSync.pluginScanProcessor.stop(); } vi.restoreAllMocks(); pluginList.set([]); @@ -62,6 +118,356 @@ afterEach(() => { }); describe("ConfigSync legacy catalogue queue", () => { + it("starts duplicate entries in FIFO order with ten concurrent items", async () => { + const settings = { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: true }; + const configSync = createQueueConfigSync(settings, {}); + const paths = [ + "ix:device/PLUGIN_MAIN/first.md", + "ix:device/PLUGIN_MAIN/second.md", + "ix:device/PLUGIN_MAIN/duplicate.md", + "ix:device/PLUGIN_MAIN/third.md", + "ix:device/PLUGIN_MAIN/duplicate.md", + "ix:device/PLUGIN_MAIN/fourth.md", + "ix:device/PLUGIN_MAIN/fifth.md", + "ix:device/PLUGIN_MAIN/sixth.md", + "ix:device/PLUGIN_MAIN/seventh.md", + "ix:device/PLUGIN_MAIN/eighth.md", + "ix:device/PLUGIN_MAIN/ninth.md", + "ix:device/PLUGIN_MAIN/tenth.md", + ]; + const gate = deferred(); + const started: string[] = []; + let active = 0; + let maximumActive = 0; + vi.spyOn(configSync, "migrateV1ToV2").mockImplementation(async (_showMessage, entry) => { + started.push(entry.path); + active++; + maximumActive = Math.max(maximumActive, active); + await gate.promise; + active--; + }); + + try { + for (const path of paths) + configSync.pluginScanProcessor.enqueue({ entry: queueEntry(path), generation: 0 }); + await waitForCondition(() => started.length === 10, "The first ten queue items did not start"); + + expect(started).toEqual(paths.slice(0, 10)); + expect(maximumActive).toBe(10); + + gate.resolve(); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); + expect(started).toEqual(paths); + } finally { + gate.resolve(); + } + }); + + it("continues with queued items after a migration throws", async () => { + const settings = { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: true }; + const configSync = createQueueConfigSync(settings, {}); + const paths = Array.from({ length: 11 }, (_, index) => `ix:device/PLUGIN_MAIN/item-${index}.md`); + const gate = deferred(); + const started: string[] = []; + vi.spyOn(configSync, "migrateV1ToV2").mockImplementation(async (_showMessage, entry) => { + started.push(entry.path); + if (entry.path === paths[0]) throw new Error("migration failed"); + if (paths.slice(1, 10).includes(entry.path)) await gate.promise; + }); + + try { + for (const path of paths) + configSync.pluginScanProcessor.enqueue({ entry: queueEntry(path), generation: 0 }); + await waitForCondition(() => started.length === 10, "The first ten queue items did not start"); + await waitForCondition(() => started.length === 11, "The item after the failed migration did not start"); + + gate.resolve(); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); + expect(started).toEqual(paths); + } finally { + gate.resolve(); + } + }); + + it("does not restore an old read result after reloading a newer catalogue", async () => { + vi.useFakeTimers(); + const oldPath = "ix:device/PLUGIN_MAIN/old" as FilePathWithPrefix; + const newerPath = "ix:device/PLUGIN_MAIN/newer" as FilePathWithPrefix; + const oldEntry = legacyCatalogueEntry(oldPath, "old"); + const newerEntry = legacyCatalogueEntry(newerPath, "newer", 3_000); + const oldRead = deferred(); + let scanCount = 0; + let oldReadStarted = false; + const localDatabase = { + findEntries: vi.fn(async function* () { + for (const entry of scanCount++ === 0 ? [oldEntry] : [newerEntry]) yield entry; + }), + getDBEntry: vi.fn(async (path: FilePathWithPrefix) => { + if (path === oldPath) { + oldReadStarted = true; + await oldRead.promise; + return oldEntry; + } + return newerEntry; + }), + }; + const settings = { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: false }; + const configSync = createQueueConfigSync(settings, localDatabase); + + try { + await configSync.updatePluginList(false); + await vi.advanceTimersByTimeAsync(100); + await waitForCondition(() => oldReadStarted, "The old catalogue read did not start"); + + await configSync.reloadPluginList(false); + await vi.advanceTimersByTimeAsync(100); + expect(configSync.pluginList.map((entry) => entry.name)).toEqual(["newer"]); + + oldRead.resolve(); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); + expect(configSync.pluginList.map((entry) => entry.name)).toEqual(["newer"]); + expect(get(pluginList).map((entry) => entry.name)).toEqual(["newer"]); + } finally { + oldRead.resolve(); + await vi.advanceTimersByTimeAsync(100); + } + }); + + it.each(["catalogue update", "settings application", "temporary suspension"] as const)( + "does not restore an active legacy read after disabling through %s and re-enabling", + async (route) => { + vi.useFakeTimers(); + const oldPath = "ix:device/PLUGIN_MAIN/old" as FilePathWithPrefix; + const oldEntry = legacyCatalogueEntry(oldPath, "old"); + const oldRead = deferred(); + let oldReadStarted = false; + let scanCount = 0; + const localDatabase = { + findEntries: vi.fn(async function* () { + if (scanCount++ === 0) yield oldEntry; + }), + getDBEntry: vi.fn(async () => { + oldReadStarted = true; + await oldRead.promise; + return oldEntry; + }), + }; + const settings = { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: false }; + const configSync = createQueueConfigSync(settings, localDatabase); + + try { + await configSync.updatePluginList(false); + await vi.advanceTimersByTimeAsync(100); + await waitForCondition(() => oldReadStarted, "The active legacy read did not start"); + + settings.usePluginSync = false; + if (route === "catalogue update") { + await configSync.updatePluginList(false); + } else if (route === "settings application") { + await configSync._everyRealizeSettingSyncMode(); + } else { + await ( + configSync as unknown as { _allSuspendExtraSync(): Promise } + )._allSuspendExtraSync(); + } + settings.usePluginSync = true; + await configSync.updatePluginList(false); + + oldRead.resolve(); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); + expect(configSync.pluginList).toEqual([]); + expect(get(pluginList)).toEqual([]); + } finally { + oldRead.resolve(); + await vi.advanceTimersByTimeAsync(100); + } + } + ); + + it("stops admission on unload and joins a read without changing the replacement instance's list", async () => { + vi.useFakeTimers(); + const entry = legacyCatalogueEntry("ix:device/PLUGIN_MAIN/old", "old"); + const read = deferred(); + const localDatabase = { + findEntries: vi.fn(async function* () { + yield entry; + }), + getDBEntry: vi.fn(async () => { + await read.promise; + return entry; + }), + }; + const settings = { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: false }; + const configSync = createQueueConfigSync(settings, localDatabase); + try { + await configSync.updatePluginList(false); + await vi.advanceTimersByTimeAsync(100); + expect(localDatabase.getDBEntry).toHaveBeenCalledOnce(); + let stopped = false; + const done = configSync.onunload().then(() => { + stopped = true; + }); + const replacement = { name: "replacement" } as (typeof configSync.pluginList)[number]; + pluginList.set([replacement]); + await configSync.updatePluginList(false); + await configSync.reloadPluginList(false); + await vi.advanceTimersByTimeAsync(100); + expect(localDatabase.findEntries).toHaveBeenCalledOnce(); + expect(stopped).toBe(false); + expect(configSync.pluginScanProcessor.remaining).toBe(1); + read.resolve(); + await done; + expect(configSync.pluginList).toEqual([]); + expect(get(pluginList)).toEqual([replacement]); + expect(configSync.pluginScanProcessor.remaining).toBe(0); + } finally { + read.resolve(); + await vi.advanceTimersByTimeAsync(100); + } + }); + + it("cancels unstarted legacy reads when the first ten are blocked and the module is disabled", async () => { + const paths = Array.from({ length: 12 }, (_, index) => `ix:device/PLUGIN_MAIN/item-${index}`); + const entries = paths.map((path, index) => legacyCatalogueEntry(path, `item-${index}`)); + const gates = entries.slice(0, 10).map(() => deferred()); + const started: string[] = []; + const localDatabase = { + findEntries: vi.fn(async function* () { + for (const entry of entries) yield entry; + }), + getDBEntry: vi.fn(async (path: FilePathWithPrefix) => { + const index = paths.indexOf(path); + started.push(path); + if (index >= 0 && index < gates.length) await gates[index].promise; + return entries[index]; + }), + }; + const settings = { ...DEFAULT_SETTINGS, usePluginSync: true, usePluginSyncV2: false }; + const configSync = createQueueConfigSync(settings, localDatabase); + + try { + await configSync.updatePluginList(false); + await waitForCondition(() => started.length === 10, "The first ten legacy reads did not start"); + + settings.usePluginSync = false; + await configSync.updatePluginList(false); + for (const gate of gates) gate.resolve(); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); + + expect(started).toEqual(paths.slice(0, 10)); + } finally { + for (const gate of gates) gate.resolve(); + } + }); + + it("finishes a started V1-to-V2 migration but does not start pending migrations after disable", async () => { + const fixture = await createOptionalFileSyncDatabase(); + const v1Path = "ix:device/PLUGIN_MAIN/migrate.md" as FilePathWithPrefix; + const v2Path = "ix:device/PLUGIN_MAIN/migrate%main.js" as FilePathWithPrefix; + const source = "module.exports = 'migrated';"; + const data = { + category: "PLUGIN_MAIN", + name: "migrate", + term: "device", + mtime: 2_000, + files: [ + { + filename: "plugins/migrate/main.js", + data: [source], + mtime: 2_000, + size: source.length, + hash: "migration-source-hash", + }, + ], + }; + const settings = fixture.settings; + const configSync = createQueueConfigSync(settings, fixture.localDatabase, { + ...fixture.services, + API: { ...fixture.services.API, addRibbonIcon: vi.fn() }, + }); + const pendingGate = deferred(); + const putGate = deferred(); + const migrationFinished = deferred(); + const started: string[] = []; + let v2PutStarted = false; + + try { + await expect( + fixture.localDatabase.putDBEntry(optionalFileEntry(v1Path, JSON.stringify(data))) + ).resolves.toMatchObject({ ok: true }); + + const loadedLegacy = { + ...optionalFileEntry(v1Path, JSON.stringify(data)), + data: [JSON.stringify(data)], + } as unknown as Awaited>; + let migrationRead = false; + const read = fixture.localDatabase.getDBEntry.bind(fixture.localDatabase); + vi.spyOn(fixture.localDatabase, "getDBEntry").mockImplementation(async (path, ...args) => { + if (path === v1Path && !migrationRead) { + migrationRead = true; + return loadedLegacy; + } + return await read(path, ...args); + }); + const migrate = configSync.migrateV1ToV2.bind(configSync); + vi.spyOn(configSync, "migrateV1ToV2").mockImplementation(async (showMessage, entry) => { + started.push(entry.path); + if (entry.path === v1Path) { + try { + await migrate(showMessage, entry); + } finally { + migrationFinished.resolve(); + } + return; + } + await pendingGate.promise; + }); + const put = fixture.localDatabase.putDBEntry.bind(fixture.localDatabase); + vi.spyOn(fixture.localDatabase, "putDBEntry").mockImplementation(async (...args) => { + if ((args[0] as { path?: string }).path === v2Path) { + v2PutStarted = true; + await putGate.promise; + } + return await put(...args); + }); + + const paths = [ + v1Path, + ...Array.from( + { length: 10 }, + (_, index) => `ix:device/PLUGIN_MAIN/pending-${index}.md` as FilePathWithPrefix + ), + ]; + for (const path of paths) + configSync.pluginScanProcessor.enqueue({ entry: queueEntry(path), generation: 0 }); + await waitForCondition( + () => started.length === 10, + `The first ten migrations did not start: ${started.join(", ")}` + ); + await waitForCondition(() => v2PutStarted, "The migration did not reach its write"); + + settings.usePluginSync = false; + await configSync.updatePluginList(false); + putGate.resolve(); + await migrationFinished.promise; + expect.soft(started).toEqual(paths.slice(0, 10)); + + pendingGate.resolve(); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); + expect.soft(started).toEqual(paths.slice(0, 10)); + + const migrated = await fixture.localDatabase.getDBEntry(v2Path, undefined, false, false); + expect(migrated).not.toBe(false); + if (migrated !== false) expect(getDocData(migrated.data)).toContain(source); + await expect(fixture.localDatabase.getDBEntry(v1Path)).resolves.toBe(false); + } finally { + putGate.resolve(); + pendingGate.resolve(); + await configSync.pluginScanProcessor.waitForIdle(); + await fixture.dispose(); + } + }); + it("loads legacy catalogue contents through the database with native timers", async () => { const fixture = await createOptionalFileSyncDatabase(); const path = "ix:device/PLUGIN_MAIN/native-timers" as FilePathWithPrefix; @@ -89,7 +495,7 @@ describe("ConfigSync legacy catalogue queue", () => { } as unknown as ConstructorParameters[0]); queueOwners.push(configSync); await configSync.updatePluginList(false); - expect(await configSync.pluginScanProcessor.waitForAllProcessed(2_000)).toBe(true); + await expect(configSync.pluginScanProcessor.waitForIdle()).resolves.toBeUndefined(); expect(configSync.pluginList).toEqual([ { ...data, @@ -100,7 +506,7 @@ describe("ConfigSync legacy catalogue queue", () => { expect(get(pluginList)).toEqual(configSync.pluginList); expect(configSync.pluginScanProcessor.remaining).toBe(0); } finally { - configSync?.pluginScanProcessor.terminateAll(); + await configSync?.pluginScanProcessor.stop(); await fixture.dispose(); } }); @@ -148,7 +554,6 @@ describe("ConfigSync legacy catalogue queue", () => { try { await configSync.updatePluginList(false); - expect(configSync.pluginScanProcessor.delay).toBe(100); expect(configSync.pluginScanProcessor.remaining).toBe(1); expect(configSync.pluginList).toEqual([]); expect(get(pluginIsEnumerating)).toBe(false); @@ -159,9 +564,9 @@ describe("ConfigSync legacy catalogue queue", () => { await vi.advanceTimersByTimeAsync(1); expect(loadHasStarted).toBe(true); expect(configSync.pluginScanProcessor.remaining).toBe(1); - const drain = configSync.pluginScanProcessor.waitForAllProcessed(); - void drain.then((result) => { - drained = result; + const drain = configSync.pluginScanProcessor.waitForIdle(); + void drain.then(() => { + drained = true; }); readGate.resolve(); diff --git a/src/features/ConfigSync/CmdConfigSync.ts b/src/features/ConfigSync/CmdConfigSync.ts index e6f61f43..55b11869 100644 --- a/src/features/ConfigSync/CmdConfigSync.ts +++ b/src/features/ConfigSync/CmdConfigSync.ts @@ -55,7 +55,6 @@ import { stripAllPrefixes } from "@vrtmrz/livesync-commonlib/compat/string_and_b import { cancelTask, EVEN, isCustomisationSyncMetadata, isPluginMetadata, scheduleTask } from "@/common/utils.ts"; import { PeriodicProcessor } from "@/common/PeriodicProcessor.ts"; import { JsonResolveModal } from "@/features/HiddenFileCommon/JsonResolveModal.ts"; -import { QueueProcessor } from "octagonal-wheels/concurrency/processor"; import { pluginScanningCount } from "@vrtmrz/livesync-commonlib/compat/mock_and_interop/stores"; import { base64ToArrayBuffer, base64ToString } from "octagonal-wheels/binary/base64"; import { ConflictResolveModal } from "@/modules/features/InteractiveConflictResolving/ConflictResolveModal.ts"; @@ -74,6 +73,7 @@ import { createModificationHandler } from "octagonal-wheels/modification"; import type { HandlerOutcome } from "@vrtmrz/livesync-commonlib/compat/services/lib/HandlerUtils"; import type { OptionalFileEventOptions } from "@vrtmrz/livesync-commonlib/compat/services/base/IService"; import { PendingConfigSaves } from "./PendingConfigSaves"; +import { ConfigScanQueue } from "./ConfigScanQueue"; const d = "\u200b"; const d2 = "\n"; @@ -394,13 +394,6 @@ export type PluginDataEx = { }; export class ConfigSync extends LiveSyncCommands { - constructor(core: LiveSyncCore) { - super(core); - pluginScanningCount.onChanged((e) => { - const total = e.value; - pluginIsEnumerating.set(total != 0); - }); - } get configDir() { return this.core.services.API.getSystemConfigDir(); } @@ -423,6 +416,7 @@ export class ConfigSync extends LiveSyncCommands { pluginList: IPluginDataExDisplay[] = []; private pluginListGeneration = 0; + private unloaded = false; showPluginSyncModal() { if (!this.isThisModuleEnabled()) { return; @@ -441,11 +435,18 @@ export class ConfigSync extends LiveSyncCommands { this.pluginDialog = undefined; } } - onunload() { + onunload(): Promise { + this.unloaded = true; + this.resetPluginList(); + const stopped = this.pluginScanProcessor.stop(); + pluginScanningCount.value = 0; + pluginIsEnumerating.set(false); + cancelTask("updatePluginListV2"); cancelTask(UPDATED_CONFIGURATION_NOTICE_KEY); this.hidePluginSyncModal(); this.periodicPluginSweepProcessor?.disable(); this.services.context.notices.hide(UPDATED_CONFIGURATION_NOTICE_KEY); + return stopped; } addRibbonIcon = this.services.API.addRibbonIcon.bind(this.services.API); onload() { @@ -542,11 +543,21 @@ export class ConfigSync extends LiveSyncCommands { q?.toggleClass("sls-hidden", !this.isThisModuleEnabled()); return Promise.resolve(true); } - async reloadPluginList(showMessage: boolean) { + private isCurrentPluginList(generation: number): boolean { + return !this.unloaded && generation === this.pluginListGeneration && this.isThisModuleEnabled(); + } + + private resetPluginList(): void { this.pluginListGeneration++; + this.pluginScanProcessor.clearPending(); this.pluginList = []; this.loadedManifest_mTime.clear(); pluginList.set(this.pluginList); + } + + async reloadPluginList(showMessage: boolean) { + if (this.unloaded) return; + this.resetPluginList(); await this.updatePluginList(showMessage); } async loadPluginData(path: FilePathWithPrefix): Promise { @@ -581,43 +592,37 @@ export class ConfigSync extends LiveSyncCommands { return false; } - pluginScanProcessor = new QueueProcessor( - async (v: AnyEntry[]) => { - const plugin = v[0]; - if (this.useV2) { - await this.migrateV1ToV2(false, plugin); - return []; - } - const path = plugin.path || this.getPath(plugin); - const oldEntry = this.pluginList.find((e) => e.documentPath == path); - if (oldEntry && oldEntry.mtime == plugin.mtime) return []; + pluginScanProcessor = new ConfigScanQueue<{ entry: AnyEntry; generation: number }>({ + process: async ({ entry: plugin, generation }) => { + if (!this.isCurrentPluginList(generation)) return; try { + if (this.useV2) { + // Once started, migration owns its writes through completion. + await this.migrateV1ToV2(false, plugin); + return; + } + const path = plugin.path || this.getPath(plugin); + const oldEntry = this.pluginList.find((entry) => entry.documentPath == path); + if (oldEntry && oldEntry.mtime == plugin.mtime) return; const pluginData = await this.loadPluginData(path); + if (!this.isCurrentPluginList(generation)) return; if (pluginData) { - let newList = [...this.pluginList]; - newList = newList.filter((x) => x.documentPath != pluginData.documentPath); + const newList = this.pluginList.filter((entry) => entry.documentPath != pluginData.documentPath); newList.push(pluginData); this.pluginList = newList; pluginList.set(newList); } - // Failed to load - return []; } catch (ex) { - this._log(`Something happened at enumerating customization :${path}`, LOG_LEVEL_NOTICE); + this._log(`Something happened at enumerating customization :${plugin.path}`, LOG_LEVEL_NOTICE); this._log(ex, LOG_LEVEL_VERBOSE); } - return []; }, - { - suspended: false, - batchSize: 1, - concurrentLimit: 10, - delay: 100, - yieldThreshold: 10, - maintainDelay: false, - totalRemainingReactiveSource: pluginScanningCount, - } - ).startPipeline(); + onProgress: (remaining) => { + if (this.unloaded) return; + pluginScanningCount.value = remaining; + pluginIsEnumerating.set(remaining !== 0); + }, + }); filenameToUnifiedKey(path: string, termOverRide?: string) { const term = termOverRide || this.services.setting.getDeviceAndVaultName(); @@ -740,7 +745,7 @@ export class ConfigSync extends LiveSyncCommands { async updatePluginListV2(showMessage: boolean, unifiedFilenameWithKey: FilePathWithPrefix): Promise { const generation = this.pluginListGeneration; - const isCurrent = () => generation === this.pluginListGeneration && this.isThisModuleEnabled(); + const isCurrent = () => this.isCurrentPluginList(generation); try { this.updatingV2Count++; pluginV2Progress.set(this.updatingV2Count); @@ -855,11 +860,9 @@ export class ConfigSync extends LiveSyncCommands { } async updatePluginList(showMessage: boolean, updatedDocumentPath?: FilePathWithPrefix): Promise { + if (this.unloaded) return; if (!this.isThisModuleEnabled()) { - this.pluginListGeneration++; - this.pluginScanProcessor.clearQueue(); - this.pluginList = []; - pluginList.set(this.pluginList); + this.resetPluginList(); return; } const generation = this.pluginListGeneration; @@ -875,7 +878,7 @@ export class ConfigSync extends LiveSyncCommands { }) : this.localDatabase.findEntries(ICXHeader + "", `${ICXHeader}\u{10ffff}`, { include_docs: true }); for await (const v of plugins) { - if (generation !== this.pluginListGeneration || !this.isThisModuleEnabled()) return; + if (!this.isCurrentPluginList(generation)) return; if (v.deleted || v._deleted) continue; if (v.path.indexOf("%") !== -1) { fireAndForget(() => this.updatePluginListV2(showMessage, v.path)); @@ -884,7 +887,7 @@ export class ConfigSync extends LiveSyncCommands { const path = v.path || this.getPath(v); if (updatedDocumentPath && updatedDocumentPath != path) continue; - this.pluginScanProcessor.enqueue(v); + this.pluginScanProcessor.enqueue({ entry: v, generation }); } } finally { pluginIsEnumerating.set(false); @@ -1206,6 +1209,7 @@ export class ConfigSync extends LiveSyncCommands { return true; } _everyRealizeSettingSyncMode(): Promise { + if (!this.isThisModuleEnabled()) this.resetPluginList(); // applySettings calls onResuming after this handler when synchronisation is active. // That handler scans and restarts the sweep; doing so here would scan twice. this.periodicPluginSweepProcessor?.disable(); @@ -1742,6 +1746,7 @@ export class ConfigSync extends LiveSyncCommands { this.core.settings.usePluginSync = false; this.core.settings.autoSweepPlugins = false; } + this.resetPluginList(); return Promise.resolve(true); } diff --git a/src/features/ConfigSync/ConfigScanQueue.ts b/src/features/ConfigSync/ConfigScanQueue.ts new file mode 100644 index 00000000..dd960dd0 --- /dev/null +++ b/src/features/ConfigSync/ConfigScanQueue.ts @@ -0,0 +1,176 @@ +import { compatGlobal, type CompatTimeoutHandle } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; +import { createNotifier } from "octagonal-wheels/concurrency/notifier"; +import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { withScope, type Awaitable } from "octagonal-wheels/resource/scope"; + +interface ConfigScanQueueOptions { + /** The caller logs recoverable item failures and decides whether to continue. */ + process: (item: T) => Awaitable; + onProgress?: (remaining: number) => void; +} + +type PendingScan = { value: T }; + +/** Owns FIFO admission, the initial scan delay, and completion for one catalogue. */ +export class ConfigScanQueue { + private pending: (PendingScan | undefined)[] = []; + private head = 0; + private active = 0; + private ready = false; + private stopped = false; + private stoppingAfterFailure = false; + private readonly failures: unknown[] = []; + private timer?: CompatTimeoutHandle; + private running?: Promise; + private readonly changed = createNotifier(); + + constructor(private readonly options: ConfigScanQueueOptions) {} + + private get pendingCount() { + return this.pending.length - this.head; + } + + get remaining(): number { + return this.pendingCount + this.active; + } + + enqueue(value: T): void { + if (!this.canDispatch()) throw new Error("The customisation scan queue is closed."); + this.pending.push({ value }); + this.reportProgress(); + this.schedule(); + } + + /** Discard unstarted scans; active reads and migrations retain their slots. */ + clearPending(): void { + this.pending = []; + this.head = 0; + this.ready = false; + this.clearTimer(); + this.reportProgress(); + } + + /** Stop admission and join active work. A processor must not await its own stop. */ + stop(): Promise { + this.stopped = true; + this.clearPending(); + return this.waitForIdle(); + } + + /** Include later arrivals until the queue is idle; this does not close admission. */ + async waitForIdle(): Promise { + this.schedule(); + while (this.running || this.timer !== undefined) await this.changed.wait(); + if (this.failures.length === 1) throw this.failures[0]; + if (this.failures.length > 1) { + throw Object.assign(new Error("Customisation scans failed."), { errors: [...this.failures] }); + } + } + + private canDispatch(): boolean { + return !this.stopped && !this.stoppingAfterFailure; + } + + private clearTimer(): void { + if (this.timer === undefined) return; + compatGlobal.clearTimeout(this.timer); + this.timer = undefined; + } + + private recordFailure(error: unknown): void { + this.stoppingAfterFailure = true; + this.failures.push(error); + this.clearTimer(); + this.changed.notify(); + } + + private reportProgress(): void { + if (this.failures.length === 0) { + try { + this.options.onProgress?.(this.remaining); + } catch (error) { + this.recordFailure(error); + } + } + this.changed.notify(); + } + + private claim(entry: PendingScan): boolean { + if (!this.canDispatch() || this.pending[this.head] !== entry) return false; + this.pending[this.head++] = undefined; + if (this.pendingCount === 0) { + this.pending = []; + this.head = 0; + this.ready = false; + } else if (this.head >= 1024 && this.head * 2 >= this.pending.length) { + this.pending = this.pending.slice(this.head); + this.head = 0; + } + return true; + } + + private async *availableWork() { + while (this.canDispatch()) { + const entry = this.pending[this.head]; + if (this.ready && entry) { + // The callback claims the item so clearing a pulled item also cancels it. + yield entry; + } else if (this.active > 0) { + // Keep free slots available to later arrivals while a slow scan finishes. + await this.changed.wait(); + } else { + return; + } + } + } + + private schedule(): void { + if (!this.canDispatch() || this.pendingCount === 0) return; + if (!this.ready) { + if (this.pendingCount > 10) { + this.ready = true; + this.clearTimer(); + } else if (this.timer === undefined) { + this.timer = compatGlobal.setTimeout(() => { + this.timer = undefined; + this.ready = true; + this.schedule(); + this.changed.notify(); + }, 100); + } + } + if (!this.ready || this.running) return; + this.running = Promise.resolve() + .then(() => + withScope(undefined, (parent) => + forEachInScope(parent, this.availableWork(), { concurrency: 10 }, async (entry, child) => { + if (!this.claim(entry)) return; + this.active++; + child.defer(() => { + this.active--; + this.reportProgress(); + }); + this.reportProgress(); + if (!this.canDispatch()) return; + try { + await this.options.process(entry.value); + } catch (error) { + this.stoppingAfterFailure = true; + this.clearTimer(); + this.changed.notify(); + throw error; + } + }) + ) + ) + .then( + (): void => undefined, + (error: unknown) => this.recordFailure(error) + ) + .finally(() => { + this.running = undefined; + this.schedule(); + this.changed.notify(); + }); + } +} diff --git a/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts b/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts new file mode 100644 index 00000000..c1182d2b --- /dev/null +++ b/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts @@ -0,0 +1,331 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ConfigScanQueue } from "./ConfigScanQueue"; + +const queues: { stop(): Promise }[] = []; +const releases: (() => void)[] = []; + +function gate() { + let resolve!: () => void; + const promise = new Promise((done) => { + resolve = done; + }); + releases.push(resolve); + return { promise, resolve }; +} + +function queue(options: ConstructorParameters>[0]) { + const result = new ConfigScanQueue(options); + queues.push(result); + return result; +} + +beforeEach(() => vi.useFakeTimers()); +afterEach(async () => { + for (const release of releases.splice(0)) release(); + await Promise.all(queues.splice(0).map((item) => item.stop().catch(() => {}))); + vi.useRealTimers(); +}); + +describe("ConfigScanQueue", () => { + it("waits from the first arrival without extending the delay for later arrivals", async () => { + const seen: string[] = []; + const scans = queue({ + process: (item) => { + seen.push(item); + }, + }); + scans.enqueue("first"); + await vi.advanceTimersByTimeAsync(50); + scans.enqueue("second"); + await vi.advanceTimersByTimeAsync(49); + expect(seen).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + await scans.waitForIdle(); + expect(seen).toEqual(["first", "second"]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("bypasses the delay only when pending work exceeds ten items", async () => { + const seen: number[] = []; + const scans = queue({ + process: (item) => { + seen.push(item); + }, + }); + for (let item = 0; item < 10; item++) scans.enqueue(item); + await vi.advanceTimersByTimeAsync(0); + expect(seen).toEqual([]); + scans.enqueue(10); + await vi.advanceTimersByTimeAsync(0); + await scans.waitForIdle(); + expect(seen).toEqual(Array.from({ length: 11 }, (_, index) => index)); + expect(vi.getTimerCount()).toBe(0); + }); + + it("keeps duplicate items in FIFO order and admits at most ten active scans", async () => { + const finish = Array.from({ length: 13 }, () => gate()); + const input = Array.from({ length: 13 }, (_, index) => index % 3); + const seen: number[] = []; + let active = 0; + let maximum = 0; + const progress: number[] = []; + const scans = queue({ + process: async (item) => { + const index = seen.length; + seen.push(item); + maximum = Math.max(maximum, ++active); + await finish[index].promise; + active--; + }, + onProgress: (remaining) => progress.push(remaining), + }); + input.forEach((item) => scans.enqueue(item)); + await vi.advanceTimersByTimeAsync(0); + expect(seen).toEqual(input.slice(0, 10)); + expect(scans.remaining).toBe(13); + finish[3].resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(seen).toEqual(input.slice(0, 11)); + finish.forEach((item) => item.resolve()); + await scans.waitForIdle(); + expect(seen).toEqual(input); + expect(maximum).toBe(10); + expect(scans.remaining).toBe(0); + expect(progress[progress.length - 1]).toBe(0); + }); + + it("starts a later arrival in a free slot before an earlier slow scan finishes", async () => { + const slow = gate(); + const seen: string[] = []; + const scans = queue({ + process: async (item) => { + seen.push(item); + if (item === "slow") await slow.promise; + }, + }); + scans.enqueue("slow"); + await vi.advanceTimersByTimeAsync(100); + let idle = false; + const done = scans.waitForIdle().then(() => { + idle = true; + }); + scans.enqueue("later"); + await vi.advanceTimersByTimeAsync(100); + expect(seen).toEqual(["slow", "later"]); + expect(idle).toBe(false); + slow.resolve(); + await done; + expect(scans.remaining).toBe(0); + }); + + it("clears delayed scans and gives replacement work its own delay", async () => { + const seen: string[] = []; + const scans = queue({ + process: (item) => { + seen.push(item); + }, + }); + scans.enqueue("old"); + await vi.advanceTimersByTimeAsync(50); + scans.clearPending(); + expect(scans.remaining).toBe(0); + expect(vi.getTimerCount()).toBe(0); + await scans.waitForIdle(); + scans.enqueue("new"); + await vi.advanceTimersByTimeAsync(99); + expect(seen).toEqual([]); + await vi.advanceTimersByTimeAsync(1); + await scans.waitForIdle(); + expect(seen).toEqual(["new"]); + }); + + it("discards all unstarted work while active scans remain tracked", async () => { + const finish = gate(); + const seen: number[] = []; + const scans = queue({ + process: async (item) => { + seen.push(item); + await finish.promise; + }, + }); + for (let item = 0; item < 50; item++) scans.enqueue(item); + await vi.advanceTimersByTimeAsync(0); + expect(seen).toHaveLength(10); + scans.clearPending(); + expect(scans.remaining).toBe(10); + let idle = false; + const done = scans.waitForIdle().then(() => { + idle = true; + }); + await vi.advanceTimersByTimeAsync(0); + expect(idle).toBe(false); + finish.resolve(); + await done; + expect(seen).toEqual(Array.from({ length: 10 }, (_, index) => index)); + expect(scans.remaining).toBe(0); + }); + + it("stops while waiting for input, joins active work, and rejects later admission", async () => { + const finish = gate(); + const seen: number[] = []; + const scans = queue({ + process: async (item) => { + seen.push(item); + await finish.promise; + }, + }); + scans.enqueue(1); + await vi.advanceTimersByTimeAsync(100); + scans.enqueue(2); + let stopped = false; + const done = scans.stop().then(() => { + stopped = true; + }); + expect(() => scans.enqueue(3)).toThrow("closed"); + expect(vi.getTimerCount()).toBe(0); + await vi.advanceTimersByTimeAsync(0); + expect(stopped).toBe(false); + finish.resolve(); + await done; + expect(seen).toEqual([1]); + expect(scans.remaining).toBe(0); + await scans.stop(); + }); + + it("stops before the first scan without leaving a timer", async () => { + const process = vi.fn(); + const scans = queue({ process }); + scans.enqueue("pending"); + await scans.stop(); + await vi.advanceTimersByTimeAsync(100); + expect(process).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); + + it("observes an unhandled item failure after other started work settles", async () => { + const fail = gate(); + const finish = gate(); + const failure = new Error("read failed"); + const seen: number[] = []; + const scans = queue({ + process: async (item) => { + seen.push(item); + if (item === 0) { + await fail.promise; + throw failure; + } + await finish.promise; + }, + }); + for (let item = 0; item < 12; item++) scans.enqueue(item); + await vi.advanceTimersByTimeAsync(0); + let error: unknown; + const done = scans.waitForIdle().catch((reason: unknown) => { + error = reason; + }); + fail.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(error).toBeUndefined(); + expect(seen).toHaveLength(10); + expect(() => scans.enqueue(12)).toThrow("closed"); + finish.resolve(); + await done; + expect(error).toBe(failure); + expect(scans.remaining).toBe(2); + }); + + it("includes work enqueued by an active scan in an existing idle wait", async () => { + const seen: string[] = []; + const scans = queue({ + process: (item) => { + seen.push(item); + if (item === "first") scans.enqueue("follow-up"); + }, + }); + scans.enqueue("first"); + let idle = false; + const done = scans.waitForIdle().then(() => { + idle = true; + }); + await vi.advanceTimersByTimeAsync(100); + expect(seen).toEqual(["first"]); + expect(idle).toBe(false); + await vi.advanceTimersByTimeAsync(100); + await done; + expect(seen).toEqual(["first", "follow-up"]); + expect(vi.getTimerCount()).toBe(0); + }); + + it("wakes an input wait when its only active scan fails", async () => { + const finish = gate(); + const failure = new Error("read failed"); + const scans = queue({ + process: async () => { + await finish.promise; + throw failure; + }, + }); + scans.enqueue("only"); + await vi.advanceTimersByTimeAsync(100); + const done = expect(scans.waitForIdle()).rejects.toBe(failure); + finish.resolve(); + await done; + expect(scans.remaining).toBe(0); + }); + + it("rejects an existing idle wait if observing completion fails", async () => { + const finish = gate(); + const failure = new Error("observer failed"); + const scans = queue({ + process: () => finish.promise, + onProgress: (remaining) => { + if (remaining === 0) throw failure; + }, + }); + scans.enqueue("active"); + await vi.advanceTimersByTimeAsync(100); + const done = expect(scans.waitForIdle()).rejects.toBe(failure); + finish.resolve(); + await done; + expect(scans.remaining).toBe(0); + }); + + it("retains both an observer failure and a later failure from active work", async () => { + const finish = gate(); + const observerFailure = new Error("observer failed"); + const readFailure = new Error("read failed"); + const scans = queue({ + process: async () => { + await finish.promise; + throw readFailure; + }, + onProgress: (remaining) => { + if (remaining === 2) throw observerFailure; + }, + }); + scans.enqueue("active"); + await vi.advanceTimersByTimeAsync(100); + scans.enqueue("pending"); + const done = expect(scans.waitForIdle()).rejects.toMatchObject({ + message: "Customisation scans failed.", + errors: [observerFailure, readFailure], + }); + finish.resolve(); + await done; + }); + + it("wakes an idle waiter when the progress observer fails", async () => { + const failure = new Error("observer failed"); + const process = vi.fn(); + const scans = queue({ + process, + onProgress: () => { + throw failure; + }, + }); + scans.enqueue("pending"); + await expect(scans.waitForIdle()).rejects.toBe(failure); + expect(process).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); +}); diff --git a/src/features/LiveSyncCommands.ts b/src/features/LiveSyncCommands.ts index 3f1ec783..d3467549 100644 --- a/src/features/LiveSyncCommands.ts +++ b/src/features/LiveSyncCommands.ts @@ -43,7 +43,7 @@ export abstract class LiveSyncCommands { this._log = createInstanceLogFunction(this.constructor.name, this.services.API); // __$checkInstanceBinding(this); } - abstract onunload(): void; + abstract onunload(): void | Promise; abstract onload(): void | Promise; _isMainReady() { diff --git a/updates.md b/updates.md index e7aa80f8..2b43202c 100644 --- a/updates.md +++ b/updates.md @@ -14,6 +14,9 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi ### Fixes +- Reloading the Customisation Sync catalogue no longer allows an earlier legacy-format scan to put outdated items back into the list. + - Reloading or disabling Customisation Sync discards unstarted scans and ignores stale read results. Migrations to per-file storage which have already started are allowed to finish. + - Buttons in confirmation and setup dialogues now align with the content above them. Confirmation dialogue buttons also have space for keyboard focus outlines. - Mobile confirmation dialogues now retain Obsidian's standard content spacing. Text and password prompts stay above the software keyboard. From dfb6215e7798f5a13a2ea46934aceb2ad5774c7e Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 14:48:57 +0000 Subject: [PATCH 13/24] Replace hidden-file conflict processors with scoped queues --- .../CmdHiddenFileSync.queue.unit.spec.ts | 213 +++++++++++++++++- .../HiddenFileSync/CmdHiddenFileSync.ts | 71 +++--- .../HiddenFileSync/HiddenFileConflictQueue.ts | 209 +++++++++++++++++ .../HiddenFileConflictQueue.unit.spec.ts | 194 ++++++++++++++++ 4 files changed, 641 insertions(+), 46 deletions(-) create mode 100644 src/features/HiddenFileSync/HiddenFileConflictQueue.ts create mode 100644 src/features/HiddenFileSync/HiddenFileConflictQueue.unit.spec.ts diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts index fbf68283..056e46a7 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts @@ -3,7 +3,11 @@ import { afterEach, describe, expect, it, vi } from "vitest"; vi.mock("@/deps.ts", () => ({})); vi.mock("@/features/HiddenFileCommon/JsonResolveModal.ts", () => ({ JsonResolveModal: class JsonResolveModal {} })); vi.mock("@/modules/features/ModuleLog.ts", () => ({ MARK_DONE: "" })); -vi.mock("@/common/PeriodicProcessor.ts", () => ({ PeriodicProcessor: class PeriodicProcessor {} })); +vi.mock("@/common/PeriodicProcessor.ts", () => ({ + PeriodicProcessor: class PeriodicProcessor { + disable = vi.fn(); + }, +})); vi.mock("./configureHiddenFileSyncMode.ts", () => ({ configureHiddenFileSyncMode: vi.fn() })); import { @@ -51,7 +55,7 @@ function createHiddenFileSync(localDatabase: object) { afterEach(() => { for (const hiddenFileSync of queueOwners.splice(0)) { - hiddenFileSync.conflictResolutionProcessor.terminateAll(); + hiddenFileSync.conflictResolutionProcessor.dispose(); } vi.restoreAllMocks(); vi.useRealTimers(); @@ -90,7 +94,6 @@ describe("HiddenFileSync conflict queue", () => { let completed = false; hiddenFileSync.queueConflictCheck(path); try { - expect(hiddenFileSync.conflictResolutionProcessor.delay).toBe(10); await waitForCondition( () => hiddenFileSync.conflictResolutionProcessor.remaining === 1, "The initial conflict check was not queued" @@ -168,7 +171,6 @@ describe("HiddenFileSync conflict queue", () => { let completed = false; hiddenFileSync.queueConflictCheck(path); try { - expect(hiddenFileSync.conflictResolutionProcessor.delay).toBe(10); await waitForCondition( () => hiddenFileSync.conflictResolutionProcessor.remaining === 1, "The initial conflict check was not queued" @@ -196,3 +198,206 @@ describe("HiddenFileSync conflict queue", () => { } }); }); + +describe("HiddenFileSync pipeline contracts", () => { + it("starts above the threshold, limits analysis to five, and retains FIFO input", async () => { + vi.useFakeTimers(); + const gates = Array.from({ length: 11 }, () => deferred()); + const paths = gates.map((_, index) => `i:.obsidian/${index}.txt` as FilePathWithPrefix); + const reads: string[] = []; + const getRaw = vi.fn((id: DocumentID) => { + reads.push(id); + return gates[paths.indexOf(id as unknown as FilePathWithPrefix)].promise; + }); + const { hiddenFileSync } = createHiddenFileSync({ getRaw }); + hiddenFileSync.path2id = async (path) => path as unknown as DocumentID; + for (const path of paths.slice(0, 10)) hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(0); + expect(reads).toEqual([]); + hiddenFileSync.queueConflictCheck(paths[10]); + await vi.advanceTimersByTimeAsync(0); + expect(reads).toEqual(paths.slice(0, 5)); + hiddenFileSync.queueConflictCheck(paths[0]); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(11); + gates[0].resolve({ path: paths[0] } as MetaEntry); + await vi.advanceTimersByTimeAsync(0); + expect(reads).toEqual(paths.slice(0, 6)); + gates.forEach((gate, index) => gate.resolve({ path: paths[index] } as MetaEntry)); + await vi.advanceTimersByTimeAsync(100); + expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(true); + expect(reads).toEqual(paths); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + }); + + it("continues analysis while one manual dialogue is open and serialises the dialogues", async () => { + vi.useFakeTimers(); + const paths = Array.from({ length: 12 }, (_, index) => `i:.obsidian/${index}.json` as FilePathWithPrefix); + const gates = paths.map(() => deferred()); + const localDatabase = { + getRaw: vi.fn(async (id: DocumentID, options?: { revs_info?: boolean }) => + options?.revs_info + ? {} + : { + _id: id, + path: id, + _rev: "2-current", + _conflicts: ["2-other"], + } + ), + getDBEntry: vi.fn(async (path: FilePathWithPrefix) => ({ path }) as LoadedEntry), + managers: { conflictManager: { mergeObject: vi.fn(async () => false) } }, + }; + const { hiddenFileSync } = createHiddenFileSync(localDatabase); + hiddenFileSync.path2id = async (path) => path as unknown as DocumentID; + const opened: FilePathWithPrefix[] = []; + hiddenFileSync.showJSONMergeDialogAndMerge = vi.fn((doc) => { + opened.push(doc.path); + return gates[paths.indexOf(doc.path)].promise; + }); + paths.forEach((path) => hiddenFileSync.queueConflictCheck(path)); + await vi.advanceTimersByTimeAsync(100); + expect(localDatabase.managers.conflictManager.mergeObject).toHaveBeenCalledTimes(12); + expect(opened).toEqual([paths[0]]); + paths.forEach((path) => hiddenFileSync.queueConflictCheck(path)); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(12); + let completed = false; + void hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed().then(() => { + completed = true; + }); + for (let index = 0; index < paths.length; index++) { + expect(opened).toEqual(paths.slice(0, index + 1)); + expect(completed).toBe(false); + gates[index].resolve(false); + await vi.advanceTimersByTimeAsync(100); + } + expect(completed).toBe(true); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + }); + + it("logs an analysis error and continues with later paths", async () => { + vi.useFakeTimers(); + const failure = new Error("Injected read failure"); + const getRaw = vi.fn().mockRejectedValueOnce(failure).mockResolvedValue({}); + const { hiddenFileSync } = createHiddenFileSync({ getRaw }); + hiddenFileSync.path2id = async (path) => path as unknown as DocumentID; + hiddenFileSync.queueConflictCheck("i:bad.txt" as FilePathWithPrefix); + hiddenFileSync.queueConflictCheck("i:good.txt" as FilePathWithPrefix); + await vi.advanceTimersByTimeAsync(100); + expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(true); + expect(getRaw).toHaveBeenCalledTimes(2); + expect(hiddenFileSync._log).toHaveBeenCalledWith(failure, expect.anything()); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + }); + + it("collects a conflict enumeration before resuming analysis", async () => { + vi.useFakeTimers(); + const gate = deferred(); + const path = "i:.obsidian/scanned.txt" as FilePathWithPrefix; + const getRaw = vi.fn(async () => ({})); + const { hiddenFileSync } = createHiddenFileSync({ + getRaw, + findEntries: async function* () { + await gate.promise; + yield { _id: path, path, _conflicts: ["2-other"] }; + }, + }); + hiddenFileSync.path2id = async (value) => value as unknown as DocumentID; + const result = hiddenFileSync.resolveConflictOnInternalFiles(); + await vi.advanceTimersByTimeAsync(100); + hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(100); + expect(getRaw).not.toHaveBeenCalled(); + gate.resolve(); + await vi.advanceTimersByTimeAsync(100); + await result; + expect(getRaw).toHaveBeenCalledOnce(); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + }); +}); + +describe("HiddenFileSync conflict queue ownership", () => { + it("stops delayed work on unload and rejects later conflict events", async () => { + vi.useFakeTimers(); + const getRaw = vi.fn(async () => ({})); + const { hiddenFileSync } = createHiddenFileSync({ getRaw }); + hiddenFileSync.path2id = async (path) => path as unknown as DocumentID; + const path = "i:.obsidian/queued.txt" as FilePathWithPrefix; + hiddenFileSync.queueConflictCheck(path); + const idle = hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed(); + hiddenFileSync.onunload(); + hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(100); + expect(await idle).toBe(false); + expect(getRaw).not.toHaveBeenCalled(); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + expect(vi.getTimerCount()).toBe(0); + }); + + it("finishes an admitted analysis without handing its result to a new dialogue after unload", async () => { + vi.useFakeTimers(); + const gate = deferred(); + const path = "i:.obsidian/active.json" as FilePathWithPrefix; + const getRaw = vi + .fn() + .mockImplementationOnce(() => gate.promise) + .mockResolvedValue({}); + const getDBEntry = vi.fn(async () => ({ path })); + const mergeObject = vi.fn(async () => false); + const { hiddenFileSync } = createHiddenFileSync({ + getRaw, + getDBEntry, + managers: { conflictManager: { mergeObject } }, + }); + hiddenFileSync.path2id = async () => path as unknown as DocumentID; + hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(10); + expect(getRaw).toHaveBeenCalledOnce(); + hiddenFileSync.onunload(); + expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(false); + gate.resolve({ + _id: String(path) as DocumentID, + path, + _rev: "2-current", + _conflicts: ["2-other"], + } as MetaEntry); + await vi.advanceTimersByTimeAsync(100); + expect(mergeObject).toHaveBeenCalledOnce(); + expect(getDBEntry).not.toHaveBeenCalled(); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + }); + + it("does not requeue a manual resolution which finishes after unload", async () => { + vi.useFakeTimers(); + const gate = deferred(); + const path = "i:.obsidian/dialogue.json" as FilePathWithPrefix; + const getRaw = vi.fn(async (_id: DocumentID, options?: { revs_info?: boolean }) => + options?.revs_info + ? {} + : { + _id: path, + path, + _rev: "2-current", + _conflicts: ["2-other"], + } + ); + const getDBEntry = vi.fn(async () => ({ path }) as LoadedEntry); + const { hiddenFileSync } = createHiddenFileSync({ + getRaw, + getDBEntry, + managers: { conflictManager: { mergeObject: async () => false } }, + }); + hiddenFileSync.path2id = async () => path as unknown as DocumentID; + hiddenFileSync.showJSONMergeDialogAndMerge = vi.fn(() => gate.promise); + hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(20); + expect(hiddenFileSync.showJSONMergeDialogAndMerge).toHaveBeenCalledOnce(); + hiddenFileSync.onunload(); + expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(false); + gate.resolve(true); + await vi.advanceTimersByTimeAsync(100); + expect(getRaw).toHaveBeenCalledTimes(2); + expect(getDBEntry).toHaveBeenCalledTimes(2); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + expect(hiddenFileSync.conflictResolutionProcessor.totalRemaining).toBe(0); + }); +}); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.ts index d3911831..ed31cc49 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.ts @@ -45,7 +45,7 @@ import { JsonResolveModal } from "@/features/HiddenFileCommon/JsonResolveModal.t import { LiveSyncCommands } from "@/features/LiveSyncCommands.ts"; import { addPrefix, stripAllPrefixes } from "@vrtmrz/livesync-commonlib/compat/string_and_binary/path"; import { createCoalescingNotifier } from "octagonal-wheels/concurrency/coalescingNotifier"; -import { QueueProcessor } from "octagonal-wheels/concurrency/processor"; +import { HiddenFileConflictQueue } from "./HiddenFileConflictQueue.ts"; import { hiddenFilesEventCount, hiddenFilesProcessingCount, @@ -108,6 +108,8 @@ export class HiddenFileSync extends LiveSyncCommands { } onunload() { this.periodicInternalFileScanProcessor?.disable(); + this.conflictResolutionProcessor.dispose(); + this.pendingConflictChecks.clear(); } onload() { this.services.API.addCommand({ @@ -745,7 +747,7 @@ Offline Changed files: ${processFiles.length}`; queueConflictCheck(path: FilePathWithPrefix) { if (this.pendingConflictChecks.has(path)) return; this.pendingConflictChecks.add(path); - this.conflictResolutionProcessor.enqueue(path); + if (!this.conflictResolutionProcessor.enqueue(path)) this.pendingConflictChecks.delete(path); } finishConflictCheck(path: FilePathWithPrefix) { @@ -802,9 +804,8 @@ Offline Changed files: ${processFiles.length}`; } // check the file again } - conflictResolutionProcessor = new QueueProcessor( - async (paths: FilePathWithPrefix[]) => { - const path = paths[0]; + conflictResolutionProcessor = new HiddenFileConflictQueue( + async (path: FilePathWithPrefix) => { try { // Retrieve data const id = await this.path2id(path, ICHeader); @@ -872,46 +873,32 @@ Offline Changed files: ${processFiles.length}`; return []; } }, - { - suspended: false, - batchSize: 1, - concurrentLimit: 5, - delay: 10, - keepResultUntilDownstreamConnected: true, - yieldThreshold: 10, - pipeTo: new QueueProcessor( - async (results) => { - const { id, doc, path, revA, revB } = results[0]; - const prefixedPath = addPrefix(path, ICHeader); - const docAMerge = await this.localDatabase.getDBEntry(prefixedPath, { rev: revA }); - const docBMerge = await this.localDatabase.getDBEntry(prefixedPath, { rev: revB }); - try { - if (docAMerge != false && docBMerge != false) { - if (await this.showJSONMergeDialogAndMerge(docAMerge, docBMerge)) { - // Again for other conflicted revisions. - this.requeueConflictCheck(path); - } else { - this.finishConflictCheck(path); - } - return; - } else { - // If either revision could not read, force resolving by the newer one. - await this.resolveByNewerEntry(id, path, doc, revA, revB); - } - } catch (ex) { + async (result) => { + const { id, doc, path, revA, revB } = result; + const prefixedPath = addPrefix(path, ICHeader); + const docAMerge = await this.localDatabase.getDBEntry(prefixedPath, { rev: revA }); + const docBMerge = await this.localDatabase.getDBEntry(prefixedPath, { rev: revB }); + try { + if (docAMerge != false && docBMerge != false) { + if (await this.showJSONMergeDialogAndMerge(docAMerge, docBMerge)) { + // Again for other conflicted revisions. + this.requeueConflictCheck(path); + } else { this.finishConflictCheck(path); - throw ex; } - }, - { - suspended: false, - batchSize: 1, - concurrentLimit: 1, - delay: 10, - keepResultUntilDownstreamConnected: false, - yieldThreshold: 10, + return; + } else { + // If either revision could not read, force resolving by the newer one. + await this.resolveByNewerEntry(id, path, doc, revA, revB); } - ), + } catch (ex) { + this.finishConflictCheck(path); + throw ex; + } + }, + (error) => { + this._log("Processor error!"); + this._log(error, LOG_LEVEL_VERBOSE); } ); diff --git a/src/features/HiddenFileSync/HiddenFileConflictQueue.ts b/src/features/HiddenFileSync/HiddenFileConflictQueue.ts new file mode 100644 index 00000000..7a123764 --- /dev/null +++ b/src/features/HiddenFileSync/HiddenFileConflictQueue.ts @@ -0,0 +1,209 @@ +import { compatGlobal, type CompatTimeoutHandle } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; +import { withCancellation } from "octagonal-wheels/concurrency/cancellation"; +import { createNotifier } from "octagonal-wheels/concurrency/notifier"; +import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { createAsyncQueue } from "octagonal-wheels/iterable/asyncQueue"; +import { withOwnedResource } from "octagonal-wheels/resource"; + +/** The scheduling used by one hidden-file conflict stage. */ +class ConflictStage { + private readonly input = createAsyncQueue(); + private readonly reader = this.input[Symbol.asyncIterator](); + private readonly changed = createNotifier(); + private readonly cancellation = new AbortController(); + private timer: CompatTimeoutHandle | undefined; + private ready = false; + private suspended = false; + private stopped = false; + private outstanding = 0; + active = 0; + + constructor( + concurrency: number, + process: (item: T) => Promise, + private readonly notify: () => void, + onError: (error: unknown) => void, + onFailure: (error: unknown) => void + ) { + // The operation owns its input until started callbacks have settled. + // Abort also releases input immediately, before that final cleanup. + void withCancellation(undefined, { signal: this.cancellation.signal }, (scope) => { + const stopInput = () => { + this.input.dispose(); + this.clearTimer(); + this.changed.notify(); + }; + scope.signal.addEventListener("abort", stopInput, { once: true }); + scope.defer(() => scope.signal.removeEventListener("abort", stopInput)); + return withOwnedResource(this.input, () => + forEachInScope(scope, this.availableItems(), { concurrency }, async (entry) => { + while (this.suspended && !this.stopped) await this.changed.wait(); + if (this.stopped) return; + this.active++; + try { + await process(entry.value); + } catch (error) { + try { + onError(error); + } catch (reportingError) { + // Wake a pending input pull before the runner joins + // its other callbacks after an unexpected failure. + onFailure(reportingError); + throw reportingError; + } + } finally { + this.active--; + this.outstanding--; + this.notify(); + } + }) + ); + }).catch(onFailure); + } + + get remaining() { + return this.outstanding; + } + + enqueue(item: T): boolean { + if (this.stopped) return false; + this.input.enqueue(item); + this.outstanding++; + this.schedule(); + this.notify(); + return true; + } + + private clearTimer() { + if (this.timer === undefined) return; + compatGlobal.clearTimeout(this.timer); + this.timer = undefined; + } + + private schedule() { + if (this.stopped || this.suspended || this.input.size === 0) return; + if (this.ready || this.input.size > 10) { + this.clearTimer(); + this.ready = true; + this.changed.notify(); + } else if (this.timer === undefined) { + this.timer = compatGlobal.setTimeout(() => { + this.timer = undefined; + this.ready = true; + this.changed.notify(); + }, 10); + } + } + + private async *availableItems() { + while (!this.stopped) { + while (!this.stopped && (this.suspended || !this.ready || this.input.size === 0)) { + await this.changed.wait(); + } + if (this.stopped) return; + const entry = await this.reader.next(); + if (entry.done) return; + if (this.input.size === 0) { + this.ready = false; + this.clearTimer(); + } + // Outstanding includes this pulled item until its callback finishes. + yield { value: entry.value }; + } + } + + suspend() { + this.suspended = true; + this.ready = false; + this.clearTimer(); + } + + resume() { + if (!this.suspended || this.stopped) return; + this.suspended = false; + this.schedule(); + this.changed.notify(); + } + + dispose() { + if (this.stopped) return; + this.stopped = true; + this.outstanding = this.active; + this.cancellation.abort(); + this.notify(); + } +} + +/** Two hidden-file stages: five analyses, followed by one manual resolution. */ +export class HiddenFileConflictQueue { + private readonly changed = createNotifier(); + private readonly analysis: ConflictStage; + private readonly resolution: ConflictStage; + private stopped = false; + private failure: { error: unknown } | undefined; + + constructor( + analyse: (item: T) => Promise, + resolve: (item: U) => Promise, + onError: (error: unknown) => void + ) { + const notify = () => this.changed.notify(); + const onFailure = (error: unknown) => { + this.failure ??= { error }; + this.dispose(); + }; + this.resolution = new ConflictStage(1, resolve, notify, onError, onFailure); + this.analysis = new ConflictStage( + 5, + async (item) => { + const results = await analyse(item); + for (const result of results) this.resolution.enqueue(result); + }, + notify, + onError, + onFailure + ); + } + + enqueue(item: T): boolean { + return this.analysis.enqueue(item); + } + + get nowProcessing() { + return this.analysis.active; + } + + get remaining() { + return this.analysis.remaining; + } + + get totalRemaining() { + return this.analysis.remaining + this.resolution.remaining; + } + + suspend() { + this.analysis.suspend(); + } + + startPipeline(): this { + this.analysis.resume(); + return this; + } + + /** Includes handoff and self-requeues; disposal is never successful drainage. */ + async waitForAllProcessed(): Promise { + this.startPipeline(); + while (!this.stopped && this.totalRemaining > 0) await this.changed.wait(); + if (this.failure) throw this.failure.error; + return !this.stopped; + } + + /** Stop admission and release pending work without waiting for active dialogue or writes. */ + dispose() { + if (this.stopped) return; + this.stopped = true; + this.analysis.dispose(); + this.resolution.dispose(); + this.changed.notify(); + } +} diff --git a/src/features/HiddenFileSync/HiddenFileConflictQueue.unit.spec.ts b/src/features/HiddenFileSync/HiddenFileConflictQueue.unit.spec.ts new file mode 100644 index 00000000..d4a51f48 --- /dev/null +++ b/src/features/HiddenFileSync/HiddenFileConflictQueue.unit.spec.ts @@ -0,0 +1,194 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { HiddenFileConflictQueue } from "./HiddenFileConflictQueue.ts"; + +const owners: { dispose(): void }[] = []; +function deferred() { + let resolve!: (value: T | PromiseLike) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} +function own(queue: HiddenFileConflictQueue) { + owners.push(queue); + return queue; +} + +afterEach(async () => { + owners.splice(0).forEach((owner) => owner.dispose()); + if (vi.isFakeTimers()) await vi.runAllTimersAsync(); + vi.useRealTimers(); +}); + +describe("HiddenFileConflictQueue", () => { + it("awaits repeated handoffs and self-requeues with native timers", async () => { + const seen: number[] = []; + let queue!: HiddenFileConflictQueue; + queue = own( + new HiddenFileConflictQueue( + async (value: number) => [value], + async (value) => { + seen.push(value); + if (value < 3) queue.enqueue(value + 1); + }, + vi.fn() + ) + ); + queue.enqueue(0); + expect(await queue.waitForAllProcessed()).toBe(true); + expect(seen).toEqual([0, 1, 2, 3]); + expect(queue.totalRemaining).toBe(0); + }); + + it("uses the first arrival's ten-millisecond delay in each stage", async () => { + vi.useFakeTimers(); + const analyse = vi.fn(async (value: number) => [value]); + const resolve = vi.fn(async (_value: number) => {}); + const queue = own(new HiddenFileConflictQueue(analyse, resolve, vi.fn())); + queue.enqueue(1); + await vi.advanceTimersByTimeAsync(9); + queue.enqueue(2); + expect(analyse).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(analyse.mock.calls).toEqual([[1], [2]]); + expect(resolve).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(9); + expect(resolve).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(resolve.mock.calls).toEqual([[1], [2]]); + expect(await queue.waitForAllProcessed()).toBe(true); + expect(queue.totalRemaining).toBe(0); + expect(vi.getTimerCount()).toBe(0); + }); + + it("starts both stages immediately above ten waiting items", async () => { + vi.useFakeTimers(); + const gate = deferred(); + const analyse = vi.fn(async (value: number) => [value]); + const resolve = vi.fn(async (_value: number) => { + await gate.promise; + }); + const queue = own(new HiddenFileConflictQueue(analyse, resolve, vi.fn())); + for (let value = 0; value < 11; value++) queue.enqueue(value); + await vi.advanceTimersByTimeAsync(0); + expect(analyse).toHaveBeenCalledTimes(11); + expect(resolve).toHaveBeenCalledTimes(1); + expect(queue.totalRemaining).toBe(11); + gate.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(resolve.mock.calls).toEqual(Array.from({ length: 11 }, (_, value) => [value])); + expect(await queue.waitForAllProcessed()).toBe(true); + }); + + it("logs item failures in both stages and continues without implicit retry", async () => { + vi.useFakeTimers(); + const first = new Error("analysis failed"); + const second = new Error("resolution failed"); + const analyse = vi.fn(async (value: number) => { + if (value === 1) throw first; + return [value]; + }); + const resolve = vi.fn(async (value: number) => { + if (value === 2) throw second; + }); + const onError = vi.fn(); + const queue = own(new HiddenFileConflictQueue(analyse, resolve, onError)); + [1, 2, 3].forEach((value) => queue.enqueue(value)); + await vi.advanceTimersByTimeAsync(20); + expect(onError.mock.calls).toEqual([[first], [second]]); + expect(analyse.mock.calls).toEqual([[1], [2], [3]]); + expect(resolve.mock.calls).toEqual([[2], [3]]); + expect(await queue.waitForAllProcessed()).toBe(true); + }); + + it("discards delayed input and releases idle waiters on disposal", async () => { + vi.useFakeTimers(); + const analyse = vi.fn(async (value: number) => [value]); + const resolve = vi.fn(async (_value: number) => {}); + const queue = own(new HiddenFileConflictQueue(analyse, resolve, vi.fn())); + queue.enqueue(1); + const idle = queue.waitForAllProcessed(); + queue.dispose(); + queue.dispose(); + expect(await idle).toBe(false); + expect(queue.enqueue(2)).toBe(false); + expect(queue.totalRemaining).toBe(0); + await vi.advanceTimersByTimeAsync(100); + expect(analyse).not.toHaveBeenCalled(); + expect(resolve).not.toHaveBeenCalled(); + expect(vi.getTimerCount()).toBe(0); + }); + + it("does not wait for active analysis or admit its late handoff and self-requeue after disposal", async () => { + vi.useFakeTimers(); + const gate = deferred(); + const attempted: boolean[] = []; + let finished = 0; + const analyse = vi.fn(async (value: number) => { + await gate.promise; + attempted.push(queue.enqueue(value)); + finished++; + return [value]; + }); + const resolve = vi.fn(async (_value: number) => {}); + const queue = own(new HiddenFileConflictQueue(analyse, resolve, vi.fn())); + for (let value = 0; value < 12; value++) queue.enqueue(value); + await vi.advanceTimersByTimeAsync(0); + expect(analyse).toHaveBeenCalledTimes(5); + const idle = queue.waitForAllProcessed(); + queue.dispose(); + expect(await idle).toBe(false); + expect(finished).toBe(0); + expect(queue.totalRemaining).toBe(5); + gate.resolve(); + await vi.advanceTimersByTimeAsync(100); + expect(finished).toBe(5); + expect(attempted).toEqual([false, false, false, false, false]); + expect(analyse).toHaveBeenCalledTimes(5); + expect(resolve).not.toHaveBeenCalled(); + expect(queue.totalRemaining).toBe(0); + expect(vi.getTimerCount()).toBe(0); + }); + + it("leaves an active dialogue running and discards the next dialogue", async () => { + vi.useFakeTimers(); + const gate = deferred(); + let finished = false; + const resolve = vi.fn(async (_value: number) => { + await gate.promise; + finished = true; + }); + const queue = own(new HiddenFileConflictQueue(async (value: number) => [value], resolve, vi.fn())); + queue.enqueue(1); + queue.enqueue(2); + await vi.advanceTimersByTimeAsync(20); + expect(resolve).toHaveBeenCalledTimes(1); + queue.dispose(); + expect(await queue.waitForAllProcessed()).toBe(false); + expect(finished).toBe(false); + gate.resolve(); + await vi.advanceTimersByTimeAsync(100); + expect(finished).toBe(true); + expect(resolve).toHaveBeenCalledTimes(1); + expect(queue.totalRemaining).toBe(0); + }); + + it("suspends analysis while already handed-off manual work continues", async () => { + vi.useFakeTimers(); + const analyse = vi.fn(async (value: number) => [value]); + const resolve = vi.fn(async (_value: number) => {}); + const queue = own(new HiddenFileConflictQueue(analyse, resolve, vi.fn())); + queue.enqueue(1); + await vi.advanceTimersByTimeAsync(10); + queue.suspend(); + queue.enqueue(2); + await vi.advanceTimersByTimeAsync(100); + expect(analyse.mock.calls).toEqual([[1]]); + expect(resolve.mock.calls).toEqual([[1]]); + queue.startPipeline(); + await vi.advanceTimersByTimeAsync(20); + expect(analyse.mock.calls).toEqual([[1], [2]]); + expect(resolve.mock.calls).toEqual([[1], [2]]); + expect(await queue.waitForAllProcessed()).toBe(true); + }); +}); From ceaf1f90e9cff9893f57684bba9a71cad5d7cd6f Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 15:50:19 +0000 Subject: [PATCH 14/24] Preserve newer hidden files during Merge initialisation --- .../CmdHiddenFileSync.completion.unit.spec.ts | 33 ++ .../HiddenFileSync/CmdHiddenFileSync.ts | 2 +- test/e2e-obsidian/README.md | 4 + .../scripts/hidden-file-snippet-sync.ts | 410 +++++++++++++++--- updates.md | 2 + 5 files changed, 388 insertions(+), 63 deletions(-) diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.completion.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.completion.unit.spec.ts index 5ef0e4de..d681ba74 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.completion.unit.spec.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.completion.unit.spec.ts @@ -90,6 +90,39 @@ afterEach(async () => { for (const fixture of fixtureOwners.splice(0)) await fixture.dispose(); }); +describe("Hidden File Sync initial modification times", () => { + it.each([ + { label: "newer", localMtime: 30_000, expected: "local content" }, + { label: "older", localMtime: 10_000, expected: "database content" }, + { label: "equal", localMtime: 20_000, expected: "database content" }, + ])("stores only a newer local file when the local timestamp is $label", async ({ localMtime, expected }) => { + const { fixture, hiddenFileSync, storageAccess } = await createHiddenFileSync(); + const entry = optionalFileEntry(`i:${path}`, "database content"); + entry.mtime = 20_000; + await fixture.localDatabase.putDBEntry(entry); + storageAccess.setFile("local content", localMtime); + + await hiddenFileSync.trackStorageFileModification(path, true); + + const saved = await fixture.localDatabase.getDBEntry(`i:${path}` as FilePath); + expect(saved).not.toBe(false); + if (saved) { + expect(await getText(saved)).toBe(expected); + expect(saved.mtime).toBe(expected === "local content" ? localMtime : 20_000); + } + }); + + it("stores a local-only file when only newer changes are requested", async () => { + const { fixture, hiddenFileSync } = await createHiddenFileSync(); + + await hiddenFileSync.trackStorageFileModification(path, true); + + const saved = await fixture.localDatabase.getDBEntry(`i:${path}` as FilePath); + expect(saved).not.toBe(false); + if (saved) expect(await getText(saved)).toBe(content); + }); +}); + describe("Hidden File Sync optional save outcomes", () => { it("retries a failed database write when the storage fingerprint is unchanged", async () => { const { fixture, hiddenFileSync } = await createHiddenFileSync(); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.ts index ed31cc49..20e70d11 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.ts @@ -688,7 +688,7 @@ Offline Changed files: ${processFiles.length}`; const dbMTime = getComparingMTime(filesOnDB, includeDeleted); const diff = compareMTime(storageMTime, dbMTime); - if (diff != TARGET_IS_NEW) { + if (diff != BASE_IS_NEW) { this._log(`Hidden file:${path} is not new.`, LOG_LEVEL_VERBOSE); if (filesOnDB && stat) { // OnlyNew not handles the deletion. diff --git a/test/e2e-obsidian/README.md b/test/e2e-obsidian/README.md index c61427a0..e0bc6ed6 100644 --- a/test/e2e-obsidian/README.md +++ b/test/e2e-obsidian/README.md @@ -269,6 +269,10 @@ This proves in real Obsidian the plug-in behaviour shared by supported platforms `test:e2e:obsidian:hidden-file-snippet-sync` runs a two-vault hidden file round-trip. It verifies creation and deletion of a real `.obsidian/snippets/*.css` file, automatic JSON conflict merging for a hidden file with the merged result propagated by a second synchronisation, manual JSON Resolve dialogue application through Obsidian's UI, and per-device target patterns where one vault ignores a hidden file that the other vault synchronises. That target-pattern case keeps a normal-file allow-list for Markdown and PDF files enabled on both devices, then requires exact hidden JSON content after the receiving device includes it. Initial enablement must open one user-visible progress Notice before the enabled setting is saved, then retain that Notice while its nested rebuild and scan phases continue in the ordinary log. The configured fixture starts with a current CouchDB remote profile, so migration from legacy remote settings remains the responsibility of the upgrade scenarios and cannot add unrelated Notices to this check. It also covers [issue #555](https://github.com/vrtmrz/obsidian-livesync/issues/555) by requiring several plug-in and settings changes to share one separate action Notice whose controls remain usable in mobile layouts; a manually dismissed group must not repeat its acknowledged rows when a later change arrives. +The JSON conflict cases enter through `resolveConflictOnInternalFiles()`, exercising the analysis queue and the serial manual-resolution queue. They check the stored content and remaining conflict revisions as well as the Vault files; the manual case must remain unfinished until a choice is made. + +Separate Vault pairs begin with Hidden File Sync disabled and enable it through the visible `Merge`, `Fetch`, and `Overwrite` buttons. Each pair contains a newer local file, a newer database file, and files present on only one side. The workflow verifies the selected contents in the files and database, the saved enablement setting, persistence after restart, and convergence on the other device. `--case=conflicts` runs only the conflict cases; `--case=enablement` runs only these enablement cases. Add `--mode=Merge`, `--mode=Fetch`, or `--mode=Overwrite` to select one enablement method. + `test:e2e:obsidian:hidden-file-selectors` stores and restores selected JS, CSS, and JSON files with a normal-file allow-list set, and compares both directions with an empty allow-list. It uses one temporary Vault and a local database, and also runs in the complete local suite. Run it through the focused wrapper to build the current bundle first; no remote service is required. Set `E2E_HIDDEN_FILE_SELECTORS_OUTPUT` to choose the JSON report path. Before enablement, the scenario directly requests initialisation while Hidden File Sync is disabled. It requires a refused result, unchanged local files, Metadata revisions, and processed markers, and no initialisation progress Notice. diff --git a/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts b/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts index 2a9cde9d..0853684f 100644 --- a/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts +++ b/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts @@ -1,5 +1,6 @@ -import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; +import { decodeBinary } from "octagonal-wheels/binary"; import { VERSIONING_DOCID } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { ENCRYPTED_INTERNAL_METADATA_FEATURE, REMOTE_FEATURE_GENERATION } from "@vrtmrz/livesync-commonlib/replication"; import { @@ -38,6 +39,7 @@ import { captureJsonResolveDialogue, clickJsonResolveOption, obsidianRemoteDebuggingPort, + openLiveSyncSettings, withObsidianPage, } from "../runner/ui.ts"; import { iPhoneSafeArea, setObsidianMobileTestMode } from "../runner/mobileUi.ts"; @@ -60,6 +62,7 @@ const snippetContent = [ const mergeJsonPath = ".obsidian/livesync-e2e-merge.json"; const manualMergeJsonPath = ".obsidian/livesync-e2e-manual-merge.json"; +const hiddenConflictStateKey = "__livesyncE2EHiddenConflictResolution"; const targetPath = ".obsidian/livesync-targeted/only-a.json"; const hiddenFileCliTimeoutMs = Number(process.env.E2E_OBSIDIAN_HIDDEN_FILE_CLI_TIMEOUT_MS ?? 90000); const hiddenFileInitialisationStateKey = "__livesyncE2EHiddenFileInitialisation"; @@ -85,6 +88,8 @@ type RunnerContext = { couchDb: CouchDbConfig; dbName: string; activeSessions: Set; + temporaryVaults: Set; + diagnosticPaths: string[]; }; async function writeVaultFile(vaultPath: string, path: string, content: string): Promise { @@ -313,72 +318,82 @@ async function resolveHiddenConflicts(cliBinary: string, env: NodeJS.ProcessEnv) ); } -async function autoMergeHiddenJsonConflict(cliBinary: string, env: NodeJS.ProcessEnv, path: string): Promise { - await evalObsidianJson( +async function startHiddenConflictResolution(cliBinary: string, env: NodeJS.ProcessEnv): Promise { + await evalObsidianJson( cliBinary, [ - "(async()=>{", - `const path=${JSON.stringify(path)};`, - "const prefixedPath=`i:${path}`;", - "const core=app.plugins.plugins['obsidian-livesync'].core;", - "const addOn=core.getAddOn('HiddenFileSync');", - "let doc=false;", - "for await (const entry of core.localDatabase.findEntries('i:','i;',{conflicts:true})){", - " if(entry.path===prefixedPath){ doc=entry; break; }", - "}", - "if(!doc) throw new Error(`Could not find hidden conflict candidate: ${path}`);", - "if(!doc._conflicts?.length) throw new Error(`Hidden file has no conflicts: ${path}`);", - "const conflicts=doc._conflicts.sort((a,b)=>Number(a.split('-')[0])-Number(b.split('-')[0]));", - "const conflictedRev=conflicts[0];", - "const conflictedRevNo=Number(conflictedRev.split('-')[0]);", - "const revFrom=await core.localDatabase.getRaw(doc._id,{revs_info:true});", - "const commonBase=(revFrom._revs_info||[])", - " .filter((rev)=>rev.status==='available'&&Number(rev.rev.split('-')[0])rev.rev)[0]||'';", - "const result=await core.localDatabase.managers.conflictManager.mergeObject(", - " doc.path, commonBase, doc._rev, conflictedRev", + "(()=>{", + `const key=${JSON.stringify(hiddenConflictStateKey)};`, + "const state={done:false,error:null};", + "globalThis[key]=state;", + "const addOn=app.plugins.plugins['obsidian-livesync'].core.getAddOn('HiddenFileSync');", + "void addOn.resolveConflictOnInternalFiles().then(", + "()=>{state.done=true;},", + "error=>{state.error=String(error);state.done=true;}", ");", - "if(!result){", - " throw new Error(`Hidden JSON conflict was not auto-mergeable: ${path}; base=${commonBase}; current=${doc._rev}; conflict=${conflictedRev}`);", - "}", - "await addOn.ensureDir(path);", - "const stat=await addOn.writeFile(path,result);", - "if(!stat) throw new Error(`Could not write merged hidden file: ${path}`);", - "await addOn.storeInternalFileToDatabase({path,mtime:stat.mtime,ctime:stat.ctime,size:stat.size},true);", - "await core.localDatabase.removeRevision(doc._id,conflictedRev);", - "await addOn.extractInternalFileFromDatabase(path);", - "await addOn.scanAllDatabaseChanges(true);", - "return JSON.stringify({ok:true,merged:JSON.parse(result)});", + "return JSON.stringify({started:true});", "})()", ].join(""), env ); } -async function openHiddenJsonResolveModal(cliBinary: string, env: NodeJS.ProcessEnv, path: string): Promise { - await evalObsidianJson( +async function waitForHiddenConflictResolution(cliBinary: string, env: NodeJS.ProcessEnv): Promise { + await evalObsidianJson( + cliBinary, + [ + "(async()=>{", + `const key=${JSON.stringify(hiddenConflictStateKey)};`, + "const state=globalThis[key];", + "if(!state)throw new Error('Hidden conflict resolution was not started');", + "const deadline=Date.now()+60000;", + "while(!state.done&&Date.now()setTimeout(resolve,50));", + "if(!state.done)throw new Error('Hidden conflict pipeline did not complete');", + "if(state.error)throw new Error(state.error);", + "delete globalThis[key];", + "return JSON.stringify({done:true});", + "})()", + ].join(""), + env, + hiddenFileCliTimeoutMs + ); +} + +async function assertResolvedHiddenContent( + cliBinary: string, + env: NodeJS.ProcessEnv, + path: string, + expectedContent: string +): Promise { + const stored = await evalObsidianJson<{ + rev: string; + currentRev: string; + conflicts: string[]; + datatype: string; + data: string | string[]; + }>( cliBinary, [ "(async()=>{", `const path=${JSON.stringify(path)};`, - "const prefixedPath=`i:${path}`;", - "const core=app.plugins.plugins['obsidian-livesync'].core;", - "const addOn=core.getAddOn('HiddenFileSync');", - "let doc=false;", - "for await (const entry of core.localDatabase.findEntries('i:','i;',{conflicts:true})){", - " if(entry.path===prefixedPath){ doc=entry; break; }", - "}", - "if(!doc?._conflicts?.length) throw new Error(`Could not find hidden JSON conflict: ${path}`);", - "const conflicts=doc._conflicts.sort((a,b)=>Number(a.split('-')[0])-Number(b.split('-')[0]));", - "const docA=await core.localDatabase.getDBEntry(prefixedPath,{rev:doc._rev});", - "const docB=await core.localDatabase.getDBEntry(prefixedPath,{rev:conflicts[0]});", - "if(docA===false||docB===false) throw new Error(`Could not load conflicted hidden JSON entries: ${path}`);", - "void addOn.showJSONMergeDialogAndMerge(docA,docB);", - "return JSON.stringify({ok:true});", + "const db=app.plugins.plugins['obsidian-livesync'].core.localDatabase;", + "const entry=await db.getDBEntry(`i:${path}`);", + "if(!entry)throw new Error(`Resolved hidden file is missing: ${path}`);", + "const current=await db.getRaw(entry._id,{conflicts:true});", + "return JSON.stringify({rev:entry._rev,currentRev:current._rev,conflicts:current._conflicts||[],datatype:entry.datatype,data:entry.data});", "})()", ].join(""), env ); + assertEqual(stored.rev, stored.currentRev, `Hidden result changed while reading ${path}.`); + assertEqual(stored.conflicts.length, 0, `Hidden conflict remains for ${path}.`); + const content = + stored.datatype === "plain" + ? typeof stored.data === "string" + ? stored.data + : stored.data.join("") + : new TextDecoder().decode(decodeBinary(stored.data)); + assertEqual(content, expectedContent, `Stored hidden content differs from the Vault file: ${path}.`); } async function storeHiddenFileAsConflict( @@ -437,6 +452,15 @@ async function createHiddenJsonConflict( await writeVaultFile(vault.path, path, right); await storeHiddenFileAsConflict(context.cliBinary, session.cliEnv, path, baseEntry.rev); + const conflicts = await evalObsidianJson( + context.cliBinary, + `(async()=>{ + const entry=await app.plugins.plugins['obsidian-livesync'].core.localDatabase.getDBEntryMeta(${JSON.stringify(`i:${path}`)},{conflicts:true}); + return JSON.stringify(entry?entry._conflicts?.length||0:0); + })()`, + session.cliEnv + ); + assertEqual(conflicts, 1, "The hidden conflict fixture did not retain two live revisions."); } async function startConfiguredSession( @@ -601,11 +625,12 @@ async function runJsonConflictRoundTrip( let session = await startConfiguredSession(context, vaultB); await createHiddenJsonConflict(context, session, vaultB, mergeJsonPath, base, left, right); - await autoMergeHiddenJsonConflict(context.cliBinary, session.cliEnv, mergeJsonPath); + await resolveHiddenConflicts(context.cliBinary, session.cliEnv); await pushLocalChanges(context.cliBinary, session.cliEnv); const mergedOnB = await waitForPathContent(vaultB.path, mergeJsonPath, (content) => hasJsonValues(content, { fromA: true, fromB: true }) ); + await assertResolvedHiddenContent(context.cliBinary, session.cliEnv, mergeJsonPath, mergedOnB); await stopSession(context, session); session = await startConfiguredSession(context, vaultA); @@ -613,6 +638,7 @@ async function runJsonConflictRoundTrip( const mergedOnA = await waitForPathContent(vaultA.path, mergeJsonPath, (content) => hasJsonValues(content, { fromA: true, fromB: true }) ); + await assertResolvedHiddenContent(context.cliBinary, session.cliEnv, mergeJsonPath, mergedOnA); await stopSession(context, session); assertEqual(mergedOnA, mergedOnB, "Merged hidden JSON content was not consistent across both vaults."); @@ -626,13 +652,21 @@ async function runJsonManualConflictResolution(context: RunnerContext, vault: Te const session = await startConfiguredSession(context, vault); await createHiddenJsonConflict(context, session, vault, manualMergeJsonPath, base, left, right); - await openHiddenJsonResolveModal(context.cliBinary, session.cliEnv, manualMergeJsonPath); + await startHiddenConflictResolution(context.cliBinary, session.cliEnv); const screenshotPath = await captureJsonResolveDialogue(obsidianRemoteDebuggingPort()); + const completedBeforeSelection = await evalObsidianJson( + context.cliBinary, + `JSON.stringify(globalThis[${JSON.stringify(hiddenConflictStateKey)}].done)`, + session.cliEnv + ); + assertEqual(completedBeforeSelection, false, "The hidden conflict pipeline completed before selection."); await clickJsonResolveOption(obsidianRemoteDebuggingPort(), "AB"); + await waitForHiddenConflictResolution(context.cliBinary, session.cliEnv); const merged = await waitForPathContent(vault.path, manualMergeJsonPath, (content) => hasJsonValues(content, { shared: "right", fromA: true, fromB: true }) ); + await assertResolvedHiddenContent(context.cliBinary, session.cliEnv, manualMergeJsonPath, merged); await stopSession(context, session); const parsed = JSON.parse(merged); @@ -1033,7 +1067,212 @@ async function runConfigurationNoticeGrouping(context: RunnerContext, vault: Tem } } +type HiddenEnablementMode = "Merge" | "Fetch" | "Overwrite"; + +async function enableHiddenSyncThroughSettings( + context: RunnerContext, + session: ObsidianLiveSyncSession, + vault: TemporaryVault, + mode: HiddenEnablementMode +): Promise { + const stateKey = "__livesyncE2EHiddenEnablement"; + await evalObsidianJson( + context.cliBinary, + `(()=>{ + const core=app.plugins.plugins['obsidian-livesync'].core; + if(core.settings.syncInternalFiles)throw new Error('Hidden File Sync must start disabled'); + const setting=core.services.setting; + const original=setting.enableOptionalFeature; + const state={done:false,error:null,mode:null,restore:()=>{setting.enableOptionalFeature=original;}}; + globalThis[${JSON.stringify(stateKey)}]=state; + setting.enableOptionalFeature=async function(mode){ + state.mode=mode; + try{return await original.call(this,mode);} + catch(error){state.error=String(error);throw error;} + finally{state.done=true;state.restore();} + }; + return JSON.stringify(true); + })()`, + session.cliEnv + ); + try { + await withObsidianPage(session.remoteDebuggingPort, async (page) => { + const navigator = await openLiveSyncSettings(page); + const settingsPage = await navigator.openPage("Sync Settings"); + const row = settingsPage.locator(".setting-item").filter({ + has: navigator.page.getByRole("button", { name: "Merge", exact: true }), + }); + await row.getByRole("button", { name: mode, exact: true }).click(); + }); + const result = await evalObsidianJson<{ mode: string; enabled: boolean }>( + context.cliBinary, + ` + (async()=>{ + const state=globalThis[${JSON.stringify(stateKey)}]; + const deadline=Date.now()+60000; + while(!state.done&&Date.now()setTimeout(resolve,50)); + if(!state.done)throw new Error('Hidden File Sync enablement did not complete'); + if(state.error)throw new Error(state.error); + const core=app.plugins.plugins['obsidian-livesync'].core; + return JSON.stringify({mode:state.mode,enabled:core.settings.syncInternalFiles}); + })() + `, + session.cliEnv, + hiddenFileCliTimeoutMs + ); + assertEqual(result.mode, mode.toUpperCase(), "The settings action invoked a different enablement mode."); + assertEqual(result.enabled, true, "Hidden File Sync was not enabled by its settings action."); + const saved = JSON.parse(await readVaultFile(vault.path, ".obsidian/plugins/obsidian-livesync/data.json")); + assertEqual(saved.syncInternalFiles, true, "Hidden File Sync enablement was not persisted."); + } finally { + await evalObsidianJson( + context.cliBinary, + `(()=>{ + globalThis[${JSON.stringify(stateKey)}]?.restore(); + delete globalThis[${JSON.stringify(stateKey)}]; + return JSON.stringify(true); + })()`, + session.cliEnv + ); + } +} + +async function startPersistedSession(context: RunnerContext, vault: TemporaryVault): Promise { + const session = await startObsidianLiveSyncSession({ binary: context.binary, cliBinary: context.cliBinary, vault }); + context.activeSessions.add(session); + await waitForLiveSyncCoreReady(context.cliBinary, session.cliEnv); + const enabled = await evalObsidianJson( + context.cliBinary, + "JSON.stringify(app.plugins.plugins['obsidian-livesync'].core.settings.syncInternalFiles)", + session.cliEnv + ); + assertEqual(enabled, true, "Hidden File Sync enablement did not survive restart."); + return session; +} + +async function verifyHiddenFiles( + context: RunnerContext, + session: ObsidianLiveSyncSession, + vault: TemporaryVault, + expected: Record +): Promise { + for (const [path, content] of Object.entries(expected)) { + await waitForPathContent(vault.path, path, (actual) => actual === content); + await assertResolvedHiddenContent(context.cliBinary, session.cliEnv, path, content); + } +} + +async function runHiddenEnablement(context: RunnerContext, mode: HiddenEnablementMode): Promise { + const source = await createTemporaryVault(); + context.temporaryVaults.add(source); + const target = await createTemporaryVault(); + context.temporaryVaults.add(target); + const root = `.obsidian/livesync-enable-${mode.toLowerCase()}`; + const localNewer = `${root}/local-newer.json`; + const remoteNewer = `${root}/remote-newer.json`; + const remoteOnly = `${root}/remote-only.json`; + const localOnly = `${root}/local-only.json`; + context.diagnosticPaths = [localNewer, remoteNewer, remoteOnly, localOnly]; + const remoteContent = JSON.stringify({ source: "remote", mode }) + "\n"; + const localContent = JSON.stringify({ source: "local", mode }) + "\n"; + const timestamp = Math.floor(Date.now() / 1000) - 120; + for (const path of [localNewer, remoteNewer, remoteOnly]) { + await writeVaultFile(source.path, path, remoteContent); + await utimes(join(source.path, path), timestamp + 10, timestamp + 10); + } + const settings = { + syncInternalFiles: false, + useAdvancedMode: true, + syncInternalFilesTargetPatterns: `^\\.obsidian(?:$|/livesync-enable-${mode.toLowerCase()}(?:/|$))`, + }; + let session = await startConfiguredSession(context, source, settings); + await enableHiddenSyncThroughSettings(context, session, source, "Overwrite"); + await verifyHiddenFiles(context, session, source, { + [localNewer]: remoteContent, + [remoteNewer]: remoteContent, + [remoteOnly]: remoteContent, + }); + await pushLocalChanges(context.cliBinary, session.cliEnv); + const uploaded: LocalDatabaseEntry[] = []; + for (const path of [localNewer, remoteNewer, remoteOnly]) { + uploaded.push(await waitForLocalDatabaseEntry(context.cliBinary, session.cliEnv, path, { hidden: true })); + } + await waitForCouchDbDocs(context.couchDb, context.dbName, (docs) => + uploaded.every((entry) => docs.some((doc) => doc._id === entry.id && doc._rev === entry.rev)) + ); + await stopSession(context, session); + + for (const [path, time] of [ + [localNewer, timestamp + 30], + [remoteNewer, timestamp], + [localOnly, timestamp + 30], + ] as const) { + await writeVaultFile(target.path, path, localContent); + await utimes(join(target.path, path), time, time); + } + session = await startConfiguredSession(context, target, settings); + await pushLocalChanges(context.cliBinary, session.cliEnv); + for (const path of [localNewer, remoteNewer]) { + assertEqual(await readVaultFile(target.path, path), localContent, "Disabled sync replaced a local fixture."); + } + const receivedRevisions = await evalObsidianJson( + context.cliBinary, + `(async()=>{ + const db=app.plugins.plugins['obsidian-livesync'].core.localDatabase; + const revisions=[]; + for(const id of ${JSON.stringify(uploaded.map((entry) => entry.id))}) { + const doc=await db.getRaw(id); + revisions.push(doc._rev); + } + return JSON.stringify(revisions); + })()`, + session.cliEnv + ); + assertEqual( + JSON.stringify(receivedRevisions), + JSON.stringify(uploaded.map((entry) => entry.rev)), + "Disabled Hidden File Sync did not retain the uploaded revisions in its database." + ); + assertEqual(await pathExists(target.path, remoteOnly), false, "Disabled sync reflected a remote-only file."); + + await enableHiddenSyncThroughSettings(context, session, target, mode); + const expected = { + [localNewer]: mode === "Fetch" ? remoteContent : localContent, + [remoteNewer]: mode === "Overwrite" ? localContent : remoteContent, + [remoteOnly]: remoteContent, + [localOnly]: localContent, + }; + await verifyHiddenFiles(context, session, target, expected); + await pushLocalChanges(context.cliBinary, session.cliEnv); + await stopSession(context, session); + + session = await startPersistedSession(context, target); + await verifyHiddenFiles(context, session, target, expected); + await stopSession(context, session); + + session = await startPersistedSession(context, source); + await pullAndApplyHiddenFiles(context, session); + await verifyHiddenFiles(context, session, source, expected); + await stopSession(context, session); + console.log( + `Hidden File Sync ${mode} preserved the selected contents in files and the database, after restart, and on the other device.` + ); +} + async function main(): Promise { + const selectedCase = process.argv.find((argument) => argument.startsWith("--case="))?.slice(7); + if (selectedCase && selectedCase !== "conflicts" && selectedCase !== "enablement") { + throw new Error("Use --case=conflicts or --case=enablement."); + } + const conflictsOnly = selectedCase === "conflicts"; + const enablementOnly = selectedCase === "enablement"; + const selectedMode = process.argv.find((argument) => argument.startsWith("--mode="))?.slice(7); + const enablementModes = (["Merge", "Fetch", "Overwrite"] as const).filter( + (mode) => !selectedMode || selectedMode === mode + ); + if (selectedMode && (!enablementOnly || enablementModes.length !== 1)) { + throw new Error("Use --case=enablement with --mode=Merge, --mode=Fetch, or --mode=Overwrite."); + } const binary = requireObsidianBinary(); const cli = discoverObsidianCli(); if (!cli.binary) { @@ -1044,7 +1283,15 @@ async function main(): Promise { const dbName = makeUniqueDatabaseName(couchDb.dbPrefix, "hidden-roundtrip"); const vaultA = await createTemporaryVault(); const vaultB = await createTemporaryVault(); - const context: RunnerContext = { binary, cliBinary: cli.binary, couchDb, dbName, activeSessions: new Set() }; + const context: RunnerContext = { + binary, + cliBinary: cli.binary, + couchDb, + dbName, + activeSessions: new Set(), + temporaryVaults: new Set([vaultA, vaultB]), + diagnosticPaths: [mergeJsonPath, manualMergeJsonPath, snippetPath], + }; try { await assertCouchDbReachable(couchDb); @@ -1055,17 +1302,56 @@ async function main(): Promise { console.log(`Temporary vault B: ${vaultB.path}`); console.log(`Temporary CouchDB database: ${dbName}`); - await runCreateRoundTrip(context, vaultA, vaultB); - await runDeleteRoundTrip(context, vaultA, vaultB); - await runJsonConflictRoundTrip(context, vaultA, vaultB); - await runJsonManualConflictResolution(context, vaultB); - await runTargetMismatch(context, vaultA, vaultB); - await runInitialisationNoticeGrouping(context, vaultB); - await runConfigurationNoticeGrouping(context, vaultB); + if (!conflictsOnly && !enablementOnly) { + await runCreateRoundTrip(context, vaultA, vaultB); + await runDeleteRoundTrip(context, vaultA, vaultB); + } + if (!enablementOnly) { + await runJsonConflictRoundTrip(context, vaultA, vaultB); + await runJsonManualConflictResolution(context, vaultB); + } + if (!conflictsOnly && !enablementOnly) { + await runTargetMismatch(context, vaultA, vaultB); + await runInitialisationNoticeGrouping(context, vaultB); + await runConfigurationNoticeGrouping(context, vaultB); + } + if (!conflictsOnly) { + for (const mode of enablementModes) await runHiddenEnablement(context, mode); + } + } catch (error) { + for (const session of context.activeSessions) { + await captureObsidianPage( + session.remoteDebuggingPort, + "hidden-file-workflow-failure.png", + async () => {} + ).catch((captureError: unknown) => console.error(String(captureError))); + await evalObsidianJson( + cli.binary, + [ + "(async()=>{", + "const core=app.plugins.plugins['obsidian-livesync'].core;", + "const addOn=core.getAddOn('HiddenFileSync');", + `const paths=${JSON.stringify(context.diagnosticPaths)};`, + "const files=await addOn.scanInternalFileNames();", + "const observations=[];", + "for(const path of paths){", + "const stat=await core.storageAccess.statHidden(path);", + "const entry=await core.localDatabase.getDBEntryMeta(`i:${path}`,{conflicts:true});", + "observations.push({path,selected:files.includes(path),target:await addOn.isTargetFile(path),stat,processed:addOn.getLastProcessedFileKey(path),entry:entry?{rev:entry._rev,conflicts:entry._conflicts||[]}:false});", + "}", + `const operation=globalThis[${JSON.stringify(hiddenConflictStateKey)}];`, + "return JSON.stringify({enabled:core.settings.syncInternalFiles,ready:core.localDatabase.isReady,remaining:addOn.conflictResolutionProcessor.totalRemaining,operation,observations});", + "})()", + ].join(""), + session.cliEnv + ) + .then((snapshot) => console.error("Hidden-file failure state:", JSON.stringify(snapshot))) + .catch((snapshotError: unknown) => console.error(String(snapshotError))); + } + throw error; } finally { for (const session of context.activeSessions) await stopSession(context, session); - await vaultA.dispose(); - await vaultB.dispose(); + for (const vault of context.temporaryVaults) await vault.dispose(); if (process.env.E2E_OBSIDIAN_KEEP_COUCHDB !== "true") { await deleteCouchDbDatabase(couchDb, dbName).catch((error: unknown) => { console.warn(error instanceof Error ? error.message : error); diff --git a/updates.md b/updates.md index 2b43202c..8f835879 100644 --- a/updates.md +++ b/updates.md @@ -14,6 +14,8 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi ### Fixes +- Hidden File Sync now stores newer local files during `Merge` initialisation by comparing local and database modification times in the correct direction. + - Reloading the Customisation Sync catalogue no longer allows an earlier legacy-format scan to put outdated items back into the list. - Reloading or disabling Customisation Sync discards unstarted scans and ignores stale read results. Migrations to per-file storage which have already started are allowed to finish. From a042115178139df9deb1378a5b99e306eab0a711 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 15:50:19 +0000 Subject: [PATCH 15/24] Reuse the disposable FIFO for customisation scans --- src/features/ConfigSync/ConfigScanQueue.ts | 66 +++++++++++------- .../ConfigSync/ConfigScanQueue.unit.spec.ts | 69 +++++++++++++++++++ 2 files changed, 111 insertions(+), 24 deletions(-) diff --git a/src/features/ConfigSync/ConfigScanQueue.ts b/src/features/ConfigSync/ConfigScanQueue.ts index dd960dd0..662b4c8b 100644 --- a/src/features/ConfigSync/ConfigScanQueue.ts +++ b/src/features/ConfigSync/ConfigScanQueue.ts @@ -1,6 +1,7 @@ import { compatGlobal, type CompatTimeoutHandle } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { createNotifier } from "octagonal-wheels/concurrency/notifier"; import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { createAsyncQueue, type AsyncQueue } from "octagonal-wheels/iterable/asyncQueue"; import { withScope, type Awaitable } from "octagonal-wheels/resource/scope"; interface ConfigScanQueueOptions { @@ -9,12 +10,20 @@ interface ConfigScanQueueOptions { onProgress?: (remaining: number) => void; } -type PendingScan = { value: T }; +interface PendingQueue { + fifo: AsyncQueue; + iterator: AsyncIterator; +} + +interface PendingScan { + value: T; + queue: PendingQueue; +} /** Owns FIFO admission, the initial scan delay, and completion for one catalogue. */ export class ConfigScanQueue { - private pending: (PendingScan | undefined)[] = []; - private head = 0; + private pending: PendingQueue; + private pendingCount = 0; private active = 0; private ready = false; private stopped = false; @@ -24,10 +33,13 @@ export class ConfigScanQueue { private running?: Promise; private readonly changed = createNotifier(); - constructor(private readonly options: ConfigScanQueueOptions) {} + constructor(private readonly options: ConfigScanQueueOptions) { + this.pending = this.createPendingQueue(); + } - private get pendingCount() { - return this.pending.length - this.head; + private createPendingQueue(): PendingQueue { + const fifo = createAsyncQueue(); + return { fifo, iterator: fifo[Symbol.asyncIterator]() }; } get remaining(): number { @@ -36,17 +48,20 @@ export class ConfigScanQueue { enqueue(value: T): void { if (!this.canDispatch()) throw new Error("The customisation scan queue is closed."); - this.pending.push({ value }); + this.pending.fifo.enqueue(value); + this.pendingCount++; this.reportProgress(); this.schedule(); } /** Discard unstarted scans; active reads and migrations retain their slots. */ clearPending(): void { - this.pending = []; - this.head = 0; + const discarded = this.pending; + this.pending = this.createPendingQueue(); + this.pendingCount = 0; this.ready = false; this.clearTimer(); + discarded.fifo.dispose(); this.reportProgress(); } @@ -96,26 +111,29 @@ export class ConfigScanQueue { } private claim(entry: PendingScan): boolean { - if (!this.canDispatch() || this.pending[this.head] !== entry) return false; - this.pending[this.head++] = undefined; - if (this.pendingCount === 0) { - this.pending = []; - this.head = 0; - this.ready = false; - } else if (this.head >= 1024 && this.head * 2 >= this.pending.length) { - this.pending = this.pending.slice(this.head); - this.head = 0; - } + if (!this.canDispatch() || this.pending !== entry.queue) return false; + this.pendingCount--; + if (this.pendingCount === 0) this.ready = false; return true; } private async *availableWork() { while (this.canDispatch()) { - const entry = this.pending[this.head]; - if (this.ready && entry) { - // The callback claims the item so clearing a pulled item also cancels it. - yield entry; - } else if (this.active > 0) { + const pending = this.pending; + if (!this.ready) { + if (this.active === 0 && this.pendingCount === 0) return; + await this.changed.wait(); + continue; + } + if (pending.fifo.size > 0) { + const entry = await pending.iterator.next(); + if (entry.done) { + if (pending !== this.pending) continue; + return; + } + // The callback checks queue identity so clearing a pulled item cancels it. + yield { value: entry.value, queue: pending }; + } else if (this.active > 0 || this.pendingCount > 0) { // Keep free slots available to later arrivals while a slow scan finishes. await this.changed.wait(); } else { diff --git a/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts b/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts index c1182d2b..4df2f64a 100644 --- a/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts +++ b/src/features/ConfigSync/ConfigScanQueue.unit.spec.ts @@ -165,6 +165,75 @@ describe("ConfigScanQueue", () => { expect(scans.remaining).toBe(0); }); + it("invalidates prefetched work after clearing and admits replacements alongside active scans", async () => { + const finishFirst = gate(); + const finishReplacement = gate(); + let scans!: ConfigScanQueue; + const seen: string[] = []; + scans = queue({ + process: async (item) => { + seen.push(item); + if (item === "first") { + void Promise.resolve().then(() => Promise.resolve().then(() => scans.clearPending())); + await finishFirst.promise; + } else if (item === "replacement") { + await finishReplacement.promise; + } + }, + }); + scans.enqueue("first"); + scans.enqueue("stale"); + await vi.advanceTimersByTimeAsync(100); + expect(seen).toEqual(["first"]); + expect(scans.remaining).toBe(1); + + scans.enqueue("replacement"); + await vi.advanceTimersByTimeAsync(100); + expect(seen).toEqual(["first", "replacement"]); + expect(scans.remaining).toBe(2); + + finishFirst.resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(scans.remaining).toBe(1); + finishReplacement.resolve(); + await scans.waitForIdle(); + expect(scans.remaining).toBe(0); + }); + + it("keeps the ten-scan limit across clear and replacement work", async () => { + const finish = Array.from({ length: 12 }, () => gate()); + const seen: number[] = []; + let active = 0; + let maximum = 0; + const scans = queue({ + process: async (item) => { + seen.push(item); + maximum = Math.max(maximum, ++active); + await finish[item].promise; + active--; + }, + }); + for (let item = 0; item < 10; item++) scans.enqueue(item); + await vi.advanceTimersByTimeAsync(100); + expect(seen).toEqual(Array.from({ length: 10 }, (_, index) => index)); + + scans.clearPending(); + scans.enqueue(10); + scans.enqueue(11); + await vi.advanceTimersByTimeAsync(100); + expect(seen).toEqual(Array.from({ length: 10 }, (_, index) => index)); + expect(maximum).toBe(10); + + finish[0].resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(seen).toEqual(Array.from({ length: 11 }, (_, index) => index)); + expect(maximum).toBe(10); + finish.forEach((item) => item.resolve()); + await scans.waitForIdle(); + expect(seen).toEqual(Array.from({ length: 12 }, (_, index) => index)); + expect(maximum).toBe(10); + }); + it("stops while waiting for input, joins active work, and rejects later admission", async () => { const finish = gate(); const seen: number[] = []; From 59abe9eebb73ffd32f72409634b65455bc011611 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sat, 31 Oct 2026 17:01:19 +0000 Subject: [PATCH 16/24] Use the canonical scoped iteration entry --- src/features/ConfigSync/ConfigScanQueue.ts | 2 +- src/features/HiddenFileSync/HiddenFileConflictQueue.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/features/ConfigSync/ConfigScanQueue.ts b/src/features/ConfigSync/ConfigScanQueue.ts index 662b4c8b..7982b1ca 100644 --- a/src/features/ConfigSync/ConfigScanQueue.ts +++ b/src/features/ConfigSync/ConfigScanQueue.ts @@ -1,6 +1,6 @@ import { compatGlobal, type CompatTimeoutHandle } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { createNotifier } from "octagonal-wheels/concurrency/notifier"; -import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { forEachInScope } from "octagonal-wheels/concurrency/scoped.iteration"; import { createAsyncQueue, type AsyncQueue } from "octagonal-wheels/iterable/asyncQueue"; import { withScope, type Awaitable } from "octagonal-wheels/resource/scope"; diff --git a/src/features/HiddenFileSync/HiddenFileConflictQueue.ts b/src/features/HiddenFileSync/HiddenFileConflictQueue.ts index 7a123764..af933c37 100644 --- a/src/features/HiddenFileSync/HiddenFileConflictQueue.ts +++ b/src/features/HiddenFileSync/HiddenFileConflictQueue.ts @@ -1,7 +1,7 @@ import { compatGlobal, type CompatTimeoutHandle } from "@vrtmrz/livesync-commonlib/compat/common/coreEnvFunctions"; import { withCancellation } from "octagonal-wheels/concurrency/cancellation"; import { createNotifier } from "octagonal-wheels/concurrency/notifier"; -import { forEachInScope } from "octagonal-wheels/concurrency/scopedIteration"; +import { forEachInScope } from "octagonal-wheels/concurrency/scoped.iteration"; import { createAsyncQueue } from "octagonal-wheels/iterable/asyncQueue"; import { withOwnedResource } from "octagonal-wheels/resource"; From 68dcc7eb94f82e4528e1119ca0580ec26552966e Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 05:19:47 +0000 Subject: [PATCH 17/24] Use published shared runtime dependencies --- package-lock.json | 22 +++++++++++----------- package.json | 4 ++-- src/apps/cli/package.json | 2 +- src/apps/webapp/package.json | 2 +- src/apps/webpeer/package.json | 2 +- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/package-lock.json b/package-lock.json index be6fb586..6c10fbe9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -24,7 +24,7 @@ "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", "@vrtmrz/livesync-commonlib": "0.2.2", - "@vrtmrz/obsidian-plugin-kit": "0.1.6", + "@vrtmrz/obsidian-plugin-kit": "0.1.7", "@vrtmrz/ui-interactions": "0.1.2", "@vrtmrz/value-store": "0.1.0", "diff-match-patch": "^1.0.5", @@ -32,7 +32,7 @@ "markdown-it": "^14.3.3", "minimatch": "^10.2.5", "obsidian": "^1.13.1", - "octagonal-wheels": "^0.1.55", + "octagonal-wheels": "0.1.56", "qrcode-generator": "^1.4.4", "xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2" }, @@ -4188,9 +4188,9 @@ } }, "node_modules/@vrtmrz/obsidian-plugin-kit": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/@vrtmrz/obsidian-plugin-kit/-/obsidian-plugin-kit-0.1.6.tgz", - "integrity": "sha512-88HhpN3G53qIQxvsTpe7VE6/unW3YtcZjmqko3Q58yRl/Y+iJDruT1HuEQYEgtkWAB6F2T93z2fhqhvRBXDDWQ==", + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/@vrtmrz/obsidian-plugin-kit/-/obsidian-plugin-kit-0.1.7.tgz", + "integrity": "sha512-Ax6u6CEHVrY+DJJtaCcVkSGzf9fia1ypzGblQ1uG4AvMjgc2o4STs6l2P7D7ZB81pryE4MfkSpBLvENxyTbWLw==", "license": "MIT", "dependencies": { "@vrtmrz/secret-store": "0.1.0", @@ -8850,9 +8850,9 @@ "license": "MIT" }, "node_modules/octagonal-wheels": { - "version": "0.1.55", - "resolved": "https://registry.npmjs.org/octagonal-wheels/-/octagonal-wheels-0.1.55.tgz", - "integrity": "sha512-mHsQv/h4Tw4ZGJCmTxXFlgeRvPuL9s47C0arD8Njqld+DKr3ppaWjVteEBP+9bWFSOpv/a1u2yY3LYNFGmuexg==", + "version": "0.1.56", + "resolved": "https://registry.npmjs.org/octagonal-wheels/-/octagonal-wheels-0.1.56.tgz", + "integrity": "sha512-c4xQqdeEGE//ZExMJDEsqPsUHsRVHMNuxudux6scYI46eqA/54ao3WJmEZj3fbSsUhR7uCRmJ5ddd1cfRybIfg==", "license": "MIT", "dependencies": { "idb": "^8.0.3" @@ -11768,7 +11768,7 @@ "@aws-crypto/sha256-js": "5.2.0", "chokidar": "^4.0.0", "minimatch": "^10.2.5", - "octagonal-wheels": "^0.1.55", + "octagonal-wheels": "0.1.56", "pouchdb-adapter-http": "^9.0.0", "pouchdb-adapter-leveldb": "^9.0.0", "pouchdb-core": "^9.0.0", @@ -11791,7 +11791,7 @@ "name": "livesync-webapp", "version": "1.0.43-webapp", "dependencies": { - "octagonal-wheels": "^0.1.55" + "octagonal-wheels": "0.1.56" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.1.2", @@ -11803,7 +11803,7 @@ "src/apps/webpeer": { "version": "1.0.43-webpeer", "dependencies": { - "octagonal-wheels": "^0.1.55" + "octagonal-wheels": "0.1.56" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.1.2", diff --git a/package.json b/package.json index 6e38dbf5..713792ae 100644 --- a/package.json +++ b/package.json @@ -210,7 +210,7 @@ "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", "@vrtmrz/livesync-commonlib": "0.2.2", - "@vrtmrz/obsidian-plugin-kit": "0.1.6", + "@vrtmrz/obsidian-plugin-kit": "0.1.7", "@vrtmrz/ui-interactions": "0.1.2", "@vrtmrz/value-store": "0.1.0", "diff-match-patch": "^1.0.5", @@ -218,7 +218,7 @@ "markdown-it": "^14.3.3", "minimatch": "^10.2.5", "obsidian": "^1.13.1", - "octagonal-wheels": "^0.1.55", + "octagonal-wheels": "0.1.56", "qrcode-generator": "^1.4.4", "xxhash-wasm-102": "npm:xxhash-wasm@^1.0.2" }, diff --git a/src/apps/cli/package.json b/src/apps/cli/package.json index 2430e32a..fbd9e644 100644 --- a/src/apps/cli/package.json +++ b/src/apps/cli/package.json @@ -40,7 +40,7 @@ "@aws-crypto/sha256-js": "5.2.0", "chokidar": "^4.0.0", "minimatch": "^10.2.5", - "octagonal-wheels": "^0.1.55", + "octagonal-wheels": "0.1.56", "pouchdb-adapter-http": "^9.0.0", "pouchdb-adapter-leveldb": "^9.0.0", "pouchdb-core": "^9.0.0", diff --git a/src/apps/webapp/package.json b/src/apps/webapp/package.json index 66ce9d59..1857b572 100644 --- a/src/apps/webapp/package.json +++ b/src/apps/webapp/package.json @@ -15,7 +15,7 @@ "test:browser": "deno test -A --no-check --frozen --config ../../../test/browser-apps/deno.json --lock ../../../test/browser-apps/deno.lock ../../../test/browser-apps/webapp/browser-smoke.test.ts" }, "dependencies": { - "octagonal-wheels": "^0.1.55" + "octagonal-wheels": "0.1.56" }, "devDependencies": { "@sveltejs/vite-plugin-svelte": "^7.1.2", diff --git a/src/apps/webpeer/package.json b/src/apps/webpeer/package.json index b460bb23..0163cd5e 100644 --- a/src/apps/webpeer/package.json +++ b/src/apps/webpeer/package.json @@ -15,7 +15,7 @@ "test:browser": "deno test -A --no-check --frozen --config ../../../test/browser-apps/deno.json --lock ../../../test/browser-apps/deno.lock ../../../test/browser-apps/webpeer/browser-smoke.test.ts" }, "dependencies": { - "octagonal-wheels": "^0.1.55" + "octagonal-wheels": "0.1.56" }, "devDependencies": { "eslint-plugin-svelte": "^3.19.0", From 6d92f19dd999f29f536464ecc61669c7ce7a7c07 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 05:29:34 +0000 Subject: [PATCH 18/24] Run binary round-trip coverage with the Node CLI runner --- test/e2e-cli/test-setup-put-cat.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/e2e-cli/test-setup-put-cat.ts b/test/e2e-cli/test-setup-put-cat.ts index 0be897cf..c1d8d142 100644 --- a/test/e2e-cli/test-setup-put-cat.ts +++ b/test/e2e-cli/test-setup-put-cat.ts @@ -73,19 +73,19 @@ test("CLI file operations: push / cat / ls / info / rm / resolve / cat-rev / pul console.log("[PASS] push/cat roundtrip matched"); }); - await t.step("push/pull binary roundtrip", async () => { + await t.test("push/pull binary roundtrip", async () => { const source = workDir.join("binary-source.bin"); const restored = workDir.join("binary-restored.bin"); const remotePath = "test/blob-roundtrip.bin"; const content = Uint8Array.from({ length: 1025 }, (_, index) => index % 256); - await Deno.writeFile(source, content); + await writeFile(source, content); await run("push", source, remotePath); await run("pull", remotePath, restored); - assertEquals(await Deno.readFile(restored), content, "Binary push/pull must preserve every byte"); - const info = JSON.parse(await run("info", remotePath)); - assertEquals(info.size, content.byteLength, "Binary Metadata must retain the original byte length"); + assert.deepStrictEqual(new Uint8Array(await readFile(restored)), content, "Binary push/pull must preserve every byte"); + const info = JSON.parse(await run("info", remotePath)) as Record; + assert.deepStrictEqual(info.size, content.byteLength, "Binary Metadata must retain the original byte length"); }); // ------------------------------------------------------------------ From 17d1e3f50af09fe364deae9caff53dab6cccb2d0 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 08:53:13 +0000 Subject: [PATCH 19/24] Use published Commonlib 0.2.3 --- devs.md | 2 +- package-lock.json | 10 +++++----- package.json | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/devs.md b/devs.md index 566e58a4..d936734c 100644 --- a/devs.md +++ b/devs.md @@ -166,7 +166,7 @@ Commonlib's `targetFilter.ts` and `prepareDatabaseForUse.ts` demonstrate the int Use interaction-based, London School unit tests for the composition boundary. Verify collaborator calls, ordering, failure short-circuiting, and handler registration, then test the focused state owner for its transitions and invariants. If a test needs a broad core fixture, a large class mock, deep mock chains, or unrelated Services, treat that friction as a design-review signal and consider a private context with narrower functions before adding more test machinery. -See [Service feature and legacy Module boundaries](docs/design_docs/service_feature_and_legacy_module_boundaries.md) for the selection criteria, current examples, reasons to avoid new `AbstractModule` subclasses, incremental migration guidance, and test shapes. Commonlib's [service feature composition guide](https://github.com/vrtmrz/livesync-commonlib/blob/main/docs/service-feature-composition.md) defines the shared host-neutral boundary. Fancy Kit's [shared runtime composition guide](https://github.com/vrtmrz/fancy-kit/blob/main/docs/runtime-composition.md) maps content application, cleanup, progress, and host adapters to their owning APIs, with their unreleased status and consumer responsibilities. +See [Service feature and legacy Module boundaries](docs/design_docs/service_feature_and_legacy_module_boundaries.md) for the selection criteria, current examples, reasons to avoid new `AbstractModule` subclasses, incremental migration guidance, and test shapes. Commonlib's [service feature composition guide](https://github.com/vrtmrz/livesync-commonlib/blob/main/docs/service-feature-composition.md) defines the shared host-neutral boundary. Fancy Kit's [shared runtime composition guide](https://github.com/vrtmrz/fancy-kit/blob/main/docs/runtime-composition.md) maps content application, cleanup, progress, and host adapters to their owning APIs, with their publication status and consumer responsibilities. Legacy Modules remain grouped by directory: diff --git a/package-lock.json b/package-lock.json index 6c10fbe9..7f6d7b88 100644 --- a/package-lock.json +++ b/package-lock.json @@ -23,7 +23,7 @@ "@smithy/types": "^4.14.3", "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", - "@vrtmrz/livesync-commonlib": "0.2.2", + "@vrtmrz/livesync-commonlib": "0.2.3", "@vrtmrz/obsidian-plugin-kit": "0.1.7", "@vrtmrz/ui-interactions": "0.1.2", "@vrtmrz/value-store": "0.1.0", @@ -4121,9 +4121,9 @@ } }, "node_modules/@vrtmrz/livesync-commonlib": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/@vrtmrz/livesync-commonlib/-/livesync-commonlib-0.2.2.tgz", - "integrity": "sha512-+nl4ntmRtUmSUuh9mOpicE0U/wpzhSPSQQXy9eg/2xdTBL58jkrQ6bQjbVKEhqUj0bUvg0ESjZm8YX/x+4zXiA==", + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/@vrtmrz/livesync-commonlib/-/livesync-commonlib-0.2.3.tgz", + "integrity": "sha512-n1BaoegBVGDqerZ9EcNbgd4KFtRPJ/lPp5ADsAsHTkPzSwev4SAFxxyFgFKLpTLpPv7McFao4oGBHGvRvoXWEg==", "license": "MIT", "dependencies": { "@aws-crypto/sha256-js": "5.2.0", @@ -4141,7 +4141,7 @@ "idb": "^8.0.3", "markdown-it": "^14.3.3", "minimatch": "^10.2.6", - "octagonal-wheels": "^0.1.55", + "octagonal-wheels": "0.1.56", "pouchdb-adapter-http": "^9.0.0", "pouchdb-adapter-idb": "^9.0.0", "pouchdb-adapter-indexeddb": "^9.0.0", diff --git a/package.json b/package.json index 713792ae..ed072a0f 100644 --- a/package.json +++ b/package.json @@ -209,7 +209,7 @@ "@smithy/types": "^4.14.3", "@smithy/util-retry": "^4.4.5", "@vrtmrz/browser-ui-kit": "0.1.0", - "@vrtmrz/livesync-commonlib": "0.2.2", + "@vrtmrz/livesync-commonlib": "0.2.3", "@vrtmrz/obsidian-plugin-kit": "0.1.7", "@vrtmrz/ui-interactions": "0.1.2", "@vrtmrz/value-store": "0.1.0", From 8844a88399d70c541601d16aac95423eee1f62f4 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 08:53:13 +0000 Subject: [PATCH 20/24] Cancel stale conflict resolutions when queueing checks --- .../conflictResolution/checker.ts | 5 + .../conflictResolution.unit.spec.ts | 96 ++++++++++++++++++- .../conflictResolution/index.ts | 1 + .../conflictResolution/operations.ts | 9 ++ 4 files changed, 108 insertions(+), 3 deletions(-) diff --git a/src/serviceFeatures/conflictResolution/checker.ts b/src/serviceFeatures/conflictResolution/checker.ts index d90263a3..21597d59 100644 --- a/src/serviceFeatures/conflictResolution/checker.ts +++ b/src/serviceFeatures/conflictResolution/checker.ts @@ -18,6 +18,7 @@ export interface ConflictCheckingDependencies { "getOptionalConflictCheckMethod" | "queueCheckFor" | "resolve" | "resolveByNewest" >; readonly conflictProcessQueueCount: ReactiveSource; + readonly cancelActiveResolution: (filename: FilePathWithPrefix) => void; readonly currentSettings: () => ConflictCheckingSettings; readonly vault: Pick; readonly log: LogFunction; @@ -69,6 +70,10 @@ export function createConflictCheckingHandlers(dependencies: ConflictCheckingDep // The conflict should be resolved by the newer entry. await dependencies.conflict.resolveByNewest(file); } else { + // The next batch waits for active checks to settle. Cancel the + // older same-file resolution now so its dialogue cannot hold the + // replacement behind that wait. + dependencies.cancelActiveResolution(file); conflictQueue.enqueue(file); } }; diff --git a/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts b/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts index 57cde733..30a0d279 100644 --- a/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts +++ b/src/serviceFeatures/conflictResolution/conflictResolution.unit.spec.ts @@ -695,6 +695,86 @@ describe("conflict resolution serviceFeature", () => { expect(harness.tryAutoMerge).toHaveBeenCalledWith(path, true); }); + it("replaces an active same-file dialogue when a later check enters the queue", async () => { + const path = "queued-dialogue-replacement.md" as FilePathWithPrefix; + const harness = createHarness({ settings: { syncAfterMerge: false } }); + harness.tryAutoMerge.mockResolvedValue({ + rightRev: "2-conflict", + leftLeaf: leaf("2-current", "Current\n", 2), + rightLeaf: leaf("2-conflict", "Conflict\n", 3), + }); + let finishFirst: (() => void) | undefined; + const resolveByUserInteraction = vi + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + finishFirst = () => resolve(false); + }) + ) + .mockResolvedValue(false); + harness.conflict.resolveByUserInteraction.addHandler(resolveByUserInteraction); + const subscription = new AbortController(); + harness.context.events.onEvent( + EVENT_CONFLICT_CANCELLED, + (filename) => { + if (filename === path) finishFirst?.(); + }, + { signal: subscription.signal } + ); + + try { + await harness.conflict.queueCheckFor(path); + await vi.waitFor(() => expect(resolveByUserInteraction).toHaveBeenCalledOnce()); + + await harness.conflict.queueCheckFor(path); + + await vi.waitFor(() => expect(resolveByUserInteraction).toHaveBeenCalledTimes(2)); + await expect(harness.conflict.ensureAllProcessed()).resolves.toBe(true); + expect(harness.conflict.conflictProcessQueueCount.value).toBe(0); + } finally { + subscription.abort(); + finishFirst?.(); + await harness.conflict.ensureAllProcessed(); + } + }); + + it("does not open an outdated dialogue when a later check is queued during inspection", async () => { + const path = "queued-during-inspection.md" as FilePathWithPrefix; + const harness = createHarness(); + const manualConflict = { + rightRev: "2-conflict", + leftLeaf: leaf("2-current", "Current\n", 2), + rightLeaf: leaf("2-conflict", "Conflict\n", 3), + }; + let finishInspection!: (result: typeof manualConflict) => void; + harness.tryAutoMerge + .mockImplementationOnce( + () => + new Promise((resolve) => { + finishInspection = resolve; + }) + ) + .mockResolvedValueOnce({ ok: NOT_CONFLICTED }); + const resolveByUserInteraction = vi.fn(async () => false); + harness.conflict.resolveByUserInteraction.addHandler(resolveByUserInteraction); + + try { + await harness.conflict.queueCheckFor(path); + await vi.waitFor(() => expect(harness.tryAutoMerge).toHaveBeenCalledOnce()); + + await harness.conflict.queueCheckFor(path); + finishInspection(manualConflict); + await expect(harness.conflict.ensureAllProcessed()).resolves.toBe(true); + + expect(resolveByUserInteraction).not.toHaveBeenCalled(); + expect(harness.tryAutoMerge).toHaveBeenCalledTimes(2); + } finally { + finishInspection?.(manualConflict); + await harness.conflict.ensureAllProcessed(); + } + }); + it("limits concurrent conflict checks and reports queued and active work", async () => { const paths = Array.from({ length: 11 }, (_, index) => `concurrent-${index}.md` as FilePathWithPrefix); const harness = createHarness(); @@ -929,8 +1009,10 @@ describe("conflict resolution serviceFeature", () => { it("resolves an identical pair, emits cancellation, and rechecks after merging", async () => { const path = "independently-created.md" as FilePathWithPrefix; const harness = createHarness({ settings: { syncAfterMerge: false } }); - const cancelled: FilePathWithPrefix[] = []; - harness.context.events.onEvent(EVENT_CONFLICT_CANCELLED, (filename) => cancelled.push(filename)); + const cancelled: Array<{ filename: FilePathWithPrefix; checks: number }> = []; + harness.context.events.onEvent(EVENT_CONFLICT_CANCELLED, (filename) => { + cancelled.push({ filename, checks: harness.tryAutoMerge.mock.calls.length }); + }); const leftLeaf = leaf("1-left", "Same content\n", 1000); const rightLeaf = leaf("1-right", "Same content\n", 2000); harness.tryAutoMerge @@ -947,7 +1029,15 @@ describe("conflict resolution serviceFeature", () => { expect(harness.fileHandler.deleteRevisionFromDB).toHaveBeenCalledWith(path, "1-left"); expect(harness.fileHandler.dbToStorage).toHaveBeenCalledWith(path, path, true); - expect(cancelled).toEqual([path, path]); + // A queued recheck may also cancel its finishing resolver. Keep both + // merge and final-inspection notifications covered without fixing the count. + expect(cancelled).toEqual( + expect.arrayContaining([ + { filename: path, checks: 1 }, + { filename: path, checks: 2 }, + ]) + ); + expect(cancelled.every(({ filename }) => filename === path)).toBe(true); expect(harness.tryAutoMerge).toHaveBeenCalledTimes(2); expect(AUTO_MERGED).toBeDefined(); }); diff --git a/src/serviceFeatures/conflictResolution/index.ts b/src/serviceFeatures/conflictResolution/index.ts index 62cd7bf1..5ca0293b 100644 --- a/src/serviceFeatures/conflictResolution/index.ts +++ b/src/serviceFeatures/conflictResolution/index.ts @@ -34,6 +34,7 @@ export const useConflictResolutionFeature = createServiceFeature((host: Conflict const checking = createConflictCheckingHandlers({ conflict: services.conflict, conflictProcessQueueCount: services.conflict.conflictProcessQueueCount, + cancelActiveResolution: operations.cancelActiveResolution, currentSettings: () => services.setting.currentSettings(), vault: services.vault, log, diff --git a/src/serviceFeatures/conflictResolution/operations.ts b/src/serviceFeatures/conflictResolution/operations.ts index 297e214d..39059d9f 100644 --- a/src/serviceFeatures/conflictResolution/operations.ts +++ b/src/serviceFeatures/conflictResolution/operations.ts @@ -54,6 +54,7 @@ export interface ConflictResolutionOperationsDependencies { } export interface ConflictResolutionOperations { + readonly cancelActiveResolution: (filename: FilePathWithPrefix) => void; readonly resolveByDeletingRevision: ( path: FilePathWithPrefix, deleteRevision: string, @@ -72,6 +73,13 @@ export function createConflictResolutionOperations( const latestResolveRequestByFilename = new Map(); let nextResolveRequestId = 0; + const cancelActiveResolution = (filename: FilePathWithPrefix): void => { + latestResolveRequestByFilename.delete(filename); + if (isLockAcquired(`conflict-resolve:${filename}`)) { + dependencies.events.emitEvent(EVENT_CONFLICT_CANCELLED, filename); + } + }; + const resolveByDeletingRevision = async ( path: FilePathWithPrefix, deleteRevision: string, @@ -299,6 +307,7 @@ export function createConflictResolutionOperations( }; return { + cancelActiveResolution, resolveByDeletingRevision, checkConflictAndPerformAutoMerge, resolve, From 8aa0438c77d1ff4adbf4062ce81823dc6882d56f Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 09:45:44 +0000 Subject: [PATCH 21/24] Replace stale hidden-file conflict dialogues --- docs/tips/hidden-file-sync.md | 6 + .../HiddenFileCommon/JsonResolveModal.ts | 13 +- .../JsonResolveModal.unit.spec.ts | 67 ++ .../CmdHiddenFileSync.queue.unit.spec.ts | 146 +++- .../HiddenFileSync/CmdHiddenFileSync.ts | 49 +- test/e2e-obsidian/README.md | 2 + .../scripts/hidden-file-snippet-sync.ts | 629 +++++++++++++++++- updates.md | 4 + 8 files changed, 894 insertions(+), 22 deletions(-) create mode 100644 src/features/HiddenFileCommon/JsonResolveModal.unit.spec.ts diff --git a/docs/tips/hidden-file-sync.md b/docs/tips/hidden-file-sync.md index 4bf0ca85..e5b74c55 100644 --- a/docs/tips/hidden-file-sync.md +++ b/docs/tips/hidden-file-sync.md @@ -72,6 +72,12 @@ Hidden File Sync must be enabled independently after ordinary setup on each devi If you later run Rebuild or Fetch as a recovery operation, expect optional features to be disabled again. Complete ordinary recovery first, then repeat this guide deliberately. +## Resolve a JSON conflict + +When automatic merging cannot combine conflicting JSON changes and no overwrite pattern applies, the **Conflicted Setting** dialogue compares two revisions. Review the proposed contents before choosing **Apply**. Closing the dialogue leaves the conflict unresolved. + +A later conflict check for the same file cancels the earlier comparison and checks the latest revisions again. If manual resolution is still needed, a replacement dialogue opens. A cancelled dialogue cannot apply a later selection. A resolution received through replication closes the comparison for that file; a remaining conflict is checked again. Dialogues for other files wait their turn. An **Apply** operation which has already started finishes before the replacement proceeds. + ## Automatic in Customisation Sync **Automatic** delegates an item's files to Hidden File Sync. Enable Hidden File Sync on this device through the steps above before choosing Automatic. If Hidden File Sync is disabled, the choice displays a Notice without changing the item's mode or starting initialisation. Previously saved Automatic assignments remain saved, so this prerequisite also applies after importing settings from another device. diff --git a/src/features/HiddenFileCommon/JsonResolveModal.ts b/src/features/HiddenFileCommon/JsonResolveModal.ts index 967645e2..6026702a 100644 --- a/src/features/HiddenFileCommon/JsonResolveModal.ts +++ b/src/features/HiddenFileCommon/JsonResolveModal.ts @@ -43,11 +43,12 @@ export class JsonResolveModal extends Modal { } async UICallback(keepRev?: string, mergedStr?: string) { - if (this.callback) { - await this.callback(keepRev, mergedStr); + const callback = this.callback; + this.callback = undefined; + if (callback) { + await callback(keepRev, mergedStr); } this.close(); - this.callback = undefined; } override onOpen() { @@ -78,8 +79,10 @@ export class JsonResolveModal extends Modal { const { contentEl } = this; contentEl.empty(); // contentEl.empty(); - if (this.callback != undefined) { - void this.callback(undefined); + const callback = this.callback; + this.callback = undefined; + if (callback) { + void callback(undefined); } if (this.component != undefined) { void unmount(this.component); diff --git a/src/features/HiddenFileCommon/JsonResolveModal.unit.spec.ts b/src/features/HiddenFileCommon/JsonResolveModal.unit.spec.ts new file mode 100644 index 00000000..c75f6451 --- /dev/null +++ b/src/features/HiddenFileCommon/JsonResolveModal.unit.spec.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from "vitest"; +import type { FilePath } from "@vrtmrz/livesync-commonlib/compat/common/types"; +import { sendSignal } from "@vrtmrz/livesync-commonlib/compat/common/utils"; +import { JsonResolveModal } from "./JsonResolveModal.ts"; + +vi.mock("@/deps.ts", () => ({ + App: class App {}, + Modal: class Modal { + contentEl = { empty: vi.fn() }; + close() { + (this as { onClose?: () => void }).onClose?.(); + } + }, +})); +vi.mock("./JsonResolvePane.svelte", () => ({ default: {} })); +vi.mock("svelte", () => ({ mount: vi.fn(), unmount: vi.fn() })); + +describe("JsonResolveModal completion", () => { + it("applies a selection once when closing the dialogue", async () => { + const filename = ".obsidian/selected-once.json" as FilePath; + const callback = vi.fn(async () => {}); + const modal = new JsonResolveModal({} as never, filename, [], callback); + + await modal.UICallback("2-kept"); + + expect(callback).toHaveBeenCalledExactlyOnceWith("2-kept", undefined); + sendSignal(`cancel-internal-conflict:${filename}`); + }); + + it("ignores a late selection after cancellation", async () => { + const filename = ".obsidian/cancelled-once.json" as FilePath; + const callback = vi.fn(async () => {}); + const modal = new JsonResolveModal({} as never, filename, [], callback); + + sendSignal(`cancel-internal-conflict:${filename}`); + await vi.waitFor(() => expect(callback).toHaveBeenCalledOnce()); + await modal.UICallback("2-stale"); + + expect(callback).toHaveBeenCalledExactlyOnceWith(undefined); + }); + + it("keeps an admitted write pending when cancellation closes its dialogue", async () => { + const filename = ".obsidian/writing-once.json" as FilePath; + let finish!: () => void; + const gate = new Promise((resolve) => { + finish = resolve; + }); + const callback = vi.fn(async () => await gate); + const modal = new JsonResolveModal({} as never, filename, [], callback); + const close = vi.spyOn(modal, "close"); + let completed = false; + const selected = modal.UICallback("2-kept").then(() => { + completed = true; + }); + + try { + sendSignal(`cancel-internal-conflict:${filename}`); + await vi.waitFor(() => expect(close).toHaveBeenCalledOnce()); + + expect(callback).toHaveBeenCalledExactlyOnceWith("2-kept", undefined); + expect(completed).toBe(false); + } finally { + finish(); + await selected; + } + }); +}); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts index 056e46a7..a7613ee8 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts @@ -18,6 +18,7 @@ import { type MetaEntry, } from "@vrtmrz/livesync-commonlib/compat/common/types"; import { HiddenFileSync } from "./CmdHiddenFileSync"; +import { sendSignal, waitForSignal } from "@vrtmrz/livesync-commonlib/compat/common/utils"; const queueOwners: HiddenFileSync[] = []; @@ -133,6 +134,132 @@ describe("HiddenFileSync conflict queue", () => { } }); + it.each(["prefixed", "unprefixed"])( + "cancels the older same-file dialogue and presents the latest revisions for a %s request", + async (form) => { + vi.useFakeTimers(); + const filename = `.obsidian/replacement-${form}.json`; + const path = `i:${filename}` as FilePathWithPrefix; + const id = String(path) as DocumentID; + let generation = 2; + const localDatabase = { + getRaw: vi.fn(async (_id: DocumentID, options?: { revs_info?: boolean }) => + options?.revs_info + ? {} + : { _id: id, path, _rev: `${generation}-current`, _conflicts: [`${generation}-other`] } + ), + getDBEntry: vi.fn( + async (_path: FilePathWithPrefix, options: { rev: string }) => + ({ _id: id, path, _rev: options.rev }) as LoadedEntry + ), + managers: { conflictManager: { mergeObject: vi.fn(async () => false) } }, + }; + const { hiddenFileSync } = createHiddenFileSync(localDatabase); + hiddenFileSync.path2id = async () => id; + const finishFirst = deferred(); + let cancelled = false; + const opened: string[][] = []; + hiddenFileSync.showJSONMergeDialogAndMerge = vi.fn(async (left, right) => { + opened.push([left._rev!, right._rev!]); + if (opened.length > 1) return false; + return await Promise.race([ + finishFirst.promise, + waitForSignal(`cancel-internal-conflict:${filename}`).then(() => { + cancelled = true; + return false; + }), + ]); + }); + + try { + hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(100); + expect(opened).toEqual([["2-current", "2-other"]]); + + generation = 3; + hiddenFileSync.queueConflictCheck((form === "prefixed" ? path : filename) as FilePathWithPrefix); + await vi.advanceTimersByTimeAsync(100); + + expect(cancelled).toBe(true); + expect(opened).toEqual([ + ["2-current", "2-other"], + ["3-current", "3-other"], + ]); + expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(true); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); + } finally { + finishFirst.resolve(false); + sendSignal(`cancel-internal-conflict:${filename}`); + await vi.advanceTimersByTimeAsync(100); + } + } + ); + + it.each(["same", "different"])( + "closes only a dialogue for the %s file when a replicated resolution arrives", + async (target) => { + vi.useFakeTimers(); + const filename = `.obsidian/received-${target}.json`; + const path = `i:${filename}` as FilePathWithPrefix; + const incomingPath = (target === "same" ? path : "i:.obsidian/other-resolved.json") as FilePathWithPrefix; + const id = String(path) as DocumentID; + let resolved = false; + const localDatabase = { + getRaw: vi.fn(async (_id: DocumentID, options?: { revs_info?: boolean }) => + options?.revs_info + ? {} + : { + _id: id, + path, + _rev: resolved ? "3-resolved" : "2-current", + _conflicts: resolved ? [] : ["2-other"], + } + ), + getDBEntry: vi.fn(async () => ({ _id: id, path }) as LoadedEntry), + managers: { conflictManager: { mergeObject: vi.fn(async () => false) } }, + }; + const { hiddenFileSync } = createHiddenFileSync(localDatabase); + hiddenFileSync.path2id = async () => id; + hiddenFileSync.getPath = () => incomingPath; + hiddenFileSync.isTargetFile = vi.fn(async () => true); + hiddenFileSync.trackDatabaseFileModification = vi.fn(async () => true); + const finishFirst = deferred(); + let cancelled = false; + hiddenFileSync.showJSONMergeDialogAndMerge = vi.fn( + async () => + await Promise.race([ + finishFirst.promise, + waitForSignal(`cancel-internal-conflict:${filename}`).then(() => { + cancelled = true; + return false; + }), + ]) + ); + + try { + hiddenFileSync.queueConflictCheck(path); + await vi.advanceTimersByTimeAsync(100); + expect(hiddenFileSync.showJSONMergeDialogAndMerge).toHaveBeenCalledOnce(); + + resolved = target === "same"; + const incoming = { _id: incomingPath, path: incomingPath, _rev: "3-received" } as LoadedEntry; + expect(await hiddenFileSync._anyProcessOptionalSyncFiles(incoming)).toBe(true); + await vi.advanceTimersByTimeAsync(100); + + expect(cancelled).toBe(target === "same"); + expect(hiddenFileSync.showJSONMergeDialogAndMerge).toHaveBeenCalledOnce(); + expect(hiddenFileSync.pendingConflictChecks.size).toBe(target === "same" ? 0 : 1); + if (target === "same") { + expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(true); + } + } finally { + finishFirst.resolve(false); + sendSignal(`cancel-internal-conflict:${filename}`); + await vi.advanceTimersByTimeAsync(100); + } + } + ); + it("waits for a cancelled manual merge dialogue and then finishes without requeueing", async () => { vi.useFakeTimers(); const path = "i:.obsidian/plugins/example/data.json" as FilePathWithPrefix; @@ -225,7 +352,7 @@ describe("HiddenFileSync pipeline contracts", () => { gates.forEach((gate, index) => gate.resolve({ path: paths[index] } as MetaEntry)); await vi.advanceTimersByTimeAsync(100); expect(await hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed()).toBe(true); - expect(reads).toEqual(paths); + expect(reads).toEqual([...paths, paths[0]]); expect(hiddenFileSync.pendingConflictChecks.size).toBe(0); }); @@ -233,6 +360,8 @@ describe("HiddenFileSync pipeline contracts", () => { vi.useFakeTimers(); const paths = Array.from({ length: 12 }, (_, index) => `i:.obsidian/${index}.json` as FilePathWithPrefix); const gates = paths.map(() => deferred()); + const firstDialogue = deferred(); + let firstCancelled = false; const localDatabase = { getRaw: vi.fn(async (id: DocumentID, options?: { revs_info?: boolean }) => options?.revs_info @@ -252,6 +381,15 @@ describe("HiddenFileSync pipeline contracts", () => { const opened: FilePathWithPrefix[] = []; hiddenFileSync.showJSONMergeDialogAndMerge = vi.fn((doc) => { opened.push(doc.path); + if (opened.length === 1) { + return Promise.race([ + firstDialogue.promise, + waitForSignal(`cancel-internal-conflict:${doc.path.slice(2)}`).then(() => { + firstCancelled = true; + return false; + }), + ]); + } return gates[paths.indexOf(doc.path)].promise; }); paths.forEach((path) => hiddenFileSync.queueConflictCheck(path)); @@ -260,12 +398,16 @@ describe("HiddenFileSync pipeline contracts", () => { expect(opened).toEqual([paths[0]]); paths.forEach((path) => hiddenFileSync.queueConflictCheck(path)); expect(hiddenFileSync.pendingConflictChecks.size).toBe(12); + await vi.advanceTimersByTimeAsync(100); + expect(firstCancelled).toBe(true); + expect(opened).toEqual([paths[0], paths[0]]); + expect(localDatabase.managers.conflictManager.mergeObject).toHaveBeenCalledTimes(24); let completed = false; void hiddenFileSync.conflictResolutionProcessor.waitForAllProcessed().then(() => { completed = true; }); for (let index = 0; index < paths.length; index++) { - expect(opened).toEqual(paths.slice(0, index + 1)); + expect(opened).toEqual([paths[0], ...paths.slice(0, index + 1)]); expect(completed).toBe(false); gates[index].resolve(false); await vi.advanceTimersByTimeAsync(100); diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.ts index 20e70d11..e9c32a96 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.ts @@ -741,21 +741,33 @@ Offline Changed files: ${processFiles.length}`; // --> Conflict processing - // Keep one in-flight conflict check per path so repeated sync events do not close the active merge dialogue. - pendingConflictChecks = new Set(); + // Coalesce unstarted checks; retain a replacement once processing has begun. + pendingConflictChecks = new Map(); queueConflictCheck(path: FilePathWithPrefix) { - if (this.pendingConflictChecks.has(path)) return; - this.pendingConflictChecks.add(path); + path = addPrefix(path, ICHeader); + const pending = this.pendingConflictChecks.get(path); + if (pending) { + if (pending.started) { + pending.recheck = true; + sendSignal(`cancel-internal-conflict:${stripAllPrefixes(path)}`); + } + return; + } + this.pendingConflictChecks.set(path, { started: false, recheck: false }); if (!this.conflictResolutionProcessor.enqueue(path)) this.pendingConflictChecks.delete(path); } finishConflictCheck(path: FilePathWithPrefix) { + path = addPrefix(path, ICHeader); + const pending = this.pendingConflictChecks.get(path); this.pendingConflictChecks.delete(path); + if (pending?.recheck) this.queueConflictCheck(path); } requeueConflictCheck(path: FilePathWithPrefix) { - this.finishConflictCheck(path); + path = addPrefix(path, ICHeader); + this.pendingConflictChecks.delete(path); this.queueConflictCheck(path); } @@ -806,10 +818,16 @@ Offline Changed files: ${processFiles.length}`; } conflictResolutionProcessor = new HiddenFileConflictQueue( async (path: FilePathWithPrefix) => { + const check = this.pendingConflictChecks.get(path); + if (check) check.started = true; try { // Retrieve data const id = await this.path2id(path, ICHeader); const doc = await this.localDatabase.getRaw(id, { conflicts: true }); + if (check?.recheck) { + this.requeueConflictCheck(path); + return []; + } if (doc._conflicts === undefined) { this.finishConflictCheck(path); return []; @@ -838,6 +856,10 @@ Offline Changed files: ${processFiles.length}`; doc._rev, conflictedRev ); + if (check?.recheck) { + this.requeueConflictCheck(path); + return []; + } if (result) { this._log(`Object merge:${path}`, LOG_LEVEL_INFO); const filename = stripAllPrefixes(path); @@ -861,7 +883,7 @@ Offline Changed files: ${processFiles.length}`; await this.resolveByNewerEntry(id, path, doc, revA, revB); return []; } - return [{ path, revA, revB, id, doc }]; + return [{ path, revA, revB, id, doc, check }]; } // When not JSON file, resolve conflicts by choosing a newer one. await this.resolveByNewerEntry(id, path, doc, revA, revB); @@ -874,10 +896,18 @@ Offline Changed files: ${processFiles.length}`; } }, async (result) => { - const { id, doc, path, revA, revB } = result; + const { id, doc, path, revA, revB, check } = result; + if (check?.recheck) { + this.requeueConflictCheck(path); + return; + } const prefixedPath = addPrefix(path, ICHeader); const docAMerge = await this.localDatabase.getDBEntry(prefixedPath, { rev: revA }); const docBMerge = await this.localDatabase.getDBEntry(prefixedPath, { rev: revB }); + if (check?.recheck) { + this.requeueConflictCheck(path); + return; + } try { if (docAMerge != false && docBMerge != false) { if (await this.showJSONMergeDialogAndMerge(docAMerge, docBMerge)) { @@ -912,7 +942,7 @@ Offline Changed files: ${processFiles.length}`; const displayFilename = `${storeFilePath}`; // const path = this.prefixedConfigDir2configDir(stripAllPrefixes(docA.path)) || docA.path; // Cancel only when replacing an existing dialogue for the same path, not on every queue pass. - sendSignal(`cancel-internal-conflict:${docA.path}`); + sendSignal(`cancel-internal-conflict:${storageFilePath}`); const modal = new JsonResolveModal(this.app, storageFilePath, [docA, docB], async (keep, result) => { // modal.close(); try { @@ -998,6 +1028,9 @@ Offline Changed files: ${processFiles.length}`; async processReplicationResult(doc: LoadedEntry): Promise { const info = this.getDocProps(doc); const path = info.path; + if (this.pendingConflictChecks.has(addPrefix(path, ICHeader))) { + this.queueConflictCheck(info.prefixedPath); + } const headerLine = `Tracking DB ${info.path} (${info.revDisplay}) :`; const ret = await this.trackDatabaseFileModification(path, headerLine); this._log(`${headerLine} Done: ${info.shortenedId})`, LOG_LEVEL_VERBOSE); diff --git a/test/e2e-obsidian/README.md b/test/e2e-obsidian/README.md index 0f16f86b..5124b640 100644 --- a/test/e2e-obsidian/README.md +++ b/test/e2e-obsidian/README.md @@ -272,6 +272,8 @@ This proves in real Obsidian the plug-in behaviour shared by supported platforms The JSON conflict cases enter through `resolveConflictOnInternalFiles()`, exercising the analysis queue and the serial manual-resolution queue. They check the stored content and remaining conflict revisions as well as the Vault files; the manual case must remain unfinished until a choice is made. +The conflict cases also verify same-file dialogue replacement and received resolutions. A newer check closes the older JSON comparison, reads the latest revisions, and preserves both leaves until selection. A resolution delivered to the registered optional-file replication handler closes only the affected dialogue, drains its queue, and retains the winner and Vault bytes; an unrelated file is a control. This isolates the Obsidian receive boundary from peer and transport setup. Use `--case=replacement` or `--case=external-resolution` to run one of these cases alone, with the CouchDB fixture already running. + Separate Vault pairs begin with Hidden File Sync disabled and enable it through the visible `Merge`, `Fetch`, and `Overwrite` buttons. Each pair contains a newer local file, a newer database file, and files present on only one side. The workflow verifies the selected contents in the files and database, the saved enablement setting, persistence after restart, and convergence on the other device. `--case=conflicts` runs only the conflict cases; `--case=enablement` runs only these enablement cases. Add `--mode=Merge`, `--mode=Fetch`, or `--mode=Overwrite` to select one enablement method. `test:e2e:obsidian:hidden-file-selectors` stores and restores selected JS, CSS, and JSON files with a normal-file allow-list set, and compares both directions with an empty allow-list. It uses one temporary Vault and a local database, and also runs in the complete local suite. Run it through the focused wrapper to build the current bundle first; no remote service is required. Set `E2E_HIDDEN_FILE_SELECTORS_OUTPUT` to choose the JSON report path. diff --git a/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts b/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts index 0853684f..4105aeca 100644 --- a/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts +++ b/test/e2e-obsidian/scripts/hidden-file-snippet-sync.ts @@ -62,7 +62,12 @@ const snippetContent = [ const mergeJsonPath = ".obsidian/livesync-e2e-merge.json"; const manualMergeJsonPath = ".obsidian/livesync-e2e-manual-merge.json"; +const replacementMergeJsonPath = ".obsidian/livesync-e2e-manual-replacement.json"; +const externalResolutionTargetPath = ".obsidian/livesync-e2e-external-resolution.json"; +const externalResolutionUnrelatedPath = ".obsidian/livesync-e2e-external-unrelated.json"; const hiddenConflictStateKey = "__livesyncE2EHiddenConflictResolution"; +const hiddenConflictComparisonStateKey = "__livesyncE2EHiddenConflictComparison"; +const hiddenConflictModalStateKey = "__livesyncE2EHiddenConflictModal"; const targetPath = ".obsidian/livesync-targeted/only-a.json"; const hiddenFileCliTimeoutMs = Number(process.env.E2E_OBSIDIAN_HIDDEN_FILE_CLI_TIMEOUT_MS ?? 90000); const hiddenFileInitialisationStateKey = "__livesyncE2EHiddenFileInitialisation"; @@ -326,6 +331,8 @@ async function startHiddenConflictResolution(cliBinary: string, env: NodeJS.Proc `const key=${JSON.stringify(hiddenConflictStateKey)};`, "const state={done:false,error:null};", "globalThis[key]=state;", + `const comparison=globalThis[${JSON.stringify(hiddenConflictComparisonStateKey)}];`, + "if(comparison)comparison.operation=state;", "const addOn=app.plugins.plugins['obsidian-livesync'].core.getAddOn('HiddenFileSync');", "void addOn.resolveConflictOnInternalFiles().then(", "()=>{state.done=true;},", @@ -338,6 +345,61 @@ async function startHiddenConflictResolution(cliBinary: string, env: NodeJS.Proc ); } +type HiddenJsonComparisonCall = { + leftRev: string | null; + rightRev: string | null; + done: boolean; + result: unknown; + error: string | null; +}; + +type HiddenJsonComparisonObservation = { + pipelineDone: boolean; + calls: HiddenJsonComparisonCall[]; +}; + +async function installHiddenJsonComparisonObserver(cliBinary: string, env: NodeJS.ProcessEnv): Promise { + await evalObsidianJson( + cliBinary, + [ + "(()=>{", + `const key=${JSON.stringify(hiddenConflictComparisonStateKey)};`, + "const addOn=app.plugins.plugins['obsidian-livesync'].core.getAddOn('HiddenFileSync');", + "const original=addOn.showJSONMergeDialogAndMerge;", + "if(typeof original!=='function')throw new Error('Hidden File Sync JSON comparison method is unavailable');", + "const state={calls:[],original,operation:null};", + "state.wrapper=function(left,right){", + "const call={leftRev:left?._rev??null,rightRev:right?._rev??null,done:false,result:null,error:null};", + "state.calls.push(call);", + "const result=state.original.call(this,left,right);", + "Promise.resolve(result).then(value=>{call.done=true;call.result=typeof value==='boolean'||value===null?value:String(value);},error=>{call.done=true;call.error=String(error);});", + "return result;};", + "addOn.showJSONMergeDialogAndMerge=state.wrapper;", + "globalThis[key]=state;return JSON.stringify({installed:true});", + "})()", + ].join(""), + env + ); +} + +async function readHiddenJsonComparisonObservation( + cliBinary: string, + env: NodeJS.ProcessEnv +): Promise { + return await evalObsidianJson( + cliBinary, + [ + "(()=>{", + `const state=globalThis[${JSON.stringify(hiddenConflictComparisonStateKey)}];`, + "const operation=state?.operation;", + "if(!state||!operation)throw new Error('Hidden JSON comparison observation is unavailable');", + "return JSON.stringify({pipelineDone:operation.done,calls:state.calls});", + "})()", + ].join(""), + env + ); +} + async function waitForHiddenConflictResolution(cliBinary: string, env: NodeJS.ProcessEnv): Promise { await evalObsidianJson( cliBinary, @@ -396,6 +458,51 @@ async function assertResolvedHiddenContent( assertEqual(content, expectedContent, `Stored hidden content differs from the Vault file: ${path}.`); } +type HiddenConflictLeaf = { + rev: string; + datatype: string; + data: string | string[]; +}; + +async function readHiddenConflictLeaves( + cliBinary: string, + env: NodeJS.ProcessEnv, + path: string +): Promise<{ currentRev: string; conflictRevs: string[]; leaves: HiddenConflictLeaf[] }> { + return await evalObsidianJson<{ + currentRev: string; + conflictRevs: string[]; + leaves: HiddenConflictLeaf[]; + }>( + cliBinary, + [ + "(async()=>{", + `const path=${JSON.stringify(path)};`, + "const db=app.plugins.plugins['obsidian-livesync'].core.localDatabase;", + "const entry=await db.getDBEntry(`i:${path}`);", + "if(!entry)throw new Error(`Hidden conflict entry is missing: ${path}`);", + "const current=await db.getRaw(entry._id,{conflicts:true});", + "const conflictRevs=current._conflicts||[];", + "const leaves=await Promise.all([current._rev,...conflictRevs].map(async rev=>{", + "const doc=await db.getDBEntry(`i:${path}`,{rev},false,true,true);", + "if(!doc)throw new Error(`Could not load hidden conflict revision ${rev}: ${path}`);", + "return {rev:doc._rev,datatype:doc.datatype,data:doc.data};}));", + "if(leaves.some(leaf=>!leaf.datatype||leaf.data===undefined))throw new Error(`Could not read every hidden conflict leaf: ${path}`);", + "return JSON.stringify({currentRev:current._rev,conflictRevs,leaves});", + "})()", + ].join(""), + env + ); +} + +function decodeHiddenConflictLeaf(leaf: HiddenConflictLeaf): string { + return leaf.datatype === "plain" + ? typeof leaf.data === "string" + ? leaf.data + : leaf.data.join("") + : new TextDecoder().decode(decodeBinary(leaf.data)); +} + async function storeHiddenFileAsConflict( cliBinary: string, env: NodeJS.ProcessEnv, @@ -676,6 +783,493 @@ async function runJsonManualConflictResolution(context: RunnerContext, vault: Te console.log(`Hidden JSON conflict modal applied the selected merged result. Screenshot: ${screenshotPath}`); } +async function runJsonManualConflictReplacement(context: RunnerContext, vault: TemporaryVault): Promise { + const base = JSON.stringify({ shared: "base" }, null, 4) + "\n"; + const left = JSON.stringify({ shared: "left", fromA: true }, null, 4) + "\n"; + const right = JSON.stringify({ shared: "right", fromB: true }, null, 4) + "\n"; + const latestMarker = `hidden-json-replacement-${context.dbName}`; + const latest = JSON.stringify({ shared: "latest", fromA: true, fromB: true, latestMarker }, null, 4) + "\n"; + const session = await startConfiguredSession(context, vault); + + await createHiddenJsonConflict(context, session, vault, replacementMergeJsonPath, base, left, right); + await installHiddenJsonComparisonObserver(context.cliBinary, session.cliEnv); + + await startHiddenConflictResolution(context.cliBinary, session.cliEnv); + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + const firstOption = page.locator('label:has(input[name="disp"][value="AB"])').last(); + await firstOption.waitFor({ state: "visible", timeout: 10000 }); + await firstOption.evaluate((element, key) => { + const firstModal = element.closest(".modal-container"); + if (!(firstModal instanceof HTMLElement)) + throw new Error("The first JSON conflict dialogue has no modal container"); + (globalThis as unknown as Record)[key] = { firstModal }; + }, hiddenConflictModalStateKey); + }); + + const firstDialogueState = await readHiddenJsonComparisonObservation(context.cliBinary, session.cliEnv); + assertEqual( + firstDialogueState.pipelineDone, + false, + "The hidden conflict pipeline completed before replacing its first dialogue." + ); + assertEqual(firstDialogueState.calls.length, 1, "The first hidden JSON comparison was not observed exactly once."); + assertEqual( + firstDialogueState.calls[0].done, + false, + "The first hidden JSON comparison completed before the replacement request." + ); + + await writeVaultFile(vault.path, replacementMergeJsonPath, latest); + const updatedWinner = await evalObsidianJson<{ rev: string }>( + context.cliBinary, + [ + "(async()=>{", + `const path=${JSON.stringify(replacementMergeJsonPath)};`, + "const core=app.plugins.plugins['obsidian-livesync'].core;", + "const addOn=core.getAddOn('HiddenFileSync');", + "const db=core.localDatabase;", + "const entry=await db.getDBEntry(`i:${path}`);", + "if(!entry)throw new Error(`Hidden conflict winner is missing: ${path}`);", + "const current=await db.getRaw(entry._id,{conflicts:true});", + "const conflictRevs=current._conflicts||[];", + "if(conflictRevs.length!==1)throw new Error(`Expected one competing hidden leaf before replacement: ${path}`);", + "const conflicts=await Promise.all(conflictRevs.map(rev=>db.getDBEntry(`i:${path}`,{rev},false,true,true)));", + "if(conflicts.some(doc=>!doc))throw new Error(`Could not read the competing hidden revision: ${path}`);", + "const mtime=Math.max(Number(entry.mtime)||0,...conflicts.map(doc=>Number(doc.mtime)||0))+10;", + "const fileInfo=await addOn.loadFileWithInfo(path);", + "if(fileInfo.deleted)throw new Error(`Hidden replacement file was unexpectedly deleted: ${path}`);", + "const baseData=await addOn.__loadBaseSaveData(path,true);", + "if(baseData===false)throw new Error(`Could not load hidden replacement save data: ${path}`);", + "const saveData={...baseData,data:fileInfo.body,mtime,ctime:fileInfo.stat.ctime,size:fileInfo.stat.size,children:[],deleted:false,type:baseData.datatype};", + "const result=await db.putDBEntry(saveData,false,entry._rev);", + "if(!result?.ok)throw new Error(`Could not advance the current hidden conflict winner: ${path}`);", + "return JSON.stringify({rev:result.rev});", + "})()", + ].join(""), + session.cliEnv + ); + const beforeQueue = await readHiddenConflictLeaves(context.cliBinary, session.cliEnv, replacementMergeJsonPath); + assertEqual( + beforeQueue.currentRev, + updatedWinner.rev, + "The latest hidden conflict revision is not the current winner." + ); + assertEqual( + beforeQueue.conflictRevs.length, + 1, + "Advancing the current winner changed the competing hidden leaf count." + ); + assertEqual( + beforeQueue.leaves.length, + 2, + "Advancing the current winner did not retain both hidden conflict leaves." + ); + const beforeQueueContents = beforeQueue.leaves.map(decodeHiddenConflictLeaf); + assertEqual( + beforeQueueContents.includes(latest), + true, + "The current hidden winner does not contain the latest JSON content." + ); + assertEqual( + beforeQueueContents.some((content) => content === left || content === right), + true, + "The competing hidden leaf content is not readable after advancing the current winner." + ); + + await evalObsidianJson( + context.cliBinary, + [ + "(()=>{", + `const path=${JSON.stringify(replacementMergeJsonPath)};`, + "const addOn=app.plugins.plugins['obsidian-livesync'].core.getAddOn('HiddenFileSync');", + "addOn.queueConflictCheck(path);", + "return JSON.stringify({queued:true});", + "})()", + ].join(""), + session.cliEnv + ); + + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + await page.waitForFunction( + (key) => { + const state = (globalThis as unknown as Record)[key]; + if (!state || state.firstModal.isConnected) return false; + const visibleLabels = Array.from( + document.querySelectorAll('label:has(input[name="disp"])') + ).filter( + (label) => label.getClientRects().length > 0 && getComputedStyle(label).visibility !== "hidden" + ); + const roots = new Set(visibleLabels.map((label) => label.closest(".modal-container"))); + return visibleLabels.length >= 2 && roots.size === 1; + }, + hiddenConflictModalStateKey, + { timeout: 10000 } + ); + const visibleDialogueCount = await page.evaluate(() => { + const visibleLabels = Array.from( + document.querySelectorAll('label:has(input[name="disp"])') + ).filter((label) => label.getClientRects().length > 0 && getComputedStyle(label).visibility !== "hidden"); + return new Set(visibleLabels.map((label) => label.closest(".modal-container"))).size; + }); + assertEqual( + visibleDialogueCount, + 1, + "Replacing a hidden comparison left more than one JSON conflict dialogue visible." + ); + }); + + const replacementDialogueState = await readHiddenJsonComparisonObservation(context.cliBinary, session.cliEnv); + assertEqual( + replacementDialogueState.pipelineDone, + false, + "The hidden conflict pipeline completed before the replacement dialogue was applied." + ); + assertEqual( + replacementDialogueState.calls.length, + 2, + "The latest hidden conflict request did not open a second comparison." + ); + assertEqual( + replacementDialogueState.calls[0].done, + true, + "The first hidden JSON comparison did not complete when replaced." + ); + assertEqual(replacementDialogueState.calls[0].result, false, "The first hidden JSON comparison was not cancelled."); + assertEqual( + [replacementDialogueState.calls[1].leftRev, replacementDialogueState.calls[1].rightRev].includes( + updatedWinner.rev + ), + true, + "The replacement JSON comparison did not include the latest current revision." + ); + assertEqual( + replacementDialogueState.calls[1].done, + false, + "The replacement JSON comparison completed before the user selected it." + ); + + const afterCancellation = await readHiddenConflictLeaves( + context.cliBinary, + session.cliEnv, + replacementMergeJsonPath + ); + assertEqual( + afterCancellation.currentRev, + updatedWinner.rev, + "Cancelling the first dialogue changed the latest current revision." + ); + assertEqual( + afterCancellation.conflictRevs.length, + 1, + "Cancelling the first dialogue removed the competing hidden leaf." + ); + assertEqual( + afterCancellation.leaves.length, + 2, + "Cancelling the first dialogue did not preserve both hidden conflict leaves." + ); + const afterCancellationContents = afterCancellation.leaves.map(decodeHiddenConflictLeaf); + assertEqual( + afterCancellationContents.includes(latest), + true, + "The latest hidden content became unreadable after cancelling the first dialogue." + ); + assertEqual( + afterCancellationContents.some((content) => content === left || content === right), + true, + "The competing hidden content became unreadable after cancelling the first dialogue." + ); + + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + const optionAB = page.locator('label:has(input[name="disp"][value="AB"])').last(); + await optionAB.waitFor({ state: "visible", timeout: 10000 }); + await optionAB.click(); + const selected = await page.locator('input[name="disp"][value="AB"]').last().isChecked(); + assertEqual(selected, true, "The replacement JSON dialogue did not select AB."); + await page.waitForFunction( + (marker) => { + const options = Array.from( + document.querySelectorAll('input[name="disp"][value="AB"]') + ); + const option = options + .reverse() + .find((candidate) => (candidate.closest("label")?.getClientRects().length ?? 0) > 0); + const modal = option?.closest(".modal-container"); + if (!(modal instanceof HTMLElement)) return false; + const values = Array.from( + modal.querySelectorAll("input,textarea") + ).map((element) => element.value); + return `${modal.innerText}\n${values.join("\n")}`.includes(marker); + }, + latestMarker, + { timeout: 10000 } + ); + await page.getByRole("button", { name: "Apply" }).last().click(); + }); + await waitForHiddenConflictResolution(context.cliBinary, session.cliEnv); + + const resolved = await waitForPathContent(vault.path, replacementMergeJsonPath, (content) => + hasJsonValues(content, { shared: "latest", fromA: true, fromB: true, latestMarker }) + ); + await assertResolvedHiddenContent(context.cliBinary, session.cliEnv, replacementMergeJsonPath, resolved); + const parsed = JSON.parse(resolved) as Record; + assertEqual(parsed.latestMarker, latestMarker, "The applied JSON result lost the latest replacement marker."); + + const finalDialogueState = await readHiddenJsonComparisonObservation(context.cliBinary, session.cliEnv); + assertEqual(finalDialogueState.pipelineDone, true, "The replacement hidden conflict pipeline did not finish."); + assertEqual( + finalDialogueState.calls[0].result, + false, + "The replaced hidden JSON comparison did not remain cancelled." + ); + assertEqual(finalDialogueState.calls[1].done, true, "The replacement hidden JSON comparison did not complete."); + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + const finalState = await page.evaluate((key) => { + const state = (globalThis as unknown as Record)[key]; + const visibleLabels = Array.from( + document.querySelectorAll('label:has(input[name="disp"])') + ).filter((label) => label.getClientRects().length > 0 && getComputedStyle(label).visibility !== "hidden"); + return { + firstConnected: state?.firstModal.isConnected ?? false, + visibleDialogueCount: new Set(visibleLabels.map((label) => label.closest(".modal-container"))).size, + }; + }, hiddenConflictModalStateKey); + assertEqual( + finalState.firstConnected, + false, + "The replaced JSON conflict dialogue remained connected after resolution." + ); + assertEqual( + finalState.visibleDialogueCount, + 0, + "A stale JSON conflict dialogue remained open after resolution." + ); + }); + + await stopSession(context, session); + console.log( + "Hidden JSON conflict replacement cancelled the stale dialogue and applied the latest revision and contents." + ); +} + +async function runJsonManualExternalResolution(context: RunnerContext, vault: TemporaryVault): Promise { + const base = JSON.stringify({ shared: "base" }, null, 4) + "\n"; + const left = JSON.stringify({ shared: "left", fromA: true }, null, 4) + "\n"; + const right = JSON.stringify({ shared: "right", fromB: true }, null, 4) + "\n"; + const unrelatedContent = JSON.stringify({ externalResolution: "unrelated" }, null, 4) + "\n"; + const session = await startConfiguredSession(context, vault); + + await writeVaultFile(vault.path, externalResolutionUnrelatedPath, unrelatedContent); + await scanHiddenStorage(context.cliBinary, session.cliEnv); + const unrelatedEntry = await waitForLocalDatabaseEntry( + context.cliBinary, + session.cliEnv, + externalResolutionUnrelatedPath, + { + hidden: true, + } + ); + await createHiddenJsonConflict(context, session, vault, externalResolutionTargetPath, base, left, right); + const initialLeaves = await readHiddenConflictLeaves( + context.cliBinary, + session.cliEnv, + externalResolutionTargetPath + ); + assertEqual( + initialLeaves.conflictRevs.length, + 1, + "The external-resolution target did not have one competing leaf." + ); + assertEqual(initialLeaves.leaves.length, 2, "The external-resolution target did not retain two live leaves."); + const winnerContent = decodeHiddenConflictLeaf( + initialLeaves.leaves.find((leaf) => leaf.rev === initialLeaves.currentRev) ?? initialLeaves.leaves[0] + ); + assertEqual( + [left, right].includes(winnerContent), + true, + "The initial hidden conflict winner content is not readable." + ); + await writeVaultFile(vault.path, externalResolutionTargetPath, winnerContent); + + await installHiddenJsonComparisonObserver(context.cliBinary, session.cliEnv); + await startHiddenConflictResolution(context.cliBinary, session.cliEnv); + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + const firstOption = page.locator('label:has(input[name="disp"][value="AB"])').last(); + await firstOption.waitFor({ state: "visible", timeout: 10000 }); + await firstOption.evaluate((element, key) => { + const firstModal = element.closest(".modal-container"); + if (!(firstModal instanceof HTMLElement)) + throw new Error("The external-resolution JSON dialogue has no modal container"); + (globalThis as unknown as Record)[key] = { firstModal }; + }, hiddenConflictModalStateKey); + }); + + const initialObservation = await readHiddenJsonComparisonObservation(context.cliBinary, session.cliEnv); + assertEqual( + initialObservation.pipelineDone, + false, + "The external-resolution conflict pipeline completed before a result arrived." + ); + assertEqual( + initialObservation.calls.length, + 1, + "The external-resolution target did not open exactly one comparison." + ); + assertEqual( + initialObservation.calls[0].done, + false, + "The external-resolution dialogue completed before a result arrived." + ); + + const unrelatedResolution = await evalObsidianJson<{ rev: string }>( + context.cliBinary, + [ + "(async()=>{", + `const path=${JSON.stringify(externalResolutionUnrelatedPath)};`, + "const core=app.plugins.plugins['obsidian-livesync'].core;", + "const meta=await core.localDatabase.getDBEntryMeta(`i:${path}`,{conflicts:true},true);", + "if(!meta)throw new Error(`Unrelated hidden metadata is missing: ${path}`);", + "if((meta._conflicts||[]).length!==0)throw new Error(`Unrelated hidden metadata unexpectedly has conflicts: ${path}`);", + "await core.services.replication.processOptionalSynchroniseResult(meta);", + "return JSON.stringify({rev:meta._rev});", + "})()", + ].join(""), + session.cliEnv, + hiddenFileCliTimeoutMs + ); + assertEqual( + unrelatedResolution.rev, + unrelatedEntry.rev, + "The unrelated hidden fixture did not have the expected single revision." + ); + const afterUnrelatedResult = await readHiddenJsonComparisonObservation(context.cliBinary, session.cliEnv); + assertEqual( + afterUnrelatedResult.pipelineDone, + false, + "A result for another hidden path completed the target conflict pipeline." + ); + assertEqual(afterUnrelatedResult.calls.length, 1, "A result for another path opened another target comparison."); + assertEqual( + afterUnrelatedResult.calls[0].done, + false, + "A result for another path closed the target JSON comparison." + ); + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + const modalState = await page.evaluate((key) => { + const state = (globalThis as unknown as Record)[key]; + const visibleLabels = Array.from( + document.querySelectorAll('label:has(input[name="disp"])') + ).filter((label) => label.getClientRects().length > 0 && getComputedStyle(label).visibility !== "hidden"); + return { + firstConnected: state?.firstModal.isConnected ?? false, + visibleDialogueCount: new Set(visibleLabels.map((label) => label.closest(".modal-container"))).size, + }; + }, hiddenConflictModalStateKey); + assertEqual(modalState.firstConnected, true, "An unrelated hidden result detached the target JSON dialogue."); + assertEqual( + modalState.visibleDialogueCount, + 1, + "An unrelated hidden result changed the visible target dialogue count." + ); + }); + + const targetResolution = await evalObsidianJson<{ winnerRev: string; removedRev: string }>( + context.cliBinary, + [ + "(async()=>{", + `const path=${JSON.stringify(externalResolutionTargetPath)};`, + "const db=app.plugins.plugins['obsidian-livesync'].core.localDatabase;", + "const entry=await db.getDBEntry(`i:${path}`);", + "if(!entry)throw new Error(`Hidden conflict entry is missing: ${path}`);", + "const current=await db.getRaw(entry._id,{conflicts:true});", + "const conflictRevs=current._conflicts||[];", + "if(conflictRevs.length!==1)throw new Error(`Expected one hidden conflict leaf before external resolution: ${path}`);", + "const removedRev=conflictRevs[0];", + "await db.removeRevision(entry._id,removedRev);", + "const meta=await db.getDBEntryMeta(`i:${path}`,{conflicts:true},true);", + "if(!meta)throw new Error(`Resolved hidden metadata is missing: ${path}`);", + "if((meta._conflicts||[]).length!==0)throw new Error(`External hidden resolution still has conflicts: ${path}`);", + "await app.plugins.plugins['obsidian-livesync'].core.services.replication.processOptionalSynchroniseResult(meta);", + "return JSON.stringify({winnerRev:meta._rev,removedRev});", + "})()", + ].join(""), + session.cliEnv, + hiddenFileCliTimeoutMs + ); + await waitForHiddenConflictResolution(context.cliBinary, session.cliEnv); + + const resolvedLeaves = await readHiddenConflictLeaves( + context.cliBinary, + session.cliEnv, + externalResolutionTargetPath + ); + assertEqual( + resolvedLeaves.currentRev, + targetResolution.winnerRev, + "External hidden resolution changed the selected winner revision." + ); + assertEqual( + resolvedLeaves.currentRev, + initialLeaves.currentRev, + "External hidden resolution changed the current winner revision." + ); + assertEqual( + targetResolution.removedRev, + initialLeaves.conflictRevs[0], + "External hidden resolution removed a different leaf than the competing revision." + ); + assertEqual( + resolvedLeaves.conflictRevs.length, + 0, + "The externally resolved hidden conflict remains in the database." + ); + assertEqual( + resolvedLeaves.leaves.length, + 1, + "External hidden resolution did not leave exactly one readable revision." + ); + assertEqual( + decodeHiddenConflictLeaf(resolvedLeaves.leaves[0]), + winnerContent, + "External hidden resolution changed the current winner bytes." + ); + const vaultWinner = await waitForPathContent( + vault.path, + externalResolutionTargetPath, + (content) => content === winnerContent + ); + await assertResolvedHiddenContent(context.cliBinary, session.cliEnv, externalResolutionTargetPath, vaultWinner); + + const finalObservation = await readHiddenJsonComparisonObservation(context.cliBinary, session.cliEnv); + assertEqual(finalObservation.pipelineDone, true, "The externally resolved hidden conflict pipeline did not drain."); + assertEqual(finalObservation.calls.length, 1, "External resolution opened a second JSON comparison."); + assertEqual(finalObservation.calls[0].done, true, "The external-resolution JSON comparison did not complete."); + assertEqual(finalObservation.calls[0].result, false, "The external-resolution JSON dialogue was not cancelled."); + await withObsidianPage(obsidianRemoteDebuggingPort(), async (page) => { + const modalState = await page.evaluate((key) => { + const state = (globalThis as unknown as Record)[key]; + const visibleLabels = Array.from( + document.querySelectorAll('label:has(input[name="disp"])') + ).filter((label) => label.getClientRects().length > 0 && getComputedStyle(label).visibility !== "hidden"); + return { + firstConnected: state?.firstModal.isConnected ?? false, + visibleDialogueCount: new Set(visibleLabels.map((label) => label.closest(".modal-container"))).size, + }; + }, hiddenConflictModalStateKey); + assertEqual(modalState.firstConnected, false, "The externally resolved JSON dialogue remained connected."); + assertEqual( + modalState.visibleDialogueCount, + 0, + "The old hidden conflict dialogue reopened after external resolution." + ); + }); + + await stopSession(context, session); + console.log( + "Hidden JSON conflict dialogue closed for an external same-path resolution and preserved the selected bytes." + ); +} + async function runTargetMismatch( context: RunnerContext, vaultA: TemporaryVault, @@ -1261,10 +1855,18 @@ async function runHiddenEnablement(context: RunnerContext, mode: HiddenEnablemen async function main(): Promise { const selectedCase = process.argv.find((argument) => argument.startsWith("--case="))?.slice(7); - if (selectedCase && selectedCase !== "conflicts" && selectedCase !== "enablement") { - throw new Error("Use --case=conflicts or --case=enablement."); + if ( + selectedCase && + selectedCase !== "conflicts" && + selectedCase !== "replacement" && + selectedCase !== "external-resolution" && + selectedCase !== "enablement" + ) { + throw new Error("Use --case=conflicts, --case=replacement, --case=external-resolution, or --case=enablement."); } const conflictsOnly = selectedCase === "conflicts"; + const replacementOnly = selectedCase === "replacement"; + const externalResolutionOnly = selectedCase === "external-resolution"; const enablementOnly = selectedCase === "enablement"; const selectedMode = process.argv.find((argument) => argument.startsWith("--mode="))?.slice(7); const enablementModes = (["Merge", "Fetch", "Overwrite"] as const).filter( @@ -1290,7 +1892,14 @@ async function main(): Promise { dbName, activeSessions: new Set(), temporaryVaults: new Set([vaultA, vaultB]), - diagnosticPaths: [mergeJsonPath, manualMergeJsonPath, snippetPath], + diagnosticPaths: [ + mergeJsonPath, + manualMergeJsonPath, + replacementMergeJsonPath, + externalResolutionTargetPath, + externalResolutionUnrelatedPath, + snippetPath, + ], }; try { @@ -1302,20 +1911,26 @@ async function main(): Promise { console.log(`Temporary vault B: ${vaultB.path}`); console.log(`Temporary CouchDB database: ${dbName}`); - if (!conflictsOnly && !enablementOnly) { + if (!conflictsOnly && !replacementOnly && !externalResolutionOnly && !enablementOnly) { await runCreateRoundTrip(context, vaultA, vaultB); await runDeleteRoundTrip(context, vaultA, vaultB); } - if (!enablementOnly) { + if (!enablementOnly && !replacementOnly && !externalResolutionOnly) { await runJsonConflictRoundTrip(context, vaultA, vaultB); await runJsonManualConflictResolution(context, vaultB); } - if (!conflictsOnly && !enablementOnly) { + if (!enablementOnly && !externalResolutionOnly) { + await runJsonManualConflictReplacement(context, vaultB); + } + if (!enablementOnly && !replacementOnly) { + await runJsonManualExternalResolution(context, vaultB); + } + if (!conflictsOnly && !replacementOnly && !externalResolutionOnly && !enablementOnly) { await runTargetMismatch(context, vaultA, vaultB); await runInitialisationNoticeGrouping(context, vaultB); await runConfigurationNoticeGrouping(context, vaultB); } - if (!conflictsOnly) { + if (!conflictsOnly && !replacementOnly && !externalResolutionOnly) { for (const mode of enablementModes) await runHiddenEnablement(context, mode); } } catch (error) { diff --git a/updates.md b/updates.md index 6d31210f..c267077b 100644 --- a/updates.md +++ b/updates.md @@ -24,6 +24,10 @@ Earlier releases remain available in the 1.0 release history, the 1.0 preview hi - Hidden File Sync now stores newer local files during `Merge` initialisation by comparing local and database modification times in the correct direction. +- Hidden File Sync refreshes an open manual JSON comparison when a later conflict check arrives for the same file. + - The earlier dialogue closes, and the latest revisions are checked again before another comparison opens. A replicated resolution also closes the affected comparison. Dialogues for other files keep their order. + - An `Apply` operation already in progress finishes before its replacement proceeds. + - Reloading the Customisation Sync catalogue no longer allows an earlier legacy-format scan to put outdated items back into the list. - Reloading or disabling Customisation Sync discards unstarted scans and ignores stale read results. Migrations to per-file storage which have already started are allowed to finish. From f596d90e1be018d0f2007739f6165f23b22e2385 Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 09:50:46 +0000 Subject: [PATCH 22/24] Use document IDs in received-conflict fixtures --- .../HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts index a7613ee8..7460692c 100644 --- a/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts +++ b/src/features/HiddenFileSync/CmdHiddenFileSync.queue.unit.spec.ts @@ -242,7 +242,11 @@ describe("HiddenFileSync conflict queue", () => { expect(hiddenFileSync.showJSONMergeDialogAndMerge).toHaveBeenCalledOnce(); resolved = target === "same"; - const incoming = { _id: incomingPath, path: incomingPath, _rev: "3-received" } as LoadedEntry; + const incoming = { + _id: String(incomingPath) as DocumentID, + path: incomingPath, + _rev: "3-received", + } as LoadedEntry; expect(await hiddenFileSync._anyProcessOptionalSyncFiles(incoming)).toBe(true); await vi.advanceTimersByTimeAsync(100); From 3364e041416ba849b9c2a0f25f06f73afe4873cd Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 10:42:27 +0000 Subject: [PATCH 23/24] Bound journal recovery fixture bucket names --- test/e2e-cli/test-journal-chunk-recovery.ts | 24 ++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/test/e2e-cli/test-journal-chunk-recovery.ts b/test/e2e-cli/test-journal-chunk-recovery.ts index cbddea52..345fbc88 100644 --- a/test/e2e-cli/test-journal-chunk-recovery.ts +++ b/test/e2e-cli/test-journal-chunk-recovery.ts @@ -15,6 +15,13 @@ function requireEnv(...keys: string[]): string { throw new Error(`Required env var is missing: ${keys.join(" or ")}`); } +function createJournalRecoveryBucketName(baseBucket: string, suffix: string): string { + const bucketSuffix = `journal-recovery-${suffix}`; + const maxBaseLength = 63 - bucketSuffix.length - 1; + const truncatedBase = baseBucket.slice(0, maxBaseLength).replace(/-+$/, ""); + return truncatedBase ? `${truncatedBase}-${bucketSuffix}` : bucketSuffix; +} + function createJournalFixture(): string { return [ "Journal chunk recovery fixture: UTF-8, newlines, and backslashes.\n", @@ -32,7 +39,7 @@ async function runScenario(encrypt: boolean): Promise { const minioEndpoint = requireEnv("MINIO_ENDPOINT", "minioEndpoint").replace(/\/$/, ""); const minioAccessKey = requireEnv("MINIO_ACCESS_KEY", "accessKey"); const minioSecretKey = requireEnv("MINIO_SECRET_KEY", "secretKey"); - const minioBucket = `${requireEnv("MINIO_BUCKET_NAME", "bucketName")}-journal-recovery-${suffix}`; + const minioBucket = createJournalRecoveryBucketName(requireEnv("MINIO_BUCKET_NAME", "bucketName"), suffix); const passphrase = "e2e-passphrase"; const fileContent = createJournalFixture(); const expectedBytes = Buffer.from(fileContent, "utf8"); @@ -184,6 +191,21 @@ async function runScenario(encrypt: boolean): Promise { } } +test("journal recovery bucket name construction stays within S3 limits", () => { + const ciBucket = createJournalRecoveryBucketName("livesync-test-bucket-ci", "enc0-1793522628122-62377"); + assert.ok(ciBucket.length <= 63, "The CI fixture must stay within the S3 bucket-name length limit"); + assert.match(ciBucket, /^[a-z0-9][a-z0-9-]*[a-z0-9]$/); + + const longBase = "a".repeat(63); + const unencryptedBucket = createJournalRecoveryBucketName(longBase, "enc0-1793522628122-62377"); + const encryptedBucket = createJournalRecoveryBucketName(longBase, "enc1-1793522628122-62377"); + assert.ok(unencryptedBucket.length <= 63); + assert.ok(encryptedBucket.length <= 63); + assert.match(unencryptedBucket, /^[a-z0-9][a-z0-9-]*[a-z0-9]$/); + assert.match(encryptedBucket, /^[a-z0-9][a-z0-9-]*[a-z0-9]$/); + assert.notEqual(unencryptedBucket, encryptedBucket, "Encryption scenarios should have distinct buckets"); +}); + test("journal chunk recovery through MINIO", async (t) => { await t.test("without encryption", async () => runScenario(false)); await t.test("with encryption", async () => runScenario(true)); From d2b55c7f49dc08d3c6105ba8a4d6ab0977f4c7dc Mon Sep 17 00:00:00 2001 From: vorotamoroz Date: Sun, 1 Nov 2026 10:51:46 +0000 Subject: [PATCH 24/24] Run CLI database continuity regression in standard CI --- test/README.md | 32 ++++-- test/e2e-cli/ci-tasks.json | 3 +- test/e2e-cli/helpers/docker.ts | 54 ++++++++++ test/e2e-cli/tasks.json | 3 +- test/e2e-cli/test-ci-task-contract.ts | 18 ++++ .../e2e-cli/test-fetch-database-continuity.ts | 101 +++++++++++++++--- 6 files changed, 185 insertions(+), 26 deletions(-) create mode 100644 test/e2e-cli/test-ci-task-contract.ts diff --git a/test/README.md b/test/README.md index c9a081f4..f083f9ec 100644 --- a/test/README.md +++ b/test/README.md @@ -94,21 +94,37 @@ This establishes the CLI and shared Rebuild/Fetch behaviour. It does not exercis ## CLI Fetch database continuity -After building the CLI, run `node test/e2e-cli/run-task.ts test:fetch-database-continuity` -with Node.js 26 and a disposable S3-compatible service. Set +The standard CLI CI suite and direct task runner execute +`test:fetch-database-continuity` against a dedicated RustFS container. Each +scenario creates its own bucket. The test binds a uniquely named container to a +dynamic loopback port, then stops only that container. Redacted evidence is +written under the operating system's temporary directory and is not uploaded as +an artefact. + +For a local run, build the CLI and run +`node test/e2e-cli/run-task.ts test:fetch-database-continuity` with Node.js 26 +and Docker available. The managed container uses `accessKey` and `secretKey` +from the CLI `.test.env` file when present, and defaults to `minioadmin` for +both. No endpoint, bucket, or evidence-directory variables are needed. Set +`LIVESYNC_ISSUE1304_EVIDENCE_DIR` to choose another evidence directory outside +the worktree. + +To use an external S3-compatible fixture without Docker, set all four `LIVESYNC_ISSUE1304_MINIO_ENDPOINT`, `LIVESYNC_ISSUE1304_MINIO_ACCESS_KEY`, `LIVESYNC_ISSUE1304_MINIO_SECRET_KEY`, and `LIVESYNC_ISSUE1304_MINIO_BUCKET`. -The bucket must be fresh and empty for every run. Set -`LIVESYNC_ISSUE1304_EVIDENCE_DIR` to an evidence directory outside the worktree. -This test writes remote data; never point it at a production bucket. +The bucket must be fresh and empty for every run. Partial external fixture +configuration is rejected. This test writes remote data; never point it at a +production bucket. The test seeds an encrypted, path-obfuscated file with a second-generation revision, imports one Setup URI on two clients, fetches on A without `--write-settings`, and restarts A while B remains online. It checks the saved database suffix, file bytes, original revision, and absence of a duplicate root. -Set `LIVESYNC_ISSUE1304_POSITIVE_CONTROL=1` and -`LIVESYNC_ISSUE1304_POSITIVE_CONTROL_BUCKET` to a second fresh bucket to exercise -the explicit `--write-settings` variant as well. +Managed runs execute the explicit `--write-settings` control automatically in +a separate scenario bucket. For an external fixture, set +`LIVESYNC_ISSUE1304_POSITIVE_CONTROL=1` and +`LIVESYNC_ISSUE1304_POSITIVE_CONTROL_BUCKET` to a second fresh bucket to run +that control. For historical reproduction against the unmodified implementation, set `LIVESYNC_ISSUE1304_VERIFY_LEGACY_FAILURE=1`. This preserves the original diff --git a/test/e2e-cli/ci-tasks.json b/test/e2e-cli/ci-tasks.json index 8b19b041..ab2ddc32 100644 --- a/test/e2e-cli/ci-tasks.json +++ b/test/e2e-cli/ci-tasks.json @@ -15,5 +15,6 @@ "test:e2e-matrix:couchdb-enc1", "test:e2e-matrix:minio-enc0", "test:e2e-matrix:minio-enc1", - "test:journal-chunk-recovery" + "test:journal-chunk-recovery", + "test:fetch-database-continuity" ] diff --git a/test/e2e-cli/helpers/docker.ts b/test/e2e-cli/helpers/docker.ts index 018dc226..961ba957 100644 --- a/test/e2e-cli/helpers/docker.ts +++ b/test/e2e-cli/helpers/docker.ts @@ -1,3 +1,4 @@ +import { randomUUID } from "node:crypto"; import { writeSync } from "node:fs"; import { spawnProcess } from "./process.ts"; /** @@ -577,6 +578,59 @@ export async function startMinio( await waitForMinioBucket(minioEndpoint, accessKey, secretKey, bucket); } +export type IsolatedMinioFixture = { + endpoint: string; + accessKey: string; + secretKey: string; + stop: () => Promise; +}; + +/** Start an S3 fixture owned by this caller without touching the shared test container. */ +export async function startIsolatedMinio(accessKey: string, secretKey: string): Promise { + const container = `livesync-cli-continuity-${randomUUID()}`; + console.log(`[INFO] starting isolated S3 test container: ${container}`); + let tracked = false; + const stop = async () => { + await stopAndRemoveContainer(container); + if (tracked) untrackContainer(container); + }; + + try { + await dockerOrFail( + "run", + "-d", + "--name", + container, + "-p", + "127.0.0.1::9000", + "-e", + `RUSTFS_ACCESS_KEY=${accessKey}`, + "-e", + `RUSTFS_SECRET_KEY=${secretKey}`, + "-e", + "RUSTFS_CONSOLE_ENABLE=true", + "-e", + "RUSTFS_CORS_ALLOWED_ORIGINS=*", + S3_IMAGE, + "/data" + ); + trackContainer(container); + tracked = true; + + const mapping = await dockerOrFail("port", container, "9000/tcp"); + const port = Number(mapping.trim().match(/:(\d+)$/)?.[1]); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error(`Could not determine the isolated S3 fixture port from: ${mapping.trim()}`); + } + const endpoint = `http://127.0.0.1:${port}`; + await fetchRetry(endpoint, { method: "GET" }, 30, 1000, [403, 404]); + return { endpoint, accessKey, secretKey, stop }; + } catch (error) { + await stop(); + throw error; + } +} + // --------------------------------------------------------------------------- // P2P relay (strfry) // --------------------------------------------------------------------------- diff --git a/test/e2e-cli/tasks.json b/test/e2e-cli/tasks.json index 1df64c08..ee62a00e 100644 --- a/test/e2e-cli/tasks.json +++ b/test/e2e-cli/tasks.json @@ -1,7 +1,8 @@ { "test:helpers": { "test": [ - "helpers/process.test.ts" + "helpers/process.test.ts", + "test-ci-task-contract.ts" ] }, "test": { diff --git a/test/e2e-cli/test-ci-task-contract.ts b/test/e2e-cli/test-ci-task-contract.ts new file mode 100644 index 00000000..22a94565 --- /dev/null +++ b/test/e2e-cli/test-ci-task-contract.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; +import { test } from "node:test"; + +test("fetch database continuity is exercised by standard CLI CI", async () => { + const ciTasks = JSON.parse(await readFile(new URL("./ci-tasks.json", import.meta.url), "utf8")) as string[]; + const tasks = JSON.parse(await readFile(new URL("./tasks.json", import.meta.url), "utf8")) as Record< + string, + { test?: string[] } + >; + const workflow = await readFile(new URL("../../.github/workflows/cli-node-tests.yml", import.meta.url), "utf8"); + + assert(ciTasks.includes("test:helpers"), "the standard CI suite must run the task registration contract"); + assert(tasks["test:helpers"]?.test?.includes("test-ci-task-contract.ts")); + assert(ciTasks.includes("test:fetch-database-continuity"), "the continuity task must be in the standard CI suite"); + assert.deepEqual(tasks["test:fetch-database-continuity"]?.test, ["test-fetch-database-continuity.ts"]); + assert.match(workflow, /test\/e2e-cli\/ci-tasks\.json/, "the automatic CI matrix must read the authoritative task list"); +}); diff --git a/test/e2e-cli/test-fetch-database-continuity.ts b/test/e2e-cli/test-fetch-database-continuity.ts index bf66c0aa..8f38548f 100644 --- a/test/e2e-cli/test-fetch-database-continuity.ts +++ b/test/e2e-cli/test-fetch-database-continuity.ts @@ -1,9 +1,12 @@ import assert from "node:assert/strict"; -import { createHash } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { test } from "node:test"; +import { after, before, test } from "node:test"; +import { CreateBucketCommand, S3Client } from "@aws-sdk/client-s3"; import { CLI_DIR, CLI_DIST } from "./helpers/cli.ts"; +import { startIsolatedMinio, type IsolatedMinioFixture } from "./helpers/docker.ts"; import { applyRemoteSyncSettings, generateSetupUriFromSettings, initSettingsFile } from "./helpers/settings.ts"; import { TempDir } from "./helpers/temp.ts"; import { spawnProcess, type RunningProcess } from "./helpers/process.ts"; @@ -24,20 +27,89 @@ const RESOLUTION_MARKER = "Resolving [same]: Conflicted revision has been delete const INITIAL_REPLICATION_COMPLETE = "[Daemon] Initial replication complete"; const INITIAL_REPLICATION_FAILED = "[Daemon] Initial replication failed"; const VERIFY_LEGACY_FAILURE = process.env["LIVESYNC_ISSUE1304_VERIFY_LEGACY_FAILURE"] === "1"; +const EXPLICIT_FIXTURE_VARIABLES = [ + "LIVESYNC_ISSUE1304_MINIO_ENDPOINT", + "LIVESYNC_ISSUE1304_MINIO_ACCESS_KEY", + "LIVESYNC_ISSUE1304_MINIO_SECRET_KEY", + "LIVESYNC_ISSUE1304_MINIO_BUCKET", +]; +const EXPLICIT_FIXTURE = EXPLICIT_FIXTURE_VARIABLES.some((name) => process.env[name]?.trim()); -function requiredEnv(name: string): string { - const value = process.env[name]?.trim(); - if (!value) throw new Error(`Required environment variable is missing: ${name}`); - return value; +if (EXPLICIT_FIXTURE && EXPLICIT_FIXTURE_VARIABLES.some((name) => !process.env[name]?.trim())) { + throw new Error(`External fixture mode requires all of: ${EXPLICIT_FIXTURE_VARIABLES.join(", ")}`); } -function remoteSettings(bucketOverride?: string): RemoteSettings { +let managedFixture: IsolatedMinioFixture | undefined; +if (!EXPLICIT_FIXTURE) { + before(async () => { + managedFixture = await startIsolatedMinio( + process.env["accessKey"]?.trim() ?? "minioadmin", + process.env["secretKey"]?.trim() ?? "minioadmin" + ); + }); + after(async () => { + await managedFixture?.stop(); + }); +} + +function requiredEnv(...names: string[]): string { + for (const name of names) { + const value = process.env[name]?.trim(); + if (value) return value; + } + throw new Error(`Required environment variable is missing: ${names.join(" or ")}`); +} + +function evidenceDirectory(): string { + return resolve( + process.env["LIVESYNC_ISSUE1304_EVIDENCE_DIR"]?.trim() || join(tmpdir(), "livesync-cli-issue1304-evidence") + ); +} + +function remoteSettings(): RemoteSettings { return { endpoint: requiredEnv("LIVESYNC_ISSUE1304_MINIO_ENDPOINT").replace(/\/$/, ""), accessKey: requiredEnv("LIVESYNC_ISSUE1304_MINIO_ACCESS_KEY"), secretKey: requiredEnv("LIVESYNC_ISSUE1304_MINIO_SECRET_KEY"), - bucket: bucketOverride ?? requiredEnv("LIVESYNC_ISSUE1304_MINIO_BUCKET"), - evidenceDir: resolve(requiredEnv("LIVESYNC_ISSUE1304_EVIDENCE_DIR")), + bucket: requiredEnv("LIVESYNC_ISSUE1304_MINIO_BUCKET"), + evidenceDir: evidenceDirectory(), + }; +} + +async function createManagedBucket(remote: Pick, mode: ScenarioMode): Promise { + const shortMode = mode === "reproduction" ? "repro" : "control"; + const bucket = `livesync-ci-1304-${shortMode}-${randomUUID().replaceAll("-", "")}`; + const client = new S3Client({ + endpoint: remote.endpoint, + region: "us-east-1", + forcePathStyle: true, + credentials: { accessKeyId: remote.accessKey, secretAccessKey: remote.secretKey }, + }); + try { + await client.send(new CreateBucketCommand({ Bucket: bucket })); + } finally { + client.destroy(); + } + return bucket; +} + +async function scenarioRemoteSettings(mode: ScenarioMode): Promise { + if (EXPLICIT_FIXTURE) { + const remote = remoteSettings(); + if (mode === "write-settings-control") remote.bucket = requiredEnv("LIVESYNC_ISSUE1304_POSITIVE_CONTROL_BUCKET"); + return remote; + } + + if (!managedFixture) throw new Error("The managed S3 fixture was not started"); + const remote = { + endpoint: managedFixture.endpoint, + accessKey: managedFixture.accessKey, + secretKey: managedFixture.secretKey, + }; + return { + ...remote, + bucket: await createManagedBucket(remote, mode), + evidenceDir: evidenceDirectory(), }; } @@ -265,8 +337,7 @@ async function settingsSummary(settingsPath: string): Promise { - const remote = remoteSettings(bucket); +async function runScenario(mode: ScenarioMode, remote: RemoteSettings): Promise { const evidenceRoot = remote.evidenceDir; const evidenceName = `${mode}-${Date.now()}-${process.pid}`; const evidenceDir = join(evidenceRoot, evidenceName); @@ -556,13 +627,11 @@ async function runScenario(mode: ScenarioMode, bucket: string): Promise { } test("CLI fetch: files remain after same-content duplicate root resolution", async () => { - const remote = remoteSettings(); - await runScenario("reproduction", remote.bucket); + await runScenario("reproduction", await scenarioRemoteSettings("reproduction")); }); -if (process.env["LIVESYNC_ISSUE1304_POSITIVE_CONTROL"] === "1") { +if (!EXPLICIT_FIXTURE || process.env["LIVESYNC_ISSUE1304_POSITIVE_CONTROL"] === "1") { test("CLI fetch: --write-settings keeps the selected database across daemon startup", async () => { - const controlBucket = requiredEnv("LIVESYNC_ISSUE1304_POSITIVE_CONTROL_BUCKET"); - await runScenario("write-settings-control", controlBucket); + await runScenario("write-settings-control", await scenarioRemoteSettings("write-settings-control")); }); }