From 7ee1580a7290e24ece2e88a006e193db40f03b7a Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:32 -0500 Subject: [PATCH 1/4] feat(mobile): add songs to queue with a full swipe (#89) --- .../app/(app)/(tabs)/home/album/[id].tsx | 3 +- .../app/(app)/(tabs)/home/playlist/[id].tsx | 11 +- apps/mobile/components/player.tsx | 8 +- apps/mobile/components/song-swipe-row.tsx | 191 +++++++++++++++--- 4 files changed, 178 insertions(+), 35 deletions(-) diff --git a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx index a32bf8c..512fccd 100644 --- a/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/album/[id].tsx @@ -488,7 +488,7 @@ const AlbumTrackRow = memo(function AlbumTrackRow({ action: MediaAction ) => Promise }) { - const Row = Platform.OS === "ios" ? SongSwipeRow : Pressable + const Row = Platform.OS !== "web" ? SongSwipeRow : Pressable const { config } = useServerConfig() return ( void onAction(track, album, "play-next")} + onAddToQueue={() => void onAction(track, album, "play-last")} style={styles.trackRow} onPress={() => void onPlay(track.id as Id<"songs">, songIds)} > diff --git a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx index f11a0d1..34037bd 100644 --- a/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx +++ b/apps/mobile/app/(app)/(tabs)/home/playlist/[id].tsx @@ -434,11 +434,18 @@ const PlaylistSongRow = memo(function PlaylistSongRow({ palette={palette} inset swipe={ - Platform.OS === "ios" + Platform.OS !== "web" ? { group: swipeGroup, backgroundColor: palette.background, onPlayNext: () => onAction(song, "play-next"), + onAddToQueue: () => onAction(song, "play-last"), + onRemove: + Platform.OS === "android" && removable + ? () => { + void onRemove(song.id) + } + : undefined, } : undefined } @@ -447,7 +454,7 @@ const PlaylistSongRow = memo(function PlaylistSongRow({ /> ) - if (Platform.OS === "ios" || !removable) { + if (Platform.OS !== "web" || !removable) { return row } diff --git a/apps/mobile/components/player.tsx b/apps/mobile/components/player.tsx index 0aaf866..3c77866 100644 --- a/apps/mobile/components/player.tsx +++ b/apps/mobile/components/player.tsx @@ -45,6 +45,8 @@ export const SongRow = memo(function SongRow({ swipe?: { group: SwipeRowGroup onPlayNext: () => void + onAddToQueue: () => void + onRemove?: () => void backgroundColor: string } /** Album/playlist layout: the divider starts at the title, not the artwork. */ @@ -107,10 +109,12 @@ export const SongRow = memo(function SongRow({ ? styles.insetRow : [styles.row, { borderBottomColor: divider }] const row = - swipe && Platform.OS === "ios" ? ( + swipe && Platform.OS !== "web" ? ( void + onAddToQueue: () => void + onRemove?: () => void backgroundColor: string } onPlay: (song: BrowseSong) => void diff --git a/apps/mobile/components/song-swipe-row.tsx b/apps/mobile/components/song-swipe-row.tsx index 3e2f044..e19973e 100644 --- a/apps/mobile/components/song-swipe-row.tsx +++ b/apps/mobile/components/song-swipe-row.tsx @@ -1,3 +1,4 @@ +import { Ionicons } from "@expo/vector-icons" import * as Haptics from "expo-haptics" import { SymbolView } from "expo-symbols" import { @@ -8,6 +9,7 @@ import { type ReactNode, } from "react" import { + Platform, Pressable, StyleSheet, type StyleProp, @@ -26,7 +28,10 @@ import Animated, { import { scheduleOnRN } from "react-native-worklets" import type { SwipeRowGroup } from "@/components/ios-swipe-to-remove-row" +const IS_ANDROID = Platform.OS === "android" + const ACTION_WIDTH = 82 +const LEADING_ACTION_WIDTH = 72 const SPRING = { duration: 450, dampingRatio: 1 } function impact() { @@ -41,6 +46,8 @@ export function SongSwipeRow({ group, onPress, onPlayNext, + onAddToQueue, + onRemove, }: { children: ReactNode style?: StyleProp @@ -48,7 +55,10 @@ export function SongSwipeRow({ group: SwipeRowGroup onPress?: () => void onPlayNext: () => void + onAddToQueue: () => void + onRemove?: () => void }) { + const hasRemove = IS_ANDROID && !!onRemove const x = useSharedValue(0) const startX = useSharedValue(0) const width = useSharedValue(0) @@ -78,10 +88,10 @@ export function SongSwipeRow({ const activate = useCallback( (side: number) => { close() - if (side > 0) onPlayNext() + if (side > 0) onAddToQueue() // Download is intentionally a placeholder. }, - [close, onPlayNext] + [close, onAddToQueue] ) const tapRow = useCallback(() => { if (open) close() @@ -105,7 +115,13 @@ export function SongSwipeRow({ Math.min(width.value, startX.value + event.translationX) ) const commit = - Math.abs(x.value) > Math.max(ACTION_WIDTH, width.value * 0.55) + Math.abs(x.value) > + Math.max( + x.value > 0 + ? LEADING_ACTION_WIDTH * 2 + : ACTION_WIDTH * (hasRemove ? 2 : 1), + width.value * 0.55 + ) if (commit !== committed.value) { committed.value = commit commitProgress.value = withSpring(commit ? 1 : 0, SPRING) @@ -124,10 +140,16 @@ export function SongSwipeRow({ Math.abs(x.value) > 10 && projected * side > ACTION_WIDTH / 2 ? side : 0 - x.value = withSpring(target * ACTION_WIDTH, { - ...SPRING, - velocity: event.velocityX, - }) + x.value = withSpring( + target * + (target > 0 + ? LEADING_ACTION_WIDTH * 2 + : ACTION_WIDTH * (hasRemove ? 2 : 1)), + { + ...SPRING, + velocity: event.velocityX, + } + ) scheduleOnRN(settle, target) }) .onFinalize((_event, success) => { @@ -145,6 +167,7 @@ export function SongSwipeRow({ return Gesture.Exclusive(pan, tap) }, [ activate, + hasRemove, begin, close, commitProgress, @@ -158,12 +181,14 @@ export function SongSwipeRow({ const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: x.value }], - borderRadius: interpolate( - Math.abs(x.value), - [0, 40], - [0, height.value / 2], - Extrapolation.CLAMP - ), + borderRadius: IS_ANDROID + ? 0 + : interpolate( + Math.abs(x.value), + [0, 40], + [0, height.value / 2], + Extrapolation.CLAMP + ), })) const fillStyle = useAnimatedStyle(() => ({ opacity: interpolate( @@ -190,8 +215,37 @@ export function SongSwipeRow({ open={open === 1} onPress={() => activate(1)} /> + { + close() + onPlayNext() + }} + /> + {hasRemove && ( + { + close() + onRemove?.() + }} + /> + )} { - if (event.nativeEvent.actionName === "playNext") activate(1) + if (event.nativeEvent.actionName === "remove" && hasRemove) { + close() + onRemove?.() + } + if (event.nativeEvent.actionName === "addToQueue") activate(1) + if (event.nativeEvent.actionName === "playNext") { + close() + onPlayNext() + } }} style={[styles.row, { backgroundColor }, rowStyle]} > @@ -225,6 +291,9 @@ export function SongSwipeRow({ function SwipeAction({ side, + secondary = false, + paired = side > 0, + remove = false, x, height, progress, @@ -232,22 +301,48 @@ function SwipeAction({ onPress, }: { side: 1 | -1 + secondary?: boolean + paired?: boolean + remove?: boolean x: SharedValue height: SharedValue progress: SharedValue open: boolean onPress: () => void }) { - const actionStyle = useAnimatedStyle(() => ({ - width: Math.max(0, x.value * side), - })) - const pillStyle = useAnimatedStyle(() => { + const actionStyle = useAnimatedStyle(() => { const revealed = Math.max(0, x.value * side) + const primaryWidth = (revealed * (1 + progress.value)) / 2 + return { + width: !paired + ? revealed + : secondary + ? revealed - primaryWidth + : primaryWidth, + ...(secondary + ? side > 0 + ? { left: primaryWidth } + : { right: primaryWidth } + : {}), + } + }) + const pillStyle = useAnimatedStyle(() => { + const total = Math.max(0, x.value * side) + const revealed = !paired + ? total + : (total * (secondary ? 1 - progress.value : 1 + progress.value)) / 2 + if (IS_ANDROID) { + return { width: revealed, height: height.value, borderRadius: 0 } + } const resting = Math.max( 0, Math.min( - revealed - 20, - interpolate(revealed, [24, ACTION_WIDTH, 220], [0, 62, 200]) + revealed - (side > 0 ? 10 : 20), + interpolate( + revealed, + [24, side > 0 ? LEADING_ACTION_WIDTH : ACTION_WIDTH, 220], + [0, 62, 200] + ) ) ) const pillWidth = @@ -292,27 +387,61 @@ function SwipeAction({ > 0 ? "Play Next" : "Download"} + accessibilityLabel={ + remove + ? "Remove from Playlist" + : side > 0 + ? secondary + ? "Play Next" + : "Add to Queue" + : "Download" + } onPress={onPress} style={styles.actionButton} > 0 ? "#6b5bff" : "#008dff" }, + { + backgroundColor: remove + ? "#d32f2f" + : side > 0 + ? secondary + ? "#6b5bff" + : "#f29943" + : "#008dff", + }, pillStyle, ]} > - 0 - ? "text.line.first.and.arrowtriangle.forward" - : "arrow.down" - } - size={22} - tintColor="white" - /> + {IS_ANDROID ? ( + + ) : ( + 0 + ? secondary + ? "text.line.first.and.arrowtriangle.forward" + : "text.line.last.and.arrowtriangle.forward" + : "arrow.down" + } + size={22} + tintColor="white" + /> + )} From db29de28c00c1942a3fb5a894adacf82c2cb7830 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:38 -0500 Subject: [PATCH 2/4] fix(playback): pause and replay the final queue track (#90) --- apps/mobile/contexts/playback.tsx | 14 +++++++++++--- apps/web/components/playback-provider.tsx | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/apps/mobile/contexts/playback.tsx b/apps/mobile/contexts/playback.tsx index 96241e8..8980e63 100644 --- a/apps/mobile/contexts/playback.tsx +++ b/apps/mobile/contexts/playback.tsx @@ -376,7 +376,8 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { const handlePlaylistStatusUpdate = useCallback( (status: AudioPlaylistStatus) => { - if (!status.isLoaded) return + // iOS may remove the finished item before delivering its final status. + if (!status.isLoaded && !status.didJustFinish) return const state = storeRef.current.getState() if (loadedSongIdsRef.current[status.currentIndex] !== state.queue[0]) { return @@ -427,7 +428,14 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { isPlayingRef.current = false setIsPlayingState(false) storeRef.current.update(playbackQueue.skipNext) - void playlistRef.current?.seekTo(0) + const playlist = playlistRef.current + if (playlist) { + playlist.pause() + // Reload the final item, which iOS removes when playback ends. + ignoreTrackChangeRef.current = true + playlist.skipTo(status.currentIndex) + scheduleTrackChangeHandling() + } currentTimeRef.current = 0 setCurrentTime(0) return @@ -443,7 +451,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { playlist?.play() } }, - [] + [scheduleTrackChangeHandling] ) const handleTrackChanged = useCallback( diff --git a/apps/web/components/playback-provider.tsx b/apps/web/components/playback-provider.tsx index 524a611..99471b7 100644 --- a/apps/web/components/playback-provider.tsx +++ b/apps/web/components/playback-provider.tsx @@ -955,6 +955,7 @@ export function PlaybackProvider({ children }: { children: ReactNode }) { if (!shouldContinuePlaying) { autoPlayNextRef.current = false isPlayingRef.current = false + audio.pause() audio.currentTime = 0 currentTimeRef.current = 0 setCurrentTime(0) From cf61b0ac2548eeddadc745f3603e58d8552979a8 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:53 -0500 Subject: [PATCH 3/4] fix(mobile): run only the selected artwork color pipeline (#92) --- .../mobile/app/(app)/(tabs)/home/settings.tsx | 6 +- apps/mobile/hooks/cover-palette-source.ts | 142 ++++++++++++++++ apps/mobile/hooks/use-cover-palette.ts | 160 ++++-------------- apps/mobile/hooks/use-legacy-cover-palette.ts | 153 +++-------------- apps/mobile/lib/artwork-color-preference.ts | 39 +++-- 5 files changed, 216 insertions(+), 284 deletions(-) create mode 100644 apps/mobile/hooks/cover-palette-source.ts diff --git a/apps/mobile/app/(app)/(tabs)/home/settings.tsx b/apps/mobile/app/(app)/(tabs)/home/settings.tsx index 30a0cfb..d3e8d72 100644 --- a/apps/mobile/app/(app)/(tabs)/home/settings.tsx +++ b/apps/mobile/app/(app)/(tabs)/home/settings.tsx @@ -23,7 +23,6 @@ import { useServerConfig } from "@/contexts/server-config" import { setArtworkColorsEnabled, useArtworkColorsEnabled, - useArtworkColorPreferenceLoaded, } from "@/lib/artwork-color-preference" import { initialsFromName } from "@/lib/format" import { useCachedQuery } from "@/hooks/use-cached-query" @@ -172,7 +171,6 @@ export default function SettingsScreen() { function AppearanceSection() { const enabled = useArtworkColorsEnabled() - const loaded = useArtworkColorPreferenceLoaded() const [saving, setSaving] = useState(false) return ( @@ -180,8 +178,8 @@ function AppearanceSection() { { setSaving(true) try { diff --git a/apps/mobile/hooks/cover-palette-source.ts b/apps/mobile/hooks/cover-palette-source.ts new file mode 100644 index 0000000..31e1d35 --- /dev/null +++ b/apps/mobile/hooks/cover-palette-source.ts @@ -0,0 +1,142 @@ +import { useEffect, useMemo, useState } from "react" + +import { themeCoverPalette, type CoverPalette } from "@/lib/cover-palette" +import { readCache, writeCache } from "@/lib/persistent-cache" +import { useIsDark, useThemeColors } from "@/lib/theme" +import { withCoverImageSize } from "@/lib/urls" + +// How long a screen holds its skeleton for the first extraction of a cover, +// so rows render once with final colors instead of flashing from the theme. +export const COVER_PALETTE_WAIT_MS = 400 + +export type CoverPaletteResult = { palette: CoverPalette; settled: boolean } + +type CoverPaletteSourceOptions = { + /** Persistent cache key for a 64px cover URI. */ + cacheKey: (colorSourceUri: string) => string + extract: (colorSourceUri: string) => Promise + derive: (swatches: Swatches, isDark: boolean) => CoverPalette | null + /** Reject persisted entries written in an older shape. */ + isValidCache?: (swatches: Swatches) => boolean +} + +/** + * One artwork color pipeline: an extractor and palette derivation with their + * own memory cache, persistent cache and in-flight requests. + */ +export function createCoverPaletteSource({ + cacheKey, + extract, + derive, + isValidCache, +}: CoverPaletteSourceOptions) { + const swatchesByKey = new Map() + const pending = new Map>() + + function cachedSwatches(key: string): Swatches | null | undefined { + if (swatchesByKey.has(key)) return swatchesByKey.get(key) + const cached = readCache(cacheKey(key)) + return cached && isValidCache && !isValidCache(cached) ? undefined : cached + } + + function extractSwatches(key: string) { + const inFlight = pending.get(key) + if (inFlight) return inFlight + + const request = extract(key) + .catch(() => null) + .then((swatches) => { + swatchesByKey.set(key, swatches) + if (swatches) writeCache(cacheKey(key), swatches) + pending.delete(key) + return swatches + }) + pending.set(key, request) + return request + } + + function prefetch(uri: string) { + const key = withCoverImageSize(uri, 64) + if (cachedSwatches(key) !== undefined) return + void extractSwatches(key) + } + + /** + * Colors for a screen tinted by `uri`'s cover art. Pass `uri` as "" to skip + * extraction. Pass `hasCover` as `undefined` while it isn't known yet so + * extraction can start early. + * + * `settled` turns true once the palette is final or after + * `COVER_PALETTE_WAIT_MS`, whichever comes first. + */ + function usePalette( + uri: string, + hasCover: boolean | undefined + ): CoverPaletteResult { + const theme = useThemeColors() + const isDark = useIsDark() + const key = uri ? withCoverImageSize(uri, 64) : "" + const [resolved, setResolved] = useState(() => ({ + key, + swatches: key ? cachedSwatches(key) : null, + })) + const [waitedKey, setWaitedKey] = useState(null) + + const swatches = + resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null + + useEffect(() => { + if (!key || hasCover === false) return + let cancelled = false + const known = cachedSwatches(key) + const show = (next: Swatches | null) => + setResolved((prev) => + prev.key === key && sameSwatches(prev.swatches, next) + ? prev + : { key, swatches: next } + ) + if (known !== undefined && swatchesByKey.has(key)) { + show(known) + return + } + + // Persisted swatches render immediately; refresh them in the background + // in case the cover changed. + const timer = + known === undefined + ? setTimeout( + () => !cancelled && setWaitedKey(key), + COVER_PALETTE_WAIT_MS + ) + : null + void extractSwatches(key).then((next) => { + if (!cancelled) show(next ?? known ?? null) + }) + return () => { + cancelled = true + if (timer) clearTimeout(timer) + } + }, [hasCover, key]) + + const palette = useMemo(() => { + const fromArt = + hasCover !== false && swatches ? derive(swatches, isDark) : null + return fromArt ?? themeCoverPalette(theme, isDark) + }, [hasCover, isDark, swatches, theme]) + + return { + palette, + settled: + !key || + hasCover === false || + swatches !== undefined || + waitedKey === key, + } + } + + return { prefetch, usePalette } +} + +function sameSwatches(a: unknown, b: unknown) { + return a === b || JSON.stringify(a) === JSON.stringify(b) +} diff --git a/apps/mobile/hooks/use-cover-palette.ts b/apps/mobile/hooks/use-cover-palette.ts index 7280c45..6cea962 100644 --- a/apps/mobile/hooks/use-cover-palette.ts +++ b/apps/mobile/hooks/use-cover-palette.ts @@ -1,147 +1,47 @@ -import { useEffect, useMemo, useState } from "react" import { - artworkColorsEnabled, + createCoverPaletteSource, + type CoverPaletteResult, +} from "@/hooks/cover-palette-source" +import { + prefetchLegacyCoverPalette, + useLegacyCoverPalette, +} from "@/hooks/use-legacy-cover-palette" +import { + loadArtworkColorsEnabled, useArtworkColorsEnabled, } from "@/lib/artwork-color-preference" -import { prefetchLegacyCoverPalette, useLegacyCoverPalette } from "@/hooks/use-legacy-cover-palette" import { extractCoverSwatches } from "@/lib/artwork-colors" +import { deriveCoverPalette, type CoverSwatches } from "@/lib/cover-palette" -import { - deriveCoverPalette, - themeCoverPalette, - type CoverPalette, - type CoverSwatches, -} from "@/lib/cover-palette" -import { readCache, writeCache } from "@/lib/persistent-cache" -import { useIsDark, useThemeColors } from "@/lib/theme" -import { withCoverImageSize } from "@/lib/urls" +export { COVER_PALETTE_WAIT_MS } from "@/hooks/cover-palette-source" -// How long a screen holds its skeleton for the first extraction of a cover, -// so rows render once with final colors instead of flashing from the theme. -export const COVER_PALETTE_WAIT_MS = 400 - -const swatchesByKey = new Map() -const pending = new Map>() - -function cacheKey(colorSourceUri: string) { - return `palette:v2:${colorSourceUri}` -} - -function sameSwatches( - a: CoverSwatches | null | undefined, - b: CoverSwatches | null | undefined -) { - return a === b || JSON.stringify(a) === JSON.stringify(b) -} - -function cachedSwatches(key: string): CoverSwatches | null | undefined { - if (swatchesByKey.has(key)) return swatchesByKey.get(key) - return readCache(cacheKey(key)) -} - -function extractSwatches(key: string) { - const inFlight = pending.get(key) - if (inFlight) return inFlight - - const request = extractCoverSwatches(key) - .catch(() => null) - .then((swatches) => { - swatchesByKey.set(key, swatches) - if (swatches) writeCache(cacheKey(key), swatches) - pending.delete(key) - return swatches - }) - pending.set(key, request) - return request -} +const region = createCoverPaletteSource({ + cacheKey: (colorSourceUri) => `palette:v2:${colorSourceUri}`, + extract: extractCoverSwatches, + derive: (swatches) => deriveCoverPalette(swatches), +}) /** Warm visible artwork colors before a detail page is pushed. */ export function prefetchCoverPalette(uri: string) { - if (!artworkColorsEnabled()) { - prefetchLegacyCoverPalette(uri) - return - } - const key = withCoverImageSize(uri, 64) - if (cachedSwatches(key) !== undefined) return - void extractSwatches(key) + void loadArtworkColorsEnabled().then((enabled) => + enabled ? region.prefetch(uri) : prefetchLegacyCoverPalette(uri) + ) } /** - * Colors for a screen tinted by `uri`'s cover art. Extraction runs once per - * cover and is cached on device. Pass `hasCover` as `undefined` while it isn't - * known yet so extraction can start early. - * - * `settled` turns true once the palette is final or after - * `COVER_PALETTE_WAIT_MS`, whichever comes first. + * Colors for a screen tinted by `uri`'s cover art, from whichever pipeline the + * device preference selects. Nothing is extracted until the preference loads, + * and the screen stays unsettled meanwhile so it doesn't flash theme colors. */ -function useRegionCoverPalette( +export function useCoverPalette( uri: string, hasCover: boolean | undefined -): { palette: CoverPalette; settled: boolean } { - const theme = useThemeColors() - const isDark = useIsDark() - const key = uri ? withCoverImageSize(uri, 64) : "" - const [resolved, setResolved] = useState(() => ({ - key, - swatches: key ? cachedSwatches(key) : null, - })) - const [waitedKey, setWaitedKey] = useState(null) - - const swatches = - resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null - - useEffect(() => { - if (!key || hasCover === false) return - let cancelled = false - const known = cachedSwatches(key) - const show = (next: CoverSwatches | null) => - setResolved((prev) => - prev.key === key && sameSwatches(prev.swatches, next) - ? prev - : { key, swatches: next } - ) - if (known !== undefined && swatchesByKey.has(key)) { - show(known) - return - } - - // Persisted swatches render immediately; refresh them in the background in - // case the cover changed. - const timer = - known === undefined - ? setTimeout( - () => !cancelled && setWaitedKey(key), - COVER_PALETTE_WAIT_MS - ) - : null - void extractSwatches(key).then((next) => { - if (!cancelled) show(next ?? known ?? null) - }) - return () => { - cancelled = true - if (timer) clearTimeout(timer) - } - }, [hasCover, key]) - - const palette = useMemo(() => { - const fromArt = - hasCover !== false && swatches - ? deriveCoverPalette(swatches) - : null - return fromArt ?? themeCoverPalette(theme, isDark) - }, [hasCover, isDark, swatches, theme]) - - return { - palette, - settled: - !key || hasCover === false || swatches !== undefined || waitedKey === key, - } -} - -/** Switch both extraction and palette derivation without mixing their caches. */ -export function useCoverPalette(uri: string, hasCover: boolean | undefined) { +): CoverPaletteResult { const enabled = useArtworkColorsEnabled() - const region = useRegionCoverPalette(enabled ? uri : "", hasCover) - const legacy = useLegacyCoverPalette(enabled ? "" : uri, hasCover) - return enabled ? region : legacy + const current = region.usePalette(enabled === true ? uri : "", hasCover) + const legacy = useLegacyCoverPalette(enabled === false ? uri : "", hasCover) + if (enabled === undefined) { + return { palette: current.palette, settled: !uri || hasCover === false } + } + return enabled ? current : legacy } diff --git a/apps/mobile/hooks/use-legacy-cover-palette.ts b/apps/mobile/hooks/use-legacy-cover-palette.ts index 49a7350..9ea720b 100644 --- a/apps/mobile/hooks/use-legacy-cover-palette.ts +++ b/apps/mobile/hooks/use-legacy-cover-palette.ts @@ -1,29 +1,14 @@ -import { useEffect, useMemo, useState } from "react" import { getColors, type ImageColorsResult } from "react-native-image-colors" +import { createCoverPaletteSource } from "@/hooks/cover-palette-source" import { - themeCoverPalette, - type CoverPalette, -} from "@/lib/cover-palette" -import { deriveCoverPalette, type LegacyCoverSwatches as CoverSwatches } from "@/lib/legacy-cover-palette" -import { readCache, writeCache } from "@/lib/persistent-cache" -import { useIsDark, useThemeColors } from "@/lib/theme" -import { withCoverImageSize } from "@/lib/urls" - -// How long a screen holds its skeleton for the first extraction of a cover, -// so rows render once with final colors instead of flashing from the theme. -const COVER_PALETTE_WAIT_MS = 400 + deriveCoverPalette, + type LegacyCoverSwatches as CoverSwatches, +} from "@/lib/legacy-cover-palette" // image-colors substitutes this for swatches it couldn't find. const MISSING = "#010203" -const swatchesByKey = new Map() -const pending = new Map>() - -function cacheKey(colorSourceUri: string) { - return `palette:${colorSourceUri}` -} - function present(colors: (string | undefined)[]) { return colors.filter( (color): color is string => !!color && color.toLowerCase() !== MISSING @@ -59,120 +44,24 @@ function toSwatches(result: ImageColorsResult): CoverSwatches | null { } } -function sameSwatches( - a: CoverSwatches | null | undefined, - b: CoverSwatches | null | undefined -) { - return a === b || JSON.stringify(a) === JSON.stringify(b) -} - -function cachedSwatches(key: string): CoverSwatches | null | undefined { - if (swatchesByKey.has(key)) return swatchesByKey.get(key) - const cached = readCache(cacheKey(key)) +const legacy = createCoverPaletteSource({ + cacheKey: (colorSourceUri) => `palette:${colorSourceUri}`, + extract: (key) => + getColors(key, { + fallback: MISSING, + cache: true, + key, + quality: "low", + pixelSpacing: 4, + }).then(toSwatches), + derive: deriveCoverPalette, // Discard the background-only entries written by the tablet palette experiment. - return cached && (!Array.isArray(cached.text) || !Array.isArray(cached.accent)) - ? undefined - : cached -} - -function extractSwatches(key: string) { - const inFlight = pending.get(key) - if (inFlight) return inFlight - - const request = getColors(key, { - fallback: MISSING, - cache: true, - key, - quality: "low", - pixelSpacing: 4, - }) - .then(toSwatches) - .catch(() => null) - .then((swatches) => { - swatchesByKey.set(key, swatches) - if (swatches) writeCache(cacheKey(key), swatches) - pending.delete(key) - return swatches - }) - pending.set(key, request) - return request -} + isValidCache: (cached) => + Array.isArray(cached.text) && Array.isArray(cached.accent), +}) /** Warm visible artwork colors before a detail page is pushed. */ -export function prefetchLegacyCoverPalette(uri: string) { - const key = withCoverImageSize(uri, 64) - if (cachedSwatches(key) !== undefined) return - void extractSwatches(key) -} +export const prefetchLegacyCoverPalette = legacy.prefetch -/** - * Colors for a screen tinted by `uri`'s cover art. Extraction runs once per - * cover and is cached on device. Pass `hasCover` as `undefined` while it isn't - * known yet so extraction can start early. - * - * `settled` turns true once the palette is final or after - * `COVER_PALETTE_WAIT_MS`, whichever comes first. - */ -export function useLegacyCoverPalette( - uri: string, - hasCover: boolean | undefined -): { palette: CoverPalette; settled: boolean } { - const theme = useThemeColors() - const isDark = useIsDark() - const key = uri ? withCoverImageSize(uri, 64) : "" - const [resolved, setResolved] = useState(() => ({ - key, - swatches: key ? cachedSwatches(key) : null, - })) - const [waitedKey, setWaitedKey] = useState(null) - - const swatches = - resolved.key === key ? resolved.swatches : key ? cachedSwatches(key) : null - - useEffect(() => { - if (!key || hasCover === false) return - let cancelled = false - const known = cachedSwatches(key) - const show = (next: CoverSwatches | null) => - setResolved((prev) => - prev.key === key && sameSwatches(prev.swatches, next) - ? prev - : { key, swatches: next } - ) - if (known !== undefined && swatchesByKey.has(key)) { - show(known) - return - } - - // Persisted swatches render immediately; refresh them in the background in - // case the cover changed. - const timer = - known === undefined - ? setTimeout( - () => !cancelled && setWaitedKey(key), - COVER_PALETTE_WAIT_MS - ) - : null - void extractSwatches(key).then((next) => { - if (!cancelled) show(next ?? known ?? null) - }) - return () => { - cancelled = true - if (timer) clearTimeout(timer) - } - }, [hasCover, key]) - - const palette = useMemo(() => { - const fromArt = - hasCover !== false && swatches - ? deriveCoverPalette(swatches, isDark) - : null - return fromArt ?? themeCoverPalette(theme, isDark) - }, [hasCover, isDark, swatches, theme]) - - return { - palette, - settled: - !key || hasCover === false || swatches !== undefined || waitedKey === key, - } -} +/** `react-native-image-colors` pipeline used when new artwork colors are off. */ +export const useLegacyCoverPalette = legacy.usePalette diff --git a/apps/mobile/lib/artwork-color-preference.ts b/apps/mobile/lib/artwork-color-preference.ts index 2651ddd..c59d684 100644 --- a/apps/mobile/lib/artwork-color-preference.ts +++ b/apps/mobile/lib/artwork-color-preference.ts @@ -3,8 +3,8 @@ import { useSyncExternalStore } from "react" const STORAGE_KEY = "otunes:artwork-colors" const listeners = new Set<() => void>() -let enabled = true -let loaded = false +// Undefined until storage has been read, so callers never act on a guess. +let enabled: boolean | undefined let loading: Promise | undefined function notify() { @@ -13,37 +13,40 @@ function notify() { function load() { return (loading ??= AsyncStorage.getItem(STORAGE_KEY) + .then((value) => value !== "false") + // Keep the default when local storage is unavailable. + .catch(() => true) .then((value) => { - enabled = value !== "false" - }) - .catch(() => { - // Keep the default when local storage is unavailable. - }) - .finally(() => { - loaded = true + enabled = value notify() })) } +void load() + function subscribe(listener: () => void) { listeners.add(listener) - void load() return () => { listeners.delete(listener) } } -/** Device preference, kept outside account data and the disposable query cache. */ +/** + * Device preference, kept outside account data and the disposable query cache. + * `undefined` until it has loaded. + */ export function useArtworkColorsEnabled() { - return useSyncExternalStore(subscribe, () => loaded && enabled, () => false) + return useSyncExternalStore( + subscribe, + () => enabled, + () => undefined + ) } -export function useArtworkColorPreferenceLoaded() { - return useSyncExternalStore(subscribe, () => loaded, () => false) -} - -export function artworkColorsEnabled() { - return loaded && enabled +/** Resolves with the preference once it has loaded. */ +export async function loadArtworkColorsEnabled() { + await load() + return enabled ?? true } export async function setArtworkColorsEnabled(value: boolean) { From 2427ca1cda42aad81ead4a9fbb810dce113c60d7 Mon Sep 17 00:00:00 2001 From: Joshua Higgins Date: Mon, 16 Nov 2026 21:43:57 -0500 Subject: [PATCH 4/4] fix(docker): run backend as non-root, keep env files out, never silently rotate auth keys (#93) --- .dockerignore | 11 +++++------ Dockerfile | 7 ++++++- docker/entrypoint.sh | 33 +++++++++++++++++++++++++++------ 3 files changed, 38 insertions(+), 13 deletions(-) diff --git a/.dockerignore b/.dockerignore index 3e1c66f..2330f90 100644 --- a/.dockerignore +++ b/.dockerignore @@ -54,12 +54,11 @@ playwright.config.* *~ *.log -# Environment variables (only commit template files) -.env -.env*.local -.env.development -.env.test -.env.production.local +# Environment variables, in any workspace. Next.js inlines NEXT_PUBLIC_* values +# into the bundle and the Convex CLI reads .env.local on deploy. +**/.env +**/.env.* +!**/.env.example # Docker configuration files (not needed inside build context) Dockerfile* diff --git a/Dockerfile b/Dockerfile index 543c78d..ae29c75 100644 --- a/Dockerfile +++ b/Dockerfile @@ -195,7 +195,12 @@ RUN node --version \ && ldd /convex/generate_key \ && ! ldd /convex/convex-local-backend /convex/generate_key | grep -q 'not found' -RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes +# The backend gets its own user so the web server cannot read the database or +# instance secret. It joins the otunes group to clean up the web server's HLS +# cache in /tmp/otunes. +RUN useradd --system --user-group --home-dir /app --shell /usr/sbin/nologin otunes \ + && useradd --system --user-group --groups otunes --create-home --home-dir /home/convex \ + --shell /usr/sbin/nologin convex COPY --from=convex-functions /app /opt/otunes/convex COPY docker/generate-auth-keys.mjs /opt/otunes/generate-auth-keys.mjs diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index c179357..39352e8 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -46,22 +46,34 @@ stop() { } trap 'stop; exit 0' TERM INT +as_convex=(setpriv --reuid=convex --regid=convex --init-groups env HOME=/home/convex) + convex_cli() { ( cd "$FUNCTIONS_DIR" unset CONVEX_DEPLOYMENT CONVEX_DEPLOY_KEY CONVEX_SELF_HOSTED_URL="$BACKEND_URL" \ CONVEX_SELF_HOSTED_ADMIN_KEY="$admin_key" \ - "$NODE" node_modules/convex/bin/main.js "$@" + "${as_convex[@]}" "$NODE" node_modules/convex/bin/main.js "$@" ) } -# Only root (the backend) may read the database and instance secret. +# Only the convex user may read the database and instance secret. Volumes from +# images that ran the backend as root are still owned by root, and +# read_credentials.sh generates a new instance secret if it cannot read the old one. mkdir -p "$CONVEX_DATA_DIR" +find "$CONVEX_DATA_DIR" \( ! -user convex -o ! -group convex \) \ + -exec chown -h convex:convex {} + chmod 700 "$CONVEX_DATA_DIR" +# The web server writes HLS streams here and a Convex cron deletes stale ones. +mkdir -p /tmp/otunes +chown otunes:otunes /tmp/otunes +chmod -R g+rwX /tmp/otunes +chmod g+s,o-rwx /tmp/otunes + log "Starting Convex backend" -(cd /convex && umask 077 && exec ./run_backend.sh) & +(cd /convex && umask 077 && exec "${as_convex[@]}" ./run_backend.sh) & backend_pid=$! for _ in $(seq 1 120); do @@ -80,17 +92,24 @@ if ! curl -fsS "$BACKEND_URL/version" >/dev/null 2>&1; then exit 1 fi -admin_key=$(cd /convex && ./generate_admin_key.sh) +admin_key=$(cd /convex && umask 077 && "${as_convex[@]}" ./generate_admin_key.sh) log "Deploying Convex functions" convex_cli deploy --typecheck disable --codegen disable -if [ -z "$(convex_cli env get JWKS 2>/dev/null || true)" ]; then +# `env get` exits 0 with no output when the variable is unset. Any other failure +# must not be read as "no keys": regenerating them signs every user out. +if ! jwks=$(convex_cli env get JWKS); then + log "Could not read Convex Auth signing keys" + stop + exit 1 +fi +if [ -z "$jwks" ]; then log "Generating Convex Auth signing keys" "$NODE" /opt/otunes/generate-auth-keys.mjs | convex_cli env set --force fi -unset admin_key +unset admin_key jwks log "Starting web server" ( @@ -100,6 +119,8 @@ log "Starting web server" # Server-side Convex helpers fall back to this at runtime. The browser bundle # is built without it, so browsers still derive their own URL. export NEXT_PUBLIC_CONVEX_URL="$BACKEND_URL" + # Lets the convex group member delete stale HLS streams. + umask 0002 exec setpriv --reuid=otunes --regid=otunes --init-groups \ "$NODE" apps/web/server.js ) &