Files

345 lines
22 KiB
Markdown

# CrossSound Game Bar widget: handoff
Written 2026-10-28 by the Claude session on the Mac that built the native Windows CrossSound app and its
local API. It is for the Claude Code instance on the Windows PC that will rebuild this widget. Read it
first. Everything here was checked against the code; where something is unverified, it says so.
## 1. What you're building
An Xbox Game Bar widget (UWP, C#, XAML, `Microsoft.Gaming.XboxGameBar` NuGet) that remote-controls
**CrossSound**, the user's SoundCloud desktop player. The widget never talks to SoundCloud. It only talks
to CrossSound's **local HTTP API on `http://127.0.0.1:8963`**, which already does everything: playback
state, commands, cover art, and a proxy to SoundCloud for Discover and Search.
Two different apps can be the server, and the widget has to work with both:
| Server | Where | Notes |
|---|---|---|
| **Native CrossSound** (C++, the current one) | user's clone `C:\Users\RedLintu16\Documents\WindowsC\CrossSound`, built to `C:\Users\RedLintu16\Documents\WindowsC\CrossSound\build-release\src\App\CrossSound.exe` (since main 1b2612d; older builds went to `WindowsC\build-release`) | Branch `main` (1b2612d or later) has everything below, `/appearance` included. Builds from before 2026-10-28 ignore `toggle`. |
| **Electron CrossSound** (older) | installed app | Same routes, same ports. Whichever app starts first owns port 8963; the native one takes the port over within 5 s of the Electron one quitting. |
The full server-side contract, with every route, its Electron source and the native behavior, is in the
user's clone at **`docs/notes/api.md`**. The server code is `src/CrossSoundCore/local_api.cpp` and
`local_api_library.cpp`. **Don't change the server from here.** It lives in another repo and has its own
tests. If the widget needs something the API doesn't have, write it down in section 8 for the user.
## 2. The PC and the project
- Windows 11 IoT LTSC 26100, Visual Studio 2026 Community (UWP workload), Git for Windows.
- Current project: `CrossSoundWidget.sln` / `CrossSoundWidget.csproj` (classic UWP csproj, .NET Native,
`Microsoft.NETCore.UniversalWindowsPlatform` 6.2.14, `Microsoft.Gaming.XboxGameBar` 7.3.2511061,
target 10.0.26100, min 10.0.17763).
- Package identity: `Name="RedLintu16.CrossSoundWidget"`, `Publisher="CN=RedLintu16"`. The installed
package family name is **`RedLintu16.CrossSoundWidget_jdapqa6743p5g`**.
- Game Bar extension: `AppExtension Id="CrossSoundMedia"` (must equal the id `App.xaml.cs` checks),
`PublicFolder="GameBar"`, a standard widget 280x420, vertical resize 360 to 620.
- Capabilities: `internetClient`, `privateNetworkClientServer`.
- The repo also committed `bin/`, `obj/` and `BundleArtifacts/` (build output). Add them to `.gitignore`
in the rebuild.
### Loopback: the #1 reason "it can't connect"
A UWP app can't reach `127.0.0.1` unless its package is **loopback-exempt**. Visual Studio grants that only
while you debug with F5 (project Properties > Debug > "Allow local network loopback"). Run it any other way
and it's blocked, which is why the old widget "worked once". The user ran this on 2026-10-28 and it fixed
the connection:
```powershell
# PowerShell as Administrator
$pfn = (Get-AppxPackage *CrossSoundWidget*).PackageFamilyName
CheckNetIsolation LoopbackExempt -a -n="$pfn"
CheckNetIsolation LoopbackExempt -s
```
The exemption belongs to the **package family name**. Keep the Identity `Name` and the signing
certificate's `Publisher` the same and it survives rebuilds. Change either, or uninstall the package, and
the name changes and the command has to run again. Give the user that command whenever it changes.
`curl.exe` working while the widget can't connect almost always means a missing exemption.
### Testing
- First check the API with curl (any shell): `curl.exe -s http://127.0.0.1:8963/ping` should return
`{"ok":true,"app":"CrossSound","service":"crosssound-api"}`, and `curl.exe -s http://127.0.0.1:8963/state`
should return the snapshot.
- Who owns the port (PowerShell):
`Get-Process -Id (Get-NetTCPConnection -LocalPort 8963 -State Listen).OwningProcess | Select Id,Path`
- A command, exactly as the widget sends it (PowerShell):
`Invoke-RestMethod -Method Post -Uri http://127.0.0.1:8963/command -ContentType 'application/json' -Body '{"action":"toggle"}'`
should return `ok : True` **and toggle real playback on the user's speakers**. Ask before you send playback
commands while the user is listening.
- The widget only runs inside Game Bar (Win+G). Deploy from VS (F5 or Deploy), then open it from the Game
Bar widget menu.
## 3. The API (port 8963)
Every answer has CORS (`Access-Control-Allow-Origin: *`). JSON is `application/json; charset=utf-8`,
`Cache-Control: no-store`. The query string is ignored when matching a route, so `/artwork?v=123` is
`/artwork`. A trailing `/` is ignored too.
### GET `/state`: the snapshot
`{}` (an empty object) when nothing is loaded. Otherwise, in this order:
```json
{
"isPlaying": true,
"isLiked": false,
"title": "Take It out On Me",
"artist": "Some Artist",
"artwork": "https://i1.sndcdn.com/artworks-...-large.jpg",
"position": 83,
"currentTimeStr": "1:23",
"durationStr": "3:37",
"shuffle": false,
"autoplay": true,
"repeat": "none",
"volume": 1,
"queue": [ { "id": 435702420, "title": "...", "artist": "...", "artwork": "...", "duration": 217000 } ],
"queueIndex": 0
}
```
- `position` is **whole seconds**. `duration` inside `queue[]` is **milliseconds**. The exact length of the
current track is `queue[queueIndex].duration`; `durationStr` is m:ss.
- `artwork` can be `""`. `repeat` is always `"none"` on native (it has no repeat mode). `volume` (0..1) is
native-only. The Electron server may leave fields out, so treat every field as optional.
- `queue[].id` is a number when numeric, otherwise a string.
### GET `/events`: live updates (Server-Sent Events)
- `text/event-stream`, `Transfer-Encoding: chunked`. Frames are `data: <snapshot JSON>\n\n`, with the same
snapshot as `/state`.
- One frame **on connect** (even `{}`), then one **only when something changes**: play/pause, track, like,
shuffle/autoplay, queue, volume, or the position jumping 3 s or more from where the clock would be (a
seek, a stall). **There is no frame per second.** Interpolate the clock yourself from `position` plus
the time since the frame arrived, while `isPlaying`.
- It can go quiet for minutes. Expect no heartbeat. Ignore lines starting with `:`, `event:` and `id:` to
be safe.
- When the app quits, the stream ends. Reconnect with a back-off (for example 1, 2, 5, 10 s), and also wait
after a **clean** end or a non-200 answer, or you'll loop hot.
### GET `/artwork`: the current cover
- The server fetches the current track's cover at 500x500 and returns the bytes (`image/jpeg` if
SoundCloud gives no type), with `Cache-Control: public, max-age=60`.
- Errors come back empty: 404 when there's no artwork, 400 for a bad URL, 502 when the fetch failed.
- **That header is a trap:** the URL never changes, so after a track change the HTTP cache can hand you
the old cover for up to a minute. Add something that changes with the track, for example
`/artwork?v=<hash of the snapshot's artwork URL>`. The server ignores the query.
- Only refetch when the snapshot's `artwork` value changes, not on every frame.
### GET `/appearance` and `/appearance/events`: the app's theme (native only)
The look CrossSound draws with, so the widget can match a custom theme. Native only: the Electron server
answers 404, so fall back to the fixed RedWhite palette (section 6). It also answers 503
`{"error":"appearance not available"}` if the app has none to give.
```json
{
"mode": "system",
"isDark": false,
"accent": "#FF0000",
"font": "Raleway",
"density": "standard",
"palette": { "red": "#FF0000", "redHover": "#FF6459", "bg": "#FFFFFF", "text": "#FF0000", "redClear": "#FF000000", "…": "…" },
"light": { "…every token…" },
"dark": { "…every token…" }
}
```
- `mode` is the user's choice (`system` / `light` / `dark`). `isDark` is what the app draws right now
(System resolved against Windows). `palette` is the token set for the current look, which is `light` or
`dark`.
- Colors are `#RRGGBB`, or `#RRGGBBAA` when not opaque (`redClear` is `#FF000000`). The palette is exactly
what CrossSound draws: the accent, CrossSound's own forced colors (all text, icons and status colors are
the accent red, so `text`, `textMuted`, `contentText` and `iconInactive` all equal `red`), then the
user's per-token overrides on top (since main 60f442a).
- **XAML reads alpha first (`#AARRGGBB`), the API sends it last (`#RRGGBBAA`).** Parse the hex yourself
into `Color.FromArgb(a, r, g, b)`; never hand the string to XAML. The washes (`redTint` `#FF00000F`,
`redSoft`, `redBorder`, `field`, `fieldFocus`, the `*Soft` status colors) are translucent red meant to sit
over `bg`. Checked live on 2026-10-28: light `redTint` `#FF00000F`, `field` `#FF000012`; dark `redTint`
`#FF000014`, `onRed` `#000000`.
- Token names are RedWhiteUI's: `red`, `redHover`, `redTint`, `redSoft`, `redBorder`, `onRed`, `bg`,
`bgSoft`, `bg2`, `text`, `textMuted`, `textSubtle`, `iconInactive`, `contentText`, `hair`, `hairStrong`,
`danger`, `dangerSoft`, `success`, `successSoft`, `warn`, `warnSoft`, `info`, `infoSoft`, `redHoverInk`,
`hoverColor`, `redClear`, `field`, `fieldFocus`, `line`. Key on the names, not the order, and ignore names
you don't know. `red` is the accent, the color every "red" in section 6 means.
- `font` is a name only. If it isn't Raleway or `System` (Segoe UI), the widget can't load it (the font
file is outside the sandbox), so fall back to Raleway.
- **`/appearance/events`** is an event stream like `/events`: one `data: <appearance>` frame on connect,
then one whenever the look changes (the Themes page, the dark-mode setting, Windows switching
light/dark under System). It is a **separate stream** from `/events` on purpose; `/events` never carries
it. Same rules as `/events`: chunked, no heartbeat, reconnect with back-off.
- The Game Bar has its own light/dark (`XboxGameBarWidget.RequestedTheme`). The user decides which wins;
until they say otherwise, follow the app's `isDark` when `/appearance` answers, and Game Bar's theme
when it doesn't.
### POST commands
Answers are `{"ok":true}`, HTTP 200, and come back at once, before the action has finished. Watch
`/events` for the result. A body that isn't JSON is read as `{}`.
`POST /command` with `{"action": "...", ...data}` is the generic route. Actions, as native maps them:
| action | data | effect |
|---|---|---|
| `toggle` or `playpause` | none | play/pause |
| `play` | none | play (absolute; never pauses) |
| `pause` | none | pause (absolute) |
| `next` (or `skip`) | none | next track |
| `prev` (or `previous`) | none | previous track |
| `seek` | `position` (seconds, can be fractional), or `seconds`, `positionMs`, `ms` | seek, clamped into the track |
| `like` | none | like/unlike the current track |
| `shuffle` / `autoplay` | none | toggle |
| `volume` | `value` (0..1) | set the volume (native only; Electron ignores it) |
| `play` | `urn` (`"soundcloud:tracks:N"`, or a bare numeric id) | play that track alone as the queue. `"soundcloud:playlists:N"` plays the playlist. |
| `play` | `url` (a soundcloud.com permalink) | play that playlist/station/album; a track link plays the track |
| `play` | `id` (number) | play that track |
| `playIndex` | `index` | jump to that spot in the current queue |
| `playPlaylist` | `id` (number) | play a playlist from the top |
| `playQueue` | `urns` (array) | play those tracks, in that order |
Unknown actions still answer 200 (and are logged). A missing `action` is 400 `{"error":"missing \"action\""}`.
The same actions also have their own routes (DockDoor and Stream Deck use them): `POST /playpause`,
`/next`, `/previous`, `/like`, `/shuffle`, `/autoplay`, `/repeat` (no body), `/volume {value}`,
`/seek {seconds}`, `/play {id|url|urn}`, `/play-index {index}`, `/play-playlist {id}`,
`/play-queue {urns}`. The widget can use either style.
### GET library routes: SoundCloud's own JSON, passed through raw
When signed out, every one of these answers **503** `{"error":"SoundCloud client not ready — sign in first"}`.
Show "Sign in to CrossSound" for that, not "Nothing to show". A failed SoundCloud call is 500
`{"error":"API error <status>: ..."}`, and a bad parameter is 400.
| Route | Returns |
|---|---|
| `/discover/history?limit=20` | `{collection:[…]}` of recently played contexts; the real card is usually under `row.system_playlist`, otherwise the row itself |
| `/discover/mixed?limit=10` | `{collection:[{title, items:{collection:[cards]}}]}`, the Discover shelves |
| `/search?q=…&kind=tracks\|playlists\|albums\|users&limit=20` | `{collection:[…], next_href, …}` |
| `/tracks/batch?ids=1,2,3` | a **bare array** of full tracks (the server chunks by 50). Use it to turn a card's stub `tracks:[{id}]` into rows. |
| `/track/:id` | one track |
| `/playlist/:id` | one playlist, with `tracks` (may be stubs; hydrate with `/tracks/batch`) |
| `/playlists?limit=50` | the user's playlists (array) |
| `/station/:urn/tracks?limit=50`, `/station?urn=…\|url=…` | a station's tracks |
| `/resolve?url=…` | SoundCloud's resolve of a link |
| `/user/:id`, `/user/:id/tracks`, `/playlists`, `/albums`, `/likes`, `/reposts`, `/popular`, `/spotlight` | a user and their lists (`popular` = most played first, `spotlight` = top 3) |
Card fields worth reading (what the old widget learned): title from `title`, `short_title`, `username`,
`full_name`; subtitle from `short_description`, `description`, `user.username`; art from
`calculated_artwork_url`, `artwork_url`, `avatar_url` (swap `-large` for `-t200x200` or `-t500x500` for a
sharper image); `permalink_url`; `urn` (else `id`); `kind` (`track`, `playlist`, `system-playlist`, `user`,
…). Track rows: `user.username` or `publisher_metadata.artist`, `duration` (ms), `playback_count`.
**SoundCloud ids pass 2^31**: use `long`, and format with `InvariantCulture`.
## 4. What's wrong with the current widget
Line numbers are in `MediaWidget.xaml.cs` / `MediaWidget.xaml` at commit 0396c41.
1. **The Game Bar object is never received.** `App.xaml.cs:47` navigates with the widget as the
*navigation parameter*, but `MediaWidget_Loaded` (`:96`) reads `this.Tag`, which nobody sets. So
`_widget` is always null: the Game Bar theme is never applied, theme changes are never heard, and no
other widget API (visibility, settings, pinning) can be used. Get it from
`OnNavigatedTo(e) => e.Parameter as XboxGameBarWidget`.
2. **Seeking spams the player.** `SeekSlider_ValueChanged` (`:326`) sends a `seek` for **every** value
change while dragging, which is dozens of POSTs per drag. Send one seek on release (pointer released,
capture lost, manipulation completed) and one for a click on the track. Keyboard steps can be debounced.
3. **The cover is re-downloaded on every update.** `ApplyState` (`:199`) calls `LoadArtworkAsync` for each
`/state` and each SSE frame, which flickers and refetches. Combined with `max-age=60` on a fixed URL,
the cover can also stay **stale for up to a minute** after a track change. See the `/artwork` notes in
section 3.
4. **The error never clears.** If the first `/state` fails, "Can't reach CrossSound server" stays up
forever: only `RefreshStateAsync` clears it (`:152`), and it runs once, at load. The SSE path
(`:277`) never clears it.
5. **The SSE loop can spin hot and can stall.** After a clean end-of-stream or a non-200 answer it
reconnects at once with no delay (`:257-288`). `reader.EndOfStream` is a synchronous read on a network
stream. The stream shares the one `HttpClient` that has a 15 s `Timeout` (`:78`). Use a separate client
with an infinite timeout for `/events`, loop on `await ReadLineAsync()` until null, check the status,
and back off.
6. **The clock drifts.** `Tick_Tick` adds 0.5 s per tick (`:242`) instead of computing from the last
frame's `position` and a stopwatch, so it drifts and jumps.
7. **Every failure is hidden.** Discover (`:381`, `:423`) and the artwork code catch everything silently.
Signed out (503) looks the same as "Nothing to show." Command results are never checked.
8. **Discover never refreshes.** It loads once (`_discoverLoaded`, `:137`), with no refresh.
9. **Dead ends in Detail.** Users open a pane that does nothing (`:591`). A playlist card without stub
`tracks` says "No track list available" (`:598`), though `/playlist/:id` would load it. There's no "Play
all" for a playlist or mix (`/command {"action":"play","url":permalink}` or `playPlaylist`).
10. **Missing controls the API already has:** like (`isLiked`), shuffle, volume, and the queue
(`queue[]` + `playIndex`).
11. **Number formatting depends on the culture.** `GetStr` formats numbers with `GetNumber().ToString()`
(`:776`), which uses the current culture. Use `InvariantCulture` (ids go into URLs and JSON).
12. **Not RedWhite.** It uses the Windows accent color (`SystemAccentColor`, `:69-85`;
`SystemControlHighlightAccentBrush`, `:508`) and rounded corners (`CornerRadius` 10/6/4, `:32`, `:131`,
`:191`, `:225`, `:257`). See section 6.
What did work, so keep it: the activation flow in `App.xaml.cs` (protocol `ms-gamebarwidget`,
`IsLaunchActivation`, extension id check), the manifest's Game Bar extension and proxy-stub block, and the
Discover/Search JSON field fallbacks.
## 5. A suggested shape
- **Player**: cover, title/artist, a clock interpolated from SSE, a seek bar that seeks on release,
prev / play-pause / next, like, shuffle, volume. "Nothing playing" for `{}`.
- **Queue**: `queue[]` with the current row marked; tap a row to `playIndex`.
- **Discover**: history + mixed shelves, refresh button, Play-all per card, detail through
`/playlist/:id` or the stub ids plus `/tracks/batch`.
- **Search**: tracks / playlists / albums / users; a user opens their tracks (`/user/:id/tracks`).
- **Connection**: one service class owning both HttpClients, the SSE loop with back-off, and a single
"connected / signed out / not running" state the UI binds to.
- **Theme**: follow `XboxGameBarWidget.RequestedTheme` (light means `redtheme`, dark means
`redtheme-dark`).
- Pause the SSE loop when the widget is hidden (`_widget.VisibleChanged`) and resume on show.
## 6. Design: RedWhite (the user's house style; follow it)
- **Color, light / dark:** page `#FFFFFF` / `#000000`. Text, icons and lines are red `#FF0000` in both
themes (body text is red, not black). Muted text `#DA4545`, captions/placeholders `#FF746C`. Raised
panels `#FFF5F5` / `#0F0000`, inset wells `#FFEBEB` / `#260000`. Selected row wash `#FFE0E0` / `#240000`.
- **Fills:** a red button is `#FF0000`. Its hover is **lighter** coral `#FF6459`, never darker. Text and
icons on a red fill are white in light and **black** in dark. Text hover is salmon `#FF7373` (text only,
never a fill).
- **Corners are square (0) everywhere** (cover art, cards, buttons, panes). The one exception is a fully
round avatar.
- **Depth is a red glow, never a grey shadow:** for example `0 18px 44px -20px` red at 45% on a card hover.
On XAML use `ThemeShadow` sparingly, or a soft red radial.
- **Motion is fading:** things fade in over 150 ms and out over 120 ms, ease-out; no slides or bounces. A
pressed button **inverts** (red fill, white or black content) as a 120 ms color fade. Respect reduced
motion (`UISettings.AnimationsEnabled`).
- **Type:** Raleway (bundle the TTF; weights 400-800), falling back to Segoe UI. Roles: title 16 / 700,
body 14 / 500, caption 12.5 / 500 muted, labels 11 / 700 uppercase with 0.08em tracking.
- **You can't reference the RedWhiteUI library itself** (`git.redlintu16.com/RedWhiteUILibraries/Windows`).
Its C# side is `RedWhiteUI.Core` on `net10.0` and `RedWhiteUI.WinUI` on WinUI 3; a UWP / .NET Native
widget can use neither. Copy the token values above into a `ResourceDictionary` (light + dark
`ThemeDictionaries`), and don't edit the library.
- **Retired colors (don't use):** `#EF4444`, `#DC2626`, `#F87171`, `#DB0000`, `#FF2424`, `#0A0A0A`,
`#171717`, `#FAFAFA`, `#F1F5F9`, and any green, amber or blue for status. Status uses reds plus a word or
icon, never color alone.
## 7. Rules
- Only edit this repo. Don't edit the CrossSound app, its repos (`WindowsVersions/CrossSound`), or the
RedWhiteUI libraries. Stay out of other folders on the PC.
- Never use or ask for the user's SoundCloud login or tokens. The widget never needs them: CrossSound
holds the session.
- Don't send playback commands while the user may be listening without asking first (they're real
speakers).
- The user wants complete commands, for both PowerShell and Command Prompt, and says which is which. They
sometimes game on this PC: ask before long builds.
- Commit when it works and push to **`https://git.redlintu16.com/CrossSound/XboxGameBar`** (`origin`, branch
`master`; the user's own server). The old GitHub copy `RANDOMBRDSHT/GameBar` isn't home any more.
**That repo is public**: never commit tokens, keys, signing certificates (`*.pfx`) or the
`CrossSoundWidget_TemporaryKey.pfx`-style files Visual Studio makes; add them to `.gitignore`.
## 8. Open questions / server wish list
- The native app has no repeat mode: `repeat` is always `"none"` and `/repeat` does nothing. Leave repeat
out, or show it disabled.
- `/events` has no heartbeat, so a silent dead connection is only noticed on the next real change. If that
turns out to matter, ask the user for a server-side heartbeat (for example a `:` comment every 15 s).
- **Matching the user's custom theme: done on the server** (main 024831c): `GET /appearance` and
`/appearance/events` (section 3). Build the widget's brushes from it and swap them live; the fixed palette
in section 6 is the fallback. Built with MSVC and answering live (2026-10-28); if `/appearance`
misbehaves, tell the user and report it back to the Mac session.
- The Electron server: untested by me against this contract beyond what `docs/notes/api.md` lists. If the
user still runs it, test the widget against both.