From 1fa5f5478749a392dcaa18b5b5556017e17a24f6 Mon Sep 17 00:00:00 2001 From: Flavio Giacchetti Date: Thu, 24 Sep 2026 19:38:31 +0200 Subject: [PATCH 1/2] feat: add advanced identity diagnostics --- CHANGELOG.md | 2 + Fadrio.slnx | 1 + README.md | 9 ++ ROADMAP.md | 4 +- src/Fadrio.Cli/DiagnosticTextRenderer.cs | 94 +++++++++++++++++++ src/Fadrio.Cli/Program.cs | 26 +++-- .../DiagnosticTextRendererTests.cs | 80 ++++++++++++++++ .../Fadrio.Cli.Tests/Fadrio.Cli.Tests.csproj | 9 ++ 8 files changed, 216 insertions(+), 9 deletions(-) create mode 100644 src/Fadrio.Cli/DiagnosticTextRenderer.cs create mode 100644 tests/Fadrio.Cli.Tests/DiagnosticTextRendererTests.cs create mode 100644 tests/Fadrio.Cli.Tests/Fadrio.Cli.Tests.csproj diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f9ed04..13ffbce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,10 +9,12 @@ All notable changes will be documented here. The format follows [Keep a Changelo - `FAD-0202` Secure local PNG icon resolution with trusted XDG roots, bounded caching, and traversal, symlink, malformed-file, and size protections. - `FAD-0203` Flatpak-first canonical identity from bounded sandbox metadata and exported host desktop entries. - `FAD-0204` Optional Snap identity from corroborated wrapper metadata without invoking or depending on Snap tooling. +- `FAD-0206` Advanced `fadrioctl inspect` diagnostics for canonical identity evidence and per-session audio state, with deterministic share-safe redaction. ### Changed - `FAD-0205` XDG desktop-entry snapshots now refresh after debounced filesystem changes, advance a monotonic identity revision, and re-resolve active sessions once through the serialized mixer coordinator. +- `FAD-0206` Ordinary `fadrioctl apps` output no longer exposes process IDs; raw process and node details live in the explicit advanced inspector. ## [0.2.0-alpha.2] - 2026-09-13 diff --git a/Fadrio.slnx b/Fadrio.slnx index 41c2149..8fe0a1c 100644 --- a/Fadrio.slnx +++ b/Fadrio.slnx @@ -11,6 +11,7 @@ + diff --git a/README.md b/README.md index b74550f..d2adb63 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,15 @@ Inspect current logical applications: dotnet run --project src/Fadrio.Cli -- apps --watch ``` +Inspect one application's resolver evidence and raw audio sessions explicitly: + +```bash +dotnet run --project src/Fadrio.Cli -- inspect xdg:org.mozilla.firefox +dotnet run --project src/Fadrio.Cli -- inspect xdg:org.mozilla.firefox --redacted +``` + +Use `--redacted` before sharing output. The ordinary application list intentionally omits process IDs and raw node details. + Exercise the shared M0 command path: ```bash diff --git a/ROADMAP.md b/ROADMAP.md index bfa0c73..ba8cc2a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -148,7 +148,9 @@ Canonical ticket format: - [x] `FAD-0205` `P1` Add resolver cache invalidation and desktop-index refresh watching. - Scope: publish atomic XDG desktop-entry snapshots, debounce filesystem notifications, expose monotonic identity revisions, and re-resolve current sessions once when a new revision is observed. - Acceptance: create, change, delete, refresh, disposal, failure-retry, and revision-initialization tests pass without watcher callbacks mutating mixer state directly. -- [ ] `FAD-0206` `P1` Add inspectable advanced identity/session diagnostics. +- [x] `FAD-0206` `P1` Add inspectable advanced identity/session diagnostics. + - Scope: add an explicit CLI inspector for canonical identity, resolver evidence, and raw per-session audio details; keep raw node and process information out of the ordinary application list; support share-safe redaction. + - Acceptance: deterministic renderer tests cover identity evidence, session ordering, sensitive-value redaction, and hostile control characters; the full managed/native validation pipeline passes. - [ ] `REL-00003` `P0` Qualify one-row Firefox identity, icons, ambiguity safety, and fallback behavior. ## 0.3 — Persistence diff --git a/src/Fadrio.Cli/DiagnosticTextRenderer.cs b/src/Fadrio.Cli/DiagnosticTextRenderer.cs new file mode 100644 index 0000000..3bd34ef --- /dev/null +++ b/src/Fadrio.Cli/DiagnosticTextRenderer.cs @@ -0,0 +1,94 @@ +using System.Globalization; +using System.Text; +using Fadrio.Core; + +namespace Fadrio.Cli; + +public static class DiagnosticTextRenderer +{ + public static string Render(RuntimeApplication application, bool redacted) + { + ArgumentNullException.ThrowIfNull(application); + + var output = new StringBuilder(); + ApplicationIdentity identity = application.Identity; + Append(output, "Application", identity.DisplayName); + Append(output, "Canonical ID", identity.Id.Value); + Append(output, "Confidence", identity.Confidence.ToString()); + Append(output, "Desktop file", identity.DesktopFileId); + Append(output, "Executable", Redact(identity.ExecutablePath, redacted)); + Append(output, "Executable name", identity.ExecutableName); + Append(output, "Flatpak ID", identity.FlatpakId); + Append(output, "Snap ID", identity.SnapId); + Append(output, "Steam app ID", identity.SteamAppId); + Append(output, "Wine executable", Redact(identity.WineExecutable, redacted)); + Append(output, "Icon", identity.Icon?.Value); + + output.AppendLine(); + output.Append("Identity evidence (") + .Append(identity.Evidence.Count.ToString(CultureInfo.InvariantCulture)) + .AppendLine("): "); + if (identity.Evidence.Count == 0) + { + output.AppendLine(" (none)"); + } + else + { + foreach (IdentityEvidence evidence in identity.Evidence + .OrderBy(item => item.Kind) + .ThenBy(item => item.Value, StringComparer.Ordinal)) + { + bool sensitive = evidence.Kind is IdentityEvidenceKind.ProcessExecutable + or IdentityEvidenceKind.ProcessEnvironment; + string? value = sensitive ? Redact(evidence.Value, redacted) : evidence.Value; + output.Append(" - ") + .Append(evidence.Kind) + .Append(": ") + .Append(SingleLine(value)) + .Append(" — ") + .AppendLine(SingleLine(evidence.Description)); + } + } + + output.AppendLine(); + output.Append("Sessions (") + .Append(application.Sessions.Count.ToString(CultureInfo.InvariantCulture)) + .AppendLine("): "); + foreach (AudioSession session in application.Sessions.OrderBy(item => item.PipeWireNodeId)) + { + output.Append(" - Node ") + .Append(session.PipeWireNodeId.ToString(CultureInfo.InvariantCulture)) + .Append(" | session ") + .AppendLine(SingleLine(session.Id.Value)); + Append(output, " Process ID", Redact(session.ProcessId?.ToString(CultureInfo.InvariantCulture), redacted)); + Append(output, " Application name", session.ApplicationName); + Append(output, " PipeWire app ID", session.ApplicationId); + Append(output, " Process binary", session.ProcessBinary); + Append(output, " Media name", Redact(session.MediaName, redacted)); + Append(output, " Media role", session.MediaRole); + Append(output, " Output device", session.OutputDevice?.Value); + Append(output, " Volume", + string.Concat((session.Volume * 100f).ToString("0.#", CultureInfo.InvariantCulture), "%")); + Append(output, " Muted", session.Muted.ToString().ToLowerInvariant()); + Append(output, " Active", session.Active.ToString().ToLowerInvariant()); + } + + if (redacted) + { + output.AppendLine(); + output.AppendLine("Sensitive process paths, process IDs, media names, and process evidence were redacted."); + } + + return output.ToString(); + } + + private static string? Redact(string? value, bool redacted) => + redacted && !string.IsNullOrWhiteSpace(value) ? "(redacted)" : value; + + private static void Append(StringBuilder output, string label, string? value) => + output.Append(label).Append(": ").AppendLine(SingleLine(value)); + + private static string SingleLine(string? value) => string.IsNullOrWhiteSpace(value) + ? "(none)" + : value.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ').Trim(); +} diff --git a/src/Fadrio.Cli/Program.cs b/src/Fadrio.Cli/Program.cs index 75cfc09..084771b 100644 --- a/src/Fadrio.Cli/Program.cs +++ b/src/Fadrio.Cli/Program.cs @@ -1,10 +1,11 @@ using Fadrio.Application; +using Fadrio.Cli; using Fadrio.Infrastructure; using Fadrio.NativeInterop; using Fadrio.Platform.Linux; string command = args.FirstOrDefault() ?? "apps"; -if (command is not ("apps" or "set" or "mute" or "unmute")) +if (command is not ("apps" or "inspect" or "set" or "mute" or "unmute")) { PrintUsage(); return 2; @@ -12,7 +13,9 @@ bool watch = command == "apps" && args.Contains("--watch", StringComparer.Ordinal); if ((command == "set" && args.Length != 3) || - (command is "mute" or "unmute" && args.Length != 2)) + (command is "mute" or "unmute" && args.Length != 2) || + (command == "inspect" && (args.Length is < 2 or > 3 || + (args.Length == 3 && args[2] != "--redacted")))) { PrintUsage(); return 2; @@ -53,16 +56,21 @@ } else if (command != "apps") { - var mixerCommands = new MixerCommands(backend, coordinator); var applicationId = new Fadrio.Core.ApplicationId(args[1]); - if (coordinator.Current.Applications.All(application => application.Identity.Id != applicationId)) + Fadrio.Core.RuntimeApplication? application = coordinator.Current.Applications + .SingleOrDefault(candidate => candidate.Identity.Id == applicationId); + if (application is null) { Console.Error.WriteLine($"Application '{applicationId}' is not currently available."); shutdown.Cancel(); await IgnoreCancellationAsync(coordinatorTask); return 1; } - if (command == "set") + if (command == "inspect") + { + Console.Write(DiagnosticTextRenderer.Render(application, args.Contains("--redacted", StringComparer.Ordinal))); + } + else if (command == "set") { if (!float.TryParse(args[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float percentage) || @@ -71,13 +79,15 @@ Console.Error.WriteLine("Volume must be a number from 0 to 100."); return 2; } - await mixerCommands.SetApplicationVolumeAsync(applicationId, percentage / 100f, shutdown.Token); + await new MixerCommands(backend, coordinator) + .SetApplicationVolumeAsync(applicationId, percentage / 100f, shutdown.Token); Console.WriteLine($"Set {applicationId} to {percentage:0.#}% across all current sessions."); } else { bool muted = command == "mute"; - await mixerCommands.SetApplicationMuteAsync(applicationId, muted, shutdown.Token); + await new MixerCommands(backend, coordinator) + .SetApplicationMuteAsync(applicationId, muted, shutdown.Token); Console.WriteLine($"{(muted ? "Muted" : "Unmuted")} {applicationId} across all current sessions."); } } @@ -104,6 +114,7 @@ static void PrintUsage() { Console.Error.WriteLine("Usage:"); Console.Error.WriteLine(" fadrioctl apps [--watch]"); + Console.Error.WriteLine(" fadrioctl inspect [--redacted]"); Console.Error.WriteLine(" fadrioctl set <0-100>"); Console.Error.WriteLine(" fadrioctl mute "); Console.Error.WriteLine(" fadrioctl unmute "); @@ -139,7 +150,6 @@ static void Print(Fadrio.Core.MixerSnapshot snapshot) Console.WriteLine($"Canonical ID: {application.Identity.Id}"); Console.WriteLine($"Confidence: {application.Identity.Confidence}"); Console.WriteLine($"Sessions: {application.Sessions.Count}"); - Console.WriteLine($"Processes: {string.Join(", ", application.Sessions.Select(session => session.ProcessId).Where(id => id.HasValue).Select(id => id!.Value))}"); string percentage = (application.EffectiveVolume * 100f).ToString("0", System.Globalization.CultureInfo.InvariantCulture); Console.WriteLine($"Volume: {percentage}%{(application.IsMixedVolume ? " (mixed)" : string.Empty)}"); Console.WriteLine($"Muted: {application.IsMuted.ToString().ToLowerInvariant()}"); diff --git a/tests/Fadrio.Cli.Tests/DiagnosticTextRendererTests.cs b/tests/Fadrio.Cli.Tests/DiagnosticTextRendererTests.cs new file mode 100644 index 0000000..3e6537b --- /dev/null +++ b/tests/Fadrio.Cli.Tests/DiagnosticTextRendererTests.cs @@ -0,0 +1,80 @@ +using Fadrio.Core; + +namespace Fadrio.Cli.Tests; + +public sealed class DiagnosticTextRendererTests +{ + [Fact] + public void RenderIncludesIdentityEvidenceAndOrderedSessionDetails() + { + string output = DiagnosticTextRenderer.Render(Application(), redacted: false); + + Assert.Contains("Canonical ID: xdg:org.mozilla.firefox", output, StringComparison.Ordinal); + Assert.Contains("Executable: /usr/lib/firefox/firefox", output, StringComparison.Ordinal); + Assert.Contains("DesktopEntry: org.mozilla.firefox — Exact desktop match.", output, StringComparison.Ordinal); + Assert.Contains("ProcessExecutable: /usr/lib/firefox/firefox", output, StringComparison.Ordinal); + Assert.True(output.IndexOf("Node 81", StringComparison.Ordinal) < output.IndexOf("Node 94", StringComparison.Ordinal)); + Assert.Contains("Media name: YouTube", output, StringComparison.Ordinal); + Assert.Contains("Volume: 52%", output, StringComparison.Ordinal); + } + + [Fact] + public void RedactedRenderHidesSensitiveProcessAndMediaValues() + { + string output = DiagnosticTextRenderer.Render(Application(), redacted: true); + + Assert.DoesNotContain("/usr/lib/firefox/firefox", output, StringComparison.Ordinal); + Assert.DoesNotContain("Process ID: 4242", output, StringComparison.Ordinal); + Assert.DoesNotContain("YouTube", output, StringComparison.Ordinal); + Assert.Contains("Process ID: (redacted)", output, StringComparison.Ordinal); + Assert.Contains("Media name: (redacted)", output, StringComparison.Ordinal); + Assert.Contains("process evidence were redacted", output, StringComparison.Ordinal); + } + + [Fact] + public void RenderFlattensControlCharactersFromExternalMetadata() + { + RuntimeApplication application = Application("Firefox\nforged heading"); + + string output = DiagnosticTextRenderer.Render(application, redacted: false); + + Assert.Contains("Application: Firefox forged heading", output, StringComparison.Ordinal); + Assert.DoesNotContain("Firefox\nforged", output, StringComparison.Ordinal); + } + + private static RuntimeApplication Application(string displayName = "Firefox") => new( + new ApplicationIdentity + { + Id = new("xdg:org.mozilla.firefox"), + DisplayName = displayName, + DesktopFileId = "org.mozilla.firefox", + ExecutablePath = "/usr/lib/firefox/firefox", + ExecutableName = "firefox", + Icon = new("/usr/share/icons/firefox.png"), + Confidence = IdentityConfidence.High, + Evidence = + [ + new(IdentityEvidenceKind.DesktopEntry, "org.mozilla.firefox", "Exact desktop match."), + new(IdentityEvidenceKind.ProcessExecutable, "/usr/lib/firefox/firefox", "Resolved from proc.") + ] + }, + [ + Session("second", 94, 5151, "WebRTC"), + Session("first", 81, 4242, "YouTube") + ]); + + private static AudioSession Session(string id, uint node, int process, string media) => new() + { + Id = new(id), + PipeWireNodeId = node, + ProcessId = process, + ApplicationName = "Firefox", + ApplicationId = "org.mozilla.firefox", + ProcessBinary = "firefox", + MediaName = media, + MediaRole = "Music", + OutputDevice = new("speakers"), + Volume = 0.52f, + Active = true + }; +} diff --git a/tests/Fadrio.Cli.Tests/Fadrio.Cli.Tests.csproj b/tests/Fadrio.Cli.Tests/Fadrio.Cli.Tests.csproj new file mode 100644 index 0000000..9eda7ab --- /dev/null +++ b/tests/Fadrio.Cli.Tests/Fadrio.Cli.Tests.csproj @@ -0,0 +1,9 @@ + + true + + + + + + + From ab077c60afc886d1c072f1f0e1d4cf2f0a42b995 Mon Sep 17 00:00:00 2001 From: Flavio Giacchetti Date: Thu, 24 Sep 2026 19:44:34 +0200 Subject: [PATCH 2/2] fix: qualify Firefox identity against live runtime --- CHANGELOG.md | 2 + ROADMAP.md | 4 +- docs/development/qualifying-browser.md | 19 ++- .../XdgDesktopApplicationIndex.cs | 8 +- .../ApplicationResolver.cs | 6 +- .../DesktopEntryTests.cs | 25 +++- .../FirefoxIdentityQualificationTests.cs | 119 ++++++++++++++++++ 7 files changed, 177 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13ffbce..5629861 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,13 @@ All notable changes will be documented here. The format follows [Keep a Changelo - `FAD-0203` Flatpak-first canonical identity from bounded sandbox metadata and exported host desktop entries. - `FAD-0204` Optional Snap identity from corroborated wrapper metadata without invoking or depending on Snap tooling. - `FAD-0206` Advanced `fadrioctl inspect` diagnostics for canonical identity evidence and per-session audio state, with deterministic share-safe redaction. +- `REL-00003` Firefox qualification covers the installed `firefox-bin` runtime, one-row grouping, visible launcher/icon preference, ambiguity safety, and executable fallback. ### Changed - `FAD-0205` XDG desktop-entry snapshots now refresh after debounced filesystem changes, advance a monotonic identity revision, and re-resolve active sessions once through the serialized mixer coordinator. - `FAD-0206` Ordinary `fadrioctl apps` output no longer exposes process IDs; raw process and node details live in the explicit advanced inspector. +- `REL-00003` Visible XDG launchers now take precedence over hidden helpers when both have strong executable evidence; common `-bin` runtime names can match their launcher executable. ## [0.2.0-alpha.2] - 2026-09-13 diff --git a/ROADMAP.md b/ROADMAP.md index ba8cc2a..e981fee 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -151,7 +151,9 @@ Canonical ticket format: - [x] `FAD-0206` `P1` Add inspectable advanced identity/session diagnostics. - Scope: add an explicit CLI inspector for canonical identity, resolver evidence, and raw per-session audio details; keep raw node and process information out of the ordinary application list; support share-safe redaction. - Acceptance: deterministic renderer tests cover identity evidence, session ordering, sensitive-value redaction, and hostile control characters; the full managed/native validation pipeline passes. -- [ ] `REL-00003` `P0` Qualify one-row Firefox identity, icons, ambiguity safety, and fallback behavior. +- [x] `REL-00003` `P0` Qualify one-row Firefox identity, icons, ambiguity safety, and fallback behavior. + - Scope: qualify the installed Firefox `firefox-bin` runtime against visible and hidden XDG launchers, plus deterministic ambiguity and missing-metadata fallbacks. + - Acceptance: two real Firefox 156.0.1 streams group into one `xdg:firefox` row with the installed icon and High confidence; fixtures preserve safe executable fallback when visible candidates conflict or metadata is absent. ## 0.3 — Persistence diff --git a/docs/development/qualifying-browser.md b/docs/development/qualifying-browser.md index c1b4f6a..0adeaf3 100644 --- a/docs/development/qualifying-browser.md +++ b/docs/development/qualifying-browser.md @@ -1,6 +1,6 @@ # Qualifying browser identity -`FAD-0012` qualifies browser multi-stream identity. Firefox-shaped fixtures retain deterministic coverage, while the real-browser observation uses the Brave installation available on the development host. +`FAD-0012` qualifies browser multi-stream identity. Firefox-shaped fixtures retain deterministic coverage, and `REL-00003` adds a real Firefox observation plus explicit ambiguity and fallback cases. ## Automated evidence @@ -36,6 +36,23 @@ The following observation passed on 2026-09-04: The fixture creates no network request and uses a very low-gain oscillator. Qualification output excludes runtime PIDs, profile paths, private browsing data, media titles, full command lines, and environment dumps. +## Real Firefox observation + +The following observation passed on 2026-09-24: + +- Zorin OS 18.1, Wayland GNOME session; +- Firefox 156.0.1 from the system package; +- PipeWire 1.0.5; +- two isolated Firefox profiles playing the repository's local low-gain Web Audio fixture; +- one `Firefox` application with canonical ID `xdg:firefox`, High confidence, the installed `firefox` icon, and two sessions; +- the real `/usr/lib/firefox/firefox-bin` runtime was reconciled with the visible `firefox.desktop` launcher; +- a hidden user-created launcher with an exact runtime path did not displace the visible application identity; +- setting volume to 35%, muting, and unmuting reached both Firefox sessions; +- terminating one profile reduced the row to one session, and its replacement rejoined the same identity as the second session; +- redacted advanced diagnostics exposed the evidence chain and both raw audio nodes without publishing process IDs, profile paths, or media names. + +Deterministic fixtures also prove that competing visible Firefox launchers fall back to executable identity rather than guessing, and that missing desktop metadata produces the same stable executable fallback. + ## Reproduction checklist 1. Launch two isolated browser profiles against `tests/fixtures/browser/brave-audio.html` with autoplay allowed. diff --git a/src/Fadrio.Infrastructure/XdgDesktopApplicationIndex.cs b/src/Fadrio.Infrastructure/XdgDesktopApplicationIndex.cs index 68e0f1d..e0d163a 100644 --- a/src/Fadrio.Infrastructure/XdgDesktopApplicationIndex.cs +++ b/src/Fadrio.Infrastructure/XdgDesktopApplicationIndex.cs @@ -61,7 +61,7 @@ public IReadOnlyList FindByExecutable(string executable DesktopApplicationEntry[] entries = Volatile.Read(ref _entries); DesktopApplicationEntry[] matches = entries.Where(entry => entry.Executable is not null && (PathEquals(entry.Executable, executablePath) || - Path.GetFileName(entry.Executable).Equals(name, StringComparison.OrdinalIgnoreCase))) + ExecutableNamesMatch(Path.GetFileName(entry.Executable), name))) .ToArray(); DesktopApplicationEntry[] visible = matches.Where(entry => !entry.NoDisplay).ToArray(); // A hidden URL handler can share its application's executable and icon. @@ -209,4 +209,10 @@ private void RefreshSafely() private static bool PathEquals(string left, string right) => Path.IsPathRooted(left) && Path.IsPathRooted(right) && Path.GetFullPath(left).Equals(Path.GetFullPath(right), StringComparison.Ordinal); + + private static bool ExecutableNamesMatch(string left, string right) => + NormalizeExecutableName(left).Equals(NormalizeExecutableName(right), StringComparison.OrdinalIgnoreCase); + + private static string NormalizeExecutableName(string value) => + value.EndsWith("-bin", StringComparison.OrdinalIgnoreCase) ? value[..^4] : value; } diff --git a/src/Fadrio.Platform.Linux/ApplicationResolver.cs b/src/Fadrio.Platform.Linux/ApplicationResolver.cs index beb5917..f3ceb95 100644 --- a/src/Fadrio.Platform.Linux/ApplicationResolver.cs +++ b/src/Fadrio.Platform.Linux/ApplicationResolver.cs @@ -144,7 +144,11 @@ await steamApplications.TryResolveAsync(session, process, cancellationToken).Con AddIdMatches(desktopApplications.FindById(iconName), 70, "PipeWire icon name"); } - DesktopCandidate[] ranked = candidates.Values + IEnumerable eligibleCandidates = candidates.Values.Any(candidate => + !candidate.Entry.NoDisplay && candidate.Score >= MinimumDesktopScore) + ? candidates.Values.Where(candidate => !candidate.Entry.NoDisplay) + : candidates.Values; + DesktopCandidate[] ranked = eligibleCandidates .OrderByDescending(candidate => candidate.Score) .ThenBy(candidate => candidate.Entry.Id, StringComparer.OrdinalIgnoreCase) .ToArray(); diff --git a/tests/Fadrio.Infrastructure.Tests/DesktopEntryTests.cs b/tests/Fadrio.Infrastructure.Tests/DesktopEntryTests.cs index 34bf6b5..e6849c1 100644 --- a/tests/Fadrio.Infrastructure.Tests/DesktopEntryTests.cs +++ b/tests/Fadrio.Infrastructure.Tests/DesktopEntryTests.cs @@ -32,6 +32,26 @@ public void IndexMatchesExecutableBasename() Assert.Equal("Firefox", Assert.Single(index.FindByExecutable("/different/path/firefox")).Name); } + [Fact] + public void IndexMatchesCommonBinRuntimeSuffixWithoutDiscardingAmbiguity() + { + using var directory = new TemporaryDirectory(); + File.WriteAllText( + System.IO.Path.Combine(directory.Path, "firefox.desktop"), + DesktopEntry("Firefox", "/usr/bin/firefox")); + File.WriteAllText( + System.IO.Path.Combine(directory.Path, "hidden-firefox.desktop"), + DesktopEntry("Hidden Firefox", "/usr/lib/firefox/firefox-bin", noDisplay: true)); + using var index = new XdgDesktopApplicationIndex([directory.Path], watchForChanges: false); + + IReadOnlyList matches = + index.FindByExecutable("/usr/lib/firefox/firefox-bin"); + + Assert.Equal(2, matches.Count); + Assert.Contains(matches, entry => entry.Id == "firefox"); + Assert.Contains(matches, entry => entry.Id == "hidden-firefox"); + } + [Fact] public void IndexMatchesDesktopIdWithOrWithoutSuffix() { @@ -135,8 +155,9 @@ public async Task DisposeCancelsQueuedRefreshAndRejectsManualRefresh() Assert.Throws(index.Refresh); } - private static string DesktopEntry(string name, string executable) => - $"[Desktop Entry]{Environment.NewLine}Name={name}{Environment.NewLine}Exec={executable}{Environment.NewLine}"; + private static string DesktopEntry(string name, string executable, bool noDisplay = false) => + $"[Desktop Entry]{Environment.NewLine}Name={name}{Environment.NewLine}Exec={executable}{Environment.NewLine}" + + $"NoDisplay={noDisplay.ToString().ToLowerInvariant()}{Environment.NewLine}"; private static async Task WaitForRevisionAsync( XdgDesktopApplicationIndex index, diff --git a/tests/Fadrio.Platform.Linux.Tests/FirefoxIdentityQualificationTests.cs b/tests/Fadrio.Platform.Linux.Tests/FirefoxIdentityQualificationTests.cs index 8c50fed..6b06ef6 100644 --- a/tests/Fadrio.Platform.Linux.Tests/FirefoxIdentityQualificationTests.cs +++ b/tests/Fadrio.Platform.Linux.Tests/FirefoxIdentityQualificationTests.cs @@ -64,6 +64,85 @@ await coordinator.ApplyAsync( Assert.Equal([71u, 73u], recreated.Sessions.Select(session => session.PipeWireNodeId).Order()); } + [Fact] + public async Task VisibleFirefoxLauncherWinsOverExactHiddenHelperForBinRuntime() + { + using var directory = new TemporaryDirectory(); + directory.WriteDesktop("firefox.desktop", "Firefox", "/usr/bin/firefox", "firefox", noDisplay: false); + directory.WriteDesktop( + "userapp-Firefox-NTRKV3.desktop", + "Firefox", + "/usr/lib/firefox/firefox-bin", + icon: null, + noDisplay: true); + using var index = new XdgDesktopApplicationIndex([directory.Path], watchForChanges: false); + var resolver = new ApplicationResolver( + new FixtureProcessProvider(new Dictionary + { + [4201] = new(4201, "/usr/lib/firefox/firefox-bin", ["firefox-bin"]), + [4202] = new(4202, "/usr/lib/firefox/firefox-bin", ["firefox-bin"]) + }), + index); + var coordinator = new MixerStateCoordinator(resolver); + + await coordinator.ApplyAsync( + new SessionAdded(1, LiveFirefoxSession("one", 81, 4201)), + TestContext.Current.CancellationToken); + await coordinator.ApplyAsync( + new SessionAdded(1, LiveFirefoxSession("two", 82, 4202)), + TestContext.Current.CancellationToken); + + RuntimeApplication firefox = Assert.Single(coordinator.Current.Applications); + Assert.Equal(new ApplicationId("xdg:firefox"), firefox.Identity.Id); + Assert.Equal("firefox", firefox.Identity.Icon?.Value); + Assert.Equal(IdentityConfidence.High, firefox.Identity.Confidence); + Assert.Equal(2, firefox.Sessions.Count); + } + + [Fact] + public async Task MultipleVisibleFirefoxCandidatesFallBackInsteadOfGuessing() + { + using var directory = new TemporaryDirectory(); + directory.WriteDesktop("firefox.desktop", "Firefox", "/usr/bin/firefox", "firefox", noDisplay: false); + directory.WriteDesktop("firefox-alt.desktop", "Alternate Firefox", "/opt/firefox", "firefox-alt", noDisplay: false); + using var index = new XdgDesktopApplicationIndex([directory.Path], watchForChanges: false); + var resolver = new ApplicationResolver( + new FixtureProcessProvider(new Dictionary + { + [4301] = new(4301, "/usr/lib/firefox/firefox-bin", ["firefox-bin"]) + }), + index); + + ApplicationIdentity identity = await resolver.ResolveAsync( + LiveFirefoxSession("ambiguous", 91, 4301), + TestContext.Current.CancellationToken); + + Assert.Equal(new ApplicationId("exe:/usr/lib/firefox/firefox-bin"), identity.Id); + Assert.Equal(IdentityConfidence.Medium, identity.Confidence); + Assert.Contains(identity.Evidence, evidence => evidence.Kind == IdentityEvidenceKind.ConflictingEvidence); + } + + [Fact] + public async Task MissingDesktopMetadataFallsBackToStableExecutableIdentity() + { + using var directory = new TemporaryDirectory(); + using var index = new XdgDesktopApplicationIndex([directory.Path], watchForChanges: false); + var resolver = new ApplicationResolver( + new FixtureProcessProvider(new Dictionary + { + [4401] = new(4401, "/usr/lib/firefox/firefox-bin", ["firefox-bin"]) + }), + index); + + ApplicationIdentity identity = await resolver.ResolveAsync( + LiveFirefoxSession("fallback", 101, 4401), + TestContext.Current.CancellationToken); + + Assert.Equal(new ApplicationId("exe:/usr/lib/firefox/firefox-bin"), identity.Id); + Assert.Equal("firefox-bin", identity.DisplayName); + Assert.Equal(IdentityConfidence.Medium, identity.Confidence); + } + private static AudioSession FirefoxSession(string id, uint nodeId, int processId, string mediaName) => new() { Id = new(id), @@ -79,6 +158,18 @@ await coordinator.ApplyAsync( Active = true, }; + private static AudioSession LiveFirefoxSession(string id, uint nodeId, int processId) => new() + { + Id = new(id), + PipeWireNodeId = nodeId, + ProcessId = processId, + ApplicationName = "Firefox", + ProcessBinary = "firefox-bin", + MediaName = "AudioStream", + Volume = 1f, + Active = true, + }; + private sealed class FixtureProcessProvider(IReadOnlyDictionary processes) : IProcessMetadataProvider { @@ -121,4 +212,32 @@ public ValueTask SetStreamMuteAsync( public ValueTask DisposeAsync() => ValueTask.CompletedTask; } + + private sealed class TemporaryDirectory : IDisposable + { + public TemporaryDirectory() + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), $"fadrio-firefox-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Path); + } + + public string Path { get; } + + public void WriteDesktop( + string fileName, + string name, + string executable, + string? icon, + bool noDisplay) + { + string iconLine = icon is null ? string.Empty : $"Icon={icon}{Environment.NewLine}"; + File.WriteAllText( + System.IO.Path.Combine(Path, fileName), + $"[Desktop Entry]{Environment.NewLine}Name={name}{Environment.NewLine}" + + $"Exec={executable}{Environment.NewLine}{iconLine}" + + $"NoDisplay={noDisplay.ToString().ToLowerInvariant()}{Environment.NewLine}"); + } + + public void Dispose() => Directory.Delete(Path, recursive: true); + } }