Skip to content

Support background media slot controls - #204

Merged
wizzomafizzo merged 3 commits into
mainfrom
issue-196-background-media
Jul 31, 2026
Merged

Support background media slot controls#204
wizzomafizzo merged 3 commits into
mainfrom
issue-196-background-media

Conversation

@wizzomafizzo

@wizzomafizzo wizzomafizzo commented Jul 31, 2026

Copy link
Copy Markdown
Member

Summary

  • gate slot-aware media support to Core 2.15.0 and preserve legacy primary-media behavior
  • synchronize independent primary/background active media and playlists without transition flicker
  • reuse playlist-aware Home cards with targeted transport and stop controls for both slots
  • preserve primary-only Create behavior and prevent media updates from resetting Home scroll

Follow-ups

Accurate native-audio pause behavior and per-slot playback status remain tracked in ZaparooProject/zaparoo-core#1172 and ZaparooProject/zaparoo-core#1173.

Ref #196

Summary by CodeRabbit

  • New Features

    • Added support for background media playback alongside primary playback.
    • Added playlist information and previous, play/pause, and next controls.
    • Added targeted stop controls and confirmation messaging for primary or background media.
    • Added feature gating for background playback on supported Core versions.
    • Added clearer media and playlist status displays with customizable labels.
  • Bug Fixes

    • Prevented background playback from replacing the primary now-playing display.
    • Preserved page scroll position during state updates.
    • Improved handling and feedback for failed media commands.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 19 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6cc554f9-92d6-4367-92ba-aef54af1a28d

📥 Commits

Reviewing files that changed from the base of the PR and between c3e94bd and 95c5a76.

📒 Files selected for processing (9)
  • src/__tests__/unit/components/ConnectionProvider.test.tsx
  • src/__tests__/unit/components/PageFrame.test.tsx
  • src/__tests__/unit/components/home/NowPlayingInfo.test.tsx
  • src/__tests__/unit/lib/coreApi.test.ts
  • src/components/ConnectionProvider.tsx
  • src/components/PageFrame.tsx
  • src/lib/coreApi.ts
  • src/lib/models.ts
  • src/lib/store.ts
📝 Walkthrough

Walkthrough

The PR adds primary and background media slots, playlist state, targeted Core API media commands, slot-aware connection reconciliation, playlist controls, feature gating, localized messages, and expanded tests. It also changes scroll restoration to run once per mount.

Changes

Slot-aware media and playlist flow

