The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 12:00 UTC
fix(server): Pull Requests says which GitHub credential cannot see a repository (#24350)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
shivam committed
Oct 30, 2026 at 22:25 UTC
33d27e999a0728574bb34a47cfa56e9b84f3d99e
8 files changed
+277
-60
apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx
+39
-25
@@ -11,6 +11,7 @@ import { useAtomValue } from "@effect/atom-react";
11
import {
12
Keyboard,
13
Platform,
14
+ Pressable,
15
RefreshControl,
16
ScrollView,
17
View,
@@ -20,6 +21,7 @@ import { NativeScrollViewMarker as ScrollViewMarker } from "../../native/NativeS
21
import { useSafeAreaInsets } from "react-native-safe-area-context";
22
23
import { AppText as Text } from "../../components/ui/AppText";
24
+import { SymbolView } from "../../components/ui/AppSymbol";
25
import { EmptyState } from "../../components/ui/EmptyState";
26
import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
27
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
@@ -32,7 +34,6 @@ import {
34
usePullRequestListFilters,
35
type PullRequestFilterMenu,
36
} from "./PullRequestListFilters";
35
-import { PullRequestCardRow } from "./PullRequestControls";
37
import { usePullRequestList } from "./usePullRequestList";
38
import { usePullRequestListControls } from "./usePullRequestListControls";
39
import { usePullRequestListActions } from "./usePullRequestListActions";
@@ -58,26 +59,38 @@ function PullRequestScrollView(props: ScrollViewProps) {
59
);
60
}
61
61
-function PullRequestListErrors(props: { readonly messages: readonly string[] }) {
62
+function PullRequestListError(props: { readonly message: string }) {
63
const [expanded, setExpanded] = useState(false);
63
- const title = `${props.messages.length} ${props.messages.length === 1 ? "error" : "errors"} loading pull requests`;
64
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"
79
/>
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>
94
);
95
}
96
@@ -334,13 +347,14 @@ export function PullRequestsScreen(
347
<>
348
<PullRequestListFilters sidebar={sidebar} filters={filters} />
349
{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>
358
) : null}
359
</>
360
}
apps/server/src/pullRequest/PullRequestService.ts
+18
-13
@@ -1359,19 +1359,24 @@ export const make = Effect.gen(function* () {
1359
: null,
1360
};
1361
}),
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
+ ),
1380
);
1381
}
1382
};
packages/source-control-core/src/server/PullRequestProvider.ts
+6
@@ -53,6 +53,11 @@ export class PullRequestProviderError extends Schema.TaggedError<PullRequestProv
53
]),
54
detail: Schema.String,
55
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),
61
cause: Schema.optional(Schema.Defect()),
62
},
63
) {
@@ -69,6 +74,7 @@ export interface ProviderChangeRequestWatchFingerprint {
74
export interface PullRequestProviderFailure {
75
readonly reason: PullRequestProviderError["reason"];
76
readonly retryAt?: number | undefined;
77
+ readonly accessHint?: string | undefined;
78
}
79
80
export interface ProviderChangeRequest {
packages/source-control-github/src/server/GitHubPullRequestApi.test.ts
+117
-3
@@ -5,6 +5,7 @@ import * as Effect from "effect/Effect";
5
import * as Deferred from "effect/Deferred";
6
import * as Fiber from "effect/Fiber";
7
import * as Layer from "effect/Layer";
8
+import * as Option from "effect/Option";
9
import * as Result from "effect/Result";
10
import * as Schema from "effect/Schema";
11
import * as TestClock from "effect/testing/TestClock";
@@ -29,6 +30,9 @@ const appSignedOut = Layer.mock(GitHubAppSignIn.GitHubAppSignIn)({
30
token: () => Effect.succeedNone,
31
invalidate: () => Effect.void,
32
});
33
+const mockedAppToken = vi.fn<(host: string) => Effect.Effect<Option.Option<string>>>(
34
+ () => Effect.succeedNone,
35
+);
36
37
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
38
@@ -111,7 +115,12 @@ type ApiAnswer = Effect.Effect<GitHubRest.GitHubRestResponse, GitHubRequestPolic
115
const mockedExecute = vi.fn<(call: ApiCall) => ApiAnswer>();
116
const defaultCredential = (host: string) =>
117
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);
124
const mockedStackMemberships = vi.fn<(call: ApiCall) => ApiAnswer>(() =>
125
Effect.succeed(output('{"data":{}}')),
126
);
@@ -180,14 +189,23 @@ const layer = it.layer(
189
Layer.provideMerge(GitHubAppAccess.layer),
190
Layer.provideMerge(mockApi),
191
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
+ ),
199
Layer.provideMerge(GitHubQuota.layer),
200
Layer.provideMerge(SourceControlRateLimit.layer),
201
Layer.provideMerge(mockHttp),
202
Layer.provideMerge(
203
Layer.succeed(GitHubCredentials.GitHubCredentials, {
204
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
+ ),
209
saved: () => Effect.succeedNone,
210
fingerprint: (host, token) => Effect.succeed(`${host}:${token}`),
211
invalidate: () => Effect.void,
@@ -617,6 +635,7 @@ afterEach(() => {
635
mockedExecute.mockReset();
636
mockedStackMemberships.mockReset();
637
mockedCredential.mockReset();
638
+ mockedAppToken.mockReset();
639
mockedCredential.mockImplementation(defaultCredential);
640
});
641
@@ -1276,6 +1295,101 @@ layer("GitHubPullRequestApi.layer", (it) => {
1295
}),
1296
);
1297
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
+
1393
it.effect("carries every repository and every qualifier into one search", () =>
1394
Effect.gen(function* () {
1395
mockedExecute.mockReturnValue(Effect.succeed(searchPage([])));
packages/source-control-github/src/server/GitHubPullRequestApi.ts
+19
-1
@@ -1816,7 +1816,7 @@ export const make = Effect.gen(function* () {
1816
);
1817
// Unindexed repositories silently return no search rows; fall back to the repository listing.
1818
const hasQuery = (input.query?.trim().length ?? 0) > 0;
1819
- return read(true).pipe(
1819
+ const listed = read(true).pipe(
1820
Effect.filterOrElse(
1821
(batch) => batch.items.length > 0 || input.cursor !== undefined || hasQuery,
1822
() => read(false),
@@ -1857,6 +1857,24 @@ export const make = Effect.gen(function* () {
1857
),
1858
),
1859
);
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
+ );
1878
}),
1879
1880
searchPullRequests: Effect.fn("GitHubPullRequestApi.searchPullRequests")(function* (input) {
packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+11
-1
@@ -24,6 +24,7 @@ import {
24
type PullRequestProviderApi,
25
type ProviderRepositoryRef,
26
} from "@t3tools/source-control-core/server/PullRequestProvider";
27
+import type { GitHubCredentialSource } from "./GitHubCredentials.ts";
28
import type {
29
GitHubRepositoryAccess,
30
GitHubViewerAccess,
@@ -120,12 +121,21 @@ function gitHubProviderFailure(
121
case "SourceControlRateLimitPausedError":
122
return { reason: "rate-limited", retryAt: error.retryAt };
123
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] };
127
default:
128
return { reason: "failed" };
129
}
130
}
131
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
+
139
function withAvatar(
140
actor: PullRequestActor | null,
141
avatarsByLogin: ReadonlyMap<string, string>,
packages/source-control-github/src/server/GitHubRequestPolicy.ts
+45
-14
@@ -28,6 +28,7 @@ export const PinnedGitHubCredential = Context.Reference<{
28
readonly host: string;
29
readonly token: Redacted.Redacted<string>;
30
readonly credentialFingerprint: string;
31
+ readonly source?: GitHubCredentials.GitHubCredentialSource;
32
} | null>("@t3tools/source-control-github/server/GitHubRequestPolicy/PinnedGitHubCredential", {
33
defaultValue: () => null,
34
});
@@ -65,7 +66,12 @@ export class GitHubApiRateLimitError extends Schema.TaggedError<GitHubApiRateLim
66
67
export class GitHubApiNotFoundError extends Schema.TaggedError<GitHubApiNotFoundError>()(
68
"GitHubApiNotFoundError",
68
- { host: Schema.String, operation: Schema.String },
69
+ {
70
+ host: Schema.String,
71
+ operation: Schema.String,
72
+ /** The source of the credential the refused request carried, when known. */
73
+ credential: Schema.optionalKey(GitHubCredentials.GitHubCredentialSource),
74
+ },
75
) {
76
override get message(): string {
77
return "GitHub could not find the requested resource, or the credential cannot see it.";
@@ -193,10 +199,16 @@ export interface GitHubRequest {
199
export class GitHubRequestPolicy extends Context.Service<
200
GitHubRequestPolicy,
201
{
196
- /** send receives auth/version headers; its failures pass through unchanged. */
202
+ /**
203
+ * send receives auth/version headers and the source of the credential they carry; its
204
+ * failures pass through unchanged.
205
+ */
206
readonly request: <A, E, R>(
207
input: GitHubRequest,
199
- send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
208
+ send: (
209
+ headers: Readonly<Record<string, string>>,
210
+ source: GitHubCredentials.GitHubCredentialSource | undefined,
211
+ ) => Effect.Effect<GitHubAnswer<A>, E, R>,
212
) => Effect.Effect<A, E | GitHubApiError, R>;
213
/**
214
* The credential requests to `host` use: a token saved in Settings, else the app sign-in,
@@ -214,6 +226,7 @@ export class GitHubRequestPolicy extends Context.Service<
226
>()("@t3tools/source-control-github/server/GitHubRequestPolicy") {}
227
228
export interface GitHubHeldCredential {
229
+ readonly source?: GitHubCredentials.GitHubCredentialSource;
230
readonly token: Redacted.Redacted<string>;
231
readonly fingerprint: string;
232
}
@@ -255,6 +268,7 @@ export const make = Effect.gen(function* () {
268
Effect.map((held): ChosenCredential => ({
269
token: held.token,
270
fingerprint: held.fingerprint,
271
+ source: held.source,
272
fromApp: false,
273
})),
274
);
@@ -265,6 +279,7 @@ export const make = Effect.gen(function* () {
279
const token = yield* appSignIn.token(normalizeHost(host));
280
if (Option.isNone(token)) return Option.none();
281
return Option.some({
282
+ source: "app" as const,
283
token: Redacted.make(token.value),
284
fingerprint: yield* credentials.fingerprint(normalizeHost(host), token.value),
285
});
@@ -279,12 +294,18 @@ export const make = Effect.gen(function* () {
294
return {
295
token: pinned.token,
296
fingerprint: pinned.credentialFingerprint,
297
+ ...(pinned.source === undefined ? {} : { source: pinned.source }),
298
fromApp: false,
299
} satisfies ChosenCredential;
300
}
301
const saved = yield* credentials.saved(host);
302
if (Option.isSome(saved)) {
287
- return { token: saved.value.token, fingerprint: saved.value.fingerprint, fromApp: false };
303
+ return {
304
+ token: saved.value.token,
305
+ fingerprint: saved.value.fingerprint,
306
+ source: saved.value.source,
307
+ fromApp: false,
308
+ };
309
}
310
if (personal) return yield* personalCredential(host);
311
const app = yield* Effect.result(appCredential(host));
@@ -298,13 +319,20 @@ export const make = Effect.gen(function* () {
319
320
const credential: GitHubRequestPolicy["Service"]["credential"] = (host, options) =>
321
choose(normalizeHost(host), options?.personal === true).pipe(
301
- Effect.map(({ token, fingerprint }) => ({ token, fingerprint })),
322
+ Effect.map(({ token, fingerprint, source }) => ({
323
+ token,
324
+ fingerprint,
325
+ ...(source === undefined ? {} : { source }),
326
+ })),
327
);
328
329
// The REST/GraphQL transport span owns request and quota metadata.
330
const request: GitHubRequestPolicy["Service"]["request"] = Effect.fnUntraced(function* <A, E, R>(
331
input: GitHubRequest,
307
- send: (headers: Readonly<Record<string, string>>) => Effect.Effect<GitHubAnswer<A>, E, R>,
332
+ send: (
333
+ headers: Readonly<Record<string, string>>,
334
+ source: GitHubCredentials.GitHubCredentialSource | undefined,
335
+ ) => Effect.Effect<GitHubAnswer<A>, E, R>,
336
) {
337
const host = normalizeHost(input.host);
338
const context = { host, operation: input.operation };
@@ -321,7 +349,7 @@ export const make = Effect.gen(function* () {
349
const settle = Effect.fnUntraced(function* (
350
lease: number,
351
answer: GitHubAnswer<A>,
324
- token: Redacted.Redacted<string>,
352
+ held: ChosenCredential,
353
) {
354
yield* quota.observe(host, answer.headers);
355
yield* Effect.annotateCurrentSpan({
@@ -346,11 +374,14 @@ export const make = Effect.gen(function* () {
374
}
375
case "Unauthorized":
376
// The source may hold a newer token than the one that was refused.
349
- yield* appSignIn.invalidate(host, Redacted.value(token));
377
+ yield* appSignIn.invalidate(host, Redacted.value(held.token));
378
yield* credentials.invalidate(host);
379
return yield* new GitHubApiAuthenticationError(context);
380
case "NotFound":
353
- return yield* new GitHubApiNotFoundError(context);
381
+ return yield* new GitHubApiNotFoundError({
382
+ ...context,
383
+ ...(held.source === undefined ? {} : { credential: held.source }),
384
+ });
385
case "Failed":
386
return yield* new GitHubApiResponseError({
387
...context,
@@ -380,10 +411,10 @@ export const make = Effect.gen(function* () {
411
);
412
// One deadline covers the headers and the body: a host that answers headers and then
413
// stalls must not hold a shared slot for undici's own five-minute body timeout.
383
- const answer = yield* send({
384
- ...REQUEST_HEADERS,
385
- authorization: `Bearer ${Redacted.value(held.token)}`,
386
- }).pipe(
414
+ const answer = yield* send(
415
+ { ...REQUEST_HEADERS, authorization: `Bearer ${Redacted.value(held.token)}` },
416
+ held.source,
417
+ ).pipe(
418
Effect.timeoutOrElse({
419
duration: input.timeout ?? DEFAULT_TIMEOUT,
420
orElse: () =>
@@ -401,7 +432,7 @@ export const make = Effect.gen(function* () {
432
return { _tag: "Retry", with: personal.value } as const;
433
}
434
}
404
- return { _tag: "Done", value: yield* settle(lease, answer, held.token) } as const;
435
+ return { _tag: "Done", value: yield* settle(lease, answer, held) } as const;
436
}),
437
)
438
// The rate-limit scope follows the credential, so a pause on one account never blocks another.
packages/source-control-github/src/server/gitHubGraphQlClient.ts
+22
-3
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
4
import { dual } from "effect/Function";
5
import * as Layer from "effect/Layer";
6
import * as Option from "effect/Option";
7
+import * as Schema from "effect/Schema";
8
import * as Stream from "effect/Stream";
9
import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
10
import * as Headers from "effect/http/Headers";
@@ -11,9 +12,13 @@ import { GraphQLClientError, GraphQLMiddleware, GraphQLProtocol } from "effect/g
12
import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
13
import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
14
15
+import * as GitHubCredentials from "./GitHubCredentials.ts";
16
import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
17
18
const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
19
+/** Added to the answer, never sent: names the credential an errored answer was given to. */
20
+const CREDENTIAL_SOURCE_HEADER = "x-t3code-credential-source";
21
+const isCredentialSource = Schema.is(GitHubCredentials.GitHubCredentialSource);
22
23
/** One client serves all hosts; each call must supply its target. */
24
export class GitHubGraphQlTarget extends Context.Service<
@@ -67,7 +72,7 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
72
resource: "graphql",
73
allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
74
},
70
- (headers) =>
75
+ (headers, source) =>
76
next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
77
Effect.map((answer) => {
78
const status = answer.status;
@@ -84,7 +89,14 @@ export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
89
? { _tag: "RateLimited" as const, status, headers: responseHeaders }
90
: {
91
_tag: "Ok" as const,
87
- value: answer,
92
+ // The source is local; never trust one GitHub's answer carries.
93
+ value: {
94
+ ...answer,
95
+ headers:
96
+ source === undefined
97
+ ? Headers.remove(responseHeaders, CREDENTIAL_SOURCE_HEADER)
98
+ : Headers.set(responseHeaders, CREDENTIAL_SOURCE_HEADER, source),
99
+ },
100
withheld,
101
status,
102
headers: responseHeaders,
@@ -223,8 +235,15 @@ const fromClientError = (
235
host: normalizeHost(target.host),
236
operation: target.operation,
237
};
238
+ const credential = Option.filter(
239
+ Headers.get(reason.headers ?? Headers.empty, CREDENTIAL_SOURCE_HEADER),
240
+ isCredentialSource,
241
+ );
242
return isNotFoundOnly(error)
227
- ? new GitHubRequestPolicy.GitHubApiNotFoundError(context)
243
+ ? new GitHubRequestPolicy.GitHubApiNotFoundError({
244
+ ...context,
245
+ ...(Option.isSome(credential) ? { credential: credential.value } : {}),
246
+ })
247
: new GitHubRequestPolicy.GitHubApiResponseError({
248
...context,
249
status: reason.status ?? 200,