feat: choose the GitHub account per host, save a GitHub token, and fewer reads per PR action #16322
Mergedjuliusmarmingemerged 9 commits into
t3code/github-api-source-control fromrefs/pull/16322/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
juliusmarminge added labelsmacroscope-review
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
juliusmarminge changed the title
- @@ -62,4 +76,19 @@76+ ...(entry.environmentVariable === null77+ ? {}78+ : { environmentVariable: entry.environmentVariable }),79+ }));80+}81+82+/**83+ * Reads `gh auth status --json hosts`. The headline account is the one GitHub requests will84+ * use: Settings can pin a login per host or turn a host off, and an environment token beats both.85+ */86+export function parseGitHubAuth(87+ input: SourceControlAuthProbeInput,88+ settings: GitHubSettings = DEFAULT_SERVER_SETTINGS.github,89+) {6290 const output = combinedAuthOutput(input);6391 const authStatus = parseGitHubAuthStatus(input.stdout);64- const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);65- const host = authenticatedAccount?.host;92+ const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];93+ const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);94+ // Lead with the host gh would pick, unless Settings turned it off.@@ -143,5 +174,15 @@143174 });144175145176 return GitHubCredentials.of({146- get: (host) => Cache.get(cache, normalizeHost(host)),147- invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),177+ get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {178+ const host = normalizeHost(rawHost);179+ const choice = yield* hostChoice(host);180+ if (choice?.enabled === false) {181+ return yield* new GitHubCredentialUnavailableError({ host, reason: "disabled" });182+ }183+ return yield* Cache.get(cache, cacheKey(host, choice?.account));184+ }),185+ invalidate: (rawHost) => {186+ const host = normalizeHost(rawHost);187+ return hostChoice(host).pipe(188+ Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),apps/server/src/pullRequest/GitHubPullRequestProvider.ts line 517OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -527,20 +517 @@527- pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null528- ? Effect.succeed(false)529- : cli530- .getPullRequestBaseComparison({531- ...input,532- headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,533- allowReserve: true,534- })535- .pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),536- ),537- Effect.orElseSucceed(() => false),538- ),539- ],540- { concurrency: 2 },541- ).pipe(542- Effect.mapError(fail("getViewerPermissions")),543- Effect.map(([access, canUpdateBranch]) =>544- gitHubViewerPermissions({ ...access, canUpdateBranch }),545- ),546- ),517+ (input.includeUpdateBranch === false@@ -62,4 +81,19 @@81+82+/**83+ * Reads `gh auth status --json hosts`. The headline account is the one GitHub requests will84+ * use: Settings can pin a login per host or turn a host off, and an environment token beats both.85+ */86+export function parseGitHubAuth(87+ input: SourceControlAuthProbeInput,88+ settings: GitHubSettings = DEFAULT_SERVER_SETTINGS.github,89+) {6290 const output = combinedAuthOutput(input);6391 const authStatus = parseGitHubAuthStatus(input.stdout);64- const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);65- const host = authenticatedAccount?.host;92+ const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];93+ const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);94+ // Lead with the host gh would pick, unless Settings turned it off.95+ const orderedHosts = fallback96+ ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]97+ : hosts;98+ const chosen = orderedHosts99+ .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))@@ -751,3 +751,5 @@751751 environmentOnly: true,752752 scope: "project-defaults",753753 },754+ {755+ id: "github-accounts",
- @@ -543,4 +517,17 @@543- Effect.map(([access, canUpdateBranch]) =>544- gitHubViewerPermissions({ ...access, canUpdateBranch }),545- ),546- ),517+ (input.includeUpdateBranch === false518+ ? cli519+ .getViewerAccess({ ...input, allowReserve: true })520+ .pipe(Effect.map((access) => gitHubViewerPermissions(access)))521+ : // The core detail already carries the viewer's access, the merge settings, and the base522+ // comparison, so one read answers what used to take three.523+ cli.getPullRequestDetail(input).pipe(524+ Effect.provideService(GitHubCli.AllowGitHubReserve, true),525+ Effect.map((pullRequest) =>526+ gitHubViewerPermissions({527+ ...pullRequest.viewerAccess,528+ canUpdateBranch:529+ pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,530+ }),531+ ),532+ )533+ ).pipe(Effect.mapError(fail("getViewerPermissions"))),@@ -120,6 +137,19 @@120137 ),121138 );122139123- const lookup = Effect.fn("GitHubCredentials.lookup")(function* (host: string) {140+ /** The Settings choice for a host; unreadable settings fall back to gh's own choice. */141+ const hostChoice = (host: string) =>142+ serverSettings.getSettings.pipe(143+ Effect.map((settings) => settings.github.hosts[host]),144+ Effect.orElseSucceed(() => undefined),145+ );146+147+ /** Cache key: the host plus its pinned account, so a changed pin misses the cache. */148+ const cacheKey = (host: string, account: string | undefined) =>149+ account === undefined ? host : `${host}\u0000${account}`;150+151+ const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {152+ const [host = key, choice] = key.split("\u0000");153+ // An environment token wins over a pinned account, exactly as it does in gh.124154 const fromEnv = environmentToken(host, globalThis.process.env);125- const token = fromEnv ?? (yield* fromGh(host));155+ const token = fromEnv ?? (yield* fromGh(host, choice));@@ -155,15 +223,17 @@155223 ...cli,156224 status: "available" as const,157- auth:158- login !== undefined225+ auth: {226+ ...(login !== undefined159227 ? providerAuth({160228 status: "authenticated",161229 account: login,162230 host: "github.com",163- detail: `Using the token in ${variable} from the server environment.`,231+ detail: `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,164232 })165233 : providerAuth({166234 status: "unauthenticated",167235 host: "github.com",168236 detail: `GitHub refused the token in ${variable}. Replace it, or unset it to use \`gh auth login\`.`,169- }),237+ })),238+ ...accounts,239+ },
- @@ -225,3 +225,4 @@225225 case "GitHubCliMissingError":226226 return new GitHubCliUnavailableError(context);227227 case "GitHubNotSignedInError":228+ case "GitHubHostDisabledError":
- @@ -0,0 +48,21 @@48+ readonly environmentId: EnvironmentId;49+ readonly auth: SourceControlProviderAuth;50+ readonly onSaved: () => void;51+}) {52+ const hosts = useEnvironmentSettings(environmentId, (settings) => settings.github.hosts);53+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {54+ label: "save GitHub account settings",55+ });56+ const [saving, setSaving] = useState(false);57+ const [revealed, setRevealed] = useState(false);58+ const groups = groupGitHubAccounts(auth.accounts ?? []);59+60+ const save = async (61+ host: string,62+ change: { readonly enabled?: boolean; readonly account?: string | null },63+ ) => {64+ setSaving(true);65+ try {66+ const result = await updateSettings({67+ environmentId,68+ input: { patch: { github: { hosts: nextGitHubHosts(hosts, host, change) } } },
juliusmarminge changed the title
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -141,8 +198,20 @@141198 const environment = yield* HostProcessEnvironment;199+ const serverSettings = yield* ServerSettings.ServerSettingsService;200+142201 return {143202 type: "managed-cli",144203 kind: discovery.kind,145204 label: discovery.label,146205 installHint: discovery.installHint,147206 probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {148- const cli = yield* probeSourceControlProvider({ cwd, process, spec: discovery });207+ const settings = yield* serverSettings.getSettings.pipe(208+ Effect.map((current) => current.github),209+ Effect.orElseSucceed(() => DEFAULT_SERVER_SETTINGS.github),210+ );211+ const cli = yield* probeSourceControlProvider({212+ cwd,213+ process,214+ spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },215+ });216+ // A token saved in Settings wins over the environment, which wins over gh.217+ const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";@@ -181,5 +235,6 @@181235 });182236183237 return GitHubCredentials.of({184- get: (host) => Cache.get(cache, normalizeHost(host)),185- invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),238+ get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {239+ const host = normalizeHost(rawHost);240+ const choice = yield* hostChoice(host);
juliusmarminge merged this9ac8f33
juliusmarminge closed this
Sign in to join this conversation.



Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
b24b803· Source CI: successScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.