diff --git a/.changes/github-token-heartbeat.md b/.changes/github-token-heartbeat.md new file mode 100644 index 0000000..204d1a9 --- /dev/null +++ b/.changes/github-token-heartbeat.md @@ -0,0 +1,4 @@ +--- +bump: minor +--- +Add a GitHub-token heartbeat: the supervisor now re-checks every ~60s whether the stored GitHub login still works, and the TUI footer shows a live `github ✓` / `✗ /login` badge — so an expired or revoked login surfaces within ~60s instead of only on the next failed request or a manual `/status`. A transient network/rate-limit hiccup is distinguished from a real auth failure, so the badge never flips on a single blip. diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3fec949 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +# Keep the build context small and avoid copying host-built artifacts into the Linux image. +# better-sqlite3 in particular is a native module — the host's (Windows) build must NOT leak in; +# the image recompiles it via `npm ci`. +node_modules +dist +.git +.claude +coverage +*.log diff --git a/.gitignore b/.gitignore index 633ea5f..ede8d55 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,11 @@ coverage .vitest .playwright-mcp .claude + +# Never commit credentials or e2e run artifacts (the real token/WebIQ key are mounted at runtime). +creds.json +webiq.json +.copilot-reverse/ +*.report.md +e2e/docker/out/ +report.md diff --git a/e2e/RESULTS.md b/e2e/RESULTS.md index 781ef52..d735fd4 100644 --- a/e2e/RESULTS.md +++ b/e2e/RESULTS.md @@ -3,6 +3,39 @@ Latest run of the end-to-end suite. Regenerate after every code change with `npm run test:e2e` and update this file (paste the summary). +- **2026-06-28 (real CLI Docker e2e + 2 Codex bugs fixed)** — Added a true black-box e2e: the actual + `claude` and `codex` CLIs run inside a `node:22` container against the real worker daemon + (`e2e/docker/Dockerfile.cli` + `cli-e2e.sh`), with a real token (+ WebIQ key) mounted. All three + checks pass: `codex exec → /openai/responses → CODEX_OK`, `claude -p → /anthropic → CLAUDE_OK`, + and `claude` gateway web search → a grounded answer ("1.96.0"). The driver writes a markdown report + after each run (`/out/report.md`). This path **caught two bugs nothing else did**: (1) Codex sends + `custom`/`tool_search` tools that the inbound translator forwarded nameless → Copilot 400 "Missing + required parameter: tools[N].name" → "stream closed before response.completed"; fixed by keeping + `custom` tools as named tools and allow-listing only nameless hosted tools (`web_search`). (2) The + `ResponsesSSE` terminal events carried empty text, so Codex completed the turn but rendered nothing; + fixed by replaying the accumulated text in `output_text.done` / `content_part.done` / + `output_item.done` and populating `response.completed.response.output`. Also added 12 hermetic + in-process Codex `/responses` cases (EP-27…EP-38) as fast regression. No secrets are committed — + the only key in any file is the placeholder `copilot-reverse-local`; real creds/keys mount at + runtime and report artifacts are gitignored. Full suite green: `npm test` → **394 passed** + (56 files), tsc build clean, real CLI Docker e2e → **all passed**. + +- **2026-06-28 (GitHub-token heartbeat)** — Added a supervisor-side heartbeat that periodically (every + 60s, plus once ~2s after boot) checks whether the stored GitHub token still exchanges for a Copilot + token, and surfaces the result via a new optional `github` field on `/api/status`. The TUI's existing + 2s status poll drives a live footer badge (`github ✓` / `✗ /login`), so an expired/revoked login + shows within ~60s instead of only on the next failed request or a manual `/status`. Key design: a + classifying `probeGithubAuth` distinguishes a definitive 401/403 (→ expired) from a transient + timeout/5xx/network error (→ keep last-known-good), so a single GitHub hiccup never flips the badge; + `nextGithubStatus` is a pure, sticky reducer. `signed-out` (no token) stays distinct from `expired`. + New files: `src/supervisor/github-heartbeat.ts`, `tests/supervisor/github-heartbeat.test.ts`. + **Real Linux container e2e** (`e2e/docker/`): a Docker image boots the real control API + a real + `GithubHeartbeat.start()`, listens on a real port, and drives it over real HTTP (`GET /api/status`) + against the real GitHub API — all four states pass, including `connected` (real token → real Copilot + token exchange, mounted read-only) and `expired` (bad token → a real GitHub 401). Only the probe + interval is shortened (now injectable) for the test. Full suite green: `npm test` → **378 passed** + (56 files), `npm run test:e2e` → **31 passed** (4 files), container e2e → **all passed**, tsc build clean. + - **2026-06-26 (default to WebIQ; disable slow borrow)** — gpt-5-mini (the Claude "borrow" backend model) is badly congested on Copilot's `/responses`: repeated `503 "high demand"` and 20s–7min stalls measured live (one user search ran 437s). Same native search on gpt-5.4-mini/gpt-5.4/gpt-5.5 diff --git a/e2e/cases.md b/e2e/cases.md index a356fb3..5237048 100644 --- a/e2e/cases.md +++ b/e2e/cases.md @@ -36,6 +36,26 @@ provider so no live network/token is needed. Spec: [`copilot-reverse.e2e.test.ts | EP-25 | `setup-codex` | writes native `~/.codex/config.toml` with `model_context_window` | | EP-26 | reset after 1M setup | removes every key including the 1M-window keys | +### Codex `/responses` (EP-27 … EP-38) + +The OpenAI Responses API end-to-end through a booted worker (Codex speaks only this). Hermetic — fake +provider, no network. Spec: same `copilot-reverse.e2e.test.ts`, `describe("E2E: Codex /responses")`. + +| ID | Scenario | Expected result | +|----|----------|-----------------| +| EP-27 | non-stream `/openai/responses` | `object:"response"`, `status:"completed"`, an `output_text` message item, `usage` totals | +| EP-28 | streaming `/openai/responses` | ordered `response.created → output_item.added → content_part.added → output_text.delta → …done → response.completed`, monotonic `sequence_number`, final `usage` | +| EP-29 | streaming tool call | `function_call` item + `function_call_arguments.delta/.done`, args reassemble | +| EP-30 | non-stream tool call | maps to a `function_call` output item with `call_id`/`name`/`arguments` | +| EP-31 | prior `function_call` + `function_call_output` in `input` | round-trips to the provider as `tool_use` + `tool_result` | +| EP-32 | `input_image` content part | round-trips to the provider as an image block | +| EP-33 | `instructions` | becomes a `system` message | +| EP-34 | hosted `web_search` tool + a function tool | `web_search` passes through as a hostedTool; the function tool is kept | +| EP-35 | expired token | `401` with `error.type:"error"` (login hint) | +| EP-36 | mid-stream failure | a `data: {"type":"error"}` frame, not a silent close | +| EP-37 | a `/responses` request | recorded in the supervisor `request_log` with `endpoint:"/openai/responses"` | +| EP-38 | `gpt-4o[1m]` model | the `[1m]` suffix is stripped before forwarding | + ## What each case protects (regressions it would catch) - **EP-01/EP-02** — core proxy translation (OpenAI/Anthropic ⇄ Copilot canonical), streaming framing. @@ -58,3 +78,21 @@ GitHub login is on disk (so CI stays hermetic). Coverage: token exchange, model real 1M-window model), OpenAI completion, Anthropic streaming with **different questions → different answers** (the unique-id regression guard), real `message_delta` usage, and count_tokens. - **EP-07/EP-08/EP-09** — TUI command wiring: logs/error visibility, dashboard/report, config reset. + +## Real CLI Docker e2e (opt-in, real `claude` + `codex`) + +The fullest test: the **actual `claude` and `codex` CLIs** drive the **real worker daemon** inside a +Linux container, with a real GitHub token (and optional WebIQ key) mounted. See +[`docker/README.md`](./docker/README.md) — built/run via `e2e/docker/Dockerfile.cli` + `cli-e2e.sh`, +not part of `npm test`. It writes a markdown report after each run. Checks: + +| Scenario | Path | Passes when | +|----------|------|-------------| +| `codex exec` | `/openai/responses` | the model returns `CODEX_OK` | +| `claude -p` | `/anthropic/v1/messages` | the model returns `CLAUDE_OK` | +| `claude` web search | gateway `web_search` loop → WebIQ | a grounded answer (a Rust `1.x` version), no error | + +This black-box path caught two bugs nothing else did: a Codex tool-translation `400` (a `custom`/ +`tool_search` tool forwarded nameless → Copilot rejects → "stream closed before response.completed"), +and empty terminal Responses events (`output_*.done` carried no text → Codex rendered nothing). + diff --git a/e2e/copilot-reverse.e2e.test.ts b/e2e/copilot-reverse.e2e.test.ts index 3657df5..2b774c7 100644 --- a/e2e/copilot-reverse.e2e.test.ts +++ b/e2e/copilot-reverse.e2e.test.ts @@ -19,7 +19,8 @@ import { claudeCopilotReverseEnv } from "../src/tui/setup/clients.js"; import { readClientStatus } from "../src/tui/setup/status.js"; import { applyCodexToml, codexTomlPath } from "../src/tui/setup/codex-toml.js"; import type { ProviderAdapter } from "../src/providers/types.js"; -import type { CanonicalChunk } from "../src/core/canonical.js"; +import type { CanonicalChunk, CanonicalResponse } from "../src/core/canonical.js"; +import type { GatewayToolRunner } from "../src/core/server-tools.js"; const ok: ProviderAdapter = { name: "copilot", @@ -36,13 +37,77 @@ const failing: ProviderAdapter = { }; // Wire a worker app to a supervisor db exactly like the daemon does (metric -> recordRequest). -function wired(provider: ProviderAdapter) { +// An optional gatewayRunner is forwarded so e2e cases can exercise the in-gateway web_search/web_fetch +// loop (production passes a real runner; the daemon's createWorkerApp takes it as the 3rd arg). +function wired(provider: ProviderAdapter, runner?: GatewayToolRunner) { const db = openDb(":memory:"); - const worker = createWorkerApp(new Router([provider], { "*": "gpt-4o" }), (m) => recordRequest(db, { ts: Date.now(), ...m })); - const control = createControlApp({ db, getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [{ name: "worker", ok: true, detail: "ready" }], subscribe: () => () => {} }); + const worker = createWorkerApp(new Router([provider], { "*": "gpt-4o" }), (m) => recordRequest(db, { ts: Date.now(), ...m }), runner); + const control = createControlApp({ db, getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [{ name: "worker", ok: true, detail: "ready" }], github: () => undefined, subscribe: () => () => {} }); return { worker, control, db }; } +// ---- fake-provider factories (deterministic, no network) ----------------------------------------- + +// A provider that streams a single tool_use (one tool call) then finishes with stop_reason tool_use. +function toolStreamProvider(name: string, args: string, id = "call_1"): ProviderAdapter { + return { + name: "copilot", + complete: async (req) => ({ id: "c1", model: req.model, content: [{ type: "tool_use", id, name, input: JSON.parse(args || "{}") }], finishReason: "tool_use", usage: { promptTokens: 2, completionTokens: 1 } }), + async *stream() { + yield { kind: "tool_use_start", index: 0, id, name, done: false } as const; + yield { kind: "tool_use_delta", index: 0, argsDelta: args, done: false } as const; + yield { kind: "done", done: true, finishReason: "tool_use" } as const; + }, + }; +} + +// A provider driven by a turn counter: turn 1 calls `toolName` (a gateway tool), later turns return +// `finalText`. The endpoint re-invokes stream()/complete() per loop iteration, so the counter selects +// behavior — this drives the gateway tool loop deterministically. +function loopProvider(toolName: string, finalText: string, opts: { capForever?: boolean } = {}) { + let turn = 0; + const adapter: ProviderAdapter = { + name: "copilot", + complete: async (req) => { + turn++; + if (opts.capForever || turn === 1) return { id: "c1", model: req.model, content: [{ type: "tool_use", id: `call_${turn}`, name: toolName, input: { query: "q" } }], finishReason: "tool_use", usage: { promptTokens: 2, completionTokens: 1 } }; + return { id: "c1", model: req.model, content: [{ type: "text", text: finalText }], finishReason: "stop", usage: { promptTokens: 2, completionTokens: 1 } }; + }, + async *stream() { + turn++; + if (opts.capForever || turn === 1) { + yield { kind: "tool_use_start", index: 0, id: `call_${turn}`, name: toolName, done: false } as const; + yield { kind: "tool_use_delta", index: 0, argsDelta: '{"query":"q"}', done: false } as const; + yield { kind: "done", done: true, finishReason: "tool_use" } as const; + } else { + yield { kind: "text", delta: finalText, done: false } as const; + yield { kind: "done", done: true, finishReason: "stop" } as const; + } + }, + }; + return { adapter, turns: () => turn }; +} + +// A provider that throws CopilotAuthError (for the 401 path) — optionally after a text yield so the +// failure lands on an already-open stream. +function authFailProvider(afterText = false): ProviderAdapter { + return { + name: "copilot", + complete: async () => { throw new CopilotAuthError(401); }, + async *stream(): AsyncIterable { + if (afterText) yield { kind: "text", delta: "partial", done: false }; + throw new CopilotAuthError(401); + }, + }; +} + +// Parse OpenAI Responses SSE (`data: {json}` frames, no event: lines) into ordered objects. +function responsesEvents(body: string): any[] { + return body.split("\n\n").map((b) => b.split("\n").find((l) => l.startsWith("data: "))?.slice(6)) + .filter((d): d is string => !!d && d.trim() !== "[DONE]").map((d) => { try { return JSON.parse(d); } catch { return null; } }) + .filter(Boolean); +} + // Parse an SSE body into ordered { event, data } frames (Anthropic) — shared by streaming cases. function frames(body: string): { event: string; data: any }[] { return body.split("\n\n").map((b) => b.trim()).filter(Boolean).map((b) => ({ @@ -251,6 +316,135 @@ describe("E2E: tool calls", () => { }); }); +// Codex speaks the OpenAI Responses API (/openai/responses). These drive the endpoint end-to-end +// through a booted worker — non-stream object shape, the full streaming event sequence, tool calls, +// inbound item round-trip, image input, instructions->system, hosted web_search passthrough, and +// errors — none of which the chat-completions cases cover. +describe("E2E: Codex /responses", () => { + it("EP-27 non-stream returns a completed response object with output_text + usage", async () => { + const { worker } = wired(ok); + const res = await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "hi", max_output_tokens: 40 }); + expect(res.status).toBe(200); + expect(res.body.object).toBe("response"); + expect(res.body.status).toBe("completed"); + const msg = res.body.output.find((o: any) => o.type === "message"); + expect(msg.content[0]).toMatchObject({ type: "output_text", text: "ok" }); + expect(res.body.usage).toMatchObject({ input_tokens: 3, output_tokens: 1, total_tokens: 4 }); + }); + + it("EP-28 streaming emits the ordered Responses event sequence with monotonic sequence_number", async () => { + const withUsage: ProviderAdapter = { name: "copilot", complete: ok.complete, async *stream() { yield { kind: "text", delta: "ok", done: false } as const; yield { kind: "done", done: true, finishReason: "stop", usage: { promptTokens: 5, completionTokens: 2 } } as const; } }; + const { worker } = wired(withUsage); + const res = await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "hi", stream: true, max_output_tokens: 40 }); + const evs = responsesEvents(res.text); + const types = evs.map((e) => e.type); + expect(types[0]).toBe("response.created"); + expect(types).toContain("response.output_item.added"); + expect(types).toContain("response.content_part.added"); + expect(types).toContain("response.output_text.delta"); + expect(types).toContain("response.output_text.done"); + expect(types.at(-1)).toBe("response.completed"); + const seqs = evs.map((e) => e.sequence_number); + expect(seqs.every((n, i) => i === 0 || n > seqs[i - 1])).toBe(true); // strictly increasing + const completed = evs.find((e) => e.type === "response.completed"); + expect(completed.response.usage).toMatchObject({ input_tokens: 5, output_tokens: 2 }); + }); + + it("EP-29 streaming a tool call emits function_call argument events, finish tool_use", async () => { + const { worker } = wired(toolStreamProvider("get_weather", '{"city":"SF"}', "call_X")); + const res = await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "weather?", stream: true }); + const evs = responsesEvents(res.text); + const added = evs.find((e) => e.type === "response.output_item.added" && e.item?.type === "function_call"); + expect(added.item).toMatchObject({ call_id: "call_X", name: "get_weather" }); + expect(evs.some((e) => e.type === "response.function_call_arguments.delta")).toBe(true); + expect(evs.some((e) => e.type === "response.function_call_arguments.done")).toBe(true); + const argsDone = evs.find((e) => e.type === "response.function_call_arguments.done"); + expect(JSON.parse(argsDone.arguments)).toEqual({ city: "SF" }); + }); + + it("EP-30 non-stream tool call maps to a function_call output item", async () => { + const { worker } = wired(toolStreamProvider("search", '{"q":"x"}', "fc1")); + const res = await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "search x" }); + const fc = res.body.output.find((o: any) => o.type === "function_call"); + expect(fc).toMatchObject({ call_id: "fc1", name: "search" }); + expect(JSON.parse(fc.arguments)).toEqual({ q: "x" }); + }); + + it("EP-31 a prior function_call + function_call_output in input round-trips to the provider", async () => { + let seen: any; + const spy: ProviderAdapter = { name: "copilot", async complete(req) { seen = req; return { id: "c1", model: req.model, content: [{ type: "text", text: "done" }], finishReason: "stop", usage: { promptTokens: 1, completionTokens: 1 } }; }, async *stream() { yield { kind: "done", done: true, finishReason: "stop" } as const; } }; + const { worker } = wired(spy); + await request(worker).post("/openai/responses").send({ + model: "gpt-5.5", + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "go" }] }, + { type: "function_call", call_id: "fc1", name: "now", arguments: '{"tz":"utc"}' }, + { type: "function_call_output", call_id: "fc1", output: "12:00" }, + ], + }); + expect(seen.messages.find((m: any) => m.content.some((b: any) => b.type === "tool_use" && b.id === "fc1"))).toBeTruthy(); + expect(seen.messages.find((m: any) => m.content.some((b: any) => b.type === "tool_result" && b.toolUseId === "fc1"))).toBeTruthy(); + }); + + it("EP-32 an input_image content part round-trips to the provider as an image block", async () => { + let seen: any; + const spy: ProviderAdapter = { name: "copilot", async complete(req) { seen = req; return { id: "c1", model: req.model, content: [{ type: "text", text: "a cat" }], finishReason: "stop", usage: { promptTokens: 1, completionTokens: 1 } }; }, async *stream() { yield { kind: "done", done: true, finishReason: "stop" } as const; } }; + const { worker } = wired(spy); + await request(worker).post("/openai/responses").send({ + model: "gpt-5.5", + input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "what?" }, { type: "input_image", image_url: "data:image/png;base64,XYZ" }] }], + }); + const img = seen.messages.flatMap((m: any) => m.content).find((b: any) => b.type === "image"); + expect(img).toEqual({ type: "image", dataUrl: "data:image/png;base64,XYZ" }); + }); + + it("EP-33 instructions become a system message", async () => { + let seen: any; + const spy: ProviderAdapter = { name: "copilot", async complete(req) { seen = req; return { id: "c1", model: req.model, content: [{ type: "text", text: "ok" }], finishReason: "stop", usage: { promptTokens: 1, completionTokens: 1 } }; }, async *stream() { yield { kind: "done", done: true, finishReason: "stop" } as const; } }; + const { worker } = wired(spy); + await request(worker).post("/openai/responses").send({ model: "gpt-5.5", instructions: "be terse", input: "hello" }); + expect(seen.messages[0]).toEqual({ role: "system", content: [{ type: "text", text: "be terse" }] }); + }); + + it("EP-34 a hosted web_search tool is passed through to the provider as a hostedTool", async () => { + let seen: any; + const spy: ProviderAdapter = { name: "copilot", async complete(req) { seen = req; return { id: "c1", model: req.model, content: [{ type: "text", text: "ok" }], finishReason: "stop", usage: { promptTokens: 1, completionTokens: 1 } }; }, async *stream() { yield { kind: "done", done: true, finishReason: "stop" } as const; } }; + const { worker } = wired(spy); + await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "news?", tools: [{ type: "web_search" }, { type: "function", name: "f", parameters: {} }] }); + expect(seen.hostedTools).toEqual(["web_search"]); + expect(seen.tools?.some((t: any) => t.name === "f")).toBe(true); // function tool still present + }); + + it("EP-35 an expired token surfaces a 401 error object on /responses", async () => { + const { worker } = wired(authFailProvider()); + const res = await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "hi" }); + expect(res.status).toBe(401); + expect(res.body.error.type).toBe("error"); + expect(res.body.error.message).toMatch(/login|expired/i); + }); + + it("EP-36 a mid-stream failure emits a data error frame, not a silent close", async () => { + const { worker } = wired(authFailProvider(true)); // throws after a text yield (stream already open) + const res = await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "hi", stream: true }); + expect(res.text).toMatch(/"type":"error"/); + }); + + it("EP-37 a /responses request is recorded in the supervisor request_log", async () => { + const { worker, db } = wired(ok); + await request(worker).post("/openai/responses").send({ model: "gpt-5.5", input: "hi" }); + const logged = recentRequests(db, 10); + expect(logged.some((r) => r.endpoint === "/openai/responses" && r.status === 200)).toBe(true); + }); + + it("EP-38 resolveModel applies to /responses too (strips the [1m] suffix)", async () => { + let seen: any; + const spy: ProviderAdapter = { name: "copilot", async complete(req) { seen = req; return { id: "c1", model: req.model, content: [{ type: "text", text: "ok" }], finishReason: "stop", usage: { promptTokens: 1, completionTokens: 1 } }; }, async *stream() { yield { kind: "done", done: true, finishReason: "stop" } as const; } }; + const { worker } = wired(spy); + await request(worker).post("/openai/responses").send({ model: "gpt-4o[1m]", input: "hi" }); + expect(seen.model).not.toContain("[1m]"); + }); +}); + describe("E2E: persistence & control API", () => { it("EP-21 a failed request's error message persists in the request_log and is queryable", async () => { const { worker, control } = wired(failing); diff --git a/e2e/docker/Dockerfile b/e2e/docker/Dockerfile new file mode 100644 index 0000000..5e82588 --- /dev/null +++ b/e2e/docker/Dockerfile @@ -0,0 +1,33 @@ +# Linux end-to-end test image for copilot-reverse. +# +# Builds the project and runs a REAL supervisor inside the container so the GitHub-token heartbeat +# can be exercised over actual HTTP (GET /api/status) against the real GitHub API — something the +# Windows host can't easily do because port 7890 is taken by a running instance. The container has its +# own network namespace, so the default ports are free here. +# +# Uses node:20 (not -slim) because better-sqlite3 is a native module that needs a C++ toolchain. +# +# Build: docker build -f e2e/docker/Dockerfile -t copilot-reverse-e2e . +# Run: docker run --rm \ +# -v "$HOME/.copilot-reverse/creds.json:/root/.copilot-reverse/creds.json:ro" \ +# copilot-reverse-e2e +# (mounting creds.json is optional — without it the "connected" case is reported as skipped.) + +FROM node:20 + +WORKDIR /app + +# Install deps first (layer-cached unless the lockfile changes). Native better-sqlite3 compiles here. +COPY package.json package-lock.json ./ +RUN npm ci + +# Bring in the source and build to dist/. +COPY tsconfig.json ./ +COPY scripts ./scripts +COPY src ./src +COPY e2e ./e2e +COPY tests ./tests +RUN npm run build + +# The e2e driver boots the supervisor, probes /api/status, and asserts the github field's states. +ENTRYPOINT ["node", "e2e/docker/heartbeat-e2e.mjs"] diff --git a/e2e/docker/Dockerfile.cli b/e2e/docker/Dockerfile.cli new file mode 100644 index 0000000..7c48388 --- /dev/null +++ b/e2e/docker/Dockerfile.cli @@ -0,0 +1,61 @@ +# Real CLI end-to-end test image. +# +# Runs the ACTUAL copilot-reverse worker daemon plus the REAL `claude` (Claude Code) and `codex` +# CLIs inside one Linux container. The CLIs are pointed at the local daemon (:7891) and driven with +# real prompts, so this is a true black-box e2e: real Copilot calls flow CLI -> daemon -> Copilot. +# +# node:22 (not 20) because @openai/codex requires Node >=22. better-sqlite3 compiles here. +# +# Build: docker build -f e2e/docker/Dockerfile.cli -t copilot-reverse-cli-e2e . +# Run: docker run --rm \ +# -v "$HOME/.copilot-reverse/creds.json:/root/.copilot-reverse/creds.json:ro" \ +# copilot-reverse-cli-e2e +# (Windows Git Bash: MSYS_NO_PATHCONV=1 + a C:/Users/... path — see e2e/docker/README.md.) + +FROM node:22 + +# jq for asserting on claude --output-format json; curl for the readiness probe. +RUN apt-get update && apt-get install -y --no-install-recommends jq curl && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Build copilot-reverse (deps layer cached unless the lockfile changes; better-sqlite3 compiles). +COPY package.json package-lock.json ./ +RUN npm ci +COPY tsconfig.json ./ +COPY scripts ./scripts +COPY src ./src +RUN npm run build + +# Install the real CLIs we drive against the daemon. +RUN npm install -g @anthropic-ai/claude-code @openai/codex + +# Headless config for both CLIs (no vendor login — they talk only to the local daemon). +ENV DISABLE_AUTOUPDATER=1 \ + DISABLE_TELEMETRY=1 \ + DISABLE_ERROR_REPORTING=1 \ + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 \ + ANTHROPIC_BASE_URL=http://127.0.0.1:7891/anthropic \ + ANTHROPIC_API_KEY=copilot-reverse-local \ + ANTHROPIC_MODEL=gpt-4o + +# Seed Claude Code's onboarding state so `claude -p` doesn't prompt on first run. +RUN echo '{"hasCompletedOnboarding":true,"installMethod":"unknown","autoUpdates":false}' > /root/.claude.json + +# Codex points at the daemon's Responses API (mirrors what the TUI's setup-codex writes). +RUN mkdir -p /root/.codex && printf '%s\n' \ + 'model = "gpt-5.5"' \ + 'model_provider = "copilot-reverse"' \ + '' \ + '[model_providers.copilot-reverse]' \ + 'name = "copilot-reverse"' \ + 'base_url = "http://127.0.0.1:7891/openai"' \ + 'wire_api = "responses"' \ + 'requires_openai_auth = false' \ + 'experimental_bearer_token = "copilot-reverse-local"' \ + > /root/.codex/config.toml + +COPY e2e/docker/cli-e2e.sh ./e2e/docker/cli-e2e.sh +RUN chmod +x ./e2e/docker/cli-e2e.sh + +ENTRYPOINT ["./e2e/docker/cli-e2e.sh"] diff --git a/e2e/docker/README.md b/e2e/docker/README.md new file mode 100644 index 0000000..326657c --- /dev/null +++ b/e2e/docker/README.md @@ -0,0 +1,100 @@ +# Linux container e2e — GitHub-token heartbeat + +A real end-to-end test of the GitHub-token heartbeat, run inside a Linux container so it can exercise +the full HTTP path against the real GitHub API. The Windows host can't easily do this (port 7890 is +held by a running instance, and native-module / path quirks get in the way); the container has its own +network namespace and a Linux toolchain. + +**What's real here:** the actual `createControlApp` control API, a real `GithubHeartbeat` started via +its real `start()`/`stop()`, a real TCP listener, real `fetch()` calls to GitHub's Copilot-token +endpoint, and real HTTP polling of `GET /api/status`. Only the probe interval is shortened (1.5s vs the +production 60s) so state transitions are observable in seconds. See [`heartbeat-e2e.mjs`](heartbeat-e2e.mjs). + +## What it asserts + +| State | How it's produced | Expected `github` | +|-------|-------------------|-------------------| +| connected | a real token (mounted) is exchanged for a real Copilot token | `ok:true, hasToken:true, detail:"token valid"` | +| signed-out | creds file removed | `ok:false, hasToken:false`, detail mentions `/login` | +| expired | a bad token → a **real GitHub 401** | `ok:false, hasToken:true`, detail mentions expired/login | +| HTTP | real `GET /api/status` | JSON carrying `workerState` + `github` | + +The `connected` case is skipped (not failed) if no token is mounted. + +## Run it + +From the repo root: + +```bash +docker build -f e2e/docker/Dockerfile -t copilot-reverse-e2e . + +# Without a real token (connected case skipped): +docker run --rm copilot-reverse-e2e + +# With your real token mounted read-only (all four cases): +# Linux/macOS: +docker run --rm -v "$HOME/.copilot-reverse/creds.json:/run/secrets/creds.json:ro" copilot-reverse-e2e +# Windows (Git Bash) — disable path conversion and use a native path: +MSYS_NO_PATHCONV=1 docker run --rm \ + -v "C:/Users//.copilot-reverse/creds.json:/run/secrets/creds.json:ro" \ + copilot-reverse-e2e +``` + +The token is mounted read-only at `/run/secrets/creds.json`; the driver copies it into a writable work +dir (`/tmp/cr-e2e`) so the signed-out / expired cases can rewrite creds without touching the mount. +Override the source path with `-e TOKEN_FILE=/some/path`. + +Exit code `0` = all asserted states observed; non-zero = a failure (the failing check is printed). + +--- + +# Real CLI e2e — claude + codex against the daemon + +A true black-box end-to-end: the **actual `claude` (Claude Code) and `codex` CLIs** run inside the +container against the **real copilot-reverse worker daemon**, driven with real prompts, making real +Copilot (and WebIQ) calls. This is the only test that exercises the proxy exactly as the real clients +do — and it has already caught two bugs that curl and unit tests could not (a Codex tool-translation +400, and empty terminal Responses events that left Codex with no text). See +[`Dockerfile.cli`](Dockerfile.cli) + [`cli-e2e.sh`](cli-e2e.sh). + +Uses `node:22` (Codex requires Node ≥22). Installs `@anthropic-ai/claude-code` + `@openai/codex`, +points Claude at `…/anthropic` (env) and Codex at `…/openai` (`~/.codex/config.toml`, +`wire_api="responses"`), boots `node dist/worker/index.js`, then asserts: + +| check | path exercised | passes when | +|-------|----------------|-------------| +| `codex exec` | `/openai/responses` (real Codex CLI) | model returns `CODEX_OK` | +| `claude -p` | `/anthropic/v1/messages` (real Claude Code CLI) | model returns `CLAUDE_OK` | +| `claude` web search | gateway `web_search` loop → WebIQ | grounded answer (a Rust `1.x` version), no error | + +The web-search check is skipped unless a WebIQ key is also mounted. + +**No secrets are baked into the image** — the only key in any file is the placeholder +`copilot-reverse-local`. The real GitHub token and WebIQ key are mounted at runtime via `-v`. + +```bash +docker build -f e2e/docker/Dockerfile.cli -t copilot-reverse-cli-e2e . + +# Windows (Git Bash): MSYS_NO_PATHCONV=1 + native C:/ paths. +MSYS_NO_PATHCONV=1 docker run --rm \ + -v "C:/Users//.copilot-reverse/creds.json:/root/.copilot-reverse/creds.json:ro" \ + -v "C:/Users//.copilot-reverse/webiq.json:/root/.copilot-reverse/webiq.json:ro" \ + -v "C:/some/host/dir:/out" \ + copilot-reverse-cli-e2e + +# Linux/macOS: +docker run --rm \ + -v "$HOME/.copilot-reverse/creds.json:/root/.copilot-reverse/creds.json:ro" \ + -v "$HOME/.copilot-reverse/webiq.json:/root/.copilot-reverse/webiq.json:ro" \ + -v "$PWD/out:/out" \ + copilot-reverse-cli-e2e +``` + +## Report + +After every run the driver writes a markdown report to **`/out/report.md`** (mount `-v :/out` +to capture it on the host; also always at `/tmp/cli-e2e-report.md` inside the container). It records +the result, the component versions (copilot-reverse / codex / claude), and each check's status + +the real CLI reply. The report contains only CLI output (e.g. `CODEX_OK`, a version number) — never a +token. Report files are gitignored. + diff --git a/e2e/docker/cli-e2e.sh b/e2e/docker/cli-e2e.sh new file mode 100644 index 0000000..56146b7 --- /dev/null +++ b/e2e/docker/cli-e2e.sh @@ -0,0 +1,115 @@ +#!/usr/bin/env bash +# Real CLI end-to-end driver. Boots the copilot-reverse worker daemon, then runs the actual `claude` +# and `codex` CLIs against it with real prompts and asserts on their output. Exit 0 = all passed. +# +# What each check proves (black-box, real Copilot calls): +# - codex exec -> /openai/responses end-to-end (the Codex-only Responses path) +# - claude -p -> /anthropic/v1/messages end-to-end (the Claude path) +# - claude web -> the gateway web_search loop returns a grounded answer with no tool leak +# +# After the run it writes a markdown REPORT to $REPORT_PATH (default /out/report.md; also always to +# /tmp/cli-e2e-report.md). Mount -v :/out to capture the report on the host. +set -uo pipefail + +PORT=7891 +REPORT_PATH="${REPORT_PATH:-/out/report.md}" +fails=0 +total=0 +rows="" # accumulates markdown table rows + +note() { printf '\n=== %s ===\n' "$1"; } +# record +record() { rows="${rows}| ${1} | ${2} | ${3} |\n"; } +check() { # check + total=$((total+1)) + if eval "$2"; then echo " PASS $1"; record "$1" "PASS" "${3:-}"; else echo " FAIL $1"; fails=$((fails+1)); record "$1" "FAIL" "${3:-}"; fi +} + +# --- preconditions ------------------------------------------------------------------------------ +if [ ! -f /root/.copilot-reverse/creds.json ]; then + echo "no GitHub token mounted at /root/.copilot-reverse/creds.json — cannot run real CLI e2e" + echo "mount it read-only: -v \$HOME/.copilot-reverse/creds.json:/root/.copilot-reverse/creds.json:ro" + exit 3 +fi +CODEX_VER=$(codex --version 2>/dev/null | head -1) +CLAUDE_VER=$(claude --version 2>/dev/null | head -1) +APP_VER=$(node -e "console.log(require('/app/package.json').version)" 2>/dev/null) + +# --- boot the worker daemon --------------------------------------------------------------------- +note "boot worker daemon (node dist/worker/index.js)" +WORKER_PORT=$PORT BIND_HOST=127.0.0.1 node dist/worker/index.js > /tmp/worker.log 2>&1 & +WPID=$! +ready=0 +for _ in $(seq 1 40); do + if curl -sf "http://127.0.0.1:$PORT/healthz" >/dev/null 2>&1; then ready=1; break; fi + if ! kill -0 "$WPID" 2>/dev/null; then echo "worker exited early:"; cat /tmp/worker.log; exit 4; fi + sleep 0.5 +done +[ "$ready" = 1 ] && echo " worker ready on :$PORT" || { echo "worker never became ready:"; cat /tmp/worker.log; exit 4; } + +# --- 1) Codex via /openai/responses ------------------------------------------------------------- +note "codex exec -> /openai/responses" +CODEX_OUT=$(cd /tmp && codex exec --skip-git-repo-check --sandbox read-only \ + "Reply with exactly the token: CODEX_OK and nothing else." 2>/tmp/codex.err) +CODEX_LINE=$(echo "$CODEX_OUT" | tail -1) +echo " codex stdout: $CODEX_LINE" +check "codex round-trips through /openai/responses" 'echo "$CODEX_OUT" | grep -q "CODEX_OK"' "codex $CODEX_VER replied: \`${CODEX_LINE}\`" + +# --- 2) Claude via /anthropic/v1/messages ------------------------------------------------------- +note "claude -p -> /anthropic/v1/messages" +CLAUDE_JSON=$(claude -p "Reply with exactly the token: CLAUDE_OK and nothing else." --output-format json 2>/tmp/claude.err) +CLAUDE_TEXT=$(echo "$CLAUDE_JSON" | jq -r '.result // empty' 2>/dev/null) +echo " claude result: $CLAUDE_TEXT" +check "claude round-trips through /anthropic/v1/messages" 'echo "$CLAUDE_TEXT" | grep -q "CLAUDE_OK"' "claude $CLAUDE_VER replied: \`${CLAUDE_TEXT}\`" + +# --- 3) Claude web search through the gateway loop ---------------------------------------------- +# Requires a WebIQ key (mount webiq.json too); skip the grounding assertion if it's absent. +if [ -f /root/.copilot-reverse/webiq.json ] || [ -n "${WEBIQ_API_KEY:-}" ]; then + note "claude web_search -> gateway loop (grounded answer, no tool leak)" + # Headless claude blocks tools by default; allow WebSearch so it can actually call the gateway tool. + WEB_JSON=$(claude -p "Use web search to find the latest stable Rust release version and reply with just the version number." \ + --allowedTools WebSearch --permission-mode acceptEdits --output-format json 2>/tmp/claude-web.err) + WEB_TEXT=$(echo "$WEB_JSON" | jq -r '.result // empty' 2>/dev/null) + WEB_ERR=$(echo "$WEB_JSON" | jq -r '.is_error // false' 2>/dev/null) + echo " claude web result: $WEB_TEXT" + check "web search returns a grounded answer" 'echo "$WEB_TEXT" | grep -Eq "1\.[0-9]+"' "claude (gateway web_search) replied: \`${WEB_TEXT}\`" + check "web search turn did not error" '[ "$WEB_ERR" != "true" ]' "is_error=${WEB_ERR}" +else + note "claude web_search -> SKIPPED (no webiq.json mounted)" + record "claude web search (gateway loop)" "SKIP" "no webiq.json mounted" +fi + +# --- teardown ----------------------------------------------------------------------------------- +kill "$WPID" 2>/dev/null + +# --- report ------------------------------------------------------------------------------------- +status_line=$([ "$fails" = 0 ] && echo "✅ ALL PASSED" || echo "❌ ${fails} FAILED") +REPORT=$(cat < /tmp/cli-e2e-report.md +if mkdir -p "$(dirname "$REPORT_PATH")" 2>/dev/null && echo "$REPORT" > "$REPORT_PATH" 2>/dev/null; then + echo ""; echo "report written to ${REPORT_PATH} (and /tmp/cli-e2e-report.md)" +else + echo ""; echo "report written to /tmp/cli-e2e-report.md (mount -v :/out to capture it on the host)" +fi + +note "summary" +echo "$status_line" +[ "$fails" = 0 ] && exit 0 || exit 1 diff --git a/e2e/docker/heartbeat-e2e.mjs b/e2e/docker/heartbeat-e2e.mjs new file mode 100644 index 0000000..3a3a1e9 --- /dev/null +++ b/e2e/docker/heartbeat-e2e.mjs @@ -0,0 +1,132 @@ +// Real, in-container end-to-end test for the GitHub-token heartbeat. +// +// This is NOT a mock. It boots the real control API (`createControlApp`) wired to a real +// `GithubHeartbeat`, listens on a real TCP port, and drives it purely over HTTP (`GET /api/status`) — +// exactly what the TUI's poll does. The heartbeat makes real calls to GitHub's Copilot-token endpoint, +// so `expired` is proven against a genuine 401 and (when a token is mounted) `connected` against a real +// token exchange. Only the probe interval is shortened so state transitions are observable in seconds +// instead of a minute. +// +// Exit 0 = all asserted states observed; non-zero = a failure (printed). + +import { mkdirSync, writeFileSync, rmSync, existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { createControlApp } from "../../dist/supervisor/api.js"; +import { GithubHeartbeat } from "../../dist/supervisor/github-heartbeat.js"; +import { openDb } from "../../dist/supervisor/db.js"; +import { readGhToken } from "../../dist/shared/creds.js"; + +const PORT = 7890; +const HOST = "127.0.0.1"; +const PROBE_MS = 1500; // fast cadence for the test (prod is 60s) + +// Use a writable working dir as the data dir, so the read-only mounted token is never written to and +// the signed-out / expired cases can freely rewrite creds.json. The real token (if mounted) is read +// once from TOKEN_FILE and cached in memory. +const WORK_DIR = "/tmp/cr-e2e"; +const credsPath = join(WORK_DIR, "creds.json"); +const TOKEN_FILE = process.env.TOKEN_FILE || "/run/secrets/creds.json"; + +function mountedRealToken() { + try { + if (!existsSync(TOKEN_FILE)) return null; + const t = JSON.parse(readFileSync(TOKEN_FILE, "utf8"))?.ghToken; + return typeof t === "string" && t ? t : null; + } catch { return null; } +} + +const log = (...a) => console.log(...a); +let failures = 0; +function check(name, cond, detail) { + if (cond) log(` ✓ ${name}`); + else { failures++; log(` ✗ ${name} — ${detail ?? ""}`); } +} + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const getStatus = async () => (await fetch(`http://${HOST}:${PORT}/api/status`)).json(); + +// Poll /api/status until github. matches predicate, or time out. +async function waitForGithub(pred, timeoutMs = 12_000) { + const start = Date.now(); + let last; + while (Date.now() - start < timeoutMs) { + last = (await getStatus()).github; + if (last && pred(last)) return last; + await sleep(300); + } + return last; // return last seen (may be undefined) for the assertion to report +} + +function setCreds(token) { + mkdirSync(WORK_DIR, { recursive: true }); + writeFileSync(credsPath, JSON.stringify({ ghToken: token })); +} +function removeCreds() { rmSync(credsPath, { force: true }); } + +async function main() { + const realToken = mountedRealToken(); + mkdirSync(WORK_DIR, { recursive: true }); + removeCreds(); // start from a clean slate regardless of prior runs + log(`\nGitHub-token heartbeat — real container e2e`); + log(`mounted real token: ${realToken ? "yes" : "no (connected case will be skipped)"}\n`); + + const db = openDb(":memory:"); + // Real heartbeat + real start()/stop(); only the cadence is shortened so transitions show in seconds. + const heartbeat = new GithubHeartbeat( + () => readGhToken(WORK_DIR), + undefined, undefined, + { intervalMs: PROBE_MS, initialDelayMs: 200 }, + ); + const app = createControlApp({ + db, getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, + doctor: async () => [], github: () => heartbeat.current(), subscribe: () => () => {}, + }); + const server = app.listen(PORT, HOST); + await new Promise((r) => server.once("listening", r)); + heartbeat.start(); + log(`supervisor control API listening on http://${HOST}:${PORT}\n`); + + try { + // --- Case 1: connected (only if a real token is mounted) --- + if (realToken) { + log("[1] real token → connected (real Copilot token exchange)"); + setCreds(realToken); + const g = await waitForGithub((x) => x.ok === true); + check("github.ok === true", g?.ok === true, JSON.stringify(g)); + check("github.hasToken === true", g?.hasToken === true, JSON.stringify(g)); + check("detail is 'token valid'", g?.detail === "token valid", g?.detail); + check("checkedAt is a real timestamp", typeof g?.checkedAt === "number" && g.checkedAt > 0); + } else { + log("[1] connected — SKIPPED (no token mounted)"); + } + + // --- Case 2: signed-out (no token on disk) --- + log("\n[2] no token on disk → signed-out"); + removeCreds(); + const g2 = await waitForGithub((x) => x.hasToken === false); + check("github.hasToken === false", g2?.hasToken === false, JSON.stringify(g2)); + check("github.ok === false", g2?.ok === false, JSON.stringify(g2)); + check("detail mentions /login", /\/login|not logged in/i.test(g2?.detail ?? ""), g2?.detail); + + // --- Case 3: expired (a real, bad token → a real GitHub 401) --- + log("\n[3] invalid token → expired (real GitHub 401)"); + setCreds("ghu_invalid000000000000000000000000000000"); + const g3 = await waitForGithub((x) => x.hasToken === true && x.ok === false); + check("github.hasToken === true", g3?.hasToken === true, JSON.stringify(g3)); + check("github.ok === false", g3?.ok === false, JSON.stringify(g3)); + check("detail mentions expired/login", /expired|login/i.test(g3?.detail ?? ""), g3?.detail); + + // --- Case 4: the field is delivered over real HTTP as JSON --- + log("\n[4] /api/status delivers github over real HTTP"); + const raw = await (await fetch(`http://${HOST}:${PORT}/api/status`)).text(); + check("response is JSON with workerState + github", /"workerState"/.test(raw) && /"github"/.test(raw), raw.slice(0, 120)); + } finally { + heartbeat.stop(); + server.close(); + } + + log(`\n${failures === 0 ? "ALL PASSED" : failures + " CHECK(S) FAILED"}`); + process.exit(failures === 0 ? 0 : 1); +} + +main().catch((e) => { console.error("e2e driver crashed:", e); process.exit(2); }); diff --git a/src/core/responses-inbound.ts b/src/core/responses-inbound.ts index 2e91c07..33082c0 100644 --- a/src/core/responses-inbound.ts +++ b/src/core/responses-inbound.ts @@ -57,14 +57,23 @@ export function responsesRequestToCanonical(req: ResponsesRequest): CanonicalReq } return { model: req.model, stream: Boolean(req.stream), temperature: req.temperature, maxTokens: req.max_output_tokens, - tools: req.tools?.filter((t) => t.type === "function" && t.name).map((t) => ({ name: t.name!, description: t.description, parameters: t.parameters ?? {} })), - // Hosted tools (web_search etc.) Codex requests for Copilot to run server-side. Keep them so the - // outbound /responses translator forwards them verbatim, instead of dropping them like before. - hostedTools: req.tools?.filter((t) => t.type !== "function" && t.type).map((t) => t.type), + // Function tools and `custom` tools (e.g. Codex's apply_patch) both carry a name — keep them as + // named tools so Copilot doesn't reject a nameless tool. Only the KNOWN nameless server-side tools + // pass through as hostedTools; an unrecognized nameless tool is dropped rather than forwarded as a + // bare {type} (which makes Copilot 400 "Missing required parameter: tools[N].name" and kills the + // whole stream — surfaced to the Codex CLI as "stream closed before response.completed"). + tools: req.tools?.filter((t) => (t.type === "function" || t.type === "custom") && t.name).map((t) => ({ name: t.name!, description: t.description, parameters: t.parameters ?? {} })), + hostedTools: req.tools?.filter((t) => HOSTED_TOOL_TYPES.has(t.type ?? "")).map((t) => t.type!), messages, }; } +// Copilot's /responses accepts these as standalone nameless hosted tools. NOTE: `tool_search` is +// deliberately excluded — Copilot rejects it unless the request also defines "deferred" tools +// ("tools.tool_search requires at least one deferred tool"), which we can't satisfy, so forwarding it +// 400s the whole request. web_search is the one Codex hosted tool we can pass straight through. +const HOSTED_TOOL_TYPES = new Set(["web_search", "web_search_preview"]); + // Build the non-stream Responses object: text -> an output_text message item, tool_use -> function_call items. export function canonicalToResponsesResponse(r: CanonicalResponse) { const output: unknown[] = []; @@ -89,6 +98,7 @@ export class ResponsesSSE { private nextIndex = 0; private textIndex?: number; private textItemId?: string; + private accumulatedText = ""; // the full assistant text, replayed in the terminal done events private toolIndex = new Map(); constructor(private responseId: string, private model: string) {} @@ -112,6 +122,7 @@ export class ResponsesSSE { out.push(this.ev("response.content_part.added", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text: "", annotations: [] } })); } out.push(this.ev("response.output_text.delta", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, delta })); + this.accumulatedText += delta; return out; } @@ -133,9 +144,10 @@ export class ResponsesSSE { finish(usage: { promptTokens: number; completionTokens: number } | undefined, _finishReason: string, argsByIdx?: Map): string[] { const out: string[] = []; if (this.textIndex !== undefined) { - out.push(this.ev("response.output_text.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, text: "" })); - out.push(this.ev("response.content_part.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text: "", annotations: [] } })); - out.push(this.ev("response.output_item.done", { output_index: this.textIndex, item: { type: "message", id: this.textItemId, role: "assistant", status: "completed", content: [] } })); + const text = this.accumulatedText; + out.push(this.ev("response.output_text.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, text })); + out.push(this.ev("response.content_part.done", { item_id: this.textItemId, output_index: this.textIndex, content_index: 0, part: { type: "output_text", text, annotations: [] } })); + out.push(this.ev("response.output_item.done", { output_index: this.textIndex, item: { type: "message", id: this.textItemId, role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] } })); } for (const [copilotIdx, t] of this.toolIndex) { const args = argsByIdx?.get(copilotIdx) ?? ""; @@ -143,7 +155,12 @@ export class ResponsesSSE { out.push(this.ev("response.output_item.done", { output_index: t.outputIndex, item: { type: "function_call", id: t.itemId, status: "completed" } })); } const u = usage ? { input_tokens: usage.promptTokens, output_tokens: usage.completionTokens, total_tokens: usage.promptTokens + usage.completionTokens } : undefined; - out.push(this.ev("response.completed", { response: { ...this.envelope("completed"), ...(u ? { usage: u } : {}) } })); + // Spec-correct clients reconstruct the final response from response.completed.response.output, so + // include the finished items (the text message + any function calls), not just an empty envelope. + const output: unknown[] = []; + if (this.textIndex !== undefined) output.push({ type: "message", id: this.textItemId, role: "assistant", status: "completed", content: [{ type: "output_text", text: this.accumulatedText, annotations: [] }] }); + for (const [copilotIdx, t] of this.toolIndex) output.push({ type: "function_call", id: t.itemId, call_id: t.itemId.replace(/^fc_/, ""), arguments: argsByIdx?.get(copilotIdx) ?? "", status: "completed" }); + out.push(this.ev("response.completed", { response: { ...this.envelope("completed"), output, ...(u ? { usage: u } : {}) } })); return out; } } diff --git a/src/providers/copilot/token.ts b/src/providers/copilot/token.ts index 1f25e3a..b173c4c 100644 --- a/src/providers/copilot/token.ts +++ b/src/providers/copilot/token.ts @@ -32,8 +32,33 @@ export class CopilotTokenStore { } } -// True if the stored GitHub token still exchanges for a Copilot token. +// True if the stored GitHub token still exchanges for a Copilot token. A thin wrapper over +// probeGithubAuth so the token-exchange logic lives in exactly one place. export async function isCopilotTokenValid(ghToken: string, fetchFn: typeof fetch = fetch): Promise { - try { await new CopilotTokenStore(ghToken, fetchFn).get(); return true; } - catch { return false; } + return (await probeGithubAuth(ghToken, fetchFn)).ok; +} + +// A classified auth check for the heartbeat. Unlike isCopilotTokenValid (a bare boolean), this +// distinguishes a DEFINITIVE auth failure (401/403) from a TRANSIENT one (timeout / 5xx / network / +// other). The heartbeat keeps the last-known-good status on transient errors, so a brief blip doesn't +// flip the UI to "expired". Known limitations of this code: +// - The stickiness is UNBOUNDED: a SUSTAINED transient fault (a long GitHub outage, DNS down, a +// persistently malformed body) also never surfaces — a connected badge stays green the whole time. +// Only 401/403 ever flips the UI to "expired". +// - 403 is treated as definitive here, but GitHub also returns 403 for some rate-limits; a rate- +// limited 403 would therefore (incorrectly) read as "expired". (429 is correctly transient.) +export interface AuthProbe { ok: boolean; transient: boolean; detail: string } +export async function probeGithubAuth(ghToken: string, fetchFn: typeof fetch = fetch): Promise { + try { + await new CopilotTokenStore(ghToken, fetchFn).get(); + return { ok: true, transient: false, detail: "token valid" }; + } catch (e) { + // CopilotTokenStore throws CopilotAuthError(status) for any non-ok response, and other errors + // (AbortError on timeout, network failures) for the rest. We treat 401/403 as definitive auth + // failures; everything else is transient. See the limitations noted above. + if (e instanceof CopilotAuthError && (e.status === 401 || e.status === 403)) { + return { ok: false, transient: false, detail: e.message }; + } + return { ok: false, transient: true, detail: e instanceof Error ? e.message : String(e) }; + } } diff --git a/src/shared/control-types.ts b/src/shared/control-types.ts index 679fdba..b4f3208 100644 --- a/src/shared/control-types.ts +++ b/src/shared/control-types.ts @@ -7,9 +7,18 @@ export interface RestartRow { stderrTail: string; markedUnhealthy: 0 | 1; } +// Result of the supervisor's GitHub-token heartbeat. `hasToken` keeps "signed-out" (no token on disk) +// distinct from "expired" (token present but no longer exchanges) without parsing `detail`. +export interface GithubStatus { + ok: boolean; // the GitHub token currently exchanges for a Copilot token + hasToken: boolean; // a GitHub token is present on disk + checkedAt: number; // ms epoch of the last completed probe + detail: string; // "token valid" | auth-error message | "not logged in — run /login" +} export interface StatusResponse { workerState: WorkerState; restarts: RestartRow[]; + github?: GithubStatus; // absent until the heartbeat's first probe completes } export interface DoctorCheck { name: string; diff --git a/src/supervisor/api.ts b/src/supervisor/api.ts index 4895c00..dbbc36e 100644 --- a/src/supervisor/api.ts +++ b/src/supervisor/api.ts @@ -1,7 +1,7 @@ import express, { type Express } from "express"; import { listRestarts, recentRequests, type Db } from "./db.js"; import { dashboardHtml } from "./dashboard.js"; -import type { WorkerState, DoctorCheck } from "../shared/control-types.js"; +import type { WorkerState, DoctorCheck, GithubStatus } from "../shared/control-types.js"; export interface ControlDeps { db: Db; @@ -10,6 +10,7 @@ export interface ControlDeps { stop: () => void; start: () => void; doctor: () => Promise; + github: () => GithubStatus | undefined; subscribe: (send: (event: string, data: unknown) => void) => () => void; } @@ -17,7 +18,7 @@ export function createControlApp(deps: ControlDeps): Express { const app = express(); app.use(express.json()); app.get("/", (_req, res) => res.type("html").send(dashboardHtml())); - app.get("/api/status", (_req, res) => res.json({ workerState: deps.getState(), restarts: listRestarts(deps.db, 50) })); + app.get("/api/status", (_req, res) => res.json({ workerState: deps.getState(), restarts: listRestarts(deps.db, 50), github: deps.github() })); app.post("/api/restart", (_req, res) => { deps.restart(); res.json({ ok: true }); }); app.post("/api/stop", (_req, res) => { deps.stop(); res.json({ ok: true }); }); app.post("/api/start", (_req, res) => { deps.start(); res.json({ ok: true }); }); diff --git a/src/supervisor/github-heartbeat.ts b/src/supervisor/github-heartbeat.ts new file mode 100644 index 0000000..0a3c412 --- /dev/null +++ b/src/supervisor/github-heartbeat.ts @@ -0,0 +1,84 @@ +import { probeGithubAuth, type AuthProbe } from "../providers/copilot/token.js"; +import type { GithubStatus } from "../shared/control-types.js"; + +// How often the supervisor re-checks the GitHub token. Token failure is rare (revoke / re-auth) and +// GitHub rate-limits, so a slow cadence is plenty; an initial short delay populates the status soon +// after boot without racing worker startup. +export const GITHUB_HEARTBEAT_INTERVAL_MS = 60_000; +export const GITHUB_HEARTBEAT_INITIAL_DELAY_MS = 2_000; + +// Shared so /doctor and the heartbeat show the same remediation hint for the signed-out state. +export const SIGNED_OUT_DETAIL = "not logged in — run /login"; + +// Pure reducer: given the prior cached status, whether a token is on disk, and the latest probe +// result, decide the next cached status. Transient errors are sticky — they keep the prior status — +// so a brief blip doesn't flip a connected session to "expired". Caveat (see probeGithubAuth): the +// stickiness is unbounded, and if the FIRST probe is transient (prev still undefined) the status stays +// undefined / "pending", so /api/status omits `github` and the HUD shows no badge until a non-transient +// result lands. +export function nextGithubStatus( + prev: GithubStatus | undefined, + hasToken: boolean, + probe: AuthProbe | null, + now: number, +): GithubStatus | undefined { + if (!hasToken) return { ok: false, hasToken: false, checkedAt: now, detail: SIGNED_OUT_DETAIL }; + if (probe && probe.transient) return prev; // keep last-known-good (or stay pending if none yet) + if (!probe) return prev; + return { ok: probe.ok, hasToken: true, checkedAt: now, detail: probe.detail }; +} + +// Periodically probes the GitHub token in the supervisor process and caches a GithubStatus the control +// API exposes via /api/status. Dependencies are injected for testing (token reader, probe, clock). +export class GithubHeartbeat { + private status: GithubStatus | undefined; + private timer: ReturnType | undefined; + private stopped = false; + private inFlight = false; + private intervalMs: number; + private initialDelayMs: number; + + constructor( + private readToken: () => string | null, + private probe: (ghToken: string) => Promise = probeGithubAuth, + private now: () => number = () => Date.now(), + opts: { intervalMs?: number; initialDelayMs?: number } = {}, + ) { + this.intervalMs = opts.intervalMs ?? GITHUB_HEARTBEAT_INTERVAL_MS; + this.initialDelayMs = opts.initialDelayMs ?? GITHUB_HEARTBEAT_INITIAL_DELAY_MS; + } + + current(): GithubStatus | undefined { return this.status; } + + // One probe cycle. Reads the token first: no token → signed-out, and the network probe is skipped. + // Guarded so a slow probe (up to ~8s) can't overlap the next tick. + async runOnce(): Promise { + if (this.inFlight) return; + this.inFlight = true; + try { + const token = this.readToken(); + const probe = token ? await this.probe(token) : null; + if (this.stopped) return; // a late result after stop() must not resurrect the timer/state + this.status = nextGithubStatus(this.status, Boolean(token), probe, this.now()); + } finally { + this.inFlight = false; + } + } + + start(): void { + if (this.timer) return; // idempotent: don't leak a second timer if start() is called twice + this.stopped = false; + const tick = () => { void this.runOnce(); }; + this.timer = setTimeout(() => { + tick(); + this.timer = setInterval(tick, this.intervalMs); + }, this.initialDelayMs); + } + + stop(): void { + this.stopped = true; + // The timer handle is either the initial setTimeout or the later setInterval; clearing both kinds + // is safe with either function in Node. + if (this.timer) { clearTimeout(this.timer); clearInterval(this.timer); this.timer = undefined; } + } +} diff --git a/src/supervisor/index.ts b/src/supervisor/index.ts index 87944e7..808b2ec 100644 --- a/src/supervisor/index.ts +++ b/src/supervisor/index.ts @@ -8,7 +8,8 @@ import { createControlApp } from "./api.js"; import { defaultConfig } from "../shared/config.js"; import { dataDir, dbPath } from "../shared/paths.js"; import { readGhToken } from "../shared/creds.js"; -import { CopilotTokenStore } from "../providers/copilot/token.js"; +import { probeGithubAuth } from "../providers/copilot/token.js"; +import { GithubHeartbeat, SIGNED_OUT_DETAIL } from "./github-heartbeat.js"; import type { WorkerState, DoctorCheck } from "../shared/control-types.js"; export function startSupervisor(): { stop: () => void } { @@ -38,28 +39,35 @@ export function startSupervisor(): { stop: () => void } { const gh = readGhToken(dataDir()); let auth: DoctorCheck; if (!gh) { - auth = { name: "github-auth", ok: false, detail: "not logged in — restart copilot-reverse to log in" }; + auth = { name: "github-auth", ok: false, detail: SIGNED_OUT_DETAIL }; } else { - // Validate the token actually exchanges, not just that it exists on disk. - try { await new CopilotTokenStore(gh).get(); auth = { name: "github-auth", ok: true, detail: "token valid" }; } - catch (e) { auth = { name: "github-auth", ok: false, detail: e instanceof Error ? e.message : String(e) }; } + // Validate the token actually exchanges, not just that it exists on disk. Shares the heartbeat's + // classifier so on-demand /doctor and the periodic probe agree. + const probe = await probeGithubAuth(gh); + auth = { name: "github-auth", ok: probe.ok, detail: probe.detail }; } return [auth, { name: "worker", ok: state === "ready", detail: `worker is ${state}` }]; }; + // Periodically re-check the GitHub token so the UI reflects an expired/revoked login within ~60s, + // instead of only on the next failed request or a manual /status. + const heartbeat = new GithubHeartbeat(() => readGhToken(dataDir())); + const app = createControlApp({ db, getState: () => state, restart: () => monitor.restartManually(), stop: () => monitor.stop(), start: () => monitor.start(), doctor, + github: () => heartbeat.current(), subscribe: (send) => bus.subscribe(send), }); app.listen(config.supervisorPort, config.bindHost, () => monitor.start()); - process.on("SIGINT", () => { monitor.stop(); process.exit(0); }); - process.on("SIGTERM", () => { monitor.stop(); process.exit(0); }); - return { stop: () => monitor.stop() }; + heartbeat.start(); + process.on("SIGINT", () => { heartbeat.stop(); monitor.stop(); process.exit(0); }); + process.on("SIGTERM", () => { heartbeat.stop(); monitor.stop(); process.exit(0); }); + return { stop: () => { heartbeat.stop(); monitor.stop(); } }; } // Allow `node dist/supervisor/index.js` to boot the daemon directly. diff --git a/src/tui/app.tsx b/src/tui/app.tsx index c2f3c36..c92772b 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -6,7 +6,7 @@ import { SetupWizard, type SetupClient } from "./setup/wizard.js"; import { ModelScreen } from "./screens/model.js"; import { ConfigScreen, type ConfigInfo } from "./screens/config.js"; import { WebIqKeyScreen } from "./screens/webiq-key.js"; -import { summarizeStatus, type StatusSummary, type GithubLoginState } from "./status-summary.js"; +import { summarizeStatus, githubLoginState, type StatusSummary, type GithubLoginState } from "./status-summary.js"; import type { Scope, ApplyResult } from "./setup/apply.js"; import type { ClientStatus } from "./setup/status.js"; import { theme } from "./theme.js"; @@ -145,6 +145,8 @@ export function App({ const [state, setState] = useState(workerState); const [status, setStatus] = useState(() => readStatus?.() ?? EMPTY_STATUS); const [webBackend, setWebBackend] = useState(() => webSearchBackend?.() ?? "unavailable"); + // GitHub login state, kept fresh by the supervisor heartbeat surfaced through the 2s status poll. + const [github, setGithub] = useState(startupStatus?.github); const [model, setModel] = useState(initialModel); const [screen, setScreen] = useState(pickModelOnStart && loadModels ? { kind: "model" } : null); const [, setNow] = useState(0); // ticks the live loading line while the assistant streams @@ -160,7 +162,13 @@ export function App({ if (!statusSource && !readStatus) return; let alive = true; const tick = async () => { - try { const s = await statusSource?.(); if (alive && s) setState(s.workerState); } catch { /* daemon momentarily down */ } + try { + const s = await statusSource?.(); + if (alive && s) { + setState(s.workerState); + if (s.github) setGithub(githubLoginState(s.github.hasToken, s.github.ok)); // live login badge + } + } catch { /* daemon momentarily down */ } if (alive) refreshStatus(); // HUD reflects the real config files, even if edited externally }; void tick(); @@ -196,14 +204,16 @@ export function App({ if (t === "/webiq" && enableWebiq) { setScreen({ kind: "webiq-key" }); return; } if (t === "/status" && (startupStatus || githubStatus || webSearchBackend)) { // Render the live status overview (same card as startup), then the worker restart history. - const github = githubStatus ? await githubStatus() : (startupStatus?.github ?? "signed-out"); + // /status is an explicit "is my login OK right now?" — do the live check when wired (the cached + // heartbeat can be up to ~60s stale), falling back to the cached/seed value only if it isn't. + const ghState = githubStatus ? await githubStatus() : (github ?? startupStatus?.github ?? "signed-out"); let worker = state, restarts: string[] = []; try { const s = await statusSource?.(); if (s) { worker = s.workerState; restarts = s.restarts.slice(0, 5).map((r) => ` ${r.reason} exit=${r.exitCode ?? "-"} ${r.stderrTail.slice(0, 60)}`); } } catch { /* daemon momentarily down — show what we have */ } const summary = summarizeStatus({ - hasToken: github !== "signed-out", tokenValid: github === "connected", + hasToken: ghState !== "signed-out", tokenValid: ghState === "connected", webSearch: webSearchBackend?.() ?? webBackend, worker, clients: { claude: status.claude.user || status.claude.project, codex: status.codex.user || status.codex.project }, }); @@ -338,12 +348,12 @@ export function App({ - model {model} - · daemon {state} - · web {webBackend === "webiq" ? "✓ webiq" : webBackend === "copilot" ? "✓ copilot" : "✗ /webiq"} + {github && <>github {github === "connected" ? "✓" : "✗ /login"}} + {github ? " · " : ""}daemon {state} - + web {webBackend === "webiq" ? "✓ webiq" : webBackend === "copilot" ? "✓ copilot" : "✗ /webiq"} + · · /help diff --git a/tests/core/responses-inbound.test.ts b/tests/core/responses-inbound.test.ts index 033ca00..701ffbd 100644 --- a/tests/core/responses-inbound.test.ts +++ b/tests/core/responses-inbound.test.ts @@ -38,6 +38,37 @@ describe("responsesRequestToCanonical", () => { // translator can forward it to Copilot (which runs it server-side), instead of dropping it. expect(c.hostedTools).toEqual(["web_search"]); }); + + it("handles Codex's real tool mix without producing a nameless hosted tool (regression)", () => { + // Codex sends function tools, a `custom` tool (apply_patch — HAS a name), and nameless hosted + // tools (tool_search, web_search). Forwarding `custom` as a bare {type:"custom"} made Copilot + // reject the whole request with 400 "Missing required parameter: tools[N].name", which surfaced + // to the codex CLI as "stream closed before response.completed". + const c = responsesRequestToCanonical({ + model: "gpt-5.5", stream: true, input: "hi", + tools: [ + { type: "function", name: "exec_command", parameters: { type: "object", properties: {} } }, + { type: "custom", name: "apply_patch", description: "patch" }, + { type: "tool_search" }, + { type: "web_search" }, + ] as any, + }); + // custom tools carry a name → treated as function tools (kept, with their name) + expect(c.tools?.map((t) => t.name).sort()).toEqual(["apply_patch", "exec_command"]); + // only web_search passes through; tool_search is NOT forwarded (Copilot 400s it without a + // deferred tool), and a nameless `custom` is never forwarded. + expect(c.hostedTools).toEqual(["web_search"]); + expect(c.hostedTools).not.toContain("custom"); + expect(c.hostedTools).not.toContain("tool_search"); + }); + + it("drops an unrecognized nameless tool rather than forwarding a malformed one", () => { + const c = responsesRequestToCanonical({ + model: "gpt-5", stream: false, input: "hi", + tools: [{ type: "some_future_hosted_tool" }] as any, // no name, not on the allowlist + }); + expect(c.hostedTools ?? []).toEqual([]); // dropped, not forwarded as {type} with no name + }); }); describe("canonicalToResponsesResponse", () => { @@ -80,6 +111,19 @@ describe("ResponsesSSE emitter", () => { expect(seqs.every((n, i) => i === 0 || n > seqs[i - 1])).toBe(true); }); + it("carries the accumulated text in the terminal done events (so codex can reconstruct the message)", () => { + // Regression: the done events used to send empty text, so the codex CLI completed the turn but + // rendered NO assistant text (it reconstructs the final message from output_text.done / + // content_part.done / output_item.done, not just the deltas). + const sse = new ResponsesSSE("resp_x", "gpt-5"); + const out = [sse.start(), ...sse.text("Hel"), ...sse.text("lo"), ...sse.finish({ promptTokens: 1, completionTokens: 1 }, "stop")]; + const events = out.join("").split("\n\n").filter(Boolean).map((b) => JSON.parse(b.replace(/^data: /, ""))); + const byType = (t: string) => events.find((e) => e.type === t); + expect(byType("response.output_text.done").text).toBe("Hello"); + expect(byType("response.content_part.done").part.text).toBe("Hello"); + expect(byType("response.output_item.done").item.content[0]).toMatchObject({ type: "output_text", text: "Hello" }); + }); + it("emits function_call argument events for a tool call", () => { const sse = new ResponsesSSE("resp_2", "gpt-5"); const out: string[] = []; diff --git a/tests/e2e/m1a-smoke.test.ts b/tests/e2e/m1a-smoke.test.ts index 91d5d7e..0a34300 100644 --- a/tests/e2e/m1a-smoke.test.ts +++ b/tests/e2e/m1a-smoke.test.ts @@ -13,6 +13,7 @@ describe("M1a control-plane e2e", () => { db, getState: () => state, restart: () => { state = "ready"; recordRestart(db, { ts: Date.now(), reason: "manual", exitCode: null, stderrTail: "", backoffMs: 0, markedUnhealthy: 0 }); bus.emit("state", { state }); }, stop: () => {}, start: () => {}, doctor: async () => [{ name: "x", ok: true, detail: "ok" }], + github: () => undefined, subscribe: (s) => bus.subscribe(s), }); expect((await request(app).get("/api/status")).body.workerState).toBe("starting"); diff --git a/tests/providers/copilot/token.test.ts b/tests/providers/copilot/token.test.ts index 672f3f2..3af1336 100644 --- a/tests/providers/copilot/token.test.ts +++ b/tests/providers/copilot/token.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi } from "vitest"; -import { CopilotTokenStore, CopilotAuthError, isCopilotTokenValid } from "../../../src/providers/copilot/token.js"; +import { CopilotTokenStore, CopilotAuthError, isCopilotTokenValid, probeGithubAuth } from "../../../src/providers/copilot/token.js"; const json = (b: unknown) => new Response(JSON.stringify(b), { status: 200, headers: { "content-type": "application/json" } }); describe("CopilotTokenStore", () => { @@ -37,3 +37,35 @@ describe("isCopilotTokenValid", () => { expect(await isCopilotTokenValid("gho", f as unknown as typeof fetch)).toBe(false); }); }); + +describe("probeGithubAuth", () => { + it("ok + non-transient when the token exchanges", async () => { + const f = vi.fn(async () => json({ token: "cop", expires_at: 9_999_999_999 })); + expect(await probeGithubAuth("gho", f as unknown as typeof fetch)).toEqual({ ok: true, transient: false, detail: "token valid" }); + }); + it("definitive failure (non-transient) on 401", async () => { + const f = vi.fn(async () => new Response("", { status: 401 })); + const p = await probeGithubAuth("gho", f as unknown as typeof fetch); + expect(p.ok).toBe(false); + expect(p.transient).toBe(false); + expect(p.detail).toMatch(/login expired/i); + }); + it("definitive failure (non-transient) on 403", async () => { + const f = vi.fn(async () => new Response("", { status: 403 })); + const p = await probeGithubAuth("gho", f as unknown as typeof fetch); + expect(p.ok).toBe(false); + expect(p.transient).toBe(false); + }); + it("transient on a 5xx (upstream hiccup, not an auth failure)", async () => { + const f = vi.fn(async () => new Response("", { status: 500 })); + const p = await probeGithubAuth("gho", f as unknown as typeof fetch); + expect(p.ok).toBe(false); + expect(p.transient).toBe(true); + }); + it("transient when the network call rejects", async () => { + const f = vi.fn(async () => { throw new Error("ECONNRESET"); }); + const p = await probeGithubAuth("gho", f as unknown as typeof fetch); + expect(p.ok).toBe(false); + expect(p.transient).toBe(true); + }); +}); diff --git a/tests/supervisor/api.test.ts b/tests/supervisor/api.test.ts index 5c4cc52..f7370c5 100644 --- a/tests/supervisor/api.test.ts +++ b/tests/supervisor/api.test.ts @@ -16,6 +16,7 @@ function fixture() { stop: () => calls.push("stop"), start: () => calls.push("start"), doctor: async () => [{ name: "copilot-auth", ok: true, detail: "token present" }], + github: () => undefined, subscribe: () => () => {}, }); return { app, calls }; @@ -27,6 +28,19 @@ describe("control api", () => { expect(res.body.workerState).toBe("ready"); expect(res.body.restarts[0].stderrTail).toBe("boom"); }); + it("status includes the github heartbeat when it has a result", async () => { + const db = openDb(":memory:"); + const app = createControlApp({ + db, getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, + doctor: async () => [], github: () => ({ ok: false, hasToken: true, checkedAt: 5, detail: "GitHub login expired" }), subscribe: () => () => {}, + }); + const res = await request(app).get("/api/status"); + expect(res.body.github).toEqual({ ok: false, hasToken: true, checkedAt: 5, detail: "GitHub login expired" }); + }); + it("status omits github before the first probe (undefined)", async () => { + const res = await request(fixture().app).get("/api/status"); // fixture's github() returns undefined + expect(res.body.github).toBeUndefined(); + }); it("restart action", async () => { const fx = fixture(); await request(fx.app).post("/api/restart"); @@ -69,7 +83,7 @@ describe("control api /api/events (SSE)", () => { it("streams an initial hello then live bus events to a connected client", async () => { const bus = new EventBus(); await withServer( - { db: openDb(":memory:"), getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [], subscribe: (send) => bus.subscribe(send) }, + { db: openDb(":memory:"), getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [], github: () => undefined, subscribe: (send) => bus.subscribe(send) }, async (base) => { const ctrl = new AbortController(); const res = await fetch(`${base}/api/events`, { signal: ctrl.signal }); @@ -94,7 +108,7 @@ describe("control api /api/events (SSE)", () => { it("unsubscribes the listener when the client disconnects", async () => { const bus = new EventBus(); await withServer( - { db: openDb(":memory:"), getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [], subscribe: (send) => bus.subscribe(send) }, + { db: openDb(":memory:"), getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [], github: () => undefined, subscribe: (send) => bus.subscribe(send) }, async (base) => { const ctrl = new AbortController(); const res = await fetch(`${base}/api/events`, { signal: ctrl.signal }); diff --git a/tests/supervisor/dashboard.test.ts b/tests/supervisor/dashboard.test.ts index 787c527..055650c 100644 --- a/tests/supervisor/dashboard.test.ts +++ b/tests/supervisor/dashboard.test.ts @@ -17,6 +17,7 @@ describe("dashboard", () => { const app = createControlApp({ db: openDb(":memory:"), getState: () => "ready", restart: () => {}, stop: () => {}, start: () => {}, doctor: async () => [], + github: () => undefined, subscribe: () => () => {}, }); const res = await request(app).get("/"); diff --git a/tests/supervisor/github-heartbeat.test.ts b/tests/supervisor/github-heartbeat.test.ts new file mode 100644 index 0000000..5a0ca8c --- /dev/null +++ b/tests/supervisor/github-heartbeat.test.ts @@ -0,0 +1,115 @@ +import { describe, it, expect, vi } from "vitest"; +import { + nextGithubStatus, GithubHeartbeat, + GITHUB_HEARTBEAT_INTERVAL_MS, GITHUB_HEARTBEAT_INITIAL_DELAY_MS, +} from "../../src/supervisor/github-heartbeat.js"; +import type { AuthProbe } from "../../src/providers/copilot/token.js"; +import type { GithubStatus } from "../../src/shared/control-types.js"; + +const ok: AuthProbe = { ok: true, transient: false, detail: "token valid" }; +const expired: AuthProbe = { ok: false, transient: false, detail: "GitHub login expired" }; +const blip: AuthProbe = { ok: false, transient: true, detail: "ECONNRESET" }; + +describe("nextGithubStatus (pure reducer)", () => { + it("signed-out when there is no token (probe ignored)", () => { + expect(nextGithubStatus(undefined, false, null, 5)).toEqual({ ok: false, hasToken: false, checkedAt: 5, detail: "not logged in — run /login" }); + }); + it("connected on a successful probe", () => { + expect(nextGithubStatus(undefined, true, ok, 7)).toEqual({ ok: true, hasToken: true, checkedAt: 7, detail: "token valid" }); + }); + it("expired on a definitive (non-transient) failure", () => { + expect(nextGithubStatus(undefined, true, expired, 9)).toEqual({ ok: false, hasToken: true, checkedAt: 9, detail: "GitHub login expired" }); + }); + it("keeps the previous status on a transient failure (sticky, no flip)", () => { + const prev: GithubStatus = { ok: true, hasToken: true, checkedAt: 1, detail: "token valid" }; + expect(nextGithubStatus(prev, true, blip, 99)).toBe(prev); // unchanged reference + }); + it("stays pending (undefined) when the first probe is transient", () => { + expect(nextGithubStatus(undefined, true, blip, 99)).toBeUndefined(); + }); +}); + +describe("GithubHeartbeat", () => { + it("runOnce → signed-out without calling the probe when there is no token", async () => { + const probe = vi.fn(); + const hb = new GithubHeartbeat(() => null, probe as unknown as (t: string) => Promise, () => 42); + await hb.runOnce(); + expect(probe).not.toHaveBeenCalled(); + expect(hb.current()).toEqual({ ok: false, hasToken: false, checkedAt: 42, detail: "not logged in — run /login" }); + }); + it("runOnce → connected when the token exchanges", async () => { + const hb = new GithubHeartbeat(() => "gho", async () => ok, () => 1); + await hb.runOnce(); + expect(hb.current()).toMatchObject({ ok: true, hasToken: true }); + }); + it("runOnce → expired on a definitive failure", async () => { + const hb = new GithubHeartbeat(() => "gho", async () => expired, () => 1); + await hb.runOnce(); + expect(hb.current()).toMatchObject({ ok: false, hasToken: true }); + }); + it("a transient failure does not flip a previously-connected status", async () => { + const probe = vi.fn<[], Promise>().mockResolvedValueOnce(ok).mockResolvedValueOnce(blip); + const hb = new GithubHeartbeat(() => "gho", probe as unknown as (t: string) => Promise, () => 1); + await hb.runOnce(); // connected + await hb.runOnce(); // transient blip + expect(hb.current()).toMatchObject({ ok: true }); + }); + it("current() is undefined before the first probe", () => { + const hb = new GithubHeartbeat(() => "gho", async () => ok); + expect(hb.current()).toBeUndefined(); + }); + + it("start() probes after the initial delay, then every interval; stop() halts it", async () => { + vi.useFakeTimers(); + try { + const probe = vi.fn(async () => ok); + const hb = new GithubHeartbeat(() => "gho", probe, () => 1); + hb.start(); + expect(probe).toHaveBeenCalledTimes(0); + await vi.advanceTimersByTimeAsync(GITHUB_HEARTBEAT_INITIAL_DELAY_MS); + expect(probe).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(GITHUB_HEARTBEAT_INTERVAL_MS); + expect(probe).toHaveBeenCalledTimes(2); + hb.stop(); + await vi.advanceTimersByTimeAsync(GITHUB_HEARTBEAT_INTERVAL_MS * 3); + expect(probe).toHaveBeenCalledTimes(2); // no further probes after stop + } finally { + vi.useRealTimers(); + } + }); + + it("honors a custom interval/initial-delay (used by the container e2e for a fast cadence)", async () => { + vi.useFakeTimers(); + try { + const probe = vi.fn(async () => ok); + const hb = new GithubHeartbeat(() => "gho", probe, () => 1, { intervalMs: 500, initialDelayMs: 100 }); + hb.start(); + await vi.advanceTimersByTimeAsync(100); + expect(probe).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(500); + expect(probe).toHaveBeenCalledTimes(2); + hb.stop(); + } finally { + vi.useRealTimers(); + } + }); + + it("start() is idempotent — a second start() without stop() does not leak a second timer", async () => { + vi.useFakeTimers(); + try { + const probe = vi.fn(async () => ok); + const hb = new GithubHeartbeat(() => "gho", probe, () => 1, { intervalMs: 500, initialDelayMs: 100 }); + hb.start(); + hb.start(); // second call must be a no-op, not a leaked parallel timer + await vi.advanceTimersByTimeAsync(100); + expect(probe).toHaveBeenCalledTimes(1); // one probe, not two + await vi.advanceTimersByTimeAsync(500); + expect(probe).toHaveBeenCalledTimes(2); // single cadence, not doubled + hb.stop(); + await vi.advanceTimersByTimeAsync(2000); + expect(probe).toHaveBeenCalledTimes(2); // stop() halts the single timer + } finally { + vi.useRealTimers(); + } + }); +}); diff --git a/tests/tui/app.test.tsx b/tests/tui/app.test.tsx index 27cf24f..1b93d87 100644 --- a/tests/tui/app.test.tsx +++ b/tests/tui/app.test.tsx @@ -64,4 +64,35 @@ describe("App", () => { expect(frame).toContain("ran-claude"); expect(frame).not.toContain("unknown command"); }); + + it("reflects the heartbeat github state in the footer (expired → ✗ /login)", async () => { + const statusSource = async () => ({ workerState: "ready" as const, restarts: [], github: { ok: false, hasToken: true, checkedAt: 1, detail: "expired" } }); + const { lastFrame } = render(); + await new Promise((r) => setTimeout(r, 60)); // let the immediate poll tick land + const f = lastFrame() ?? ""; + expect(f).toMatch(/github.*✗ \/login/); + }); + + it("footer shows github ✓ when the heartbeat reports connected", async () => { + const statusSource = async () => ({ workerState: "ready" as const, restarts: [], github: { ok: true, hasToken: true, checkedAt: 1, detail: "token valid" } }); + const { lastFrame } = render(); + await new Promise((r) => setTimeout(r, 60)); + expect(lastFrame() ?? "").toMatch(/github.*✓/); + }); + + it("/status does a live githubStatus() check rather than trusting the cached heartbeat (which can be stale)", async () => { + // Live check says "expired" (token just revoked); the cached heartbeat still reads "connected". + // /status must reflect the fresh live result, not the up-to-60s-stale cache. + const githubStatus = vi.fn(async () => "expired" as const); + const statusSource = async () => ({ workerState: "ready" as const, restarts: [], github: { ok: true, hasToken: true, checkedAt: 1, detail: "token valid" } }); + const { stdin, lastFrame } = render(); + await new Promise((r) => setTimeout(r, 60)); // poll populates the cached 'connected' state + stdin.write("/status"); + await new Promise((r) => setTimeout(r, 20)); + stdin.write("\r"); + await new Promise((r) => setTimeout(r, 80)); + const f = lastFrame() ?? ""; + expect(githubStatus).toHaveBeenCalled(); // /status is authoritative: it runs the live check + expect(f).toMatch(/expired/i); // and reflects the live result, not the stale cache + }); });