mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-16 20:11:08 +00:00
* feat(plugins): add sync providers and encrypted sidecar sync
Implement PR 8 of the plugin platform (#2269): namespaced sync Providers
with provider.sync, encrypted-object storage operations, WebDAV through the
shared storage surface, dynamic cloud provider IDs, and non-cascade sidecars
for sync:true plugin settings plus account/CRDT baselines.
Related to #2269
* fix(plugins): wire sync providers and sidecars into production paths
Close PR 8 integration gaps: dynamic plugin provider registry and
getConnectedAdapter createPluginStorage, WebDAV through EncryptedObjectStorage,
cloud payload collect/apply for pluginSidecars, and IPC/preload bridges.
Related to #2269
* fix(plugins): preserve WebDAV auth reuse and resourceId through EOS wrap
encryptedObjectStorageAsCloudAdapter now reports initiallyAuthenticated when
config exists (matching raw WebDAVAdapter) so getConnectedAdapter reuses the
cached instance, and preserves/refreshes resourceId from the backing adapter
instead of always forcing the default object key.
Related to #2269
* fix(plugins): address Codex PR 8 review findings
Carry pluginSidecars through merge/convergent uploads, lazy-connect before
object I/O with revision-aware writes, fail closed on sidecar collect errors,
expose connectPluginProvider, preserve remote timestamps, and drop deleted
installed-plugin settings from collection.
Related to #2269
* fix(plugins): close remaining Codex P1/P2 sync issues
Lazy stream cancel for inline sync reads, must-not-exist conditional writes,
three-way sidecar merge for local resets, validated apply path for settings,
and merge remote sidecars into convergent uploads.
Related to #2269
* fix(plugins): harden sidecar collect/apply and write verification
Preserve last-known sidecars when the host is offline, apply remote
deletions for installed plugins, force convergent upload on sidecar
divergence, verify plugin object writes, and pick plugin providers in
auto-sync startup checks.
Related to #2269
* fix(plugins): close remaining Codex sidecar/sync path gaps
Include sidecars in auto-sync payload and hash, keep explicit empty bundles,
fail apply when host is offline, require getCapabilities, and carry merged
sidecars into convergent local apply/upload decisions.
Related to #2269
* fix(plugins): close Codex P1 sidecar collect/apply/merge gaps
Treat null host responses as unavailable, persist collected settings into
the non-cascade table, retain decoded convergent payloads, use three-way
sidecar merge for deletions, and fail apply only on operational errors.
Also treat non-empty plugin sidecars as meaningful sync data and re-run
auto-sync when plugin contributions change.
Related to #2269
* fix(plugins): close remaining Codex P1 sidecar and provider gaps
Replay offline-cached sidecars before collect, keep explicit empty
sidecar fields after three-way merge, thread sidecars through convergent
conflict/downgrade materialization, keep gated-off plugin providers from
joining sync as connected, and rebind plugin EOS sessions after runtime
replacement.
Related to #2269
* fix(plugins): separate pending remote sidecars from last-known cache
Replay only host-offline remote applies into the DB, keep last-known as
upload fallback, use contribution reset for deleted settings, probe real
plugin host readiness, rebind storage events for plugin providers, clear
plugin bases on reset, and swallow disconnect rejections.
Related to #2269
* fix(plugins): hydrate retained sidecars and gate missing providers
Materialize installed-plugin settings from retained sidecars before
collect pruning, clear sidecars on setting reset, fail closed when
pending remote replay fails, and only restore plugin providers that are
contribution-available. Also initialize dynamic provider counters on
connect.
Related to #2269
* fix(plugins): surface plugin sync providers and preserve conflict sidecars
Collect live sidecars before convergent conflict apply/upload, include
dynamic providers in status and disconnect paths, and list plugin sync
providers in Cloud Sync settings for connect/disconnect.
Related to #2269
* fix(plugins): per-provider sidecar baselines and safer collect/UI
Merge convergent sidecars against each provider's own baseline, keep
retained settings in sidecars without unvalidated plugin_settings writes,
guard isConnectDisabled for never-connected plugins, and fall back plugin
provider labels/icons in the status popup.
Related to #2269
* fix(plugins): correct plugin provider discovery and sidecar reverify
Read nested contribution metadata for sync provider cards, gate empty-config
connects, enforce single-provider disconnect for plugins, and re-verify after
sidecar-only convergent uploads so baselines track the post-write payload.
Related to #2269
* fix(plugins): refresh sync provider availability from live contributions
Replace the contribution-available provider ID set when plugins change so
disabled or uninstalled sync providers leave the auto-sync ready set and
drop to disconnected with config retained.
Related to #2269
* fix(plugins): preserve sidecars in backups, pending queue, and migration
Attach last-known plugin sidecars to protective local vault backups, fail
operationally when pending/last-known storage writes are rejected, carry
sidecars through convergent migration publish, and reject trailing garbage
on encrypted object parse.
Related to #2269
* fix(plugins): abort conflict collect failures and merge migration sidecars
Rethrow operational sidecar collection errors during convergent conflict
resolution, LWW-union all local/provider sidecars during convergent
migration, re-collect last-known after apply, and prefer live host collect
for protective local vault backups.
Related to #2269
* fix(plugins): restore pluginBridge tests, fix import path, union downgrade sidecars
Correct SettingsSyncTab dynamic import path so production builds resolve,
add ipcMain.on to the plugin bridge test double, union all provider
sidecars on convergent downgrade, keep empty last-known resets, and skip
force-delete when contribution reset validation rejects.
Related to #2269
* fix(plugins): abort backup collect failures and honor empty remote wipes
Only fall back to last-known sidecars when the host is unavailable during
protective backups, treat explicit empty remote sidecar bundles as
authoritative wipes, remove lint-blocking anys from harness tests, and
use a stable equal-timestamp sidecar tie-break.
Related to #2269
* fix(plugins): include sidecars in equality, preserve merge base on reconnect
Compare pluginSidecars in cloudSyncPayloadsEqual for migration freshness,
clear plugin merge state only when account/resource changes on reconnect,
cancel accepted sync read streams on failure, and stop re-connecting the
plugin EOS adapter on every I/O.
Related to #2269
* fix(plugins): drop cached adapters on contribution refresh
Invalidate plugin sync adapters when live contributions change so a
restarted runtime gets a fresh connect, take offline any non-disconnected
missing providers, and latch version-change backups only after cancellation
checks pass.
Related to #2269
* fix(plugins): preserve omitted sidecars and hydrate on plugin enable
Treat missing pluginSidecars as legacy/unsupported in three-way merge
(only explicit empty is a wipe), hydrate retained settings when a plugin
enables, and re-enable retained provider configs when contributions return.
Related to #2269
* fix(plugins): keep newer retained sidecars over older stored settings
When collection merges existing sidecars with plugin_settings rows, prefer
the newer updatedAt so a schema-rejected remote value retained only in
the sidecar table is not overwritten by a stale local setting.
Related to #2269
* fix(plugins): seal plugin provider config and clear base on config change
Encrypt opaque plugin provider configuration before persistence, clear
merge state when reconnect configuration changes, and stream sync objects
below a base64-safe inline threshold so control-plane JSON stays in budget.
Related to #2269
* fix(plugins): seal plugin configs by provider id and hydrate before start
Encrypt plugin provider configuration only for non-builtin provider IDs
so field-name collisions cannot skip sealing, hydrate retained sidecars
before plugin enable starts the runtime, and stop tearing down live
adapters on no-op availability refreshes.
Related to #2269
* fix(plugins): seal scalar configs, safe inline reads, stable config fingerprint
Encrypt any non-builtin plugin configuration JSON shape, enforce the
base64-safe inline read cutoff, and compare reconnect configurations with
order-independent fingerprints so merge bases are not cleared spuriously.
Related to #2269
* fix(plugins): thread sync credentials and harden availability checks
Pass SyncConnectPayload.credential through the object-storage and IPC host
path, treat only null/undefined config as missing, and avoid wiping the
plugin provider availability catalog on transient discovery failures.
Related to #2269
* fix(plugins): unblock schema-required sync connect and scalar configs
Add a JSON config dialog for plugin sync providers that declare a
required configurationSchema, reuse retained configs on reconnect, and
treat falsy scalar configs as present in readiness and adapter lookup.
Related to #2269
* fix(plugins): rebind sync adapters on contribution refresh
Drop cached plugin sync adapters when live contributions still include
the provider so replaced runtimes get a fresh connect, and seal falsy
scalar plugin configs with nullish presence checks end-to-end.
Related to #2269
* fix(plugins): apply sidecars under current declared setting scopes
When a plugin update changes a syncable setting scope, write under the
live declaration and drop the obsolete scope row so collection does not
republish duplicates.
Related to #2269
* fix(plugins): seal config envelopes and stabilize provider counters
Use an unambiguous host-owned sealed-config envelope, initialize
dynamic-provider sequence counters before cross-window decrypt, keep
three-way sidecar deletions during convergent migration, and create the
sidecar table for existing schema-1 plugin databases.
Related to #2269
* fix(plugins): avoid mid-sync adapter drops and sidecar resurrection
Keep plugin adapters across setting-only contribution refreshes and
rebind sessions on ensureConnected; stop preserving local-only missing
plugin sidecars when remote already mentions the plugin; compare configs
with nullish semantics across windows; swallow quick-connect failures
after toasting.
Related to #2269
* fix(plugins): restore remoteKeys for installed sidecar resets
Reintroduce the remote key set used when dropping installed-plugin
settings the remote no longer carries so applyFromSync cannot throw
after replacing the sidecar table.
Related to #2269
* fix(plugins): honor conflict policy and re-key scoped sidecars
Pass preferCloud/preferLocal into three-way sidecar merge, use
per-provider baselines on convergent downgrade so local resets are not
resurrected, and re-key applied settings under the current declared
scope coordinates.
Related to #2269
* fix(plugins): keep strategy on final sidecar merge and block dual legacy
Pass preferCloud/preferLocal through the final verified sidecar merge,
avoid auto-reactivating a retained plugin while another legacy provider
is already connected, cache plugin adapters only after initializeSync,
and preserve explicit null configuration values.
Related to #2269
* fix(plugins): strip plugin avatars and protect last-known sidecars
Do not load plugin-supplied avatar URLs in the main renderer, and avoid
overwriting last-known sidecars with an unmerged remote bundle when the
post-apply collect fails or is non-authoritative.
Related to #2269
* fix(plugins): strip top-bar plugin avatars and stop always-rebind
Hide plugin avatar URLs in the sync status popover, drop always-on
rebindSession for plugin adapters, and read convergent mode from the
local config module when deciding whether to auto-reactivate providers.
Related to #2269
* fix(plugins): use window.netcatty for sync IPC and allow null configs
Read plugin sync and sidecar APIs from the production preload global,
and treat an explicit config property (including JSON null) as present
for readiness and adapter lookup.
Related to #2269
* fix(plugins): close residual Codex P2 sync edge cases
Three-way merge sidecars during v2 convergent migration so local
resets are not resurrected, preserve explicit null plugin configs on
adapter rebuild, rebind EOS sessions after I/O failure for replaced
runtimes, and accept the public inlineObjectBytes limit on readObject.
Related to #2269
* fix(plugins): keep inline read cutoff under control-plane budget
Restore the base64-safe inline cutoff so advertised-size reads cannot
overflow the 128 KiB provider JSON envelope; providers near the public
inlineObjectBytes limit must stream.
Related to #2269
* fix(plugins): harden sidecar empty-vault, hydrate LWW, and credential seals
Close remaining Codex/review gaps for PR8: keep empty sidecar shells from
bypassing upload guards, skip startup hydrate when local settings are newer,
seal/validate durable plugin credential refs, and cover schema 1→2 migration.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): rebind plugin sync sessions and keep null configs
Address Codex P2 on 8ae52c54: re-issue connect after runtime replacement,
and treat stored config:null as present in the dashboard reconnect path.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): defer empty sidecar last-known until sync succeeds
Keep prior non-empty last-known across an authoritative empty collect so the
empty-vault guard can still recognize a plugin-only reset, then commit the
empty cache after a successful upload.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): avoid restricted localStorage global in sidecar test
Bind the mock to a local binding so eslint no-restricted-globals stays clean.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): commit applied sidecar cache and reset orphan settings
Prefer merged payload sidecars when updating last-known after sync, and clear
syncable plugin_settings that lack sidecar rows on authoritative remote deletes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): reseal marker-shaped plugin configs instead of skipping
Exact __netcatty_plugin_config_v1 collisions no longer bypass encryption; trusted
host envelopes are unwrapped then resealed, and false collisions are sealed whole.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): keep merged sidecars in last-known after apply collect fails
Return applyFromSync entries from IPC and use them when follow-up collect fails,
so preserved missing-plugin rows are not dropped from the offline upload cache.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): delete stale-scope settings at stored coordinates on reset
After resetSetting against the current declared scope, also remove the row at
the sidecar's stored scope so scope migrations cannot republish remote deletes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): close sync-provider credential, stream, and sidecar gaps
Make SecretRef usable end-to-end via lease-bound network.request, keep
renderer/main transfers abortable and bounded, and stop sidecar
last-known/pending from corrupting backups and conflict apply.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): harden single-provider, secret schema, and conditional conflicts
Keep legacy restart from dual-connecting providers, extract writeOnly schema
secrets into OS storage, and surface conditional-write precondition failures
as conflict UI instead of a generic sync error.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): dedupe sync type imports for lint
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: address Codex review on PR #2713
* fix(plugins): wait for sidecar host before version backup latch
Defer the one-shot upgrade snapshot until the plugin sidecar host is ready (or a short grace), and catch getDataHash failures so pending/baseline paths do not reject unhandled.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(plugins): require sidecar grace before version backup
Always wait for contributions/grace tick before the upgrade snapshot, and only latch after a non-cancelled attempt so cleanup cannot suppress retries.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: netcatty-bot <308658023+netcatty-bot@users.noreply.github.com>
840 lines
32 KiB
TypeScript
840 lines
32 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import {
|
|
SYNC_CONSTANTS,
|
|
SYNC_STORAGE_KEYS,
|
|
isProviderReadyForSync,
|
|
} from '../../../domain/sync';
|
|
import packageJson from '../../../package.json';
|
|
import { EncryptionService } from '../EncryptionService';
|
|
import { mergeSyncPayloads } from '../../../domain/syncMerge';
|
|
import {
|
|
SYNC_SNAPSHOT_LIMIT,
|
|
summarizeSyncChanges,
|
|
withSyncReliabilityMeta,
|
|
} from '../../../domain/syncReliability';
|
|
import { detectSuspiciousShrink, type ShrinkFinding } from '../../../domain/syncGuards';
|
|
import { resolveCloudSyncConflictAction, type CloudSyncConflictAction } from '../../../domain/syncStrategy';
|
|
import { assertConvergentSyncWriteCompatible } from '../../../domain/convergentSync';
|
|
import { getConvergentSyncLocalConfig } from '../convergentSyncConfig';
|
|
import { syncAllProvidersConvergentlyImpl } from './convergentSyncRuntimeMethods';
|
|
import type { CloudAdapter } from '../adapters';
|
|
import type {
|
|
CloudProvider,
|
|
ProviderConnection,
|
|
SyncedFile,
|
|
SyncHistoryEntry,
|
|
SyncSnapshotEntry,
|
|
SyncPayload,
|
|
SyncResult,
|
|
} from '../../../domain/sync';
|
|
// CloudProvider used when clearing dynamic plugin-provider bases/anchors.
|
|
import {
|
|
decryptLocalStorageValue,
|
|
encryptLocalStorageValue,
|
|
} from './encryptedLocalStorage';
|
|
|
|
function getSyncSecurityGeneration(manager: any): number | undefined {
|
|
return typeof manager.getSyncSecurityGeneration === 'function'
|
|
? manager.getSyncSecurityGeneration()
|
|
: undefined;
|
|
}
|
|
|
|
function assertSyncSecurityGeneration(manager: any, generation?: number): void {
|
|
if (typeof manager.assertSyncSecurityGeneration === 'function') {
|
|
manager.assertSyncSecurityGeneration(generation);
|
|
}
|
|
}
|
|
|
|
async function downloadRemoteForSyncAllImpl(this: any,
|
|
provider: CloudProvider,
|
|
remoteFile: SyncedFile,
|
|
syncSecurityGeneration?: number,
|
|
): Promise<SyncResult> {
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
const payload = await EncryptionService.decryptPayload(remoteFile, this.masterPassword);
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
this.updateProviderStatus(provider, 'connected');
|
|
|
|
const result: SyncResult = {
|
|
success: true,
|
|
provider,
|
|
action: 'download',
|
|
version: remoteFile.meta.version,
|
|
mergedPayload: payload,
|
|
remoteFile,
|
|
};
|
|
this.emit({ type: 'SYNC_COMPLETED', provider, result });
|
|
return result;
|
|
}
|
|
|
|
const SYNC_HISTORY_STORAGE_KEY = 'netcatty_sync_history_v1';
|
|
const SYNC_SNAPSHOTS_STORAGE_KEY = 'netcatty_sync_snapshots_v1';
|
|
|
|
async function loadRawSyncBase(this: any, provider?: CloudProvider): Promise<SyncPayload | null> {
|
|
const key = this.state.unlockedKey?.derivedKey;
|
|
if (!key || typeof this.loadFromStorage !== 'function') return null;
|
|
const encoded = this.loadFromStorage(this.syncBaseKey(provider));
|
|
if (!encoded || typeof encoded !== 'string') return null;
|
|
return decryptLocalStorageValue<SyncPayload>(encoded, key);
|
|
}
|
|
|
|
async function rememberCurrentSyncBaseSnapshot(this: any, provider?: CloudProvider): Promise<void> {
|
|
if (typeof this.syncSnapshotsKey !== 'function') return;
|
|
const previous = await loadRawSyncBase.call(this, provider);
|
|
if (!previous) return;
|
|
const snapshots = await loadSyncSnapshotsImpl.call(this, provider);
|
|
const entry: SyncSnapshotEntry = {
|
|
id: `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`,
|
|
timestamp: Date.now(),
|
|
...(provider ? { provider } : {}),
|
|
payload: previous,
|
|
};
|
|
await saveSyncSnapshotsImpl.call(this, [entry, ...snapshots].slice(0, SYNC_SNAPSHOT_LIMIT), provider);
|
|
}
|
|
|
|
export async function syncAllProvidersImpl(this: any,
|
|
inputPayload?: SyncPayload,
|
|
opts: {
|
|
overrideShrink?: boolean;
|
|
conflictActionOverride?: CloudSyncConflictAction;
|
|
applyConvergentPayload?: (
|
|
payload: SyncPayload,
|
|
commitReplica: () => Promise<void>,
|
|
) => Promise<void>;
|
|
} = {},
|
|
): Promise<Map<CloudProvider, SyncResult>> {
|
|
const results = new Map<CloudProvider, SyncResult>();
|
|
let payload = inputPayload;
|
|
let wasMerged = false;
|
|
|
|
const convergentConfig = getConvergentSyncLocalConfig();
|
|
if (convergentConfig.initialized && inputPayload) {
|
|
if (convergentConfig.enabled) {
|
|
return syncAllProvidersConvergentlyImpl.call(this, inputPayload, {
|
|
...opts,
|
|
applyPayload: opts.applyConvergentPayload,
|
|
});
|
|
}
|
|
const message = 'Convergent sync is paused on this device';
|
|
for (const [provider, connection] of Object.entries(
|
|
this.state.providers as Record<CloudProvider, ProviderConnection>,
|
|
)) {
|
|
if (!isProviderReadyForSync(connection)) continue;
|
|
results.set(provider as CloudProvider, {
|
|
success: false,
|
|
provider: provider as CloudProvider,
|
|
action: 'none',
|
|
error: message,
|
|
});
|
|
}
|
|
return results;
|
|
}
|
|
|
|
const overrideShrinkRequested = opts.overrideShrink === true;
|
|
const syncSecurityGeneration = getSyncSecurityGeneration(this);
|
|
|
|
if (!payload) {
|
|
// Caller should provide payload from app state
|
|
return results;
|
|
}
|
|
|
|
if (this.state.securityState !== 'UNLOCKED') {
|
|
return results; // Or throw? Caller handles it.
|
|
}
|
|
|
|
if (!this.masterPassword) {
|
|
return results;
|
|
}
|
|
|
|
const connectedProviders = Object.entries(
|
|
this.state.providers as Record<CloudProvider, ProviderConnection>,
|
|
)
|
|
.filter(([provider, connection]) => {
|
|
if (!isProviderReadyForSync(connection)) return false;
|
|
if (connection.status === 'error') {
|
|
this.state.providers[provider as CloudProvider].status = 'connected';
|
|
this.state.providers[provider as CloudProvider].error = undefined;
|
|
// Clear cached adapter so a fresh one is created with current (decrypted) tokens
|
|
this.adapters.delete(provider as CloudProvider);
|
|
}
|
|
return true;
|
|
})
|
|
.map(([p]) => p as CloudProvider);
|
|
|
|
if (connectedProviders.length === 0) {
|
|
return results;
|
|
}
|
|
|
|
this.state.lastError = null;
|
|
this.state.syncState = 'SYNCING';
|
|
|
|
// 1. Parallel Checks
|
|
const checkTasks = connectedProviders.map(async (provider) => {
|
|
try {
|
|
// We handle connection error here to prevent one provider blocking others
|
|
const adapter = await this.getConnectedAdapter(provider);
|
|
this.updateProviderStatus(provider, 'syncing');
|
|
this.emit({ type: 'SYNC_STARTED', provider });
|
|
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
const check = await this.checkProviderConflict(provider, adapter);
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
return { provider, adapter, check };
|
|
} catch (error) {
|
|
return { provider, error: String(error) };
|
|
}
|
|
});
|
|
|
|
const checkResults = await Promise.all(checkTasks);
|
|
|
|
// 2. Analyze Results & Handle Conflicts — merge ALL conflicting providers
|
|
//
|
|
// Contract: every connected provider is assumed to mirror the *same*
|
|
// logical vault. When providers hold divergent content (e.g. user
|
|
// intentionally points GitHub and OneDrive at separate accounts with
|
|
// different data), uploading the conflict-merged payload below will
|
|
// overwrite provider-unique content on non-conflicting providers. A
|
|
// proper fix requires per-provider compare-and-swap (follow-up work,
|
|
// see I-1 and `docs/`). Until then, we log a diagnostic warning when
|
|
// we detect cross-provider base divergence so the issue is visible in
|
|
// support logs.
|
|
const conflicts = checkResults.filter((r) => !r.error && r.check?.conflict && r.check?.remoteFile);
|
|
|
|
// Instrumentation only — detect divergent provider bases (an
|
|
// unsupported configuration). Cheap: bases are already persisted
|
|
// and we only read their aggregate counts.
|
|
if (checkResults.filter((r) => !r.error).length > 1) {
|
|
try {
|
|
const summaries = await Promise.all(
|
|
checkResults
|
|
.filter((r) => !r.error)
|
|
.map(async (r) => {
|
|
const base = await this.loadSyncBase(r.provider as CloudProvider);
|
|
return {
|
|
provider: r.provider,
|
|
hosts: base?.hosts?.length ?? 0,
|
|
keys: base?.keys?.length ?? 0,
|
|
snippets: base?.snippets?.length ?? 0,
|
|
};
|
|
}),
|
|
);
|
|
const signatures = summaries.map((s) => `${s.hosts}/${s.keys}/${s.snippets}`);
|
|
const allSame = signatures.every((sig) => sig === signatures[0]);
|
|
if (!allSame) {
|
|
console.warn(
|
|
'[CloudSyncManager] syncAll: connected providers hold divergent bases (multi-account setup?). Uploading the conflict-merged payload will replace each provider\'s current remote. See I-7 in PR #720 for context.',
|
|
summaries,
|
|
);
|
|
// Surface the same finding to the UI so multi-account / intentionally
|
|
// diverged configurations can be warned visibly instead of silently
|
|
// having one provider's data merged over another's (#779 follow-up).
|
|
this.emit({
|
|
type: 'PROVIDERS_DIVERGED',
|
|
summaries: summaries.map((s) => ({
|
|
provider: s.provider as CloudProvider,
|
|
hosts: s.hosts,
|
|
keys: s.keys,
|
|
snippets: s.snippets,
|
|
})),
|
|
});
|
|
}
|
|
} catch (diagError) {
|
|
// Non-fatal diagnostic; never let it block the sync.
|
|
console.warn('[CloudSyncManager] syncAll: base-divergence check failed:', diagError);
|
|
}
|
|
}
|
|
|
|
if (conflicts.length > 0) {
|
|
const conflictAction = opts.conflictActionOverride
|
|
?? resolveCloudSyncConflictAction(this.state.syncStrategy, {
|
|
hasConflict: true,
|
|
hasRemoteFile: true,
|
|
});
|
|
|
|
if (conflictAction === 'download-remote') {
|
|
const newestConflict = conflicts.reduce((latest, entry) => {
|
|
const latestUpdatedAt = latest.check?.remoteFile?.meta.updatedAt ?? 0;
|
|
const entryUpdatedAt = entry.check?.remoteFile?.meta.updatedAt ?? 0;
|
|
return entryUpdatedAt > latestUpdatedAt ? entry : latest;
|
|
});
|
|
try {
|
|
const remoteResult = await downloadRemoteForSyncAllImpl.call(
|
|
this,
|
|
newestConflict.provider as CloudProvider,
|
|
newestConflict.check!.remoteFile!,
|
|
syncSecurityGeneration,
|
|
);
|
|
const sourceProvider = newestConflict.provider as CloudProvider;
|
|
results.set(sourceProvider, remoteResult);
|
|
payload = remoteResult.mergedPayload ?? payload;
|
|
|
|
for (const r of checkResults) {
|
|
const provider = r.provider as CloudProvider;
|
|
if (provider === sourceProvider) continue;
|
|
if (r.check) {
|
|
r.check.conflict = false;
|
|
}
|
|
}
|
|
} catch (error) {
|
|
const msg = String(error);
|
|
this.state.syncState = 'ERROR';
|
|
this.state.lastError = msg;
|
|
this.updateProviderStatus(newestConflict.provider as CloudProvider, 'error', msg);
|
|
this.emit({ type: 'SYNC_ERROR', provider: newestConflict.provider as CloudProvider, error: msg });
|
|
results.set(newestConflict.provider as CloudProvider, {
|
|
success: false,
|
|
provider: newestConflict.provider as CloudProvider,
|
|
action: 'none',
|
|
error: msg,
|
|
});
|
|
return results;
|
|
}
|
|
}
|
|
|
|
if (conflictAction === 'upload-local') {
|
|
for (const r of checkResults) {
|
|
if (r.check) r.check.conflict = false;
|
|
}
|
|
} else if (conflictAction === 'smart-merge') {
|
|
// Three-way merge: incorporate remote data from every conflicting provider
|
|
try {
|
|
let merged = payload;
|
|
for (const c of conflicts) {
|
|
const providerBase = await this.loadSyncBase(c.provider as CloudProvider);
|
|
const remotePayload = await EncryptionService.decryptPayload(
|
|
c.check!.remoteFile!,
|
|
this.masterPassword,
|
|
);
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
const result = mergeSyncPayloads(providerBase, merged, remotePayload);
|
|
merged = result.payload;
|
|
}
|
|
const mergeResult = { payload: merged };
|
|
|
|
console.info('[CloudSyncManager] syncAll: three-way merge completed');
|
|
|
|
// Replace payload with merged payload for upload to all providers
|
|
payload = mergeResult.payload;
|
|
wasMerged = true;
|
|
|
|
// Re-classify: all providers (including the conflicting one) should now upload
|
|
// Clear the conflict check result so all go through the upload path
|
|
for (const r of checkResults) {
|
|
if (r.check) r.check.conflict = false;
|
|
}
|
|
} catch (mergeError) {
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
// Merge failed — fall back to conflict UI
|
|
console.error('[CloudSyncManager] syncAll: merge failed', mergeError);
|
|
const { provider, check } = conflicts[0];
|
|
const remoteFile = check!.remoteFile!;
|
|
let conflictSummary;
|
|
try {
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
const base = await this.loadSyncBase(provider as CloudProvider);
|
|
const remotePayload = await EncryptionService.decryptPayload(remoteFile, this.masterPassword);
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
conflictSummary = summarizeSyncChanges(
|
|
base,
|
|
payload,
|
|
remotePayload,
|
|
);
|
|
} catch {
|
|
conflictSummary = undefined;
|
|
}
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
|
|
this.state.syncState = 'CONFLICT';
|
|
this.state.currentConflict = {
|
|
provider: provider as CloudProvider,
|
|
localVersion: this.state.localVersion,
|
|
localUpdatedAt: this.state.localUpdatedAt,
|
|
localDeviceName: this.state.deviceName,
|
|
remoteVersion: remoteFile.meta.version,
|
|
remoteUpdatedAt: remoteFile.meta.updatedAt,
|
|
remoteDeviceName: remoteFile.meta.deviceName,
|
|
...(conflictSummary ? { changeSummary: conflictSummary } : {}),
|
|
};
|
|
|
|
this.emit({
|
|
type: 'CONFLICT_DETECTED',
|
|
conflict: this.state.currentConflict,
|
|
});
|
|
|
|
for (const r of checkResults) {
|
|
if (r.error) {
|
|
results.set(r.provider as CloudProvider, {
|
|
success: false,
|
|
provider: r.provider as CloudProvider,
|
|
action: 'none',
|
|
error: r.error,
|
|
});
|
|
this.updateProviderStatus(r.provider as CloudProvider, 'error', r.error);
|
|
this.emit({ type: 'SYNC_ERROR', provider: r.provider as CloudProvider, error: r.error });
|
|
} else if (r.provider === conflicts[0].provider) {
|
|
results.set(r.provider as CloudProvider, {
|
|
success: false,
|
|
provider: r.provider as CloudProvider,
|
|
action: 'none',
|
|
conflictDetected: true,
|
|
});
|
|
} else {
|
|
this.updateProviderStatus(r.provider as CloudProvider, 'connected');
|
|
results.set(r.provider as CloudProvider, {
|
|
success: true,
|
|
provider: r.provider as CloudProvider,
|
|
action: 'none',
|
|
});
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Shrink guard (multi-provider): check the final outgoing payload against
|
|
// each provider's stored base. If ANY provider would suffer a suspicious
|
|
// shrink, block ALL uploads — the same payload goes to every provider, so
|
|
// any one provider's "would lose too much" is a global block. Override flag
|
|
// is one-shot and clears regardless of outcome.
|
|
const shrinkSuspectByProvider: Array<{
|
|
provider: CloudProvider;
|
|
finding: Extract<ShrinkFinding, { suspicious: true }>;
|
|
}> = [];
|
|
const candidateProviders = checkResults
|
|
.filter((r) => !r.error && !r.check?.conflict && r.adapter)
|
|
.map((r) => r.provider as CloudProvider);
|
|
for (const provider of candidateProviders) {
|
|
const providerBase = await this.loadSyncBase(provider);
|
|
// When no stored base exists, fall back to the remote payload fetched
|
|
// during the parallel check above — the shrink guard needs a reference
|
|
// or it fails open and lets degraded local state overwrite remote
|
|
// (#779). checkResults carries the per-provider remoteFile already.
|
|
let providerRemoteRef: SyncPayload | null = null;
|
|
if (!providerBase) {
|
|
const entry = checkResults.find((r) => r.provider === provider);
|
|
const remoteFile = entry?.check?.remoteFile;
|
|
if (remoteFile) {
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
try {
|
|
providerRemoteRef = await EncryptionService.decryptPayload(
|
|
remoteFile,
|
|
this.masterPassword,
|
|
);
|
|
} catch {
|
|
providerRemoteRef = null;
|
|
}
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
}
|
|
}
|
|
const finding = detectSuspiciousShrink(payload, providerBase, providerRemoteRef);
|
|
if (finding.suspicious) {
|
|
shrinkSuspectByProvider.push({ provider, finding });
|
|
}
|
|
}
|
|
const shouldBlockAll = shrinkSuspectByProvider.length > 0 && !overrideShrinkRequested;
|
|
const shouldForceAll = shrinkSuspectByProvider.length > 0 && overrideShrinkRequested;
|
|
|
|
if (shouldBlockAll) {
|
|
this.state.syncState = 'BLOCKED';
|
|
this.state.lastShrinkFinding = shrinkSuspectByProvider[0].finding;
|
|
for (const { provider, finding } of shrinkSuspectByProvider) {
|
|
this.emit({ type: 'SYNC_BLOCKED_SHRINK', provider, finding });
|
|
this.updateProviderStatus(provider, 'error', 'Sync blocked: would delete too much');
|
|
results.set(provider, {
|
|
success: false,
|
|
provider,
|
|
action: 'none',
|
|
shrinkBlocked: true,
|
|
finding,
|
|
});
|
|
}
|
|
// Process check errors from the parallel check phase so a provider that
|
|
// failed during checkProviderConflict is not silently dropped from results.
|
|
checkResults.forEach((r) => {
|
|
if (r.error) {
|
|
results.set(r.provider as CloudProvider, {
|
|
success: false,
|
|
provider: r.provider as CloudProvider,
|
|
action: 'none',
|
|
error: r.error,
|
|
});
|
|
this.updateProviderStatus(r.provider as CloudProvider, 'error', r.error);
|
|
this.emit({ type: 'SYNC_ERROR', provider: r.provider as CloudProvider, error: r.error });
|
|
}
|
|
});
|
|
// Providers in candidateProviders that didn't trip the shrink check still
|
|
// share the same payload — mark them as not-uploaded so the caller doesn't
|
|
// think a "successful" no-op happened.
|
|
const blockedProviders = new Set(shrinkSuspectByProvider.map((e) => e.provider));
|
|
for (const provider of candidateProviders) {
|
|
if (!results.has(provider) && !blockedProviders.has(provider)) {
|
|
results.set(provider, {
|
|
success: false,
|
|
provider,
|
|
action: 'none',
|
|
error: 'Sync blocked: another provider would lose too much data',
|
|
});
|
|
this.updateProviderStatus(provider, 'error', 'Sync blocked due to peer provider');
|
|
}
|
|
}
|
|
return results;
|
|
}
|
|
|
|
if (shouldForceAll) {
|
|
for (const { provider, finding } of shrinkSuspectByProvider) {
|
|
this.emit({ type: 'SYNC_FORCED', provider, finding });
|
|
}
|
|
}
|
|
|
|
// 3. Encrypt Once
|
|
const validUploads = checkResults.filter(
|
|
(r) => !r.error && !r.check?.conflict && r.adapter
|
|
) as { provider: CloudProvider; adapter: CloudAdapter }[];
|
|
|
|
if (validUploads.length === 0) {
|
|
// Process errors if any
|
|
checkResults.forEach((r) => {
|
|
if (r.error) {
|
|
results.set(r.provider as CloudProvider, {
|
|
success: false,
|
|
provider: r.provider as CloudProvider,
|
|
action: 'none',
|
|
error: r.error,
|
|
});
|
|
this.updateProviderStatus(r.provider as CloudProvider, 'error', r.error);
|
|
this.emit({ type: 'SYNC_ERROR', provider: r.provider as CloudProvider, error: r.error });
|
|
}
|
|
});
|
|
if (Array.from(results.values()).some((r) => r.success)) {
|
|
this.exitBlockedState();
|
|
this.state.syncState = 'IDLE';
|
|
} else {
|
|
this.state.syncState = 'ERROR';
|
|
}
|
|
this.notifyStateChange();
|
|
return results;
|
|
}
|
|
|
|
// Use the highest version as base: either local or any remote that was merged
|
|
// or forcibly overwritten. Explicit keep-local (conflictActionOverride
|
|
// upload-local) can run while syncStrategy is still smartMerge; without
|
|
// taking the remote version here, encryptPayload would mint local+1 and
|
|
// regress past a higher conflicting remote (e.g. local v1 over remote v5).
|
|
let baseVersion = this.state.localVersion;
|
|
if (
|
|
wasMerged
|
|
|| (
|
|
conflicts.length > 0
|
|
&& (
|
|
this.state.syncStrategy !== 'smartMerge'
|
|
|| opts.conflictActionOverride === 'upload-local'
|
|
)
|
|
)
|
|
) {
|
|
for (const c of conflicts) {
|
|
const rv = c.check?.remoteFile?.meta?.version ?? 0;
|
|
if (rv > baseVersion) baseVersion = rv;
|
|
}
|
|
}
|
|
|
|
// 4. Parallel Uploads — each provider gets metadata derived from its own
|
|
// base, then that exact payload is persisted as the provider base
|
|
// inside uploadToProvider BEFORE the per-provider anchor advances.
|
|
// Ordering matters: a crash between the two writes must leave the
|
|
// stale anchor re-triggering inspection on next startup, not a
|
|
// fresh anchor paired with a stale base.
|
|
const uploadTasks = validUploads.map(async ({ provider, adapter }) => {
|
|
try {
|
|
const entry = checkResults.find((result) => result.provider === provider);
|
|
assertConvergentSyncWriteCompatible(entry?.check?.remoteFile?.meta, payload);
|
|
const providerBase = await this.loadSyncBase(provider);
|
|
let providerRemoteRef: SyncPayload | null = null;
|
|
if (!providerBase) {
|
|
const remoteFile = entry?.check?.remoteFile;
|
|
if (remoteFile) {
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
try {
|
|
providerRemoteRef = await EncryptionService.decryptPayload(
|
|
remoteFile,
|
|
this.masterPassword,
|
|
);
|
|
} catch {
|
|
providerRemoteRef = null;
|
|
}
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
}
|
|
}
|
|
const providerPayload = withSyncReliabilityMeta(payload, providerBase ?? providerRemoteRef, {
|
|
deviceId: this.state.deviceId,
|
|
now: Date.now(),
|
|
});
|
|
const syncedFile = await EncryptionService.encryptPayload(
|
|
providerPayload,
|
|
this.masterPassword,
|
|
this.state.deviceId,
|
|
this.state.deviceName,
|
|
packageJson.version,
|
|
baseVersion
|
|
);
|
|
assertSyncSecurityGeneration(this, syncSecurityGeneration);
|
|
const result = await this.uploadToProvider(provider, adapter, syncedFile, providerPayload, syncSecurityGeneration);
|
|
results.set(provider, result);
|
|
} catch (error) {
|
|
const msg = String(error);
|
|
this.state.lastError = msg;
|
|
this.updateProviderStatus(provider, 'error', msg);
|
|
this.emit({ type: 'SYNC_ERROR', provider, error: msg });
|
|
results.set(provider, {
|
|
success: false,
|
|
provider,
|
|
action: 'none',
|
|
error: msg,
|
|
});
|
|
}
|
|
});
|
|
|
|
await Promise.all(uploadTasks);
|
|
|
|
// 5. Final State Update
|
|
const resultList = Array.from(results.values());
|
|
const hasSuccess = resultList.some((r) => r.success);
|
|
const hasConflict = resultList.some((r) => r.conflictDetected);
|
|
if (hasConflict) {
|
|
// Prefer CONFLICT over IDLE even when another provider succeeded, so the
|
|
// conflict UI from uploadToProvider is not wiped by a mixed multi-provider run.
|
|
this.state.syncState = 'CONFLICT';
|
|
if (wasMerged && payload) {
|
|
for (const [p, r] of results) {
|
|
if (r.success) {
|
|
results.set(p, { ...r, action: 'merge', mergedPayload: payload });
|
|
}
|
|
}
|
|
}
|
|
} else if (hasSuccess) {
|
|
this.exitBlockedState();
|
|
this.state.syncState = 'IDLE';
|
|
this.state.lastShrinkFinding = undefined;
|
|
|
|
// If a merge happened, attach the merged payload to successful results
|
|
// so callers can apply remote additions to local state
|
|
if (wasMerged && payload) {
|
|
for (const [p, r] of results) {
|
|
if (r.success) {
|
|
results.set(p, { ...r, action: 'merge', mergedPayload: payload });
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
this.state.syncState = 'ERROR';
|
|
// lastError is set by uploadToProvider
|
|
}
|
|
this.notifyStateChange(); // Notify UI that sync is complete
|
|
|
|
// Process errors from initial checks (if any)
|
|
checkResults.forEach((r) => {
|
|
if (r.error) {
|
|
results.set(r.provider as CloudProvider, {
|
|
success: false,
|
|
provider: r.provider as CloudProvider,
|
|
action: 'none',
|
|
error: r.error,
|
|
});
|
|
this.updateProviderStatus(r.provider as CloudProvider, 'error', r.error);
|
|
this.emit({ type: 'SYNC_ERROR', provider: r.provider as CloudProvider, error: r.error });
|
|
}
|
|
});
|
|
|
|
return results;
|
|
}
|
|
|
|
export function setDeviceNameImpl(this: any,name: string): void {
|
|
this.state.deviceName = name;
|
|
this.saveToStorage(SYNC_STORAGE_KEYS.DEVICE_NAME, name);
|
|
this.notifyStateChange();
|
|
}
|
|
|
|
export function setAutoSyncImpl(this: any,enabled: boolean, intervalMinutes?: number): void {
|
|
this.state.autoSyncEnabled = enabled;
|
|
if (intervalMinutes) {
|
|
this.state.autoSyncInterval = Math.max(
|
|
SYNC_CONSTANTS.MIN_SYNC_INTERVAL,
|
|
Math.min(SYNC_CONSTANTS.MAX_SYNC_INTERVAL, intervalMinutes)
|
|
);
|
|
}
|
|
this.saveSyncConfig();
|
|
this.notifyStateChange(); // Notify UI of state change
|
|
|
|
if (enabled && this.state.securityState === 'UNLOCKED') {
|
|
this.startAutoSync();
|
|
} else {
|
|
this.stopAutoSync();
|
|
}
|
|
}
|
|
|
|
export function startAutoSyncImpl(this: any): void {
|
|
if (this.autoSyncTimer) {
|
|
return;
|
|
}
|
|
|
|
this.autoSyncTimer = setInterval(
|
|
() => {
|
|
// Auto-sync callback - caller should provide payload
|
|
this.emit({ type: 'SYNC_STARTED', provider: 'github' }); // Trigger UI to initiate sync
|
|
},
|
|
this.state.autoSyncInterval * 60 * 1000
|
|
);
|
|
}
|
|
|
|
export function stopAutoSyncImpl(this: any): void {
|
|
if (this.autoSyncTimer) {
|
|
clearInterval(this.autoSyncTimer);
|
|
this.autoSyncTimer = null;
|
|
}
|
|
}
|
|
|
|
export function saveSyncConfigImpl(this: any): void {
|
|
this.saveToStorage(SYNC_STORAGE_KEYS.SYNC_CONFIG, {
|
|
autoSync: this.state.autoSyncEnabled,
|
|
interval: this.state.autoSyncInterval,
|
|
localVersion: this.state.localVersion,
|
|
localUpdatedAt: this.state.localUpdatedAt,
|
|
remoteVersion: this.state.remoteVersion,
|
|
remoteUpdatedAt: this.state.remoteUpdatedAt,
|
|
syncStrategy: this.state.syncStrategy,
|
|
});
|
|
}
|
|
|
|
export function syncBaseKeyImpl(this: any,provider?: CloudProvider): string {
|
|
const suffix = provider ? `_${provider}` : '';
|
|
return `${SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD}${suffix}`;
|
|
}
|
|
|
|
export function providerAccountIdKeyImpl(this: any,provider: CloudProvider): string {
|
|
return `netcatty.sync.accountId.${provider}`;
|
|
}
|
|
|
|
export function loadProviderAccountIdImpl(this: any,provider: CloudProvider): string | null {
|
|
const stored = this.loadFromStorage(this.providerAccountIdKey(provider));
|
|
return typeof stored === 'string' ? stored : null;
|
|
}
|
|
|
|
export function saveProviderAccountIdImpl(this: any,provider: CloudProvider, id: string): void {
|
|
this.saveToStorage(this.providerAccountIdKey(provider), id);
|
|
}
|
|
|
|
export async function saveSyncBaseImpl(this: any,payload: SyncPayload, provider?: CloudProvider): Promise<void> {
|
|
const key = this.state.unlockedKey?.derivedKey;
|
|
if (!key) {
|
|
throw new Error('Sync base encryption key is unavailable');
|
|
}
|
|
try {
|
|
try {
|
|
await rememberCurrentSyncBaseSnapshot.call(this, provider);
|
|
} catch (snapshotError) {
|
|
console.warn('[CloudSyncManager] Failed to save previous sync snapshot', snapshotError);
|
|
}
|
|
if (
|
|
this.saveToStorage(
|
|
this.syncBaseKey(provider),
|
|
await encryptLocalStorageValue(payload, key),
|
|
) === false
|
|
) {
|
|
throw new Error('Unable to persist sync base');
|
|
}
|
|
} catch (error) {
|
|
console.warn('[CloudSyncManager] Failed to save sync base', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function loadSyncBaseImpl(this: any,provider?: CloudProvider): Promise<SyncPayload | null> {
|
|
const key = this.state.unlockedKey?.derivedKey;
|
|
if (!key) return null;
|
|
try {
|
|
const encoded = this.loadFromStorage(this.syncBaseKey(provider)) as unknown;
|
|
if (!encoded || typeof encoded !== 'string') return null;
|
|
return decryptLocalStorageValue<SyncPayload>(encoded, key);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export function syncSnapshotsKeyImpl(this: any,provider?: CloudProvider): string {
|
|
const suffix = provider ? `_${provider}` : '';
|
|
return `${SYNC_SNAPSHOTS_STORAGE_KEY}${suffix}`;
|
|
}
|
|
|
|
export async function loadSyncSnapshotsImpl(this: any,provider?: CloudProvider): Promise<SyncSnapshotEntry[]> {
|
|
const key = this.state.unlockedKey?.derivedKey;
|
|
if (!key) return [];
|
|
try {
|
|
const encoded = this.loadFromStorage(this.syncSnapshotsKey(provider)) as unknown;
|
|
if (!encoded || typeof encoded !== 'string') return [];
|
|
const snapshots = await decryptLocalStorageValue<SyncSnapshotEntry[]>(encoded, key);
|
|
return Array.isArray(snapshots) ? snapshots : [];
|
|
} catch {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
export async function saveSyncSnapshotsImpl(this: any,snapshots: SyncSnapshotEntry[], provider?: CloudProvider): Promise<void> {
|
|
const key = this.state.unlockedKey?.derivedKey;
|
|
if (!key) {
|
|
throw new Error('Sync snapshot encryption key is unavailable');
|
|
}
|
|
if (this.saveToStorage(
|
|
this.syncSnapshotsKey(provider),
|
|
await encryptLocalStorageValue(snapshots.slice(0, SYNC_SNAPSHOT_LIMIT), key),
|
|
) === false) throw new Error('Unable to persist sync snapshots');
|
|
}
|
|
|
|
export function clearSyncBaseImpl(this: any): void {
|
|
this.removeFromStorage(SYNC_STORAGE_KEYS.SYNC_BASE_PAYLOAD);
|
|
if (typeof this.syncSnapshotsKey === 'function') {
|
|
this.removeFromStorage(this.syncSnapshotsKey());
|
|
}
|
|
const providers = new Set<CloudProvider>([
|
|
'github', 'google', 'onedrive', 'webdav', 's3',
|
|
]);
|
|
for (const id of Object.keys(this.state?.providers ?? {})) {
|
|
providers.add(id as CloudProvider);
|
|
}
|
|
if (typeof this.listRegisteredPluginProviderIds === 'function') {
|
|
for (const id of this.listRegisteredPluginProviderIds()) {
|
|
providers.add(id as CloudProvider);
|
|
}
|
|
}
|
|
for (const p of providers) {
|
|
this.removeFromStorage(this.syncBaseKey(p));
|
|
this.removeFromStorage(this.convergentProviderBaselineKey(p));
|
|
if (typeof this.syncSnapshotsKey === 'function') {
|
|
this.removeFromStorage(this.syncSnapshotsKey(p));
|
|
}
|
|
}
|
|
this.clearSyncAnchor();
|
|
}
|
|
|
|
export function addSyncHistoryEntryImpl(this: any,entry: Omit<SyncHistoryEntry, 'id'>): void {
|
|
const newEntry: SyncHistoryEntry = {
|
|
...entry,
|
|
id: crypto.randomUUID(),
|
|
};
|
|
|
|
// Keep only the last 50 entries
|
|
this.state.syncHistory = [newEntry, ...this.state.syncHistory].slice(0, 50);
|
|
this.saveToStorage(SYNC_HISTORY_STORAGE_KEY, this.state.syncHistory);
|
|
this.notifyStateChange(); // Notify UI of new history entry
|
|
}
|
|
|
|
export function resetLocalVersionImpl(this: any): void {
|
|
this.state.localVersion = 0;
|
|
this.state.localUpdatedAt = 0;
|
|
this.state.syncHistory = [];
|
|
this.saveSyncConfig();
|
|
this.saveToStorage(SYNC_HISTORY_STORAGE_KEY, []);
|
|
this.clearSyncBase();
|
|
this.clearSyncAnchor();
|
|
this.notifyStateChange();
|
|
}
|