Compare commits

...

2 Commits

Author SHA1 Message Date
amir 5ade80a334 v1.0.29: fix sync loop, stale-state auto-heal, icon redesign
- SyncEngine: self-healing stale folder state detection (isRetry) wipes
  orphaned SyncFileStateEntity records when localPath changes without a
  pair re-save — prevents repeated DELETE_REMOTE on 32 old files
- SyncEngine: second-precision mtime comparison (/ 1000 / .epochSecond)
  eliminates phantom localChanged=true from FAT32/WebDAV precision mismatch
- FileWatchService: syncCooldownUntil map suppresses FileObserver events
  for 120s after sync starts and 60s after it finishes, breaking the
  download→FileObserver→sync→download feedback loop
- Icon: three bold teardrop shapes (teal/red/amber) rotated 0/120/240°
  on dark charcoal background with white cloud at intersection

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 11:51:59 +00:00
amir 34fb06a673 v1.0.28: fix sync rewrite/delete loop, Avast-inspired icon
Sync loop root-cause fixes (three independent bugs):

1. Folder change clears stale file states (AddPairViewModel): when
   localPath or remotePath changes on an existing pair, all
   SyncFileStateEntity records are wiped. Previously those stale records
   caused every sync to attempt DELETE_REMOTE on the old folder's files
   and to treat all new-folder files as changed — causing both the
   "deleting 32 files" loop and rewrites on every run.

2. Download stores null localModifiedAt (SyncEngine): SAF document
   cursors can return a stale mtime immediately after a write. Storing
   null forces the SKIP reconciliation pass on the next sync to read
   the actual walkFiles cursor value, breaking the download->changed->
   download loop caused by mtime inconsistency.

3. Second-precision mtime comparison (syncDecide): WebDAV RFC-1123 has
   1-second precision; FAT32 has 2-second precision. Comparing at
   millisecond level caused phantom "changed" detections after syncing
   to/from these systems. Now uses epochSecond for both local and remote.