Layer / File(s) Summary
Media contracts, API, and store state
src/lib/models.ts, src/lib/coreApi.ts, src/lib/featureGates.ts, src/lib/store.ts, src/__tests__/unit/lib/*, src/__tests__/unit/featureGates.test.ts
The media models support slots and playlists. CoreApi.mediaControl sends targeted commands. The store maintains independent primary and background playback and playlist state.
Connection hydration and slot reconciliation
src/components/ConnectionProvider.tsx, src/__tests__/unit/components/ConnectionProvider.test.tsx
Connection handling hydrates both slots, applies playlist state, ignores unknown slots, guards stale responses, and delays stop reconciliation by 250 ms.
Playlist controls and background media UI
src/routes/-pages/Index.tsx, src/components/home/NowPlayingInfo.tsx, src/components/home/StopConfirmModal.tsx, src/translations/en-US.json, src/__tests__/integration/index-route.test.tsx, src/__tests__/unit/components/home/NowPlayingInfo.test.tsx, src/__tests__/unit/routes/create.index.test.tsx
The page renders slot-specific media and playlist controls. Commands support previous, play/pause, next, and stop actions. Background media is feature-gated and uses localized labels and errors.

Scroll restoration

Layer / File(s) Summary
One-time scroll restoration
src/components/PageFrame.tsx, src/__tests__/unit/components/PageFrame.test.tsx
PageFrameLayout restores saved scroll coordinates once per mount and preserves them during state-triggered rerenders.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant IndexPage
  participant CoreAPI
  participant StatusStore
  User->>IndexPage: Select playlist control
  IndexPage->>CoreAPI: Send media.control for selected slot
  CoreAPI-->>IndexPage: Resolve or reject command
  IndexPage->>StatusStore: Update local playlist playback state
  StatusStore-->>IndexPage: Render slot-specific media controls
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the pull request's main change: adding background media slot controls.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch issue-196-background-media

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jul 31, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.75362% with 15 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/components/ConnectionProvider.tsx 86.51% 12 Missing ⚠️
src/routes/-pages/Index.tsx 94.91% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
src/lib/models.ts (1)

345-349: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider a literal union for action.

action accepts any string. The only current caller sends "stop". A union documents the supported commands and catches typos at compile time.

♻️ Optional refactor
+export type MediaControlAction = "stop";
+
 export interface MediaControlRequest {
-  action: string;
+  action: MediaControlAction;
   slot?: MediaSlot;
   args?: Record<string, string>;
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/models.ts` around lines 345 - 349, Update the MediaControlRequest
interface’s action property to a string-literal union containing the currently
supported "stop" command, preserving the optional slot and args fields.
src/lib/store.ts (1)

230-241: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider one exported factory for empty playback state.

The empty PlayingResponse literal now appears four times in this file. src/components/ConnectionProvider.tsx Line 95 defines the same object as emptyPlaying(). Export a single factory from src/lib/models.ts or this file and reuse it in both places. This keeps the shape aligned if PlayingResponse gains required fields.

Also applies to: 470-479

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/store.ts` around lines 230 - 241, Centralize the empty
PlayingResponse construction in one exported factory, such as emptyPlaying,
instead of repeating the literal in the store and ConnectionProvider. Update the
backgroundPlaying initialization and all other empty playback-state usages in
the store, including the referenced later block, to call the factory, and reuse
that same exported factory from ConnectionProvider.
src/__tests__/unit/components/home/NowPlayingInfo.test.tsx (1)

138-154: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use accessible queries instead of DOM traversal for the control assertions.

Lines 142-148 use controls.parentElement and controls.querySelectorAll("button"). Use within(controls).getAllByRole("button") and compare accessible names. This keeps the assertion aligned with the accessible-query order and removes the dependency on the current DOM nesting.

♻️ Proposed refactor
       const controls = screen.getByRole("group", {
         name: "scan.playlistControls",
       });
       expect(controls).toBeInTheDocument();
-      expect(controls.parentElement).toContainElement(
-        screen.getByRole("heading", { name: "scan.backgroundMediaHeading" }),
-      );
       expect(
-        Array.from(controls.querySelectorAll("button")).map((button) =>
-          button.getAttribute("aria-label"),
-        ),
+        within(controls)
+          .getAllByRole("button")
+          .map((button) => button.getAttribute("aria-label")),
       ).toEqual([
         "scan.playlistPrevious",
         "scan.stopBackgroundMediaButton",
         "scan.playlistPause",
         "scan.playlistNext",
       ]);
+      expect(
+        screen.getByRole("heading", { name: "scan.backgroundMediaHeading" }),
+      ).toBeInTheDocument();

Add within to the test-utils import.

As per coding guidelines: "Use accessible queries in this order: getByRole, getByLabelText, getByText, then getByTestId".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/__tests__/unit/components/home/NowPlayingInfo.test.tsx` around lines 138
- 154, Update the control assertions in the NowPlayingInfo test to use
accessible queries: import within from the existing test utilities, locate the
heading independently with getByRole instead of controls.parentElement, and
retrieve buttons through within(controls).getAllByRole("button"), comparing
their accessible names in order rather than querying DOM elements and aria-label
attributes.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/__tests__/unit/components/PageFrame.test.tsx`:
- Line 239: Update the test around the “Update 0” interaction to import and
initialize userEvent with userEvent.setup(), make the test asynchronous, and
replace fireEvent.click with await user.click. Preserve the existing findByRole
assertion for the post-click rerender.

In `@src/components/ConnectionProvider.tsx`:
- Around line 348-358: Update the MediaStarted notification handling in
ConnectionProvider so clearStagedToken() runs only when the resolved slot is
"primary", matching the MediaStopped branch. Continue canceling reconciliation
and refreshing media state for every recognized slot.
- Around line 104-112: Update getMediaSlot to treat null as an alias for the
primary slot, alongside undefined, empty string, and "primary"; preserve the
existing "background" mapping and null return for other unsupported values so
primary playback state and media.started notifications are handled correctly.
- Line 827: Update fetchMediaState to increment mediaStateRequestToken and
capture that request’s token before awaiting CoreAPI.media(); compare it with
the current token before calling applyMediaState, skipping stale responses. Keep
token creation inside fetchMediaState so retry attempts receive fresh tokens,
and preserve refreshMediaState’s notification-driven invalidation behavior.

In `@src/components/PageFrame.tsx`:
- Line 51: Update PageFrame’s scroll-restoration logic around hasRestoredScroll
so it tracks the router history-entry identity and resets the guard whenever
that identity changes, including same-route parameter navigations for the
edit-mapping and device-settings routes. Add a test covering navigation between
parameter values on the same route and verify scroll restoration runs for the
new history entry.

In `@src/lib/coreApi.ts`:
- Around line 1508-1523: Update mediaControl to inspect the value resolved by
this.call and reject when it indicates cancellation ({ cancelled: true}),
matching the existing guard in run(). Preserve the current success resolution
for non-cancelled results and retain logMediaApiFailure handling for rejected
API calls.

---

Nitpick comments:
In `@src/__tests__/unit/components/home/NowPlayingInfo.test.tsx`:
- Around line 138-154: Update the control assertions in the NowPlayingInfo test
to use accessible queries: import within from the existing test utilities,
locate the heading independently with getByRole instead of
controls.parentElement, and retrieve buttons through
within(controls).getAllByRole("button"), comparing their accessible names in
order rather than querying DOM elements and aria-label attributes.

In `@src/lib/models.ts`:
- Around line 345-349: Update the MediaControlRequest interface’s action
property to a string-literal union containing the currently supported "stop"
command, preserving the optional slot and args fields.

In `@src/lib/store.ts`:
- Around line 230-241: Centralize the empty PlayingResponse construction in one
exported factory, such as emptyPlaying, instead of repeating the literal in the
store and ConnectionProvider. Update the backgroundPlaying initialization and
all other empty playback-state usages in the store, including the referenced
later block, to call the factory, and reuse that same exported factory from
ConnectionProvider.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 028bd08d-1fc6-462d-aacc-318397656694

📥 Commits

Reviewing files that changed from the base of the PR and between 2464002 and c3e94bd.

📒 Files selected for processing (19)
  • src/__tests__/integration/index-route.test.tsx
  • src/__tests__/unit/components/ConnectionProvider.test.tsx
  • src/__tests__/unit/components/PageFrame.test.tsx
  • src/__tests__/unit/components/home/NowPlayingInfo.test.tsx
  • src/__tests__/unit/coreApi.error-handling.test.ts
  • src/__tests__/unit/featureGates.test.ts
  • src/__tests__/unit/lib/coreApi.test.ts
  • src/__tests__/unit/lib/store.test.ts
  • src/__tests__/unit/routes/create.index.test.tsx
  • src/components/ConnectionProvider.tsx
  • src/components/PageFrame.tsx
  • src/components/home/NowPlayingInfo.tsx
  • src/components/home/StopConfirmModal.tsx
  • src/lib/coreApi.ts
  • src/lib/featureGates.ts
  • src/lib/models.ts
  • src/lib/store.ts
  • src/routes/-pages/Index.tsx
  • src/translations/en-US.json

Comment thread src/__tests__/unit/components/PageFrame.test.tsx Outdated
Comment thread src/components/ConnectionProvider.tsx
Comment thread src/components/ConnectionProvider.tsx
Comment thread src/components/ConnectionProvider.tsx
Comment thread src/components/PageFrame.tsx
Comment thread src/lib/coreApi.ts
@wizzomafizzo
wizzomafizzo merged commit 1cab35e into main Jul 31, 2026
6 checks passed
@wizzomafizzo
wizzomafizzo deleted the issue-196-background-media branch July 31, 2026 09:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant