test: drive login poll loop with a fake clock

Give login an optional clock ({ now, sleep }) with the real timers as
the default, so the device-code poll loop can be tested without
wall-clock time. Neither t.mock.timers nor jiti aliasing reaches
node:timers/promises, so a seam is the only way in; auth.oauth.login
still passes only the interaction, so pi's interface is unchanged.

Six tests cover pending to slow_down to success, the interval fallback
and floor, the deadline cap, a non-retryable error and a non-OK device
code response. The token mock gives up after 100 polls: an
auto-advancing fake starves the event loop, so a sleep-less regression
would otherwise hang the suite with no test timeout able to fire.
This commit is contained in:
AlexKucera committed 2026-11-25 13:50:00 +01:00
1 parent cb5aecf815
commit 544af1eeea
4 files changed
+69 -8

No files matched your search

+1
View File
@@ -15,6 +15,7 @@
- Uses the **native** pi-ai `Provider` (`createProvider`) rather than the legacy `ProviderConfig` + `oauth` block. The legacy `getApiKey` contract pushes an extension toward minting an agent key; Nous retired that endpoint (`410 session_key_minting_retired`). Here `OAuthAuth.toAuth` returns the access token itself, and pi owns the locked refresh pattern. See `docs/adr/0001-stack.md`.
- Streaming is delegated to pi's built-in `openai-completions` API. No custom wire protocol.
- The catalog tier rides **on the model** as the `catalogTier` property, because pi persists and restores model objects across runs and a side table would miss restored entries. It is a property, not a header: pi forwards only `model.headers` to requests (and copies them into the options first), so nothing is stripped before a request. Do not move it into `headers` without bringing back a strip on both the model and the options. The persisted catalog is `<agentDir>/models-store.json` (`ModelsStore`); `models.json` holds only user overrides, so check the store when verifying anything carried on a model.
- `login` accepts an optional clock (`{ now, sleep }`): production uses `node:timers/promises` and `Date.now`, tests an auto-advancing fake. `auth.oauth.login` passes only the interaction, so pi's interface is unchanged.
## Conventions and gotchas
+8 -5
View File
@@ -107,8 +107,11 @@ export function toCredential(token: TokenResponse, previous?: OAuthCredential):
};
}
type Clock = { now: () => number; sleep: (ms: number, signal?: AbortSignal) => Promise<void> };
// Production adapter: the node:timers/promises sleep, which rejects on abort. Tests pass an auto-advancing fake.
const realClock: Clock = { now: Date.now, sleep: (ms, signal) => sleep(ms, undefined, { signal }) };
async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {
export async function login(interaction: ProviderAuthInteraction, clock: Clock = realClock): Promise<OAuthCredential> {
const { signal } = interaction;
const response = await fetch(`${PORTAL}/api/oauth/device/code`, {
method: "POST",
@@ -130,14 +133,14 @@ async function login(interaction: ProviderAuthInteraction): Promise<OAuthCredent
// pi's dialog shows the code and opens the browser on Enter. Do NOT prompt here: a prompt clears that
// confirm action (login-dialog.js showPrompt → clearDeviceCodeAction), so Enter would open nothing.
const deadline = Date.now() + device.expires_in * 1000;
const deadline = clock.now() + device.expires_in * 1000;
// Floor at 1 s and reject non-finite values like pi-ai's own poller: a missing, zero, non-numeric or
// overflowing interval must not become a tight loop (Node clamps an overflowing setTimeout to 1 ms).
const requested = Number(device.interval);
let interval = Number.isFinite(requested) && requested > 0 ? Math.max(requested, 1) : 5;
// Never sleep past the deadline.
const nap = () => sleep(Math.min(interval * 1000, deadline - Date.now()), undefined, { signal });
while (Date.now() < deadline) {
const nap = () => clock.sleep(Math.min(interval * 1000, deadline - clock.now()), signal);
while (clock.now() < deadline) {
try {
return toCredential(
await tokenRequest({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: device.device_code }, signal),
@@ -161,7 +164,7 @@ const auth: ProviderAuth = {
name: "Nous Portal (subscription)",
isSubscription: true,
loginLabel: "Sign in to Nous Portal (subscription)",
login,
login: (interaction) => login(interaction),
refresh: (credential, signal) =>
tokenRequest({ grant_type: "refresh_token", refresh_token: credential.refresh }, signal).then((t) => toCredential(t, credential)),
// The access token is the inference credential; no agent key is minted.
+3 -2
View File
@@ -2,7 +2,7 @@
## Purpose
Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, model fetching, token-endpoint error handling, and the slash commands (driven through a recording `pi`). No network, no real credentials.
Offline unit tests for `index.ts`. They pin the pure logic that has real branching: model mapping, credential construction, the device-code poll loop, model fetching, token-endpoint error handling, and the slash commands (driven through a recording `pi`). No network, no real credentials, no wall-clock time.
## Ownership
@@ -15,7 +15,8 @@ Offline unit tests for `index.ts`. They pin the pure logic that has real branchi
- `index.test.mjs` loads `index.ts` through jiti, the same TS loader pi uses, because the host packages are not installed in `node_modules`.
- Host imports are aliased to `stubs/pi-ai.mjs`. Alias keys are matched longest-prefix first: `@earendil-works/pi-ai/compat` must be listed before `@earendil-works/pi-ai`, or the bare key swallows the subpath and resolution fails.
- `stubs/pi-ai.mjs` exports only what `index.ts` imports: `envApiKeyAuth`, `createProvider`, `openAICompletionsApi`, `getAgentDir` (plus `agentDir` so tests can find the flag file). `getAgentDir` is called inside the default export, so it is reached only by tests that drive the commands; it returns a private `mkdtemp` dir per run, shared through `globalThis` because jiti loads the stub as a separate instance from a native import. It is a type-less stub; correctness of those functions is pi's concern and is verified live, not here.
- Exported functions under test: `toModel`, `toCredential`, `tokenRequest`, `fetchModels`, `tierOf`, and the default export via the `drive()` harness. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached. Anything else is not unit-tested (notably the device-code poll loop inside `login`, which would need timer control and extraction).
- Exported functions under test: `toModel`, `toCredential`, `login`, `tokenRequest`, `fetchModels`, `tierOf`, and the default export via the `drive()` harness. `drive(flag)` returns `run(name, model, available, refresh)` — pass a deferred promise as `refresh` to simulate overlapping command invocations, and a Nous `model` when the `setModel` half of a contract is under test — plus the registered `provider`, which is how the provider-level `fetchModels` last-good retention is reached.
- `login` takes an optional clock (`{ now, sleep }`) and defaults to real timers. Five of the six `login` tests drive it with `driveLogin(t, replies, device)`; the sixth exercises the default clock: an auto-advancing clock (each sleep adds its ms to `now`) plus a mocked device-code and token endpoint, where the last reply repeats and the mock gives up after 100 token polls, so a sleep-less regression fails instead of hanging (the fake clock starves the event loop; no test timeout can fire). Never wait on wall-clock time in tests: `t.mock.timers` does not capture `node:timers/promises` and jiti does not alias `node:` builtins (both probed on Node 26).
- Network calls are replaced with `t.mock.method(globalThis, "fetch", …)` from `node:test`, which restores itself when the test ends. Do not hand-roll a `globalThis.fetch` swap.
- `fetchModels` reads a key only from the `credential` argument. Env resolution of `$NOUS_API_KEY` is `envApiKeyAuth`'s job upstream. The one test that touches `process.env` sets it deliberately, to pin that `fetchModels` ignores it; it restores the previous value in `t.after`.
+57 -1
View File
@@ -17,7 +17,7 @@ const jiti = createJiti(import.meta.url, {
},
});
const extension = await jiti.import("../index.ts");
const { toModel, toCredential, tokenRequest, fetchModels, tierOf } = extension;
const { toModel, toCredential, login, tokenRequest, fetchModels, tierOf } = extension;
// The stub shares its private agent dir through globalThis (see stubs/pi-ai.mjs); the catalog flag lives there.
const { agentDir } = await import("./stubs/pi-ai.mjs");
const flagPath = join(agentDir, "nous-portal-catalog");
@@ -56,6 +56,62 @@ test("toModel: the catalog tier is a model property, never a header, so nothing
assert.equal(toModel({ id: "openai/gpt-5.4-nano" }).catalogTier, undefined, "untiered models carry no tier");
});
// login() is driven with an auto-advancing clock: each sleep adds its ms to `now` and resolves at once, so the
// deadline falls out of the sleeps themselves. The token endpoint is mocked; the last reply repeats, and the mock
// gives up after 100 polls so a sleep-less regression FAILS instead of hanging (the fake clock starves the event
// loop, so no test timeout can fire).
const DEVICE = { device_code: "d", user_code: "USER-1", verification_uri: "https://portal.nousresearch.com/device", expires_in: 60, interval: 5 };
const oauthError = (error) => ({ ok: false, status: 400, text: async () => JSON.stringify({ error }) });
const token = (access_token) => ({ ok: true, text: async () => JSON.stringify({ access_token, expires_in: 3600 }) });
const driveLogin = (t, replies, device = DEVICE) => {
const sleeps = [], events = [];
let now = 1_000_000, call = 0;
t.mock.method(globalThis, "fetch", async (url) => {
if (String(url).endsWith("/device/code")) return { ok: true, json: async () => device };
if (call >= 100) throw new Error("runaway poll loop: 100 token polls without reaching the deadline");
return replies[Math.min(call++, replies.length - 1)];
});
const clock = { now: () => now, sleep: async (ms) => { sleeps.push(ms); now += ms; } };
return { sleeps, events, run: () => login({ notify: (event) => events.push(event), signal: new AbortController().signal }, clock) };
};
test("login: shows the device code once, waits the server interval on pending and 5 s more on slow_down, then returns the credential", async (t) => {
const { run, sleeps, events } = driveLogin(t, [oauthError("authorization_pending"), oauthError("slow_down"), token("tok")]);
const credential = await run();
assert.deepEqual(sleeps, [5000, 10000]);
assert.deepEqual(events, [{ type: "device_code", userCode: "USER-1", verificationUri: "https://portal.nousresearch.com/device", intervalSeconds: 5, expiresInSeconds: 60 }]);
assert.equal(credential.access, "tok");
});
test("login: a missing interval falls back to 5 s", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("a")], { ...DEVICE, interval: undefined });
await run();
assert.deepEqual(sleeps, [5000]);
});
test("login: a fractional interval is floored at 1 s", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending"), token("b")], { ...DEVICE, interval: 0.5 });
await run();
assert.deepEqual(sleeps, [1000]);
});
test("login: never sleeps past the deadline; a poll that stays pending times out", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("authorization_pending")], { ...DEVICE, expires_in: 12 });
await assert.rejects(run(), /Nous login timed out/);
assert.deepEqual(sleeps, [5000, 5000, 2000]);
});
test("login: a non-retryable OAuth error propagates without sleeping", async (t) => {
const { run, sleeps } = driveLogin(t, [oauthError("expired_token")]);
await assert.rejects(run(), /expired_token/);
assert.deepEqual(sleeps, []);
});
test("login: a non-OK device-code response throws with its status (real clock; no sleep is reached)", async (t) => {
t.mock.method(globalThis, "fetch", async () => ({ ok: false, status: 403 }));
await assert.rejects(login({ notify() {}, signal: new AbortController().signal }), /device code request failed: 403/);
});
test("toCredential: keeps the previous refresh token when the server rotates only the access token", () => {
const prev = { type: "oauth", access: "old", refresh: "rt_keep", expires: 0 };
const rotated = toCredential({ access_token: "new", expires_in: 100 });