Skip to content

Commit bb89009

Browse files
saravmajesticclaude
andcommitted
fix(auth): Ctrl+C during browser sign-in exits 130 instead of 0
`auth login` waited for the browser callback under a clack spinner. In a terminal the spinner's raw-mode stdin turns Ctrl+C into `process.exit(0)`, so `auth login ... && altimate-code link` continued after a canceled sign-in. Without a terminal its SIGINT listener swallowed the signal and the process kept waiting until the sign-in timed out. - Replace the spinner on the OAuth "auto" wait with a log line and race the callback against SIGINT; on cancel, fail with "Sign-in canceled." and exit 130 - `index.ts`: set the default exit code 1 before `FormatError`, so a `CliError`'s own `exitCode` is no longer overwritten (this also makes the existing `fail("Cancelled.", 130)` in `learn` exit 130) - Subprocess tests for Ctrl+C in a PTY and SIGINT without a terminal; both fail on `main` Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 70e3669 commit bb89009

3 files changed

Lines changed: 150 additions & 6 deletions

File tree

‎packages/opencode/src/cli/cmd/providers.ts‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,18 @@ const cliTry = <Value>(message: string, fn: () => PromiseLike<Value>) =>
4141
catch: (error) => new CliError({ message: message + errorMessage(error) }),
4242
})
4343

