Skip to content

Commit 33d27e9

Browse files
shivamhwpPR Batch Testerclaude
authored
fix(server): Pull Requests says which GitHub credential cannot see a repository (#24350)
Co-authored-by: PR Batch Tester <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 5b357b3 commit 33d27e9

8 files changed

Lines changed: 277 additions & 60 deletions

File tree

‎apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx‎

Lines changed: 39 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { useAtomValue } from "@effect/atom-react";
1111
import {
1212
Keyboard,
1313
Platform,
14+
Pressable,
1415
RefreshControl,
1516
ScrollView,
1617
View,
@@ -20,6 +21,7 @@ import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeS
2021
import { useSafeAreaInsets } from "react-native-safe-area-context";
2122

2223
import { AppText as Text } from "../../components/ui/AppText";
24+
import { SymbolView } from "../../components/ui/AppSymbol";
2325
import { EmptyState } from "../../components/ui/EmptyState";
2426
import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
2527
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
@@ -32,7 +34,6 @@ import {
3234
usePullRequestListFilters,
3335
type PullRequestFilterMenu,
3436
} from "./PullRequestListFilters";
35-
import { PullRequestCardRow } from "./PullRequestControls";
3637
import { usePullRequestList } from "./usePullRequestList";
3738
import { usePullRequestListControls } from "./usePullRequestListControls";
3839
import { usePullRequestListActions } from "./usePullRequestListActions";
@@ -58,26 +59,38 @@ function PullRequestScrollView(props: ScrollViewProps) {
5859
);
5960
}
6061

61-
function PullRequestListErrors(props: { readonly messages: readonly string[] }) {
62+
function PullRequestListError(props: { readonly message: string }) {
6263
const [expanded, setExpanded] = useState(false);
63-
const title = `${props.messages.length} ${props.messages.length === 1 ? "error" : "errors"} loading pull requests`;
6464
return (
65-
<View>
66-
<PullRequestCardRow
67-
title={title}
68-
icon="exclamationmark.triangle"
69-
compact
70-
last
71-
expanded={expanded}
72-
accessibilityLabel={`${title}. ${expanded ? "Hide" : "Show"} details`}
73-
onPress={() => setExpanded((value) => !value)}
65+
<Pressable
66+
accessibilityRole="button"
67+
accessibilityLabel={props.message}
68+
accessibilityState={{ expanded }}
69+
onPress={() => setExpanded((value) => !value)}
70+
// A long press selects the text; collapsing under that selection crashes Android's
71+
// smart-select animation, so it must not also count as a press.
72+
onLongPress={() => undefined}
73+
className="min-h-11 flex-row items-center gap-3 px-4 py-2.5 active:opacity-70"
74+
>
75+
<SymbolView
76+
name="exclamationmark.triangle"
77+
size={18}
78+
tintColorClassName="accent-icon-muted"
7479
/>
75-
{expanded ? (
76-
<Text selectable className="px-4 pb-3 text-sm text-foreground-muted">
77-
{props.messages.join("\n")}
78-
</Text>
79-
) : null}
80-
</View>
80+
<Text
81+
selectable={expanded}
82+
numberOfLines={expanded ? undefined : 1}
83+
ellipsizeMode="tail"
84+
className="min-w-0 flex-1 text-sm text-foreground-muted"
85+
>
86+
{props.message}
87+
</Text>
88+
<SymbolView
89+
name={expanded ? "chevron.up" : "chevron.down"}
90+
size={11}
91+
tintColorClassName="accent-icon-muted"
92+
/>
93+
</Pressable>
8194
);
8295
}
8396

@@ -334,13 +347,14 @@ export function PullRequestsScreen(
334347
<>
335348
<PullRequestListFilters sidebar={sidebar} filters={filters} />
336349
{result.data?.errors.length ? (
337-
<PullRequestListErrors
338-
key={JSON.stringify(targets)}
339-
messages={result.data.errors.map(
340-
(error) =>
341-
`${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`,
342-
)}
343-
/>
350+
<View key={JSON.stringify(targets)}>
351+
{result.data.errors.map((error) => (
352+
<PullRequestListError
353+
key={`${error.environmentId} ${error.projectTitle} ${error.message}`}
354+
message={`${error.projectTitle || environments.find((environment) => environment.environmentId === error.environmentId)?.environmentLabel || "Environment"}: ${error.message}`}
355+
/>
356+
))}
357+
</View>
344358
) : null}
345359
</>
346360
}

‎apps/server/src/pullRequest/PullRequestService.ts‎

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1359,19 +1359,24 @@ export const make = Effect.gen(function* () {
13591359
: null,
13601360
};
13611361
}),
1362-
Effect.orElseSucceed((): RepositoryBatch => ({
1363-
key,
1364-
entries: [],
1365-
errors: [
1366-
{
1367-
projectId: project.project.id,
1368-
projectTitle: project.project.title,
1369-
message: `${project.repository} could not be read.`,
1370-
},
1371-
],
1372-
truncated: false,
1373-
nextCursor: null,
1374-
})),
1362+
Effect.catch((error): Effect.Effect<RepositoryBatch> =>
1363+
Effect.succeed({
1364+
key,
1365+
entries: [],
1366+
errors: [
1367+
{
1368+
projectId: project.project.id,
1369+
projectTitle: project.project.title,
1370+
message:
1371+
error.accessHint === undefined
1372+
? `${project.repository} could not be read.`
1373+
: `${project.repository} could not be read. ${error.accessHint}`,
1374+
},
1375+
],
1376+
truncated: false,
1377+
nextCursor: null,
1378+
}),
1379+
),
13751380
);
13761381
}
13771382
};

