Skip to content

Commit b16b5d0

Browse files
Preserve explicit Firefox media targets across browser restarts
1 parent 587bf0a commit b16b5d0

5 files changed

Lines changed: 255 additions & 19 deletions

File tree

‎apps/decksmith-daemon/src/shared_native_media.rs‎

Lines changed: 84 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,35 @@ use std::{
1616
type Result<T> = std::result::Result<T, &'static str>;
1717
const PATH: &str = "/org/mpris/MediaPlayer2";
1818
const PLAYER: &str = "org.mpris.MediaPlayer2.Player";
19+
fn dbus_instance_suffix(suffix: &str) -> bool {
20+
let Some((bus, connection)) = suffix.strip_prefix('_').and_then(|s| s.split_once('_')) else {
21+
return false;
22+
};
23+
!bus.is_empty()
24+
&& !connection.is_empty()
25+
&& bus.bytes().all(|b| b.is_ascii_digit())
26+
&& connection.bytes().all(|b| b.is_ascii_digit())
27+
}
1928
fn family(name: &str) -> &str {
2029
name.rsplit_once(".instance")
21-
.filter(|(_, suffix)| !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()))
30+
.filter(|(_, suffix)| {
31+
!suffix.is_empty()
32+
&& (suffix.bytes().all(|b| b.is_ascii_digit()) || dbus_instance_suffix(suffix))
33+
})
2234
.map_or(name, |(prefix, _)| prefix)
2335
}
36+
fn selector_family(selector: &str) -> &str {
37+
// Retain layouts saved before Firefox's D-Bus-derived suffix was recognized.
38+
selector
39+
.rsplit_once(".instance")
40+
.filter(|(_, suffix)| dbus_instance_suffix(suffix))
41+
.map_or(selector, |(prefix, _)| prefix)
42+
}
43+
fn matches_selector(name: &str, selector: &str) -> bool {
44+
selector == crate::saved_native::DEFAULT_MEDIA
45+
|| name == selector
46+
|| family(name) == selector_family(selector)
47+
}
2448
fn previous_selection() -> Option<Session> {
2549
#[derive(Deserialize)]
2650
#[serde(deny_unknown_fields)]
@@ -52,11 +76,7 @@ fn selection(
5276
) -> Option<Session> {
5377
candidates
5478
.iter()
55-
.filter(|c| {
56-
selector == crate::saved_native::DEFAULT_MEDIA
57-
|| c.name == selector
58-
|| family(&c.name) == selector
59-
})
79+
.filter(|c| matches_selector(&c.name, selector))
6080
.min_by_key(|c| {
6181
(
6282
preferred.is_none_or(|p| p.name != c.name || p.owner != c.owner),
@@ -92,9 +112,7 @@ impl Session {
92112
if !(crate::launch::valid_player(&self.selector)
93113
|| self.selector == crate::saved_native::DEFAULT_MEDIA)
94114
|| !crate::launch::valid_player(&self.name)
95-
|| !(self.selector == crate::saved_native::DEFAULT_MEDIA
96-
|| family(&self.name) == self.selector
97-
|| self.selector == self.name)
115+
|| !matches_selector(&self.name, &self.selector)
98116
|| self.owner.len() > 255
99117
|| zbus::names::UniqueName::try_from(self.owner.as_str()).is_err()
100118
{
@@ -316,11 +334,10 @@ impl NativeBackend {
316334
if std::time::Instant::now() >= deadline {
317335
break;
318336
}
319-
if !selectors.iter().any(|selector| {
320-
selector == crate::saved_native::DEFAULT_MEDIA
321-
|| selector == &name
322-
|| selector == family(&name)
323-
}) {
337+
if !selectors
338+
.iter()
339+
.any(|selector| matches_selector(&name, selector))
340+
{
324341
continue;
325342
}
326343
let Ok(owner) = bus.owner(&name) else {
@@ -555,6 +572,59 @@ mod tests {
555572
);
556573
}
557574
#[test]
575+
fn firefox_saved_choices_survive_restart_without_cross_app_fallback() {
576+
let candidates = vec![
577+
Candidate {
578+
name: "org.mpris.MediaPlayer2.firefox.instance_1_955".into(),
579+
owner: ":1.955".into(),
580+
status: "Paused".into(),
581+
},
582+
Candidate {
583+
name: "org.mpris.MediaPlayer2.music".into(),
584+
owner: ":1.22".into(),
585+
status: "Playing".into(),
586+
},
587+
];
588+
for selector in [
589+
"org.mpris.MediaPlayer2.firefox",
590+
"org.mpris.MediaPlayer2.firefox.instance_1_162",
591+
] {
592+
let selected = selection(selector, &candidates, None).unwrap();
593+
selected.validate().unwrap();
594+
assert_eq!(selected.selector, selector);
595+
assert_eq!(selected.owner, ":1.955");
596+
let (bus, _) = fixture();
597+
*bus.owner.borrow_mut() = ":1.955".into();
598+
execute(&bus, &selected, "play_pause", || true).unwrap();
599+
assert_eq!(
600+
*bus.writes.borrow(),
601+
vec![(":1.955".into(), "PlayPause".into())]
602+
);
603+
bus.writes.borrow_mut().clear();
604+
bus.replace.set(true);
605+
assert!(execute(&bus, &selected, "play_pause", || true).is_err());
606+
assert!(bus.writes.borrow().is_empty());
607+
assert!(selection(selector, &candidates[1..], None).is_none());
608+
}
609+
}
610+
#[test]
611+
fn instance_suffixes_are_bounded_and_existing_exact_choices_stay_exact() {
612+
let base = "org.mpris.MediaPlayer2.firefox";
613+
assert_eq!(family(&format!("{base}.instance_1_162")), base);
614+
for suffix in ["_1", "_1_2_extra", "__2", "_1_", "_named", "_١_٢"] {
615+
let name = format!("{base}.instance{suffix}");
616+
assert_eq!(family(&name), name);
617+
assert_eq!(selector_family(&name), name);
618+
}
619+
let exact = "org.mpris.MediaPlayer2.brave.instance123";
620+
assert_eq!(family(exact), "org.mpris.MediaPlayer2.brave");
621+
assert_eq!(selector_family(exact), exact);
622+
assert!(!matches_selector(
623+
"org.mpris.MediaPlayer2.brave.instance456",
624+
exact
625+
));
626+
}
627+
#[test]
558628
fn daily_factory_requires_no_media_or_audio_connection_at_startup() {
559629
let backend = NativeBackend::connect_daily().unwrap();
560630
assert!(backend.daily && backend.bus.is_none());

‎apps/decksmith-studio/media.py‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,12 @@ def valid_player(value):
1111
return isinstance(value,str) and len(value)<=255 and re.fullmatch(r'org\.mpris\.MediaPlayer2\.[A-Za-z_][A-Za-z0-9_-]*(?:\.[A-Za-z_][A-Za-z0-9_-]*)*',value) is not None
1212

1313
def family(name):
14-
return re.sub(r'\.instance[0-9]+$','',name)
14+
return re.sub(r'\.instance(?:[0-9]+|_[0-9]+_[0-9]+)$','',name)
15+
16+
def selector_family(target):
17+
# Older Firefox choices stored its transient D-Bus instance name. Accept
18+
# those saves without rewriting layouts or broadening another app's scope.
19+
return re.sub(r'\.instance_[0-9]+_[0-9]+$','',target)
1520

1621
def choices():
1722
bus=Gio.bus_get_sync(Gio.BusType.SESSION,None)
@@ -24,6 +29,7 @@ def choices():
2429
return sorted(result.values(),key=lambda item:item['label'].casefold())
2530

2631
def players(bus,target=None):
32+
if target is not None:target=selector_family(target)
2733
names=bus.call_sync('org.freedesktop.DBus','/org/freedesktop/DBus','org.freedesktop.DBus','ListNames',None,None,Gio.DBusCallFlags.NONE,200,None).unpack()[0]
2834
result=[]
2935
for name in sorted(n for n in names if n.startswith('org.mpris.MediaPlayer2.') and (target is None or family(n)==target or n==target))[:8]:

‎apps/decksmith-studio/test_media.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,47 @@
11
import unittest
2+
from unittest.mock import patch
23
from media import choose,execute,IFACE
34
from gi.repository import GLib
45

56
def props(state):
67
return {'PlaybackStatus':state,'CanControl':True,'CanPause':True,'CanPlay':True,'CanGoNext':True,'CanGoPrevious':True}
78

89
class MediaTests(unittest.TestCase):
10+
def test_firefox_choice_survives_restart_and_never_selects_unrelated_player(self):
11+
from media import choices
12+
class Bus:
13+
def __init__(self):
14+
self.firefox='org.mpris.MediaPlayer2.firefox.instance_1_162';self.sent=[]
15+
def call_sync(self,name,path,interface,method,*args):
16+
if method=='ListNames':return GLib.Variant('(as)',(([self.firefox] if self.firefox else [])+['org.mpris.MediaPlayer2.music'],))
17+
if method=='GetAll':return GLib.Variant('(a{sv})',({k:GLib.Variant('s' if isinstance(v,str) else 'b',v) for k,v in props('Paused' if name==self.firefox else 'Playing').items()},))
18+
if method=='Get':return GLib.Variant('(v)',(GLib.Variant('s','Firefox' if name==self.firefox else 'Music'),))
19+
if method=='GetNameOwner':return GLib.Variant('(s)',(':1.955' if args[0].unpack()[0]==self.firefox else ':1.22',))
20+
self.sent.append((name,method))
21+
bus=Bus();legacy=bus.firefox
22+
with patch('media.Gio.bus_get_sync',return_value=bus):
23+
saved=next(c['id'] for c in choices() if c['label']=='Firefox')
24+
self.assertEqual(saved,'org.mpris.MediaPlayer2.firefox')
25+
bus.firefox='org.mpris.MediaPlayer2.firefox.instance_1_955'
26+
for target in (saved,legacy):
27+
bus.sent=[];execute('play_pause',bus,target=target)
28+
self.assertEqual(bus.sent,[(':1.955','PlayPause')])
29+
bus.firefox=None;bus.sent=[]
30+
for target in (saved,legacy):
31+
with self.assertRaises(ValueError):execute('play_pause',bus,target=target)
32+
self.assertEqual(bus.sent,[])
33+
34+
def test_instance_normalization_is_bounded_and_preserves_existing_exact_choices(self):
35+
from media import family,selector_family
36+
base='org.mpris.MediaPlayer2.firefox'
37+
self.assertEqual(family(base+'.instance_1_162'),base)
38+
for suffix in ('.instance_1','.instance_1_2_extra','.instance__2','.instance_1_','.instance_named','.instance_١_٢'):
39+
self.assertEqual(family(base+suffix),base+suffix)
40+
self.assertEqual(selector_family(base+suffix),base+suffix)
41+
exact='org.mpris.MediaPlayer2.brave.instance123'
42+
self.assertEqual(family(exact),'org.mpris.MediaPlayer2.brave')
43+
self.assertEqual(selector_family(exact),exact)
44+
945
def test_prefers_playing_and_does_not_skip_to_another_player_for_unsupported_action(self):
1046
playing=props('Playing');playing['CanGoNext']=False
1147
candidates=[('org.mpris.MediaPlayer2.a',props('Paused')),('org.mpris.MediaPlayer2.z',playing)]

‎docs/ROADMAP.md‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,17 @@ change system routing.
77

88
## Current work — Monday, October 19
99

10-
**Physical acceptance remains first.** Resume the approved Ubuntu 26.04 VM
11-
hardware session on the workstation when the maintainer is ready. Preserve the
12-
desktop build and saved layouts, confirm before handing both Decks to the guest,
13-
and restore normal controls afterward. Debian validation remains independent.
10+
**Physical acceptance remains first.** The October 19 updated Ubuntu VM trial
11+
passed paired physical controls, native editor/copying, real output/app/microphone
12+
checks, GNOME pages/lock and USB redelivery recovery. It exposed an explicit
13+
Firefox player choice that stops resolving after browser restart; Automatic
14+
controls still work. A bounded editor/native-adapter correction passes local
15+
media tests and CI-toolchain Rust tests/linting on the AI server. The maintainer
16+
approved publishing the reviewed source and building/verifying new signed
17+
candidates; corrected-package physical retest remains required.
18+
Do not promote Ubuntu support yet. Fedora's original build, both Decks, exact
19+
audio settings and all 492 backed-up saved files were restored/verified, and the
20+
VM shut down normally. Debian validation remains independent.
1421
The October 17 corrected signed Debian candidate `1.5.2-1272d3a4d717` passed native
1522
package/editor/recovery and actual GNOME 48.7 integration without guest metadata
1623
changes; Ubuntu's earlier signed candidate passed actual GNOME 50.1 integration.

‎docs/checkpoints/2026-10-17-ubuntu-debian-support.md‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,122 @@
11
# Ubuntu support and parallel Debian validation — October 17, 2026
22

3+
## October 19 physical Ubuntu trial — Firefox restart correction required
4+
5+
The maintainer approved using the workstation's existing Ubuntu VM and temporarily
6+
passing both Decks, Schiit Magni and Wave:3 to it. The guest was updated before
7+
hardware testing: Ubuntu 26.04, kernel `7.0.0-38-generic`, GNOME Shell 50.1 and
8+
Firefox Snap 158.0-2 (revision 9057). A normal reboot, clean package audit, no
9+
remaining apt upgrades and no remaining Snap refreshes were verified.
10+
11+
The unchanged signed Ubuntu candidate **1.5.2-d4a17d906de7** was re-admitted against
12+
its original source/provenance and archive SHA-256
13+
`81d55bba2cea7433c638b52b17b56e9ed539ef1ba09d26068791433e47fb3a40`, then installed
14+
as the normal guest user. No signed runtime file was patched for acceptance.
15+
An offline byte-verified VM recovery image and complete guest/desktop backups
16+
preceded changes. Native GNOME integration and scoped USB access were configured
17+
in the owned guest; normal Fedora controls were restored after the trial.
18+
19+
Human checks, with saved-profile/device/audio observations, passed:
20+
21+
- Independent physical pages and brightness, clear Plus keys/touch strip and
22+
MK.2 keys, real Magni output volume/mute from both Decks, Firefox app volume,
23+
moving output/app gauges and Automatic Firefox pause/resume.
24+
- Real Wave:3 holds on both Decks, overlapping holds until the last release,
25+
Mute on either Deck cancelling all holds, fresh holds afterward, microphone
26+
volume/gauge activity, normal unmute surviving page changes, and page changes
27+
cancelling push-to-talk.
28+
- Unplugging either Deck while it held the mic returning the mic to Muted,
29+
continued operation of the connected partner, recovered pages/controls and
30+
fresh holds without stale unmute after reconnection.
31+
- Native editor label/checkmark saves, copying an output key from MK.2 to Plus
32+
and a media key from Plus to MK.2, and executing both copied physical actions.
33+
Sequential device-setting saves/readbacks ultimately confirmed MK.2 40% and
34+
Plus 60%; those values survived lock/unlock. Earlier human confirmations did
35+
not match saved readbacks, so they were not used alone to pass this check.
36+
- Quit Decksmith blanking all keys and the full touch strip, normal service
37+
restart, GNOME Files/default pages versus different Firefox-assigned pages on
38+
each Deck, and lock blanking/input suppression/unlock recovery. Both Locked
39+
and unlocked source states were recorded.
40+
41+
**Confirmed failure:** saving an explicit Firefox player choice retains
42+
`org.mpris.MediaPlayer2.firefox.instance_1_<connection>`. Restarting Firefox changes
43+
that identifier. The saved Plus third-dial action then stops pausing/resuming,
44+
while Automatic MK.2 media controls still work. The maintainer reproduced the
45+
physical failure; native discovery independently showed the old selector no
46+
longer resolves and the replacement Firefox player is present. This is a
47+
candidate compatibility defect, not a failed USB transfer or an unrelated-player
48+
fallback. It blocks accepting this candidate for Ubuntu support.
49+
50+
A local correction recognizes Firefox's bounded numeric D-Bus instance suffix
51+
in both the editor's player picker and native adapter. New choices use a stable
52+
app family; previously saved Firefox instance choices resolve the replacement
53+
instance without rewriting layouts. Existing exact numeric-instance choices for
54+
other naming schemes retain their old behavior. Missing explicit targets still
55+
fail without controlling another app, and dispatch still pins/revalidates the
56+
unique owner.
57+
58+
The correction passed 348 Rust tests (six existing ignored), all-target/all-feature
59+
strict Clippy and formatting with the existing CI-pinned Rust 1.97.1, plus six
60+
focused Python media tests. Tests cover old/new Firefox names, missing-player
61+
isolation, malformed suffixes and late owner replacement. A separate private
62+
Python helper resolved the actual restarted Firefox player using both the old
63+
saved choice and new stable choice. The signed candidate itself remained
64+
unchanged; these results do **not** pass corrected-candidate physical acceptance.
65+
The first server check used distribution Rust 1.99: Rust tests passed, but strict
66+
lint stopped on two unchanged `fetch_update` deprecations. That outcome is
67+
retained separately; no unrelated code or warning policy was changed. The
68+
matching 1.97.1 attempt passed.
69+
70+
The five-minute unlocked idle sample measured **2.89% of one CPU core** and a
71+
sampled service memory peak of 56,823,808 bytes. Scope is the guest background
72+
service and its audio helpers; it excludes the editor, observation helper and
73+
host VM emulator. Playback was paused, both Decks connected and observation
74+
polling stopped. A temporary guest idle/suspend inhibitor kept the session awake
75+
without changing desktop preferences. A separate five-minute mixed-activity
76+
sample measured 9.37% and 100,196,352 bytes; it included page/microphone actions
77+
and USB recovery, so it is not a continuously connected playback benchmark or
78+
an input/display-latency measurement.
79+
80+
Test-environment limits and retained evidence:
81+
82+
- The initial VM was terminated when host controls stopped; subsequent startup
83+
verified its QEMU process was outside Decksmith's service group. The VM also
84+
needed additional USB port capacity and temporary, automatically reverted
85+
access to only the two approved audio USB nodes. Failed attempts and safe
86+
rollbacks are retained rather than counted as product acceptance.
87+
- Both physical reconnects changed the host USB address and required an explicit
88+
QEMU routing refresh. Decksmith was not restarted for those recoveries. This
89+
establishes app recovery after guest USB redelivery, not automatic VM USB
90+
rerouting or Ubuntu bare-metal suspend/resume qualification.
91+
- One device-retirement warning was recorded during physical unplug. The mic
92+
and surviving/reconnected Decks recovered; no actual suspend trial occurred.
93+
Retain this diagnostic observation separately from suspend acceptance.
94+
- An evidence-copy attempt encountered a root-owned OS-update record. Existing
95+
OS-update evidence was already preserved; a separate readable-file collector
96+
captured 46 guest outcomes/logs. This did not prevent hardware restoration.
97+
98+
Cleanup restored original guest profiles/Auto-Lock and disabled/inactive startup,
99+
retained the updated guest and signed candidate with recovery copies, restored the
100+
original VM definition, and powered the guest off normally. Fedora's original
101+
`1.5.2-46ed033e0491` build and both services are active. Original audio volumes,
102+
mutes and defaults were verified exactly, including Wave:3 muted; temporary USB
103+
permissions were removed. All **492** original desktop saved settings/artwork
104+
files compare byte-for-byte with the pre-test backup. The maintainer confirmed
105+
normal Fedora pages and controls on both Decks afterward.
106+
107+
Private evidence: `outputs/ubuntu-physical-20261019/physical-acceptance.json`,
108+
`host-restoration-verification.json`, `host-saved-data-comparison.json`,
109+
`guest-final-power-state.json`, guest snapshots/traces, exact candidate admission,
110+
resource outcomes and pinned server regression logs. No release, support
111+
promotion, desktop replacement, commit or push occurred in this trial. Next:
112+
publish the correction and build/verify signed Ubuntu, Debian and Fedora
113+
candidates under the maintainer's subsequent explicit approval (source/build
114+
attestations only, no release publication or desktop update), repeat explicit
115+
Firefox restart on the corrected Ubuntu
116+
package, then complete remaining lifecycle/distribution qualification. Broader
117+
editor-state work remains after physical acceptance.
118+
119+
3120
## Debian GNOME 48 correction — unchanged signed candidate acceptance passed
4121

5122
Following explicit maintainer approval, the source extension declaration now

0 commit comments

Comments
 (0)