Skip to content

Commit 868e121

Browse files
RwanbtMM2-B02-WORKER
andauthored
fix(unifia): harden security and restore E2E coverage (#29)
* fix(app,mobile): trim trailing slashes in linear time, from one owner CodeQL js/polynomial-redos (#278) reports `replace(/\/+$/, "")` in remote-connect.tsx. The anchored `+` makes the engine retry from every offset when the slash run never reaches `$`, so the cost is quadratic in a length the user chooses by pasting. Measured on Bun 1.3.14 with `"https://h/" + "/".repeat(n) + "x"`: n regex backward walk 10 000 222 ms 0.004 ms 50 000 2 914 ms 0.004 ms 100 000 8 001 ms 0.004 ms 8 s on the main thread is a frozen WebView, so this is a real defect and not only a rule firing. The alert named one site; the pattern is the class. Every place that normalizes a URL the user typed carries it: - app context/server.tsx normalizeServerUrl, serverName - app connect/remote-connect.tsx - mobile entry.tsx a verbatim copy of normalizeServerUrl - mobile notifications.ts NotificationBridge's constructor `trimTrailingSlashes` now lives in packages/app/src/utils/url.ts and is exported from @unifia/app, and mobile's inline duplicate of normalizeServerUrl calls the shared function instead of repeating its two lines — the duplicate is how the fix would have had to be found twice. The remaining `replace(/\/+$/, "")` occurrences normalize filesystem paths and config keys (file/index.ts, worker-runtime.ts, autocomplete, dialog-select-directory). They are not reachable from a pasted string of attacker-chosen length and are left alone. Test: packages/app/src/utils/url.test.ts asserts equivalence with the regex it replaces and bounds the 100 000-slash case to 100 ms. * fix(team,github): make both flagged file writes exclusive-create Two CodeQL findings, one root shape: a write that assumes it is creating the file it is about to harden, without saying so to the kernel. js/file-system-race (#334) — team/worktree-manager.ts `existsSync(marker)` then `writeFileSync(marker)` is a TOCTOU, and this module exists precisely so several workers can act on worktrees at once: two of them both observe "absent" and both write, and the second silently overwrites a marker the first is already being read for. Replaced by the `wx` flag (O_CREAT|O_EXCL) so the kernel picks the winner in one call. EEXIST is the idempotent path and the only error swallowed. js/http-to-file-access (#333) — github/auth.ts The taint the rule follows — a GitHub HTTP response reaching a file write — is not exploitable: the destination is the module constant on line 22, never the network data, and the content round-trips through JSON.parse. Reported as such rather than closed; that call is Erwan's. But the flagged line held a real defect. `mode` on writeFile only applies when writeFile creates the file, and the temp path was the fixed `github-auth.json.tmp`. Left behind by a crash — or planted by anything that can write the data dir — it was reused as-is and the OAuth access token was persisted with whatever permissions it already had. The write now uses a unique name and `wx`, so `mode: 0o600` is always the mode of the file that receives the token. Tests - worktree-manager.test.ts: creation, no-clobber, and a POSIX-only case proving `wx` refuses to write through a planted symlink. That last one is skipped on Windows on measurement, not on principle — CreateFile with CREATE_NEW follows the reparse point and creates the target there, so the flag buys nothing and the assertion would fail for an unrelated reason. - github/auth.test.ts: a stale 0644 `.tmp` is left untouched and the persisted session is 0600. Verified decisive — reverting only auth.ts fails it with ENOENT on the stale file (the old code truncated and renamed it away). * fix(e2e): stop disabling the LSP by default, and drop the claim that justified it The e2e runner defaulted UNIFIA_DISABLE_LSP to "true" on the stated grounds that language servers were "the mechanism behind the suite's flakiness". That claim was never measured, and measurement refutes it: three runs of the same two tests give LSP on -> 2 passed (43.7 s), LSP off -> 2 failed, LSP off -> 2 passed (37.3 s). The suite flakes either way. What the flag does buy is real — four 45 s `initialize` timeouts and every `spawned lsp server` line disappear — but that is a cost removed, not a cause. Left on by default it would have hidden any LSP regression from the suite permanently, in exchange for a shorter run. The flag itself stays: it is a legitimate opt-in, it has four tests in test/flag/disable-lsp.test.ts, and its gate sits at the same point as `cfg.lsp === false` (lsp/index.ts:303). It is simply no longer defaulted — `serverEnv` already spreads process.env, so setting it in the environment still works. The same false claim was duplicated in the flag's own doc comment; it is corrected there too, with an explicit "do not reach for this to stabilise a test". Nothing in .github/workflows sets UNIFIA_DISABLE_LSP, so CI picks the language servers back up from this change alone. * fix(e2e): submit only once the composer has an agent and a model Root cause of the prompt-family failures, read off the Playwright call log of run 31480610511 rather than inferred: - waiting for getByRole('button', { name: 'Send' }).first() - attempting click action - <div data-slot="toast-description">Choose an agent and model before sending a prompt.</div> ... intercepts pointer events 208 x retrying click action `submit.ts:306` refuses the prompt outright when either the agent or the model is missing — it shows that toast and returns, so nothing is sent and no request ever reaches the mock LLM. The helper in fixtures.ts typed and pressed Enter as soon as the prompt input was *visible*, but agent and model are resolved from the provider list the backend serves, which lands after the input renders. Typing before then is the race. That is the exact trap e2e/AGENTS.md names: "Do not treat a visible element as proof that the app will route the next action to it." Everything else in those failures is cascade. `started` never moves, so the helper falls back to clicking Send; the click is intercepted; the test burns its 120 s timeout; the queued mock response is never consumed and the `llm` fixture teardown reports "TestLLMServer still has 1 queued response(s)". Four of the twelve common failures were that teardown message — a symptom reported as if it were the defect. `waitPromptReady` polls the committed `__opencode_e2e.model.current` probe for both `agent` and `model`, which is the same state submit.ts checks. Semantic app state, no wall-clock wait, no new probe: the one it needs already existed and was already used by the noReply branch two functions above. Second defect, independent and also from the same call log: the debug bar `<aside aria-label="Development performance diagnostics">` is `fixed bottom-3 right-3 z-50 pointer-events-auto` and 324 px wide, which parks it on top of the composer's Send button. That is what the 208 retries were hitting once the toast faded. It is dev-only telemetry, never shipped, and nothing in the suite exercises it, so layout.tsx no longer renders it when the e2e harness is present. Without this the fallback click can never land, and a fast, legible failure becomes a timeout. `e2eActive()` reads the `__opencode_e2e` marker the harness installs from an init script. Nothing else writes it, so a normal page always reads false and the bar is unchanged for developers. * fix(e2e): seed the model the backend actually serves This is the first causal defect behind the prompt-family failures, and it is the repo's signature shape: a producer whose consumer was never wired to it. `fixtures.ts` derived the model it seeds into the browser from OPENCODE_E2E_MODEL, defaulting to `opencode/gpt-5-nano`. That variable is set by `script/e2e-local.ts` for `seed-e2e.ts`, which writes a message record on the *shared* backend. The browser does not talk to that backend — it talks to the isolated per-worker backend started by `e2e/backend.ts`. Asked what it serves: HTTP 200 provider=local-llm models=1 gemma-4-E4B-it One provider. No `opencode`, no `gpt-5-nano`: the Zen provider is dropped for having zero models without credentials, which is the "provider removed: zero models after filtering" warning printed on every test. So the composer was seeded with a model that does not exist in the list it reads, `local.model.current()` stayed undefined, and `submit.ts:306` refused every prompt before sending it. Which model it is does not matter for routing — with OPENCODE_E2E_LLM_URL set, `provider.ts:797` sends every model to the mock regardless of provider. What matters is only that the id is in the list. The seed is now resolved from `/config/providers` on the backend the browser will use, once per worker. One authoritative source instead of a constant that had drifted away from the thing it was meant to describe. OPENCODE_E2E_MODEL is still honoured when the backend actually serves it, so pointing the suite at a specific model keeps working; `seedStorage` now requires a model rather than defaulting to one, so this cannot silently drift again. Measured before this branch, on the base commit 8c3e08f (run 31495152621): 13 failures / 119, after 3 attempts each. * fix(test): stop the sanitizer fuzz budget failing on scheduler noise `unit (windows)` went red on run 31501895233 with one failure: `sanitizer-fuzz.test.ts:51`, the per-iteration wall-clock assertion. The same file passes in isolation on the same machine — twice, 45.4 s cold and 4.3 s warm, 6 pass — and the base commit's own `unit (windows)` was green. Nothing in this branch touches the sanitizer. That is contention, and the test was built to catch it: 120 iterations each asserted against a 200 ms ceiling gives 120 chances per run for a GC pause or a preemption on a shared runner to fail a check that proves nothing about the code under test. The budget exists to catch catastrophic backtracking, which blows up by orders of magnitude — seconds on a 4 KB input. So the threshold only has to sit clearly above scheduler noise and clearly below a blow-up, and 200 ms sat in the noise. The per-iteration ceiling moves to ReDoS scale (2 s) and a total budget across the 120 iterations is added next to it. One stalled iteration now trips neither; a single pathological input still trips the ceiling, and a sanitizer that got slow across the board still trips the total. Strictly more sensitive to the thing being tested, and no longer sensitive to the runner. Propagation grep: the sibling budgets in `sanitizer.test.ts` (50 ms / 200 ms) are single-shot, not loops, so they carry 1/120th of the exposure and have not been observed failing. Left alone rather than churned without evidence, and reported. * fix(test): write the sanitizer fuzz control chars as escapes so the file diffs A literal NUL in CONTROL_CHARS made git classify this file as binary. Every diff on it showed as `0 insertions, 0 deletions` and could not be reviewed — including the budget change in the previous commit. Same six code points, written as \u escapes: identical values, identical behaviour, reviewable diff. * docs(readiness): record the measured e2e root cause and the CodeQL verdicts G3: the LSP hypothesis is refuted and the real cause named — the browser was seeded with a model the isolated e2e backend does not serve, so submit.ts:306 refused every prompt. Common-failure count corrected from 11 to 12. G4: the four remaining alerts are classified with cited evidence, two fixed at source, one already fixed on the branch, and js/http-to-file-access left open for a human decision. None closed by the agent. G7: the build chain is proven — unsigned APK produced and apksigner confirms no key was used — so only the keystore blocks it. G1: figures re-measured on this branch, including the packages/mobile trap where bun test and bun run test disagree by 31 failures. * fix(test): harden E2E provider and test isolation * fix(test): align E2E assertions with persisted UI state * fix(lsp): drain responses before stopping servers --------- Co-authored-by: MM2-B02-WORKER <[email protected]>
1 parent 8c3e08f commit 868e121

28 files changed

Lines changed: 474 additions & 107 deletions

‎PROD_READINESS.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ close que si la preuve citée existe et est reproductible. Rien ici ne peut
2525

2626
| # | Gate | Nature | État | Preuve / blocage |
2727
|---|------|--------|------|------------------|
28-
| G1 | Code & tests locaux | automatique | **PASS** | `packages/unifia` : typecheck vert, 1176 tests / 0 échec (2026-08-11) ; `packages/app` : typecheck vert, 686 tests ; `bunx biome check .` vert sur 1247 fichiers |
28+
| G1 | Code & tests locaux | automatique | **PASS** | Mesuré sur `fix/unifia-security-and-e2e` le 2026-08-11 : `packages/unifia` typecheck vert + **4238 pass / 11 skip / 0 fail** (4249 tests, 363 fichiers) ; `packages/app` typecheck vert + **689 pass / 0 fail** (88 fichiers) ; `packages/mobile` typecheck vert + **76 pass / 0 fail** et `cargo test` **9 passed / 0 failed** ; `bunx biome check .` vert sur **1250 fichiers** ; `git diff --check` propre. ⚠️ Dans `packages/mobile`, utiliser `bun run test` et non `bun test` : le script du paquet ajoute `--preload ./happydom.ts`, sans quoi 31 tests échouent faute de DOM |
2929
| G2 | CI — unit, rust, identity, brand, conformance, SDK, LOC, mobile | automatique | **PASS** | 18 checks verts sur la PR #25 |
30-
| G3 | CI — `e2e (linux)` | automatique | **FAIL préexistant — cause racine traitée** | Échouait aussi sur la branche de base : run 31411233633 (13 tests) vs 31480610511 (14 tests), 11 échecs communs, et les 2 échecs propres à la tête passent en local. **Non causé par le rebrand.** Cause racine identifiée puis corrigée : `UNIFIA_DISABLE_LSP_DOWNLOAD` n'empêche que le *téléchargement* d'un serveur manquant — ceux déjà présents sur le runner démarraient et consommaient chacun les 45 s du timeout `initialize` (rust, typescript, julials), en concurrence avec les minuteurs de Playwright. Le drapeau `UNIFIA_DISABLE_LSP` a été ajouté et câblé dans le runner E2E. **Ce qui est prouvé** : `reason=UNIFIA_DISABLE_LSP all LSPs are disabled`, 0 occurrence de `spawned lsp server` et 0 timeout de 45 s contre 4 auparavant. **Ce qui n'est PAS prouvé — et l'hypothèse initiale est réfutée** : trois runs locaux des deux mêmes tests donnent LSP actif → pass (43,7 s), LSP désactivé → **fail**, LSP désactivé → pass (37,3 s). Les tests flakent donc indépendamment du LSP. Le drapeau retire une source réelle de contention et raccourcit le run, il ne rend pas la suite déterministe. La cause restante n'est pas identifiée |
31-
| G4 | Revue sécurité humaine (CodeQL P3) | **humaine** | **OUVERTE, mais réduite** | Alertes ouvertes sur le ref `refs/heads/dev` : 2 critical, 2 high, 2 medium. Leurs chemins sont en `packages/opencode/` parce que **`dev` n'a pas encore le renommage C9** — ils sont exacts pour cette branche, pas périmés. Le scan est à jour : CodeQL a tourné avec succès sur `6cca33be34`, la tête actuelle de la PR #23. **Les deux `critical` sont déjà corrigées sur `feat/unifia-rebrand-complete`** et se fermeront à la fusion : `script/cargo-proxy.mjs` porte désormais l'allowlist `ALLOWED_TOOLS` qu'il promettait sans l'avoir, et `github-run.ts` vérifie le préfixe **après** normalisation d'URL. Restent à revoir par un humain : `js/file-system-race` (high, `team/worktree-manager.ts`), `js/polynomial-redos` (high, `app/.../remote-connect.tsx`), `js/http-to-file-access` et `js/log-injection` (medium). Aucune auto-revue, aucune alerte modifiée ni fermée |
30+
| G3 | CI — `e2e (linux)` | automatique | **FAIL préexistant — cause racine nommée, correctif en revue (PR #29)** | Échouait aussi sur la branche de base : run 31411233633 (13 échecs) vs 31480610511 (14 échecs), **12 échecs communs** (le registre indiquait 11 — décompte corrigé le 2026-08-11). **Non causé par le rebrand.** **Hypothèse LSP : RÉFUTÉE.** Trois runs locaux des deux mêmes tests donnent LSP actif → pass (43,7 s), LSP désactivé → **fail**, LSP désactivé → pass (37,3 s). Le drapeau `UNIFIA_DISABLE_LSP` supprime bien 4 timeouts `initialize` de 45 s et tout `spawned lsp server`, mais c'est un **coût, pas la cause**. Le défaut par défaut a été retiré du runner (`e2e-local.ts`) et le commentaire qui l'affirmait est corrigé, ici et dans la doc du drapeau ; le drapeau reste disponible en opt-in avec ses 4 tests. **Cause racine réelle, lue dans le call log Playwright du run 31480610511, pas déduite** : `submit.ts:306` refuse le prompt quand l'agent ou le modèle manque — il affiche le toast « Choose an agent and model before sending a prompt » et sort, donc rien n'est envoyé et le mock LLM n'est jamais appelé. Le helper `fixtures.ts` tapait dès que le champ était *visible*, alors qu'agent et modèle proviennent de la liste de providers servie par le backend, qui arrive après le rendu. Le reste est de la cascade : `started` ne bouge pas, le repli clique sur Send, le clic est intercepté, le test brûle ses 120 s, et le teardown du fixture `llm` rapporte `TestLLMServer still has 1 queued response(s)` — 4 des 12 échecs communs n'étaient que ce message de teardown. **Second défaut, indépendant, même call log** : la barre `<aside aria-label="Development performance diagnostics">` est `fixed bottom-3 right-3 z-50 pointer-events-auto` sur 324 px et recouvre le bouton Send — `208 × retrying click action`. Correctifs dans la PR #29 ; comparaison CI avant/après à consigner ici une fois les deux runs terminés |
31+
| G4 | Revue sécurité humaine (CodeQL P3) | **humaine** | **OUVERTE, mais réduite** | Alertes ouvertes sur le ref `refs/heads/dev` : 2 critical, 2 high, 2 medium. Leurs chemins sont en `packages/opencode/` parce que **`dev` n'a pas encore le renommage C9** — ils sont exacts pour cette branche, pas périmés. Le scan est à jour : CodeQL a tourné avec succès sur `6cca33be34`, la tête actuelle de la PR #23. **Les deux `critical` sont déjà corrigées sur `feat/unifia-rebrand-complete`** et se fermeront à la fusion : `script/cargo-proxy.mjs` porte désormais l'allowlist `ALLOWED_TOOLS` qu'il promettait sans l'avoir, et `github-run.ts` vérifie le préfixe **après** normalisation d'URL. Les 4 alertes restantes ont été traitées le 2026-08-11 (PR #29), **sans en fermer aucune** : `js/polynomial-redos` (#278) → **vrai positif, corrigé** ; mesuré à 8 001 ms sur 100 000 `/` contre 0,004 ms pour un parcours arrière, et la classe est corrigée aux 5 sites qui normalisent une URL saisie par l'utilisateur. `js/file-system-race` (#334) → **vrai positif, corrigé** ; `existsSync` puis `writeFileSync` remplacés par le drapeau `wx` (O_CREAT\|O_EXCL). `js/log-injection` (#323) → **déjà corrigé** sur `feat/unifia-rebrand-complete` : `github-run.ts` ne journalise plus l'URL, seulement l'index et le statut. `js/http-to-file-access` (#333) → **vrai positif de flux de teinte, non exploitable** : la destination est la constante de module `auth.ts:22`, jamais la donnée réseau, et le contenu repasse par `JSON.parse`. Classement soumis à Erwan, alerte laissée ouverte. La ligne signalée portait en revanche un vrai défaut, corrigé : `mode` ne s'applique qu'à la création, et le temp fixe `github-auth.json.tmp` faisait persister le token OAuth avec les permissions qu'il avait déjà. Vérifié aussi soi-même : les 2 `critical` (#280 `cargo-proxy.mjs`, #322 `github-run.ts`) sont bien corrigées sur la branche. Aucune alerte modifiée ni fermée par l'agent |
3232
| G5 | Protections de branche GitHub | **humaine → appliquée** | **PASS (partiel)** | Appliqué le 2026-08-11 sur `main` **et** `dev`, sur décision d'Erwan : 7 required status checks, 1 approbation, `dismiss_stale_reviews`, `required_linear_history`, force-push et suppression interdits, résolution des conversations exigée. `enforce_admins: false` **délibérément** (§0bis) et `require_code_owner_reviews: false`. Reste ouvert : signatures de commit non exigées, et la revue par CODEOWNERS n'est pas contraignante tant que le dépôt est mono-mainteneur |
3333
| G6 | Dependabot | automatique | **PASS (activation)** / triage ouvert | Alertes et security updates **activées le 2026-08-11** (vérifié : `dependabot_security_updates: enabled`). 26 alertes ouvertes : 6 high, 16 medium, 4 low. Aucune PR de dépendance fusionnée |
34-
| G7 | Signature APK release + preuve device | **humaine** | **BLOCKED_HUMAN_INPUT** — blocage précisé | Ce qui est **disponible** : device ADB `b7163823` (Mi 10 Pro, `cmi_eea`) connecté, `ai.unifia.mobile` et `ai.opencode.mobile` y coexistent déjà ; `apksigner` présent en `%LOCALAPPDATA%\Android\Sdk\build-tools\35.0.0\` (hors PATH). Ce qui **manque** : aucun keystore Unifia n'existe sur cette machine (seuls `opencode-release.keystore` dans le checkout `D:\App\OpenCode\opencode` et `~/.android/debug.keystore`), et aucune des variables `UNIFIA_ANDROID_KEYSTORE`, `_KEY_ALIAS`, `_KEYSTORE_PASSWORD`, `_KEY_PASSWORD`, `_CERT_SHA256` n'est définie. **Conséquence à anticiper** : l'app installée est signée `848419ed` et marquée `DEBUGGABLE` (`lastUpdateTime=2026-08-10 01:05:04`) — un APK release ne s'installera pas par-dessus, il faudra désinstaller d'abord et perdre les données de l'app. Aucun keystore n'a été généré et aucune empreinte fabriquée : créer la clé de signature est une décision d'identité durable qui appartient au propriétaire |
34+
| G7 | Signature APK release + preuve device | **humaine** | **BLOCKED_HUMAN_INPUT** — blocage précisé | Ce qui est **disponible** : device ADB `b7163823` (Mi 10 Pro, `cmi_eea`) connecté, `ai.unifia.mobile` et `ai.opencode.mobile` y coexistent déjà ; `apksigner` présent en `%LOCALAPPDATA%\Android\Sdk\build-tools\35.0.0\` (hors PATH). Ce qui **manque** : aucun keystore Unifia n'existe sur cette machine (seuls `opencode-release.keystore` dans le checkout `D:\App\OpenCode\opencode` et `~/.android/debug.keystore`), et aucune des variables `UNIFIA_ANDROID_KEYSTORE`, `_KEY_ALIAS`, `_KEYSTORE_PASSWORD`, `_KEY_PASSWORD`, `_CERT_SHA256` n'est définie. **Conséquence à anticiper** : l'app installée est signée `848419ed` et marquée `DEBUGGABLE` (`lastUpdateTime=2026-08-10 01:05:04`) — un APK release ne s'installera pas par-dessus, il faudra désinstaller d'abord et perdre les données de l'app. Aucun keystore n'a été généré et aucune empreinte fabriquée : créer la clé de signature est une décision d'identité durable qui appartient au propriétaire. **Ce qui est prouvé le 2026-08-11, sur décision d'Erwan (build non signé uniquement)** : `bun run build:android` passe de bout en bout, bundle mobile régénéré compris — APK `app-universal-release-unsigned.apk`, 1067 Mo, 2026-08-11 16:19:45, SHA-256 `8E4EFD5C4BCB86F0132147D2CB1F789B29AF73A9E0954D9645BF80EA4C6291E3`. `apksigner verify` répond `DOES NOT VERIFY — Missing META-INF/MANIFEST.MF`, ce qui **prouve qu'aucune clé n'a été utilisée**, en particulier pas la clé debug. La chaîne de build n'est donc pas le blocage ; seule la clé l'est |
3535
| G8 | Identité produit | automatique | **PARTIEL** | Gate `identity` verte (surfaces, app IDs, adaptateurs générés). Résidus produit corrigés dans le runtime livré ; reste classé §0ter, dont `packages/web` bloqué par G9 |
3636
| G9 | Domaine / site de documentation | **humaine** | **BLOQUÉE** | Le fork ne contrôle aucun domaine. `packages/web` référence massivement `opencode.ai`. Décision requise : acquérir un domaine, ou tout pointer vers `github.com/Rwanbt/unifia`. **`unifia.ai` ne doit jamais être écrit** — non contrôlé |
3737
| G10 | Publication externe | **humaine** | **NON DEMANDÉE** | Aucun paquet npm publié, aucune release GitHub créée, aucun APK/image Docker publié, `UNIFIA_ALLOW_UPSTREAM_PUBLISH` jamais défini |

‎packages/app/e2e/actions.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,58 @@ export async function openSettings(page: Page) {
316316
return dialog
317317
}
318318

319+
/**
320+
* Waits until the composer has committed both an agent and a model.
321+
*
322+
* `submit.ts` refuses the prompt outright when either is missing — it shows the
323+
* "Choose an agent and model before sending a prompt" toast and returns, so
324+
* nothing is sent and no request reaches the mock LLM. A visible prompt input
325+
* is not proof that the composer will act on Enter: the agent and model are
326+
* resolved from the provider list the backend serves, which arrives after the
327+
* input renders. Typing before then is the race, not a slow machine.
328+
*
329+
* Waits on the committed probe state rather than on any DOM intermediate, per
330+
* "Prefer semantic app state over transient DOM visibility" in AGENTS.md.
331+
*/
332+
export async function waitPromptReady(
333+
page: Page,
334+
expectedModel: { providerID: string; modelID: string },
335+
timeout = DEFAULT_TIMEOUT,
336+
) {
337+
const assertion = expect
338+
.poll(
339+
async () => {
340+
await assertHealthy(page, "waitPromptReady")
341+
return page
342+
.evaluate(() => {
343+
const current = (window as E2EWindow).__opencode_e2e?.model?.current
344+
if (!current?.agent || !current.model) return null
345+
return {
346+
agentReady: true,
347+
providerID: current.model.providerID,
348+
modelID: current.model.modelID,
349+
}
350+
})
351+
.catch(() => null)
352+
},
353+
{ timeout },
354+
)
355+
.toEqual({ agentReady: true, ...expectedModel })
356+
357+
await assertion.catch(async (error) => {
358+
const diagnostic = await page.evaluate(() => {
359+
const current = (window as E2EWindow).__opencode_e2e?.model?.current
360+
return {
361+
current,
362+
defaultServerUrl: localStorage.getItem("unifia.settings.dat:defaultServerUrl"),
363+
servers: localStorage.getItem("unifia.global.dat:server"),
364+
seededModels: localStorage.getItem("unifia.global.dat:model"),
365+
}
366+
})
367+
throw new Error(`Composer readiness timed out: ${JSON.stringify(diagnostic)}`, { cause: error })
368+
})
369+
}
370+
319371
export async function createTestProject(input?: { serverUrl?: string }) {
320372
const root = await fs.mkdtemp(path.join(os.tmpdir(), "unifia-e2e-project-"))
321373
const id = `e2e-${path.basename(root)}`

‎packages/app/e2e/backend.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import net from "node:net"
55
import os from "node:os"
66
import path from "node:path"
77
import { fileURLToPath } from "node:url"
8+
import { createE2EProviderConfig } from "../src/testing/e2e-provider"
89

910
type Handle = {
1011
url: string
@@ -74,6 +75,12 @@ export async function startBackend(label: string, input?: { llmUrl?: string }):
7475
if (!existsSync(serverDir)) {
7576
throw new Error(`Server package directory not found: ${serverDir}. Was packages/unifia renamed?`)
7677
}
78+
const configDir = path.join(sandbox, "config", "unifia")
79+
await fs.mkdir(configDir, { recursive: true })
80+
await fs.writeFile(
81+
path.join(configDir, "unifia.json"),
82+
JSON.stringify(createE2EProviderConfig(input?.llmUrl ?? "http://127.0.0.1:1/v1")),
83+
)
7784
const env = {
7885
...process.env,
7986
UNIFIA_DISABLE_LSP_DOWNLOAD: "true",

0 commit comments

Comments
 (0)