44+
// altimate_change start — resolve a pending wait on Ctrl+C (SIGINT) instead of letting it run to timeout
45+
const SIGNIN_CANCELED = Symbol("signin-canceled")
46+
const untilSigint = <Value>(promise: Promise<Value>) => {
47+
let onSigint = () => {}
48+
const canceled = new Promise<typeof SIGNIN_CANCELED>((resolve) => {
49+
onSigint = () => resolve(SIGNIN_CANCELED)
50+
process.once("SIGINT", onSigint)
51+
})
52+
return Promise.race([promise, canceled]).finally(() => process.off("SIGINT", onSigint))
53+
}
54+
// altimate_change end
55+
4456
const handlePluginAuth = Effect.fn("Cli.providers.pluginAuth")(function* (
4557
plugin: { auth: PluginAuth },
4658
provider: string,
@@ -108,11 +120,14 @@ const handlePluginAuth = Effect.fn("Cli.providers.pluginAuth")(function* (
108120
if (authorize.instructions) {
109121
yield* Prompt.log.info(authorize.instructions)
110122
}
111-
const spinner = Prompt.spinner()
112-
yield* spinner.start("Waiting for authorization...")
113-
const result = yield* cliTry("Failed to authorize: ", () => authorize.callback())
123+
// altimate_change start — no clack spinner here: its raw-mode stdin turns Ctrl+C into
124+
// process.exit(0), so a canceled sign-in looked successful to `&&` chains and scripts.
125+
yield* Prompt.log.info("Waiting for authorization... (Ctrl+C to cancel)")
126+
const result = yield* cliTry("Failed to authorize: ", () => untilSigint(authorize.callback()))
127+
if (result === SIGNIN_CANCELED) return yield* fail("Sign-in canceled.", 130)
128+
// altimate_change end
114129
if (result.type === "failed") {
115-
yield* spinner.stop("Failed to authorize", 1)
130+
yield* Prompt.log.error("Failed to authorize")
116131
}
117132
if (result.type === "success") {
118133
const saveProvider = result.provider ?? provider
@@ -133,7 +148,7 @@ const handlePluginAuth = Effect.fn("Cli.providers.pluginAuth")(function* (
133148
...(result.metadata ? { metadata: result.metadata } : {}),
134149
})
135150
}
136-
yield* spinner.stop("Login successful")
151+
yield* Prompt.log.success("Login successful")
137152
}
138153
}
139154

‎packages/opencode/src/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -286,13 +286,15 @@ try {
286286
await cli.parse()
287287
}
288288
} catch (e) {
289+
// altimate_change start — set the default before FormatError so a CliError's own exitCode (e.g. 130) wins
290+
process.exitCode = 1
289291
const formatted = FormatError(e)
292+
// altimate_change end
290293
if (formatted) UI.error(formatted)
291294
if (formatted === undefined) {
292295
UI.error("Unexpected error" + EOL)
293296
process.stderr.write(errorMessage(e) + EOL)
294297
}
295-
process.exitCode = 1
296298
} finally {
297299
// altimate_change start - telemetry flush
298300
// Flush any buffered telemetry events before exiting.
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
// Ctrl+C while `auth login` waits for a browser sign-in must exit 130, not 0.
2+
//
3+
// The wait used a clack spinner. In a terminal its raw-mode stdin turned Ctrl+C into
4+
// `process.exit(0)`, so `auth login ... && altimate-code link` carried on after a canceled
5+
// sign-in. Without a terminal its SIGINT listener swallowed the signal and the process kept
6+
// waiting until the sign-in timed out.
7+
import { afterAll, beforeAll, describe, expect, test } from "bun:test"
8+
import fs from "node:fs/promises"
9+
import os from "node:os"
10+
import path from "node:path"
11+
import { spawn as ptySpawn } from "@opencode-ai/core/pty/pty.bun"
12+
13+
const cliEntry = path.resolve(import.meta.dir, "../../src/index.ts")
14+
const argv = ["run", "--conditions=browser", cliEntry, "auth", "login", "-p", "fake-oauth"]
15+
const WAITING = "Waiting for authorization"
16+
17+
// An OAuth "auto" method whose browser callback never completes.
18+
const fakeAuthPlugin = `export const FakeAuth = async () => ({
19+
auth: {
20+
provider: "fake-oauth",
21+
methods: [
22+
{
23+
type: "oauth",
24+
label: "Fake browser sign-in",
25+
authorize: async () => ({
26+
url: "https://example.test/authorize",
27+
method: "auto",
28+
callback: () => new Promise(() => {}),
29+
}),
30+
},
31+
],
32+
},
33+
})
34+
`
35+
36+
let root: string
37+
let env: Record<string, string>
38+
39+
beforeAll(async () => {
40+
root = await fs.mkdtemp(path.join(os.tmpdir(), "auth-login-cancel-"))
41+
const pluginPath = path.join(root, "fake-auth.ts")
42+
await fs.writeFile(pluginPath, fakeAuthPlugin)
43+
env = {
44+
...(process.env as Record<string, string>),
45+
OPENCODE_TEST_HOME: root,
46+
HOME: root,
47+
XDG_CONFIG_HOME: path.join(root, ".config"),
48+
XDG_DATA_HOME: path.join(root, ".local/share"),
49+
XDG_STATE_HOME: path.join(root, ".local/state"),
50+
XDG_CACHE_HOME: path.join(root, ".cache"),
51+
OPENCODE_PURE: "1",
52+
OPENCODE_DISABLE_AUTOUPDATE: "1",
53+
OPENCODE_DISABLE_MODELS_FETCH: "1",
54+
OPENCODE_DISABLE_PROJECT_CONFIG: "1",
55+
OPENCODE_DISABLE_TELEMETRY: "1",
56+
OPENCODE_AUTH_CONTENT: "{}",
57+
OPENCODE_CONFIG_CONTENT: JSON.stringify({ plugin: [`file://${pluginPath}`] }),
58+
}
59+
})
60+
61+
afterAll(async () => {
62+
await fs.rm(root, { recursive: true, force: true })
63+
})
64+
65+
const withTimeout = <T>(promise: Promise<T>, ms: number, label: string) =>
66+
Promise.race([
67+
promise,
68+
new Promise<never>((_, reject) => setTimeout(() => reject(new Error(`${label} after ${ms}ms`)), ms)),
69+
])
70+
71+
describe("auth login cancel", () => {
72+
test("Ctrl+C in a terminal exits 130", async () => {
73+
const child = ptySpawn(process.execPath, argv, { name: "xterm-256color", cols: 120, rows: 40, cwd: root, env })
74+
let output = ""
75+
child.onData((data) => {
76+
output += data.toString()
77+
})
78+
const exited = new Promise<{ exitCode: number }>((resolve) => child.onExit(resolve))
79+
try {
80+
await withTimeout(
81+
(async () => {
82+
while (!output.includes(WAITING)) await Bun.sleep(50)
83+
})(),
84+
60_000,
85+
`never printed "${WAITING}": ${output}`,
86+
)
87+
child.write("\x03")
88+
const { exitCode } = await withTimeout(exited, 10_000, "still running after Ctrl+C")
89+
expect(exitCode).toBe(130)
90+
expect(output).toContain("Sign-in canceled.")
91+
} finally {
92+
child.kill()
93+
}
94+
}, 90_000)
95+
96+
test("SIGINT without a terminal exits 130 instead of waiting for the timeout", async () => {
97+
const proc = Bun.spawn([process.execPath, ...argv], {
98+
cwd: root,
99+
env,
100+
stdin: "ignore",
101+
stdout: "pipe",
102+
stderr: "pipe",
103+
})
104+
try {
105+
const reader = proc.stdout.getReader()
106+
const decoder = new TextDecoder()
107+
let output = ""
108+
await withTimeout(
109+
(async () => {
110+
while (!output.includes(WAITING)) {
111+
const { value, done } = await reader.read()
112+
if (done) throw new Error(`exited before waiting: ${output}`)
113+
output += decoder.decode(value)
114+
}
115+
})(),
116+
60_000,
117+
`never printed "${WAITING}": ${output}`,
118+
)
119+
reader.releaseLock()
120+
proc.kill("SIGINT")
121+
expect(await withTimeout(proc.exited, 10_000, "still running after SIGINT")).toBe(130)
122+
expect(await new Response(proc.stderr).text()).toContain("Sign-in canceled.")
123+
} finally {
124+
proc.kill("SIGKILL")
125+
}
126+
}, 90_000)
127+
})

0 commit comments

Comments
 (0)