diff --git a/apps/web/src/components/settings/ProviderConnectFlow.tsx b/apps/web/src/components/settings/ProviderConnectFlow.tsx index 923d35229..a408be38c 100644 --- a/apps/web/src/components/settings/ProviderConnectFlow.tsx +++ b/apps/web/src/components/settings/ProviderConnectFlow.tsx @@ -134,6 +134,13 @@ export interface ProviderConnectFlowProps { * a flow that asks for it itself (Pi asks in its own question). */ readonly acceptsRedirect?: boolean; + /** + * A terminal run's command opens its sign-in page in the browser itself + * (`codex login`, `/login` in Pi). The panel then keeps the address it + * prints as a link, for when the browser didn't open, instead of opening + * the page a second time. + */ + readonly commandOpensBrowser?: boolean; /** * A browser sign-in the agent can also run in its own terminal (Pi's * `/login`): the command fallback stays, with what to type in it, and can @@ -348,6 +355,7 @@ export function ProviderConnectFlow({ runningHint, surface = "terminal", acceptsRedirect = true, + commandOpensBrowser = false, terminalFallback, }: ProviderConnectFlowProps) { const [showFallback, setShowFallback] = useState(false); @@ -415,10 +423,10 @@ export function ProviderConnectFlow({ } }, [autoShowTerminal, isBrowserFlow, needsTerminal, state.status, terminalFallbackRun]); - // Open the printed sign-in page once per run. Most CLIs open the browser - // themselves; the ones that cannot (fx inside WSL) print a device-code URL - // and wait, which would otherwise time out silently. A browser sign-in's - // page is opened by the flow hook, for whichever surface started it. + // Open the printed sign-in page once per run, unless the command opened it + // itself. CLIs that cannot (fx inside WSL) print a device-code URL and + // wait, which would otherwise time out silently. A browser sign-in's page + // is opened by the flow hook, for whichever surface started it. const openedSignInUrlRef = useRef(null); const openSignInUrl = (url: string) => { openedSignInUrlRef.current = url; @@ -433,6 +441,7 @@ export function ProviderConnectFlow({ if ( isBrowserFlow || isCommunityAgent || + commandOpensBrowser || !url || !isProviderConnectFlowActive(state.status) || openedSignInUrlRef.current === url @@ -440,7 +449,7 @@ export function ProviderConnectFlow({ return; } openSignInUrl(url); - }, [isBrowserFlow, isCommunityAgent, state.signInUrl, state.status]); + }, [commandOpensBrowser, isBrowserFlow, isCommunityAgent, state.signInUrl, state.status]); const startFlow = (options?: { readonly terminal?: boolean }) => { setShowTerminal(false); diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 8dd288040..a2a0ce91f 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -46,6 +46,7 @@ import { deriveClaudeLongLivedOAuthTokenState, GROK_DRIVER_KIND, sanitizeClaudeLongLivedOAuthTokenInput, + SELF_OPENING_SIGN_IN_DRIVERS, upsertClaudeLongLivedOAuthTokenEnvironment, } from "@threadlines/shared/providerAuthCommands"; @@ -562,6 +563,8 @@ function ClaudeLongLivedAuthSection(props: { readonly idPrefix: string; readonly instanceId: ProviderInstanceId; readonly setupCommand: string; + /** `claude setup-token` opens the authorization page itself. */ + readonly commandOpensBrowser: boolean; readonly environment: ReadonlyArray; readonly onChange: (environment: ReadonlyArray) => void; }) { @@ -630,6 +633,7 @@ function ClaudeLongLivedAuthSection(props: { displayName="Claude" actionLabel={tokenState.configured ? "Generate new token" : "Generate token"} command={props.setupCommand} + commandOpensBrowser={props.commandOpensBrowser} buttonVariant={tokenState.configured ? "outline" : "default"} description="Threadlines saves the token for you when it appears." /> @@ -881,6 +885,9 @@ function ProviderAccountSignInSection(props: { const browserSignIn = props.driverKind !== null && BROWSER_SIGN_IN_DRIVERS.has(String(props.driverKind)); const signOut = browserSignIn ? browserSignOutCopy(props.driverKind, props.instance) : null; + // Codex, Claude, Cursor, OpenCode and Pi open their sign-in page themselves. + const commandOpensBrowser = + props.driverKind !== null && SELF_OPENING_SIGN_IN_DRIVERS.has(String(props.driverKind)); const hasClaudeCredentialOverride = isClaude && hasClaudeCredentialOverrideEnvironment(props.environment); const claudeLongLivedTokenConfigured = @@ -954,6 +961,7 @@ function ProviderAccountSignInSection(props: { autoShowTerminal={(props.signInHandoffActive ?? false) || signInStartsInTerminal} surface={browserSignIn || isPi ? "browser" : "terminal"} acceptsRedirect={!isPi} + commandOpensBrowser={commandOpensBrowser} terminalFallback={ isPi ? { @@ -1072,6 +1080,7 @@ function ProviderAccountSignInSection(props: { idPrefix={props.idPrefix} instanceId={props.instanceId} setupCommand={props.claudeSetupTokenCommand} + commandOpensBrowser={commandOpensBrowser} environment={props.environment} onChange={props.onEnvironmentChange} /> diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index f5ea4d368..5f3b27022 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -2152,6 +2152,15 @@ describe("GeneralSettingsPanel observability", () => { }); it("signs a provider in without leaving settings", async () => { + const openExternal = vi.fn().mockResolvedValue(undefined); + window.nativeApi = { + persistence: { + getClientSettings: vi.fn().mockResolvedValue(null), + setClientSettings: vi.fn().mockResolvedValue(undefined), + }, + shell: { openExternal }, + server: {}, + } as unknown as LocalApi; setServerConfigSnapshot({ ...createBaseServerConfig(), providers: [ @@ -2206,6 +2215,19 @@ describe("GeneralSettingsPanel observability", () => { .toBeVisible(); await expect.element(page.getByText("Opening browser to complete sign-in")).toBeVisible(); + // Claude opened the page itself: the address it prints is a link, not a second tab. + const fallbackUrl = "https://claude.com/cai/oauth/authorize?code=true&state=abc"; + providerAuthHarness.emit({ + instanceId: "claudeAgent", + createdAt: "2026-08-03T00:00:01.500Z", + type: "output", + data: `If the browser didn't open, visit: ${fallbackUrl}\r\n`, + }); + const openPage = page.getByRole("button", { name: "Open sign-in page" }); + await openPage.click(); + // Opened once, by the click. + expect(openExternal.mock.calls).toEqual([[fallbackUrl]]); + providerAuthHarness.emit({ instanceId: "claudeAgent", createdAt: "2026-08-03T00:00:02.000Z", diff --git a/apps/web/src/components/settings/providerConnectFlow.logic.test.ts b/apps/web/src/components/settings/providerConnectFlow.logic.test.ts index 037bab8b1..5c2b59a9c 100644 --- a/apps/web/src/components/settings/providerConnectFlow.logic.test.ts +++ b/apps/web/src/components/settings/providerConnectFlow.logic.test.ts @@ -4,6 +4,7 @@ import type { ProviderAuthEvent, ProviderInstanceId } from "@threadlines/contrac import { applyProviderAuthEvent, appendOutputPreview, + extractSignInUrl, initialProviderConnectFlowState, providerConnectStatusLine, shouldAutoExpandTerminal, @@ -142,6 +143,61 @@ describe("provider connect flow state", () => { ).toMatchObject({ pageRequest: null, question: null }); }); + it("takes Codex's sign-in page, not its local server, as Windows prints them", () => { + const authUrl = + "https://auth.openai.com/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A1455%2Fauth%2Fcallback&state=abc&originator=codex_cli_rs"; + // ConPTY draws the blank lines around the address as a jump to a later row. + const state = replay([ + event({ type: "status", status: "starting", exitCode: null, detail: null }), + event({ + type: "output", + data: `Starting local login server on http://localhost:1455.\r\nIf your browser did not open, navigate to this URL to authenticate:\r\n\u001B[5;1H${authUrl}\u001B[7;1HOn a remote or headless machine? Use \`codex login --device-auth\` instead.`, + }), + ]); + expect(state.signInUrl).toBe(authUrl); + expect(state.lastLine).toBe( + "On a remote or headless machine? Use `codex login --device-auth` instead.", + ); + }); + + it("reads the whole address of a link Pi's screen wraps into rows", () => { + const authUrl = `https://claude.ai/oauth/authorize?code=true&client_id=pi&state=${"s".repeat(200)}`; + // Each row: a jump to it, the link with its full target, a 98-character slice. + const rows = [0, 98, 196] + .map( + (start, index) => + `\u001B[${index + 4};1H\u001B[2K \u001B]8;;${authUrl}\u001B\\${authUrl.slice(start, start + 98)}\u001B]8;;\u001B\\`, + ) + .join(""); + // Split inside the first link's code: the target must survive the chunk boundary. + const split = rows.indexOf("claude.ai"); + const state = replay([ + event({ type: "status", status: "starting", exitCode: null, detail: null }), + event({ type: "output", data: rows.slice(0, split) }), + event({ type: "output", data: rows.slice(split) }), + ]); + expect(state.signInUrl).toBe(authUrl); + + // A link longer than the kept tail, split just before its code ends. + const longUrl = `https://auth.example.com/authorize?state=${"x".repeat(2400)}`; + const longRow = `\u001B[4;1H \u001B]8;;${longUrl}\u001B\\${longUrl.slice(0, 98)}\u001B]8;;\u001B\\\u001B[5;1H`; + const end = longRow.indexOf("\u001B\\"); + expect( + replay([ + event({ type: "output", data: longRow.slice(0, end) }), + event({ type: "output", data: longRow.slice(end) }), + ]).signInUrl, + ).toBe(longUrl); + }); + + it("never takes an address on the CLI's own machine, or one cut short", () => { + expect( + extractSignInUrl( + "http://127.0.0.2:1455/ http://0.0.0.0:8080 http://login.localhost/ http://[::1]:1455/ https://auth.example.com/sign-in\n", + ), + ).toBe("https://auth.example.com/sign-in"); + }); + it("waits for a URL split across output chunks to finish before taking it", () => { const state = replay([ event({ type: "status", status: "starting", exitCode: null, detail: null }), @@ -153,6 +209,18 @@ describe("provider connect flow state", () => { const finished = applyProviderAuthEvent(state, event({ type: "output", data: "QL-JLJT\r\n" })); expect(finished.signInUrl).toBe("https://vercel.com/oauth/device?user_code=QJQL-JLJT"); + + // Still waiting for its line to end when the kept output is trimmed. + const authUrl = "https://auth.example.com/sign-in?code=abc"; + expect( + replay([ + event({ + type: "output", + data: `${"Waiting for sign-in\r".repeat(120)}${authUrl}\u001B[0m`, + }), + event({ type: "output", data: "\r\n" }), + ]).signInUrl, + ).toBe(authUrl); }); it("tracks a run from start to success and keeps the resolved command", () => { diff --git a/apps/web/src/components/settings/providerConnectFlow.logic.ts b/apps/web/src/components/settings/providerConnectFlow.logic.ts index dc22d1892..158a8822b 100644 --- a/apps/web/src/components/settings/providerConnectFlow.logic.ts +++ b/apps/web/src/components/settings/providerConnectFlow.logic.ts @@ -35,9 +35,9 @@ export interface ProviderConnectFlowState { */ readonly signInUrl: string | null; /** - * Recent output not yet holding a finished URL. Terminal output arrives in - * arbitrary chunks, so a device-code URL can be split mid-code; it is only - * taken once something follows it. + * Recent raw output not yet holding a finished URL. Terminal output arrives + * in arbitrary chunks, so a device-code URL (or the code around a link) can + * be split mid-way; it is only taken once something follows it. */ readonly urlScanTail: string; /** @@ -82,25 +82,103 @@ const OPEN_LINE_CHARS = 2048; const SIGN_IN_URL_PATTERN = /https?:\/\/[^\s"'<>)\]]+/gu; const URL_SCAN_TAIL_CHARS = 2048; +/** + * Whether `url` is a page to open: it parses, and its host is not the machine + * the CLI runs on. A local address (`codex login`'s `localhost:1455`) is where + * the CLI waits for the browser to come back. + */ +function isOpenablePage(url: string): boolean { + let hostname: string; + try { + // WHATWG parsing writes every IPv4 form (`127.1`, `2130706433`) as dotted. + hostname = new URL(url).hostname.toLowerCase(); + } catch { + // Cut short, like `http://[::1` where the pattern stops at `]`. + return false; + } + return !( + hostname === "localhost" || + hostname.endsWith(".localhost") || + hostname === "0.0.0.0" || + /^127\.\d+\.\d+\.\d+$/u.test(hostname) + ); +} + /** * The first http(s) URL in `text` that something follows (so it cannot still - * be streaming in), minus trailing punctuation. + * be streaming in), minus trailing punctuation, skipping any that is not a + * page to open. */ export function extractSignInUrl(text: string): string | null { for (const match of text.matchAll(SIGN_IN_URL_PATTERN)) { - if (match.index + match[0].length < text.length) { - return match[0].replace(/[.,;:!?]+$/u, ""); - } + if (match.index + match[0].length >= text.length) continue; + const url = match[0].replace(/[.,;:!?]+$/u, ""); + if (isOpenablePage(url)) return url; } return null; } const ANSI_ESCAPE_PATTERN = /\u001B\[[0-9;?]*[ -/]*[@-~]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)?|\u001B[@-Z\\-_]/gu; +/** + * Cursor moves to another row. Windows terminals (ConPTY) draw blank lines as + * such a jump instead of line breaks, so dropping it would run a printed URL + * into the words of the next line. + */ +// oxlint-disable-next-line no-control-regex -- matching escape sequences is the point +const CURSOR_ROW_MOVE_PATTERN = /\u001B\[[0-9;]*[ABEFHdf]/gu; const OTHER_CONTROL_PATTERN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/gu; +/** Terminal output as plain text: a jump to another row reads as a line break. */ export function stripTerminalControlSequences(value: string): string { - return value.replace(ANSI_ESCAPE_PATTERN, "").replace(OTHER_CONTROL_PATTERN, ""); + return value + .replace(CURSOR_ROW_MOVE_PATTERN, "\n") + .replace(ANSI_ESCAPE_PATTERN, "") + .replace(OTHER_CONTROL_PATTERN, ""); +} + +/** + * A hyperlink's opening code (OSC 8) and its target. A TUI that wraps a long + * link (`/login` in Pi) cuts the visible address into rows, but each row's + * link still carries the whole address. + */ +const HYPERLINK_TARGET_PATTERN = + // oxlint-disable-next-line no-control-regex -- matching escape sequences is the point + /\u001B\]8;[^;\u0007\u001B]*;([^\u0007\u001B]*)(?:\u0007|\u001B\\)/gu; + +/** Output as the URL scan reads it: each hyperlink's target on a line of its own. */ +function urlScanText(raw: string): string { + return stripTerminalControlSequences( + raw.replace(HYPERLINK_TARGET_PATTERN, (_, target: string) => (target ? `\n${target}\n` : "")), + ); +} + +/** + * One whole code at a given index: an OSC string with its end, a CSI + * sequence, or a two-character escape (never `ESC ]`, which starts an OSC). + */ +const ESCAPE_CODE_AT = + // oxlint-disable-next-line no-control-regex -- matching escape sequences is the point + /\u001B(?:\][^\u0007\u001B]*(?:\u0007|\u001B\\)|\[[0-?]*[ -/]*[@-~]|[@-Z\\^_])/uy; +/** The longest code kept whole across the cut: a link's target is one address. */ +const OPEN_CODE_MAX_CHARS = 16_384; + +/** + * The raw output the scan keeps for the next chunk: the last + * `URL_SCAN_TAIL_CHARS`, unless that cut lands inside a code. Then the tail + * starts at the code instead, so a link's target is never split from its + * code and run into the text after it. + */ +function nextUrlScanTail(raw: string): string { + const cut = raw.length - URL_SCAN_TAIL_CHARS; + if (cut <= 0) return raw; + const codeStart = raw.lastIndexOf("\u001B", cut - 1); + if (codeStart === -1) return raw.slice(cut); + ESCAPE_CODE_AT.lastIndex = codeStart; + // An unfinished code runs to the end of the output so far. + const codeEnd = ESCAPE_CODE_AT.test(raw) ? ESCAPE_CODE_AT.lastIndex : raw.length; + if (codeEnd <= cut) return raw.slice(cut); + return raw.length - codeStart <= OPEN_CODE_MAX_CHARS ? raw.slice(codeStart) : raw.slice(codeEnd); } /** @@ -140,14 +218,14 @@ export function applyProviderAuthEvent( if (state.signInUrl !== null) { return { ...state, lastLine, openLine }; } - const scanned = `${state.urlScanTail}${stripTerminalControlSequences(event.data)}`; - const signInUrl = extractSignInUrl(scanned); + const scanned = `${state.urlScanTail}${event.data}`; + const signInUrl = extractSignInUrl(urlScanText(scanned)); return { ...state, lastLine, openLine, signInUrl, - urlScanTail: signInUrl === null ? scanned.slice(-URL_SCAN_TAIL_CHARS) : "", + urlScanTail: signInUrl === null ? nextUrlScanTail(scanned) : "", }; } case "status": diff --git a/packages/shared/src/providerAuthCommands.ts b/packages/shared/src/providerAuthCommands.ts index ee9e2d0a0..83602a1ce 100644 --- a/packages/shared/src/providerAuthCommands.ts +++ b/packages/shared/src/providerAuthCommands.ts @@ -42,6 +42,21 @@ export const BROWSER_SIGN_IN_DRIVERS: ReadonlySet = new Set([ */ export const GUIDED_SIGN_IN_DRIVERS: ReadonlySet = new Set([PI_DRIVER_KIND]); +/** + * Drivers whose sign-in commands open the sign-in page in the browser + * themselves and print its address only for when the browser didn't open + * (`codex login`, `claude auth login` and `claude setup-token`, `cursor-agent + * login`, `opencode auth login`, `/login` in `pi`). Threadlines offers that + * address as a link instead of opening the page a second time. + */ +export const SELF_OPENING_SIGN_IN_DRIVERS: ReadonlySet = new Set([ + CODEX_DRIVER_KIND, + CLAUDE_DRIVER_KIND, + CURSOR_DRIVER_KIND, + OPENCODE_DRIVER_KIND, + PI_DRIVER_KIND, +]); + /** What a driver's browser sign-in is called where a command would be shown. */ export function browserSignInLabel(driver: string): string { return driver === GROK_DRIVER_KIND ? "Sign in with Grok" : "Sign in with Google";