diff --git a/src/main.ts b/src/main.ts index 7f50fd8f..076e1783 100644 --- a/src/main.ts +++ b/src/main.ts @@ -545,7 +545,9 @@ export default class ObsidianNextcloudsync extends Plugin { // 0 = no startup sync; 1-10 = seconds to wait. if (this.settings.startupSyncDelaySeconds > 0) { const delayMs = this.settings.startupSyncDelaySeconds * 1000; - window.setTimeout(() => { void this.syncEngine?.syncManual(); }, delayMs); + window.setTimeout(() => { + void this.syncEngine?.syncManual({ silent: !this.settings.startupSyncNotificationsEnabled }); + }, delayMs); } } diff --git a/src/settings/settingDefinitions.ts b/src/settings/settingDefinitions.ts index 3b0708cd..fb45d6b9 100644 --- a/src/settings/settingDefinitions.ts +++ b/src/settings/settingDefinitions.ts @@ -249,6 +249,12 @@ function syncGroup(host: SettingDefinitionsHost): SettingDefinitionGroup { () => s.startupSyncDelaySeconds, (v) => { s.startupSyncDelaySeconds = v; }, ), + { + name: 'Startup sync notifications', + desc: 'Show a "Syncing…" toast and a completion toast when the startup sync runs. Mobile only — desktop has no toast, so this is inert there.', + aliases: ['notification', 'toast', 'notice', 'startup sync', 'quiet'], + control: { type: 'toggle', key: 'startupSyncNotificationsEnabled' }, + }, slider( host, 'Sync interval (minutes)', diff --git a/src/sync/SyncEngine.ts b/src/sync/SyncEngine.ts index a270324f..7c326764 100644 --- a/src/sync/SyncEngine.ts +++ b/src/sync/SyncEngine.ts @@ -44,6 +44,7 @@ import { WatchOperations } from './watch/WatchOperations'; import { MirrorService } from './mirror/MirrorService'; import { SyncHistoryStore } from '../data/SyncHistoryStore'; import { IStatusBar } from '../ui/StatusBarItem'; +import { NullStatusBar } from '../ui/NullStatusBar'; import { WebDAVFactory } from '../network/WebDAVFactory'; import { IWebDAVClient } from '../network/IWebDAVClient'; import { RenameTracker } from './RenameTracker'; @@ -124,6 +125,9 @@ export class SyncEngine { private readonly mirror: MirrorService; private syncProgress = { processed: 0, total: 0 }; + // Status surface for the sync currently running; swapped to a no-op for a silent sync (startup sync with + // notifications off). Watch mode and the mirror keep their own injected statusBar, so they are unaffected. + private activeStatusBar: IStatusBar; // Monotonic; read as a delta around one watch operation to learn whether it touched a conflict. // Summary counters cannot say: conflicts settled by a deterministic strategy count as plain uploads/downloads. private conflictEncounters = 0; @@ -138,6 +142,7 @@ export class SyncEngine { private readonly remoteListing: RemoteListingSource; constructor(private readonly opts: SyncEngineOptions) { + this.activeStatusBar = opts.statusBar; this.configSync = new ConfigSyncResolver({ configDir: opts.configDir, settings: opts.settings, @@ -308,7 +313,7 @@ export class SyncEngine { return isCellularBlocked(this.opts.settings.syncOnWifiOnly, Platform.isIosApp, conn?.type); } - async syncManual(opts: { manual?: boolean } = {}): Promise { + async syncManual(opts: { manual?: boolean; silent?: boolean } = {}): Promise { // Mobile has no status bar; NoticeStatusBar surfaces state there. The early returns below need explicit // notices because they exit before any toast exists. void this.opts.logger?.log(`sync: start (manual=${opts.manual === true})`); @@ -325,6 +330,7 @@ export class SyncEngine { // Set the balking flag synchronously (before any await) so a concurrent call still balks. this.running = true; this.cancelled = false; + this.activeStatusBar = opts.silent === true ? new NullStatusBar() : this.opts.statusBar; const run = this.runSyncSession(); this.currentRun = run; try { @@ -352,7 +358,7 @@ export class SyncEngine { void this.opts.logger?.log('sync: connecting (ensureClient)'); await this.ensureClient(); this.syncProgress = { processed: 0, total: 0 }; - this.opts.statusBar.setStatus('syncing'); + this.activeStatusBar.setStatus('syncing'); const isFirstSync = !this.opts.stateDB.getSyncToken() && this.opts.stateDB.getAllFiles().length === 0; @@ -389,7 +395,7 @@ export class SyncEngine { void this.opts.logger?.log(`sync: post-sync save failed — ${(persistErr as Error).message}`, 'error'); } const conflictCount = this.opts.stateDB.countConflicted(); - this.opts.statusBar.setSyncComplete( + this.activeStatusBar.setSyncComplete( summary.uploadedCount, summary.downloadedCount, conflictCount, summary.errorCount, ); @@ -747,7 +753,7 @@ export class SyncEngine { const eligible = remoteFiles.filter(f => !this.isSystemExcluded(f.path)); this.syncProgress = { processed: 0, total: eligible.length }; - if (eligible.length > 0) this.opts.statusBar.setProgress(0, eligible.length); + if (eligible.length > 0) this.activeStatusBar.setProgress(0, eligible.length); // Bounded parallel; uploads to the same directory are serialized to avoid 423s. await this.runFileBatch( eligible, @@ -1206,7 +1212,7 @@ export class SyncEngine { const remoteMap = new Map(remoteFiles.map(f => [f.path, f])); const actionFiles = plan.uploads.length + plan.downloads.length + plan.conflicts.length; this.syncProgress = { processed: 0, total: actionFiles }; - if (actionFiles > 0) this.opts.statusBar.setProgress(0, actionFiles); + if (actionFiles > 0) this.activeStatusBar.setProgress(0, actionFiles); await this.runFileBatch( plan.uploads, @@ -1278,7 +1284,7 @@ export class SyncEngine { private tickProgress(): void { this.syncProgress.processed = Math.min(this.syncProgress.processed + 1, this.syncProgress.total); if (this.syncProgress.total > 0) { - this.opts.statusBar.setProgress(this.syncProgress.processed, this.syncProgress.total); + this.activeStatusBar.setProgress(this.syncProgress.processed, this.syncProgress.total); } } diff --git a/src/types.ts b/src/types.ts index 6f1b3f4e..b2325847 100644 --- a/src/types.ts +++ b/src/types.ts @@ -71,6 +71,8 @@ export interface DavSyncSettings { watchOnChangeEnabled: boolean; /** Startup sync delay in seconds, 0-10; 0 = no startup sync. */ startupSyncDelaySeconds: number; + /** Show the syncing/completion toast during the startup sync on mobile. Desktop has no toast, so it is inert there. */ + startupSyncNotificationsEnabled: boolean; /** Number of concurrent WebDAV requests. Derived from device RAM on first run if not persisted. */ networkConcurrency: number; /** Sync only on Wi-Fi; ignored on iOS (no network-type API). */ @@ -120,6 +122,7 @@ export const DEFAULT_SETTINGS: DavSyncSettings = { maxFileSizeMB: 0, // desktop default; mobile gets a cap in loadSettings() watchOnChangeEnabled: true, startupSyncDelaySeconds: 1, + startupSyncNotificationsEnabled: true, networkConcurrency: 16, // overridden on first run by autoNetworkConcurrency() // Mobile's first run flips this ON (metered data). syncOnWifiOnly: false, diff --git a/src/ui/NullStatusBar.ts b/src/ui/NullStatusBar.ts index 4fdd1a06..fd2a066a 100644 --- a/src/ui/NullStatusBar.ts +++ b/src/ui/NullStatusBar.ts @@ -1,6 +1,7 @@ import { IStatusBar } from './StatusBarItem'; -// Injected on mobile (no status bar, no progress shown) so call sites need no platform branching. +// A status surface that shows nothing: used for a silent sync (startup sync with notifications disabled), +// so the sync still runs but produces no toast. Stateless, so one instance is reusable. export class NullStatusBar implements IStatusBar { setStatus(): void { /* no-op */ } setProgress(): void { /* no-op */ } diff --git a/tests/a-no-nextcloud/settings/settingDefinitions.test.ts b/tests/a-no-nextcloud/settings/settingDefinitions.test.ts index 26f15c14..dc296feb 100644 --- a/tests/a-no-nextcloud/settings/settingDefinitions.test.ts +++ b/tests/a-no-nextcloud/settings/settingDefinitions.test.ts @@ -40,6 +40,7 @@ const BASELINE: { heading: string | null; rows: string[] }[] = [ heading: 'Sync', rows: [ 'Startup sync delay (seconds)', + 'Startup sync notifications', 'Sync interval (minutes)', 'Network timeout (seconds)', 'Network concurrency', @@ -65,7 +66,7 @@ const BASELINE: { heading: string | null; rows: string[] }[] = [ { heading: 'Maintenance', rows: ['Reset vault index', 'Mirror from remote', 'Last session summary'] }, ]; -const STATIC_ROW_COUNT = BASELINE.reduce((n, s) => n + s.rows.length, 0); // 27 +const STATIC_ROW_COUNT = BASELINE.reduce((n, s) => n + s.rows.length, 0); // 28 function makeHost(over: Partial = {}): SettingDefinitionsHost { return { diff --git a/tests/a-no-nextcloud/sync/initialScan.test.ts b/tests/a-no-nextcloud/sync/initialScan.test.ts index 3d2e8ab0..f51e5954 100644 --- a/tests/a-no-nextcloud/sync/initialScan.test.ts +++ b/tests/a-no-nextcloud/sync/initialScan.test.ts @@ -45,7 +45,7 @@ const SETTINGS = { function makeEngine(localAdapter: unknown) { const opts = { app: {}, settings: SETTINGS, localAdapter, - stateDB: {}, statusBar: {}, webdavFactory: {}, + stateDB: {}, statusBar: { setProgress: jest.fn() }, webdavFactory: {}, pluginDir: '.obsidian/plugins/x', configDir: '.obsidian', }; return new SyncEngine(opts as never); @@ -208,7 +208,6 @@ describe('SyncEngine.executePlan — reuses the scan (P0-C / FR-010, no double h (engine as unknown as { client: unknown }).client = {}; (engine as unknown as { uploadStrategy: unknown }).uploadStrategy = { upload: jest.fn(async () => 'skipped') }; (engine as unknown as { opts: { stateDB: unknown } }).opts.stateDB = { setFile: jest.fn() }; - (engine as unknown as { opts: { statusBar: unknown } }).opts.statusBar = { setProgress: jest.fn() }; const localFiles: LocalFiles = new Map([['a.md', { size: 0, mtime: 1 }]]); await (engine as unknown as { diff --git a/tests/a-no-nextcloud/sync/silentSync.test.ts b/tests/a-no-nextcloud/sync/silentSync.test.ts new file mode 100644 index 00000000..7fe2b104 --- /dev/null +++ b/tests/a-no-nextcloud/sync/silentSync.test.ts @@ -0,0 +1,126 @@ +// A silent sync (startup sync with notifications disabled) still runs but drives no status surface: +// the engine swaps its active status bar for a no-op, so the mobile toast never appears. This pins that +// wiring at the real SyncEngine level (not a mock of runSyncSession) so a regression that reintroduces +// statusBar calls for the startup path is caught. +import { DataAdapter } from 'obsidian'; +import { SyncEngine } from '../../../src/sync/SyncEngine'; +import { StateDB } from '../../../src/data/StateDB'; +import { DEFAULT_SETTINGS } from '../../../src/types'; +import { TFile, TFolder } from '../support/obsidian'; + +const enc = new TextEncoder(); +const PLUGIN_DIR = '.obsidian/plugins/nextcloud-sync'; + +function makeStateAdapter(): DataAdapter { + const store: Record = {}; + return { + read: jest.fn(async (p: string) => store[p] ?? ''), + write: jest.fn(async (p: string, d: string) => { store[p] = d; }), + exists: jest.fn(async (p: string) => p in store), + remove: jest.fn(async (p: string) => { delete store[p]; }), + rename: jest.fn(async (f: string, t: string) => { store[t] = store[f]; delete store[f]; }), + stat: jest.fn(), list: jest.fn(), readBinary: jest.fn(), writeBinary: jest.fn(), + } as unknown as DataAdapter; +} + +async function buildEngine() { + const stateDB = new StateDB(makeStateAdapter(), PLUGIN_DIR, 'dev1'); + await stateDB.load(); + + const vault: Record = {}; + const localAdapter = { + files: vault, + listVaultFiles: jest.fn(() => [] as { path: string; size: number; mtime: number }[]), + list: jest.fn(async () => ({ files: [], folders: [] })), + stat: jest.fn(async () => null), + exists: jest.fn(async () => false), + read: jest.fn(async (p: string) => vault[p] ?? ''), + readBinary: jest.fn(async (p: string) => enc.encode(vault[p] ?? '').buffer as ArrayBuffer), + atomicWrite: jest.fn(async (p: string, d: string) => { vault[p] = d; }), + atomicWriteBinary: jest.fn(async (p: string, d: ArrayBuffer) => { vault[p] = new TextDecoder().decode(d); }), + writeBinary: jest.fn(async (p: string, d: ArrayBuffer) => { vault[p] = new TextDecoder().decode(d); }), + setMtime: jest.fn(), + ignore: jest.fn(), + remove: jest.fn(async (p: string) => { delete vault[p]; }), + }; + + const client = { + getRootEtag: jest.fn(async () => null as string | null), + getFiles: jest.fn(async () => []), + getSyncToken: jest.fn(async (): Promise => null), + remoteExists: jest.fn(async () => false), + statFile: jest.fn(async () => null), + uploadFile: jest.fn(async () => undefined), + deleteFile: jest.fn(async () => undefined), + getDirectories: jest.fn(async () => []), + createDirectory: jest.fn(async () => undefined), + deleteCollection: jest.fn(async () => undefined), + isRemoteDirEmpty: jest.fn(async () => true), + recalcChecksum: jest.fn(async () => null), + downloadFile: jest.fn(async () => enc.encode('x').buffer as ArrayBuffer), + }; + const createClient = jest.fn(async () => ({ client, features: { isNextcloud: true } })); + + const app = { + vault: { + adapter: { + exists: jest.fn(async (p: string) => p in vault), + remove: jest.fn(async (p: string) => { delete vault[p]; }), + mkdir: jest.fn(async () => undefined), + }, + getAbstractFileByPath: (p: string) => (p in vault ? new TFile(p) : null), + getAllFolders: () => [] as TFolder[], + }, + fileManager: { + trashFile: jest.fn(async () => undefined), + }, + }; + + const logger = { log: jest.fn(async () => undefined) }; + const statusBar = { + setStatus: jest.fn(), + setProgress: jest.fn(), + setConflictCount: jest.fn(), + setErrorCount: jest.fn(), + setSyncComplete: jest.fn(), + }; + + const engine = new SyncEngine({ + app, settings: { ...DEFAULT_SETTINGS, syncOnWifiOnly: false }, + localAdapter, stateDB, statusBar, webdavFactory: { createClient }, logger, + pluginDir: PLUGIN_DIR, configDir: '.obsidian', + } as never); + + return { engine, statusBar }; +} + +beforeEach(() => { + (globalThis as { navigator?: unknown }).navigator ??= {}; +}); + +describe('silent sync (startup notifications off)', () => { + it('a normal sync drives the status surface', async () => { + const { engine, statusBar } = await buildEngine(); + await engine.syncManual({ manual: true }); + expect(statusBar.setStatus).toHaveBeenCalledWith('syncing'); + expect(statusBar.setSyncComplete).toHaveBeenCalled(); + }); + + it('a silent sync runs without touching the status surface', async () => { + const { engine, statusBar } = await buildEngine(); + await engine.syncManual({ manual: true, silent: true }); + expect(statusBar.setStatus).not.toHaveBeenCalled(); + expect(statusBar.setProgress).not.toHaveBeenCalled(); + expect(statusBar.setSyncComplete).not.toHaveBeenCalled(); + }); + + it('a silent sync does not leak into the next non-silent sync', async () => { + const { engine, statusBar } = await buildEngine(); + await engine.syncManual({ manual: true, silent: true }); + statusBar.setStatus.mockClear(); + statusBar.setSyncComplete.mockClear(); + await engine.syncManual({ manual: true }); + expect(statusBar.setStatus).toHaveBeenCalledWith('syncing'); + expect(statusBar.setSyncComplete).toHaveBeenCalled(); + }); +});