Icon: three bold teal/red/yellow teardrop streaks (Avast palette) flying
into a white cloud centre, on dark charcoal background.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-25 04:18:13 +00:00
6 changed files with 129 additions and 102 deletions
@@ -62,13 +62,28 @@ class SyncEngine @Inject constructor(
else
LocalAccessor.JavaFile(File(localPath))
private suspend fun performSync(pair: SyncPair, provider: CloudProvider): SyncResult {
private suspend fun performSync(
pair: SyncPair,
provider: CloudProvider,
isRetry: Boolean = false,
): SyncResult {
val accessor = makeAccessor(pair.localPath)
val knownStates = fileStateDao.getForPair(pair.id).associateBy { it.relativePath }
var knownStates = fileStateDao.getForPair(pair.id).associateBy { it.relativePath }
val remoteFiles = provider.listFiles(pair.remotePath).getOrThrow()
.associateBy { it.path.removePrefix(pair.remotePath).trimStart('/') }
val localFiles = accessor.walkFiles(pair)
// Self-healing: if every known-state path is absent from the current local scan but
// the local folder does have files, the localPath was changed without clearing state.
// The stale records would cause every old file to look like "DELETE_REMOTE" and every
// new file to re-upload indefinitely. Wipe and retry once as a fresh initial sync.
if (!isRetry && knownStates.isNotEmpty() && localFiles.isNotEmpty() &&
knownStates.keys.none { it in localFiles }) {
Timber.w("SyncEngine: stale folder states detected for pair ${pair.id} — resetting")
fileStateDao.deleteForPair(pair.id)
return performSync(pair, provider, isRetry = true)
}
val allPaths = (localFiles.keys + remoteFiles.keys + knownStates.keys).toSet()
val hasPriorSyncState = knownStates.isNotEmpty()
val semaphore = Semaphore(4)
@@ -126,7 +141,9 @@ class SyncEngine @Inject constructor(
logEvent(pair.id, SyncEventType.FILE_DOWNLOADED, rel, null, bytes)
FileOutcome(downloaded = 1, bytesTransferred = bytes,
newState = buildState(pair.id, rel,
LocalFileInfo(rel, remote!!.sizeBytes, localMtime), remoteAfterTransfer = remote))
LocalFileInfo(rel, remote!!.sizeBytes, localMtime),
remoteAfterTransfer = remote,
storeLocalMtime = false))
}
SyncDecision.DELETE_LOCAL -> {
accessor.delete(rel)
@@ -203,10 +220,13 @@ class SyncEngine @Inject constructor(
rel: String,
local: LocalFileInfo?,
remoteAfterTransfer: RemoteFile?,
storeLocalMtime: Boolean = true,
) = SyncFileStateEntity(
syncPairId = pairId,
relativePath = rel,
localModifiedAt = local?.lastModifiedMs?.let { Instant.ofEpochMilli(it) },
// When storeLocalMtime=false, leave localModifiedAt null so the SKIP reconciliation
// pass on the next sync reads it from the walkFiles cursor (avoids SAF stale-mtime loops).
localModifiedAt = if (storeLocalMtime) local?.lastModifiedMs?.let { Instant.ofEpochMilli(it) } else null,
localSizeBytes = local?.sizeBytes ?: 0L,
localHash = null,
remoteModifiedAt = remoteAfterTransfer?.modifiedAt,
@@ -236,12 +256,16 @@ internal fun syncDecide(
// Treat null known timestamps as "not yet recorded" — don't treat as changed.
// The SKIP reconciliation pass will fill them in on the next sync.
// Use second-precision for both sides: FAT32 has 2-second mtime resolution, WebDAV
// RFC-1123 has 1-second resolution, so millisecond comparison causes phantom "changed"
// detections and rewrite loops after a fresh download/upload.
val localChanged = known == null ||
(localExists && known.localModifiedAt != null &&
local!!.lastModifiedMs != known.localModifiedAt.toEpochMilli())
local!!.lastModifiedMs / 1000 != known.localModifiedAt.epochSecond)
val remoteChanged = known == null ||
(remoteExists && known.remoteModifiedAt != null &&
(remote!!.etag != known.remoteEtag || remote.modifiedAt != known.remoteModifiedAt))
(remote!!.etag != known.remoteEtag ||
remote.modifiedAt.epochSecond != known.remoteModifiedAt.epochSecond))
return when {
!localExists && !remoteExists -> SyncDecision.SKIP
@@ -5,6 +5,7 @@ import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.syncflow.data.db.CloudAccountDao
import com.syncflow.data.db.SyncFileStateDao
import com.syncflow.data.db.SyncPairDao
import com.syncflow.data.db.entities.CloudAccountEntity
import com.syncflow.data.db.entities.SyncPairEntity
@@ -58,6 +59,7 @@ data class AddPairUiState(
@HiltViewModel
class AddPairViewModel @Inject constructor(
private val syncPairDao: SyncPairDao,
private val fileStateDao: SyncFileStateDao,
private val accountDao: CloudAccountDao,
@ApplicationContext private val context: Context,
savedState: SavedStateHandle,
@@ -148,7 +150,20 @@ class AddPairViewModel @Inject constructor(
notifyOnComplete = s.notifyOnComplete, notifyOnError = s.notifyOnError,
isEnabled = true, lastSyncAt = null, lastSyncResult = SyncStatus.IDLE, pendingConflicts = 0,
)
if (editPairId == null) syncPairDao.insert(entity) else syncPairDao.update(entity)
if (editPairId == null) {
syncPairDao.insert(entity)
} else {
val existing = syncPairDao.getById(editPairId)
syncPairDao.update(entity)
// If local or remote folder changed, old file-state records no longer
// correspond to any real path — wipe them so the next sync starts fresh
// instead of trying to delete/re-upload stale paths.
if (existing != null &&
(existing.localPath != entity.localPath || existing.remotePath != entity.remotePath)
) {
fileStateDao.deleteForPair(editPairId)
}
}
}
.onSuccess {
if (s.scheduleType == ScheduleType.ON_CHANGE) FileWatchService.start(context)
@@ -40,6 +40,9 @@ class FileWatchService : Service() {
private val fileObservers = mutableMapOf<Long, MutableList<FileObserver>>()
private val contentObservers = mutableMapOf<Long, ContentObserver>()
private val debounceJobs = mutableMapOf<Long, Job>()
// After a watcher-triggered sync completes, suppress FileObserver events for this long
// to stop the feedback loop: sync writes files → FileObserver fires → another sync → repeat.
private val syncCooldownUntil = mutableMapOf<Long, Long>()
companion object {
const val CHANNEL_WATCH = "sync_watching"
@@ -210,6 +213,13 @@ class FileWatchService : Service() {
}
private fun onChangeDetected(pairId: Long, wifiOnly: Boolean, chargingOnly: Boolean) {
// Ignore events fired by our own sync writing files — prevents the feedback loop
// where downloaded/uploaded files trigger another sync indefinitely.
if (System.currentTimeMillis() < (syncCooldownUntil[pairId] ?: 0L)) {
Timber.d("FileWatchService: suppressing change event for pair $pairId (sync cooldown)")
return
}
debounceJobs[pairId]?.cancel()
debounceJobs[pairId] = scope.launch {
delay(5_000)
@@ -217,19 +227,22 @@ class FileWatchService : Service() {
if (pair == null || !pair.isEnabled) return@launch
Timber.d("FileWatchService: triggering sync for pair $pairId after debounce")
// Block new triggers from this point until 60s after sync completes
syncCooldownUntil[pairId] = System.currentTimeMillis() + 120_000
val req = SyncWorker.buildOneTimeRequest(pairId, wifiOnly, chargingOnly, silent = true)
WorkManager.getInstance(applicationContext)
.enqueueUniqueWork("onchange_$pairId", ExistingWorkPolicy.KEEP, req)
// Update notification while sync is in progress
updateNotificationDynamic("Syncing: ${pair.name}")
// Wait for completion and show result in the persistent notification
scope.launch {
try {
val info = WorkManager.getInstance(applicationContext)
.getWorkInfoByIdFlow(req.id)
.first { it?.state?.isFinished == true }
// Extend cooldown: 60s after sync finishes to let filesystem settle
syncCooldownUntil[pairId] = System.currentTimeMillis() + 60_000
val summary = info?.outputData?.getString(SyncWorker.KEY_RESULT_SUMMARY)
val watchCount = fileObservers.keys.size + contentObservers.size
val watching = "Watching $watchCount folder${if (watchCount != 1) "s" else ""}"
@@ -239,8 +252,9 @@ class FileWatchService : Service() {
updateNotificationDynamic("$watching")
}
delay(12_000)
updateNotificationDynamic(null) // revert to default watching text
updateNotificationDynamic(null)
} catch (_: Exception) {
syncCooldownUntil[pairId] = 0L
updateNotificationDynamic(null)
}
}
@@ -254,6 +268,7 @@ class FileWatchService : Service() {
contentObservers.clear()
debounceJobs.values.forEach { it.cancel() }
debounceJobs.clear()
syncCooldownUntil.clear()
}
private fun ensureChannel() {
@@ -6,14 +6,19 @@
android:viewportWidth="108"
android:viewportHeight="108">
<!-- Deep purple-black base, matching the knot reference icon's dark background -->
<path android:pathData="M0,0 H108 V108 H0 Z">
<!-- Dark charcoal background, matching Avast-style dark icon bg -->
<path android:pathData="M0,0 H108 V108 H0 Z"
android:fillColor="#1F1F2E"/>
<!-- Very subtle inner glow -->
<path android:pathData="M0,0 H108 V108 H0 Z"
android:fillAlpha="0.25">
<aapt:attr name="android:fillColor">
<gradient android:type="radial"
android:gradientRadius="76"
android:centerX="54" android:centerY="44"
android:startColor="#1E1628"
android:endColor="#080610"/>
android:gradientRadius="60"
android:centerX="54" android:centerY="50"
android:startColor="#3D3A50"
android:endColor="#00000000"/>
</aapt:attr>
</path>
@@ -1,99 +1,67 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
SyncFlow icon foreground (108x108dp, safe zone 72dp centred at 54,54).
Design: two thick tube-style sync arcs that form a circular refresh symbol,
inspired by the braided knot icon's color palette:
Arc 1 (left side, CW): coral #E8665A -> orange #E8A040
Arc 2 (right side, CW): steel blue #4A7FD4 -> purple #7B5EA7
Each arc has a thin inner highlight to give a 3D glossy tube look.
Geometry: circle centred at (54,54), radius 27.
Arc 1: 100 deg to 260 deg CW (160 deg, through west/left)
start (49.31, 80.59) end (49.31, 27.41)
Arc 2: 280 deg to 80 deg CW (160 deg, through east/right)
start (58.69, 27.41) end (58.69, 80.59)
20-degree gaps at top (~260-280) and bottom (~80-100).
Highlights at r=23 (inner edge):
Arc 1 highlight: (49.99, 76.64) to (49.99, 31.36)
Arc 2 highlight: (58.01, 31.36) to (58.01, 76.64)
SyncFlow icon foreground.
Three bold teardrop shapes in Avast-palette colors (teal, red, amber),
tips meeting at center (54,54), wide heads pointing outward at 0/120/240 deg.
White cloud centred over the intersection point.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<!-- Arc 1 shadow (offset slightly down-right for depth) -->
<!-- Teal teardrop — head pointing straight up -->
<group android:rotation="0"
android:pivotX="54"
android:pivotY="54">
<path
android:fillColor="#00C4A7"
android:pathData="M 54,57 C 50,57 38,52 34,41 C 30,30 38,20 54,20 C 70,20 78,30 74,41 C 70,52 58,57 54,57 Z"/>
</group>
<!-- Red teardrop — head pointing lower-right (120 deg CW from up) -->
<group android:rotation="120"
android:pivotX="54"
android:pivotY="54">
<path
android:fillColor="#F44336"
android:pathData="M 54,57 C 50,57 38,52 34,41 C 30,30 38,20 54,20 C 70,20 78,30 74,41 C 70,52 58,57 54,57 Z"/>
</group>
<!-- Amber teardrop — head pointing lower-left (240 deg CW from up) -->
<group android:rotation="240"
android:pivotX="54"
android:pivotY="54">
<path
android:fillColor="#FFC107"
android:pathData="M 54,57 C 50,57 38,52 34,41 C 30,30 38,20 54,20 C 70,20 78,30 74,41 C 70,52 58,57 54,57 Z"/>
</group>
<!-- White cloud centred at (54,52), sits over the teardrop intersection -->
<path
android:pathData="M 50.31,82.59 A 27,27 0 0,1 50.31,29.41"
android:fillColor="#00000000"
android:strokeWidth="9"
android:strokeLineCap="round"
android:strokeColor="#44000000"/>
android:fillColor="#FFFFFF"
android:pathData="
M 42,62
A 8,8 0 0,1 42,46
A 8,8 0 0,1 51,39
A 11,11 0 0,1 67,42
A 7,7 0 0,1 68,56
A 7,7 0 0,1 66,62
Z"/>
<!-- Arc 2 shadow -->
<!-- Cloud inner shadow to make it pop from the coloured teardrops -->
<path
android:pathData="M 59.69,29.41 A 27,27 0 0,1 59.69,82.59"
android:fillColor="#00000000"
android:strokeWidth="9"
android:strokeLineCap="round"
android:strokeColor="#44000000"/>
<!-- Arc 1: left side, coral to orange -->
<path
android:pathData="M 49.31,80.59 A 27,27 0 0,1 49.31,27.41"
android:fillColor="#00000000"
android:strokeWidth="9"
android:strokeLineCap="round">
<aapt:attr name="android:strokeColor">
<gradient android:type="linear"
android:startX="49.31" android:startY="80.59"
android:endX="49.31" android:endY="27.41"
android:startColor="#E8665A"
android:endColor="#E8A040"/>
</aapt:attr>
</path>
<!-- Arc 2: right side, blue to purple -->
<path
android:pathData="M 58.69,27.41 A 27,27 0 0,1 58.69,80.59"
android:fillColor="#00000000"
android:strokeWidth="9"
android:strokeLineCap="round">
<aapt:attr name="android:strokeColor">
<gradient android:type="linear"
android:startX="58.69" android:startY="27.41"
android:endX="58.69" android:endY="80.59"
android:startColor="#4A7FD4"
android:endColor="#7B5EA7"/>
</aapt:attr>
</path>
<!-- Arc 1 inner highlight (glossy tube sheen) -->
<path
android:pathData="M 49.99,76.64 A 23,23 0 0,1 49.99,31.36"
android:fillColor="#00000000"
android:strokeWidth="2.5"
android:strokeLineCap="round"
android:strokeColor="#55FFC8B0"/>
<!-- Arc 2 inner highlight -->
<path
android:pathData="M 58.01,31.36 A 23,23 0 0,1 58.01,76.64"
android:fillColor="#00000000"
android:strokeWidth="2.5"
android:strokeLineCap="round"
android:strokeColor="#55B0C8FF"/>
<!-- Arrowhead at end of Arc 1 (260 deg, top-left area, pointing right-up) -->
<path android:pathData="M 42.13,32.74 L 49.31,27.41 L 40.73,24.86 Z"
android:fillColor="#E8A040"/>
<!-- Arrowhead at end of Arc 2 (80 deg, bottom-right area, pointing left-down) -->
<path android:pathData="M 67.27,83.14 L 58.69,80.59 L 65.87,75.26 Z"
android:fillColor="#7B5EA7"/>
android:strokeColor="#18000000"
android:strokeWidth="1.5"
android:pathData="
M 42,62
A 8,8 0 0,1 42,46
A 8,8 0 0,1 51,39
A 11,11 0 0,1 67,42
A 7,7 0 0,1 68,56
A 7,7 0 0,1 66,62
Z"/>
</vector>
+2 -2
View File
@@ -1,2 +1,2 @@
VERSION_NAME=1.0.27
VERSION_CODE=28
VERSION_NAME=1.0.29
VERSION_CODE=30