diff --git a/Cargo.lock b/Cargo.lock index 6b2f1e2..6fe210f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1102,6 +1102,7 @@ dependencies = [ "futures-util", "libc", "maestro-config", + "maestro-names", "maestro-protocol", "reqwest", "serde", @@ -1146,6 +1147,13 @@ dependencies = [ "thiserror 1.0.69", ] +[[package]] +name = "maestro-names" +version = "0.1.0" +dependencies = [ + "rand 0.8.6", +] + [[package]] name = "maestro-protocol" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index a5cc5ef..7fb7deb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ dirs = "5" futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } libc = "0.2" maestro-config = { path = "crates/maestro-config" } +maestro-names = { path = "crates/maestro-names" } maestro-protocol = { path = "crates/maestro-protocol" } maestro-testing = { path = "crates/maestro-testing" } maestro-tui = { path = "crates/maestro-tui" } diff --git a/crates/maestro-daemon/Cargo.toml b/crates/maestro-daemon/Cargo.toml index 112f736..24c5c52 100644 --- a/crates/maestro-daemon/Cargo.toml +++ b/crates/maestro-daemon/Cargo.toml @@ -18,6 +18,7 @@ dirs.workspace = true futures-util.workspace = true libc.workspace = true maestro-config.workspace = true +maestro-names.workspace = true maestro-protocol.workspace = true serde.workspace = true serde_json.workspace = true @@ -32,5 +33,6 @@ reqwest.workspace = true tokio-tungstenite.workspace = true urlencoding = "2" tempfile.workspace = true +maestro-names.workspace = true # `test-util` enables `start_paused` for instant timeout tests (NAP-270). tokio = { workspace = true, features = ["test-util"] } diff --git a/crates/maestro-daemon/src/local_api.rs b/crates/maestro-daemon/src/local_api.rs index 082451e..69a4494 100644 --- a/crates/maestro-daemon/src/local_api.rs +++ b/crates/maestro-daemon/src/local_api.rs @@ -19,7 +19,7 @@ use axum::routing::{any, delete, get}; use axum::{Json, Router}; use maestro_config::SpawnPreset; use maestro_protocol::{ - routes, ApiError, CatalogEvent, CreateSessionRequest, DaemonInfo, GitRoot, Session, + routes, ApiError, CatalogEvent, CreateSessionRequest, DaemonInfo, GitRoot, NameBatch, Session, PROTOCOL_VERSION, }; use serde::Deserialize; @@ -49,6 +49,7 @@ pub fn router(state: LocalApiState) -> Router { .route(routes::PROJECTS, get(projects)) .route(routes::GITROOT, get(git_root)) .route(routes::BRANCHES, get(crate::branches::handler)) + .route(routes::NAMES, get(names)) .route(routes::INFO, get(daemon_info)) .route(routes::EVENTS, any(events_ws)) .route(routes::patterns::ATTACH, any(attach_ws)) @@ -122,6 +123,22 @@ async fn git_root(State(s): State, Query(q): Query) -> .into_response() } +/// Query string for `GET /api/names`. `count` defaults to 1 and is capped at +/// [`maestro_names::MAX_BATCH`] (#53). +#[derive(Debug, Deserialize)] +struct NamesQuery { + count: Option, +} + +/// Fresh session handles for the spawn form's instant reroll (#53). The web +/// client fetches one batch per draft pane and rerolls locally from it. +async fn names(Query(q): Query) -> Json { + let count = q.count.unwrap_or(1).clamp(1, maestro_names::MAX_BATCH); + Json(NameBatch { + names: maestro_names::generate_batch(count), + }) +} + async fn daemon_info(State(s): State) -> Json { Json(DaemonInfo { hostname: (*s.hostname).clone(), diff --git a/crates/maestro-daemon/tests/local_api.rs b/crates/maestro-daemon/tests/local_api.rs index 194df70..b04abeb 100644 --- a/crates/maestro-daemon/tests/local_api.rs +++ b/crates/maestro-daemon/tests/local_api.rs @@ -232,6 +232,57 @@ async fn projects_returns_empty_for_a_disabled_scanner() { assert!(projects.is_empty()); } +/// #53: every returned handle splits into a known adjective and noun. +fn assert_valid_names(batch: &maestro_protocol::NameBatch) { + for name in &batch.names { + let (adj, noun) = name.split_once('-').unwrap_or_else(|| { + panic!("handle {name:?} is not adjective-noun"); + }); + assert!( + maestro_names::ADJECTIVES.contains(&adj), + "{adj} not in ADJECTIVES" + ); + assert!(maestro_names::NOUNS.contains(&noun), "{noun} not in NOUNS"); + } +} + +#[tokio::test] +async fn names_defaults_to_one_handle() { + let h = spawn("naps-laptop").await; + let batch: maestro_protocol::NameBatch = reqwest::get(url(h.addr, "/api/names")) + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(batch.names.len(), 1); + assert_valid_names(&batch); +} + +#[tokio::test] +async fn names_honors_count_and_caps_it() { + use maestro_names::MAX_BATCH; + let h = spawn("naps-laptop").await; + + let batch: maestro_protocol::NameBatch = reqwest::get(url(h.addr, "/api/names?count=5")) + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(batch.names.len(), 5); + assert_valid_names(&batch); + + let batch: maestro_protocol::NameBatch = + reqwest::get(url(h.addr, &format!("/api/names?count={}", MAX_BATCH * 10))) + .await + .unwrap() + .json() + .await + .unwrap(); + assert_eq!(batch.names.len(), MAX_BATCH); +} + #[tokio::test] async fn gitroot_probes_path() { // #26: resolves the query against the daemon home dir and walks up for a diff --git a/crates/maestro-names/Cargo.toml b/crates/maestro-names/Cargo.toml new file mode 100644 index 0000000..ca64850 --- /dev/null +++ b/crates/maestro-names/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "maestro-names" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true +description = "Session-handle generator: musical adjective-noun wordlists" + +[dependencies] +rand.workspace = true diff --git a/crates/maestro-names/src/lib.rs b/crates/maestro-names/src/lib.rs new file mode 100644 index 0000000..9f88c72 --- /dev/null +++ b/crates/maestro-names/src/lib.rs @@ -0,0 +1,96 @@ +//! The one home of the session-handle wordlists (#53). +//! +//! Previously duplicated in `web/src/names.ts`; every client now gets handles +//! from here, served by `GET /api/names`. + +/// Musical adjectives — tempo, dynamics, and articulation markings. +pub const ADJECTIVES: &[&str] = &[ + "allegro", + "andante", + "adagio", + "presto", + "vivace", + "largo", + "grave", + "lento", + "moderato", + "crescendo", + "staccato", + "legato", + "forte", + "dolce", + "agitato", + "cantabile", + "sostenuto", + "tremolo", + "rubato", + "marcato", + "brillante", + "maestoso", + "grazioso", + "espressivo", + "tranquillo", + "animato", + "spirito", + "sotto", + "vivo", + "feroce", +]; + +/// Musical nouns — instruments and forms from the concert hall. +pub const NOUNS: &[&str] = &[ + "cello", "violin", "viola", "oboe", "flute", "clarinet", "bassoon", "trumpet", "trombone", + "tuba", "horn", "timpani", "harp", "piano", "organ", "lyre", "lute", "fugue", "sonata", + "octave", "chord", "cadence", "prelude", "rondo", "nocturne", "scherzo", "refrain", "coda", + "motif", "overture", +]; + +/// Upper bound for a `GET /api/names?count=N` batch. +pub const MAX_BATCH: usize = 100; + +/// A fresh `adjective-noun` handle, e.g. `allegro-cello`. +pub fn generate() -> String { + use rand::seq::SliceRandom; + let mut rng = rand::thread_rng(); + format!( + "{}-{}", + ADJECTIVES.choose(&mut rng).unwrap(), + NOUNS.choose(&mut rng).unwrap() + ) +} + +/// `count` fresh handles (the caller clamps; this only trusts its input). +pub fn generate_batch(count: usize) -> Vec { + (0..count).map(|_| generate()).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn generated_name_is_adjective_dash_noun() { + let name = generate(); + let (adj, noun) = name.split_once('-').expect("name contains a dash"); + assert!(ADJECTIVES.contains(&adj), "{adj} not in ADJECTIVES"); + assert!(NOUNS.contains(&noun), "{noun} not in NOUNS"); + } + + #[test] + fn batch_returns_the_requested_count() { + assert_eq!(generate_batch(1).len(), 1); + assert_eq!(generate_batch(50).len(), 50); + for name in generate_batch(10) { + let (adj, noun) = name.split_once('-').unwrap(); + assert!(ADJECTIVES.contains(&adj) && NOUNS.contains(&noun)); + } + } + + #[test] + fn rerolls_can_differ() { + // 30x30=900 combinations; 20 draws all matching has probability ~1e-40. + let first = generate(); + let differs = (0..20).any(|_| generate() != first); + assert!(differs); + } +} diff --git a/crates/maestro-protocol/src/lib.rs b/crates/maestro-protocol/src/lib.rs index e63b34e..3bb1284 100644 --- a/crates/maestro-protocol/src/lib.rs +++ b/crates/maestro-protocol/src/lib.rs @@ -294,6 +294,13 @@ pub struct DaemonInfo { pub presets: Vec, } +/// Payload of `GET /api/names?count=N` (#53) — a batch of fresh +/// `adjective-noun` session handles generated by the `maestro-names` crate. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct NameBatch { + pub names: Vec, +} + // --------------------------------------------------------------------------- // Catalog events (`WS /api/events`) // --------------------------------------------------------------------------- diff --git a/crates/maestro-protocol/src/routes.rs b/crates/maestro-protocol/src/routes.rs index c89aa97..3f50b62 100644 --- a/crates/maestro-protocol/src/routes.rs +++ b/crates/maestro-protocol/src/routes.rs @@ -23,12 +23,18 @@ pub const PROJECTS: &str = "/api/projects"; pub const GITROOT: &str = "/api/gitroot"; /// `GET` one repository's local branches. Takes a `path` query param. pub const BRANCHES: &str = "/api/branches"; +/// `GET` a batch of generated session handles (#53). Takes a `count` query +/// param (default 1, capped at [`maestro_names`]' batch cap). +pub const NAMES: &str = "/api/names"; /// `WS` catalog snapshot + session deltas. pub const EVENTS: &str = "/api/events"; /// Name of the query parameter [`DIRS`], [`GITROOT`], and [`BRANCHES`] take. pub const PATH_QUERY: &str = "path"; +/// Name of the query parameter [`NAMES`] takes. +pub const COUNT_QUERY: &str = "count"; + /// `DELETE /api/sessions/:id`. pub fn session(id: Uuid) -> String { format!("{SESSIONS}/{id}") @@ -184,6 +190,7 @@ mod tests { PROJECTS, GITROOT, BRANCHES, + NAMES, EVENTS, ] { assert!(path.starts_with(API_PREFIX), "{path} escapes {API_PREFIX}"); diff --git a/web/src/api.ts b/web/src/api.ts index 92c3b64..d3867e9 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -5,6 +5,7 @@ import type { DaemonInfo, DirListing, GitRoot, + NameBatch, Projects, RecentDirs, Session, @@ -81,4 +82,11 @@ export async function gitRoot(path: string): Promise { return jsonOrError(await fetch(url, { credentials: "same-origin" })); } +/** A batch of fresh session handles for the spawn form's instant reroll (#53). + * Rerolls consume the batch locally; only exhaustion goes back to the daemon. */ +export async function fetchNames(count: number): Promise { + const url = `${routes.NAMES}?${routes.COUNT_QUERY}=${encodeURIComponent(count)}`; + return jsonOrError(await fetch(url, { credentials: "same-origin" })); +} + export { eventsWsUrl } from "./routes.js"; diff --git a/web/src/names.ts b/web/src/names.ts deleted file mode 100644 index 9de5d70..0000000 --- a/web/src/names.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Client-side session-handle generator for the spawn form's instant reroll -// (#23/#27). The spawn form rerolls without a round trip, so the wordlists -// live here; nothing server-side generates handles. - -/** Musical adjectives — tempo, dynamics, and articulation markings. */ -const ADJECTIVES = [ - "allegro", "andante", "adagio", "presto", "vivace", "largo", "grave", "lento", - "moderato", "crescendo", "staccato", "legato", "forte", "dolce", "agitato", - "cantabile", "sostenuto", "tremolo", "rubato", "marcato", "brillante", - "maestoso", "grazioso", "espressivo", "tranquillo", "animato", "spirito", - "sotto", "vivo", "feroce", -]; - -/** Musical nouns — instruments and forms from the concert hall. */ -const NOUNS = [ - "cello", "violin", "viola", "oboe", "flute", "clarinet", "bassoon", "trumpet", - "trombone", "tuba", "horn", "timpani", "harp", "piano", "organ", "lyre", - "lute", "fugue", "sonata", "octave", "chord", "cadence", "prelude", "rondo", - "nocturne", "scherzo", "refrain", "coda", "motif", "overture", -]; - -function pick(list: T[]): T { - return list[Math.floor(Math.random() * list.length)]; -} - -/** A fresh `adjective-noun` handle, e.g. `allegro-cello`. */ -export function generateName(): string { - return `${pick(ADJECTIVES)}-${pick(NOUNS)}`; -} diff --git a/web/src/projectPicker.test.ts b/web/src/projectPicker.test.ts index f3e2b51..ba6b821 100644 --- a/web/src/projectPicker.test.ts +++ b/web/src/projectPicker.test.ts @@ -15,7 +15,8 @@ function project(overrides: Partial): Project { }; } -/** Two fetches gate the form's initial load: /api/info then /api/projects. */ +/** Three fetches gate the form's initial load: /api/info, /api/projects, and + * the /api/names batch (#53). */ function stubFetch(info: unknown, projects: Project[]): void { vi.stubGlobal( "fetch", @@ -25,7 +26,9 @@ function stubFetch(info: unknown, projects: Project[]): void { ? info : url.includes("/api/projects") ? projects - : undefined; + : url.includes("/api/names") + ? { names: ["allegro-cello", "presto-fugue", "adagio-lyre"] } + : undefined; return new Response(JSON.stringify(body), { status: 200 }); }), ); diff --git a/web/src/routes.ts b/web/src/routes.ts index 1263611..c76bf8a 100644 --- a/web/src/routes.ts +++ b/web/src/routes.ts @@ -11,11 +11,15 @@ export const DIRS = "/api/dirs"; export const RECENT_DIRS = "/api/recent-dirs"; export const PROJECTS = "/api/projects"; export const GITROOT = "/api/gitroot"; +export const NAMES = "/api/names"; export const EVENTS = "/api/events"; /** Name of the query parameter `DIRS` and `GITROOT` both take. */ export const PATH_QUERY = "path"; +/** Name of the query parameter `NAMES` takes. */ +export const COUNT_QUERY = "count"; + export function session(id: Uuid): string { return `${SESSIONS}/${encodeURIComponent(id)}`; } diff --git a/web/src/spawnForm.ts b/web/src/spawnForm.ts index 916ca18..3351949 100644 --- a/web/src/spawnForm.ts +++ b/web/src/spawnForm.ts @@ -1,8 +1,7 @@ import { escapeHtml } from "./html.js"; -import { createSession, getDaemonInfo, projects as fetchProjects, gitRoot } from "./api.js"; +import { createSession, fetchNames, getDaemonInfo, projects as fetchProjects, gitRoot } from "./api.js"; import { attachDirAutocomplete } from "./dirAutocomplete.js"; import { filterProjects, groupProjects, isStale, sortProjects } from "./projectList.js"; -import { generateName } from "./names.js"; import type { CreateSessionRequest, Project, Session, SpawnPreset } from "./types.js"; import { abbreviateCwd, abbreviateFolderName } from "./types.js"; @@ -197,8 +196,46 @@ export function createSpawnForm(opts: SpawnFormOptions): SpawnFormHandle { const syncBranchToName = () => { if (!branchEdited) branchInput.value = nameInput.value; }; - nameInput.value = prefill.name ?? generateName(); + // Handles come from `GET /api/names` in batches (#53): the first one seeds + // the field, rerolls consume the rest locally so they stay instant, and a + // new batch is fetched when (and only when) the queue runs dry. One refill + // at a time keeps rapid rerolls from storming the daemon. + const NAME_BATCH_SIZE = 20; + let nameQueue: string[] = []; + let nameFetch: Promise | null = null; + // Guards against a late batch clobbering something the operator already + // typed or rerolled. + let nameTouched = Boolean(prefill.name); + const refillNames = (): Promise => { + if (!nameFetch) { + nameFetch = fetchNames(NAME_BATCH_SIZE) + .then((batch) => { + if (!destroyed) nameQueue.push(...batch.names); + }) + .catch(() => { + /* reroll just stays on the current name */ + }) + .finally(() => { + nameFetch = null; + }); + } + return nameFetch; + }; + + nameInput.value = prefill.name ?? ""; + if (!nameTouched) { + void refillNames().then(() => { + if (destroyed || nameTouched || nameInput.value) return; + const next = nameQueue.shift(); + if (next !== undefined) { + nameInput.value = next; + syncBranchToName(); + emit(); + } + }); + } nameInput.addEventListener("input", () => { + nameTouched = true; syncBranchToName(); emit(); }); @@ -207,9 +244,21 @@ export function createSpawnForm(opts: SpawnFormOptions): SpawnFormHandle { emit(); }); (form.querySelector(".reroll") as HTMLButtonElement).addEventListener("click", () => { - nameInput.value = generateName(); - syncBranchToName(); - emit(); + nameTouched = true; + const apply = () => { + if (destroyed) return; + const next = nameQueue.shift(); + if (next === undefined) return; + nameInput.value = next; + syncBranchToName(); + emit(); + }; + // Only hit the daemon when the local batch is exhausted. + if (nameQueue.length === 0) { + void refillNames().then(apply); + } else { + apply(); + } }); syncBranchToName(); // seed the branch from the initial name diff --git a/web/src/spawnFormNames.test.ts b/web/src/spawnFormNames.test.ts new file mode 100644 index 0000000..50aab84 --- /dev/null +++ b/web/src/spawnFormNames.test.ts @@ -0,0 +1,129 @@ +// @vitest-environment happy-dom +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createSpawnForm, type SpawnFormHandle } from "./spawnForm.js"; + +const BATCH_A = ["allegro-cello", "presto-fugue", "adagio-lyre"]; +const BATCH_B = ["forte-oboe", "largo-tuba", "vivace-harp"]; + +/** Stub the three fetches the form's initial load makes. Records every + * /api/names URL so tests can assert how many batches were fetched. */ +function stubFetch(batches: string[][]): string[] { + let batch = 0; + const nameUrls: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url.includes("/api/names")) { + nameUrls.push(url); + const names = batches[Math.min(batch, batches.length - 1)]; + batch += 1; + return new Response(JSON.stringify({ names }), { status: 200 }); + } + const body = url.includes("/api/info") + ? { hostname: "h", version: "0", home_dir: "/home/user", presets: [] } + : []; + return new Response(JSON.stringify(body), { status: 200 }); + }), + ); + return nameUrls; +} + +describe("spawnForm name batch (#53)", () => { + let handle: SpawnFormHandle | null = null; + let nameUrls: string[]; + + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + handle?.destroy(); + handle = null; + vi.unstubAllGlobals(); + vi.useRealTimers(); + }); + + async function mount(seed?: Parameters[0]["seed"]) { + nameUrls = stubFetch([BATCH_A, BATCH_B]); + handle = createSpawnForm({ seed, onSuccess() {} }); + document.body.appendChild(handle.el); + for (let i = 0; i < 40; i++) await Promise.resolve(); + return handle.el; + } + + const nameOf = (form: HTMLFormElement) => + form.querySelector("input[name=name]")!.value; + + function reroll(form: HTMLFormElement): void { + form.querySelector(".reroll")!.click(); + } + + async function drain(): Promise { + for (let i = 0; i < 40; i++) await Promise.resolve(); + } + + it("seeds its name from a fetched batch when no seed provides one", async () => { + const form = await mount(); + expect(BATCH_A).toContain(nameOf(form)); + expect(nameUrls).toHaveLength(1); + expect(nameUrls[0]).toContain("/api/names"); + expect(nameUrls[0]).toContain("count="); + }); + + it("keeps a seeded name and defers fetching until the first reroll", async () => { + const form = await mount({ name: "my-session" }); + expect(nameOf(form)).toBe("my-session"); + expect(nameUrls ?? []).toHaveLength(0); + + reroll(form); + await drain(); + expect(nameOf(form)).not.toBe("my-session"); + expect(nameUrls).toHaveLength(1); + }); + + it("rerolls locally from the batch with no extra round trips", async () => { + const form = await mount(); + expect(nameUrls).toHaveLength(1); + const seen = new Set([nameOf(form)]); + + for (let i = 0; i < BATCH_A.length; i++) { + reroll(form); + seen.add(nameOf(form)); + } + await drain(); + + // Every value came from the one fetched batch. + expect(seen.size).toBeGreaterThanOrEqual(2); + for (const value of seen) { + expect([...BATCH_A, ...BATCH_B]).toContain(value); + } + expect(nameUrls).toHaveLength(2); // refetch fired when the batch ran out + expect(nameUrls[1]).toContain("/api/names"); + }); + + it("refetches only once even if rerolls outpace the network", async () => { + const form = await mount(); + // Drain the batch without awaiting between rerolls. + for (let i = 0; i < BATCH_A.length + 1; i++) reroll(form); + await drain(); + // One refill in flight covers the whole run — no fetch storm. + expect(nameUrls.length).toBeLessThanOrEqual(2); + }); + + it("does not clobber an operator-typed name when the batch arrives late", async () => { + nameUrls = stubFetch([BATCH_A]); + handle = createSpawnForm({ onSuccess() {} }); + const form = handle.el; + document.body.appendChild(form); + + // The operator types before the fetch resolves. + const input = form.querySelector("input[name=name]")!; + input.value = "hand-typed"; + input.dispatchEvent(new Event("input")); + for (let i = 0; i < 40; i++) await Promise.resolve(); + + expect(nameOf(form)).toBe("hand-typed"); + }); +}); diff --git a/web/src/types.ts b/web/src/types.ts index 4a56bde..844a02a 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -83,6 +83,12 @@ export interface GitRoot { root?: string; } +/** `GET /api/names?count=N` — a batch of fresh session handles (#53). Mirrors + * `maestro_protocol::NameBatch`. */ +export interface NameBatch { + names: string[]; +} + /** One discovered git repository (or linked worktree) for `GET /api/projects` * (#54). Mirrors `maestro_protocol::Project`. */ export interface Project {