TypeScript
feat: choose the GitHub account per host, save a GitHub token, and fewer reads per PR action (#16322)
Julius Marminge9ac8f33f1685
diff --git a/apps/server/scripts/evaluate-thread-titles.ts b/apps/server/scripts/evaluate-thread-titles.tsindex 4e0691fe3a0..414bd99d074 100644--- a/apps/server/scripts/evaluate-thread-titles.ts+++ b/apps/server/scripts/evaluate-thread-titles.ts@@ -157,9 +157,11 @@ await Effect.runPromise(ForgejoCli.layer,AzureDevOpsCli.layer,// No saved credentials here; Bitbucket falls back to T3CODE_BITBUCKET_* variables.- BitbucketApi.layer.pipe(Layer.provide(ServerSettings.layerTest())),+ BitbucketApi.layer,),),+ // Default settings: no saved Bitbucket token, gh's own GitHub account choice.+ Layer.provide(ServerSettings.layerTest()),Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))),Layer.provide(GitVcsDriver.layer),Layer.provide(VcsProcess.layer),diff --git a/apps/server/scripts/measure-pr-preview.ts b/apps/server/scripts/measure-pr-preview.tsindex ae291cd17cc..98fc82b5398 100644--- a/apps/server/scripts/measure-pr-preview.ts+++ b/apps/server/scripts/measure-pr-preview.ts@@ -14,6 +14,7 @@ import * as GitHubPullRequestCli from "../src/pullRequest/GitHubPullRequestCli.timport * as GitHubPullRequestProvider from "../src/pullRequest/GitHubPullRequestProvider.ts";import * as GitHubApi from "../src/sourceControl/GitHubApi.ts";import * as GitHubCredentials from "../src/sourceControl/GitHubCredentials.ts";+import * as ServerSettings from "../src/serverSettings.ts";import * as GitHubGraphQlBudget from "../src/sourceControl/githubGraphQlBudget.ts";import * as SourceControlRateLimit from "../src/sourceControl/SourceControlRateLimit.ts";import * as VcsProcess from "../src/vcs/VcsProcess.ts";@@ -64,7 +65,7 @@ const measuredApi = Layer.effect(});}),).pipe(- Layer.provide(GitHubCredentials.layer),+ Layer.provide(GitHubCredentials.layer.pipe(Layer.provide(ServerSettings.layerTest()))),Layer.provide(GitHubGraphQlBudget.layer),Layer.provide(SourceControlRateLimit.layer),Layer.provide(FetchHttpClient.layer),diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.tsindex 42fdc87afe5..8f743c65fa3 100644--- a/apps/server/src/git/GitManager.test.ts+++ b/apps/server/src/git/GitManager.test.ts@@ -4553,7 +4553,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {Effect.flip,Effect.map((error) => error.message),);- expect(errorMessage).toContain("GitHub CLI (`gh`) is required");+ expect(errorMessage).toContain("No GitHub credential on the server");}),);diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.test.tsindex 33f0df8e8bc..d9579f317d9 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.test.ts@@ -18,7 +18,6 @@ import * as GitHubGraphQlBudget from "../sourceControl/githubGraphQlBudget.ts";import * as SourceControlRateLimit from "../sourceControl/SourceControlRateLimit.ts";import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";import { KnownWorkflowRuns } from "./gitHubConditionalChecks.ts";-import { BASE_COMPARISON_GRAPHQL_QUERY } from "./gitHubPullRequestJson.ts";const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));@@ -4041,45 +4040,6 @@ layer("GitHubPullRequestCli.layer", (it) => {}),);- it.effect("sends the base comparison's head as a variable, not inside the document", () =>- Effect.gen(function* () {- mockedExecute.mockReturnValue(- Effect.succeed(- output(- encodeJson({- data: {- repository: {- pullRequest: {- viewerCanUpdateBranch: true,- baseRef: { compare: { behindBy: 4 } },- },- },- },- }),- ),- ),- );- const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;-- const comparison = yield* cli.getPullRequestBaseComparison({- cwd: "/w",- repository: "acme/web",- host: "github.com",- number: 7,- headRef: "fork:feat/page",- });-- expect(varsAt(0)).toEqual({- owner: "acme",- name: "web",- number: 7,- headRef: "fork:feat/page",- });- expect(comparison).toEqual({ behindBy: 4, viewerCanUpdate: true });- expect(queryAt(0)).toContain(BASE_COMPARISON_GRAPHQL_QUERY.slice(0, -2));- }),- );-it.effect("stops GraphQL reads at the protected reserve until reset", () =>Effect.gen(function* () {mockedExecute.mockReturnValue(@@ -4088,10 +4048,11 @@ layer("GitHubPullRequestCli.layer", (it) => {encodeJson({data: {repository: {- pullRequest: {- viewerCanUpdateBranch: true,- baseRef: { compare: { behindBy: 4 } },- },+ mergeCommitAllowed: true,+ squashMergeAllowed: false,+ rebaseMergeAllowed: true,+ viewerPermission: "READ",+ pullRequest: { viewerCanUpdate: true, viewerDidAuthor: true },},rateLimit: {cost: 1,@@ -4110,13 +4071,12 @@ layer("GitHubPullRequestCli.layer", (it) => {repository: "acme/web",host: "github.com",number: 7,- headRef: "fork:feat/page",} as const;- yield* cli.getPullRequestBaseComparison(input);+ yield* cli.getViewerAccess(input);expect(queryAt(0)).toContain("rateLimit { cost limit remaining resetAt }");- const error = yield* Effect.flip(cli.getPullRequestBaseComparison(input));+ const error = yield* Effect.flip(cli.getViewerAccess(input));assert.strictEqual(error._tag, "SourceControlRateLimitPausedError");if (error._tag !== "SourceControlRateLimitPausedError") return;@@ -4136,10 +4096,11 @@ layer("GitHubPullRequestCli.layer", (it) => {encodeJson({data: {repository: {- pullRequest: {- viewerCanUpdateBranch: true,- baseRef: { compare: { behindBy: 4 } },- },+ mergeCommitAllowed: true,+ squashMergeAllowed: false,+ rebaseMergeAllowed: true,+ viewerPermission: "READ",+ pullRequest: { viewerCanUpdate: true, viewerDidAuthor: true },},rateLimit: {cost: 1,@@ -4171,12 +4132,11 @@ layer("GitHubPullRequestCli.layer", (it) => {);const cli = yield* GitHubPullRequestCli.GitHubPullRequestCli;- yield* cli.getPullRequestBaseComparison({+ yield* cli.getViewerAccess({cwd: "/w",repository: "acme/web",host: "github.com",number: 7,- headRef: "fork:feat/page",});const access = yield* cli.getViewerAccess({cwd: "/w",diff --git a/apps/server/src/pullRequest/GitHubPullRequestCli.ts b/apps/server/src/pullRequest/GitHubPullRequestCli.tsindex d393db9fa78..9e98286dc82 100644--- a/apps/server/src/pullRequest/GitHubPullRequestCli.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestCli.ts@@ -94,8 +94,6 @@ import {decodePullRequestStackMembershipsJson,pullRequestSearchGraphQlQuery,PULL_REQUEST_SEARCH_MAX_ROWS,- BASE_COMPARISON_GRAPHQL_QUERY,- decodeBaseComparisonJson,PULL_REQUEST_FILES_VIEWED_GRAPHQL_QUERY,PULL_REQUEST_NODE_ID_GRAPHQL_QUERY,REACTION_SUBJECT_PULL_REQUEST_GRAPHQL_QUERY,@@ -115,7 +113,6 @@ import {UPDATE_REVIEW_COMMENT_GRAPHQL_MUTATION,VIEWER_PERMISSIONS_GRAPHQL_QUERY,decodeViewerPermissionsJson,- type GitHubBaseComparison,type GitHubPullRequestActivity,type GitHubPullRequestActivityPage,type GitHubWorkflowRunPage,@@ -146,7 +143,7 @@ export class GitHubPullRequestReadError extends Schema.TaggedError<GitHubPullReq},) {override get message(): string {- return `GitHub CLI returned an unreadable ${this.operation} response.`;+ return `GitHub returned an unreadable ${this.operation} response.`;}}@@ -159,7 +156,7 @@ export class GitHubViewerLoginUnavailableError extends Schema.TaggedError<GitHub},) {override get message(): string {- return "GitHub CLI returned no login for the authenticated account.";+ return "GitHub returned no login for the authenticated account.";}}@@ -588,22 +585,6 @@ export class GitHubPullRequestCli extends Context.Service<readonly number: number;}) => Effect.Effect<GitHubPullRequestStack | null, GitHubPullRequestCliError>;- /**- * How far the branch trails its base, and whether this viewer may update it. Its own read- * because the comparison needs the head ref the detail answers with — a fork's branch is not- * addressable in the base repository by name alone.- */- readonly getPullRequestBaseComparison: (input: {- readonly cwd: string;- readonly repository: string;- readonly host: string;- readonly number: number;- /** Qualified `owner:branch`, which is the only form a fork's head resolves under. */- readonly headRef: string;- /** Manual action checks may use the quota held back from automatic reads. */- readonly allowReserve?: boolean | undefined;- }) => Effect.Effect<GitHubBaseComparison, GitHubPullRequestCliError>;-readonly getPullRequestActivity: (input: {readonly cwd: string;readonly repository: string;@@ -2170,19 +2151,6 @@ export const make = Effect.gen(function* () {);},- getPullRequestBaseComparison: (input) => {- const { owner, name } = parseRepositorySelector(input.repository);- return graphqlRead({- cwd: input.cwd,- host: input.host,- operation: "getPullRequestBaseComparison",- ...(input.allowReserve === true ? { allowReserve: true } : {}),- variables: { owner, name, number: input.number, headRef: input.headRef },- query: BASE_COMPARISON_GRAPHQL_QUERY,- decode: decodeBaseComparisonJson,- });- },-getPullRequestActivity: (input) =>Effect.gen(function* () {const { owner, name } = parseRepositorySelector(input.repository);diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.tsindex 6905b382688..88079ebb94c 100644--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.test.ts@@ -7,7 +7,9 @@ import type { PullRequestReaction } from "@t3tools/contracts";import { decodePullRequestDetailJson } from "./gitHubPullRequestJson.ts";import * as GitHubApi from "../sourceControl/GitHubApi.ts";+import * as GitHubCli from "../sourceControl/GitHubCli.ts";import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";+import type { GitHubPullRequestCore } from "./gitHubPullRequestJson.ts";import { gitHubViewerPermissions, loginAvatarUrl, make } from "./GitHubPullRequestProvider.ts";import type { GitHubReviewThreadComments } from "./gitHubPullRequestJson.ts";@@ -486,8 +488,6 @@ describe("gitHubViewerPermissions", () => {url: "https://github.com/acme/web/actions/runs/123",},]),- getPullRequestBaseComparison: () =>- Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),getViewerAccess: () =>Effect.succeed({canWrite: true,@@ -585,7 +585,6 @@ it.effect("does not classify same-repository gates as fork workflow approvals",Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({revalidateChecks: (_input, read) => read,getPullRequestDetail: () => Effect.succeed({ ...openDetail, isCrossRepository: false }),- getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),listWorkflowRunsRequiringApproval: () =>Effect.die("same-repository pull requests must not probe fork workflow approvals"),getViewerAccess: () =>@@ -625,7 +624,6 @@ it.effect("keeps an unsafe workflow approval scope visible as unknown", () =>Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({revalidateChecks: (_input, read) => read,getPullRequestDetail: () => Effect.succeed(openDetail),- getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),listWorkflowRunsRequiringApproval: () =>Effect.fail(new GitHubPullRequestCli.GitHubWorkflowApprovalRefusedError({@@ -669,7 +667,6 @@ it.effect("propagates workflow discovery rate limits", () =>Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({revalidateChecks: (_input, read) => read,getPullRequestDetail: () => Effect.succeed(openDetail),- getPullRequestBaseComparison: () => Effect.succeed({ behindBy: 0, viewerCanUpdate: true }),listWorkflowRunsRequiringApproval: () =>Effect.fail(new GitHubApi.GitHubApiRateLimitError({@@ -691,6 +688,14 @@ it.effect("propagates workflow discovery rate limits", () =>);describe("getViewerPermissions", () => {+ const access = {+ canWrite: true,+ canTriage: true,+ canUpdate: true,+ didAuthor: false,+ mergeCapabilities: { merge: true, squash: true, rebase: true },+ };+it.effect("checks fresh access without reading branch details for unrelated operations", () => {let accessReads = 0;return Effect.gen(function* () {@@ -711,44 +716,27 @@ describe("getViewerPermissions", () => {Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({revalidateChecks: (_input, read) => read,getPullRequestDetail: () => Effect.die("Unexpected detail read"),- getPullRequestBaseComparison: () => Effect.die("Unexpected comparison read"),- getViewerAccess: () =>- Effect.sync(() => {- accessReads++;- return {- canWrite: true,- canTriage: true,- canUpdate: true,- didAuthor: false,- mergeCapabilities: { merge: true, squash: true, rebase: true },- };- }),+ getViewerAccess: () => Effect.sync(() => (accessReads++, access)),}),),);});- const layerWithComparison = (- comparison: Effect.Effect<{- readonly behindBy: number | null;- readonly viewerCanUpdate: boolean;- }>,+ const layerWithDetail = (+ detail: Effect.Effect<GitHubPullRequestCore, GitHubPullRequestCli.GitHubPullRequestCliError>,+ onDetail: (allowReserve: boolean) => void = () => {},) =>Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({revalidateChecks: (_input, read) => read,- getPullRequestDetail: () => Effect.succeed(openDetail),- getPullRequestBaseComparison: () => comparison,- getViewerAccess: () =>- Effect.succeed({- canWrite: true,- canTriage: true,- canUpdate: true,- didAuthor: false,- mergeCapabilities: { merge: true, squash: true, rebase: true },- }),+ getPullRequestDetail: () =>+ GitHubCli.AllowGitHubReserve.pipe(+ Effect.tap((allowReserve) => Effect.sync(() => onDetail(allowReserve))),+ Effect.flatMap(() => detail),+ ),+ getViewerAccess: () => Effect.die("Unexpected access read"),});- it.effect("offers update-branch when the comparison grants it", () =>+ it.effect("answers access and update-branch from the one detail read", () =>Effect.gen(function* () {const provider = yield* make;const permissions = yield* provider.getViewerPermissions({@@ -758,16 +746,20 @@ describe("getViewerPermissions", () => {number: 7,});+ expect(permissions.actions).toContain("merge");expect(permissions.actions).toContain("update-branch");expect(permissions.updateMethods).toEqual(["merge", "rebase"]);}).pipe(- Effect.provide(layerWithComparison(Effect.succeed({ behindBy: 3, viewerCanUpdate: true }))),+ Effect.provide(+ layerWithDetail(+ Effect.succeed({ ...openDetail, comparison: { behindBy: 3, viewerCanUpdate: true } }),+ ),+ ),),);it.effect("uses the GraphQL reserve for manual permission checks", () => {- let viewerAllowReserve: boolean | undefined;- let comparisonAllowReserve: boolean | undefined;+ let allowed: boolean | undefined;return Effect.gen(function* () {const provider = yield* make;yield* provider.getViewerPermissions({@@ -776,36 +768,15 @@ describe("getViewerPermissions", () => {host: "github.com",number: 7,});-- expect(viewerAllowReserve).toBe(true);- expect(comparisonAllowReserve).toBe(true);+ expect(allowed).toBe(true);}).pipe(Effect.provide(- Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({- revalidateChecks: (_input, read) => read,- getPullRequestDetail: () => Effect.succeed(openDetail),- getPullRequestBaseComparison: (input) =>- Effect.sync(() => {- comparisonAllowReserve = input.allowReserve;- return { behindBy: 3, viewerCanUpdate: true };- }),- getViewerAccess: (input) =>- Effect.sync(() => {- viewerAllowReserve = input.allowReserve;- return {- canWrite: true,- canTriage: true,- canUpdate: true,- didAuthor: false,- mergeCapabilities: { merge: true, squash: true, rebase: true },- };- }),- }),+ layerWithDetail(Effect.succeed(openDetail), (allowReserve) => (allowed = allowReserve)),),);});- it.effect("withholds update-branch when the comparison cannot be read", () =>+ it.effect("still answers from the light access read when the detail read fails", () =>Effect.gen(function* () {const provider = yield* make;const permissions = yield* provider.getViewerPermissions({@@ -814,37 +785,42 @@ describe("getViewerPermissions", () => {host: "github.com",number: 7,});-- expect(permissions.actions).not.toContain("update-branch");- expect(permissions.updateMethods).toBeUndefined();- // The rest of the answer survives a comparison nobody could make.expect(permissions.actions).toContain("merge");+ expect(permissions.actions).not.toContain("update-branch");}).pipe(Effect.provide(Layer.mock(GitHubPullRequestCli.GitHubPullRequestCli)({revalidateChecks: (_input, read) => read,- getPullRequestDetail: () => Effect.succeed(openDetail),- getPullRequestBaseComparison: () =>+ getPullRequestDetail: () =>Effect.fail(new GitHubPullRequestCli.GitHubPullRequestReadError({command: "gh",cwd: "/w",- operation: "getPullRequestBaseComparison",- cause: new Error("unreadable"),+ operation: "getPullRequestDetail",+ cause: new Error("head changed"),}),),- getViewerAccess: () =>- Effect.succeed({- canWrite: true,- canTriage: true,- canUpdate: true,- didAuthor: false,- mergeCapabilities: { merge: true, squash: true, rebase: true },- }),+ getViewerAccess: () => Effect.succeed(access),}),),),);++ it.effect("withholds update-branch where GitHub could not compare the branch", () =>+ Effect.gen(function* () {+ const provider = yield* make;+ const permissions = yield* provider.getViewerPermissions({+ cwd: "/w",+ repository: "acme/web",+ host: "github.com",+ number: 7,+ });++ expect(permissions.actions).not.toContain("update-branch");+ expect(permissions.updateMethods).toBeUndefined();+ expect(permissions.actions).toContain("merge");+ }).pipe(Effect.provide(layerWithDetail(Effect.succeed({ ...openDetail, comparison: null })))),+ );});describe("getChangeRequest commits", () => {diff --git a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts b/apps/server/src/pullRequest/GitHubPullRequestProvider.tsindex 940b04715c8..74c5852a48a 100644--- a/apps/server/src/pullRequest/GitHubPullRequestProvider.ts+++ b/apps/server/src/pullRequest/GitHubPullRequestProvider.ts@@ -7,6 +7,7 @@ import type {PullRequestViewerPermissions,} from "@t3tools/contracts";+import * as GitHubCli from "../sourceControl/GitHubCli.ts";import * as GitHubPullRequestCli from "./GitHubPullRequestCli.ts";import {PullRequestProviderError,@@ -109,6 +110,7 @@ export function gitHubProviderFailure(case "GitHubCliMissingError":return { reason: "missing-tool" };case "GitHubNotSignedInError":+ case "GitHubHostDisabledError":case "GitHubApiAuthenticationError":return { reason: "unauthenticated" };case "GitHubApiRateLimitError":@@ -513,38 +515,34 @@ export const make = Effect.gen(function* () {getReviewThreadComments: (input) =>cli.getReviewThreadComments(input).pipe(Effect.mapError(fail("getReviewThreadComments"))),- getViewerPermissions: (input) =>- Effect.all(- [- cli.getViewerAccess({ ...input, allowReserve: true }),- // Whether this viewer may update the branch is only on the comparison, and the- // comparison only resolves through the head ref the detail carries. A failure here- // withholds that one action rather than the whole answer, the way the detail path- // leaves the banner unknown.- input.includeUpdateBranch === false- ? Effect.succeed(false)- : cli.getPullRequestDetail(input).pipe(- Effect.flatMap((pullRequest) =>- pullRequest.state !== "open" || pullRequest.headRepositoryOwner === null- ? Effect.succeed(false)- : cli- .getPullRequestBaseComparison({- ...input,- headRef: `${pullRequest.headRepositoryOwner}:${pullRequest.headBranch}`,- allowReserve: true,- })- .pipe(Effect.map((comparison) => comparison.viewerCanUpdate === true)),- ),- Effect.orElseSucceed(() => false),- ),- ],- { concurrency: 2 },- ).pipe(- Effect.mapError(fail("getViewerPermissions")),- Effect.map(([access, canUpdateBranch]) =>- gitHubViewerPermissions({ ...access, canUpdateBranch }),+ getViewerPermissions: (input) => {+ const lightAccess = cli+ .getViewerAccess({ ...input, allowReserve: true })+ .pipe(Effect.map((access) => gitHubViewerPermissions(access)));+ if (input.includeUpdateBranch === false) {+ return lightAccess.pipe(Effect.mapError(fail("getViewerPermissions")));+ }+ // The core detail already carries the viewer's access, the merge settings, and the base+ // comparison, so one read usually answers what used to take three. When that heavier read+ // fails, the light access read still answers, withholding only update-branch.+ return cli.getPullRequestDetail(input).pipe(+ Effect.provideService(GitHubCli.AllowGitHubReserve, true),+ Effect.map((pullRequest) =>+ gitHubViewerPermissions({+ ...pullRequest.viewerAccess,+ canUpdateBranch:+ pullRequest.state === "open" && pullRequest.comparison?.viewerCanUpdate === true,+ }),),- ),+ Effect.catchIf(+ (error) =>+ error._tag !== "GitHubApiRateLimitError" &&+ error._tag !== "SourceControlRateLimitPausedError",+ () => lightAccess,+ ),+ Effect.mapError(fail("getViewerPermissions")),+ );+ },getDiff: (input) => cli.getPullRequestDiff(input).pipe(Effect.mapError(fail("getDiff"))),diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.test.tsindex 2e008fe4c63..3105634dc08 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.test.ts@@ -11,7 +11,6 @@ import {decodePullRequestStackMembershipsJson,buildReviewerRequest,buildSetFilesViewedGraphQlMutation,- decodeBaseComparisonJson,decodePullRequestActivityJson,decodePullRequestDetailJson,decodePullRequestFilesJson,@@ -1696,48 +1695,6 @@ describe("decodePullRequestFilesJson", () => {});});-describe("how far a branch trails its base", () => {- const comparison = (pullRequest: unknown) =>- JSON.stringify({ data: { repository: { pullRequest } } });-- it("reads the commit count and whether this viewer may move the branch", () => {- const decoded = expectSuccess(- decodeBaseComparisonJson(- comparison({ viewerCanUpdateBranch: true, baseRef: { compare: { behindBy: 12 } } }),- ),- );- expect(decoded).toEqual({ behindBy: 12, viewerCanUpdate: true });- });-- it("reads a current branch as nothing to do", () => {- expect(- expectSuccess(- decodeBaseComparisonJson(- comparison({ viewerCanUpdateBranch: false, baseRef: { compare: { behindBy: 0 } } }),- ),- ),- ).toEqual({ behindBy: 0, viewerCanUpdate: false });- });-- it("answers unknown where the head could not be compared", () => {- // A pull request from a fork whose repository is gone, which GitHub answers with a null- // comparison beside a perfectly good pull request.- expect(- expectSuccess(- decodeBaseComparisonJson(comparison({ viewerCanUpdateBranch: true, baseRef: null })),- ).behindBy,- ).toBeNull();- expect(expectSuccess(decodeBaseComparisonJson(comparison(null)))).toEqual({- behindBy: null,- viewerCanUpdate: false,- });- });-- it("refuses a body that is not the answer to this question", () => {- expect(Result.isSuccess(decodeBaseComparisonJson("{"))).toBe(false);- });-});-describe("decodePullRequestFilesViewedJson", () => {const page = (nodes: ReadonlyArray<unknown>,diff --git a/apps/server/src/pullRequest/gitHubPullRequestJson.ts b/apps/server/src/pullRequest/gitHubPullRequestJson.tsindex 1409e92a1fa..ce89cf6fe44 100644--- a/apps/server/src/pullRequest/gitHubPullRequestJson.ts+++ b/apps/server/src/pullRequest/gitHubPullRequestJson.ts@@ -2892,75 +2892,12 @@ function toCanTriage(viewerPermission: string | null | undefined): boolean {* need `read:org`, which a repository-scoped token need not carry — and a query GitHub refuses* fails whole, taking the people down with the teams.*/-/**- * Where the branch stands against its base, and whether this viewer may move it.- *- * `mergeStateStatus` is not the answer: GitHub only reports BEHIND where the repository requires- * branches to be up to date before merging, so on every other repository a stale branch reads as- * CLEAN or BLOCKED like any other. The comparison counts the commits instead, which is the same- * number GitHub's own "out-of-date" banner shows.- *- * `headRef` is qualified `owner:branch` because a pull request from a fork has no branch of that- * name in the base repository, and an unqualified name is simply not found there.- */-export const BASE_COMPARISON_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!, $headRef: String!) {- repository(owner: $owner, name: $name) {- pullRequest(number: $number) {- viewerCanUpdateBranch- baseRef {- compare(headRef: $headRef) {- behindBy- }- }- }- }-}`;--const RawBaseComparisonSchema = Schema.Struct({- data: Schema.Struct({- repository: Schema.NullOr(- Schema.Struct({- pullRequest: Schema.NullOr(- Schema.Struct({- viewerCanUpdateBranch: Schema.optional(Schema.NullOr(Schema.Boolean)),- /** Null where the head repository is gone, which is a comparison nobody can make. */- baseRef: Schema.optional(- Schema.NullOr(- Schema.Struct({- compare: Schema.optional(- Schema.NullOr(Schema.Struct({ behindBy: Schema.Number })),- ),- }),- ),- ),- }),- ),- }),- ),- }),-});--const decodeBaseComparison = decodeJsonResult(RawBaseComparisonSchema);-export interface GitHubBaseComparison {/** Null where the host could not compare, which the page reads as "unknown". */readonly behindBy: number | null;readonly viewerCanUpdate: boolean;}-export function decodeBaseComparisonJson(- raw: string,-): Result.Result<GitHubBaseComparison, DecodeFailure> {- const decoded = decodeBaseComparison(raw);- if (!Result.isSuccess(decoded)) return Result.fail(decoded.failure);- const pullRequest = decoded.success.data.repository?.pullRequest;- const behindBy = pullRequest?.baseRef?.compare?.behindBy;- return Result.succeed({- behindBy: typeof behindBy === "number" && behindBy >= 0 ? behindBy : null,- viewerCanUpdate: pullRequest?.viewerCanUpdateBranch === true,- });-}-export const REVIEWER_CANDIDATES_GRAPHQL_QUERY = `query($owner: String!, $name: String!, $number: Int!) {repository(owner: $owner, name: $name) {assignableUsers(first: ${GRAPHQL_PAGE_SIZE}) {diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.tsindex 4376d5d7ea6..59f188d7d1b 100644--- a/apps/server/src/serverSettings.test.ts+++ b/apps/server/src/serverSettings.test.ts@@ -1588,6 +1588,54 @@ it.layer(NodeServices.layer)("server settings", (it) => {}).pipe(Effect.provide(layerServerSettingsWithSecrets())),);+ it.effect(+ "keeps GitHub tokens per host in the secret store and tells clients only that one is set",+ () =>+ Effect.gen(function* () {+ const serverSettings = yield* ServerSettingsModule.ServerSettingsService;+ const secrets = yield* ServerSecretStore.ServerSecretStore;+ const serverConfig = yield* ServerConfig.ServerConfig;+ const fileSystem = yield* FileSystem.FileSystem;++ const saved = yield* serverSettings.updateSettings({+ github: { tokens: { "GitHub.com": "ghp_dotcom", "ghe.acme.test": "ghp_ghe" } },+ });+ assert.deepEqual(saved.github.tokens, {+ "github.com": "ghp_dotcom",+ "ghe.acme.test": "ghp_ghe",+ });+ const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);+ assert.notInclude(raw, "ghp_dotcom");+ assert.notInclude(raw, "ghp_ghe");++ const forClient = ServerSettingsModule.redactServerSettingsForClient(saved).github;+ assert.notInclude(forClient.tokens["github.com"]!, "ghp_dotcom");+ assert.isAbove(forClient.tokens["github.com"]!.length, 0);++ // Echoing the redacted values back keeps them; host and account changes leave tokens alone.+ yield* serverSettings.updateSettings({ github: { tokens: forClient.tokens } });+ yield* serverSettings.updateSettings({+ github: { hosts: { "github.com": { enabled: true, account: "work" } } },+ });+ assert.deepEqual((yield* serverSettings.getSettings).github.tokens, {+ "github.com": "ghp_dotcom",+ "ghe.acme.test": "ghp_ghe",+ });++ // An empty token removes that host's token and nothing else.+ const cleared = yield* serverSettings.updateSettings({+ github: { tokens: { "github.com": "" } },+ });+ assert.equal(cleared.github.tokens["github.com"] ?? "", "");+ assert.equal(cleared.github.tokens["ghe.acme.test"], "ghp_ghe");+ const remaining = yield* Effect.forEach(["github.com", "ghe.acme.test"], (host) =>+ secrets.get(`github-token-${Buffer.from(host, "utf8").toString("base64url")}`),+ );+ assert.isTrue(Option.isNone(remaining[0]!));+ assert.isTrue(Option.isSome(remaining[1]!));+ }).pipe(Effect.provide(layerServerSettingsWithSecrets())),+ );+it.effect("removes a Bitbucket secret once its token is cleared by hand in settings.json", () =>Effect.gen(function* () {const serverConfig = yield* ServerConfig.ServerConfig;diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.tsindex 6452c8d775a..7cbcd895ac1 100644--- a/apps/server/src/serverSettings.ts+++ b/apps/server/src/serverSettings.ts@@ -161,6 +161,11 @@ const BITBUCKET_SECRET_NAMES = {} as const;const BITBUCKET_SECRET_FIELDS = ["accessToken", "apiToken"] as const;+/** Hosts are case-insensitive; a patch can arrive before decoding lowercased its keys. */+function gitHubTokenSecretName(host: string): string {+ return `github-token-${Buffer.from(host.trim().toLowerCase(), "utf8").toString("base64url")}`;+}+const redactSecret = (value: string) => (value.length > 0 ? SECRET_REDACTED : "");function redactProviderEnvironmentVariable(@@ -204,7 +209,13 @@ export function redactServerSettingsForClient(settings: ServerSettings): ServerSaccessToken: redactSecret(settings.bitbucket.accessToken),apiToken: redactSecret(settings.bitbucket.apiToken),};- return { ...settings, providerInstances, usageLimitSources, bitbucket };+ const github = {+ ...settings.github,+ tokens: Object.fromEntries(+ Object.entries(settings.github.tokens).map(([host, token]) => [host, redactSecret(token)]),+ ),+ };+ return { ...settings, providerInstances, usageLimitSources, bitbucket, github };}export function applyProviderInstanceMutation(@@ -707,7 +718,24 @@ const make = Effect.gen(function* () {bitbucket[field] = SECRET_REDACTED;moved = true;}- return moved ? { ...settings, bitbucket } : settings;+ const tokens = { ...settings.github.tokens };+ for (const [host, value] of Object.entries(tokens)) {+ if (value.length === 0 || value === SECRET_REDACTED) continue;+ const stored = yield* secretStore+ .set(gitHubTokenSecretName(host), textEncoder.encode(value))+ .pipe(+ Effect.as(true),+ Effect.catch(() =>+ Effect.logWarning("failed to move a GitHub token into the secret store", {+ host,+ }).pipe(Effect.as(false)),+ ),+ );+ if (!stored) continue;+ tokens[host] = SECRET_REDACTED;+ moved = true;+ }+ return moved ? { ...settings, bitbucket, github: { ...settings.github, tokens } } : settings;});const loadSettingsFromDisk = Effect.gen(function* () {@@ -882,11 +910,27 @@ const make = Effect.gen(function* () {);bitbucket[field] = Option.isSome(secret) ? textDecoder.decode(secret.value) : "";}+ const tokens: Record<string, string> = {};+ for (const [host, value] of Object.entries(settings.github.tokens)) {+ if (value !== SECRET_REDACTED) {+ tokens[host] = value;+ continue;+ }+ const secret = yield* secretStore+ .get(gitHubTokenSecretName(host))+ .pipe(+ Effect.mapError(+ (cause) => new ServerSettingsError({ settingsPath, operation: "read-secret", cause }),+ ),+ );+ tokens[host] = Option.isSome(secret) ? textDecoder.decode(secret.value) : "";+ }return {...settings,providerInstances: providerInstances as ServerSettings["providerInstances"],usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],bitbucket,+ github: { ...settings.github, tokens },};});@@ -1047,12 +1091,46 @@ const make = Effect.gen(function* () {bitbucket[field] = SECRET_REDACTED;}+ const tokens: Record<string, string> = {};+ for (const [rawHost, raw] of Object.entries(next.github.tokens)) {+ const host = rawHost.trim().toLowerCase();+ let value = raw;+ if (value === SECRET_REDACTED) {+ // The marker keeps what is saved; a hand-edited plaintext token moves into the store.+ const inline = current.github.tokens[host];+ if (inline === undefined || inline === SECRET_REDACTED || inline.length === 0) {+ tokens[host] = SECRET_REDACTED;+ continue;+ }+ value = inline;+ }+ const secretName = gitHubTokenSecretName(host);+ if (value.length === 0) {+ changes.push({ kind: "remove", secretName, operation: "remove-secret" });+ continue;+ }+ changes.push({ kind: "write", secretName, value: textEncoder.encode(value) });+ tokens[host] = SECRET_REDACTED;+ }+ const nextHosts = new Set(+ Object.keys(next.github.tokens).map((host) => host.trim().toLowerCase()),+ );+ for (const host of Object.keys(current.github.tokens)) {+ if (nextHosts.has(host.trim().toLowerCase())) continue;+ changes.push({+ kind: "remove",+ secretName: gitHubTokenSecretName(host),+ operation: "remove-stale-secret",+ });+ }+return {settings: {...next,providerInstances: providerInstances as ServerSettings["providerInstances"],usageLimitSources: usageLimitSources as ServerSettings["usageLimitSources"],bitbucket,+ github: { ...next.github, tokens },},changes,};diff --git a/apps/server/src/sourceControl/GitHubApi.test.ts b/apps/server/src/sourceControl/GitHubApi.test.tsindex 85fe9a2dcfb..a5c0f82be44 100644--- a/apps/server/src/sourceControl/GitHubApi.test.ts+++ b/apps/server/src/sourceControl/GitHubApi.test.ts@@ -15,6 +15,7 @@ import * as GitHubCredentials from "./GitHubCredentials.ts";import * as GitHubGraphQlBudget from "./githubGraphQlBudget.ts";import * as SourceControlRateLimit from "./SourceControlRateLimit.ts";import * as VcsProcess from "../vcs/VcsProcess.ts";+import * as ServerSettings from "../serverSettings.ts";const NOW = Date.parse("2026-10-05T12:00:00.000Z");@@ -416,6 +417,7 @@ describe("GitHubCredentials", () => {GitHubCredentials.layer.pipe(Layer.provide(Layer.mock(VcsProcess.VcsProcess)({ run })),Layer.provide(NodeServices.layer),+ Layer.provide(ServerSettings.layerTest()),);it.effect("fails with GitHubCliMissingError when gh is not on PATH", () =>diff --git a/apps/server/src/sourceControl/GitHubCli.ts b/apps/server/src/sourceControl/GitHubCli.tsindex 95501d3c163..f4463be6de8 100644--- a/apps/server/src/sourceControl/GitHubCli.ts+++ b/apps/server/src/sourceControl/GitHubCli.ts@@ -44,7 +44,7 @@ export class GitHubCliUnavailableError extends Schema.TaggedError<GitHubCliUnavagitHubCliFailureFields,) {override get message(): string {- return "GitHub CLI (`gh`) is required but not available on PATH. Install it and run `gh auth login`, or set GH_TOKEN.";+ return "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI and run `gh auth login`.";}}@@ -53,7 +53,10 @@ export class GitHubCliAuthenticationError extends Schema.TaggedError<GitHubCliAugitHubCliFailureFields,) {override get message(): string {- return "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.";+ // A missing or turned-off credential already says what to do about it.+ return GitHubCredentials.isGitHubCredentialUnavailableError(this.cause)+ ? this.cause.message+ : "GitHub is not authenticated. Run `gh auth login` (or set GH_TOKEN) and retry.";}}@@ -153,6 +156,7 @@ function fromGitHubApiError(cwd: string, error: GitHubApi.GitHubApiError): GitHucase "GitHubCliMissingError":return new GitHubCliUnavailableError(context);case "GitHubNotSignedInError":+ case "GitHubHostDisabledError":case "GitHubApiAuthenticationError":return new GitHubCliAuthenticationError(context);case "GitHubCliFailedError":diff --git a/apps/server/src/sourceControl/GitHubCredentials.test.ts b/apps/server/src/sourceControl/GitHubCredentials.test.tsnew file mode 100644index 00000000000..734a309f002--- /dev/null+++ b/apps/server/src/sourceControl/GitHubCredentials.test.ts@@ -0,0 +1,170 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "@effect/vitest";+import * as NodeServices from "@effect/platform-node/NodeServices";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Redacted from "effect/Redacted";+import { ChildProcessSpawner } from "effect/process";++import * as ServerSettings from "../serverSettings.ts";+import * as VcsProcess from "../vcs/VcsProcess.ts";+import * as GitHubCredentials from "./GitHubCredentials.ts";++const TOKEN_VARIABLES = [+ "GH_TOKEN",+ "GITHUB_TOKEN",+ "GH_ENTERPRISE_TOKEN",+ "GITHUB_ENTERPRISE_TOKEN",+] as const;++function harness(+ hosts: Record<string, { readonly account?: string; readonly enabled?: boolean }> = {},+ signedOut: ReadonlyArray<string> = [],+ tokens: Record<string, string> = {},+) {+ const calls: Array<ReadonlyArray<string>> = [];+ const process = Layer.mock(VcsProcess.VcsProcess)({+ run: (input) =>+ Effect.sync(() => {+ calls.push(input.args);+ const user = input.args[input.args.indexOf("--user") + 1];+ if (input.args.includes("--user") && user !== undefined && signedOut.includes(user)) {+ return {+ exitCode: ChildProcessSpawner.ExitCode(0),+ stdout: "",+ stderr: "",+ stdoutTruncated: false,+ stderrTruncated: false,+ };+ }+ return {+ exitCode: ChildProcessSpawner.ExitCode(0),+ stdout: input.args.includes("--user") ? `token-for-${user}\n` : "active-token\n",+ stderr: "",+ stdoutTruncated: false,+ stderrTruncated: false,+ };+ }),+ });+ const layer = GitHubCredentials.layer.pipe(+ Layer.provideMerge(+ ServerSettings.ServerSettingsService.layerTest({ github: { hosts, tokens } }),+ ),+ Layer.provide(process),+ Layer.provide(NodeServices.layer),+ );+ return { layer, calls };+}++describe("GitHubCredentials", () => {+ beforeEach(() => {+ for (const name of TOKEN_VARIABLES) vi.stubEnv(name, "");+ });+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it.effect("asks gh for the active login when Settings pin nothing", () => {+ const { layer, calls } = harness();+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ const credential = yield* credentials.get("GitHub.com");+ expect(Redacted.value(credential.token)).toBe("active-token");+ expect(calls).toEqual([["auth", "token", "--hostname", "github.com"]]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("passes --user for an account pinned in Settings", () => {+ const { layer, calls } = harness({ "github.com": { account: "work" } });+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ const credential = yield* credentials.get("github.com");+ expect(Redacted.value(credential.token)).toBe("token-for-work");+ expect(calls).toEqual([["auth", "token", "--hostname", "github.com", "--user", "work"]]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("fails a host turned off in Settings without asking gh", () => {+ const { layer, calls } = harness({ "github.com": { enabled: false } });+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ const error = yield* Effect.flip(credentials.get("github.com"));+ expect(error._tag).toBe("GitHubHostDisabledError");+ expect(error.message).toBe(+ "GitHub host github.com is turned off in Settings → Source Control.",+ );+ expect(calls).toEqual([]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("lets an environment token win over a pinned account, as gh does", () => {+ vi.stubEnv("GH_TOKEN", "from-env");+ const { layer, calls } = harness({ "github.com": { account: "work" } });+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ const credential = yield* credentials.get("github.com");+ expect(Redacted.value(credential.token)).toBe("from-env");+ expect(credential.source).toBe("env");+ expect(calls).toEqual([]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("picks up a changed account on the next request without a restart", () => {+ const { layer, calls } = harness();+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ const settings = yield* ServerSettings.ServerSettingsService;+ expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");++ yield* settings.updateSettings({+ github: { hosts: { "github.com": { account: "work", enabled: true } } },+ });+ expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("token-for-work");++ yield* settings.updateSettings({ github: { hosts: { "github.com": { enabled: false } } } });+ expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(+ "GitHubHostDisabledError",+ );++ yield* settings.updateSettings({ github: { hosts: {} } });+ expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");+ // The unpinned token stayed cached; only the newly pinned account cost a gh call.+ expect(calls).toHaveLength(2);+ }).pipe(Effect.provide(layer));+ });++ it.effect("falls back to the active login when the pinned one is no longer signed in", () => {+ const { layer, calls } = harness({ "github.com": { account: "gone" } }, ["gone"]);+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ expect(Redacted.value((yield* credentials.get("github.com")).token)).toBe("active-token");+ expect(calls).toEqual([+ ["auth", "token", "--hostname", "github.com", "--user", "gone"],+ ["auth", "token", "--hostname", "github.com"],+ ]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("uses a token saved in Settings before GH_TOKEN and gh", () => {+ vi.stubEnv("GH_TOKEN", "env-token");+ const { layer, calls } = harness({}, [], { "github.com": "saved-token" });+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ const credential = yield* credentials.get("github.com");+ expect(Redacted.value(credential.token)).toBe("saved-token");+ expect(credential.source).toBe("settings");+ expect(calls).toEqual([]);+ }).pipe(Effect.provide(layer));+ });++ it.effect("keeps a host turned off even with a token saved in Settings", () => {+ const { layer } = harness({ "github.com": { enabled: false } }, [], {+ "github.com": "saved-token",+ });+ return Effect.gen(function* () {+ const credentials = yield* GitHubCredentials.GitHubCredentials;+ expect((yield* Effect.flip(credentials.get("github.com")))._tag).toBe(+ "GitHubHostDisabledError",+ );+ }).pipe(Effect.provide(layer));+ });+});diff --git a/apps/server/src/sourceControl/GitHubCredentials.ts b/apps/server/src/sourceControl/GitHubCredentials.tsindex 7207373bcf3..fb043d809c6 100644--- a/apps/server/src/sourceControl/GitHubCredentials.ts+++ b/apps/server/src/sourceControl/GitHubCredentials.ts@@ -13,6 +13,7 @@ import * as Schema from "effect/Schema";import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";+import * as ServerSettings from "../serverSettings.ts";import * as VcsProcess from "../vcs/VcsProcess.ts";/** How long a token is reused before `gh` is asked again, so a `gh auth switch` applies soon. */@@ -20,7 +21,7 @@ const TOKEN_TTL = Duration.minutes(5);/** No credential is retried sooner, so a fresh `gh auth login` takes effect on the next read. */const MISSING_TTL = Duration.seconds(10);-export const GitHubCredentialSource = Schema.Literals(["env", "gh"]);+export const GitHubCredentialSource = Schema.Literals(["settings", "env", "gh"]);export type GitHubCredentialSource = typeof GitHubCredentialSource.Type;export interface GitHubCredential {@@ -41,13 +42,25 @@ export class GitHubCliMissingError extends Schema.TaggedError<GitHubCliMissingEr}}-/** `gh` is installed but holds no login for the host. */+/** `gh` is installed but holds no login for the host, or not the account chosen in Settings. */export class GitHubNotSignedInError extends Schema.TaggedError<GitHubNotSignedInError>()("GitHubNotSignedInError",+ { host: Schema.String, account: Schema.optional(Schema.String) },+) {+ override get message(): string {+ return this.account === undefined+ ? `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`+ : `No GitHub credential for ${this.account} on ${this.host}: run \`gh auth login --hostname ${this.host}\` for that account or pick another in Settings → Source Control.`;+ }+}++/** The user turned the host off in Settings. */+export class GitHubHostDisabledError extends Schema.TaggedError<GitHubHostDisabledError>()(+ "GitHubHostDisabledError",{ host: Schema.String },) {override get message(): string {- return `No GitHub credential for ${this.host}: run \`gh auth login --hostname ${this.host}\`.`;+ return `GitHub host ${this.host} is turned off in Settings → Source Control.`;}}@@ -65,8 +78,13 @@ export class GitHubCliFailedError extends Schema.TaggedError<GitHubCliFailedErroexport type GitHubCredentialUnavailableError =| GitHubCliMissingError| GitHubNotSignedInError+ | GitHubHostDisabledError| GitHubCliFailedError;+export const isGitHubCredentialUnavailableError = Schema.is(+ Schema.Union([GitHubCliMissingError, GitHubNotSignedInError, GitHubHostDisabledError]),+);+/*** Where GitHub tokens come from. Callers ask per host and never see how the token was found,* so another source (an in-app OAuth login) slots in here without touching any of them.@@ -115,6 +133,7 @@ export function environmentToken(/** @public Service construction is part of the canonical Effect module API. */export const make = Effect.gen(function* () {const process = yield* VcsProcess.VcsProcess;+ const serverSettings = yield* ServerSettings.ServerSettingsService;const crypto = yield* Crypto.Crypto;const environment = yield* HostProcessEnvironment;const workingDirectory = yield* HostProcessWorkingDirectory;@@ -127,12 +146,18 @@ export const make = Effect.gen(function* () {Effect.orDie,);- const fromGh = (host: string) =>+ const fromGh = (host: string, account: string | undefined) =>process.run({operation: "GitHubCredentials.get",command: "gh",- args: ["auth", "token", "--hostname", host],+ args: [+ "auth",+ "token",+ "--hostname",+ host,+ ...(account === undefined ? [] : ["--user", account]),+ ],cwd: workingDirectory,// Never let gh print the token into a debug log.env: { GH_DEBUG: "", GH_PROMPT_DISABLED: "1" },@@ -146,19 +171,48 @@ export const make = Effect.gen(function* () {? new GitHubCliMissingError({ host }): // gh exits non-zero with "no oauth token" when it has no login for the host.error._tag === "VcsProcessExitError"- ? new GitHubNotSignedInError({ host })+ ? new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }): new GitHubCliFailedError({ host, cause: error }),),Effect.map((output) => output.stdout.trim()),Effect.filterOrFail((token) => token !== "",- () => new GitHubNotSignedInError({ host }),+ () => new GitHubNotSignedInError({ host, ...(account === undefined ? {} : { account }) }),),);- const lookup = Effect.fn("GitHubCredentials.lookup")(function* (host: string) {+ /** The Settings choice for a host; unreadable settings fall back to gh's own choice. */+ const hostChoice = (host: string) =>+ serverSettings.getSettings.pipe(+ Effect.map((settings) => settings.github.hosts[host]),+ Effect.orElseSucceed(() => undefined),+ );++ /** A token saved in Settings for the host, read fresh so a saved or removed one applies at once. */+ const savedToken = (host: string) =>+ serverSettings.getSettings.pipe(+ Effect.map((settings) => settings.github.tokens[host]?.trim() || null),+ Effect.orElseSucceed(() => null),+ );++ /** Cache key: the host plus its pinned account, so a changed pin misses the cache. */+ const cacheKey = (host: string, account: string | undefined) =>+ account === undefined ? host : `${host}\u0000${account}`;++ const lookup = Effect.fn("GitHubCredentials.lookup")(function* (key: string) {+ const [host = key, choice] = key.split("\u0000");+ // An environment token wins over a pinned account, exactly as it does in gh.const fromEnv = environmentToken(host, environment);- const token = fromEnv ?? (yield* fromGh(host));+ // A pinned login gh no longer holds (logged out, expired) falls back to the active one,+ // which is what discovery reports as the account in use.+ const token =+ fromEnv ??+ (yield* fromGh(host, choice).pipe(+ Effect.catchTags({+ GitHubNotSignedInError: (error) =>+ choice === undefined ? Effect.fail(error) : fromGh(host, undefined),+ }),+ ));return {host,token: Redacted.make(token),@@ -181,8 +235,31 @@ export const make = Effect.gen(function* () {});return GitHubCredentials.of({- get: (host) => Cache.get(cache, normalizeHost(host)),- invalidate: (host) => Cache.invalidate(cache, normalizeHost(host)),+ get: Effect.fn("GitHubCredentials.get")(function* (rawHost) {+ const host = normalizeHost(rawHost);+ const choice = yield* hostChoice(host);+ if (choice?.enabled === false) {+ return yield* new GitHubHostDisabledError({ host });+ }+ // A token saved in Settings is the most deliberate choice, so it comes before the+ // environment and gh. It is read from the secret store each time, so it needs no cache.+ const saved = yield* savedToken(host);+ if (saved !== null) {+ return {+ host,+ token: Redacted.make(saved),+ source: "settings",+ fingerprint: yield* fingerprintOf(host, saved),+ } satisfies GitHubCredential;+ }+ return yield* Cache.get(cache, cacheKey(host, choice?.account));+ }),+ invalidate: (rawHost) => {+ const host = normalizeHost(rawHost);+ return hostChoice(host).pipe(+ Effect.flatMap((choice) => Cache.invalidate(cache, cacheKey(host, choice?.account))),+ );+ },});});diff --git a/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts b/apps/server/src/sourceControl/GitHubSourceControlProvider.test.tsindex 6376e2d868e..ea6624aef89 100644--- a/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts+++ b/apps/server/src/sourceControl/GitHubSourceControlProvider.test.ts@@ -329,6 +329,7 @@ it("parses GitHub auth status accounts by host and active state", () => {authenticated: true,active: true,error: null,+ environmentVariable: null,},{host: "github.com",@@ -336,6 +337,7 @@ it("parses GitHub auth status accounts by host and active state", () => {authenticated: false,active: false,error: null,+ environmentVariable: null,},{host: "github.example.test",@@ -343,6 +345,7 @@ it("parses GitHub auth status accounts by host and active state", () => {authenticated: true,active: false,error: null,+ environmentVariable: null,},],);@@ -466,3 +469,75 @@ it.effect.each(["read", "decode"] as const)(else assert.propertyVal(error.cause, "_tag", "SchemaError");}),);++const multiAccountStatus = (extra: ReadonlyArray<Record<string, unknown>> = []) =>+ processResult(+ JSON.stringify({+ hosts: {+ "github.com": [+ { state: "success", active: true, host: "github.com", login: "personal" },+ { state: "success", active: false, host: "github.com", login: "work" },+ ...extra,+ ],+ "ghe.acme.test": [+ { state: "error", active: true, host: "ghe.acme.test", login: "jm", error: "expired" },+ ],+ },+ }),+ );++it("reports every gh login and leads with the account Settings pin", () => {+ const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {+ hosts: { "github.com": { account: "work", enabled: true } },+ tokens: {},+ });+ assert.deepStrictEqual(auth.account, Option.some("work"));+ assert.deepStrictEqual(auth.accounts, [+ { host: "github.com", account: "personal", active: true, authenticated: true },+ { host: "github.com", account: "work", active: false, authenticated: true },+ { host: "ghe.acme.test", account: "jm", active: true, authenticated: false, error: "expired" },+ ]);+});++it("falls back to gh's active login when the pinned account is gone", () => {+ const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {+ hosts: { "github.com": { account: "former-job", enabled: true } },+ tokens: {},+ });+ assert.deepStrictEqual(auth.account, Option.some("personal"));+});++it("reports unauthenticated when Settings turn off every signed-in host", () => {+ const auth = GitHubSourceControlProvider.parseGitHubAuth(multiAccountStatus(), {+ hosts: { "github.com": { enabled: false } },+ tokens: {},+ });+ assert.strictEqual(auth.status, "unauthenticated");+ assert.deepStrictEqual(+ auth.detail,+ Option.some("Every GitHub host gh is signed in to is turned off in Settings → Source Control."),+ );+});++it("names the environment token that overrides the Settings choice", () => {+ const auth = GitHubSourceControlProvider.parseGitHubAuth(+ multiAccountStatus([+ {+ state: "success",+ active: false,+ host: "github.com",+ login: "bot",+ tokenSource: "GH_TOKEN",+ },+ ]),+ { hosts: { "github.com": { account: "work", enabled: true } }, tokens: {} },+ );+ assert.deepStrictEqual(auth.account, Option.some("bot"));+ assert.deepStrictEqual(+ auth.detail,+ Option.some(+ "Using GH_TOKEN from the server environment; it overrides the account chosen in Settings.",+ ),+ );+ assert.strictEqual(auth.accounts?.[2]?.environmentVariable, "GH_TOKEN");+});diff --git a/apps/server/src/sourceControl/GitHubSourceControlProvider.ts b/apps/server/src/sourceControl/GitHubSourceControlProvider.tsindex 8e183e8b9ac..0b868ba3f43 100644--- a/apps/server/src/sourceControl/GitHubSourceControlProvider.ts+++ b/apps/server/src/sourceControl/GitHubSourceControlProvider.ts@@ -4,16 +4,24 @@ import * as Effect from "effect/Effect";import * as Option from "effect/Option";import * as Result from "effect/Result";import {+ DEFAULT_SERVER_SETTINGS,SourceControlProviderError,type ChangeRequest,+ type GitHubSettings,type SourceControlProviderDiscoveryItem,} from "@t3tools/contracts";import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";+import * as ServerSettings from "../serverSettings.ts";import * as GitHubApi from "./GitHubApi.ts";import * as GitHubCli from "./GitHubCli.ts";-import { findAuthenticatedGitHubAccount, parseGitHubAuthStatus } from "./gitHubAuthStatus.ts";+import {+ effectiveGitHubAccount,+ findAuthenticatedGitHubAccount,+ parseGitHubAuthStatus,+ type GitHubAuthStatusAccount,+} from "./gitHubAuthStatus.ts";import * as SourceControlProvider from "./SourceControlProvider.ts";import {combinedAuthOutput,@@ -60,29 +68,78 @@ function toChangeRequest(summary: GitHubCli.GitHubPullRequestSummary): ChangeReq};}-function parseGitHubAuth(input: SourceControlAuthProbeInput) {+function authAccounts(accounts: ReadonlyArray<GitHubAuthStatusAccount>) {+ return accounts.map((entry) => ({+ host: entry.host,+ account: entry.account,+ active: entry.active,+ authenticated: entry.authenticated,+ ...(entry.error === null ? {} : { error: entry.error }),+ ...(entry.environmentVariable === null+ ? {}+ : { environmentVariable: entry.environmentVariable }),+ }));+}++/**+ * Reads `gh auth status --json hosts`. The headline account is the one GitHub requests will+ * use: Settings can pin a login per host or turn a host off, and an environment token beats both.+ */+export function parseGitHubAuth(+ input: SourceControlAuthProbeInput,+ settings: GitHubSettings = DEFAULT_SERVER_SETTINGS.github,+) {const output = combinedAuthOutput(input);const authStatus = parseGitHubAuthStatus(input.stdout);- const authenticatedAccount = findAuthenticatedGitHubAccount(authStatus.accounts);- const host = authenticatedAccount?.host;+ const hosts = [...new Set(authStatus.accounts.map((entry) => entry.host))];+ const fallback = findAuthenticatedGitHubAccount(authStatus.accounts);+ // Lead with the host gh would pick, unless Settings turned it off.+ const orderedHosts = fallback+ ? [fallback.host, ...hosts.filter((host) => host !== fallback.host)]+ : hosts;+ const chosen = orderedHosts+ .map((host) => effectiveGitHubAccount(host, authStatus.accounts, settings))+ .find((entry) => entry !== undefined);+ const accounts = authStatus.parsed ? { accounts: authAccounts(authStatus.accounts) } : {};- if (authenticatedAccount) {- return providerAuth({- status: "authenticated",- account: authenticatedAccount.account,- host,- });+ if (chosen) {+ return {+ ...providerAuth({+ status: "authenticated",+ account: chosen.account,+ host: chosen.host,+ detail:+ chosen.environmentVariable === null+ ? undefined+ : `Using ${chosen.environmentVariable} from the server environment; it overrides the account chosen in Settings.`,+ }),+ ...accounts,+ };+ }++ if (fallback) {+ return {+ ...providerAuth({+ status: "unauthenticated",+ host: fallback.host,+ detail: "Every GitHub host gh is signed in to is turned off in Settings → Source Control.",+ }),+ ...accounts,+ };}const failedAccount = authStatus.accounts.find((entry) => entry.active) ?? authStatus.accounts[0];if (authStatus.parsed) {- return providerAuth({- status: "unauthenticated",- host: failedAccount?.host,- detail:- failedAccount?.error ??- "Run `gh auth login` to authenticate GitHub CLI with an active account.",- });+ return {+ ...providerAuth({+ status: "unauthenticated",+ host: failedAccount?.host,+ detail:+ failedAccount?.error ??+ "Run `gh auth login` to authenticate GitHub CLI with an active account.",+ }),+ ...accounts,+ };}// gh gained `auth status --json` in 2.81.0. Older versions reject the flag and exit@@ -98,14 +155,12 @@ function parseGitHubAuth(input: SourceControlAuthProbeInput) {if (input.exitCode !== 0) {return providerAuth({status: "unauthenticated",- host,detail: firstSafeAuthLine(output) ?? "Run `gh auth login` to authenticate GitHub CLI.",});}return providerAuth({status: "unknown",- host,detail: firstSafeAuthLine(output) ?? "GitHub CLI auth status could not be parsed.",});}@@ -132,51 +187,75 @@ function environmentTokenVariable(environment: NodeJS.ProcessEnv): string | null}/**- * GitHub is usable with a token from the environment or with `gh` to hand one over. An- * environment token is checked against the API, since `gh auth status` may not know it.+ * GitHub is usable with a token saved in Settings, one from the environment, or `gh` to hand one+ * over. Reads the+ * GitHub settings on every probe, so a saved account choice shows on rescan. An environment+ * token is checked against the API, since `gh auth status` may not know it.*/export const makeDiscovery = Effect.gen(function* () {const api = yield* GitHubApi.GitHubApi;const process = yield* VcsProcess.VcsProcess;const environment = yield* HostProcessEnvironment;+ const serverSettings = yield* ServerSettings.ServerSettingsService;+return {type: "managed-cli",kind: discovery.kind,label: discovery.label,installHint: discovery.installHint,probe: Effect.fn("GitHubSourceControlProvider.discovery")(function* (cwd: string) {- const cli = yield* probeSourceControlProvider({ cwd, process, spec: discovery });+ const settings = yield* serverSettings.getSettings.pipe(+ Effect.map((current) => current.github),+ Effect.orElseSucceed(() => DEFAULT_SERVER_SETTINGS.github),+ );+ const cli = yield* probeSourceControlProvider({+ cwd,+ process,+ spec: { ...discovery, parseAuth: (input) => parseGitHubAuth(input, settings) },+ });+ // A token saved in Settings wins over the environment, which wins over gh.+ const savedToken = (settings.tokens["github.com"] ?? "").trim() !== "";const variable = environmentTokenVariable(environment);- if (variable === null) return cli;+ const tokenSource = savedToken ? "the token saved in Settings" : variable;+ // A host turned off in Settings stays off even with a token.+ if (tokenSource === null || settings.hosts["github.com"]?.enabled === false) return cli;const viewer = yield* api.rest({ host: "github.com", operation: "discovery", path: "user" }).pipe(Effect.result);const login = Result.isSuccess(viewer)? Option.getOrUndefined(decodeViewer(viewer.success.body))?.login: undefined;+ // The per-host logins stay, so the account picker still lists every host gh knows.+ const accounts = cli.auth.accounts === undefined ? {} : { accounts: cli.auth.accounts };return {...cli,status: "available" as const,- auth:- login !== undefined+ auth: {+ ...(login !== undefined? providerAuth({status: "authenticated",account: login,host: "github.com",- detail: `Using the token in ${variable} from the server environment.`,+ detail: savedToken+ ? "Using the token saved in Settings; it overrides GH_TOKEN and the gh login."+ : `Using ${variable} from the server environment; it overrides the account chosen in Settings.`,}): Result.isFailure(viewer) && viewer.failure._tag !== "GitHubApiAuthenticationError"? // Only a refusal says the token is bad; a network error or a pause says nothing.providerAuth({status: "unknown",host: "github.com",- detail: `Could not check the token in ${variable}: ${viewer.failure.message}`,+ detail: `Could not check ${savedToken ? tokenSource : `the token in ${tokenSource}`}: ${viewer.failure.message}`,}): providerAuth({status: "unauthenticated",host: "github.com",- detail: `GitHub refused the token in ${variable}. Replace it, or unset it to use \`gh auth login\`.`,- }),+ detail: savedToken+ ? "GitHub refused the token saved in Settings. Replace or remove it in Settings → Source Control."+ : `GitHub refused the token in ${tokenSource}. Replace it, or unset it to use \`gh auth login\`.`,+ })),+ ...accounts,+ },} satisfies SourceControlProviderDiscoveryItem;}),refineUnknownRemote: () => Effect.succeed(null),diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.tsindex 672963fc9ec..54de8cc14fd 100644--- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts+++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts@@ -11,6 +11,7 @@ import { ChildProcessSpawner } from "effect/process";import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";import { VcsProcessSpawnError } from "@t3tools/contracts";+import * as ServerSettings from "../serverSettings.ts";import * as ServerConfig from "../config.ts";import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";import * as VcsProcess from "../vcs/VcsProcess.ts";@@ -38,6 +39,7 @@ const layerSourceControlProviderRegistryTest = (input: {}).pipe(Layer.provide(NodeServices.layer)),Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),Layer.mock(BitbucketApi.BitbucketApi)(input.bitbucket),+ ServerSettings.ServerSettingsService.layerTest(),Layer.mock(GitHubCli.GitHubCli)({}),Layer.mock(GitHubApi.GitHubApi)({}),Layer.mock(GitLabCli.GitLabCli)({}),diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.tsindex 39dbcaba04f..08751017b35 100644--- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts+++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts@@ -7,6 +7,7 @@ import * as Option from "effect/Option";import { ChildProcessSpawner } from "effect/process";import { VcsRepositoryDetectionError } from "@t3tools/contracts";+import * as ServerSettings from "../serverSettings.ts";import * as ServerConfig from "../config.ts";import type * as VcsDriver from "../vcs/VcsDriver.ts";import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";@@ -96,6 +97,7 @@ function makeRegistry(input: {layerProcess,Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({}),Layer.mock(BitbucketApi.BitbucketApi)({}),+ ServerSettings.ServerSettingsService.layerTest(),Layer.mock(GitHubCli.GitHubCli)(input.github ?? {}),Layer.mock(GitHubApi.GitHubApi)(input.githubApi ?? {}),Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}),diff --git a/apps/server/src/sourceControl/gitHubAuthStatus.ts b/apps/server/src/sourceControl/gitHubAuthStatus.tsindex d58909c560c..7321ead2d4e 100644--- a/apps/server/src/sourceControl/gitHubAuthStatus.ts+++ b/apps/server/src/sourceControl/gitHubAuthStatus.ts@@ -1,3 +1,4 @@+import type { GitHubSettings } from "@t3tools/contracts";import * as Option from "effect/Option";import * as Schema from "effect/Schema";@@ -7,6 +8,7 @@ const GitHubAuthStatusAccountSchema = Schema.Struct({active: Schema.Boolean,host: Schema.String,login: Schema.String,+ tokenSource: Schema.optional(Schema.String),});const GitHubAuthStatusSchema = Schema.Struct({@@ -23,6 +25,8 @@ export interface GitHubAuthStatusAccount {readonly authenticated: boolean;readonly active: boolean;readonly error: string | null;+ /** The variable (GH_TOKEN and kin) the login came from; it overrides every stored login. */+ readonly environmentVariable: string | null;}export interface GitHubAuthStatus {@@ -30,6 +34,8 @@ export interface GitHubAuthStatus {readonly accounts: ReadonlyArray<GitHubAuthStatusAccount>;}+const ENVIRONMENT_TOKEN_SOURCE = /^(?:GH|GITHUB)_(?:ENTERPRISE_)?TOKEN$/u;+function nonEmptyString(value: string): string | null {const trimmed = value.trim();return trimmed.length > 0 ? trimmed : null;@@ -54,6 +60,9 @@ export function parseGitHubAuthStatus(text: string): GitHubAuthStatus {authenticated: account.state === "success",active: account.active,error: account.error?.trim() || null,+ environmentVariable: ENVIRONMENT_TOKEN_SOURCE.test(account.tokenSource ?? "")+ ? (account.tokenSource ?? null)+ : null,},];}),@@ -70,3 +79,25 @@ export function findAuthenticatedGitHubAccount(accounts.find((account) => account.authenticated));}++/**+ * The login GitHub requests for a host will use, honoring Settings: an environment token+ * first (gh's own precedence), then the pinned account, then gh's active login.+ * Returns undefined when the host is turned off or has no usable login.+ */+export function effectiveGitHubAccount(+ host: string,+ accounts: ReadonlyArray<GitHubAuthStatusAccount>,+ settings: GitHubSettings,+): GitHubAuthStatusAccount | undefined {+ const choice = settings.hosts[host];+ if (choice?.enabled === false) return undefined;+ const usable = accounts.filter((account) => account.host === host && account.authenticated);+ return (+ usable.find((account) => account.environmentVariable !== null) ??+ (choice?.account === undefined+ ? undefined+ : usable.find((account) => account.account === choice.account)) ??+ findAuthenticatedGitHubAccount(usable)+ );+}diff --git a/apps/web/src/components/settings/GitHubAccountSettings.logic.test.ts b/apps/web/src/components/settings/GitHubAccountSettings.logic.test.tsnew file mode 100644index 00000000000..a1a895297da--- /dev/null+++ b/apps/web/src/components/settings/GitHubAccountSettings.logic.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from "vite-plus/test";++import { groupGitHubAccounts, nextGitHubHosts } from "./GitHubAccountSettings.logic";++describe("groupGitHubAccounts", () => {+ it("groups logins by host, keeping broken and environment logins out of the picker", () => {+ expect(+ groupGitHubAccounts([+ { host: "github.com", account: "personal", active: true, authenticated: true },+ { host: "github.com", account: "work", active: false, authenticated: true },+ { host: "github.com", account: "old", active: false, authenticated: false, error: "bad" },+ {+ host: "github.com",+ account: "bot",+ active: false,+ authenticated: true,+ environmentVariable: "GH_TOKEN",+ },+ { host: "ghe.acme.test", account: "jm", active: false, authenticated: true },+ ]),+ ).toEqual([+ {+ host: "github.com",+ activeAccount: "personal",+ selectable: ["personal", "work"],+ broken: [+ { host: "github.com", account: "old", active: false, authenticated: false, error: "bad" },+ ],+ environmentVariable: "GH_TOKEN",+ },+ {+ host: "ghe.acme.test",+ activeAccount: "jm",+ selectable: ["jm"],+ broken: [],+ environmentVariable: null,+ },+ ]);+ });+});++describe("nextGitHubHosts", () => {+ it("pins an account, keeps other hosts, and drops a host back on gh's defaults", () => {+ const other = { "ghe.acme.test": { enabled: false } };+ const pinned = nextGitHubHosts(other, "github.com", { account: "work" });+ expect(pinned).toEqual({ ...other, "github.com": { enabled: true, account: "work" } });++ const disabled = nextGitHubHosts(pinned, "github.com", { enabled: false });+ expect(disabled["github.com"]).toEqual({ enabled: false, account: "work" });++ expect(nextGitHubHosts(disabled, "github.com", { enabled: true, account: null })).toEqual(+ other,+ );+ });+});diff --git a/apps/web/src/components/settings/GitHubAccountSettings.logic.ts b/apps/web/src/components/settings/GitHubAccountSettings.logic.tsnew file mode 100644index 00000000000..466372f7699--- /dev/null+++ b/apps/web/src/components/settings/GitHubAccountSettings.logic.ts@@ -0,0 +1,52 @@+import type { GitHubSettings, SourceControlProviderAuth } from "@t3tools/contracts";++export type GitHubDiscoveredAccount = NonNullable<SourceControlProviderAuth["accounts"]>[number];++export interface GitHubHostGroup {+ readonly host: string;+ /** gh's active stored login, the one used when Settings pin nothing. */+ readonly activeAccount: string | null;+ /** Stored logins that work and can be pinned with `gh auth token --user`. */+ readonly selectable: ReadonlyArray<string>;+ /** Logins gh holds but cannot use; shown with their error. */+ readonly broken: ReadonlyArray<GitHubDiscoveredAccount>;+ /** Set when GH_TOKEN or a sibling overrides every stored login for this host. */+ readonly environmentVariable: string | null;+}++/** Groups gh's logins by host, in the order gh reported the hosts. */+export function groupGitHubAccounts(+ accounts: ReadonlyArray<GitHubDiscoveredAccount>,+): ReadonlyArray<GitHubHostGroup> {+ const hosts = [...new Set(accounts.map((entry) => entry.host))];+ return hosts.map((host) => {+ const entries = accounts.filter((entry) => entry.host === host);+ const stored = entries.filter((entry) => entry.environmentVariable === undefined);+ const selectable = stored.filter((entry) => entry.authenticated);+ return {+ host,+ activeAccount: (selectable.find((entry) => entry.active) ?? selectable[0])?.account ?? null,+ selectable: selectable.map((entry) => entry.account),+ broken: stored.filter((entry) => !entry.authenticated),+ environmentVariable:+ entries.find((entry) => entry.environmentVariable)?.environmentVariable ?? null,+ };+ });+}++/**+ * The full `hosts` map after one host changes. Hosts left on gh's defaults (enabled,+ * no pinned account) are dropped so settings only hold real choices.+ */+export function nextGitHubHosts(+ current: GitHubSettings["hosts"],+ host: string,+ change: { readonly enabled?: boolean; readonly account?: string | null },+): GitHubSettings["hosts"] {+ const previous = current[host];+ const enabled = change.enabled ?? previous?.enabled ?? true;+ const account = change.account === undefined ? previous?.account : (change.account ?? undefined);+ const { [host]: _replaced, ...rest } = current;+ if (enabled && account === undefined) return rest;+ return { ...rest, [host]: { enabled, ...(account === undefined ? {} : { account }) } };+}diff --git a/apps/web/src/components/settings/GitHubAccountSettings.tsx b/apps/web/src/components/settings/GitHubAccountSettings.tsxnew file mode 100644index 00000000000..98e7289b260--- /dev/null+++ b/apps/web/src/components/settings/GitHubAccountSettings.tsx@@ -0,0 +1,224 @@+import type { EnvironmentId, SourceControlProviderAuth } from "@t3tools/contracts";+import { EyeIcon, EyeOffIcon } from "lucide-react";+import { useState } from "react";++import { useEnvironmentSettings } from "../../hooks/useSettings";+import { serverEnvironment } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import { Button } from "../ui/button";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { Switch } from "../ui/switch";+import { groupGitHubAccounts, nextGitHubHosts } from "./GitHubAccountSettings.logic";+import { redactedPlaceholder } from "./RedactedSensitiveText";++/** Sentinel select value for "follow gh's active login"; logins never contain spaces. */+const ACTIVE_ACCOUNT = "active gh account";++/**+ * A login, blurred like RedactedSensitiveText until the panel reveals it. Plain text, not a+ * button, so it can sit inside select options; one panel toggle reveals every login.+ */+function RedactedLogin(props: {+ readonly account: string;+ readonly revealed: boolean;+ /** Distinguishes hidden logins from each other for a screen reader, e.g. "Account 2". */+ readonly label?: string;+}) {+ return props.revealed ? (+ <span className="min-w-0 truncate font-mono text-2xs">{props.account}</span>+ ) : (+ <span className="min-w-0 truncate font-mono text-2xs">+ <span className="select-none blur-xs" aria-hidden>+ {redactedPlaceholder(props.account)}+ </span>+ <span className="sr-only">{props.label ?? "Hidden account"}</span>+ </span>+ );+}++/**+ * Per-host GitHub choices for one environment: turn a host off, or pin which of the+ * logins `gh` holds is used instead of its active one. Changes save immediately.+ */+export function GitHubAccountSettings({+ environmentId,+ auth,+ onSaved,+}: {+ readonly environmentId: EnvironmentId;+ readonly auth: SourceControlProviderAuth;+ readonly onSaved: () => void;+}) {+ const hosts = useEnvironmentSettings(environmentId, (settings) => settings.github.hosts);+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {+ label: "save GitHub account settings",+ });+ const [saving, setSaving] = useState(false);+ const [revealed, setRevealed] = useState(false);+ const groups = groupGitHubAccounts(auth.accounts ?? []);++ const save = async (+ host: string,+ change: { readonly enabled?: boolean; readonly account?: string | null },+ ) => {+ setSaving(true);+ try {+ const result = await updateSettings({+ environmentId,+ input: { patch: { github: { hosts: nextGitHubHosts(hosts, host, change) } } },+ });+ if (result._tag === "Success") onSaved();+ } finally {+ setSaving(false);+ }+ };++ if (groups.length === 0) {+ return (+ <p className="text-xs text-muted-foreground">+ Sign in with <code className="rounded bg-muted px-1 py-px text-2xs">gh auth login</code> on+ the server host, then rescan to choose accounts here.+ </p>+ );+ }++ return (+ <div className="grid gap-4">+ <div className="flex items-center justify-between gap-3">+ <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">+ Choose which <code className="rounded bg-muted px-1 py-px text-2xs">gh</code> login each+ GitHub host uses, or turn a host off.+ </p>+ <Button+ size="icon-xs"+ variant="ghost-muted"+ onClick={() => setRevealed((current) => !current)}+ aria-label={revealed ? "Hide GitHub accounts" : "Reveal GitHub accounts"}+ aria-pressed={revealed}+ >+ {revealed ? <EyeOffIcon /> : <EyeIcon />}+ </Button>+ </div>+ {groups.map((group) => {+ const choice = hosts[group.host];+ const enabled = choice?.enabled ?? true;+ const stalePin =+ choice?.account !== undefined && !group.selectable.includes(choice.account);+ const pinned = choice?.account !== undefined && !stalePin ? choice.account : ACTIVE_ACCOUNT;+ return (+ <div key={group.host} className="grid gap-2">+ <div className="flex items-center justify-between gap-3">+ <div className="min-w-0 space-y-0.5">+ <span className="text-xs font-medium text-foreground">{group.host}</span>+ {group.selectable.length === 1 && group.selectable[0] !== undefined ? (+ <p className="flex min-w-0 items-center gap-1 text-xs text-muted-foreground">+ <span>Signed in as</span>+ <RedactedLogin revealed={revealed} account={group.selectable[0]} />+ </p>+ ) : null}+ </div>+ <Switch+ checked={enabled}+ disabled={saving}+ aria-label={`Use GitHub on ${group.host}`}+ onCheckedChange={(checked) => void save(group.host, { enabled: checked })}+ />+ </div>+ {group.selectable.length > 1 ? (+ <div className="flex items-center justify-between gap-3">+ <span className="text-xs text-muted-foreground">Account</span>+ <div className="w-64 max-w-full">+ <Select+ value={pinned}+ disabled={saving || !enabled}+ onValueChange={(value) => {+ if (typeof value !== "string") return;+ void save(group.host, {+ account: value === ACTIVE_ACCOUNT ? null : value,+ });+ }}+ >+ <SelectTrigger size="sm" aria-label={`GitHub account for ${group.host}`}>+ <SelectValue>+ {(value: string) =>+ value === ACTIVE_ACCOUNT ? (+ <span className="flex min-w-0 items-center gap-1">+ Active gh account+ {group.activeAccount ? (+ <>+ (+ <RedactedLogin+ revealed={revealed}+ account={group.activeAccount}+ />+ )+ </>+ ) : null}+ </span>+ ) : (+ <RedactedLogin revealed={revealed} account={value} />+ )+ }+ </SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ <SelectItem value={ACTIVE_ACCOUNT}>+ <span className="flex min-w-0 items-center gap-1">+ Active gh account+ {group.activeAccount ? (+ <>+ (<RedactedLogin revealed={revealed} account={group.activeAccount} />)+ </>+ ) : null}+ </span>+ </SelectItem>+ {group.selectable.map((account, index) => (+ <SelectItem key={account} value={account}>+ <RedactedLogin+ revealed={revealed}+ account={account}+ label={`Account ${index + 1}`}+ />+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>+ </div>+ ) : null}+ {stalePin ? (+ <div className="flex items-center justify-between gap-3">+ <p className="text-xs text-warning">+ The chosen login is no longer signed in, so the active gh login is used.+ </p>+ <Button+ size="xs"+ variant="outline"+ disabled={saving}+ onClick={() => void save(group.host, { account: null })}+ >+ Use active login+ </Button>+ </div>+ ) : null}+ {group.broken.map((entry) => (+ <p+ key={entry.account}+ className="flex min-w-0 flex-wrap items-center gap-1 text-xs text-muted-foreground/70"+ >+ <RedactedLogin revealed={revealed} account={entry.account} />+ <span>can't be used: {entry.error ?? "gh reports this login as invalid."}</span>+ </p>+ ))}+ {group.environmentVariable ? (+ <p className="text-xs text-warning">+ {group.environmentVariable} is set on the server, so it overrides the account chosen+ here until it is unset.+ </p>+ ) : null}+ </div>+ );+ })}+ </div>+ );+}diff --git a/apps/web/src/components/settings/GitHubTokenSettings.tsx b/apps/web/src/components/settings/GitHubTokenSettings.tsxnew file mode 100644index 00000000000..80ad552f15b--- /dev/null+++ b/apps/web/src/components/settings/GitHubTokenSettings.tsx@@ -0,0 +1,138 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { ExternalLinkIcon } from "lucide-react";+import { useState } from "react";++import { useEnvironmentSettings } from "../../hooks/useSettings";+import { serverEnvironment } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import { Button, InlineButton } from "../ui/button";+import { Input } from "../ui/input";+import { Label } from "../ui/label";++const DEFAULT_HOST = "github.com";++/** Where to create a token for a host: GitHub's own page, or the same path on an Enterprise host. */+function newTokenUrl(host: string): string {+ return `https://${host}/settings/personal-access-tokens/new`;+}++/**+ * A GitHub token for one host, kept in the server's secret store. It is used before+ * `GH_TOKEN` and the `gh` login, so it also works on a server without `gh` installed.+ * Write-only: the saved token is never shown, only whether one is set.+ */+export function GitHubTokenSettings({+ environmentId,+ onSaved,+}: {+ readonly environmentId: EnvironmentId;+ readonly onSaved: () => void;+}) {+ const tokens = useEnvironmentSettings(environmentId, (settings) => settings.github.tokens);+ const updateSettings = useAtomCommand(serverEnvironment.updateSettings, {+ label: "save GitHub token",+ });+ const [host, setHost] = useState(DEFAULT_HOST);+ const [draft, setDraft] = useState("");+ const [saving, setSaving] = useState(false);+ const normalizedHost = host.trim().toLowerCase();+ const isSaved = (tokens[normalizedHost] ?? "").length > 0;+ const savedHosts = Object.entries(tokens)+ .filter(([, value]) => value.length > 0)+ .map(([saved]) => saved);++ const save = async (target: string, token: string) => {+ setSaving(true);+ try {+ const result = await updateSettings({+ environmentId,+ input: { patch: { github: { tokens: { [target]: token } } } },+ });+ if (result._tag === "Success") {+ setDraft("");+ onSaved();+ }+ } finally {+ setSaving(false);+ }+ };++ return (+ <form+ className="grid gap-3"+ onSubmit={(event) => {+ event.preventDefault();+ if (normalizedHost && draft.trim()) void save(normalizedHost, draft.trim());+ }}+ >+ {/* Locked while saving: a successful save clears the draft, which would drop edits made mid-request. */}+ <fieldset disabled={saving} className="contents">+ <p className="max-w-2xl text-xs leading-relaxed text-muted-foreground">+ A token saved here is used before{" "}+ <code className="rounded bg-muted px-1 py-px text-2xs">GH_TOKEN</code> and the{" "}+ <code className="rounded bg-muted px-1 py-px text-2xs">gh</code> login, so GitHub works+ without the GitHub CLI. Give it read and write access to pull requests and contents.{" "}+ <InlineButton+ render={+ <a+ href={newTokenUrl(normalizedHost || DEFAULT_HOST)}+ target="_blank"+ rel="noreferrer noopener"+ />+ }+ >+ Create a token+ <ExternalLinkIcon aria-hidden className="size-3" />+ </InlineButton>+ </p>+ <div className="grid gap-3 sm:grid-cols-[12rem_1fr]">+ <div className="grid gap-1.5">+ <Label htmlFor={`github-token-host-${environmentId}`}>Host</Label>+ <Input+ id={`github-token-host-${environmentId}`}+ autoComplete="off"+ size="sm"+ placeholder={DEFAULT_HOST}+ value={host}+ onChange={(event) => setHost(event.target.value)}+ />+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor={`github-token-${environmentId}`}>Token</Label>+ <Input+ id={`github-token-${environmentId}`}+ type="password"+ autoComplete="off"+ size="sm"+ placeholder={isSaved ? "Stored secret, enter a new value to replace" : "Not set"}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ </div>+ </div>+ <div className="flex items-center justify-between gap-3">+ <p className="text-xs text-muted-foreground">+ {savedHosts.length === 0+ ? "No token saved; the server uses GH_TOKEN or the gh login."+ : `Saved for ${savedHosts.join(", ")}.`}+ </p>+ <div className="flex shrink-0 gap-2">+ {isSaved ? (+ <Button+ size="xs"+ variant="outline"+ disabled={saving}+ onClick={() => void save(normalizedHost, "")}+ >+ Remove+ </Button>+ ) : null}+ <Button type="submit" size="xs" disabled={!normalizedHost || !draft.trim() || saving}>+ Save+ </Button>+ </div>+ </div>+ </fieldset>+ </form>+ );+}diff --git a/apps/web/src/components/settings/RedactedSensitiveText.tsx b/apps/web/src/components/settings/RedactedSensitiveText.tsxindex 4ae2276b8e6..46f0897db34 100644--- a/apps/web/src/components/settings/RedactedSensitiveText.tsx+++ b/apps/web/src/components/settings/RedactedSensitiveText.tsx@@ -5,7 +5,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";const REDACTED_TEXT_ALPHABET = "abcdefghjkmnpqrstuvwxyz23456789";-function redactedPlaceholder(value: string): string {+export function redactedPlaceholder(value: string): string {let state = 0x811c9dc5;for (let index = 0; index < value.length; index += 1) {state ^= value.charCodeAt(index);diff --git a/apps/web/src/components/settings/SourceControlSettings.tsx b/apps/web/src/components/settings/SourceControlSettings.tsxindex 9fba0edc7d4..978d7a57105 100644--- a/apps/web/src/components/settings/SourceControlSettings.tsx+++ b/apps/web/src/components/settings/SourceControlSettings.tsx@@ -57,6 +57,8 @@ import {type Icon,} from "../Icons";import { BitbucketCredentialsSettings } from "./BitbucketCredentialsSettings";+import { GitHubAccountSettings } from "./GitHubAccountSettings";+import { GitHubTokenSettings } from "./GitHubTokenSettings";import { RedactedSensitiveText } from "./RedactedSensitiveText";import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";import {@@ -222,6 +224,9 @@ function itemSummary({if (auth) {if (auth.status === "authenticated") {+ // The server names the account its requests use, Settings choice included, and+ // says when an environment token overrides it.+ const authDetail = optionLabel(auth.detail);return (<><span>Authenticated</span>@@ -231,6 +236,7 @@ function itemSummary({<RedactedAccount account={authAccount} /></>) : null}+ {authDetail ? <span>· {authDetail}</span> : null}</>);}@@ -241,6 +247,11 @@ function itemSummary({return <span>Available. {item.installHint}</span>;}+ // Signed in, but every login is turned off here: the fix is the switch below, not the CLI.+ if (auth.status === "unauthenticated" && auth.accounts?.some((entry) => entry.authenticated)) {+ return <span>{optionLabel(auth.detail) ?? `Every ${item.label} host is turned off.`}</span>;+ }+if (auth.status === "unauthenticated") {return (<span>@@ -283,7 +294,8 @@ function DiscoveryItemRow({if ((item.kind === "git" && searchTargetId === searchableSetting("git-fetch-interval").id) ||(item.kind === "bitbucket" &&- searchTargetId === searchableSetting("bitbucket-credentials").id)+ searchTargetId === searchableSetting("bitbucket-credentials").id) ||+ (item.kind === "github" && searchTargetId === searchableSetting("github-accounts").id)) {setIsExpanded(true);}@@ -603,6 +615,25 @@ export function SourceControlSettingsPanel() {onSaved={handleScan}/></SettingsSearchTarget>+ ) : item.kind === "github" ? (+ <SettingsSearchTarget id={searchableSetting("github-accounts").id}>+ <div className="grid gap-6">+ {/* Shown even without gh: a saved token is how GitHub works without the CLI. */}+ <GitHubTokenSettings+ key={`token-${environmentId}`}+ environmentId={environmentId}+ onSaved={handleScan}+ />+ {item.status === "available" ? (+ <GitHubAccountSettings+ key={environmentId}+ environmentId={environmentId}+ auth={item.auth}+ onSaved={handleScan}+ />+ ) : null}+ </div>+ </SettingsSearchTarget>) : undefined}</DiscoveryItemRow>))}diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex 4797c9b64dd..18b2fe5a30a 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -751,6 +751,16 @@ export const SETTINGS_SEARCH_ITEMS = [environmentOnly: true,scope: "project-defaults",},+ {+ id: "github-accounts",+ title: "GitHub accounts and token",+ to: "/settings/source-control",+ searchTerms: [+ "github gh account login user host enterprise ghes switch multiple accounts disable sign in token personal access token pat api key credential",+ ],+ environmentOnly: true,+ scope: "environment-defaults",+ },{id: "bitbucket-credentials",title: "Bitbucket credentials",diff --git a/docs/user/source-control.md b/docs/user/source-control.mdindex d5ffeb0b477..03c360ff3a1 100644--- a/docs/user/source-control.md+++ b/docs/user/source-control.md@@ -11,11 +11,18 @@ and choose **Rescan**.### GitHub-Install [GitHub CLI](https://cli.github.com/) 2.81.0 or newer, then sign in:+T3 Code talks to GitHub's API directly and only needs a token. Any of these works, in this+order of precedence:-```bash-gh auth login-```+1. A token saved in **Settings → Source Control → GitHub**. It is kept in the server's secret+ store, and works without the GitHub CLI.+2. `GH_TOKEN` (`GH_ENTERPRISE_TOKEN` with `GH_HOST` for GitHub Enterprise Server) in the+ server's environment.+3. [GitHub CLI](https://cli.github.com/) 2.81.0 or newer, signed in with `gh auth login`.++If `gh` is signed in to several accounts or hosts, expand **GitHub** in the same place to pick+the account each host uses or turn a host off. A saved token or `GH_TOKEN` takes precedence+over that choice; a host turned off stays off either way.### Forgejo and Gitea@@ -136,7 +143,7 @@ environment clears its permission.GitHub review details, linked PR status, and permitted review actions can then use anotherconnected environment signed in to the same GitHub account. Each needs a project on that host.A connected local environment is preferred for actions and can answer slow or failed reads.-Browsers and mobile clients need a paired environment to use its GitHub CLI credentials.+Browsers and mobile clients need a paired environment to use its GitHub credentials.Credentials stay on their machines. Previously verified credentials remain usable for routingfor ten minutes during a GitHub outage; new credentials must be verified first. An action withan uncertain result is never automatically retried elsewhere. Listings, diffs, and checkout or@@ -164,7 +171,7 @@ does not show its diff, so marks are made and read on web and desktop.- **Not authenticated:** run the provider's login command on the server, then rescan. For Bitbucket,check the credentials saved in Settings → Source Control, or confirm the running server receivedthe environment variables.-- **GitHub sign-in cannot be verified:** update GitHub CLI to at least 2.81.0.+- **GitHub sign-in cannot be verified:** update GitHub CLI to at least 2.81.0, or save a token in Settings → Source Control.- **Push fails despite a connected account:** check the Git remote's credentials. SSH and HTTPSremotes can require separate setup from the hosting provider's API access.- **A review cannot load:** open it on the host website while resolving connectivity, permissions,diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.tsindex 68cdfc43e40..2cd0e45cc8e 100644--- a/packages/contracts/src/pullRequest.ts+++ b/packages/contracts/src/pullRequest.ts@@ -1264,16 +1264,17 @@ export type PullRequestUnavailableReason = typeof PullRequestUnavailableReason.T/*** What each host needs before it can be read, so a failure names the fix rather than the- * symptom. Bitbucket is credentials on the server rather than a signed-in CLI, which is why- * these are whole sentences instead of a tool name to interpolate.+ * symptom. The reason names keep their `cli-` prefix for wire compatibility; for GitHub and+ * Bitbucket they mean "no credential" and "a refused credential", not a missing tool.*/const PROVIDER_REQUIREMENT: Partial<Record<SourceControlProviderKind, { readonly missing: string; readonly unauthenticated: string }>> = {github: {missing:- "GitHub CLI (`gh`) is required to browse change requests on this host. Install it from https://cli.github.com/ and reload.",- unauthenticated: "GitHub CLI is not authenticated. Run `gh auth login` and retry.",+ "No GitHub credential on the server. Set GH_TOKEN, or install the GitHub CLI (https://cli.github.com/) and run `gh auth login`.",+ unauthenticated:+ "GitHub has no working credential for this host. Run `gh auth login`, or check the account and hosts in Settings → Source Control.",},forgejo: {missing:diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.tsindex 20fc7b7ddd3..419db85883b 100644--- a/packages/contracts/src/settings.test.ts+++ b/packages/contracts/src/settings.test.ts@@ -987,6 +987,13 @@ describe("ServerSettingsPatch.providerInstances", () => {});describe("ServerSettingsPatch string normalization", () => {+ it("lowercases GitHub hosts and defaults them to enabled", () => {+ const patch = decodeServerSettingsPatch({+ github: { hosts: { " GitHub.com ": { account: " work " } } },+ });+ expect(patch.github?.hosts).toEqual({ "github.com": { account: "work", enabled: true } });+ });+it("trims string settings while decoding patches", () => {const patch = decodeServerSettingsPatch({addProjectBaseDirectory: " ~/Development ",diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex 7e73079a58d..7984ca20b57 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -1013,6 +1013,37 @@ export const BitbucketSettings = Schema.Struct({});export type BitbucketSettings = typeof BitbucketSettings.Type;+/**+ * Per-host choices for the GitHub CLI's logins. `account` pins one of the logins+ * `gh` holds for the host instead of its active one; a disabled host gets no+ * credential at all. A token saved here wins over `GH_TOKEN` and friends, which win over `gh`.+ */+/** A GitHub host name, lowercased on decode so `GitHub.com` and `github.com` are one entry. */+export const GitHubHost = TrimmedNonEmptyString.pipe(+ Schema.decodeTo(Schema.String, SchemaTransformation.toLowerCase()),+);++export const GitHubHostSettings = Schema.Struct({+ account: Schema.optionalKey(TrimmedNonEmptyString),+ enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),+});+export type GitHubHostSettings = typeof GitHubHostSettings.Type;++export const GitHubSettings = Schema.Struct({+ /** Keyed by lowercased host, for example `github.com`. */+ hosts: Schema.Record(GitHubHost, GitHubHostSettings).pipe(+ Schema.withDecodingDefault(Effect.succeed({})),+ ),+ /**+ * A token per host, used before `GH_TOKEN` and `gh`. The server keeps each one in its secret+ * store; settings and clients only ever see a redaction marker for a saved token.+ */+ tokens: Schema.Record(GitHubHost, TrimmedString).pipe(+ Schema.withDecodingDefault(Effect.succeed({})),+ ),+});+export type GitHubSettings = typeof GitHubSettings.Type;+export const ObservabilitySettings = Schema.Struct({otlpTracesUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),otlpMetricsUrl: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),@@ -1423,6 +1454,7 @@ export const ServerSettings = Schema.Struct({),observability: ObservabilitySettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),bitbucket: BitbucketSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),+ github: GitHubSettings.pipe(Schema.withDecodingDefault(Effect.succeed({}))),// Keyed by a user-chosen id so a source keeps its rows across edits. Entries// this build cannot decode round-trip untouched, as provider instances do.usageLimitSources: Schema.Record(UsageLimitSourceId, UsageLimitSourceConfig).pipe(@@ -1714,6 +1746,16 @@ export const ServerSettingsPatch = Schema.Struct({apiToken: Schema.optionalKey(TrimmedString),}),),+ /**+ * `hosts` replaces the whole map, so an omitted host or account clears it. `tokens` merges per+ * host: an empty token removes that host's token, the redaction marker keeps it.+ */+ github: Schema.optionalKey(+ Schema.Struct({+ hosts: Schema.optionalKey(Schema.Record(GitHubHost, GitHubHostSettings)),+ tokens: Schema.optionalKey(Schema.Record(GitHubHost, TrimmedString)),+ }),+ ),providers: Schema.optionalKey(Schema.Struct({codex: Schema.optionalKey(CodexSettingsPatch),diff --git a/packages/contracts/src/sourceControl.ts b/packages/contracts/src/sourceControl.tsindex b0d2bd4a75b..f9717b45c4c 100644--- a/packages/contracts/src/sourceControl.ts+++ b/packages/contracts/src/sourceControl.ts@@ -123,6 +123,20 @@ export const SourceControlProviderAuth = Schema.Struct({account: Schema.Option(TrimmedNonEmptyString),host: Schema.Option(TrimmedNonEmptyString),detail: Schema.Option(TrimmedNonEmptyString),+ /** Every login the provider CLI holds, across hosts. Only GitHub reports these today. */+ accounts: Schema.optionalKey(+ Schema.Array(+ Schema.Struct({+ host: TrimmedNonEmptyString,+ account: TrimmedNonEmptyString,+ active: Schema.Boolean,+ authenticated: Schema.Boolean,+ error: Schema.optionalKey(TrimmedNonEmptyString),+ /** Set when the login comes from a token variable such as `GH_TOKEN`, which wins over Settings. */+ environmentVariable: Schema.optionalKey(TrimmedNonEmptyString),+ }),+ ),+ ),});export type SourceControlProviderAuth = typeof SourceControlProviderAuth.Type;diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.tsindex fb25119cadc..f7305812e74 100644--- a/packages/shared/src/serverSettings.test.ts+++ b/packages/shared/src/serverSettings.test.ts@@ -41,6 +41,17 @@ describe("serverSettings helpers", () => {logsAfterDays: 30,});});+ it("replaces GitHub host choices so a cleared account pin does not survive", () => {+ const pinned = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, {+ github: { hosts: { "github.com": { account: "work", enabled: true } } },+ });+ expect(pinned.github.hosts).toEqual({ "github.com": { account: "work", enabled: true } });+ expect(+ applyServerSettingsPatch(pinned, {+ github: { hosts: { "github.com": { enabled: false } } },+ }).github.hosts,+ ).toEqual({ "github.com": { enabled: false } });+ });it("replaces SSH host lists when saving, editing, and removing hosts", () => {const host = { id: "mini", label: "Mac mini", target: "mini" };const saved = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { deviceHosts: [host] });diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.tsindex aabc3612c98..5e66b0ebe33 100644--- a/packages/shared/src/serverSettings.ts+++ b/packages/shared/src/serverSettings.ts@@ -378,6 +378,10 @@ export function applyServerSettingsPatch(],}: {}),+ // Host replacement: deepMerge would keep a cleared account pin.+ ...(patch.github?.hosts !== undefined+ ? { github: { ...next.github, hosts: patch.github.hosts } }+ : {}),...(projectSettingsOverridesPatch !== undefined? {projectSettingsOverrides: Object.fromEntries(