From 931386dfe652bc8d04dcc0d4656e67816e1d8a4c Mon Sep 17 00:00:00 2001 From: zarzet <42882290+zarzet@users.noreply.github.com> Date: Sun, 25 Oct 2026 12:52:46 +0700 Subject: [PATCH] fix(link): keep playback usable while the desktop is out of reach A failed connection attempt now moves playback back to the phone, so songs picked meanwhile no longer wait for a desktop that cannot answer. A new song abandons a source still preparing on the phone's player instead of queueing behind the plugin's 30 second prepare timeout, so a local song plays at once after a network song that hangs. While the session cannot reach the desktop its Library songs check the server with a short connect before playing and fail within seconds instead of waiting the 20 second network timeout. --- .../link/client/link_client_controller.dart | 4 ++ .../link/client/link_client_library.dart | 8 ++++ .../link/features/link_remote_playback.dart | 24 ++++++++-- lib/services/music_playback_deck.dart | 18 +++++++- lib/services/network_storage_service.dart | 45 ++++++++++++++++++- test/link_client_controller_test.dart | 3 ++ test/link_remote_playback_test.dart | 16 +++++++ test/music_player_automix_test.dart | 14 ++++++ test/network_storage_service_test.dart | 19 ++++++++ test/support/link_client_fakes.dart | 7 +++ .../support/music_player_automix_harness.dart | 5 +++ 11 files changed, 158 insertions(+), 5 deletions(-) diff --git a/lib/services/link/client/link_client_controller.dart b/lib/services/link/client/link_client_controller.dart index 70838c801..30f5f136f 100644 --- a/lib/services/link/client/link_client_controller.dart +++ b/lib/services/link/client/link_client_controller.dart @@ -348,6 +348,10 @@ class LinkClientController extends Notifier { issue: session.issue, clearIssue: session.issue == null, ); + _library.setReachable( + session.server.connectionId, + reachable: session.issue != LinkSessionIssue.unreachable, + ); _updateDiscovery(); } diff --git a/lib/services/link/client/link_client_library.dart b/lib/services/link/client/link_client_library.dart index 4e8d2e7b7..173b150d3 100644 --- a/lib/services/link/client/link_client_library.dart +++ b/lib/services/link/client/link_client_library.dart @@ -19,6 +19,10 @@ abstract interface class LinkLibraryBridge { /// Points the connection at the desktop's new `https://host:port`. Future updateAddress(String connectionId, String address); + /// Whether the session reaches the desktop; its songs fail quickly while + /// it does not. + void setReachable(String connectionId, {required bool reachable}); + /// Adds the connection's root to Library and scans it, as the network /// storage screen does after adding a Subsonic server. Future addLibrarySource(NetworkConnection connection); @@ -81,6 +85,10 @@ class LinkNetworkLibraryBridge implements LinkLibraryBridge { ); } + @override + void setReachable(String connectionId, {required bool reachable}) => + _storage.setReachable(connectionId, reachable: reachable); + @override Future addLibrarySource(NetworkConnection connection) async { final source = await _ref diff --git a/lib/services/link/features/link_remote_playback.dart b/lib/services/link/features/link_remote_playback.dart index 63d215a65..7a5471599 100644 --- a/lib/services/link/features/link_remote_playback.dart +++ b/lib/services/link/features/link_remote_playback.dart @@ -8,6 +8,7 @@ import 'package:mornye/services/link/features/link_desktop_remote.dart'; import 'package:mornye/services/link/features/link_handoff.dart'; import 'package:mornye/services/link/features/link_phone_features.dart'; import 'package:mornye/services/link/features/link_track_resolver.dart'; +import 'package:mornye/services/link/link_client_api.dart'; import 'package:mornye/services/link/link_protocol.dart'; import 'package:mornye/services/playable_media.dart'; import 'package:mornye/services/remote_playback.dart'; @@ -18,12 +19,29 @@ final _log = AppLogger('LinkRemotePlayback'); /// Whether the paired desktop plays in this phone's place, as after Play on /// desktop. The phone takes over again after Continue on this phone, when /// the desktop is unpaired, and when the phone's own player starts, such as -/// for a Library song picked in the car. The notification and headset -/// drive the desktop meanwhile. +/// for a Library song picked in the car. It also takes over when the +/// desktop cannot be reached, so songs picked then play here instead of +/// waiting for it. The notification and headset drive the desktop +/// meanwhile. class LinkPlaysOnDesktop extends Notifier { @override bool build() { - if (ref.watch(linkPhoneClientProvider) == null) return false; + final client = ref.watch(linkPhoneClientProvider); + if (client == null) return false; + // A failed attempt goes from connecting to disconnected. The session + // pausing in the background disconnects a connected one instead, which + // keeps the desktop. + var connection = client.connectionState; + final connections = client.connectionStates.listen((next) { + final was = connection; + connection = next; + if (was == LinkConnectionState.connecting && + next == LinkConnectionState.disconnected && + state) { + state = false; + } + }); + ref.onDispose(connections.cancel); bool? playing; final subscription = ref .watch(musicPlayerRuntimeProvider) diff --git a/lib/services/music_playback_deck.dart b/lib/services/music_playback_deck.dart index 263f81109..4f1805609 100644 --- a/lib/services/music_playback_deck.dart +++ b/lib/services/music_playback_deck.dart @@ -207,6 +207,7 @@ class AudioplayersPlaybackDeck implements PlaybackDeck { bool _polling = false; bool _direct = false; bool _preparing = false; + Completer? _ordinaryPreparation; bool _disposed = false; int _token = 0; Duration? _duration; @@ -225,6 +226,11 @@ class AudioplayersPlaybackDeck implements PlaybackDeck { @override Future cancelPreparation() async { if (_preparing) await stop(); + final preparation = _ordinaryPreparation; + if (preparation == null) return; + _ordinaryPreparation = null; + preparation.complete(); + await _ordinary.release(); } @override @@ -392,7 +398,17 @@ class AudioplayersPlaybackDeck implements PlaybackDeck { // reuse the previous MediaPlayer or its pending preparation callbacks. await _ordinary.release(); _ordinaryError = null; - await _ordinary.setSource(source); + final abandoned = _ordinaryPreparation = Completer(); + try { + // A network source waits for its server, up to the plugin's prepare + // timeout; a newer song abandons it instead of queueing behind it. + await Future.any([_ordinary.setSource(source), abandoned.future]); + } finally { + if (identical(_ordinaryPreparation, abandoned)) { + _ordinaryPreparation = null; + } + } + if (abandoned.isCompleted) return; await _syncEqualizer(); } diff --git a/lib/services/network_storage_service.dart b/lib/services/network_storage_service.dart index 97cfee55e..bfe211d9d 100644 --- a/lib/services/network_storage_service.dart +++ b/lib/services/network_storage_service.dart @@ -240,6 +240,11 @@ class NetworkStorageService { final Future Function(String) _write; final Future Function(Uri) _ensureAccess; static const timeout = Duration(seconds: 20); + static const _probeTimeout = Duration(seconds: 3); + static const _probeReuse = Duration(seconds: 10); + + /// Connections known to be out of reach, with when a probe last failed. + final _unreachable = {}; Future>? _loading; List? _connections; Future? _server; @@ -379,7 +384,9 @@ class NetworkStorageService { } final path = networkPath(uri.pathSegments.join('/')); final c = await connection(uri.host); - await _ensureAccess(networkTarget(c, path)); + final target = networkTarget(c, path); + await _ensureAccess(target); + await _checkReachable(c.id, target); _server ??= HttpServer.bind(InternetAddress.loopbackIPv4, 0).then((server) { server.listen((request) => unawaited(_serve(request))); return server; @@ -399,6 +406,42 @@ class NetworkStorageService { return 'http://127.0.0.1:${server.port}/$token'; } + /// Marks connection [id] out of reach, as a paired Mornye Link desktop + /// whose session cannot connect, or reachable again. Songs of a marked + /// connection check its server briefly before playing instead of + /// waiting [timeout] for it. + void setReachable(String id, {required bool reachable}) { + if (reachable) { + _unreachable.remove(id); + } else { + _unreachable.putIfAbsent(id, () => null); + } + } + + /// Throws at once for a connection marked out of reach, unless its + /// server accepts a connection again. A failed check is reused briefly + /// so a song and its cover wait for one check. + Future _checkReachable(String id, Uri target) async { + if (!_unreachable.containsKey(id) || target.port == 0) return; + final failedAt = _unreachable[id]; + if (failedAt == null || DateTime.now().difference(failedAt) > _probeReuse) { + try { + final socket = await Socket.connect( + target.host, + target.port, + timeout: _probeTimeout, + ); + socket.destroy(); + _unreachable.remove(id); + return; + } on SocketException { + if (!_unreachable.containsKey(id)) return; + _unreachable[id] = DateTime.now(); + } + } + throw const SocketException('The server cannot be reached'); + } + Future _smb(NetworkConnection c, Uri target) async { await _ensureAccess(target); var expired = false; diff --git a/test/link_client_controller_test.dart b/test/link_client_controller_test.dart index 9bb3529fe..2dc58c060 100644 --- a/test/link_client_controller_test.dart +++ b/test/link_client_controller_test.dart @@ -220,6 +220,7 @@ void main() { await pumpEventQueue(); expect(harness.state.connection, LinkConnectionState.connected); expect(harness.browser.stopped, 1); + expect(harness.bridge.reachable[record.connectionId], isTrue); session.emit( LinkConnectionState.disconnected, @@ -228,6 +229,8 @@ void main() { await pumpEventQueue(); expect(harness.state.issue, LinkSessionIssue.unreachable); expect(harness.browser.started, 2); + // The desktop's songs fail quickly while it cannot be reached. + expect(harness.bridge.reachable[record.connectionId], isFalse); // Seen again at the same address: reconnect at once. harness.browser.resolve('a', '10.0.0.2'); diff --git a/test/link_remote_playback_test.dart b/test/link_remote_playback_test.dart index 8dd845546..cc6d34691 100644 --- a/test/link_remote_playback_test.dart +++ b/test/link_remote_playback_test.dart @@ -12,6 +12,7 @@ import 'package:mornye/services/link/features/link_phone_files.dart'; import 'package:mornye/services/link/features/link_remote_playback.dart'; import 'package:mornye/services/link/features/link_track_refs.dart'; import 'package:mornye/services/link/features/link_track_resolver.dart'; +import 'package:mornye/services/link/link_client_api.dart'; import 'package:mornye/services/link/link_protocol.dart'; import 'package:mornye/services/music_player_service.dart'; import 'package:mornye/services/remote_playback.dart'; @@ -351,6 +352,21 @@ void main() { expect(phone.read(linkPlaysOnDesktopProvider), isFalse); }); + test('the phone takes over when the desktop cannot be reached', () { + phone.listen(linkPlaysOnDesktopProvider, (_, _) {}); + phone.read(linkPlaysOnDesktopProvider.notifier).set(true); + // The session pauses in the background and reconnects on return. + client.setConnection(LinkConnectionState.disconnected); + client.setConnection(LinkConnectionState.connecting); + client.setConnection(LinkConnectionState.connected); + expect(phone.read(linkPlaysOnDesktopProvider), isTrue); + + client.setConnection(LinkConnectionState.disconnected); + client.setConnection(LinkConnectionState.connecting); + client.setConnection(LinkConnectionState.disconnected); + expect(phone.read(linkPlaysOnDesktopProvider), isFalse); + }); + test('the player screens follow the desktop only while it plays', () { phone.listen(linkRemotePlaybackProvider, (_, _) {}); expect(phone.read(linkRemotePlaybackProvider), isNull); diff --git a/test/music_player_automix_test.dart b/test/music_player_automix_test.dart index 3a6eb5f9a..0238ff6df 100644 --- a/test/music_player_automix_test.dart +++ b/test/music_player_automix_test.dart @@ -324,6 +324,20 @@ void main() { expect(native.resumedSources, ['/two.flac']); }); + test('a song still preparing does not hold up the next one', () async { + // A server that never answers keeps the first song preparing. + final gate = Completer(); + native.sourceGates['/one.flac'] = gate; + final first = handler.setQueueAndPlay(_tracks); + await _until(() => native.calls.any((c) => c.$2 == 'setSourceUrl')); + await handler.skipToNext(); + await first; + expect(handler.mediaItem.value?.id, 'two'); + expect(native.sources['music-player'], '/two.flac'); + expect(native.resumedSources, ['/two.flac']); + gate.complete(); + }); + for (final stop in [false, true]) { test( 'a pending prepare cannot resume after ${stop ? 'stop' : 'pause'}', diff --git a/test/network_storage_service_test.dart b/test/network_storage_service_test.dart index db6390313..925681f6f 100644 --- a/test/network_storage_service_test.dart +++ b/test/network_storage_service_test.dart @@ -337,6 +337,25 @@ void main() { }, ); + test('a server marked out of reach fails fast until it answers', () async { + final closed = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = closed.port; + await closed.close(); + await service.save(connection('http://127.0.0.1:$port/', id: 'gone')); + await service.save(connection('$origin/music/')); + final gone = NetworkStorageService.source('gone', 'A B.flac'); + final back = NetworkStorageService.source('server', 'A B.flac'); + + service.setReachable('gone', reachable: false); + await expectLater(service.resolve(gone), throwsA(isA())); + service.setReachable('gone', reachable: true); + expect(await service.resolve(gone), startsWith('http://127.0.0.1:')); + + // A server that answers again plays as usual. + service.setReachable('server', reachable: false); + expect(await service.resolve(back), startsWith('http://127.0.0.1:')); + }); + test( 'authenticated listing, proxy range seek, HEAD, and revocation', () async { diff --git a/test/support/link_client_fakes.dart b/test/support/link_client_fakes.dart index de547b80f..22f8a687c 100644 --- a/test/support/link_client_fakes.dart +++ b/test/support/link_client_fakes.dart @@ -148,10 +148,17 @@ class FakeLinkBridge implements LinkLibraryBridge { final connections = {}; final calls = []; + /// The latest reachability reported for each connection. + final reachable = {}; + @override Future connection(String connectionId) async => connections[connectionId]; + @override + void setReachable(String connectionId, {required bool reachable}) => + this.reachable[connectionId] = reachable; + @override Future saveConnection(NetworkConnection connection) async { connections[connection.id] = connection; diff --git a/test/support/music_player_automix_harness.dart b/test/support/music_player_automix_harness.dart index 05cf8faab..317363924 100644 --- a/test/support/music_player_automix_harness.dart +++ b/test/support/music_player_automix_harness.dart @@ -91,6 +91,7 @@ class AudioNative { final sourceContents = {}; final preparedContents = {}; final sourceGates = >{}; + final releases = {}; final sourceFailures = {}; final resumeFailures = {}; bool failResumeMethod = false; @@ -137,7 +138,10 @@ class AudioNative { ); case 'setSourceUrl': final source = args['url']! as String; + final released = releases[id]; await sourceGates[source]?.future; + // A release meanwhile reset the player and its old prepare. + if (releases[id] != released) return null; if (sourceFailures.contains(source)) { unawaited(error(id)); return null; @@ -178,6 +182,7 @@ class AudioNative { playing.remove(id); clocks[id]?.stop(); case 'release': + releases[id] = (releases[id] ?? 0) + 1; playing.remove(id); sources.remove(id); preparedContents.remove(id);