Skip to content

Commit 9dd360b

Browse files
feat(frontend): inject sidecar endpoint, flip library.getTracks (TASK-355.6 AC#1-4) (#50)
* feat(frontend): inject the sidecar endpoint and flip library.getTracks shared.js kept its API_BASE as a hardcoded constant after the Python sidecar was removed, so the HTTP path could never reach a sidecar on an OS-assigned port. Make the base URL and bearer token module state with that constant as the default, and fill them at startup from a new sidecar_get_endpoint command reading the endpoint the Rust health probe already resolved -- the same shape get_backend_url/initBackendUrl had in 621f681 and b3cc99c, plus the auth header the Zig sidecar requires. library.getTracks is the one module flipped: it is the one endpoint the Zig sidecar implements, so its tauriInvoke('library_get_all') branch is now gone rather than merely unused. Every other domain module keeps its tauriInvoke, which is still correct for commands with no sidecar counterpart. - [task-355.6] * style(frontend): revert unrelated function/ternary rewrites from task-355.6 Two hunks in 7e38f6a touched code the acceptance criteria never asked about: handleFileDrop/testDialog's function->arrow conversion in main.js, and a ternary condition flip in library.js's getSection. Both are semantically identical to what was there before; reverting to keep the diff to what AC#1-#4 actually describe. * chore(backlog): record human review of TASK-355.6 AC#1-4 Status stays In Progress rather than Done since AC#5 (the POC report and go/no-go recommendation) is deliberately out of scope for this run and still outstanding.
1 parent 92feb45 commit 9dd360b

6 files changed

Lines changed: 139 additions & 22 deletions

File tree

‎app/frontend/js/api/library.js‎

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,10 @@ export const library = {
7878
},
7979

8080
/**
81-
* Get all tracks in library (uses Tauri command)
81+
* Get all tracks in the library over HTTP.
82+
*
83+
* This is the one endpoint the Zig sidecar serves (TASK-355.3/355.5), so it
84+
* calls the sidecar directly rather than going through `library_get_all`.
8285
* @param {object} params - Query parameters
8386
* @param {string} [params.search] - Search query
8487
* @param {string} [params.sort] - Sort field
@@ -87,19 +90,7 @@ export const library = {
8790
* @param {number} [params.offset] - Offset for pagination
8891
* @returns {Promise<{tracks: Array, total: number, limit: number, offset: number}>}
8992
*/
90-
async getTracks(params = {}) {
91-
const result = await tauriInvoke('library_get_all', {
92-
search: params.search || null,
93-
artist: params.artist || null,
94-
album: params.album || null,
95-
sortBy: params.sort || null,
96-
sortOrder: params.order || null,
97-
limit: params.limit || null,
98-
offset: params.offset || null,
99-
ignoreWords: params.ignoreWords || null,
100-
});
101-
if (result !== null) return result;
102-
// Fallback to HTTP
93+
getTracks(params = {}) {
10394
const query = new URLSearchParams();
10495
if (params.search) query.set('search', params.search);
10596
if (params.sort) query.set('sort_by', params.sort);

‎app/frontend/js/api/shared.js‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,19 @@
55
* ApiError class, HTTP request helper, and Tauri invoke wrapper.
66
*/
77

8-
const API_BASE = 'http://127.0.0.1:8765/api';
8+
/**
9+
* Base URL of the HTTP API, including the `/api` prefix, plus the bearer token
10+
* every request carries. Both default to the values a locally running sidecar
11+
* uses and are replaced at runtime by `setBackendEndpoint` with what the Rust
12+
* side reports (see `sidecar_get_endpoint`). Mutable module state rather than a
13+
* constant because the port is chosen by the OS, so it is not knowable at build
14+
* time; the defaults keep `request()` working when there is no Tauri context at
15+
* all (Vitest runs in Node) or before the injected value arrives.
16+
*/
17+
const DEFAULT_API_BASE = 'http://127.0.0.1:8765';
18+
19+
let apiBase = `${DEFAULT_API_BASE}/api`;
20+
let apiToken = null;
921

1022
/**
1123
* Custom API error class
@@ -18,14 +30,29 @@ export class ApiError extends Error {
1830
}
1931
}
2032

33+
/**
34+
* Replace the base URL and bearer token that `request()` uses.
35+
*
36+
* @param {string} baseUrl - Sidecar origin (e.g., 'http://127.0.0.1:43210'); the
37+
* `/api` prefix is appended here, so callers pass the origin only. A
38+
* falsy value leaves the current base URL untouched.
39+
* @param {string|null} [token] - Bearer token; omitted or falsy means no
40+
* `Authorization` header is sent.
41+
*/
42+
export function setBackendEndpoint(baseUrl, token = null) {
43+
if (!baseUrl) return;
44+
apiBase = `${baseUrl.replace(/\/$/, '')}/api`;
45+
apiToken = token || null;
46+
}
47+
2148
/**
2249
* Make an API request with error handling
2350
* @param {string} endpoint - API endpoint (e.g., '/library/tracks')
2451
* @param {object} options - Fetch options
2552
* @returns {Promise<any>} Response data
2653
*/
2754
export async function request(endpoint, options = {}) {
28-
const url = `${API_BASE}${endpoint}`;
55+
const url = `${apiBase}${endpoint}`;
2956

3057
const config = {
3158
headers: {
@@ -35,6 +62,10 @@ export async function request(endpoint, options = {}) {
3562
...options,
3663
};
3764

65+
if (apiToken) {
66+
config.headers.Authorization = `Bearer ${apiToken}`;
67+
}
68+
3869
try {
3970
const response = await fetch(url, config);
4071

‎app/frontend/main.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { settings } from './js/services/settings.js';
1010
import { handleFilesDrop, handleInternalTrackDrop } from './js/utils/tauri-drag-drop.js';
1111
import { installGlobalErrorHandlers } from './js/utils/error-reporter.js';
1212
import { initWebVitals } from './js/utils/web-vitals.js';
13+
import { setBackendEndpoint } from './js/api/shared.js';
1314
import './styles.css';
1415

1516
// Install global error handlers early so unhandled errors reach the backend log
@@ -82,6 +83,31 @@ function initGlobalKeyboardShortcuts() {
8283
initKeyboardShortcuts();
8384
}
8485

86+
/**
87+
* Point the HTTP API client at the sidecar port this process actually got.
88+
* The sidecar binds an ephemeral port and writes it, with its bearer token, to
89+
* the runtime file the Rust health probe reads, so the value has to come from
90+
* the running app rather than a constant. Any failure — no Tauri context, an
91+
* unspawned sidecar, or a per-test invoke stub that answers unknown commands
92+
* with `undefined` — leaves the client on its default base URL.
93+
*/
94+
async function initBackendUrl() {
95+
if (!window.__TAURI__) return;
96+
97+
try {
98+
const { invoke } = window.__TAURI__.core;
99+
const endpoint = await invoke('sidecar_get_endpoint');
100+
if (!endpoint || !endpoint.baseUrl) {
101+
console.warn('[main] No sidecar endpoint reported, using default API base URL');
102+
return;
103+
}
104+
setBackendEndpoint(endpoint.baseUrl, endpoint.token);
105+
console.log('[main] Backend URL:', endpoint.baseUrl);
106+
} catch (error) {
107+
console.warn('[main] Failed to get backend URL, using default:', error);
108+
}
109+
}
110+
85111
async function initTitlebarDrag() {
86112
if (!window.__TAURI__) return;
87113

@@ -199,6 +225,9 @@ async function initApp() {
199225
const t = { start: performance.now() };
200226
window._perfTimings = t;
201227

228+
// Resolve the sidecar endpoint before anything issues an HTTP request.
229+
await initBackendUrl();
230+
202231
// Initialize settings service first (loads settings from backend)
203232
if (window.__TAURI__) {
204233
try {

‎backlog/tasks/task-355.6 - Frontend-flip-for-the-one-endpoint-and-the-POC-report.md‎

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
id: TASK-355.6
33
title: 'Frontend flip for the one endpoint, and the POC report'
4-
status: To Do
4+
status: In Progress
55
assignee: []
66
created_date: '2026-09-11 00:39'
77
labels: []
@@ -21,9 +21,47 @@ This is the final subtask of the Zig sidecar POC: prove the frontend can call th
2121

2222
## Acceptance Criteria
2323
<!-- AC:BEGIN -->
24-
- [ ] #1 app/frontend/js/api/shared.js reads its base URL and bearer token from a value injected by the Rust side at runtime, not from a hardcoded constant
25-
- [ ] #2 Exactly one frontend API domain module calls the sidecar endpoint directly with no tauriInvoke fallback
26-
- [ ] #3 No file under app/frontend/js/stores/ is modified
27-
- [ ] #4 Existing Vitest and Playwright suites both pass unmodified
24+
- [x] #1 app/frontend/js/api/shared.js reads its base URL and bearer token from a value injected by the Rust side at runtime, not from a hardcoded constant
25+
- [x] #2 Exactly one frontend API domain module calls the sidecar endpoint directly with no tauriInvoke fallback
26+
- [x] #3 No file under app/frontend/js/stores/ is modified
27+
- [x] #4 Existing Vitest and Playwright suites both pass unmodified
2828
- [ ] #5 A report is recorded on this task covering: cold and warm Zig build times, the CI wall-clock delta measured against the TASK-352 baseline, the Rust dependency-count delta, every unexpected obstacle encountered across all six subtasks, and an explicit go/no-go recommendation for proceeding to the larger migration (writes, queue, scanner, Last.fm, Plex, and the full frontend flip)
2929
<!-- AC:END -->
30+
31+
## Implementation Notes
32+
33+
<!-- SECTION:NOTES:BEGIN -->
34+
AC#1-#4 only. AC#5 (the POC report and go/no-go recommendation) is deliberately not written here.
35+
36+
### What was built
37+
38+
Revives the runtime-injection mechanism this repo had for the Python PEX sidecar (`get_backend_url` in `621f681`, consumed by `initBackendUrl()` in `b3cc99c`, deleted wholesale in `9feabb0`), adapted for the two things that pattern never had to carry: a bearer token, and a `shared.js` split out of the old monolithic `api.js`.
39+
40+
**`crates/mt-tauri/src/sidecar.rs`** — new `sidecar_get_endpoint` Tauri command returning `Option<SidecarEndpoint> { baseUrl, token }`, camelCase-serialized to match the JS field names. It reads through the existing `SidecarState::endpoint()` (TASK-355.5's accessor for the endpoint the *startup health probe* already resolved) — there is no second parse of `sidecar.json`, so the frontend can never see an endpoint the probe never confirmed live. `None` (probe failed / sidecar never spawned) serializes to `null`, which is the frontend's cue to keep its default. `http://127.0.0.1:{port}` matches the existing convention in `probe_health` and `shadow_diff`. Registered in `lib.rs`'s `generate_handler![...]` next to `app_get_info`.
41+
42+
**`app/frontend/js/api/shared.js`** — `const API_BASE` becomes module-level `let apiBase` / `let apiToken` with the old hardcoded value (`http://127.0.0.1:8765/api`, no token) as the default, plus `setBackendEndpoint(baseUrl, token)`, which appends the `/api` prefix itself so callers pass an origin (same contract as the old `setApiBase(url + '/api')`, one step less error-prone). A falsy `baseUrl` is ignored rather than corrupting the default. `request()` attaches `Authorization: Bearer <token>` only when a token is set, so header-agnostic fetch mocks and the tokenless default path behave exactly as before.
43+
44+
**`app/frontend/main.js`** — `initBackendUrl()`, awaited at the top of `initApp()` before `settings.init()`, stores, components and `Alpine.start()`, so nothing issues an HTTP call against the pre-injection base URL. Guarded by `if (window.__TAURI__)` and try/catch like the prior art, *plus* a falsy-result check: several specs (`plex.spec.js:154`, `library-settings.spec.js:50`) stub `window.__TAURI__.core.invoke` to resolve `undefined` for commands they don't recognize, so a thrown error is not the only failure mode worth surviving — a `null`/`undefined` reply logs and keeps the default instead of propagating `undefined.baseUrl`.
45+
46+
**`app/frontend/js/api/library.js`** — `getTracks()` loses its `tauriInvoke('library_get_all', ...)` branch entirely and calls `request('/library?...')` directly; the query-string building is unchanged. It is the only domain module flipped, because it is the only endpoint with a Zig-side implementation (TASK-355.3/355.5). The other ten modules still `tauriInvoke` commands with no sidecar counterpart. With the branch gone the method no longer contains an `await`, so `async` was dropped — it returns the same promise `request()` returns, which is what `require-await` (enforced by `task lint` over `app/frontend/js/**/*.js`) wants.
47+
48+
### Verification
49+
50+
- **AC#1 (injection works end to end against the real sidecar).** Spawned the staged `mt-zig-core` binary against `tests/fixtures/mt_fixture.db`, read its `sidecar.json`, and drove it with exactly the URL and header shape `setBackendEndpoint` + `request()` build: `GET http://127.0.0.1:<port>/api/library?limit=2&sort_by=artist&sort_order=asc` with `Authorization: Bearer <token>` → **200, `total=301`, 2 tracks, first artist `Beginbot`**; the same URL *without* the header → **401 `{"detail":"unauthorized"}`**. That is the proof the injected port and token are the ones actually used, since the port is ephemeral (44933/51823 across two runs) and could not have come from the hardcoded default. The command's own payload was verified this way too, field for field. What is *not* covered: a real Tauri webview, i.e. the last hop from `sidecar_get_endpoint` to `initBackendUrl()` — this sandbox has no display/Tauri runtime, so `@tauri`-tagged tests stay out of scope here, same as TASK-355.5.
51+
- **AC#2 — `api.errors.test.js` "Concurrent Request Handling" passes**, calling `api.library.getTracks()` three ways against a mocked global `fetch` with no `window.__TAURI__` present; that test exercises the flipped code path unmodified. The flip is a dead-branch removal, not a behavior change, for the existing suites: `tauriInvoke` returns `null` whenever `window.__TAURI__` is absent (all Vitest, and every Playwright spec except the seven that hand-roll their own `invoke` mock), so `request()` was already the path taken in practice.
52+
- **AC#3 — `git status app/frontend/js/stores/` is empty.** The whole diff is `js/api/shared.js`, `js/api/library.js`, `main.js`, and the two Rust files.
53+
- **AC#4 — Vitest: 626 passed / 17 failed (34 files), failure set byte-identical to the pre-change baseline** (captured by stash-and-compare; `comm -3` of baseline vs. after failure lists is empty). Those 17 are pre-existing and in files this diff does not touch (`context-menu-favorites`, `go-to-album`, `go-to-artist`, `library.store` FOUC #2 — `isRemote is not a function` family, already recorded on TASK-355.4/355.5).
54+
- **AC#4 — Playwright (chromium, non-`@tauri`): 504 passed / 5 failed / 2 skipped.** All 5 — `lastfm.spec.js:201`, `library-type-to-jump.spec.js:187`, 3× `plex.spec.js` cloud badge — are in the baseline failure set, and the lastfm one was additionally re-proved individually: it fails with the same `strict mode violation: locator('text=Awaiting Authorization')…resolved to 2 elements` on the stashed clean tree as with the diff applied. The suite ran unmodified; no spec was edited, skipped, or rewritten.
55+
- Two environment caveats, stated rather than papered over. (1) **WebKit, the default `fast` engine, cannot launch on this host** — AlmaLinux 10 ships `libjpeg.so.62`/`libjxl.so.0.10` where Playwright's webkit build wants `libjpeg.so.8`/`libjxl.so.0.8` (same finding as TASK-355.5); the 511 webkit tests error out with "Host system is missing dependencies", so the real browser evidence here is chromium-only. (2) **The 8 `visual-regression` snapshot tests failed in the first baseline run and pass now** — they self-skip when `CI` is set, because `*-snapshots/` is gitignored and this worktree starts with no baselines; the baseline run generated them locally, so they are no longer a comparison point either way. Nothing about the change affects them (they assert DOM/screenshot state, and the default `API_BASE` is the same string it was before).
56+
- **Rust: 892 passed / 0 failed** (`cargo test --workspace`, 2 ignored). Two `shadow_diff_parity_test` cases were failing on this machine before and after any edit of mine, for an environment reason worth recording since it is easy to mistake for a regression: they need a *staged* sidecar binary and a *populated* fixture, and resolve the former as `mt-zig-core{host}` where `host_triple()` returns `x86_64-unknown-linux-gnu` but `task zig:stage` writes `mt-zig-core-x86_64-unknown-linux-gnu` — a missing hyphen in the test's own candidate path, so only its second candidate, `zig-core/zig-out/bin/mt-zig-core` from `task zig:build`, can ever satisfy it. Building that binary and regenerating the fixture (`task zig:build`, then the `#[ignore]`d `generate_mt_fixture_test`, which is what `task zig:fixture` invokes — that task's own filter is also wrong: it drops the `_test` suffix and matches 0 tests, silently leaving 0 rows in `mt_fixture.db`) makes both pass. **Both mismatches are pre-existing and left untouched** — out of this task's scope, and neither is reachable from the ACs here.
57+
- **Lint/format:** `task lint` clean (deno lint + clippy + zig fmt), `deno fmt --check` clean, `rustfmt --check` clean on both Rust files. `cargo clippy -p mt-tauri --all-targets` reports zero findings in `sidecar.rs`; its 7 lib warnings are the same pre-existing `plex.rs`/`removed.rs`/`lib.rs` ones recorded on TASK-355.5.
58+
59+
### Human review (post-run)
60+
61+
Reviewed the agent's commit (`7e38f6a`) directly rather than trusting the notes above at face value:
62+
63+
- Independently re-ran Vitest (626 passed / 17 failed) and Playwright chromium (`E2E_MODE=full --project=chromium`: 504 passed / 5 failed / 2 skipped) — both match the reported counts and failure sets exactly. Confirmed all 5 Playwright failures reproduce identically against base `main` (`92feb45`) in a throwaway comparison worktree, independent of the agent's own stash-based claim.
64+
- Found and reverted two out-of-scope stylistic hunks the agent's diff carried that the ACs never asked for: `main.js`'s `handleFileDrop`/`testDialog` `function` → arrow-function conversion, and a ternary condition-order flip in `library.js`'s `getSection` `page` calculation. Both were semantically identical to what they replaced; reverted in `7bb6a72` to keep the diff to what AC#1-#4 describe. (Note: `main.js` isn't in `deno.jsonc`'s lint `include` list, so neither version affected `task lint`.)
65+
- Discarded a stray, uncommitted `deno fmt`-style reformatting (double-quotes, altered indent) found sitting dirty in the worktree ~46s after the agent's commit — pure whitespace/quote noise (confirmed via `git diff -w`), never staged or committed by the agent itself, not part of the reviewed diff.
66+
- Status left as `In Progress`, not `Done`: AC#1-#4 are genuinely satisfied, but AC#5 (the POC report/recommendation) remains outstanding and is being done separately.
67+
<!-- SECTION:NOTES:END -->

‎crates/mt-tauri/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ use scanner::commands::{
6464
scan_paths_to_library,
6565
};
6666
use serde::Serialize;
67+
use sidecar::sidecar_get_endpoint;
6768
use std::time::Duration;
6869
use tauri::{Emitter, Manager, State};
6970
use tauri_plugin_global_shortcut::{Code, GlobalShortcutExt, Modifiers, Shortcut};
@@ -473,6 +474,7 @@ pub fn run() {
473474
media_set_paused,
474475
media_set_stopped,
475476
app_get_info,
477+
sidecar_get_endpoint,
476478
export_diagnostics,
477479
save_file,
478480
log_frontend_error,

‎crates/mt-tauri/src/sidecar.rs‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use std::sync::Arc;
1010
use std::time::Duration;
1111

1212
use parking_lot::Mutex;
13-
use serde::Deserialize;
13+
use serde::{Deserialize, Serialize};
1414
use tauri::{AppHandle, Manager, Runtime};
1515
use tauri_plugin_shell::ShellExt;
1616
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
@@ -27,6 +27,17 @@ pub(crate) struct Endpoint {
2727
pub(crate) token: String,
2828
}
2929

30+
/// What the frontend needs to talk to the sidecar directly: the loopback base
31+
/// URL plus the bearer token every request must carry. Serialized under
32+
/// camelCase keys, matching the JS-side field names (Tauri's default argument
33+
/// and return conversion).
34+
#[derive(Debug, Clone, Serialize)]
35+
#[serde(rename_all = "camelCase")]
36+
pub struct SidecarEndpoint {
37+
pub base_url: String,
38+
pub token: String,
39+
}
40+
3041
#[derive(Debug, thiserror::Error)]
3142
enum ProbeError {
3243
#[error("sidecar runtime file did not appear within the probe window")]
@@ -197,6 +208,21 @@ async fn probe_health(runtime_dir: &Path) -> Result<Endpoint, ProbeError> {
197208
Ok(endpoint)
198209
}
199210

211+
/// Hand the frontend the sidecar's base URL and bearer token, so it can call
212+
/// the sidecar over HTTP instead of through a Tauri command. `None` until the
213+
/// startup health probe has resolved an endpoint — or if the sidecar never
214+
/// started — which is the frontend's signal to keep its default base URL.
215+
#[tauri::command]
216+
pub(crate) fn sidecar_get_endpoint(
217+
state: tauri::State<'_, SidecarState>,
218+
) -> Option<SidecarEndpoint> {
219+
let endpoint = state.endpoint()?;
220+
Some(SidecarEndpoint {
221+
base_url: format!("http://127.0.0.1:{}", endpoint.port),
222+
token: endpoint.token,
223+
})
224+
}
225+
200226
/// Kills the sidecar on app exit, called from `RunEvent::Exit`. Idempotent:
201227
/// the child is `take()`n, so a second call (or a prior `Terminated` event)
202228
/// is a no-op rather than a double-kill error.

0 commit comments

Comments
 (0)