Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
6 changes: 6 additions & 0 deletions src/settings/settingDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)',
Expand Down
18 changes: 12 additions & 6 deletions src/sync/SyncEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -308,7 +313,7 @@ export class SyncEngine {
return isCellularBlocked(this.opts.settings.syncOnWifiOnly, Platform.isIosApp, conn?.type);
}

async syncManual(opts: { manual?: boolean } = {}): Promise<void> {
async syncManual(opts: { manual?: boolean; silent?: boolean } = {}): Promise<void> {
// 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})`);
Expand All @@ -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 {
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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,
);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). */
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion src/ui/NullStatusBar.ts
Original file line number Diff line number Diff line change
@@ -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 */ }
Expand Down
3 changes: 2 additions & 1 deletion tests/a-no-nextcloud/settings/settingDefinitions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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> = {}): SettingDefinitionsHost {
return {
Expand Down
3 changes: 1 addition & 2 deletions tests/a-no-nextcloud/sync/initialScan.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down
126 changes: 126 additions & 0 deletions tests/a-no-nextcloud/sync/silentSync.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {};
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<string, string> = {};
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<string | null> => 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();
});
});