‎packages/source-control-core/src/server/PullRequestProvider.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ export class PullRequestProviderError extends Schema.TaggedError<PullRequestProv
5353
]),
5454
detail: Schema.String,
5555
retryAt: Schema.optional(Schema.Number),
56+
/**
57+
* Why the host would not return a repository and what to change, in the reader's terms.
58+
* Shown beside that repository in the list; `detail` is about the failed call instead.
59+
*/
60+
accessHint: Schema.optional(Schema.String),
5661
cause: Schema.optional(Schema.Defect()),
5762
},
5863
) {
@@ -69,6 +74,7 @@ export interface ProviderChangeRequestWatchFingerprint {
6974
export interface PullRequestProviderFailure {
7075
readonly reason: PullRequestProviderError["reason"];
7176
readonly retryAt?: number | undefined;
77+
readonly accessHint?: string | undefined;
7278
}
7379

7480
export interface ProviderChangeRequest {

‎packages/source-control-github/src/server/GitHubPullRequestApi.test.ts‎

Lines changed: 117 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
55
import * as Deferred from "effect/Deferred";
66
import * as Fiber from "effect/Fiber";
77
import * as Layer from "effect/Layer";
8+
import * as Option from "effect/Option";
89
import * as Result from "effect/Result";
910
import * as Schema from "effect/Schema";
1011
import * as TestClock from "effect/testing/TestClock";
@@ -29,6 +30,9 @@ const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
2930
token: () => Effect.succeedNone,
3031
invalidate: () => Effect.void,
3132
});
33+
const mockedAppToken = vi.fn<(host: string) => Effect.Effect<Option.Option<string>>>(
34+
() => Effect.succeedNone,
35+
);
3236

3337
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
3438

@@ -111,7 +115,12 @@ type ApiAnswer = Effect.Effect<GitHubRest.GitHubRestResponse, GitHubRequestPolic
111115
const mockedExecute = vi.fn<(call: ApiCall) => ApiAnswer>();
112116
const defaultCredential = (host: string) =>
113117
Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:token` });
114-
const mockedCredential = vi.fn(defaultCredential);
118+
const mockedCredential =
119+
vi.fn<
120+
(
121+
host: string,
122+
) => Effect.Effect<GitHubRequestPolicy.GitHubHeldCredential, GitHubRequestPolicy.GitHubApiError>
123+
>(defaultCredential);
115124
const mockedStackMemberships = vi.fn<(call: ApiCall) => ApiAnswer>(() =>
116125
Effect.succeed(output('{"data":{}}')),
117126
);
@@ -180,14 +189,23 @@ const layer = it.layer(
180189
Layer.provideMerge(GitHubAppAccess.layer),
181190
Layer.provideMerge(mockApi),
182191
Layer.provideMerge(GitHubRequestPolicy.layer),
183-
Layer.provideMerge(appSignedOut),
192+
Layer.provideMerge(
193+
Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
194+
enabled: false,
195+
token: (host) => mockedAppToken(host),
196+
invalidate: () => Effect.void,
197+
}),
198+
),
184199
Layer.provideMerge(GitHubQuota.layer),
185200
Layer.provideMerge(SourceControlRateLimit.layer),
186201
Layer.provideMerge(mockHttp),
187202
Layer.provideMerge(
188203
Layer.succeed(GitHubCredentials.GitHubCredentials, {
189204
get: (host) =>
190-
Effect.map(mockedCredential(host), (held) => ({ ...held, host, source: "gh" as const })),
205+
mockedCredential(host).pipe(
206+
Effect.map((held) => ({ source: "gh" as const, ...held, host })),
207+
Effect.mapError(() => new GitHubCredentials.GitHubCliMissingError({ host })),
208+
),
191209
saved: () => Effect.succeedNone,
192210
fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
193211
invalidate: () => Effect.void,
@@ -617,6 +635,7 @@ afterEach(() => {
617635
mockedExecute.mockReset();
618636
mockedStackMemberships.mockReset();
619637
mockedCredential.mockReset();
638+
mockedAppToken.mockReset();
620639
mockedCredential.mockImplementation(defaultCredential);
621640
});
622641

@@ -1276,6 +1295,101 @@ layer("GitHubPullRequestApi.layer", (it) => {
12761295
}),
12771296
);
12781297

1298+
/**
1299+
* Lists a repository GitHub will not return, answering credential lookups in turn (the last
1300+
* answer repeats; `undefined` is no credential), and returns the error with the tokens sent.
1301+
*/
1302+
const listUnreadableRepository = (
1303+
...lookups: ReadonlyArray<
1304+
| { readonly token: string; readonly source: GitHubCredentials.GitHubCredentialSource }
1305+
| undefined
1306+
>
1307+
) => {
1308+
mockedExecute.mockClear();
1309+
let lookup = 0;
1310+
mockedCredential.mockImplementation((host) =>
1311+
Effect.suspend(() => {
1312+
const held = lookups[Math.min(lookup++, lookups.length - 1)];
1313+
return held === undefined
1314+
? Effect.fail(
1315+
new GitHubRequestPolicy.GitHubApiAuthenticationError({
1316+
host,
1317+
operation: "credential",
1318+
}),
1319+
)
1320+
: Effect.succeed({
1321+
token: Redacted.make(held.token),
1322+
fingerprint: `${host}:${held.token}`,
1323+
source: held.source,
1324+
});
1325+
}),
1326+
);
1327+
route(
1328+
["PullRequestSearch", { data: { search: { pageInfo: lastPage, nodes: [] } } }],
1329+
[
1330+
"PullRequestList",
1331+
{
1332+
data: { repository: null },
1333+
errors: [
1334+
{
1335+
type: "NOT_FOUND",
1336+
path: ["repository"],
1337+
message: "Could not resolve to a Repository with the name 'acme/private'.",
1338+
},
1339+
],
1340+
},
1341+
],
1342+
);
1343+
return GitHubPullRequestProvider.make.pipe(
1344+
Effect.flatMap((provider) =>
1345+
Effect.flip(
1346+
provider.listChangeRequests({
1347+
cwd: "/w",
1348+
repository: "acme/private",
1349+
host: "github.com",
1350+
state: "open",
1351+
involvement: "all",
1352+
viewer: "bilal",
1353+
limit: 10,
1354+
}),
1355+
),
1356+
),
1357+
Effect.map((error) => ({
1358+
error,
1359+
sentWith: mockedExecute.mock.calls.map(([call]) =>
1360+
call.kind === "graphql" ? call.authorization : undefined,
1361+
),
1362+
})),
1363+
);
1364+
};
1365+
1366+
it.effect("names the credential GitHub would not return a repository to", () =>
1367+
Effect.gen(function* () {
1368+
// The saved token is replaced mid-read; every request still goes out with the one named.
1369+
const saved = yield* listUnreadableRepository(
1370+
{ token: "first", source: "settings" },
1371+
{ token: "replaced", source: "settings" },
1372+
);
1373+
expect(saved.error.accessHint).toContain("saved GitHub token");
1374+
assert.isAbove(saved.sentWith.length, 1);
1375+
for (const authorization of saved.sentWith) expect(authorization).toContain("first");
1376+
1377+
// The policy hands what the app cannot see to the gh login, which GitHub refuses too.
1378+
mockedAppToken.mockReturnValue(Effect.succeedSome("app"));
1379+
const app = { token: "app", source: "app" } as const;
1380+
const gh = { token: "personal", source: "gh" } as const;
1381+
const retried = yield* listUnreadableRepository(app, gh);
1382+
expect(retried.error.accessHint).toContain("gh login");
1383+
expect(retried.sentWith).toEqual(["Bearer app", "Bearer app", "Bearer personal"]);
1384+
1385+
// With no gh login when the app is refused, the app made the last request; a login that
1386+
// turns up afterwards is not named.
1387+
const appOnly = yield* listUnreadableRepository(app, undefined, gh);
1388+
assert.isUndefined(appOnly.error.accessHint);
1389+
expect(appOnly.sentWith).toEqual(["Bearer app", "Bearer app"]);
1390+
}),
1391+
);
1392+
12791393
it.effect("carries every repository and every qualifier into one search", () =>
12801394
Effect.gen(function* () {
12811395
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));

‎packages/source-control-github/src/server/GitHubPullRequestApi.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1816,7 +1816,7 @@ export const make = Effect.gen(function* () {
18161816
);
18171817
// Unindexed repositories silently return no search rows; fall back to the repository listing.
18181818
const hasQuery = (input.query?.trim().length ?? 0) > 0;
1819-
return read(true).pipe(
1819+
const listed = read(true).pipe(
18201820
Effect.filterOrElse(
18211821
(batch) => batch.items.length > 0 || input.cursor !== undefined || hasQuery,
18221822
() => read(false),
@@ -1857,6 +1857,24 @@ export const make = Effect.gen(function* () {
18571857
),
18581858
),
18591859
);
1860+
// GitHub answers a private repository the token cannot see as missing, and its error names
1861+
// the credential that request carried. A personal credential is pinned for the whole
1862+
// read, so a token changed mid-read does not split it; the app keeps the policy's fallback.
1863+
const host = normalizeHost(input.host);
1864+
return api.credential(host).pipe(
1865+
Effect.flatMap(({ token, fingerprint, source }) =>
1866+
source === undefined || source === "app"
1867+
? listed
1868+
: listed.pipe(
1869+
Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
1870+
host,
1871+
token,
1872+
credentialFingerprint: fingerprint,
1873+
source,
1874+
}),
1875+
),
1876+
),
1877+
);
18601878
}),
18611879

18621880
searchPullRequests: Effect.fn("GitHubPullRequestApi.searchPullRequests")(function* (input) {

‎packages/source-control-github/src/server/GitHubPullRequestProvider.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
type PullRequestProviderApi,
2525
type ProviderRepositoryRef,
2626
} from "@t3tools/source-control-core/server/PullRequestProvider";
27+
import type { GitHubCredentialSource } from "./GitHubCredentials.ts";
2728
import type {
2829
GitHubRepositoryAccess,
2930
GitHubViewerAccess,
@@ -120,12 +121,21 @@ function gitHubProviderFailure(
120121
case "SourceControlRateLimitPausedError":
121122
return { reason: "rate-limited", retryAt: error.retryAt };
122123
case "GitHubApiNotFoundError":
123-
return { reason: "not-found" };
124+
return error.credential === undefined || error.credential === "app"
125+
? { reason: "not-found" }
126+
: { reason: "not-found", accessHint: REPOSITORY_ACCESS_HINTS[error.credential] };
124127
default:
125128
return { reason: "failed" };
126129
}
127130
}
128131

132+
const REPOSITORY_ACCESS_HINTS: Record<Exclude<GitHubCredentialSource, "app">, string> = {
133+
settings:
134+
"Your saved GitHub token can't see it. Give it access, or change it in Settings → Source Control.",
135+
env: "The server's environment token can't see it. Give it access, or unset it.",
136+
gh: "Your gh login can't see it. Give it access, or save a token in Settings → Source Control.",
137+
};
138+
129139
function withAvatar(
130140
actor: PullRequestActor | null,
131141
avatarsByLogin: ReadonlyMap<string, string>,

0 commit comments

Comments
 (0)