<!-- docs/internals/15_testing.md at c0eed7328db2609e5a535be704e90638aef1c111 · https://github.com/pingdotgg/t3code/blob/c0eed7328db2609e5a535be704e90638aef1c111/docs/internals/15_testing.md · status: fresh -->

# Testing

Rules for writing tests, and for asking for them in review.

## What to test

- **Proof is not a permanent test.** Every fix needs proof recorded in the PR's Verification section: a repro command, a temporary test, a scenario run, a runtime trace, or before/after captures. Delete temporary proof tests before committing unless they clear the keep bar below. Zero new tests is a valid, expected outcome for narrow fixes.
- **Keep bar.** Commit a new test (or table row) only when **both** are true:
  1. It catches a realistic regression that TypeScript, schemas, lint, and existing tests miss.
  2. Normal users would hit it and we would drop work to hotfix it — **or** it guards a high-consequence area: security/permissions/secrets, data loss/corruption, stuck/lost runs, protocol correctness, migrations, git/worktree safety, or a documented perf/budget guard.
- **Leave out:** what types or schemas already guarantee, trivial logic, smoke runs, mock-call mirrors, callback wiring, props rendered to static markup, exotic edges (rare Unicode/encodings, symlink swaps with harmless outcomes, multi-way races with harmless fallbacks), UI cosmetic/copy/ordering/threshold/focus/scroll-hide tweaks, one-off typo or null guards, dev/CI tooling scripts, and redundant `.each` rows taking the same branch as a kept row.
- **Backend changes** to orchestration, persistence, auth, git/worktree safety, or provider protocol main flows ship with focused tests.
- **Extend before you add.** When an existing test or table covers the behavior, add a row or assertion there instead of a new `it`. Almost never create a new standalone test file for a single bug fix (especially `*.browser.test.*`). Test at one layer—the lowest one that fails on `main`—and when a shared helper fixes several call sites, test one representative caller instead of repeating the case in wrappers or across web and mobile.
- **Browser tests are expensive.** Add a browser test only when the behavior clears the keep bar above **and** needs a real browser (real workers or a critical component wired to its hooks). Logic a component calls gets a unit test beside it (`*.logic.test.ts`). A browser test file spends seconds in CI loading its module graph before its first test runs; a unit test takes milliseconds. Purely visual, layout, threshold, scroll-hide, or focus polish gets before/after captures as proof and no test.
- **In review:** a reviewer asking for a test must name the realistic future regression and why existing checks miss it. Never request tests for exotic edges, cosmetic/focus/threshold tweaks, or optional review-finding nits (authors may decline optional coverage nits). Flag any new test that fails the rules above and name the fix: delete it, fold it into an existing case or table, keep one layer, or move pure logic out of a browser test.

## Waiting for work

- The server is event-sourced, and side effects run after the command commits. In tests, drain the effect worker (`OrchestrationEffectWorkerV2.drain`) or await the specific persisted event or `Deferred` that marks the milestone. Never wait on sleeps or polling. A test that needs a timeout to pass is wrong. Concretely:
  - `it.effect` runs on a `TestClock`; `Effect.sleep` only advances through `TestClock.adjust`. `it.live` is wall-clock and only for subprocess or network fixtures.
  - No `yieldNow` or `sleep` polling loops. Await the `Deferred`, take from the `Queue`, or drain the worker.
  - No per-test timeout argument or `retry`. The project timeout is the ceiling, and flaky tests are fixed, not retried.
  - No `performance.now()` or `Date.now()` deltas. Assert on events and counts, not elapsed time.
  - Browser tests assert through `expect.element` or `vi.waitFor`, never `requestAnimationFrame` or `transitionend`.
  - `vi.mock` factories must not spread a real module that pulls in Shiki or the diff workers.
  - `it.skip` and friends need a tracking issue on the line above: `// quarantine: #1234 <why>`.
  - Lint enforces this: `t3code/no-test-timeout-or-unreasoned-skip`, `t3code/no-frame-waits-in-browser-tests`, `t3code/no-wall-clock-in-tests`, `t3code/no-real-time-wait-in-tests`, `t3code/no-polling-loop-in-tests`.

## Web browser tests

- Web browser tests are `*.browser.test.tsx` or `*.browser.test.ts` and render with `await using screen = await render(...)` from `apps/web/test/render.tsx`. `t3code/require-disposable-render` errors on the old patterns.
  - Acquire what the test drives after mounting (fake timers it advances, spies it sets up after mounting) after the render, so it disposes before the unmount. Anything the first render reads comes before it.
  - A helper that renders and then waits or clicks puts the screen in an `AsyncDisposableStack` and `move()`s it out only on success, so a failed wait still unmounts.
  - `rerender` needs a fresh element on every call.
  - No lifecycle hooks and no module-level mutable state. Shared mock state that `vi.mock` factories read is reset by a `setup()` call at the top of the test.
  - `router` is on by default. Pass `router: false` only with a one-line comment saying why.

  ```tsx
  it("saves on Enter", async () => {
    const onSave = vi.fn();
    using _now = vi.spyOn(Date, "now").mockReturnValue(0);
    await using screen = await render(<TitleEditor onSave={onSave} />, { router: "/threads/1" });
    await userEvent.type(screen.getByRole("textbox"), "Title{Enter}");
    expect(onSave).toHaveBeenCalledWith("Title");
  });
  ```

## Scenarios

Scenarios are [e2e](https://e2e.com/docs) tests in [`scripts/scenarios`](../../scripts/scenarios) (`*.e2e.ts`) that drive the real app (server, HTTP/WS, web browser or pooled iOS simulator) using the free `Replay (dev)` agent. Use one as real-app proof for a user-reproducible bug fix:

```sh
vp run scenarios                                                  # run all
vp run scenarios:prove scripts/scenarios/<name>.e2e.ts --base main --upload-command "ghdrop upload"
```

- One test per file (`WEB` from `./t3.ts` or `IOS` from `./t3-mobile.ts`). Seed projects and threads via `t3.project` / `t3.thread` before calling `t3.open(...)` so the app does not land on first-run setup.
- In web scenarios, navigate directly with `t3.open(thread)` or `t3.open("/settings/...")` unless the scenario exercises sidebar navigation.
- Put `expect` assertions only on the behavior the bug breaks, and take `app.screenshot("label")` where the bug shows so `scenarios:prove` pairs base and head captures. Never call `agent.act` or `agent.assert` (no model is configured).
- The app starts with a minimal env (`PATH`, `HOME`, temp dir); pass extra env vars via `T3_SCENARIO_INHERIT_ENV='VAR,PREFIX_*'`. Run one scenario run at a time per checkout.
- `scenarios:prove` exits `0` only when the test fails on base and passes on head (`1` = did not prove, `2` = app failed to start, `3` = scenario failed before its assertion). iOS scenarios lease a Simlock simulator and require `SIMLOCK_AGENT_DEVICE_URL` and `AGENT_DEVICE_DAEMON_AUTH_TOKEN`.
- Scenarios cannot cover desktop shell/IPC, Android, provider-specific protocol behavior (replay speaks generic ACP), or timing/perf regressions.
