diff --git a/crates/factory-server/examples/e2e_fixture.rs b/crates/factory-server/examples/e2e_fixture.rs index 4365cae9..e52c35c8 100644 --- a/crates/factory-server/examples/e2e_fixture.rs +++ b/crates/factory-server/examples/e2e_fixture.rs @@ -31,7 +31,7 @@ use factory_core::{ RenovateAccess, RenovateCi, RetryLimits, Session, }; use factory_runner::ForgeKind; -use factory_server::Store; +use factory_server::{OpenRouterModel, Store}; const ADMIN: &str = "admin@e2e.test"; const COLLABORATOR: &str = "alice@e2e.test"; @@ -313,6 +313,22 @@ fn seed_local(store: &Store, url: &str, models: Option<&Vec>) -> Result< Ok(()) } +fn seed_openrouter_models(store: &Store, models: Option<&Vec>) -> Result<()> { + let models: Vec = models + .map_or(&[][..], Vec::as_slice) + .iter() + .map(|model| { + let (id, name) = model.split_once('|').unwrap_or((model, model)); + OpenRouterModel { + id: id.to_owned(), + name: name.to_owned(), + } + }) + .collect(); + store.replace_openrouter_models(&models, 0)?; + Ok(()) +} + fn seed(store: &Store) -> Result<()> { store.create_project( SHARED_PROJECT, @@ -452,6 +468,7 @@ fn main() -> Result<()> { let store = Store::open(&db)?; match command.as_str() { "seed" => seed(&store)?, + "openrouter-models" => seed_openrouter_models(&store, flags.get("model"))?, "local-models" => seed_local(&store, one("url")?, flags.get("model"))?, "project" => { let name = one("name")?; diff --git a/crates/factory-server/src/pages.rs b/crates/factory-server/src/pages.rs index b3e1c5d6..6892e08a 100644 --- a/crates/factory-server/src/pages.rs +++ b/crates/factory-server/src/pages.rs @@ -1061,6 +1061,9 @@ pub struct AgentChoice { /// Whether a stage on this agent needs a model, so the panel offers no /// "CLI default" chip. pub model_required: bool, + /// For an agent whose model field is a search, the stored models as id and + /// name. The field then draws no chip per model. + pub model_search: Option>, } /// One server's block inside a project's form: whether the project runs it, the @@ -3643,6 +3646,7 @@ fn agent_data(agents: &[AgentChoice]) -> (String, String) { "models": choice.models, "hint": choice.model_hint, "required": choice.model_required, + "search": choice.model_search, }) }); (efforts, models) @@ -3796,6 +3800,7 @@ fn agent_fields( let choice = project.agents.iter().find(|choice| choice.id == agent); let suggestions: &[String] = choice.map_or(&[], |choice| &choice.models); let model_required = choice.is_some_and(|choice| choice.model_required); + let searchable = choice.is_some_and(|choice| choice.model_search.is_some()); let model_hint = choice.map_or_else( || { format!( @@ -3831,11 +3836,19 @@ fn agent_fields( button.chip type="button" data-model=(suggestion) data-model-for=(key) { (suggestion) } } } - input id={ (project.name) "-" (key) } type="text" name=(key) list={ "model-suggestions-" (key) } + input id={ (project.name) "-" (key) } type="text" name=(key) + list=[(!searchable).then(|| format!("model-suggestions-{key}"))] + role=[searchable.then_some("combobox")] + aria-autocomplete=[searchable.then_some("list")] + aria-controls=[searchable.then(|| format!("model-results-{key}"))] + aria-expanded=[searchable.then_some("false")] + autocomplete=[searchable.then_some("off")] placeholder=(if model_required { "Model ID" } else { "CLI default" }) value=(model) data-model-input=(key); datalist id={ "model-suggestions-" (key) } { @for suggestion in suggestions { option value=(suggestion) {} } } + ul.model-results id={ "model-results-" (key) } role="listbox" aria-label="Matches" + data-model-results=(key) hidden {} p.hint data-model-hint=(key) { (model_hint) } } div.field { diff --git a/crates/factory-server/src/web.rs b/crates/factory-server/src/web.rs index 2ad8c594..caa32d6a 100644 --- a/crates/factory-server/src/web.rs +++ b/crates/factory-server/src/web.rs @@ -2513,6 +2513,12 @@ fn agent_choices(state: &AppState) -> Result, StoreError let local_url = local.url; let models_url = local.models_url; let local_models = state.store.local_models()?; + let openrouter_models: Vec<(String, String)> = state + .store + .openrouter_models()? + .into_iter() + .map(|model| (model.id, model.name)) + .collect(); Ok(state .registry .entries() @@ -2528,8 +2534,10 @@ fn agent_choices(state: &AppState) -> Result, StoreError .map(|&model| model.to_owned()) .collect() }; - let model_hint = if openrouter { - "Type an OpenRouter model ID. An OpenRouter stage needs a model.".to_owned() + let model_hint = if openrouter && openrouter_models.is_empty() { + "No OpenRouter model list is stored. Type a model id.".to_owned() + } else if openrouter { + format!("Search {} OpenRouter models.", openrouter_models.len()) } else if local { match (&local_url, models.is_empty()) { (None, _) => { @@ -2569,6 +2577,7 @@ fn agent_choices(state: &AppState) -> Result, StoreError models, model_hint, model_required: local || openrouter, + model_search: openrouter.then(|| openrouter_models.clone()), } }) .collect()) diff --git a/crates/factory-server/static/settings-pipeline.js b/crates/factory-server/static/settings-pipeline.js index 0e738a9c..6cc84a46 100644 --- a/crates/factory-server/static/settings-pipeline.js +++ b/crates/factory-server/static/settings-pipeline.js @@ -1,7 +1,8 @@ // The pipeline on a project's settings page. Selecting a stage, a gate or // merge shows its panel without a reload and updates the `?stage=` value in // the address and the form's action, so a save comes back to the same panel. -// The model buttons fill the stage's model field, "Use the default" sets a +// The model buttons fill the stage's model field, and an agent with a model +// search lists the stored models that match what is typed. "Use the default" sets a // gate back to the factory default, and the nodes follow the fields as they // change. Without this script each node is a link that reloads the page with // its panel open, and the buttons stay hidden. @@ -71,6 +72,72 @@ setEffortLabel(stage, selected); } + var MAX_RESULTS = 20; + + function showResults(stage) { + var results = form.querySelector('[data-model-results="' + stage + '"]'); + var input = form.querySelector('[data-model-input="' + stage + '"]'); + if (!results || !input) return; + var agent = form.querySelector('input[name="' + stage + '_agent"]:checked'); + var spec = agent && AGENT_MODELS[agent.value]; + var query = input.value.trim().toLowerCase(); + results.textContent = ""; + results.removeAttribute("data-active"); + input.removeAttribute("aria-activedescendant"); + var matches = []; + if (spec && spec.search && query !== "") { + for (var i = 0; i < spec.search.length && matches.length < MAX_RESULTS; i++) { + var model = spec.search[i]; + if ( + model[0].toLowerCase().indexOf(query) >= 0 || + model[1].toLowerCase().indexOf(query) >= 0 + ) { + matches.push(model); + } + } + } + matches.forEach(function (model, index) { + var item = document.createElement("li"); + item.id = "model-result-" + stage + "-" + index; + item.setAttribute("role", "option"); + item.dataset.modelResult = model[0]; + item.textContent = model[1] && model[1] !== model[0] ? model[0] + " (" + model[1] + ")" : model[0]; + results.appendChild(item); + }); + setExpanded(stage, !!(spec && spec.search), matches.length > 0); + } + + function setExpanded(stage, searchable, open) { + var results = form.querySelector('[data-model-results="' + stage + '"]'); + var input = form.querySelector('[data-model-input="' + stage + '"]'); + results.hidden = !open; + input.removeAttribute("aria-activedescendant"); + if (searchable) { + input.setAttribute("role", "combobox"); + input.setAttribute("aria-autocomplete", "list"); + input.setAttribute("aria-controls", results.id); + input.setAttribute("aria-expanded", open ? "true" : "false"); + input.removeAttribute("list"); + input.setAttribute("autocomplete", "off"); + } else { + input.removeAttribute("role"); + input.removeAttribute("aria-autocomplete"); + input.removeAttribute("aria-controls"); + input.removeAttribute("aria-expanded"); + input.removeAttribute("autocomplete"); + input.setAttribute("list", "model-suggestions-" + stage); + } + } + + function pickResult(stage, id) { + var input = form.querySelector('[data-model-input="' + stage + '"]'); + input.value = id; + input.dispatchEvent(new Event("input", { bubbles: true })); + var results = form.querySelector('[data-model-results="' + stage + '"]'); + results.textContent = ""; + setExpanded(stage, true, false); + } + function redrawModels(stage) { var agent = form.querySelector('input[name="' + stage + '_agent"]:checked'); var spec = agent && AGENT_MODELS[agent.value]; @@ -78,7 +145,7 @@ var input = form.querySelector('[data-model-input="' + stage + '"]'); if (!spec || !chips || !input) return; var previous = AGENT_MODELS[chips.dataset.agent]; - var datalist = form.querySelector("#" + input.getAttribute("list")); + var datalist = form.querySelector("#model-suggestions-" + stage); var hint = form.querySelector('[data-model-hint="' + stage + '"]'); chips.dataset.agent = agent.value; chips.textContent = ""; @@ -103,15 +170,23 @@ hint.textContent = spec.hint; } input.placeholder = spec.required ? "Model ID" : "CLI default"; + showResults(stage); var value = input.value.trim(); setModelLabel(stage); - if (value !== "" && previous && previous.models.indexOf(value) >= 0) { + var offered = previous ? previous.models.concat((previous.search || []).map(function (m) { return m[0]; })) : []; + if (value !== "" && offered.indexOf(value) >= 0) { input.value = ""; input.dispatchEvent(new Event("input", { bubbles: true })); } } form.addEventListener("click", function (event) { + var result = event.target.closest("[data-model-result]"); + if (result) { + var results = result.closest("[data-model-results]"); + pickResult(results.dataset.modelResults, result.dataset.modelResult); + return; + } var chip = event.target.closest("[data-model-for]"); if (!chip) return; var input = form.querySelector('[data-model-input="' + chip.dataset.modelFor + '"]'); @@ -120,7 +195,35 @@ }); form.addEventListener("input", function (event) { - if (event.target.dataset.modelInput) setModelLabel(event.target.dataset.modelInput); + var stage = event.target.dataset.modelInput; + if (!stage) return; + setModelLabel(stage); + showResults(stage); + }); + + form.addEventListener("keydown", function (event) { + var stage = event.target.dataset && event.target.dataset.modelInput; + var results = stage && form.querySelector('[data-model-results="' + stage + '"]'); + if (!results || results.hidden) return; + var items = results.children; + var active = Number(results.dataset.active === undefined ? -1 : results.dataset.active); + if (event.key === "ArrowDown" || event.key === "ArrowUp") { + active = event.key === "ArrowDown" ? Math.min(active + 1, items.length - 1) : Math.max(active - 1, 0); + results.dataset.active = String(active); + Array.prototype.forEach.call(items, function (item, i) { + if (i === active) item.setAttribute("aria-selected", "true"); + else item.removeAttribute("aria-selected"); + }); + event.target.setAttribute("aria-activedescendant", items[active].id); + items[active].scrollIntoView({ block: "nearest" }); + event.preventDefault(); + } else if (event.key === "Enter" && active >= 0) { + event.preventDefault(); + pickResult(stage, items[active].dataset.modelResult); + } else if (event.key === "Escape") { + results.removeAttribute("data-active"); + setExpanded(stage, true, false); + } }); form.addEventListener("change", function (event) { diff --git a/crates/factory-server/static/style.css b/crates/factory-server/static/style.css index 6fbcc127..c88d56ed 100644 --- a/crates/factory-server/static/style.css +++ b/crates/factory-server/static/style.css @@ -1204,6 +1204,10 @@ form.card { padding: var(--space-24); margin-bottom: var(--space-24); } .pipeline-js .model-chips { display: flex; } .chip { border: var(--border-width) solid var(--border); border-radius: var(--radius-pill); background: var(--surface); color: var(--text); padding: 3px var(--space-10); font-size: var(--font-size-sm); } .chip:hover { border-color: var(--accent); color: var(--accent); } +.model-results { list-style: none; margin: var(--space-6) 0 0; padding: 0; border: var(--border-width) solid var(--border); border-radius: var(--radius-md); background: var(--surface); max-height: 16rem; overflow-y: auto; } +.model-results[hidden] { display: none; } +.model-results li { padding: var(--space-6) var(--space-10); font-size: var(--font-size-sm); cursor: pointer; } +.model-results li:hover, .model-results li[aria-selected="true"] { color: var(--accent); text-decoration: underline; } .seg { display: inline-flex; border: var(--border-width) solid var(--border); border-radius: var(--radius-md); overflow: hidden; } .seg label { display: block; position: relative; margin: 0; font-weight: normal; } .seg input { position: absolute; opacity: 0; width: 1px; height: 1px; } diff --git a/crates/factory-server/tests/dashboard.rs b/crates/factory-server/tests/dashboard.rs index cc8da62a..dee6420a 100644 --- a/crates/factory-server/tests/dashboard.rs +++ b/crates/factory-server/tests/dashboard.rs @@ -8031,6 +8031,64 @@ async fn a_local_stage_offers_the_stored_models_and_names_the_server() { assert!(page.body.contains(""local"")); } +#[tokio::test] +async fn an_openrouter_stage_is_a_search_over_the_stored_models_with_no_chips() { + let dashboard = dashboard(); + dashboard + .store + .replace_openrouter_models( + &[ + factory_server::OpenRouterModel { + id: "openai/gpt-5".to_owned(), + name: "OpenAI: GPT-5".to_owned(), + }, + factory_server::OpenRouterModel { + id: "x-ai/grok-4".to_owned(), + name: "xAI: Grok 4".to_owned(), + }, + ], + 1, + ) + .unwrap(); + dashboard + .store + .save_project_agents( + "maestro", + &agents("openrouter", "claude", "claude", "claude", "claude"), + ) + .unwrap(); + let page = dashboard.get("/settings/projects/maestro").await; + let start = page.body.find("data-panel=\"clarify\"").unwrap(); + let rest = &page.body[start..]; + let panel = &rest[..rest.find("data-model-hint").unwrap() + 200]; + assert!(!panel.contains("data-model=\""), "no chip, no CLI default"); + assert!(!panel.contains(" c.textContent), list: s.list.children.map((o) => o.value), hint: s.hint.textContent, + results: s.results.children.map((r) => r.dataset.modelResult), + resultsHidden: s.results.hidden, placeholder: s.input.placeholder, efforts: s.seg.children.map((l) => l.children[0].value), effort: (s.seg.children.find((l) => l.children[0].checked) || { children: [{}] }).children[0].value, @@ -232,3 +240,72 @@ console.log(JSON.stringify({ local, back: state(implement) })); serde_json::json!(["low", "medium", "high", "xhigh", "max"]) ); } + +#[test] +fn openrouter_draws_no_chips_and_searches_the_list_by_id_or_name_up_to_twenty() { + let out = run(r#" +const implement = stage("implement", "claude", "fable"); +load(); +pick(implement, "openrouter"); +const drawn = state(implement); +function type(text) { + implement.input.value = text; + implement.input.dispatchEvent({ type: "input", target: implement.input, bubbles: true }); + return state(implement); +} +console.log(JSON.stringify({ drawn, id: type("GPT"), name: type("xai: grok"), many: type("acme"), none: type("zzz"), blank: type("") })); +"#); + assert_eq!(out["drawn"]["chips"], serde_json::json!([])); + assert_eq!(out["drawn"]["list"], serde_json::json!([])); + assert_eq!(out["drawn"]["hint"], "Search 30 OpenRouter models."); + assert_eq!(out["drawn"]["placeholder"], "Model ID"); + assert_eq!(out["drawn"]["model"], ""); + assert_eq!(out["id"]["results"], serde_json::json!(["openai/gpt-5"])); + assert_eq!(out["name"]["results"], serde_json::json!(["x-ai/grok-4"])); + assert_eq!(out["many"]["results"].as_array().unwrap().len(), 20); + assert_eq!(out["none"]["resultsHidden"], true); + assert_eq!(out["blank"]["resultsHidden"], true); +} + +#[test] +fn clicking_a_result_fills_the_field_and_an_unlisted_id_stays() { + let out = run(r#" +const implement = stage("implement", "claude", ""); +load(); +pick(implement, "openrouter"); +implement.input.value = "grok"; +implement.input.dispatchEvent({ type: "input", target: implement.input, bubbles: true }); +const item = implement.results.children[0]; +item.dispatchEvent({ type: "click", target: item }); +const picked = state(implement); +implement.input.value = "my/own-id:free"; +implement.input.dispatchEvent({ type: "input", target: implement.input, bubbles: true }); +console.log(JSON.stringify({ picked, typed: state(implement) })); +"#); + assert_eq!(out["picked"]["model"], "x-ai/grok-4"); + assert_eq!(out["picked"]["resultsHidden"], true); + assert_eq!(out["typed"]["model"], "my/own-id:free"); + assert_eq!(out["typed"]["results"], serde_json::json!([])); +} + +#[test] +fn switching_away_from_openrouter_clears_a_listed_id_hides_results_and_restores_chips() { + let out = run(r#" +const implement = stage("implement", "claude", ""); +load(); +pick(implement, "openrouter"); +implement.input.value = "x-ai/grok-4"; +implement.input.dispatchEvent({ type: "input", target: implement.input, bubbles: true }); +pick(implement, "claude"); +const back = state(implement); +pick(implement, "openrouter"); +console.log(JSON.stringify({ back, again: state(implement) })); +"#); + assert_eq!(out["back"]["model"], ""); + assert_eq!( + out["back"]["chips"], + serde_json::json!(["", "fable", "opus"]) + ); + assert_eq!(out["back"]["resultsHidden"], true); + assert_eq!(out["again"]["chips"], serde_json::json!([])); +} diff --git a/docs/design.md b/docs/design.md index 4538757d..b1aee763 100644 --- a/docs/design.md +++ b/docs/design.md @@ -20,7 +20,7 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | Account resolution | `Accounts::resolve(project, requested_by)` picks the account when each forge or git operation of a job starts, so a token saved or cleared, or a switch changed, applies from the next operation with no restart. A request job runs as the stored token of its `requested_by` login when that login is a collaborator, has "Use my account" on for the project and has a token for the project's forge. Every other job runs as the project token. A job with the requester `factory` always does: Renovate discovery, Renovate jobs, and gap proposals before approval. `Store::approve_proposal` sets `requested_by` to the approving login, so an approved gap job follows the request rule from then on. An answer, approval or retry by another collaborator does not change `requested_by`. There is no fallback after resolution. With no project token the operation fails with "Project has no project token. Save one on /settings/projects/" and makes no forge call. A failed resolution or a refused token fails the job through `FactoryFailed`, or `AgentFailed` for an agent run, and the job page shows Retry. Retry resolves again, so it runs with a token saved since, and no other token is tried first. A transient error in a publish, watch or Renovate step still logs and tries again after the poll interval. Each executor request carries an `AccountSource`, and the executor calls `resolve` before every forge or authenticated git operation, so the push and the pull request open of one publish may run as different accounts when a token changes between them. The command that ran classifies a refusal: the runner marks an error with `REJECTED` when `gh` or `git` output holds HTTP 401, "Bad credentials" or git's authentication failure, and the executor turns that into "The forge rejected the project token of " or "the GitHub token of ", with the page that replaces it. Agent failure text is never searched. The runner replaces the token and the authorization header with `` in every `gh` and `git` error, so no job log or failure reason holds them. The worker writes the checkout's git configuration, so no command that reads it gets a credential. A clone runs where no checkout exists yet. A fetch or push runs in a bare repository the factory makes in a temporary directory, with `--git-dir`, hooks off and no credential helper, against the forge's URL with the header scoped to that host. The checkout hands the branch to that repository and takes the fetched base from it, each without a credential, so its proxy, certificate, `url.*` and `include` settings are never loaded with a token. `Git::prepare` takes a closure and calls it before the clone and again before the fetch, so a token saved between them reaches the fetch. A failed log fetch inside a CI failure report is noted in the report, except a refused credential, which fails the step like any other refusal. After a Renovate merge succeeds, the job records the merge before it reads the merged pull request, so a refusal on that read leaves Retry resuming the watch and not merging again. The `Account` comes from `Forge::account`, so its commit identity is the account's login and noreply address. `Resolved.ignore` holds the resolved login and the project token's login, read from the metadata tables, and `Forge::status` leaves out comments from those logins. After a push the job log reads "Pushed to as (project account)" or "(requester's account)", with the login of the account the push ran as. With the secret store unavailable no token is readable, so no forge operation runs. A collaborator who is removed loses the switch, and their jobs move to the project token at the next operation. | | One-time `GH_TOKEN` copy | The factory reads `GH_TOKEN` for this copy only. Jobs and onboarding do not use it, so an install with no `GH_TOKEN` works. At startup, after the toml import, with the secret store available and `GH_TOKEN` set, `forge_tokens::copy_gh_token` gives each `github` project with no project token that value as its project token. It looks the account up with `Forge::lookup_account` first and stores the token with the account's login and id. A project whose lookup fails or times out stores nothing, is named in a warning with the token removed from the text, and is tried again at the next start. The lookup runs once per start, bounded by `LOOKUP_TIMEOUT`, and the `gh` child is killed when it times out, so a stalled CLI cannot hold the start. The copy is recorded per project in `gh_token_copies (project)`. The marker is written in the same transaction as the token, whether it is a copy, a collaborator's save or a clear, and when the project already holds a token. A token cleared before the first successful pass therefore stays cleared across restarts. `Store::create_project` with an onboarding login writes the marker too, so a project onboarded later does not get the token of the factory account. The toml import passes no login and writes no marker, so imported projects get the copy. `Store::remove_project` deletes the marker, so a project onboarded under a reused name starts with none. Projects on another forge are skipped. With the secret store unavailable the factory logs one warning and copies nothing. The log names the project and the account login, never the token. | | gh stdin | `GitHub::run` in `factory-runner` passes a body to gh on stdin for `pr create`, `pr edit`, `pr comment` and the approval `api` call. It closes the pipe and waits for gh in every case, even when the write fails. A non-zero exit returns `gh failed: `, so gh's own message survives. A zero exit ignores a `BrokenPipe` write error, because gh may exit without reading its stdin, and any other write error returns `writing to gh: ...`. An early return on the write error made the result depend on whether gh read its stdin and when it exited, and it lost the stderr of a gh that failed first, for example on a bad token. | -| Agent registry | `AgentRegistry` in `factory-server` maps each agent to what the server needs to run and present it: the credential, the worker image, the host config directory, the settings page URL, and the model aliases and effort levels the stage panel offers. It holds the `ClaudeToken` resolver, the `CodexLogin` coordinator and the secret store, and is built once at startup. For Claude the credential is that resolved token, the image is the `worker_image` setting from the Workers page, the host config directory and the stdout parser come from `factory-runner`'s `AgentBackend` (see "Agent runtime"), the settings page is `/settings/agents/claude`, the model aliases are fable, opus, sonnet and haiku, and the effort levels are the ones `factory-core` exposes. Codex carries the same: its credential is the stored `auth.json` the `CodexLogin` coordinator resolves, it runs in the same `worker_image` since one image carries both agents, its settings page is `/settings/agents/codex`, and its model aliases track the pinned CLI's `gpt-6` family. Copilot's credential is the GitHub token in its own secret store row, read afresh on each run, so a token saved on the settings page reaches the next run. It runs in the same `worker_image`, and its model suggestions are `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash`. Its settings page is `/settings/agents/copilot`, which the sidebar links. The Local agent has an entry that points at `/settings/agents/local` and offers the model ids stored from its server instead of aliases; it runs in the `worker_image`, has no host config directory because its CLI is a runtime setting, and its credential fails with "the Local agent has no subscription credential", and the executor never asks for it. The podman executor reads the credential, the image and the host config directory from the registry rather than naming an agent. A run whose agent resolves no credential fails before any checkout or container; Claude's reason is "no Claude token is set", Codex's is "no Codex login is set" and Copilot's is "no Copilot login is set". An unavailable secret store, or a Copilot row that will not decrypt, reads as no login. The stage panel renders the model chips, the datalist and the hint under the model field from `model_suggestions` of the stage's saved agent, so each agent offers only its own ids: Claude `fable`, `opus`, `sonnet` and `haiku`, Codex `gpt-6.1-sol` and `gpt-6.1-codex`, Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash`. The hint names the agent's CLI. Local's ids are not a constant: `project_settings` fills them from `Store::local_models()`, the list stored from the server's `/v1/models`, and the hint reads "Models served by .", or "No model list is stored for ." with no chips, or says that no server is set. `AgentChoice` carries the ids, the hint and `model_required`; a Local stage offers no "CLI default" chip, because it needs a model, and its node reads "Model required" while the model is blank, in the first render and after a switch of agent. `local_settings.models_url` records the URL the stored list came from, so when the URL changed and the fetch since failed, the hint says "Models from , the server before ." and the ids stay as suggestions. The panel script reads the same three from `data-agent-models`. Job 47 showed why: with Copilot selected the panel still offered Claude's aliases, and a Claude alias saved on a Copilot stage would make a Copilot run fail. Any id can still be typed, and a save does not check it against the list. OpenRouter has a settings page, `/settings/agents/openrouter`, but no model suggestions, no host config directory and no worker image, and its `credential()` fails with "the OpenRouter agent has no subscription credential", which the executor never asks for. It runs in the `worker_image`. The stage panel gives an OpenRouter stage no chips, the hint "Type an OpenRouter model ID. An OpenRouter stage needs a model." and `model_required`; a later change replaces this with a search of the stored list. | +| Agent registry | `AgentRegistry` in `factory-server` maps each agent to what the server needs to run and present it: the credential, the worker image, the host config directory, the settings page URL, and the model aliases and effort levels the stage panel offers. It holds the `ClaudeToken` resolver, the `CodexLogin` coordinator and the secret store, and is built once at startup. For Claude the credential is that resolved token, the image is the `worker_image` setting from the Workers page, the host config directory and the stdout parser come from `factory-runner`'s `AgentBackend` (see "Agent runtime"), the settings page is `/settings/agents/claude`, the model aliases are fable, opus, sonnet and haiku, and the effort levels are the ones `factory-core` exposes. Codex carries the same: its credential is the stored `auth.json` the `CodexLogin` coordinator resolves, it runs in the same `worker_image` since one image carries both agents, its settings page is `/settings/agents/codex`, and its model aliases track the pinned CLI's `gpt-6` family. Copilot's credential is the GitHub token in its own secret store row, read afresh on each run, so a token saved on the settings page reaches the next run. It runs in the same `worker_image`, and its model suggestions are `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash`. Its settings page is `/settings/agents/copilot`, which the sidebar links. The Local agent has an entry that points at `/settings/agents/local` and offers the model ids stored from its server instead of aliases; it runs in the `worker_image`, has no host config directory because its CLI is a runtime setting, and its credential fails with "the Local agent has no subscription credential", and the executor never asks for it. The podman executor reads the credential, the image and the host config directory from the registry rather than naming an agent. A run whose agent resolves no credential fails before any checkout or container; Claude's reason is "no Claude token is set", Codex's is "no Codex login is set" and Copilot's is "no Copilot login is set". An unavailable secret store, or a Copilot row that will not decrypt, reads as no login. The stage panel renders the model chips, the datalist and the hint under the model field from `model_suggestions` of the stage's saved agent, so each agent offers only its own ids: Claude `fable`, `opus`, `sonnet` and `haiku`, Codex `gpt-6.1-sol` and `gpt-6.1-codex`, Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash`. The hint names the agent's CLI. Local's ids are not a constant: `project_settings` fills them from `Store::local_models()`, the list stored from the server's `/v1/models`, and the hint reads "Models served by .", or "No model list is stored for ." with no chips, or says that no server is set. `AgentChoice` carries the ids, the hint and `model_required`; a Local stage offers no "CLI default" chip, because it needs a model, and its node reads "Model required" while the model is blank, in the first render and after a switch of agent. `local_settings.models_url` records the URL the stored list came from, so when the URL changed and the fetch since failed, the hint says "Models from , the server before ." and the ids stay as suggestions. The panel script reads the same three from `data-agent-models`. Job 47 showed why: with Copilot selected the panel still offered Claude's aliases, and a Claude alias saved on a Copilot stage would make a Copilot run fail. Any id can still be typed, and a save does not check it against the list. OpenRouter has a settings page, `/settings/agents/openrouter`, but no model suggestions, no host config directory and no worker image, and its `credential()` fails with "the OpenRouter agent has no subscription credential", which the executor never asks for. It runs in the `worker_image`. The stage panel gives an OpenRouter stage no chips, no datalist and `model_required`, and turns its model field into a search of the stored list, see "The stage panel" in "Running the OpenRouter agent in a worker". | | Prompt boundary | The stage prompts stay Rust format strings in `factory-runner`'s `prompt.rs`, which interpolate the job's data and are covered by the prompt tests. Moving them to template files would add a loader, a path in the worker image and a template syntax, and every prompt would stay shared anyway, so the fix is at the boundary: `prompt.rs` names no agent. The parts that differ per agent come from the `AgentBackend` as a `PromptStyle`, next to the command line and parser that already sit behind the trait (see "Agent runtime"): the repository instructions file the prompt names, `CLAUDE.md` for Claude and `AGENTS.md` for Codex and Copilot, the review method a review run follows, the review skill for Claude and Copilot and the skill's path for Codex, and the schema the prompt carries when the agent's CLI has no output-schema flag. Claude and Codex pass the stage's schema to the CLI, so their `PromptStyle` carries none; Copilot has no such flag, so its `PromptStyle` carries an instruction that tells the agent to end with one message of only the JSON, says that text outside the JSON fails the run, and says a summary goes into the schema's fields, and `prompt.rs` appends the stage's schema after it. `Cli::rules_doc` in `factory-core` owns the instructions file name, and `Agent::rules_doc` wraps it through `Agent::cli`, so the name stays in one place. The `PromptStyle` and the podman executor's missing-`AGENTS.md` warning both read. A run with at least one active MCP server also gets one trailing paragraph that names the servers, tells the agent to load their tools before it starts, and covers gateway servers. A gateway such as Composio lists only a dozen meta tools that search a catalog and run what they find, so an agent that loaded only those tools could conclude that no tool exists for an app the gateway covers; the paragraph says the listed tools are then not all the server offers and tells the agent to ask the server's search tool before it decides no tool exists. The text is generic and names no vendor, because `job_prompt` gets only operator-chosen names, so matching a name or URL is a guess that misses other gateways, and the sentence is conditional, so it costs a plain server nothing. Claude Code keeps an MCP server's tools behind a search step and loads a tool's schema only when the model asks for it, so without the paragraph an agent never reaches a tool nothing names; the paragraph is what lets a later step use one. The scheduler passes the active server names into `job_prompt`, so the set tracks the run's config, and the wording is the same for every harness and stage because that set can change between runs. A run with no active server gets no MCP paragraph. Every run, for every agent and stage, also gets one fixed nix paragraph, built by `end_prompt` in `prompt.rs` before the schema instruction. It says nix is installed with flakes enabled and that a missing tool can come from nixpkgs, for example `nix shell nixpkgs# -c `, and that the repository's own instructions still decide how to build and test. The worker image has nix with flakes and every worker mounts the shared `/nix` volume, but an agent only learned of it from a repository's own instructions, so it could give up on a missing binary. The wording is identical for every agent, so it needs no `PromptStyle` field and `prompt.rs` still names no agent. It sits before the Copilot schema instruction, so a Copilot prompt still ends with the schema, or with the MCP paragraph, and the final JSON message is unaffected. A prompt whose schema requires more than `outcome` also names the required top-level fields and the optional ones, taken from the schema's `required` list and `properties` so the two cannot drift apart, and says each is its own field. A Haiku diff check run sent `StructuredOutput` calls the tool rejected for a missing top-level `summary` six times, and the prompt never named the field. Whether the prompt was the cause is not confirmed. | | Contributor setup | This repository's own agent files are laid out for both Claude Code and Codex. `AGENTS.md` at the root holds the project instructions, worded for any coding agent, and `CLAUDE.md` is the single line `@AGENTS.md`. Claude Code reads `CLAUDE.md` and expands its `@path` imports, so the import pulls in `AGENTS.md`; Codex reads `AGENTS.md` into its developer message on its own. One file holds the text, so the two never drift. The `unslop` skill lives at `.agents/skills/unslop/SKILL.md`, the path Codex scans, and `.claude/skills/unslop` is a relative symlink to it, the path Claude Code scans, so both load the one skill. Before this a factory Codex run against this repository logged a missing `AGENTS.md` and could not load `unslop`. | | Host | `moon.local` (`ssh moon@moon.local`): Ubuntu 26.04, x86_64, 8 cores, 7.2 GB RAM, 74 GB free disk, systemd linger on for user `moon`. Tailscale is up at `100.77.68.75`. | @@ -44,7 +44,7 @@ These decisions were made on 2026-11-19 while brainstorming in the maestro repos | MCP tool toggles | A project can turn off single tools of an MCP server it uses. Every tool is on by default, so the factory stores the tools that are off, and a project with none off behaves as before. The setting is per project and server and applies to all five stages, without a per-stage grid. A tool a server adds later starts on. The settings page marks it "new" so an operator sees it. The `project_mcp_tools` table holds the last tool list per project and server, keyed by project, server and tool name, with the tool's description, an `offered` flag, a `disabled` flag and the number of the refresh that first saw it. `project_mcp_tool_refreshes` counts each project and server's refreshes, so a tool is "new" when the latest refresh first saw it and is not the first one. The list is per project because a server may offer different tools for different credentials. "Refresh connection" fills the table, see MCP connection check: after a successful `initialize` it sends `notifications/initialized` and pages through `tools/list` by its cursor with the negotiated `MCP-Protocol-Version` and the `Mcp-Session-Id`. The same 15-second total timeout covers the whole exchange, and each reply is read up to 1 MiB. Only a complete list replaces the stored one. A tool missing from it keeps its row with `offered` cleared, so a turned-off tool stays off if the server offers it again, and the page lists it as "no longer offered". A failed list keeps the old rows and the result says the tools could not be listed. The refresh route returns the page's refresh area, the button, the result and the tool list, and htmx replaces that area, found from the button with `closest .mcp-refresh`. The swap drops unsaved changes to that list's checkboxes, and the hint says so. The list sits on the project's page for the server as one checkbox per stored tool, checked when on, with its description. Each shown tool posts a hidden `mcp..shown.` field and, when checked, `mcp..tool.`. A server name has no `.`, so the handler splits the tool name off after the prefix. The save handler turns off the shown tools left unchecked and turns on the checked ones. It leaves a tool the form did not show as it is, so a refresh between render and save turns nothing off by accident. The proxy enforces the setting, because a worker with `bypassPermissions` and a run token could call a tool with `curl` that a Claude Code flag only hid from the model. `StoreUpstreams` returns the server's turned-off tool names with its headers, read on each request, so a change reaches a run in flight at its next request. For a POST, the proxy parses the body it already buffers as JSON-RPC, rejecting duplicate keys so it and the server cannot read two different tool names. A `tools/call` whose `params.name` is off gets a JSON-RPC error that names the tool as turned off for the project, with the request's `id`, and the proxy forwards nothing. A batch array holding such a call gets a 403 and nothing is forwarded. When the server has a tool turned off, a POST body that does not parse gets a 400 rather than being forwarded. A `tools/list` reply is buffered up to 4 MiB and the turned-off tools are removed from `result.tools`, in a JSON body or in the SSE event carrying the response, with other SSE events passed through as they are. A reply over the cap or one that does not parse is relayed unchanged, and the call block still applies. A stream resumed by `Last-Event-ID` may replay an unfiltered list, and the call block applies there too. Every other request and response streams as before. Each blocked call goes through `McpWarnings`, deduped per run, server and tool, and `Store` writes a factory line to the job log and an `mcp-tool-blocked` row in `job_events` with `: ` in its `detail`, which the job page timeline shows as a note under the step. Deleting a server deletes its tool rows with its `project_mcp` rows. A rename loses them like the stored values. An edit that changes the URL's origin clears `offered` on every row and keeps each `disabled` flag until the next refresh. A stdio server has no tool toggles. The proxy is what enforces them, a stdio server bypasses it, and listing its tools needs the same throwaway container as the connection check. A toggle could then only hide a tool from the model, not block it. Both are a follow-up. | | Job MCP tool calls | The proxy records every call a job makes to a remote server, and the scheduler records every call to a stdio server from the agent's output. After `screen` lets a request through, and before it forwards the body, the proxy finds every `tools/call` in the body, which is one for a single JSON-RPC object and several for a batch array, and reports each through its callback. This runs whether or not the project turned a tool off. `Store::record_mcp_tool_call` writes one `mcp-tool-call` row to `job_events` for each call, with `: ` in `detail` and the job's current stage, pull request and turn, the way a cost row is written, so it changes neither the stage nor the turn. It writes no job log line, because the agent's own `tool mcp__…` line already records the call, and it does not deduplicate: every call is a row. A refused call is recorded only as `mcp-tool-blocked`, never also as a call. A call to a stdio server never reaches the proxy, so the scheduler records it from the agent's output. The scheduler's log sink sees each `LogLine::Tool` the parsers emit. When its name is `mcp____` and `` is a stdio server of that run, the sink calls `McpWarnings::record_tool_called`, which writes the same `mcp-tool-call` row under the run's job. The name splits at the first `__` after the prefix, because a server name holds no underscore. A tool name that belongs to a remote server is skipped, so no call is counted twice. All three parsers already emit that name: Claude from `tool_use`, Codex from `mcp_tool_call` and Copilot from the `mcpServerName` and `mcpToolName` of `tool.execution_start`. With no tool turned off the reading is lenient: a body that is not JSON, or a `tools/call` with no string tool name, is forwarded unchanged and records nothing. The timeline adds no note for an `mcp-tool-call` row, and its step timing and cost are unchanged, because the row stores the stage the job is already in. Job expiry deletes the rows with the job. The job page shows these calls in its own "MCP tool calls" card, see Job page look. | | Approval gates | Spec, plan and publish. Each project has its own gates, in a `project_gates` table in SQLite with one row per project and a column per gate. The factory-wide gates in the stored settings are the defaults: onboarding a project copies them into its row, and a later change to a default leaves existing projects alone. Spec and plan are on in the code default, publish is off. The settings page edits the defaults on the Default gates page and a project's gates on its pipeline, see Settings layout. A job copies its project's gates when it is created, so a later settings change does not touch existing jobs. Everything after the last gate runs without stopping, apart from questions the agent asks. The state machine stops at a gate only when the job has it. A job with the publish gate stops before the first push of each planned pull request and waits for approval. Later pushes to the same pull request, such as fixes for CI or review comments, are not gated. Gates were one global setting before. A one-time migration at startup gives every project with no `project_gates` row the current global gates, the way `Store::migrate_global_auto_merge` moved auto-merge, so each project keeps its earlier behaviour. You merge on GitHub, unless the project's auto-merge setting is on: then the factory squash-merges a pull request once every check passed and no review comment waits for the agent. Auto-merge is per project, see Project settings. A pull request with no checks reported yet is not merged, so a push is never merged before GitHub starts its CI. | -| Settings layout | The settings pages share a sidebar with six groups. You has Notifications, the per-user page at `/settings/notifications`, Project groups, the per-user page at `/settings/groups`, see Project groups, Local, the per-user page at `/settings/local`, and OpenRouter, the per-user page at `/settings/openrouter`, see User settings. Forges has one entry per forge kind, GitHub at `/settings/forges/github`, each a page for the login's own token on that forge, see "Forge tokens". `/settings/forges/` is a 404. A login that is not a factory admin sees only the You, Forges and Projects groups, since the Factory, Agents and Integrations pages answer it with 403, see Factory admins. Factory has Workers, Default gates, Pull request polling, Renovate and Forgejo servers. Forgejo servers is the registry at `/settings/forgejo`, see Forgejo. `/settings/github` redirects to `/settings/polling`, because the interval applies to every forge. Agents has one entry per registered agent, from the registry, each linking to its page, except an agent with no page, which shows as text marked "Not available yet": Claude's is `/settings/agents/claude`, Codex's is `/settings/agents/codex`, Copilot's is `/settings/agents/copilot` and Local's is `/settings/agents/local` and OpenRouter's is `/settings/agents/openrouter`. Local's radio in each stage panel is enabled, and with Local selected the panel offers the stored model ids, see Agent registry. Integrations has MCP servers. Projects has one entry per project the login collaborates on and a link to onboarding. Each entry is its own page with its own URL: `/settings/local`, `/settings/openrouter`, `/settings/workers`, `/settings/gates`, `/settings/polling`, `/settings/forges/`, `/settings/renovate`, `/settings/forgejo`, `/settings/agents/claude`, `/settings/agents/codex`, `/settings/agents/copilot`, `/settings/agents/local`, `/settings/agents/openrouter`, `/settings/mcp`, `/settings/mcp/`, `/settings/projects/` and `/settings/projects//mcp/`. `/settings` redirects to the first project the login collaborates on, or to `/settings/notifications` when it collaborates on none. The Projects group lists only the login's own projects, from `Store::project_labels_for`, by shown name, see Dashboard access and Project display name. `/settings` redirects to the first project of that list. The project page has a Project name card above the forge account and Local checks cards, which saves the display name. The Codex page shows whether a login is stored and when Codex last refreshed it, never the file or a token. "Sign in with ChatGPT" starts a `codex login --device-auth` container from the worker image, and a fragment polls `/settings/agents/codex/login/fragment` every five seconds for the verification URL and one-time code, then for "Signed in" or a failure reason with the scrubbed output below it, under the headings described in "Copilot auth"; Cancel removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only textarea posts a pasted `auth.json` to `/settings/agents/codex/auth` as the fallback, and Clear removes the stored login. The Copilot page shows whether a token is stored, never the token, in an input value or in the page source. "Sign in with GitHub" posts to `/settings/agents/copilot/login` and starts a `copilot login --device-code` container from the worker image. A fragment at `/settings/agents/copilot/login/fragment` polls every five seconds for the URL and code with the ANSI color stripped, then for "Signed in" or a failure reason with the scrubbed output below it, under one of the two headings in "Copilot auth". The fragment that reports "Signed in" carries an `HX-Refresh` header, so the page reloads and its stored-token status updates. Cancel posts to `/settings/agents/copilot/login/cancel` and removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only token field posts to `/settings/agents/copilot/token` as the fallback, and Clear posts to `/settings/agents/copilot/token/clear`. An empty save keeps the stored token. With no master key the field and the sign-in button are disabled and Clear still works. A note says the GitHub account needs a Copilot plan, that it should not be moonthebot unless that is intended, and that the token goes to Copilot workers. The page has no price table. The Codex page also holds the Codex price table, one row per model with its input, cached input and output prices per million tokens, with a form to add or edit a model at `/settings/agents/codex/prices` and a Delete button that posts to `/settings/agents/codex/prices/delete`, see Job cost. Each page has one form, and its Save button sits in a bar that stays at the bottom of the window. The Save button comes before a Delete or Clear button in the form, so Enter in a field saves. Once an input of the form changes, the bar reads "Unsaved changes." and leaving the page asks first. `static/settings-form.js` does both, and without it the forms save the same way. A save redraws the same page with a notice. Adding a server opens its page, and deleting one opens the MCP servers page. A project's page also has a Forge account card, `#forge-account`, see "Project collaborators". A project's page has a Local checks card above the Maintenance card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/checks`, see Project registry. A project's page ends its pipeline form with a Maintenance card, a form of its own with its own save bar, see Project maintenance settings. A project's page draws its settings as the path a job takes: clarify, spec, plan, implement, review and merge, with the spec, plan and publish gates between them. Each stage shows its model, its effort and the MCP servers on in it. The agent is set in the panel, not shown on the node. Selecting a stage, a gate or merge opens its panel under the pipeline. The selection is a `?stage=` query parameter, `clarify` to `review`, `gate-spec`, `gate-plan`, `gate-publish` or `merge`, and an unknown value opens clarify. It works without JavaScript, a link opens the same panel, and a save comes back to it. Every panel sits in the one form and only the selected one shows, so a save posts every field and a hidden panel's values are kept. `static/settings-pipeline.js` switches panels without a reload, keeps the address and the form's action on the open panel, and updates the nodes as the fields change. A stage panel sets the stage's agent, its model, its effort and a switch per MCP server for that stage. The agent control lists every registered agent above the model as a radio; an agent that cannot run has a disabled radio, and Local's is enabled. It preselects the stage's effective agent, Claude when the project saved none. The model suggestions and the effort radios come from the selected agent: for Claude the aliases fable, opus, sonnet and haiku and the levels low, medium, high, xhigh and max, for Codex the `gpt-6` family aliases and the levels minimal, low, medium, high and xhigh, and for Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash` and the levels low, medium, high, xhigh and max. The model is typed or picked from the aliases, and the effort is one radio per level of the stage's agent, five for Claude, Codex and Copilot and four for Local. A server's switch is on when the server runs in that stage. Saving with a switch on turns the server on in exactly the stages switched on. Saving with every switch off stops a running server and keeps its stages for the server's own page, and leaves a stopped server as it is. The review stage reads Off and is drawn dashed while LLM review is off, and its panel holds the LLM review switch. A gate panel shows the factory default, marks a gate that differs from it on the panel and with a dot on its diamond, and offers "Use the default". The merge panel holds auto-merge. A card under the pipeline sums up each MCP server for the project and links to its page. A project's panels and MCP page link to the server registry (`/settings/mcp`) only for a factory admin. Collaborators still turn servers on and off and enter header values. A project's MCP page holds the project's header values, the connection check, the five stage switches and the tool list with a filter, a count of the tools on, and buttons to turn every shown tool on or off. `static/mcp-tools.js` runs those controls, and without it they stay hidden. A server's page holds its URL and header names and lists the projects that use it. A save that renames or removes a header, or changes the URL's origin, and so deletes stored values, is held back: `Store::mcp_edit_deletes` lists the values it would delete without writing, and the page shows the posted URL and names with each project and header it deletes and a button that saves anyway. An edit that deletes nothing saves at once. Deleting a server is a form of its own, below the edit form, and needs the server's name typed into it. Any other name deletes nothing and redraws the page with the problem. The model chips, the datalist and the hint follow the selected agent. The page draws the saved agent's set on load, so it is right without JavaScript. When the user switches a stage's agent, `settings-pipeline.js` redraws them for the new agent, as it does the effort radios. A model field that holds one of the previous agent's suggestions is cleared, and its node reads "CLI default", or "Model required" for Local, because the new agent would refuse it. A typed id that is not one of those suggestions stays. The "CLI default" chip stays for every agent but Local, whose stage needs a model and offers no such chip; with Local selected and the field blank the node reads "Model required". Each stage panel has its own chips and datalist, so a switch on one stage leaves the hidden panels alone. Job 47 is the reason: the panel offered Claude's aliases for a Copilot stage. A project's page for a stdio server, `/settings/projects//mcp/`, shows the enabled switch, the stages, the command and base arguments, the project's extra arguments and the command line a run starts. The project's pipeline panels list a stdio server with a switch per stage like a remote one, and the project's MCP servers card marks it "stdio". A project's page has a Worker packages card below the Local checks card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/packages`, see Worker packages. The sidebar is pinned under the top bar. Its height follows its entries up to a limit, the window height minus the top bar and a 16px gap above and below, so it never reaches past the bottom of the window and follows a resize without a reload. Above 760px it scrolls on its own when the entries exceed that limit, the way the job page timeline does, see Job page timeline. After a load a small script, `settings-nav.js`, sets the sidebar's `scrollTop` so the current entry shows, and leaves the window where it is. At 760px and narrower the sidebar stays a row of links that scrolls sideways, with no height limit. The Agents group lists OpenRouter after Local. | +| Settings layout | The settings pages share a sidebar with six groups. You has Notifications, the per-user page at `/settings/notifications`, Project groups, the per-user page at `/settings/groups`, see Project groups, Local, the per-user page at `/settings/local`, and OpenRouter, the per-user page at `/settings/openrouter`, see User settings. Forges has one entry per forge kind, GitHub at `/settings/forges/github`, each a page for the login's own token on that forge, see "Forge tokens". `/settings/forges/` is a 404. A login that is not a factory admin sees only the You, Forges and Projects groups, since the Factory, Agents and Integrations pages answer it with 403, see Factory admins. Factory has Workers, Default gates, Pull request polling, Renovate and Forgejo servers. Forgejo servers is the registry at `/settings/forgejo`, see Forgejo. `/settings/github` redirects to `/settings/polling`, because the interval applies to every forge. Agents has one entry per registered agent, from the registry, each linking to its page, except an agent with no page, which shows as text marked "Not available yet": Claude's is `/settings/agents/claude`, Codex's is `/settings/agents/codex`, Copilot's is `/settings/agents/copilot` and Local's is `/settings/agents/local` and OpenRouter's is `/settings/agents/openrouter`. Local's radio in each stage panel is enabled, and with Local selected the panel offers the stored model ids, see Agent registry. Integrations has MCP servers. Projects has one entry per project the login collaborates on and a link to onboarding. Each entry is its own page with its own URL: `/settings/local`, `/settings/openrouter`, `/settings/workers`, `/settings/gates`, `/settings/polling`, `/settings/forges/`, `/settings/renovate`, `/settings/forgejo`, `/settings/agents/claude`, `/settings/agents/codex`, `/settings/agents/copilot`, `/settings/agents/local`, `/settings/agents/openrouter`, `/settings/mcp`, `/settings/mcp/`, `/settings/projects/` and `/settings/projects//mcp/`. `/settings` redirects to the first project the login collaborates on, or to `/settings/notifications` when it collaborates on none. The Projects group lists only the login's own projects, from `Store::project_labels_for`, by shown name, see Dashboard access and Project display name. `/settings` redirects to the first project of that list. The project page has a Project name card above the forge account and Local checks cards, which saves the display name. The Codex page shows whether a login is stored and when Codex last refreshed it, never the file or a token. "Sign in with ChatGPT" starts a `codex login --device-auth` container from the worker image, and a fragment polls `/settings/agents/codex/login/fragment` every five seconds for the verification URL and one-time code, then for "Signed in" or a failure reason with the scrubbed output below it, under the headings described in "Copilot auth"; Cancel removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only textarea posts a pasted `auth.json` to `/settings/agents/codex/auth` as the fallback, and Clear removes the stored login. The Copilot page shows whether a token is stored, never the token, in an input value or in the page source. "Sign in with GitHub" posts to `/settings/agents/copilot/login` and starts a `copilot login --device-code` container from the worker image. A fragment at `/settings/agents/copilot/login/fragment` polls every five seconds for the URL and code with the ANSI color stripped, then for "Signed in" or a failure reason with the scrubbed output below it, under one of the two headings in "Copilot auth". The fragment that reports "Signed in" carries an `HX-Refresh` header, so the page reloads and its stored-token status updates. Cancel posts to `/settings/agents/copilot/login/cancel` and removes the container, one login runs at a time, and a login not finished within fifteen minutes fails. A write-only token field posts to `/settings/agents/copilot/token` as the fallback, and Clear posts to `/settings/agents/copilot/token/clear`. An empty save keeps the stored token. With no master key the field and the sign-in button are disabled and Clear still works. A note says the GitHub account needs a Copilot plan, that it should not be moonthebot unless that is intended, and that the token goes to Copilot workers. The page has no price table. The Codex page also holds the Codex price table, one row per model with its input, cached input and output prices per million tokens, with a form to add or edit a model at `/settings/agents/codex/prices` and a Delete button that posts to `/settings/agents/codex/prices/delete`, see Job cost. Each page has one form, and its Save button sits in a bar that stays at the bottom of the window. The Save button comes before a Delete or Clear button in the form, so Enter in a field saves. Once an input of the form changes, the bar reads "Unsaved changes." and leaving the page asks first. `static/settings-form.js` does both, and without it the forms save the same way. A save redraws the same page with a notice. Adding a server opens its page, and deleting one opens the MCP servers page. A project's page also has a Forge account card, `#forge-account`, see "Project collaborators". A project's page has a Local checks card above the Maintenance card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/checks`, see Project registry. A project's page ends its pipeline form with a Maintenance card, a form of its own with its own save bar, see Project maintenance settings. A project's page draws its settings as the path a job takes: clarify, spec, plan, implement, review and merge, with the spec, plan and publish gates between them. Each stage shows its model, its effort and the MCP servers on in it. The agent is set in the panel, not shown on the node. Selecting a stage, a gate or merge opens its panel under the pipeline. The selection is a `?stage=` query parameter, `clarify` to `review`, `gate-spec`, `gate-plan`, `gate-publish` or `merge`, and an unknown value opens clarify. It works without JavaScript, a link opens the same panel, and a save comes back to it. Every panel sits in the one form and only the selected one shows, so a save posts every field and a hidden panel's values are kept. `static/settings-pipeline.js` switches panels without a reload, keeps the address and the form's action on the open panel, and updates the nodes as the fields change. A stage panel sets the stage's agent, its model, its effort and a switch per MCP server for that stage. The agent control lists every registered agent above the model as a radio; an agent that cannot run has a disabled radio, and Local's is enabled. It preselects the stage's effective agent, Claude when the project saved none. The model suggestions and the effort radios come from the selected agent: for Claude the aliases fable, opus, sonnet and haiku and the levels low, medium, high, xhigh and max, for Codex the `gpt-6` family aliases and the levels minimal, low, medium, high and xhigh, and for Copilot `claude-sonnet-5.5`, `claude-opus-5.5`, `gpt-6.2-sol` and `gemini-3.8-flash` and the levels low, medium, high, xhigh and max. The model is typed or picked from the aliases, and the effort is one radio per level of the stage's agent, five for Claude, Codex and Copilot and four for Local. A server's switch is on when the server runs in that stage. Saving with a switch on turns the server on in exactly the stages switched on. Saving with every switch off stops a running server and keeps its stages for the server's own page, and leaves a stopped server as it is. The review stage reads Off and is drawn dashed while LLM review is off, and its panel holds the LLM review switch. A gate panel shows the factory default, marks a gate that differs from it on the panel and with a dot on its diamond, and offers "Use the default". The merge panel holds auto-merge. A card under the pipeline sums up each MCP server for the project and links to its page. A project's panels and MCP page link to the server registry (`/settings/mcp`) only for a factory admin. Collaborators still turn servers on and off and enter header values. A project's MCP page holds the project's header values, the connection check, the five stage switches and the tool list with a filter, a count of the tools on, and buttons to turn every shown tool on or off. `static/mcp-tools.js` runs those controls, and without it they stay hidden. A server's page holds its URL and header names and lists the projects that use it. A save that renames or removes a header, or changes the URL's origin, and so deletes stored values, is held back: `Store::mcp_edit_deletes` lists the values it would delete without writing, and the page shows the posted URL and names with each project and header it deletes and a button that saves anyway. An edit that deletes nothing saves at once. Deleting a server is a form of its own, below the edit form, and needs the server's name typed into it. Any other name deletes nothing and redraws the page with the problem. The model chips, the datalist and the hint follow the selected agent. The page draws the saved agent's set on load, so it is right without JavaScript. When the user switches a stage's agent, `settings-pipeline.js` redraws them for the new agent, as it does the effort radios. With OpenRouter selected the field is a search over the stored OpenRouter models instead of chips, see "Running the OpenRouter agent in a worker". A model field that holds one of the previous agent's suggestions, or an id of the stored OpenRouter list, is cleared, and its node reads "CLI default", or "Model required" for Local, because the new agent would refuse it. A typed id that is not one of those suggestions stays. The "CLI default" chip stays for every agent but Local, whose stage needs a model and offers no such chip; with Local selected and the field blank the node reads "Model required". Each stage panel has its own chips and datalist, so a switch on one stage leaves the hidden panels alone. Job 47 is the reason: the panel offered Claude's aliases for a Copilot stage. A project's page for a stdio server, `/settings/projects//mcp/`, shows the enabled switch, the stages, the command and base arguments, the project's extra arguments and the command line a run starts. The project's pipeline panels list a stdio server with a switch per stage like a remote one, and the project's MCP servers card marks it "stdio". A project's page has a Worker packages card below the Local checks card, a form of its own with its own save bar that posts to `POST /settings/projects/{project}/packages`, see Worker packages. The sidebar is pinned under the top bar. Its height follows its entries up to a limit, the window height minus the top bar and a 16px gap above and below, so it never reaches past the bottom of the window and follows a resize without a reload. Above 760px it scrolls on its own when the entries exceed that limit, the way the job page timeline does, see Job page timeline. After a load a small script, `settings-nav.js`, sets the sidebar's `scrollTop` so the current entry shows, and leaves the window where it is. At 760px and narrower the sidebar stays a row of links that scrolls sideways, with no height limit. The Agents group lists OpenRouter after Local. | | Renovate retry limits | Two factory-wide limits govern the reruns of failed CI on a Renovate pull request. Automatic reruns is how many times the factory reruns failed CI on one head commit before it asks an agent, default 3. Total reruns is how many reruns one head commit gets before the factory comments and stops triage, default 7. They live in the settings JSON row as `renovate_auto_reruns` and `renovate_total_reruns`, so a factory that never saved them reads 3 and 7. They are factory-wide because the factory has one CI flakiness profile for its Renovate pull requests, and a per-project value would only add a field to forget. The page is `/settings/renovate`, in the Factory group and admin-only like the other Factory pages. A save is refused with a message and nothing stored when a value is not a whole number, when total is less than 1, or when automatic is greater than total. Automatic 0 is valid and sends the first failure to the agent. The Renovate triage reads them on every watch, so a change will apply to jobs already in flight and need no restart. | | Renovate pull request jobs | A Renovate job is a `Job` with `kind` `Renovate(RenovatePr)`, at its own `Stage::Renovate` with the request text set to the pull request title. A job stored before `kind` existed loads as `Request`. It skips clarify, spec, plan, implement and publish. The factory watches the pull request, and the core decides everything from what each watch reports. `Event::RenovateObserved` carries the head commit, the CI state (`NoChecks`, `Pending`, `Failed` with the log, or `Passed` with the diff and description when the job has no verdict for that head), the retry limits, the project's auto-merge flag and the project account's access (`RenovateAccess`: whether it may rerun CI, whether it may merge, and its login; a job stored before this loads with full access). The factory holds the limits and passes them in on every observation, so a saved limit reaches a job in flight with no restart and the job stores only its counts. A different head resets the reruns, the automatic reruns, the stop and the verdict. A failed observation checks the total first: at or above the total the job queues the stopped comment, which names the rerun count, and stops. Below it, the job reruns with no agent until the automatic reruns are used up, then runs `Task::AnalyzeFailure`. A transient verdict reruns and counts toward the total only. With Read access the factory makes no rerun call: a failed head goes straight to `Task::AnalyzeFailure` and a transient verdict queues a `TransientNoWrite` comment, which says the failure looks transient and that the project account needs Write to rerun CI, and stops until a new head or Retry. The executor reads the account's access with `Forge::access` and `Forge::may_merge` on every watch, so granting Write takes effect on the next head with no restart, and a failed read fails the watch so the scheduler retries. A caused-by-update verdict queues a comment with the reason and stops. A passed observation with no verdict for the head runs `Task::CheckDiff`. The diff is safe when every change only moves a version (number, tag, ref, SHA or digest pin, with lockfile or checksum lines), in any file, and nothing in the new version breaks the project. The agent reads the release notes in the description and checks the repository for use of each breaking change, and answers unsafe when the project is affected or it cannot tell. Any other change is unsafe, and a major bump is not unsafe by itself. The old rule allowed only version changes in dependency or packaging files, so it marked a pure `actions/checkout` ref bump in a workflow unsafe (wormholes #130) and left a person to check triggers the agent could read. With a safe verdict, auto-merge on queues `Command::MergeRenovate`, which approves and merges only that head, unless the account may not merge (Read access, or a forge that refuses it), when the job waits as ready to merge and the job page names the account and the access it needs, and auto-merge off waits as ready to merge and merges on a later watch once the switch is on. An unsafe verdict queues a comment and waits. `NoChecks` and `Pending` change nothing, so a pull request with no checks never merges. A comment is a factory turn with `Command::PostComment`, answered by `Event::Commented`, and a `(head, kind)` pair is recorded so each kind posts once per head. A stopped or unsafe job waits at `Ask::Renovate` and keeps a watch-only command, so it still sees a merge, a close or a new head. A ready job keeps the full watch. Limits and the auto-merge switch arrive on every watch and core applies them. `Store::apply_in` writes no `job_events` row and does not rewrite the job for an `Event::RenovateObserved` that leaves the job equal, because every look would otherwise change the job's notification key. A change those settings cause, such as a merge or a stop, is recorded. `Event::Retry` on a stopped job resets both counts. When the stored access may rerun CI it reruns without counting that rerun. When it may not (Read), Retry returns the job to the factory turn, so a fresh watch reads the current head, CI and access and decides again. The executor checks the access of the credential it resolves before each Renovate rerun, approval and merge (an agent-requested rerun in a request job is not checked), because a collaborator may replace the token after the watch. A denied rerun returns `Event::RerunDenied`, which returns the job to the factory turn for a fresh watch, so Retry on a Read account goes to the failure analysis and not to a rerun. A denied approval or merge returns the job to watching and the executor makes no write call. The denial error starts with `NOT_PERMITTED`, and the scheduler treats it as a denial and not a retryable failure. `Event::Merged` ends in `merged` and `Event::ClosedUnmerged` in `cancelled`, which is Done and sends no notification. The comment bodies are plain text from the project account. A Renovate job has the requester `factory`, so every operation of it, and the discovery that creates it, runs as the project token. A project with Renovate on and no project token is skipped by discovery with a logged warning. The diff verdict records `from` and `to`, the upstream refs the bump moves between when the diff shows them, because the packaging analysis fetches the upstream build config changes between them. Each run starts a fresh session under `Session::Renovate`. It uses the project's Renovate agent, model and effort when one is saved, else the review stage's, see Renovate agent. Its MCP servers are the review stage's. The worker gets the log or the diff in its prompt and no GitHub token. Discovery: on each pass the scheduler lists, for each project with "Renovate pull requests" on, the open pull requests against the project's base branch that `renovate[bot]` or `renovate` opened, at most once per 5 minutes per project, which keeps it under the spec's 10 minutes. The last listing time per project lives in memory, so a restart lists again at once. A project with the switch off gets no listing call. `create_renovate_job` inserts the job and a `renovate_prs (project, number, job_id)` row in one transaction and does nothing when the pair exists, so a pull request gets one job across restarts, even after the job finishes and expires. Job expiry leaves the table alone and `remove_project` deletes its rows. The job's requester is `factory`, because the factory made it, see Job board. The scheduler reads the retry limits from `Settings` and the project's auto-merge flag on every watch and passes them to the executor, which builds `RenovateObserved`. The executor reads the pull request status with the project token, fetches the failure log only for a failed head and the diff only for a passed head with no verdict, and reports a merge or close at once. A watch-only look reports nothing while the head is the one the job already has. A merge approves the checked head with a plain review text and then squash-merges only that head, so a commit pushed after the watch is never approved. GitHub may still accept a review of an older commit that stays in the pull request, and the merge, guarded by the head SHA, is what refuses a moved head. A refused approval or merge returns the job to watching, so the next look sees the current head or a merge or close by a person. A rerun that finds no failed Actions run changes no count and stops triage with a comment, because a rerun that never happened must not use up the limit. A rerun of a Renovate job logs "Rerunning CI" and not that the agent asked. Discovery passes the stored Renovate account to `Forge::renovate_prs` for a Salsa or Forgejo project and `None` for GitHub. With `None` the forge keeps `renovate[bot]` and `renovate`. With a name the GitLab forge lists open merge requests with `author_username` and `target_branch` set to the base. | | Pull request jobs | A job on a pull request the user picked is a `Job` with `kind` `PullRequest(PickedPr)`. `PickedPr` holds the number, URL, title, head and base branch, a `fork` flag and a `PrMode`: `Request`, `QuickReview { comment }` or `ReviewAndFix`. `Request` runs clarify, spec and plan under the project's gates. The job never opens a pull request, because the picked one is the plan. When the plan arrives, the core folds it into one `PlannedPr` with `number` preset to the picked number, and joins the summaries and notes when the agent planned several, because the picked pull request takes all the work and a rejected plan would fail the job over a planning detail. An empty plan is still rejected. A preset number would skip the publish gate, so the job keeps a `pushed` flag, set by `Published`, and the gate applies until it is set. The job never merges: `Job::may_merge()` is false, and the person who picked the pull request merges it, including a pull request that someone else wrote. When CI is green and the reviewer has nothing left, the executor reports `MergeLeftToUser` and the job waits at `Ask::MergeLeftToUser`. It keeps a `PrWatch::MergeCloseOrComments` watch, so a merge ends it in `merged`, a close fails it with "the pull request was closed without merging", and a new review comment sends it to the agent as `AddressReview`. A job that reaches the wait with no comment watermark, such as a `ReviewAndFix` job whose reviewer approved on the first pass, has the first merge-wait watch set the watermark to the newest comment already on the pull request, or to an empty baseline when there is none, so a first comment posted later is delivered. That watch delivers nothing and looks up no one, so only comments posted after the wait began reach the agent. The comments older than the wait were on the pull request when the reviewer approved, and they must not make the agent push to a picked pull request. A comment posted in the few seconds between the approval and that first watch counts as old. The fix is pushed, which clears the approval, so CI and the reviewer run again before the merge is left to the user again. A stopped review keeps a `PrWatch::MergeOrClose` watch, which reports only a merge or a close. Neither watch merges or starts a review, and neither moves the comment watermark except to deliver comments or, for the merge-wait watch, to seed a missing one. The runner prepares the checkout from the forge's head ref of the pull request, which also exists for a fork, and pushes fast-forward only, with no force. A push the remote rejects because someone else pushed first fails with a distinct error, and the next run rebases the local branch's unpushed commits, the ones in `..HEAD`, onto the new head. Commits already in the pull request keep their ids and the new tip descends from the head, so no commit the factory did not write is rewritten, none is dropped, and the push stays fast-forward. The factory merges the head instead in three cases. The rebase conflicts, and the factory aborts it first. An unpushed commit is a merge commit, because a rebase would replay the base branch's commits into the pull request. Or the pull request's history was rewritten, so the head the checkout last took in is not an ancestor of the new head, because the old commits in the branch would come back under new ids. The factory records that head in `refs/factory/pr-/taken` and recovers it from the previously fetched head before each fetch. A branch with no recorded head is merged, because nothing shows which of its commits the pull request holds. A rebase that fails without a conflict is aborted and fails the run. A rebase a restart interrupted is aborted before the next push. A conflict with the base branch is met with a merge commit, never a rebase, because a rebase would rewrite commits the factory did not write. `POST /jobs` takes an optional `pr` (`12` or `#12`), and with it an optional `mode` (`request`, `quick-review` or `review-and-fix`) and a `comment` box that only a quick review reads. The server reads the pull request with `Accounts::resolve` for the requester and creates no job, answering 400 with the reason, when it is missing, closed or merged. It also refuses a fork or held pull request for `request` and `review-and-fix`, and allows a quick review of either. A review needs a `pr`, and only a review may have an empty text. Its text stays empty or holds the user's focus, and `Job::title()` gives an empty one the title "Review #N: ". A pull request is held while an unfinished job could push to or merge it: a Renovate job watching it, a request job whose plan has its number, or a pull request job that is not a quick review. `Store::create_pull_request_job` runs the held check in the same transaction as the insert, so two posts cannot both win, and `Store::holding_job` names the holder. The scheduler takes the remote branch and the base from the picked pull request and keeps a local branch `factory/job-N-pr-1`. The executor never calls `open_pr`, which would edit the title and description, so the factory never writes a picked pull request's title or description. A `commits_ready` without a title and description (`AgentResult::CommitsReady(None)`) therefore keeps the earlier `plan[pr].description` on a picked job that is not stacked, and on any job whose earlier run set one. Otherwise the factory opens the pull request itself and has no description, so the job fails with Retry. That is the first `Implement` run of a request job and the first `AddressReview` run of a fix in another branch. A returned description still replaces the old one. The executor pushes the local branch to the head branch with `push_fast_forward`. The executor pushes once. When the remote rejects the push, it merges the new head into the checkout and reports `HeadMoved`. A clean merge sends the job back to `Verifying`, so the checks run on the combined tree before the next push. When the checks pass, the executor saves the commit they ran on in `checked-head` in the job directory. It reads the checked-out branch, `HEAD` and the tip of the job branch before and after the checks, and sends the agent a repair request, as a failed check, when the checkout is not on the job branch, `HEAD` is not the branch tip, or the checks moved the branch or `HEAD`. The agent that gets the repair request starts in the checkout as the checks left it, because the job remembers the repair until the checks next pass or fail otherwise, so the scheduler marks that run, and the run that resumes after an answer, `keep_checkout` and the executor then skips preparing the checkout, which could refuse over the agent's edits. Every other run on a picked pull request, including a review, still prepares the checkout. A push rejected while another branch is checked out stops the job with a reason, and merges nothing. A publish pushes the job branch, so it compares `checked-head` with that branch tip. A publish whose branch tip is another commit pushes nothing and answers `HeadMoved`. A publish with an unfinished merge in the checkout answers `HeadMoved` with a conflict whether or not the project has checks. A restart at any point of the merge therefore cannot push an unchecked commit or retry against an unfinished merge. A conflicted merge is left unfinished and goes to the agent as `Task::MergeHead`, which finishes the merge with a commit. If the head moves again before the agent starts, checkout preparation redoes the merge against the latest head and leaves its conflict for the agent. The failed round and review round counts reset only when implementation of a new pull request starts, so repeated head conflicts, and a question the merge agent asks, do not reset either cap. A rejected push is not a failed round. Before the push, when the watch sees a conflict, before it reports a green pull request, and when the reviewer's checkout starts, the executor reads the pull request again. If someone retargeted it, the job fails with a reason that names both bases, and Retry publishes again. The held check also runs on Renovate discovery, which skips a held pull request, and on Retry, which refuses a job whose pull request another live job took. `ready_action` takes `may_merge`, and a job that may not merge gets `LeaveToUser`, so `forge.merge` is never called for it. A conflict gives the agent a merge-base prompt instead of the rebase prompt. Every commit-task prompt on a picked, non-stacked job says the pull request's title and description stay as they are and that the agent may leave `pull_request` out, or return `null` for it to hosted Codex, whose strict schema requires the key, because the factory never writes them. | @@ -445,6 +445,16 @@ No OpenRouter key was available, so each CLI ran with the settings above against | Codex | 0.165.0, the pinned one | `POST /api/v1/responses` with `Authorization: Bearer <key>`, no `auth.json` written | Finished. Stdout held no response id. The id was in the rollout file as `response_id`. A run with `--output-schema` was tried against the stub only and also finished; the stub answers whatever it is asked, so this says nothing about a real model, and the flag stays off as for Local because the local model skipped its tools with it. | | Copilot | 1.0.114, the pinned one | `POST /api/v1/chat/completions` with `Authorization: Bearer <key>` | Finished with exit code 0 with a custom provider, no GitHub token and no `COPILOT_OFFLINE`. The `assistant.message` line carried `apiCallId` `gen-test-1`. | +### The stage panel + +With OpenRouter selected, a stage's model field, and the Renovate agent card's, is a search over the stored model list (`Store::openrouter_models()`, id and name) instead of chips. + +- `AgentChoice.model_search` holds the stored models for OpenRouter and is `None` for the other agents. `agent_data` puts it in the form's `data-agent-models` JSON as `search`, so the list is in the page once per form, not once per stage. The browser makes no request to openrouter.ai. +- The panel draws no chip, no "CLI default" chip and no datalist for OpenRouter, and the node reads "Model required" while the field is blank. A `ul[data-model-results]` under the field, hidden until the script fills it, holds the matches. +- Typing in the field lists the first 20 stored models whose id or name contains the text, case-insensitively. Clicking a match, or ArrowDown and Enter, fills the field. With no match active, Enter saves the form as typed. A save does not check the id against the list, so `:free` and `:nitro` ids work. +- The hint reads "Search <n> OpenRouter models." or, with no stored list, "No OpenRouter model list is stored. Type a model id.". Without JavaScript the page is a plain text field with the hint. +- Switching the agent redraws the field without a reload. A field holding an id of the stored list is cleared on a switch to another agent, as a Local model is, and the results list is emptied. + ### Scheduling and recording an OpenRouter run - `openrouter_request` checks the model, then resolves the key, then picks the CLI, and applies `AgentFailed` on a failure before any checkout, as `local_request` does. The Renovate agent reuses it. diff --git a/e2e/tests/openrouter-models.spec.ts b/e2e/tests/openrouter-models.spec.ts new file mode 100644 index 00000000..4e99983c --- /dev/null +++ b/e2e/tests/openrouter-models.spec.ts @@ -0,0 +1,136 @@ +import { ADMIN, expect, startFactory, test as base, type Factory } from '../fixtures'; + +const test = base.extend<{ own: Factory }>({ + own: async ({}, use) => { + const { factory, stop } = await startFactory(); + await use(factory); + await stop(); + }, + baseURL: async ({ own }, use) => { + await use(own.url); + }, + extraHTTPHeaders: async ({}, use) => { + await use({ 'Tailscale-User-Login': ADMIN }); + }, +}); + +function seed(own: Factory, count = 2) { + const models = ['openai/gpt-5|OpenAI: GPT-5', 'x-ai/grok-4|xAI: Grok 4']; + for (let i = 0; i < count - 2; i++) models.push(`acme/model-${i}|Acme Model ${i}`); + own.fixture('openrouter-models', ...models.flatMap((model) => ['--model', model])); +} + +test('typing in the model field lists matches from the stored models and picking one fills it', async ({ + page, + own, +}) => { + seed(own, 40); + const requests: string[] = []; + page.on('request', (request) => requests.push(new URL(request.url()).hostname)); + await page.goto('/settings/projects/maestro?stage=spec'); + const spec = page.locator('[data-panel="spec"]'); + const field = spec.getByLabel('Model'); + const results = spec.locator('[data-model-results] li'); + const label = page.locator('.pipeline [data-part="spec"] [data-model-label]'); + + await spec.getByRole('radio', { name: 'OpenRouter' }).check(); + await expect(label).toHaveText('Model required'); + await expect(spec.locator('.model-chips .chip')).toHaveCount(0); + await expect(spec.locator('[data-model-hint]')).toHaveText('Search 40 OpenRouter models.'); + + await field.fill('GROK'); + await expect(results).toHaveText(['x-ai/grok-4 (xAI: Grok 4)']); + await field.fill('acme'); + await expect(results).toHaveCount(20); + await field.fill('openai: gpt'); + await results.first().click(); + await expect(field).toHaveValue('openai/gpt-5'); + await expect(label).toHaveText('openai/gpt-5'); + await expect(results).toHaveCount(0); + + await field.fill('grok'); + await field.press('ArrowDown'); + await field.press('Enter'); + await expect(field).toHaveValue('x-ai/grok-4'); + expect(requests.filter((host) => host.includes('openrouter'))).toEqual([]); +}); + +test('an id that is not in the list saves, and switching agents redraws the field without a reload', async ({ + page, + own, +}) => { + seed(own); + await page.goto('/settings/projects/maestro?stage=spec'); + const spec = page.locator('[data-panel="spec"]'); + const field = spec.getByLabel('Model'); + const chips = spec.locator('.model-chips .chip'); + + await spec.getByRole('radio', { name: 'OpenRouter' }).check(); + await field.fill('x-ai/grok-4'); + await spec.getByRole('radio', { name: 'Claude' }).check(); + await expect(chips).toHaveText(['CLI default', 'fable', 'opus', 'sonnet', 'haiku']); + await expect(field).toHaveValue(''); + await expect(spec.locator('[data-model-results] li')).toHaveCount(0); + await spec.getByRole('radio', { name: 'OpenRouter' }).check(); + await expect(chips).toHaveCount(0); + + await field.fill('openai/gpt-5:nitro'); + await page.getByRole('button', { name: 'Save maestro' }).click(); + await page.goto('/settings/projects/maestro?stage=spec'); + await expect(page.locator('input[name="spec_agent"][value="openrouter"]')).toBeChecked(); + await expect(spec.getByLabel('Model')).toHaveValue('openai/gpt-5:nitro'); +}); + +test('the Renovate agent card searches the stored models too', async ({ page, own }) => { + seed(own); + await page.goto('/settings/projects/maestro'); + const card = page.locator('.renovate-agent-form'); + const field = card.getByLabel('Model'); + await card.getByRole('checkbox', { name: /separate agent for Renovate/ }).check(); + await card.getByRole('radio', { name: 'OpenRouter' }).check(); + await expect(card.locator('.model-chips .chip')).toHaveCount(0); + await expect(card.locator('[data-model-hint]')).toHaveText('Search 2 OpenRouter models.'); + await field.fill('grok'); + await card.locator('[data-model-results] li').first().click(); + await expect(field).toHaveValue('x-ai/grok-4'); + + await card.getByRole('radio', { name: 'Claude' }).check(); + await expect(card.locator('.model-chips .chip')).toHaveText(['CLI default', 'fable', 'opus', 'sonnet', 'haiku']); + await expect(field).toHaveValue(''); + await card.getByRole('radio', { name: 'OpenRouter' }).check(); + await field.fill('custom/model:free'); + await card.getByRole('button', { name: 'Save Renovate agent' }).click(); + await expect(page.getByText('Saved.')).toBeVisible(); + await page.reload(); + await expect(field).toHaveValue('custom/model:free'); +}); + +test('arrowing past the visible rows scrolls the active result into view and Escape closes the list', async ({ + page, + own, +}) => { + seed(own, 40); + await page.goto('/settings/projects/maestro?stage=spec'); + const spec = page.locator('[data-panel="spec"]'); + const field = spec.getByLabel('Model'); + const list = spec.locator('[data-model-results]'); + await spec.getByRole('radio', { name: 'OpenRouter' }).check(); + await expect(field).toHaveAttribute('role', 'combobox'); + await expect(field).not.toHaveAttribute('list', /.*/); + await field.fill('acme'); + await expect(field).toHaveAttribute('aria-expanded', 'true'); + for (let i = 0; i < 20; i++) await field.press('ArrowDown'); + const active = spec.locator('[data-model-results] li[aria-selected="true"]'); + await expect(active).toHaveText('acme/model-19 (Acme Model 19)'); + await expect(active).toBeInViewport(); + expect(await list.evaluate((el) => el.scrollTop)).toBeGreaterThan(0); + await field.press('Escape'); + await expect(list).toBeHidden(); + await expect(field).toHaveAttribute('aria-expanded', 'false'); + await expect(field).not.toHaveAttribute('aria-activedescendant', /.*/); + + await spec.getByRole('radio', { name: 'Claude' }).check(); + await expect(field).toHaveAttribute('list', 'model-suggestions-spec'); + await expect(field).not.toHaveAttribute('role', /.*/); + await expect(spec.locator('#model-suggestions-spec option')).toHaveCount(4); +}); diff --git a/e2e/tests/project-settings.spec.ts b/e2e/tests/project-settings.spec.ts index a8070f15..3f7f6b88 100644 --- a/e2e/tests/project-settings.spec.ts +++ b/e2e/tests/project-settings.spec.ts @@ -101,7 +101,7 @@ test('OpenRouter is selectable in every stage, shows its effort levels and needs await expect(spec.locator('[data-effort-seg] label')).toHaveText(['low', 'medium', 'high', 'xhigh']); await expect(spec.locator('.model-chips .chip')).toHaveCount(0); await expect(node(page, 'spec').locator('[data-model-label]')).toHaveText('Model required'); - await expect(spec.locator('[data-model-hint]')).toContainText('Type an OpenRouter model ID'); + await expect(spec.locator('[data-model-hint]')).toContainText('No OpenRouter model list is stored. Type a model id.'); await page.getByRole('button', { name: `Save ${project}` }).click(); await expect(page.getByText('The spec stage runs on OpenRouter, which needs a model ID.')).toBeVisible();