Skip to content
Merged
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
21 changes: 19 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ Service modules:
- **autoEqService/**: AutoEq headphone correction profiles (index + fixed-band curves)
- **lyricsService/**: Lyrics fetching (LRCLIB, SimpMusic Lyrics, BetterLyrics)
- **listenTogether/**: shared listening rooms, wire-compatible with Metrolist (`MetrolistGroup/metroproto`)
- **loginSync/**: the QR-paired transport that moves sign-ins from the Android app to the Desktop app (Ktor client on the phone, one-shot Ktor CIO server on the Desktop, AES-256-GCM). Android + JVM targets only; carries opaque bytes — the data layer decides what they mean
- **loginSync/**: the QR-paired transport that moves sign-ins from the Android app to the Desktop app (Ktor client on the phone, one-shot Ktor CIO server on the Desktop, AES-256-GCM). Android + JVM targets only; carries opaque bytes — the data layer decides what they mean. Also carries library sync's long-lived paired channel (`PairedSyncWire`/`PairedSyncClient`/`PairedSyncServer`, fixed port 48517)
- **kizzy/**: Discord Rich Presence for FOSS builds (the user's own token, from a WebView login on Android or pasted on Desktop). Left untouched by the OAuth work below
- **discord/**: Discord Rich Presence over OAuth for Full builds (package `org.simpmusic.discord`): PKCE login, a Ktor gateway client that identifies with a Bearer token, and the presence itself. Used instead of kizzy whenever the build carries a Discord application id
- **ktorExt/**: Ktor extensions for networking
Expand Down Expand Up @@ -1162,6 +1162,23 @@ if (getPlatform() == Platform.Android) {
- **Linux slice rebuilt with `aeval` (2026-11-11).** `aeval` joined the FFmpeg `--enable-filter` list in `scripts/mpv-linux/Dockerfile`; the slice was rebuilt natively on ubuntu-work (38 libs, every object x86-64 ET_DYN, no glib, every other filter unchanged), republished on `abc` and pinned in `mpvNativesChecksums` (`f2f56dc6…45b0`, 16,035,411 B; the public URL served it at once). Checked by playing a left-only tone through that libmpv with `ao=pcm` and the app's 8D tier written by `af set`: the tone moved between the ears at the chosen period, while the previous slice answered `af set` with -12 and stayed left-only. The staged macOS (arm64, x64) and Windows (arm64, x64) slices carry `aeval` already.
- Tests: `EightDEffectTest` (domain commonTest), `EightDKernelTest` (media3), `EightDGraphsTest` (media-jvm, which gained `testImplementation(libs.junit)`). Written, not run; nothing was built or listened to. aeval parses its expression only when the output is configured, so `EightDGraphsTest` cannot catch a broken one: the graph string was run through ffmpeg 8.0.1 and through the rebuilt libmpv instead (the measurements above; `1.0E-4` phases parse). The kernel's expected numbers were checked against a line-for-line Python port first: ILD 0.41 dB at 200 Hz, 16.3 dB at 8 kHz, 17.8 dB at 12 kHz with the source at the right ear, far ear 30-31 samples late at 48 kHz, 0.5/0.5 on both ears for a left-only DC input at every azimuth.

- **Library sync between a phone and its paired computer (2026-11-12, issue #2663, branch `feat/data_sync`, NOT BUILT OR TESTED YET)**: the Desktop app is the server and keeps the log; the Android app drives every round — on app open (at most every 5 min, `MainActivity.syncLibraryIfDue`), every 15 min through WorkManager (`androidApp/.../service/sync/`, scheduled only while paired) and on "Sync now". Not realtime, never touches the queue or the player. Synced: liked songs, followed artists, hearted albums / YouTube playlists / podcasts, local playlists (title, cover, songs, order) and listening history (a phone gets the year before it was paired and everything after, on every batch). Not synced: queue, recents, caches, downloads, Smart downloads, device-bound settings and secrets. Downloads stay each device's own: Smart downloads scores only the plays made on that device (`getSongPlaysSince` reads `deviceId IS NULL`), and a like arriving by sync never triggers "download songs you like", which runs only on the like action itself. A device with local tracking off neither sends nor takes plays (the computer then relays none either). UI: Settings → Devices → **Library sync** opens `LibrarySyncDialog` (`expect/ui/LibrarySync*.kt`, state in `LibrarySyncHostViewModel` / `LibrarySyncPhoneViewModel`). Desktop: QR with the address picker, then the paired phones with per-phone sync time and Remove; Windows Public and port-in-use warnings. Android: scan → "Pair with this computer?" → status with Sync now / Unpair. The settings prompt names each differing key (`PendingSettings.keys`, labelled from the key name, English only). Paired, "Send sign-ins to desktop" skips the QR and goes over the paired channel; the computer asks with `LibrarySyncLoginPrompt`, drawn over the whole Desktop window. "Apply & restart" exits on Desktop (as a restored backup does) and relaunches on Android.
- **Layers**: transport in `core/service/loginSync` (above); domain `LibrarySyncRepository` + `LibrarySyncHostRepository` (Desktop) / `LibrarySyncPhoneRepository` (Android) and `model/librarysync`; data `librarysync/` — `SyncChangeRecorder` (write hooks in `LocalDataSource`/`AnalyticsDatasource`), `SyncEngine` (one round, both ends), `SyncApplier`, `SyncSnapshot`, `SyncedSettings`, `SyncPrefs`, platform repos in `jvmMain`/`androidMain`, bound in `Loader.*.kt`. iOS binds nothing.
- **Database v28** (AutoMigration from 25/26/27): new `sync_change` table; `syncId` (unique, nullable) on `local_playlist` and `playback_event`; `deviceId` on `playback_event` (null = played on this device). "Recently played" reads `deviceId IS NULL` only, so another device's plays never show up there. `27.json` was overwritten once by an IDE build mid-edit and restored from git: **the `from` schema of an AutoMigration must stay the shipped one**.
- **`sync_change` is two things.** On the phone it is the outbox (`serverSeq` null = not taken yet), so changes made while the computer is away go out later. On the computer it is the log phones pull from by `serverSeq`, keeping only the newest row per (entity, key) except history. It exists because an unlike writes `favoriteAt` back to null, so without it the moment of an "off" is lost and two devices cannot tell which came last.
- **Merge**: last change wins (`supersedes`: `changedAt`, then "on" beats "off", then `changeId`), compared against the log on the computer and against the phone's own pending rows on the phone, one change at a time right before it is applied. The computer logs a change only once it holds there (`SyncApplier.applyOne` returns whether it did), and when a phone's change loses it sends the winning row back. A playlist's name, cover and order are read when sent, not when changed. Writes made while applying run under the `SyncApplying` context element so the hooks do not record them again. Referenced rows (songs, albums, artists…) travel along and are inserted IGNORE with `inLibrary = 2000-01-01`, so they never surface as "recently added".
- **Local playlists are the hard part** (found by an independent review on 2026-11-12). A rename logs a new playlist row at the end of the log while its songs keep their old places, so a phone pulling from scratch can get the songs several batches before the playlist: every song and order row therefore carries the playlist's `meta`, and the receiver creates the playlist from it unless it deleted it later itself. A deletion loses to a later edit; the side that keeps the playlist then sends it again whole (`SyncSnapshot.playlistChanges`) instead of logging the deletion, since other phones would otherwise delete it too. When the computer brings back a playlist it had deleted from an edit alone, it asks that phone to send it again whole (`SyncResponse.resend`).
- **The YouTube link travels too** (owner's call, 2026-11-12): `PlaylistMeta.youtubePlaylistId`, and each song row of a linked playlist carries its `setVideoId` (the YouTube entry id `LocalPlaylistRepositoryImpl.findSetVideoId` needs to remove a song there). Only the device where the user made an edit pushes it to YouTube; applying a synced edit never does. Linking (`updateLocalPlaylistYouTubePlaylistId`) sends the playlist whole so every song carries its entry id, and an entry id stored after its song (`insertSetVideoId`) sends that song again. **A playlist imported from the same YouTube playlist on both devices is one playlist**: the side that receives a syncId it lacks, while holding a playlist with that link, gives its own the incoming syncId, drops what it recorded under the old one and sends it again whole. Both sides adopt what they receive, so they agree whichever row arrives first.
- **Sign-ins sent over the paired channel wait for the computer's user** (`LibrarySyncHostRepository.pendingLogins` / `answerLogins`): holding the paired key is not enough, so a lost phone cannot switch the computer's accounts. The phone's request waits up to 100 s for the answer (its client gives up at 120 s) and gets back only what was accepted; one prompt at a time.
- **Identity is the key, not the IP.** Pairing hands the phone a long-lived key under the QR's one-time key; every later knock carries a nonce the computer must echo with its id, and every sync reply echoes the request's nonce. A 403 alone never unpairs a phone: only the computer's own sealed "removed" knock reply does, and the computer keeps answering it for the 30 days a removed phone is remembered. The server refuses a body with no Content-Length before reading it. The phone looks for the computer at the address picked when pairing (LAN, Tailscale, anything listed), then every address it last reported, then a sealed UDP probe (multicast 239.255.48.17 + broadcast), then a sweep of its /24.
- **Deletion never propagates by accident.** Clearing listening history unpairs first (Desktop: every phone), and so does restoring a backup. A removed phone is told under its own key the next time it knocks. Settings travel every round but are applied only after the user agrees (allowlist in `SyncedSettings.KEYS`). A database copy is taken before the first merge of a pairing and before a merge that removes something, at most one an hour, three kept (`~/.simpmusic/sync-backups`, `filesDir/sync-backups`). Pairing state lives in its own `library_sync.preferences_pb`, outside the settings file, so a backup cannot carry a pairing key to another device.

- **Desktop vertical scrollbars, one artwork corner, tighter Android Home (2026-11-12)**:
- `VerticalScrollBar(scrollState, modifier)` (`expect/ui/Scrollbar*.kt`, overloads for `LazyListState`, `LazyGridState`, `ScrollState`) puts Compose Desktop's `VerticalScrollbar`, in the horizontal bars' `scrollBarStyle`, on the right edge of every scrolling page, the sidebar, both queues and the comments sheet. The Desktop gate is inside the function and the Android actual is empty. Thumb drag and press-and-hold paging (one page, then one every 100ms after 300ms) are Compose's own. Put it right after the list in a parent that stacks its children (Box, Crossfade, AnimatedContent): it fills that parent and only the bar takes input. `modifier` carries the list's top inset and `DesktopMiniPlayerClearance` (80dp: the capsule's 60dp plus its 20dp margin). A new vertical list on Desktop gets one too.
- `ArtworkShape` (`ui/theme/Theme.kt`, 4dp, measured off Spotify) is the one corner for rounded artwork; it replaced 2–14dp radii at 44 sites. It is not for circles (artists, avatars), edge-to-edge headers, or the three cards that define a style (M3 Expressive 28dp, SoundCloud 20dp, Your daily discover 28dp).
- Android Home packs tighter, Desktop unchanged: card sides 8dp (`cardSidePadding`), Quick picks rows 56dp, no 8dp/5dp around Quick picks' own header, no 8dp spacer over each section title. Android's card floor is artwork + `cardTextBlockFloor()`, the tallest text block (two `titleSmall` lines plus the subtitle row) measured with `rememberTextMeasurer`: Desktop's fixed 70dp counts Poppins' line gap (Skia) and left ~10dp spare under every Android card. Keep the floor: without it a row takes the height of the cards on screen and Home jumps when a two-line title scrolls in. Titles stay two lines, as on Spotify's song cards; the spare line belongs under the subtitle, never between title and subtitle.
- `AppTheme {}` with no arguments is the app's default cyan dark theme, not the user's: anything drawn outside `App()` (Desktop's `LibrarySyncLoginPrompt`) must read theme mode, colour source and custom colour the way `App()` does. Force-dark `typo()` paints `headlineMedium`/`bodyMedium` in its #A8A8A8 body grey, so text on a scrim (the daily discover hero) names `onSurface`/`onSurfaceVariant`.

## 🔄 CLAUDE.md Auto-Update Rule (MANDATORY)

After completing any of the following types of changes, the AI agent **MUST** update this CLAUDE.md file:
Expand All @@ -1186,6 +1203,6 @@ After completing any of the following types of changes, the AI agent **MUST** up

*This document helps AI Agents quickly understand the SimpMusic project. Update regularly when there are major changes to architecture or structure.*

**Last updated**: 2026-11-11
**Last updated**: 2026-11-12
**Project version**: Check latest release on GitHub
**Maintained by**: maxrave-dev and contributors
16 changes: 16 additions & 0 deletions androidApp/src/main/java/com/maxrave/simpmusic/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.SystemClock
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
Expand All @@ -34,6 +35,7 @@ import com.maxrave.domain.data.model.intent.GenericIntent
import com.maxrave.domain.manager.DataStoreManager
import com.maxrave.domain.mediaservice.handler.MediaPlayerHandler
import com.maxrave.domain.mediaservice.handler.ToastType
import com.maxrave.domain.repository.LibrarySyncPhoneRepository
import com.maxrave.logger.Logger
import com.maxrave.media3.di.setServiceActivitySession
import com.maxrave.simpmusic.di.viewModelModule
Expand All @@ -53,11 +55,15 @@ import pub.devrel.easypermissions.EasyPermissions
import java.util.Locale
import java.util.concurrent.TimeUnit

// Process-wide, so a recreated activity (rotation, theme change) does not count as opening the app.
private var lastLibrarySyncAt = 0L

@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
val viewModel: SharedViewModel by inject()
val mediaPlayerHandler by inject<MediaPlayerHandler>()
val dataStoreManager: DataStoreManager by inject()
private val librarySync: LibrarySyncPhoneRepository by inject()

private var mBound = false
private var shouldUnbind = false
Expand All @@ -84,6 +90,16 @@ class MainActivity : AppCompatActivity() {
startMusicService()
// Every return to the screen asks; the pass itself runs at most once a day.
viewModel.runSmartDownloadsIfDue()
syncLibraryIfDue()
}

// ponytail: a fixed 5-minute gap between app-open rounds, since a computer that is off costs a
// LAN sweep each time; WorkManager covers the rest every 15 minutes, and "Sync now" ignores it.
private fun syncLibraryIfDue() {
val now = SystemClock.elapsedRealtime()
if (lastLibrarySyncAt != 0L && now - lastLibrarySyncAt < 5 * 60_000L) return
lastLibrarySyncAt = now
lifecycleScope.launch { librarySync.syncNow() }
}

override fun onStop() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@ import coil3.request.crossfade
import com.maxrave.common.AppIdentity
import com.maxrave.data.di.loader.loadAllModules
import com.maxrave.domain.manager.DataStoreManager
import com.maxrave.domain.repository.LibrarySyncPhoneRepository
import com.maxrave.logger.Logger
import com.maxrave.simpmusic.di.viewModelModule
import com.maxrave.simpmusic.service.backup.AutoBackupScheduler
import com.maxrave.simpmusic.service.sync.LibrarySyncScheduler
import com.maxrave.simpmusic.utils.NetworkFirstInterceptor
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
Expand All @@ -34,6 +36,7 @@ import okio.FileSystem
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.component.KoinComponent
import org.koin.core.component.get
import org.koin.core.component.inject
import org.koin.core.context.loadKoinModules
import org.koin.core.context.startKoin
Expand Down Expand Up @@ -90,6 +93,11 @@ class SimpMusicApplication :
autoBackupScheduler.observeAndSchedule()
}

val librarySyncScheduler = LibrarySyncScheduler(this, get<LibrarySyncPhoneRepository>())
applicationScope.launch {
librarySyncScheduler.observeAndSchedule()
}

CaocConfig.Builder
.create()
.backgroundMode(CaocConfig.BACKGROUND_MODE_SILENT) // default: CaocConfig.BACKGROUND_MODE_SHOW_CUSTOM
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.maxrave.simpmusic.service.sync

import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import com.maxrave.domain.repository.LibrarySyncPhoneRepository
import com.maxrave.logger.Logger
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import java.util.concurrent.TimeUnit

/**
* Runs a library sync round in the background while this phone is paired with a computer (#2663).
* Fifteen minutes is the shortest interval WorkManager allows; opening the app and "Sync now" fill in
* between.
*/
class LibrarySyncScheduler(
private val context: Context,
private val repository: LibrarySyncPhoneRepository,
) {
/** Call from a scope that lives as long as the application. */
suspend fun observeAndSchedule() {
var wasPaired = false
repository.state
.map { it.isPaired }
.distinctUntilChanged()
.collect { paired ->
val workManager = WorkManager.getInstance(context)
if (paired) {
val request =
PeriodicWorkRequestBuilder<LibrarySyncWorker>(15, TimeUnit.MINUTES)
.setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
.build()
// KEEP: a launch must not restart the period, or cancel the job that woke the process.
workManager.enqueueUniquePeriodicWork(WORK_NAME, ExistingPeriodicWorkPolicy.KEEP, request)
Logger.i(TAG, "background sync scheduled")
} else if (wasPaired) {
// Only a real unpairing cancels it. The first value is "not paired" until the
// pairing file has been read, and acting on it would cancel a job that is running.
workManager.cancelUniqueWork(WORK_NAME)
Logger.i(TAG, "background sync cancelled")
}
wasPaired = paired
}
}

private companion object {
const val TAG = "LibrarySync"
const val WORK_NAME = "LibrarySyncWorker"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.maxrave.simpmusic.service.sync

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.maxrave.domain.repository.LibrarySyncPhoneRepository
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject

/** One round; a computer that is away is simply tried again on the next run. */
class LibrarySyncWorker(
context: Context,
params: WorkerParameters,
) : CoroutineWorker(context, params),
KoinComponent {
private val repository: LibrarySyncPhoneRepository by inject()

override suspend fun doWork(): Result {
repository.syncNow()
return Result.success()
}
}
Loading
Loading