From 16973ca97cd89b9211c4851b25411676925e9555 Mon Sep 17 00:00:00 2001 From: LHaghfoss Date: Tue, 24 Nov 2026 15:00:48 +0100 Subject: [PATCH] feat(desktop): sign in to GitHub and manage model accounts in Connections --- apps/desktop/src/acp/mock.ts | 24 +- apps/desktop/src/acp/mockConnections.ts | 114 ++++++ apps/desktop/src/acp/types.ts | 1 + apps/desktop/src/state/connections.ts | 125 ++++++ apps/desktop/src/ui/Settings.tsx | 125 +----- apps/desktop/src/ui/SettingsConnections.tsx | 404 ++++++++++++++++++++ apps/desktop/src/ui/icons.tsx | 4 + docs/desktop.md | 3 +- 8 files changed, 656 insertions(+), 144 deletions(-) create mode 100644 apps/desktop/src/acp/mockConnections.ts create mode 100644 apps/desktop/src/state/connections.ts create mode 100644 apps/desktop/src/ui/SettingsConnections.tsx diff --git a/apps/desktop/src/acp/mock.ts b/apps/desktop/src/acp/mock.ts index 1f3254801..7df277db8 100644 --- a/apps/desktop/src/acp/mock.ts +++ b/apps/desktop/src/acp/mock.ts @@ -21,6 +21,7 @@ import { mockGit, mockQrRows } from "./mockGit"; import { BUILTIN_THEMES } from "../lib/themes"; import { arr, type Json, type JsonObject, num, obj, str } from "./jsonrpc"; +import { MockConnections } from "./mockConnections"; import { mockBrowse, mockCreate } from "./mockFolders"; import { ACP_CAPS, HARNESS_MODELS, initialHarnesses, MOCK_CUSTOM_MODELS, withLast } from "./mockHarnesses"; import { MockLoops } from "./mockLoops"; @@ -93,6 +94,7 @@ export class MockEngine { private waiting = new Map void>(); private counter = 0; private loops = new MockLoops(); + private connections = new MockConnections(); private agents = new Map(); /** The inbox seed runs once, after the list the app first reads. */ private needsYouSeeded = false; @@ -858,6 +860,8 @@ export class MockEngine { private async handle(method: string, params: JsonObject): Promise { if (method.startsWith("_rustcode/loops/")) return this.loops.answer(method, obj(params) ?? {}); + if (method === "_rustcode/connections" || method.startsWith("_rustcode/connections/")) + return this.connections.answer(method, obj(params) ?? {}); if (isMockTransferMethod(method)) { return handleMockTransfer(method, params, { getThread: (id) => this.thread(id), @@ -2467,26 +2471,6 @@ export class MockEngine { this.mcpRestarted.add(name); return this.handle("_rustcode/capabilities", {}); } - case "_rustcode/connections": - return { - github: { - cliInstalled: true, - accounts: [{ host: "github.com", login: "octocat", active: true, valid: true, scopes: ["repo"] }], - pending: null, - error: null, - }, - accounts: [ - { - provider: "openai", - account: "a1", - display: "you@example.com", - method: "chat_gpt", - active: true, - expiresAt: null, - needsSignIn: false, - }, - ], - }; default: throw Object.assign(new Error("Method not found"), { code: -32601 }); } diff --git a/apps/desktop/src/acp/mockConnections.ts b/apps/desktop/src/acp/mockConnections.ts new file mode 100644 index 000000000..35ddd4ffb --- /dev/null +++ b/apps/desktop/src/acp/mockConnections.ts @@ -0,0 +1,114 @@ +import { type JsonObject, str } from "./jsonrpc"; + +const APPROVE_MS = 4000; + +interface GitHubRow { + host: string; + login: string; + active: boolean; + valid: boolean; + scopes: string[]; +} + +interface AccountRow { + provider: string; + account: string; + display: string; + method: string; + active: boolean; + expiresAt: null; + needsSignIn: boolean; +} + +/** + * The mock engine's Settings › Connections (`_rustcode/connections/*`): one GitHub sign-in, a + * device-code sign-in that GitHub approves after a few seconds, and three model accounts. + */ +export class MockConnections { + private github: GitHubRow[] = [ + { host: "github.com", login: "octocat", active: true, valid: true, scopes: ["repo", "read:org"] }, + ]; + private accounts: AccountRow[] = [ + { + provider: "openai", + account: "a1", + display: "you@example.com", + method: "chat_gpt", + active: true, + expiresAt: null, + needsSignIn: false, + }, + { + provider: "anthropic", + account: "work", + display: "Work API key", + method: "api_key", + active: false, + expiresAt: null, + needsSignIn: false, + }, + { + provider: "github_copilot", + account: "c1", + display: "octocat", + method: "github_copilot", + active: false, + expiresAt: null, + needsSignIn: true, + }, + ]; + private pending: { code: string; url: string } | null = null; + private approval: ReturnType | null = null; + + snapshot(): JsonObject { + return { + github: { + cliInstalled: true, + installHint: "brew install gh", + accounts: this.github.map((a) => ({ ...a })), + pending: this.pending, + error: null, + }, + accounts: this.accounts.map((a) => ({ ...a })), + }; + } + + async answer(method: string, params: JsonObject): Promise { + switch (method) { + case "_rustcode/connections/github/login": + this.pending = { code: "4F2A-9C7D", url: "https://github.com/login/device" }; + return this.pending; + case "_rustcode/connections/github/wait": + await new Promise((resolve, reject) => { + this.approval = setTimeout(resolve, APPROVE_MS); + this.rejectWait = reject; + }); + this.pending = null; + this.github = this.github.filter((a) => a.login !== "hubot").map((a) => ({ ...a, active: false })); + this.github.push({ host: "github.com", login: "hubot", active: true, valid: true, scopes: ["repo"] }); + return this.snapshot(); + case "_rustcode/connections/github/cancel": + if (this.approval) clearTimeout(this.approval); + this.pending = null; + this.rejectWait?.(new Error("GitHub sign-in was cancelled.")); + return {}; + case "_rustcode/connections/github/logout": + this.github = this.github.filter( + (a) => !(a.host === str(params.host) && a.login === str(params.login)), + ); + return this.snapshot(); + case "_rustcode/connections/account/logout": + this.accounts = this.accounts.filter( + (a) => !(a.provider === str(params.provider) && a.account === str(params.account)), + ); + return this.snapshot(); + case "_rustcode/connections/account/refresh": + await new Promise((r) => setTimeout(r, 600)); + return this.snapshot(); + default: + return this.snapshot(); + } + } + + private rejectWait: ((e: Error) => void) | null = null; +} diff --git a/apps/desktop/src/acp/types.ts b/apps/desktop/src/acp/types.ts index cb08c502c..fddda0317 100644 --- a/apps/desktop/src/acp/types.ts +++ b/apps/desktop/src/acp/types.ts @@ -97,6 +97,7 @@ export const Method = { githubCancel: "_rustcode/connections/github/cancel", githubLogout: "_rustcode/connections/github/logout", accountLogout: "_rustcode/connections/account/logout", + accountRefresh: "_rustcode/connections/account/refresh", pulls: "_rustcode/pulls", /** The timed approvals still in force ("Allow for 1 hour"), and revoking one. */ permissions: "_rustcode/permissions", diff --git a/apps/desktop/src/state/connections.ts b/apps/desktop/src/state/connections.ts new file mode 100644 index 000000000..fa791df14 --- /dev/null +++ b/apps/desktop/src/state/connections.ts @@ -0,0 +1,125 @@ +import { arr, bool, type Json, obj, str } from "../acp/jsonrpc"; + +/** A GitHub CLI sign-in on this computer. */ +export interface GitHubAccount { + host: string; + login: string; + active: boolean; + valid: boolean; + scopes: string[]; +} + +/** A saved model account (`credentials.json`), signed in with `/login`. */ +export interface ModelAccount { + provider: string; + account: string; + display: string; + method: string; + active: boolean; + needsSignIn: boolean; +} + +/** The one-time code `gh auth login --web` printed, and where to enter it. */ +export interface DeviceCode { + code: string; + url: string; +} + +/** Settings › Connections: the engine's `_rustcode/connections` snapshot. */ +export interface Connections { + github?: { + cliInstalled: boolean; + installHint?: string; + accounts: GitHubAccount[]; + pending?: DeviceCode; + error?: string; + }; + accounts: ModelAccount[]; +} + +export function parseDeviceCode(v: Json): DeviceCode | undefined { + const o = obj(v); + const code = str(o?.code); + const url = str(o?.url); + return code && url ? { code, url } : undefined; +} + +export function parseConnections(v: Json): Connections { + const root = obj(v) ?? {}; + const gh = obj(root.github); + return { + github: gh + ? { + cliInstalled: bool(gh.cliInstalled) ?? false, + installHint: str(gh.installHint), + accounts: arr(gh.accounts).map((a) => { + const o = obj(a) ?? {}; + return { + host: str(o.host) ?? "", + login: str(o.login) ?? "", + active: bool(o.active) ?? false, + valid: bool(o.valid) ?? false, + scopes: arr(o.scopes).flatMap((s) => (typeof s === "string" ? [s] : [])), + }; + }), + pending: parseDeviceCode(gh.pending ?? null), + error: str(gh.error), + } + : undefined, + accounts: arr(root.accounts).map((a) => { + const o = obj(a) ?? {}; + return { + provider: str(o.provider) ?? "", + account: str(o.account) ?? "", + display: str(o.display) ?? "", + method: str(o.method) ?? "", + active: bool(o.active) ?? false, + needsSignIn: bool(o.needsSignIn) ?? false, + }; + }), + }; +} + +const PROVIDERS: Record = { + openai: { label: "OpenAI", mark: "codex" }, + anthropic: { label: "Anthropic", mark: "claude" }, + google: { label: "Google", mark: "gemini" }, + gemini: { label: "Google", mark: "gemini" }, + github_copilot: { label: "GitHub Copilot" }, + openrouter: { label: "OpenRouter" }, + deepseek: { label: "DeepSeek" }, + mistral: { label: "Mistral" }, + xai: { label: "xAI" }, +}; + +const METHODS: Record = { + api_key: "API key", + chat_gpt: "ChatGPT sign-in", + github_copilot: "Copilot sign-in", + claude_cli: "Claude Code sign-in", +}; + +/** A provider id as people write it: `openai` is OpenAI. An unknown id keeps its own spelling. */ +export function providerLabel(provider: string): string { + return PROVIDERS[provider]?.label ?? provider; +} + +/** The harness whose mark stands for a provider (OpenAI is Codex's knot), if one does. */ +export function providerMark(provider: string): string | undefined { + return PROVIDERS[provider]?.mark; +} + +/** How an account signed in, in words: `chat_gpt` is "ChatGPT sign-in". */ +export function methodLabel(method: string): string { + return METHODS[method] ?? method.replace(/_/g, " "); +} + +/** The model account's second line: provider and how it signed in. */ +export function accountDetail(account: ModelAccount): string { + return [providerLabel(account.provider), methodLabel(account.method)].filter(Boolean).join(" · "); +} + +/** A GitHub account's second line: host, and the scopes its token carries when it lists any. */ +export function githubDetail(account: GitHubAccount): string { + return account.scopes.length ? `${account.host} · ${account.scopes.join(", ")}` : account.host; +} diff --git a/apps/desktop/src/ui/Settings.tsx b/apps/desktop/src/ui/Settings.tsx index 9ac515735..686df19c3 100644 --- a/apps/desktop/src/ui/Settings.tsx +++ b/apps/desktop/src/ui/Settings.tsx @@ -16,8 +16,7 @@ import { VoiceGroup } from "./VoiceGroup"; // Diagnostics (DiagnosticsPage.tsx) asks the shell about the server itself. import { lazy, type ReactNode, Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { arr, bool, type Json, type JsonObject, obj, str } from "../acp/jsonrpc"; -import { Method } from "../acp/types"; +import { type Json, type JsonObject, obj } from "../acp/jsonrpc"; import { CHAT_WIDTH_LABEL, type ChatWidth } from "../lib/chatWidth"; import { CRASH_REPORTS_DEFAULT, @@ -91,6 +90,7 @@ import { HEADER_HEIGHT, SidebarCluster } from "./MainHeader"; import { RestartToApply } from "./RestartToApply"; import { AboutPage, AdvancedPage, STATUS_READ_MS } from "./SettingsAbout"; import { AppearancePage } from "./SettingsAppearance"; +import { ConnectionsPage } from "./SettingsConnections"; import { OrchestrationPage } from "./SettingsOrchestration"; import { useLightsInset } from "./Titlebar"; import { onTitleRowDoubleClick, windowControlsInset } from "./WindowControls"; @@ -134,9 +134,7 @@ import { SettingsHeaderProvider, type SettingsPageMeta, Slider, - useEngineData, useRowResets, - withCode, } from "./settingsKit"; const UsagePage = lazy(() => import("./UsagePage").then((m) => ({ default: m.UsagePage }))); @@ -763,125 +761,6 @@ function VoicePage() { ); } -interface Connections { - github?: { - cliInstalled: boolean; - installHint?: string; - accounts: { host: string; login: string; active: boolean; valid: boolean }[]; - error?: string; - }; - accounts: { provider: string; display: string; method: string; active: boolean; needsSignIn: boolean }[]; -} - -const parseConnections = (v: Json): Connections => { - const root = obj(v) ?? {}; - const gh = obj(root.github); - return { - github: gh - ? { - cliInstalled: bool(gh.cliInstalled) ?? false, - installHint: str(gh.installHint), - accounts: arr(gh.accounts).map((a) => { - const o = obj(a) ?? {}; - return { - host: str(o.host) ?? "", - login: str(o.login) ?? "", - active: bool(o.active) ?? false, - valid: bool(o.valid) ?? false, - }; - }), - error: str(gh.error), - } - : undefined, - accounts: arr(root.accounts).map((a) => { - const o = obj(a) ?? {}; - return { - provider: str(o.provider) ?? "", - display: str(o.display) ?? "", - method: str(o.method) ?? "", - active: bool(o.active) ?? false, - needsSignIn: bool(o.needsSignIn) ?? false, - }; - }), - }; -}; - -function ConnectionsPage() { - const { data, error } = useEngineData(Method.connections, parseConnections); - const { scope, machines } = useScope(); - const remote = - scope.mode === "machine" - ? machines.find((machine) => machine.host === scope.host && !machine.local) - : undefined; - if (remote) - return ( - <> - - - - - - ); - if (!data) - return ( - <> - - - - ); - return ( - <> - - - {!data.github?.cliInstalled ? ( - - ) : data.github.accounts.length ? ( - data.github.accounts.map((a) => ( - - {a.valid ? ( - {a.active ? "Signed in" : "Usable"} - ) : ( - - Token invalid - - )} - - )) - ) : ( - - )} - - - {data.accounts.length ? ( - data.accounts.map((a, i) => ( - - {a.needsSignIn ? ( - Sign in again - ) : a.active ? ( - Active - ) : ( - Idle - )} - - )) - ) : ( - - )} - - - ); -} - // ---------------------------------------------------------------- appearance // ---------------------------------------------------------------- the panel diff --git a/apps/desktop/src/ui/SettingsConnections.tsx b/apps/desktop/src/ui/SettingsConnections.tsx new file mode 100644 index 000000000..1c69446e3 --- /dev/null +++ b/apps/desktop/src/ui/SettingsConnections.tsx @@ -0,0 +1,404 @@ +import { useState } from "react"; +import { Method } from "../acp/types"; +import { openExternal } from "../lib/native"; +import { + accountDetail, + type Connections, + type DeviceCode, + type GitHubAccount, + githubDetail, + type ModelAccount, + parseConnections, + parseDeviceCode, + providerLabel, + providerMark, +} from "../state/connections"; +import { useScope } from "../state/settingsScope"; +import { askConfirm, errorText, request, toast } from "../state/store"; +import { HarnessIcon } from "./HarnessIcon"; +import { ExternalLink, Github, LogOut, RefreshCw } from "./icons"; +import { CopyButton } from "./Markdown"; +import { cx, Spinner, Tooltip } from "./primitives"; +import { SettingsScopeBar } from "./SettingsScope"; +import { Action, Chip, Group, Literal, Loading, Row, useEngineData, withCode } from "./settingsKit"; + +/** How long the page waits for someone to approve the GitHub code before it gives up. */ +const GITHUB_WAIT_MS = 15 * 60_000; + +type GitHubSignIn = + | { phase: "idle" } + | { phase: "starting" } + | { phase: "code"; code: DeviceCode } + | { phase: "failed"; message: string }; + +/** + * Settings › Connections: the GitHub CLI's sign-ins and the saved model accounts on this + * computer. GitHub signs in here with the device code `gh auth login --web` prints; model + * accounts sign in with `/login` in a thread and sign out or refresh their models here. + */ +export function ConnectionsPage() { + const { data, error, setData } = useEngineData(Method.connections, parseConnections); + const { scope, machines } = useScope(); + const remote = + scope.mode === "machine" + ? machines.find((machine) => machine.host === scope.host && !machine.local) + : undefined; + if (remote) + return ( + <> + + + + + + ); + if (!data) + return ( + <> + + + + ); + return ( + <> + + + + + ); +} + +function Avatar({ children, dim }: { children: React.ReactNode; dim?: boolean }) { + return ( + + {children} + + ); +} + +function AccountTitle({ avatar, name }: { avatar: React.ReactNode; name: string }) { + return ( + + {avatar} + {name} + + ); +} + +function GitHubGroup({ data, onChange }: { data: Connections; onChange: (next: Connections) => void }) { + const github = data.github; + const [signIn, setSignIn] = useState(() => + github?.pending ? { phase: "code", code: github.pending } : { phase: "idle" }, + ); + const [signingOut, setSigningOut] = useState(null); + const busy = signIn.phase === "starting" || signIn.phase === "code"; + + const start = async () => { + setSignIn({ phase: "starting" }); + try { + const code = parseDeviceCode(await request(Method.githubLogin, {}, 30_000)); + if (!code) throw new Error("GitHub did not give a sign-in code."); + setSignIn({ phase: "code", code }); + const next = parseConnections(await request(Method.githubWait, {}, GITHUB_WAIT_MS)); + onChange(next); + setSignIn({ phase: "idle" }); + const login = next.github?.accounts.find((a) => a.active)?.login; + toast(login ? `Signed in to GitHub as ${login}` : "Signed in to GitHub", "success"); + } catch (e) { + setSignIn((now) => (now.phase === "idle" ? now : { phase: "failed", message: errorText(e) })); + } + }; + const cancel = () => { + setSignIn({ phase: "idle" }); + void request(Method.githubCancel, {}).catch(() => undefined); + }; + const signOut = (account: GitHubAccount) => + askConfirm({ + title: `Sign ${account.login} out of GitHub?`, + message: + "The GitHub CLI forgets this account on this computer. Pull requests stop working until you sign in again.", + action: "Sign out", + destructive: true, + run: () => { + const key = `${account.host}/${account.login}`; + setSigningOut(key); + void request(Method.githubLogout, { host: account.host, login: account.login }, 30_000) + .then((v) => { + onChange(parseConnections(v)); + toast(`Signed ${account.login} out of GitHub`, "success"); + }) + .catch((e) => toast(`Could not sign out: ${errorText(e)}`, "error")) + .finally(() => setSigningOut(null)); + }, + }); + + const accounts = github?.accounts ?? []; + return ( + 0 && !busy ? ( + void start()}> + Add account + + ) : undefined + } + > + {!github?.cliInstalled ? ( + + + + } + name="GitHub CLI not installed" + /> + } + subtitle="Install it, then come back here to sign in." + status={ + github?.installHint ? ( + + {github.installHint} + + + ) : undefined + } + > + openExternal("https://cli.github.com")}> + + cli.github.com + + + ) : ( + <> + {accounts.map((a) => { + const key = `${a.host}/${a.login}`; + return ( + + + + } + name={a.login} + /> + } + subtitle={{githubDetail(a)}} + badge={ + a.valid ? ( + {a.active ? "Signed in" : "Usable"} + ) : ( + Token invalid + ) + } + > + {!a.valid && ( + void start()}> + Sign in again + + )} + + signOut(a)} + > + {signingOut === key ? : } + + + + ); + })} + {accounts.length === 0 && signIn.phase !== "code" && ( + + + + } + name="Not signed in" + /> + } + subtitle={Sign in so threads can open and merge pull requests.} + > + void start()}> + {signIn.phase === "starting" ? : } + Sign in with GitHub + + + )} + {signIn.phase === "code" && } + {signIn.phase === "failed" && ( + + void start()}> + Try again + + + )} + + )} + + ); +} + +/** The one-time code, large enough to read across, with the two things to do with it. */ +function DeviceCodePanel({ code, onCancel }: { code: DeviceCode; onCancel: () => void }) { + return ( +
+
Enter this code on GitHub to finish signing in.
+
+ + {code.code} + + +
+
+ { + void navigator.clipboard?.writeText(code.code).catch(() => undefined); + openExternal(code.url); + }} + > + + Copy code and open GitHub + + + Cancel + + + + Waiting for GitHub… + +
+
+ ); +} + +function ModelAccountsGroup({ + accounts, + onChange, +}: { + accounts: ModelAccount[]; + onChange: (next: Connections) => void; +}) { + const [working, setWorking] = useState(null); + const keyOf = (a: ModelAccount) => `${a.provider}/${a.account}`; + const run = async (a: ModelAccount, method: string, done: string) => { + setWorking(keyOf(a)); + try { + onChange(parseConnections(await request(method, { provider: a.provider, account: a.account }, 60_000))); + toast(done, "success"); + } catch (e) { + toast(errorText(e), "error"); + } finally { + setWorking(null); + } + }; + const signOut = (a: ModelAccount) => + askConfirm({ + title: `Sign ${a.display || providerLabel(a.provider)} out?`, + message: "Threads on this account stop until it signs in again with /login.", + action: "Sign out", + destructive: true, + run: () => void run(a, Method.accountLogout, `Signed ${a.display || providerLabel(a.provider)} out`), + }); + return ( + + {accounts.length === 0 && ( + + + + } + name="No model accounts yet" + /> + } + subtitle={{withCode("Type `/login` in a thread to add one.")}} + /> + )} + {accounts.map((a) => { + const mark = providerMark(a.provider); + const key = keyOf(a); + return ( + + {mark ? ( + + ) : a.provider === "github_copilot" ? ( + + ) : ( + + {providerLabel(a.provider).slice(0, 2)} + + )} + + } + name={a.display || providerLabel(a.provider)} + /> + } + subtitle={{accountDetail(a)}} + badge={ + a.needsSignIn ? ( + Sign in again + ) : a.active ? ( + Active + ) : ( + Idle + ) + } + > + + void run(a, Method.accountRefresh, "Models refreshed")} + > + {working === key ? : } + + + + signOut(a)} + > + + + + + ); + })} + + ); +} diff --git a/apps/desktop/src/ui/icons.tsx b/apps/desktop/src/ui/icons.tsx index 88d06a00a..f9374f223 100644 --- a/apps/desktop/src/ui/icons.tsx +++ b/apps/desktop/src/ui/icons.tsx @@ -68,6 +68,7 @@ import { GitCommitHorizontalIcon, GitCompareIcon, GitForkIcon, + GithubIcon, GitMergeIcon, GitPullRequestClosedIcon, GitPullRequestDraftIcon, @@ -91,6 +92,7 @@ import { LinkSquare02Icon, ListViewIcon, Loading03Icon, + Logout01Icon, Maximize01Icon, Message01Icon, Message02Icon, @@ -321,6 +323,8 @@ export const GitCompareArrows = (props: IconProps) => ( ); export const GitFork = (props: IconProps) => ; export const GitMerge = (props: IconProps) => ; +export const Github = (props: IconProps) => ; +export const LogOut = (props: IconProps) => ; export const GitPullRequest = (props: IconProps) => ( ); diff --git a/docs/desktop.md b/docs/desktop.md index 00414574d..9a965867d 100644 --- a/docs/desktop.md +++ b/docs/desktop.md @@ -2200,7 +2200,8 @@ From the SwiftUI app, still missing or partial: are not offered. - The vibrancy was not checked by eye in a native window yet (the display was off during the change); the CSS and config were. -- GitHub sign-in flow, model account switching (Connections is read-only). +- Model account switching (Connections signs GitHub in and out, and model + accounts out, but adding one is still `/login` in a thread). - An E2E driver for the native window; Developer ID signing and notarization run only once the secrets exist (#2034). The Smart UI `rcui://` path was checked by unit test and the page itself in