From b051e0c8cf5c2fc88536a4fe6e054948593a4b86 Mon Sep 17 00:00:00 2001 From: Wang Can Date: Thu, 25 Jun 2026 12:40:18 +0800 Subject: [PATCH 1/3] fix(login): show device code immediately so /login no longer hangs /login produced no output and deadlocked: the slash dispatcher only renders a command's resolved value, but the handler blocked in pollForToken before returning, so the device code stayed hidden and the user could never authorize it. Split device login into beginDeviceLogin (returns the code at once) + complete() (polls), and give the TUI a non-blocking /login branch that renders the verification URL + code first, then a completion card. Also refresh the CopilotTokenStore after re-login so the model picker keeps working once the old Copilot token rotates. Co-Authored-By: Claude --- .changes/fix-login-deadlock.md | 4 ++++ e2e/RESULTS.md | 7 +++++++ src/cli/auth.ts | 28 ++++++++++++++++++++++++---- src/cli/index.ts | 26 ++++++++++++++++---------- src/tui/app.tsx | 15 ++++++++++++++- tests/cli/auth.test.ts | 23 ++++++++++++++++++++++- tests/tui/app-interaction.test.tsx | 27 +++++++++++++++++++++++++++ 7 files changed, 114 insertions(+), 16 deletions(-) create mode 100644 .changes/fix-login-deadlock.md diff --git a/.changes/fix-login-deadlock.md b/.changes/fix-login-deadlock.md new file mode 100644 index 0000000..7990c6e --- /dev/null +++ b/.changes/fix-login-deadlock.md @@ -0,0 +1,4 @@ +--- +bump: patch +--- +Fix `/login` hanging with no output: the device-code prompt is now shown immediately while authorization is pending, instead of being buffered behind the blocking token poll. diff --git a/e2e/RESULTS.md b/e2e/RESULTS.md index b06481f..aa590f6 100644 --- a/e2e/RESULTS.md +++ b/e2e/RESULTS.md @@ -3,6 +3,13 @@ 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-25** — Fixed the `/login` deadlock: the slash command buffered the device code behind a + blocking token poll, so the Repl showed nothing and the user could never authorize. Split device + login into `beginDeviceLogin` (returns the code immediately) + `complete()` (polls), and gave the + TUI a non-blocking `/login` branch that renders the verification URL + code first, then a + completion card. Full suite green: `npm test` → **238 passed** (47 files), `npm run test:e2e` → + **31 passed** (4 files), tsc build clean. + - **2026-06-23** — Added `ToolCallExtractor` (recovers text-emitted ``/`` tool calls into structured tool chunks) plus changeset-driven auto-release (build-time version injection, release workflow). Full suite green: `npm test` → **236 passed** (47 files), e2e all diff --git a/src/cli/auth.ts b/src/cli/auth.ts index 11d5dc4..d13ff98 100644 --- a/src/cli/auth.ts +++ b/src/cli/auth.ts @@ -1,10 +1,30 @@ -import { requestDeviceCode, pollForToken } from "../providers/copilot/auth.js"; +import { requestDeviceCode, pollForToken, type DeviceCode } from "../providers/copilot/auth.js"; import { writeGhToken } from "../shared/creds.js"; -export async function runDeviceLogin(dir: string, fetchFn: typeof fetch = fetch, log: (m: string) => void = console.log): Promise { +export interface PendingLogin { + code: DeviceCode; // verification URL + user_code — show this immediately + complete: () => Promise; // blocks on authorization, then persists the token +} + +// Two-phase device login. `beginDeviceLogin` returns the verification code right away so a caller +// can surface it to the user; `complete()` then blocks on authorization and writes the token. +// Splitting these is what lets the TUI render the code while the poll is still pending — folding +// both into one call buffers the code behind the blocking poll, and the user can't authorize a +// code they can't see. +export async function beginDeviceLogin(dir: string, fetchFn: typeof fetch = fetch): Promise { const code = await requestDeviceCode(fetchFn); + return { + code, + complete: async () => { + const token = await pollForToken(code.device_code, code.interval * 1000, fetchFn); + writeGhToken(token, dir); + }, + }; +} + +export async function runDeviceLogin(dir: string, fetchFn: typeof fetch = fetch, log: (m: string) => void = console.log): Promise { + const { code, complete } = await beginDeviceLogin(dir, fetchFn); log(`\nOpen ${code.verification_uri} and enter code: ${code.user_code}\n`); - const token = await pollForToken(code.device_code, code.interval * 1000, fetchFn); - writeGhToken(token, dir); + await complete(); log("GitHub authorization complete."); } diff --git a/src/cli/index.ts b/src/cli/index.ts index ba69057..010eec6 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -5,7 +5,7 @@ import { Command } from "commander"; import { App } from "../tui/app.js"; import { buildRegistry } from "../tui/slash/commands.js"; import { DaemonClient } from "../tui/daemon-client.js"; -import { runDeviceLogin } from "./auth.js"; +import { runDeviceLogin, beginDeviceLogin } from "./auth.js"; import { probeSupervisor } from "../daemon/lifecycle.js"; import { startSupervisor } from "../supervisor/index.js"; import { runAssistantTurn } from "../tui/assistant/runtime.js"; @@ -78,14 +78,6 @@ async function launchTui(): Promise { appVersion: APP_VERSION, platform: `${process.platform} node-${process.version}`, resetClient, - // Re-run device-code login, then restart the worker so it picks up the new token. - login: async () => { - const lines: string[] = []; - await runDeviceLogin(dataDir(), fetch, (m) => lines.push(m)); - await client.restart().catch(() => {}); - lines.push("worker restarting with the new token"); - return lines; - }, // Clear the stored token and restart the worker (it will report unauthenticated until re-login). logout: async () => { clearGhToken(dataDir()); @@ -93,9 +85,22 @@ async function launchTui(): Promise { return ["signed out — GitHub token removed", "run /login to sign in again"]; }, }); + // Two-phase /login for the TUI: surface the device code immediately, poll in the background, then + // restart the worker so it picks up the new token. The blocking single-call form deadlocked the + // Repl (the code stayed hidden behind the poll, so the user could never authorize it). + const doLogin = async (show: (lines: string[]) => void): Promise => { + const { code, complete } = await beginDeviceLogin(dataDir()); + show([`Open ${code.verification_uri} and enter code: ${code.user_code}`, "waiting for authorization…"]); + await complete(); + // Re-point the token store at the freshly written GitHub token; the old store still holds the + // expired one and would 401 once its cached Copilot token rotates, breaking the model picker. + tokenStore = new CopilotTokenStore(readGhToken(dataDir())!); + await client.restart().catch(() => {}); + return ["GitHub authorization complete — worker restarting with the new token"]; + }; // Filled in below once we have a token; the assistant prefers a model's real window over the default. const modelLimits: Record = {}; - const tokenStore = new CopilotTokenStore(readGhToken(dataDir())!); + let tokenStore = new CopilotTokenStore(readGhToken(dataDir())!); const loadModels = async () => { const token = await tokenStore.get(); const [ids, limits] = await Promise.all([fetchCopilotModels(token), fetchModelLimits(token)]); @@ -155,6 +160,7 @@ async function launchTui(): Promise { }, onModelChange: (m: string) => writeChatModel(dataDir(), m), pickModelOnStart: !persistedModel, + login: doLogin, }), ); } diff --git a/src/tui/app.tsx b/src/tui/app.tsx index f8729cd..64425f1 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -47,6 +47,10 @@ export interface AppProps { info?: ConfigInfo; onModelChange?: (model: string) => void; pickModelOnStart?: boolean; + // Device-code login. `show` pushes the verification URL + code to the UI immediately; the + // returned promise resolves with a completion message once the user authorizes. The two-phase + // shape is required: a single blocking call would hide the code behind the token poll. + login?: (show: (lines: string[]) => void) => Promise; } function OutputCard({ title, lines, tone }: { title: string; lines: string[]; tone: "info" | "ok" | "error" }) { @@ -101,7 +105,7 @@ function ClientBadge({ name, status }: { name: string; status: { user: boolean; export function App({ registry, title, workerState = "starting", initialModel = "—", statusSource, readStatus, modelLimits, onChat, - loadModels, setup, info, onModelChange, pickModelOnStart, + loadModels, setup, info, onModelChange, pickModelOnStart, login, }: AppProps) { const cmds: CommandHint[] = registry.list().map((c) => ({ name: c.name, describe: c.describe })); const [entries, setEntries] = useState([ @@ -150,6 +154,15 @@ export function App({ const t = line.trim(); if (t === "/model" && loadModels) { setScreen({ kind: "model" }); return; } if (t === "/config" && info) { setScreen({ kind: "config" }); return; } + if (t === "/login" && login) { + // Show the verification URL + code right away, then resolve a completion card once the user + // authorizes. Done as a special case (not a registry command) because the slash registry only + // renders a command's final return value — it can't surface the code mid-poll. + void login((lines) => add({ type: "card", title: "/login", tone: "info", lines })) + .then((lines) => add({ type: "card", title: "/login", tone: "ok", lines })) + .catch((e) => add({ type: "card", title: "/login", tone: "error", lines: [`login failed: ${String(e)}`] })); + return; + } if (setup && loadModels && (t === "/setup-claude" || t === "/setup-codex")) { setScreen({ kind: "setup", client: t === "/setup-claude" ? "claude" : "codex" }); return; diff --git a/tests/cli/auth.test.ts b/tests/cli/auth.test.ts index 37d2dc4..1167cf8 100644 --- a/tests/cli/auth.test.ts +++ b/tests/cli/auth.test.ts @@ -2,7 +2,7 @@ import { describe, it, expect, vi } from "vitest"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runDeviceLogin } from "../../src/cli/auth.js"; +import { runDeviceLogin, beginDeviceLogin } from "../../src/cli/auth.js"; import { readGhToken } from "../../src/shared/creds.js"; const json = (b: unknown) => new Response(JSON.stringify(b), { status: 200, headers: { "content-type": "application/json" } }); @@ -18,3 +18,24 @@ describe("runDeviceLogin", () => { expect(log).toHaveBeenCalledWith(expect.stringContaining("AB-12")); }); }); + +describe("beginDeviceLogin (two-phase)", () => { + it("returns the device code immediately, before any token poll runs", async () => { + const d = mkdtempSync(join(tmpdir(), "m-")); + let polled = false; + const f = vi.fn() + .mockResolvedValueOnce(json({ device_code: "dc", user_code: "AB-12", verification_uri: "https://github.com/login/device", interval: 0, expires_in: 900 })) + .mockImplementationOnce(() => { polled = true; return Promise.resolve(json({ access_token: "gho_z" })); }); + + const { code, complete } = await beginDeviceLogin(d, f as unknown as typeof fetch); + // The verification code is available without waiting for authorization. + expect(code.user_code).toBe("AB-12"); + expect(code.verification_uri).toContain("github.com/login/device"); + expect(polled).toBe(false); + + // Completing the flow then polls and persists the token. + await complete(); + expect(polled).toBe(true); + expect(readGhToken(d)).toBe("gho_z"); + }); +}); diff --git a/tests/tui/app-interaction.test.tsx b/tests/tui/app-interaction.test.tsx index 5fc524d..eab1cf5 100644 --- a/tests/tui/app-interaction.test.tsx +++ b/tests/tui/app-interaction.test.tsx @@ -107,6 +107,33 @@ describe("TUI: Repl autocomplete navigation", () => { }); }); +describe("TUI: /login surfaces the device code before the poll resolves", () => { + it("renders the verification URL + code immediately, not buffered behind the token poll", async () => { + // Reproduces the deadlock: the old /login buffered its device-code line and only returned + // (and thus rendered) after pollForToken resolved — but the user can't authorize a code they + // can't see. The login prop must push the code to the UI, then resolve when authorized. + let releaseToken!: () => void; + const tokenGate = new Promise((r) => { releaseToken = r; }); + const login = (show: (lines: string[]) => void) => { + show(["Open https://github.com/login/device and enter code: AB-12"]); + return tokenGate.then(() => ["GitHub authorization complete."]); + }; + const { stdin, lastFrame } = render(); + await tick(); + stdin.write("/login"); + await tick(); + stdin.write("\r"); + await tick(80); + // The code is on screen WHILE the token poll is still pending (gate not released). + expect(lastFrame()).toContain("AB-12"); + expect(lastFrame()).toContain("github.com/login/device"); + + releaseToken(); + await tick(80); + expect(lastFrame()).toContain("GitHub authorization complete."); + }); +}); + describe("TUI: model picker", () => { it("/model opens the picker and lists models with context windows", async () => { const loadModels = async () => ["gpt-4o", "claude-opus-4.8"]; From 6382fbece7a163b9621f0f418f4c4e4388c67deb Mon Sep 17 00:00:00 2001 From: Wang Can Date: Thu, 25 Jun 2026 14:51:22 +0800 Subject: [PATCH 2/3] fix(login): handle auth failure + guard double /login MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A rejected device-code poll (e.g. incorrect_device_code) previously escaped as an unhandled rejection and killed the process. Surface it as an error card with a clean message (strip the Error: prefix), and guard against a double Enter starting two concurrent device-code flows — the second code supersedes the first, so polling the first 401s. Co-Authored-By: Claude --- e2e/RESULTS.md | 4 +++- src/tui/app.tsx | 9 ++++++-- tests/tui/app-interaction.test.tsx | 33 ++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/e2e/RESULTS.md b/e2e/RESULTS.md index aa590f6..17efd76 100644 --- a/e2e/RESULTS.md +++ b/e2e/RESULTS.md @@ -7,7 +7,9 @@ and update this file (paste the summary). blocking token poll, so the Repl showed nothing and the user could never authorize. Split device login into `beginDeviceLogin` (returns the code immediately) + `complete()` (polls), and gave the TUI a non-blocking `/login` branch that renders the verification URL + code first, then a - completion card. Full suite green: `npm test` → **238 passed** (47 files), `npm run test:e2e` → + completion card. Also hardened the failure path: auth errors (e.g. `incorrect_device_code`) render + a clean error card instead of crashing the process, and a double Enter no longer starts two + device-code flows. Full suite green: `npm test` → **240 passed** (47 files), `npm run test:e2e` → **31 passed** (4 files), tsc build clean. - **2026-06-23** — Added `ToolCallExtractor` (recovers text-emitted ``/`` diff --git a/src/tui/app.tsx b/src/tui/app.tsx index 64425f1..641255e 100644 --- a/src/tui/app.tsx +++ b/src/tui/app.tsx @@ -117,6 +117,7 @@ export function App({ const [screen, setScreen] = useState(pickModelOnStart && loadModels ? { kind: "model" } : null); const [, setNow] = useState(0); // ticks the live loading line while the assistant streams const abortRef = useRef(null); // current turn's interrupt handle + const loginInFlight = useRef(false); // guards against starting a second device-login flow const add = (e: Entry) => setEntries((p) => [...p, e].slice(-100)); const refreshStatus = () => { if (readStatus) setStatus(readStatus()); }; @@ -157,10 +158,14 @@ export function App({ if (t === "/login" && login) { // Show the verification URL + code right away, then resolve a completion card once the user // authorizes. Done as a special case (not a registry command) because the slash registry only - // renders a command's final return value — it can't surface the code mid-poll. + // renders a command's final return value — it can't surface the code mid-poll. Guarded so a + // double Enter doesn't start two device-code flows (polling a superseded code 401s). + if (loginInFlight.current) { add({ type: "card", title: "/login", tone: "info", lines: ["already waiting for authorization…"] }); return; } + loginInFlight.current = true; void login((lines) => add({ type: "card", title: "/login", tone: "info", lines })) .then((lines) => add({ type: "card", title: "/login", tone: "ok", lines })) - .catch((e) => add({ type: "card", title: "/login", tone: "error", lines: [`login failed: ${String(e)}`] })); + .catch((e) => add({ type: "card", title: "/login", tone: "error", lines: [`login failed: ${e instanceof Error ? e.message : String(e)}`] })) + .finally(() => { loginInFlight.current = false; }); return; } if (setup && loadModels && (t === "/setup-claude" || t === "/setup-codex")) { diff --git a/tests/tui/app-interaction.test.tsx b/tests/tui/app-interaction.test.tsx index eab1cf5..62c7b74 100644 --- a/tests/tui/app-interaction.test.tsx +++ b/tests/tui/app-interaction.test.tsx @@ -132,6 +132,39 @@ describe("TUI: /login surfaces the device code before the poll resolves", () => await tick(80); expect(lastFrame()).toContain("GitHub authorization complete."); }); + + it("renders an error card (not a crash) when authorization fails", async () => { + // A rejected poll (e.g. expired/incorrect device code) must surface as an error card. The old + // path let the rejection escape as an unhandled rejection and killed the whole process. + const login = (show: (lines: string[]) => void) => { + show(["Open https://github.com/login/device and enter code: AB-12"]); + return Promise.reject(new Error("authorization failed: incorrect_device_code")); + }; + const { stdin, lastFrame } = render(); + await tick(); + stdin.write("/login"); + await tick(); + stdin.write("\r"); + await tick(80); + const f = lastFrame() ?? ""; + expect(f).toContain("login failed"); + expect(f).toContain("incorrect_device_code"); + // The raw "Error:" prefix should be stripped — show a clean message. + expect(f).not.toContain("Error:"); + }); + + it("ignores a second /login while one is already in flight", async () => { + // The user can hit Enter on /login twice; without a guard that starts two device-code flows, + // and polling a superseded code fails with incorrect_device_code. Only one flow should start. + let starts = 0; + const gate = new Promise(() => {}); // never resolves — login stays pending + const login = (show: (lines: string[]) => void) => { starts++; show([`code ${starts}`]); return gate; }; + const { stdin } = render(); + await tick(); + stdin.write("/login"); await tick(); stdin.write("\r"); await tick(60); + stdin.write("/login"); await tick(); stdin.write("\r"); await tick(60); + expect(starts).toBe(1); + }); }); describe("TUI: model picker", () => { From 7dec5a630aa0e7fd0c391dcd25bd0d744c7ff59f Mon Sep 17 00:00:00 2001 From: Wang Can Date: Thu, 25 Jun 2026 15:11:04 +0800 Subject: [PATCH 3/3] feat(chat): block signed-out turns with a /login hint instead of hanging After /logout (or an expired login), sending a chat message fired a request that just hung until the 120s turn timeout, then printed an opaque "no response". Add an optional pre-flight auth gate to makeOnChat that runs before each turn; production wires it to the long-lived tokenStore so a valid login is a cached, round-trip-free check, while a missing/expired token blocks the turn immediately with a "run /login" hint. Co-Authored-By: Claude --- e2e/RESULTS.md | 6 ++++-- src/cli/index.ts | 10 ++++++++++ src/tui/assistant/on-chat.ts | 12 +++++++++++- tests/cli/onchat.test.ts | 20 ++++++++++++++++++++ 4 files changed, 45 insertions(+), 3 deletions(-) diff --git a/e2e/RESULTS.md b/e2e/RESULTS.md index 17efd76..6327996 100644 --- a/e2e/RESULTS.md +++ b/e2e/RESULTS.md @@ -9,8 +9,10 @@ and update this file (paste the summary). TUI a non-blocking `/login` branch that renders the verification URL + code first, then a completion card. Also hardened the failure path: auth errors (e.g. `incorrect_device_code`) render a clean error card instead of crashing the process, and a double Enter no longer starts two - device-code flows. Full suite green: `npm test` → **240 passed** (47 files), `npm run test:e2e` → - **31 passed** (4 files), tsc build clean. + device-code flows. Added a pre-flight auth gate on chat: a signed-out or expired-login message is + blocked immediately with a "run /login" hint instead of hanging until the 120s turn timeout. Full + suite green: `npm test` → **242 passed** (47 files), `npm run test:e2e` → **31 passed** (4 files), + tsc build clean. - **2026-06-23** — Added `ToolCallExtractor` (recovers text-emitted ``/`` tool calls into structured tool chunks) plus changeset-driven auto-release (build-time version diff --git a/src/cli/index.ts b/src/cli/index.ts index 010eec6..ee46a33 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -136,6 +136,16 @@ async function launchTui(): Promise { setupClient: async (c, s, m) => applyClient(c, s, m), }, (c, p, print, abort) => runAssistantTurn(c, p, print, undefined, abort), + undefined, + // Pre-flight auth gate: block a turn (with an actionable hint) when there's no GitHub token, or + // the stored one no longer exchanges for a Copilot token — instead of firing a request that just + // hangs until the turn timeout. Reuses the long-lived tokenStore so a valid login is a cached, + // round-trip-free check between message bursts (its get() caches with a 60s skew). + async () => { + if (!readGhToken(dataDir())) return "you're signed out — run /login to sign in before chatting"; + try { await tokenStore.get(); return null; } + catch { return "your GitHub login has expired — run /login to sign in again"; } + }, ); const persistedModel = readChatModel(dataDir()); diff --git a/src/tui/assistant/on-chat.ts b/src/tui/assistant/on-chat.ts index fd30c0b..fe6ee40 100644 --- a/src/tui/assistant/on-chat.ts +++ b/src/tui/assistant/on-chat.ts @@ -2,10 +2,20 @@ import type { AssistantConfig } from "./runtime.js"; type TurnRunner = (cfg: AssistantConfig, prompt: string, print: (l: string) => void, abort?: AbortController) => Promise; +// Optional pre-flight check run before each turn. Returns a message to show (and block the turn) when +// the user can't chat yet — e.g. signed out or an expired Copilot login — or null to proceed. +type Precheck = () => Promise; + const DEFAULT_TURN_TIMEOUT_MS = 120_000; // 2 minutes — a turn that hasn't replied by then is given up on -export function makeOnChat(cfg: AssistantConfig, runner: TurnRunner, timeoutMs = DEFAULT_TURN_TIMEOUT_MS) { +export function makeOnChat(cfg: AssistantConfig, runner: TurnRunner, timeoutMs = DEFAULT_TURN_TIMEOUT_MS, precheck?: Precheck) { return async (text: string, print: (line: string) => void, model?: string, abort?: AbortController): Promise => { + // Gate the turn on auth before firing a doomed request. Without this, a signed-out user's message + // hangs until the 120s timeout instead of getting an immediate, actionable hint. + if (precheck) { + const blocked = await precheck().catch(() => null); // a failed check must never wedge chat + if (blocked) { print(blocked); return; } + } const ctrl = abort ?? new AbortController(); let timedOut = false; // Race the turn against a hard timeout so a hung SDK/upstream can never block the UI forever. diff --git a/tests/cli/onchat.test.ts b/tests/cli/onchat.test.ts index fb66b92..f334d80 100644 --- a/tests/cli/onchat.test.ts +++ b/tests/cli/onchat.test.ts @@ -48,4 +48,24 @@ describe("makeOnChat", () => { await p; expect(printed.join("\n")).toMatch(/interrupted/); }); + + it("blocks the turn and steers to /login when the precheck reports no valid login", async () => { + const runner = vi.fn(async () => {}); + const printed: string[] = []; + const precheck = vi.fn(async () => "signed out — run /login to sign in again"); + const onChat = makeOnChat({ client: {} as any, workerBaseUrl: "http://x", apiKey: "k", model: "m" }, runner as any, undefined, precheck); + await onChat("hi", (l) => printed.push(l)); + expect(runner).not.toHaveBeenCalled(); // never fires the doomed request + expect(printed.join("\n")).toMatch(/\/login/); + }); + + it("runs the turn normally when the precheck passes", async () => { + const runner = vi.fn(async (_c: any, prompt: string, print: (l: string) => void) => { print(`echo:${prompt}`); }); + const printed: string[] = []; + const precheck = vi.fn(async () => null); // null = login OK + const onChat = makeOnChat({ client: {} as any, workerBaseUrl: "http://x", apiKey: "k", model: "m" }, runner as any, undefined, precheck); + await onChat("hello", (l) => printed.push(l)); + expect(precheck).toHaveBeenCalled(); + expect(printed).toContain("echo:hello"); + }); });