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 21, 23:30 UTC
fix(web): fall back to a readable server for shared repositories (#21530)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
sanjai balajee committed
Nov 11, 2026 at 16:48 UTC
54a5c51a58a9b3f7cd123eab967ec87922198113
11 files changed
+883
-88
apps/server/src/pullRequest/PullRequestService.test.ts
+168
@@ -905,6 +905,173 @@ it.effect("tells two hosts of one kind apart in the switcher and the filter", ()
905
}),
906
);
907
908
+it.effect("retains an unavailable host's summary when it is the only queried host", () =>
909
+ Effect.gen(function* () {
910
+ for (const reason of ["missing-tool", "unauthenticated"] as const) {
911
+ const service = yield* makeService({
912
+ projects: [
913
+ project({
914
+ id: "p1",
915
+ title: "t3code",
916
+ workspaceRoot: "/a",
917
+ repository: "pingdotgg/t3code",
918
+ }),
919
+ ],
920
+ providers: [
921
+ fakePullRequestProvider(SourceControlProviderKind.make("github"), {
922
+ getViewer: () =>
923
+ Effect.fail(unusable(SourceControlProviderKind.make("github"), reason)),
924
+ }),
925
+ ],
926
+ });
927
+
928
+ for (const filter of [{}, { host: "github.com" }]) {
929
+ const error = yield* service.list({ state: "open", ...filter }).pipe(Effect.flip);
930
+ assert.strictEqual(error._tag, "PullRequestUnavailableError");
931
+ assert.strictEqual(
932
+ error._tag === "PullRequestUnavailableError" ? error.reason : null,
933
+ reason === "missing-tool" ? "cli-missing" : "cli-unauthenticated",
934
+ );
935
+ assert.isDefined(error.listResult);
936
+ const result = error.listResult!;
937
+ assert.deepStrictEqual(result.entries, []);
938
+ assert.deepStrictEqual(result.viewers, {});
939
+ assert.deepStrictEqual(
940
+ result.providers.map(({ host, configured, projectIds }) => ({
941
+ host,
942
+ configured,
943
+ projectIds: projectIds?.map(String),
944
+ })),
945
+ [{ host: "github.com", configured: false, projectIds: undefined }],
946
+ );
947
+ assert.strictEqual(result.providers[0]?.detail?.includes("github"), true);
948
+ assert.deepStrictEqual(
949
+ result.errors.map(({ projectId }) => projectId),
950
+ ["p1"],
951
+ );
952
+ }
953
+ }
954
+ }),
955
+);
956
+
957
+it.effect("retains a Bitbucket host summary when the provider rejects saved credentials", () =>
958
+ Effect.gen(function* () {
959
+ const provider = fakePullRequestProvider(SourceControlProviderKind.make("bitbucket"), {
960
+ getViewer: () =>
961
+ Effect.fail(
962
+ new PullRequestProviderError({
963
+ provider: SourceControlProviderKind.make("bitbucket"),
964
+ operation: "getViewer",
965
+ reason: "failed",
966
+ detail: "HTTP 403",
967
+ }),
968
+ ),
969
+ });
970
+ const service = yield* makeService({
971
+ projects: [
972
+ project({
973
+ id: "bitbucket",
974
+ title: "Widget",
975
+ workspaceRoot: "/widget",
976
+ repository: "acme/widget",
977
+ provider: "bitbucket",
978
+ host: "bitbucket.org",
979
+ }),
980
+ ],
981
+ providers: [provider],
982
+ });
983
+ for (const filter of [{}, { host: "bitbucket.org" }]) {
984
+ const error = yield* service.list({ state: "open", ...filter }).pipe(Effect.flip);
985
+ assert.strictEqual(error._tag, "PullRequestOperationError");
986
+ assert.isDefined(error.listResult);
987
+ const result = error.listResult!;
988
+ assert.deepStrictEqual(
989
+ result.providers.map(({ host, configured, projectIds }) => ({
990
+ host,
991
+ configured,
992
+ projectIds: projectIds?.map(String),
993
+ })),
994
+ [{ host: "bitbucket.org", configured: false, projectIds: undefined }],
995
+ );
996
+ assert.deepStrictEqual(result.entries, []);
997
+ assert.deepStrictEqual(
998
+ result.errors.map(({ projectId }) => projectId),
999
+ ["bitbucket"],
1000
+ );
1001
+ }
1002
+ }),
1003
+);
1004
+
1005
+it.effect.each([
1006
+ {
1007
+ provider: "forgejo",
1008
+ host: "ssh.forge.example",
1009
+ remoteUrl: "ssh://git@ssh.forge.example:2222/team/repo.git",
1010
+ },
1011
+ {
1012
+ provider: "unknown",
1013
+ host: "forge.example",
1014
+ remoteUrl: "http://forge.example:3000/team/repo.git",
1015
+ },
1016
+])(
1017
+ "identifies every worktree behind an unavailable refined Forgejo authority",
1018
+ ({ provider, host, remoteUrl }) =>
1019
+ Effect.gen(function* () {
1020
+ const service = yield* makeService({
1021
+ projects: ["ssh", "ssh-worktree"].map((id) =>
1022
+ project({
1023
+ id,
1024
+ title: id,
1025
+ workspaceRoot: `/${id}`,
1026
+ repository: "team/repo",
1027
+ provider,
1028
+ host,
1029
+ remoteUrl,
1030
+ }),
1031
+ ),
1032
+ providers: [
1033
+ fakePullRequestProvider(SourceControlProviderKind.make("forgejo"), {
1034
+ getViewer: ({ host }) => {
1035
+ assert.strictEqual(host, "forge.example:3000");
1036
+ return Effect.fail(
1037
+ unusable(SourceControlProviderKind.make("forgejo"), "unauthenticated"),
1038
+ );
1039
+ },
1040
+ listChangeRequests: () => Effect.die("An unauthenticated host must not be queried"),
1041
+ }),
1042
+ ],
1043
+ resolveHandle: ({ context }) =>
1044
+ Effect.succeed({
1045
+ context: {
1046
+ ...context!,
1047
+ provider: {
1048
+ kind: SourceControlProviderKind.make("forgejo"),
1049
+ name: "Forgejo",
1050
+ baseUrl: "http://forge.example:3000",
1051
+ },
1052
+ },
1053
+ provider: undefined as never,
1054
+ }),
1055
+ });
1056
+ const error = yield* service.list({ state: "open" }).pipe(Effect.flip);
1057
+ assert.isDefined(error.listResult);
1058
+ const result = error.listResult!;
1059
+ assert.deepStrictEqual(
1060
+ result.providers.map(({ host, configured, projectIds }) => ({
1061
+ host,
1062
+ configured,
1063
+ projectIds: projectIds?.map(String),
1064
+ })),
1065
+ [{ host: "forge.example:3000", configured: false, projectIds: ["ssh", "ssh-worktree"] }],
1066
+ );
1067
+ assert.deepStrictEqual(result.entries, []);
1068
+ assert.deepStrictEqual(
1069
+ result.errors.map(({ projectId }) => projectId),
1070
+ ["ssh"],
1071
+ );
1072
+ }),
1073
+);
1074
+
1075
it.effect("reads a repository once when several worktrees share it", () =>
1076
Effect.gen(function* () {
1077
let calls = 0;
@@ -936,6 +1103,7 @@ it.effect("reads a repository once when several worktrees share it", () =>
1103
1104
assert.strictEqual(calls, 1);
1105
assert.strictEqual(result.entries.length, 1);
1106
+ assert.isUndefined(result.providers[0]?.projectIds);
1107
}),
1108
);
1109
apps/server/src/pullRequest/PullRequestService.ts
+30
-12
@@ -344,6 +344,7 @@ interface WorkspaceProjects {
344
{ readonly kind: SourceControlProviderKind; readonly projectCount: number }
345
>;
346
readonly viewerRoots: ReadonlyMap<string, ReadonlyArray<string>>;
347
+ readonly refinedProjectIdsByHost: ReadonlyMap<string, ReadonlyArray<ProjectId>>;
348
}
349
350
// Inherited by fibers forked inside the scope, so it is closed, not just dropped, when the scope ends.
@@ -930,6 +931,7 @@ export const make = Effect.gen(function* () {
931
{ kind: SourceControlProviderKind; projectCount: number }
932
>();
933
const viewerRoots = new Map<string, string[]>();
934
+ const refinedProjectIdsByHost = new Map<string, ProjectId[]>();
935
const seen = new Set<string>();
936
for (const project of projects) {
937
if (filter.projectId !== undefined && project.id !== filter.projectId) continue;
@@ -950,6 +952,11 @@ export const make = Effect.gen(function* () {
952
if (filter.host !== undefined && host !== filter.host.toLowerCase()) {
953
continue;
954
}
955
+ if (host !== sourceControlDefinitions.changeRequestHost(identity, identity.provider)) {
956
+ const projectIds = refinedProjectIdsByHost.get(host);
957
+ if (projectIds === undefined) refinedProjectIdsByHost.set(host, [project.id]);
958
+ else projectIds.push(project.id);
959
+ }
960
const registered = registry.get(kind);
961
const api = registered?.servesHost?.(host) === false ? null : registered;
962
if (api !== null) {
@@ -983,7 +990,7 @@ export const make = Effect.gen(function* () {
990
: sourceControlDefinitions.canonicalRepositoryKey(repositoryKey.toLowerCase()),
991
});
992
}
986
- return { supported, unimplemented, viewerRoots };
993
+ return { supported, unimplemented, viewerRoots, refinedProjectIdsByHost };
994
}),
995
);
996
@@ -1307,7 +1314,12 @@ export const make = Effect.gen(function* () {
1314
const involvement = input.involvement ?? "all";
1315
const epochAtStart = epochCounter;
1316
const continuation = yield* decodeCursors(input.cursors);
1310
- const { supported: projects, unimplemented, viewerRoots } = yield* listWorkspaceProjects(input);
1317
+ const {
1318
+ supported: projects,
1319
+ unimplemented,
1320
+ viewerRoots,
1321
+ refinedProjectIdsByHost,
1322
+ } = yield* listWorkspaceProjects(input);
1323
const projectCounts = new Map<string, number>();
1324
for (const { host } of projects) {
1325
projectCounts.set(host, (projectCounts.get(host) ?? 0) + 1);
@@ -1329,6 +1341,7 @@ export const make = Effect.gen(function* () {
1341
searchesOnHost: capabilities?.search ?? false,
1342
actions: capabilities?.actions ?? [],
1343
projectCount: projectCounts.get(result.host) ?? 1,
1344
+ projectIds: refinedProjectIdsByHost.get(result.host),
1345
configured: result.viewer !== null,
1346
detail: result.error === null ? null : providerDetail(requirementOf, result.error),
1347
};
@@ -1339,6 +1352,7 @@ export const make = Effect.gen(function* () {
1352
searchesOnHost: false,
1353
actions: [],
1354
projectCount,
1355
+ projectIds: refinedProjectIdsByHost.get(host),
1356
configured: false,
1357
detail: "This host cannot be browsed here yet.",
1358
})),
@@ -1357,6 +1371,14 @@ export const make = Effect.gen(function* () {
1371
message: `${repository} could not be read.`,
1372
}));
1373
if (readable.length === 0) {
1374
+ const listResult: PullRequestListResult = {
1375
+ viewers: viewers as PullRequestListResult["viewers"],
1376
+ providers,
1377
+ entries: [],
1378
+ errors: unreadable,
1379
+ truncated: false,
1380
+ nextCursors: {},
1381
+ };
1382
const errors = viewerResults.flatMap((result) =>
1383
result.error === null || !selected.some(({ host }) => host === result.host)
1384
? []
@@ -1364,17 +1386,13 @@ export const make = Effect.gen(function* () {
1386
);
1387
const blocking = errors.find(isProviderUnusable) ?? errors[0];
1388
if (blocking) {
1367
- return yield* toPullRequestError("list")(blocking);
1389
+ // Preserve failure/retry semantics while letting clients try another server for these hosts.
1390
+ const error = toPullRequestError("list")(blocking);
1391
+ return yield* error._tag === "PullRequestUnavailableError"
1392
+ ? new PullRequestUnavailableError({ ...error, listResult })
1393
+ : new PullRequestOperationError({ ...error, listResult });
1394
}
1369
-
1370
- return {
1371
- viewers: viewers as PullRequestListResult["viewers"],
1372
- providers,
1373
- entries: [],
1374
- errors: [],
1375
- truncated: false,
1376
- nextCursors: {},
1377
- };
1395
+ return listResult;
1396
}
1397
1398
const limit = input.limit ?? DEFAULT_REPOSITORY_LIST_LIMIT;
apps/web/src/components/pullRequest/PullRequestsPage.tsx
+61
-38
@@ -115,6 +115,11 @@ import { useAtomCommand } from "~/state/use-atom-command";
115
import { cn } from "~/lib/utils";
116
import { primaryServerKeybindingsAtom } from "~/state/server";
117
import { getSourceControlPresentationForKind } from "~/sourceControlPresentation";
118
+import {
119
+ rememberPullRequestHosts,
120
+ resetPullRequestHosts,
121
+ type PullRequestHostRead,
122
+} from "./pullRequestProjectAssignment.logic";
123
124
function getShortcutContext() {
125
return {
@@ -149,6 +154,9 @@ export function PullRequestsPage() {
154
sort === "ready" || sort === "largest" || sort === "smallest" ? "eager" : "visible";
155
const navigate = useNavigate({ from: "/pull-requests" });
156
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
157
+ const [hostReads, setHostReads] = useState<ReadonlyMap<EnvironmentId, PullRequestHostRead>>(
158
+ () => new Map(),
159
+ );
160
const {
161
capableEnvironments,
162
scopedEnvironmentId,
@@ -163,11 +171,12 @@ export function PullRequestsPage() {
171
selectedProject,
172
queryEnvironmentIds,
173
environmentQueries,
174
+ preferredEnvironmentQueries,
175
assignmentKey,
176
linkedSelection,
177
expectedHosts,
178
projectsKnown,
170
- } = usePullRequestScope(search);
179
+ } = usePullRequestScope(search, hostReads);
180
const rightPanelRef = capableEnvironments.length === 0 ? null : PULL_REQUESTS_PANEL_REF;
181
const openPanelPullRequestUrl = useOpenPanelPullRequestUrl(rightPanelRef);
182
const rightPanelState = useRightPanelStore((state) =>
@@ -272,9 +281,9 @@ export function PullRequestsPage() {
281
localFilters,
282
hasLocalFilters,
283
} = usePullRequestQueryFilters(search, typedQuery);
275
- const turnRefreshes = usePullRequestTurnRefreshes(
276
- environmentQueries.map(({ environmentId }) => environmentId),
277
- );
284
+ const turnRefreshes = usePullRequestTurnRefreshes([
285
+ ...new Set(environmentQueries.map(({ environmentId }) => environmentId)),
286
+ ]);
287
const turnRefreshToken = turnRefreshes
288
.map(([environmentId, revision]) => `${environmentId}:${revision}`)
289
.join("|");
@@ -308,28 +317,30 @@ export function PullRequestsPage() {
317
});
318
}
319
311
- const listTargets = environmentQueries.flatMap(({ environmentId, projectIds }) => {
312
- const cursors = sentCursors?.[environmentId];
313
- if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
314
- return [];
315
- }
316
- return [
317
- {
318
- environmentId,
319
- input: {
320
- state: search.state,
321
- involvement: search.involvement,
322
- limit: pageSize,
323
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
324
- ...(projectIds ? { projectIds } : {}),
325
- ...(search.host ? { host: search.host } : {}),
326
- ...(hasFilters ? { filters } : {}),
327
- ...(sentParsed.text ? { query: sentParsed.text } : {}),
328
- ...(cursors === undefined ? {} : { cursors }),
329
- } satisfies PullRequestListInput,
330
- },
331
- ];
332
- });
320
+ const listTargetsFor = (queries: typeof environmentQueries) =>
321
+ queries.flatMap(({ environmentId, projectIds }) => {
322
+ const cursors = sentCursors?.[environmentId];
323
+ if (sentCursors !== null && cursors === undefined && !sentRegrown.includes(environmentId)) {
324
+ return [];
325
+ }
326
+ return [
327
+ {
328
+ environmentId,
329
+ input: {
330
+ state: search.state,
331
+ involvement: search.involvement,
332
+ limit: pageSize,
333
+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
334
+ ...(projectIds ? { projectIds } : {}),
335
+ ...(search.host ? { host: search.host } : {}),
336
+ ...(hasFilters ? { filters } : {}),
337
+ ...(sentParsed.text ? { query: sentParsed.text } : {}),
338
+ ...(cursors === undefined ? {} : { cursors }),
339
+ } satisfies PullRequestListInput,
340
+ },
341
+ ];
342
+ });
343
+ const listTargets = listTargetsFor(environmentQueries);
344
const listQuery = usePullRequestList(listTargets);
345
346
/**
@@ -337,19 +348,26 @@ export function PullRequestsPage() {
348
* say which question it belongs to: mid-switch the text has already changed and the data has
349
* not, and a search's answer would file itself under the workspace.
350
*/
340
- const baselineTargets = environmentQueries.map(({ environmentId, projectIds }) => ({
341
- environmentId,
342
- input: {
343
- state: search.state,
344
- involvement: search.involvement,
345
- limit: PAGE_SIZE,
346
- ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
347
- ...(projectIds ? { projectIds } : {}),
348
- ...(search.host ? { host: search.host } : {}),
349
- ...(menuFiltered ? { filters: menuFilters } : {}),
350
- } satisfies PullRequestListInput,
351
- }));
351
+ const baselineTargetsFor = (queries: typeof environmentQueries) =>
352
+ queries.map(({ environmentId, projectIds }) => ({
353
+ environmentId,
354
+ input: {
355
+ state: search.state,
356
+ involvement: search.involvement,
357
+ limit: PAGE_SIZE,
358
+ ...(scopedProjectId ? { projectId: scopedProjectId } : {}),
359
+ ...(projectIds ? { projectIds } : {}),
360
+ ...(search.host ? { host: search.host } : {}),
361
+ ...(menuFiltered ? { filters: menuFilters } : {}),
362
+ } satisfies PullRequestListInput,
363
+ }));
364
+ const baselineTargets = baselineTargetsFor(environmentQueries);
365
const baselineQuery = usePullRequestList(baselineTargets);
366
+ const observedHosts = rememberPullRequestHosts(
367
+ rememberPullRequestHosts(hostReads, baselineQuery.observations),
368
+ listQuery.observations,
369
+ );
370
+ if (observedHosts !== hostReads) setHostReads(observedHosts);
371
const baselineEmpty =
372
baselineQuery.data?.entries.length === 0 &&
373
baselineQuery.data.errors.length === 0 &&
@@ -895,6 +913,11 @@ export function PullRequestsPage() {
913
await Promise.all(
914
queryEnvironmentIds.map((environmentId) => invalidate({ environmentId, input: {} })),
915
);
916
+ listQuery.refresh([
917
+ ...listTargetsFor(preferredEnvironmentQueries),
918
+ ...baselineTargetsFor(preferredEnvironmentQueries),
919
+ ]);
920
+ setHostReads(resetPullRequestHosts);
921
setInvalidating(false);
922
refreshListAndStats(requestedStatsScope);
923
setDetailRefreshToken((token) => token + 1);
apps/web/src/components/pullRequest/pullRequestList.logic.test.ts
+56
@@ -433,6 +433,51 @@ describe("merging the environments' own listings", () => {
433
]);
434
});
435
436
+ it.each([false, true])(
437
+ "merges worktree batches without duplicate rows (reversed: %s)",
438
+ (reverse) => {
439
+ const older = entry({
440
+ projectId: "worktree-1" as ProjectId,
441
+ number: 4,
442
+ updatedAt: "2026-07-01T00:00:00Z",
443
+ });
444
+ const newer = entry({
445
+ projectId: "worktree-101" as ProjectId,
446
+ number: 4,
447
+ updatedAt: "2026-07-02T00:00:00Z",
448
+ });
449
+ const rows = reverse ? [newer, older] : [older, newer];
450
+ const merged = mergePullRequestLists([
451
+ ...rows.map((row) => [ENV_1, answer({ entries: [row] })] as const),
452
+ [ENV_2, answer({ entries: [older] })],
453
+ ]);
454
+ expect(merged?.entries).toEqual([
455
+ { ...newer, environmentId: ENV_1 },
456
+ { ...older, environmentId: ENV_2 },
457
+ ]);
458
+ },
459
+ );
460
+
461
+ it("keeps Azure pull requests from distinct projects with the same repository name and number", () => {
462
+ const first = entry({
463
+ provider: SourceControlProviderKind.make("azure-devops"),
464
+ host: "dev.azure.com",
465
+ repository: "web",
466
+ number: 4,
467
+ projectId: "azure-first" as ProjectId,
468
+ url: "https://dev.azure.com/acme/first/_git/web/pullrequest/4",
469
+ });
470
+ const second = {
471
+ ...first,
472
+ projectId: "azure-second" as ProjectId,
473
+ url: "https://dev.azure.com/acme/second/_git/web/pullrequest/4",
474
+ };
475
+ const merged = mergePullRequestLists([[ENV_1, answer({ entries: [first, second] })]]);
476
+ expect(merged?.entries).toEqual(
477
+ [first, second].map((entry) => ({ ...entry, environmentId: ENV_1 })),
478
+ );
479
+ });
480
+
481
// regression: #6490 one environment's error showed on every environment
482
it("keeps project errors scoped to the environment that reported them", () => {
483
const error = {
@@ -478,6 +523,17 @@ describe("merging the environments' own listings", () => {
523
},
524
]);
525
});
526
+
527
+ it("keeps continuations from every project batch on the same environment", () => {
528
+ const merged = mergePullRequestLists([
529
+ [ENV_1, answer({ truncated: true, nextCursors: { "github.com acme/first": "cursor-1" } })],
530
+ [ENV_1, answer({ truncated: true, nextCursors: { "github.com acme/second": "cursor-2" } })],
531
+ ]);
532
+ expect(merged?.nextCursors).toEqual({
533
+ [ENV_1]: { "github.com acme/first": "cursor-1", "github.com acme/second": "cursor-2" },
534
+ });
535
+ expect(merged?.truncatedEnvironments).toEqual([ENV_1]);
536
+ });
537
});
538
539
describe('who "I" am, per server', () => {
apps/web/src/components/pullRequest/pullRequestList.logic.ts
+13
-7
@@ -536,9 +536,9 @@ export function mergePullRequestLists(
536
): MergedPullRequestList | null {
537
if (answers.length === 0) return null;
538
const viewers: Record<string, string> = {};
539
- const truncatedEnvironments: string[] = [];
539
+ const truncatedEnvironments = new Set<string>();
540
const providers = new Map<string, PullRequestListResult["providers"][number]>();
541
- const entries: EnvironmentPullRequestEntry[] = [];
541
+ const entries = new Map<string, EnvironmentPullRequestEntry>();
542
const errors: EnvironmentPullRequestError[] = [];
543
const nextCursors: Record<string, PullRequestListCursors> = {};
544
let truncated = false;
@@ -560,22 +560,28 @@ export function mergePullRequestLists(
560
},
561
);
562
}
563
- entries.push(...answer.entries.map((entry) => ({ ...entry, environmentId })));
563
+ for (const entry of answer.entries) {
564
+ const key = JSON.stringify([environmentId, entry.url]);
565
+ const held = entries.get(key);
566
+ if (held === undefined || entry.updatedAt > held.updatedAt) {
567
+ entries.set(key, { ...entry, environmentId });
568
+ }
569
+ }
570
errors.push(...answer.errors.map((error) => ({ ...error, environmentId })));
571
truncated ||= answer.truncated;
566
- if (answer.truncated) truncatedEnvironments.push(environmentId);
572
+ if (answer.truncated) truncatedEnvironments.add(environmentId);
573
if (Object.keys(answer.nextCursors).length > 0) {
568
- nextCursors[environmentId] = answer.nextCursors;
574
+ nextCursors[environmentId] = { ...nextCursors[environmentId], ...answer.nextCursors };
575
}
576
}
577
return {
578
viewers,
579
providers: [...providers.values()],
574
- entries: entries.toSorted(comparePullRequestsByRecency),
580
+ entries: [...entries.values()].toSorted(comparePullRequestsByRecency),
581
errors,
582
truncated,
583
nextCursors,
578
- truncatedEnvironments,
584
+ truncatedEnvironments: [...truncatedEnvironments],
585
};
586
}
587
apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.test.ts
+271
-1
@@ -1,8 +1,18 @@
1
-import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
1
+import {
2
+ PullRequestListInput,
3
+ SourceControlProviderKind,
4
+ type EnvironmentId,
5
+ type ProjectId,
6
+ type PullRequestProviderSummary,
7
+} from "@t3tools/contracts";
8
+import * as Schema from "effect/Schema";
9
import { describe, expect, it } from "vite-plus/test";
10
11
import {
12
assignProjectsToEnvironments,
13
+ rememberPullRequestHosts,
14
+ resetPullRequestHosts,
15
+ pullRequestProjectQueries,
16
resolvePickableEnvironments,
17
type AssignableProject,
18
} from "./pullRequestProjectAssignment.logic";
@@ -22,6 +32,134 @@ const envs = (...ids: ReadonlyArray<string>) => ids as ReadonlyArray<Environment
32
33
const plain = (assignment: Map<EnvironmentId, ProjectId[]>) =>
34
Object.fromEntries([...assignment].map(([id, projectIds]) => [id, projectIds]));
35
+const decodeListInput = Schema.decodeSync(PullRequestListInput);
36
+
37
+const hostAvailability = (hosts: ReadonlyMap<string, boolean>) => ({
38
+ hosts: new Map([...hosts].map(([host, configured]) => [host, { configured, observedAt: 0 }])),
39
+ projectHosts: new Map<ProjectId, { host: string; observedAt: number }>(),
40
+});
41
+
42
+const provider = (host: string, configured: boolean): PullRequestProviderSummary => ({
43
+ host,
44
+ kind: "bitbucket" as PullRequestProviderSummary["kind"],
45
+ searchesOnHost: false,
46
+ projectCount: 1,
47
+ configured,
48
+ detail: configured ? null : "Credentials rejected",
49
+});
50
+
51
+describe("host read results", () => {
52
+ const environmentId = "env-1" as EnvironmentId;
53
+
54
+ it("remembers a failed host after the assignment stops requesting it", () => {
55
+ const failed = rememberPullRequestHosts(new Map(), [
56
+ [environmentId, { providers: [provider("BITBUCKET.org", false)] }, 100],
57
+ ]);
58
+ const next = rememberPullRequestHosts(failed, [
59
+ [environmentId, { providers: [provider("github.com", true)] }, 200],
60
+ ]);
61
+ expect(
62
+ [...next.get(environmentId)!.hosts].map(([host, read]) => [host, read.configured]),
63
+ ).toEqual([
64
+ ["bitbucket.org", false],
65
+ ["github.com", true],
66
+ ]);
67
+ expect(
68
+ [...failed.get(environmentId)!.hosts].map(([host, read]) => [host, read.configured]),
69
+ ).toEqual([["bitbucket.org", false]]);
70
+ });
71
+
72
+ it("does not replay cached failures after refresh clears availability", () => {
73
+ const cleared = new Map([
74
+ [
75
+ environmentId,
76
+ { observedAt: 100, resetAt: 100, ...hostAvailability(new Map<string, boolean>()) },
77
+ ],
78
+ ]);
79
+ expect(
80
+ rememberPullRequestHosts(cleared, [
81
+ [environmentId, { providers: [provider("bitbucket.org", false)] }, 100],
82
+ ]),
83
+ ).toBe(cleared);
84
+ const refreshed = rememberPullRequestHosts(cleared, [
85
+ [environmentId, { providers: [provider("bitbucket.org", true)] }, 200],
86
+ ]);
87
+ expect(refreshed.get(environmentId)!.hosts.get("bitbucket.org")?.configured).toBe(true);
88
+ });
89
+
90
+ it("ignores an older answer when a newer read has already succeeded", () => {
91
+ const readable = rememberPullRequestHosts(new Map(), [
92
+ [environmentId, { providers: [provider("bitbucket.org", true)] }, 200],
93
+ ]);
94
+ expect(
95
+ rememberPullRequestHosts(readable, [
96
+ [environmentId, { providers: [provider("bitbucket.org", false)] }, 100],
97
+ ]),
98
+ ).toBe(readable);
99
+ });
100
+
101
+ it.each([false, true])(
102
+ "treats a host as readable when any active batch succeeds (reversed: %s)",
103
+ (reverse) => {
104
+ const observations = [
105
+ [environmentId, { providers: [provider("gitlab.example", true)] }, 100],
106
+ [environmentId, { providers: [provider("gitlab.example", false)] }, 200],
107
+ ] as const;
108
+ const next = rememberPullRequestHosts(
109
+ new Map(),
110
+ reverse ? observations.toReversed() : observations,
111
+ );
112
+ expect(next.get(environmentId)!.hosts.get("gitlab.example")).toEqual({
113
+ configured: true,
114
+ observedAt: 200,
115
+ });
116
+ expect(next.get(environmentId)!.observedAt).toBe(200);
117
+ const cleared = resetPullRequestHosts(next);
118
+ expect(rememberPullRequestHosts(cleared, observations)).toBe(cleared);
119
+ const failed = rememberPullRequestHosts(next, [
120
+ [environmentId, { providers: [provider("gitlab.example", false)] }, 300],
121
+ ]);
122
+ expect(failed.get(environmentId)!.hosts.get("gitlab.example")?.configured).toBe(false);
123
+ },
124
+ );
125
+});
126
+
127
+describe("assignment query limits", () => {
128
+ it("splits the healthy remainder after fallback into valid project filters", () => {
129
+ const healthy = Array.from({ length: 101 }, (_, index) =>
130
+ project(`healthy-${index}`, "env-1", `github.com/acme/repo-${index}`),
131
+ );
132
+ const projects = [
133
+ project("shared", "env-1", "bitbucket.org/acme/app"),
134
+ ...healthy,
135
+ project("copy", "env-2", "bitbucket.org/acme/app"),
136
+ ];
137
+ const queries = pullRequestProjectQueries(
138
+ projects,
139
+ envs("env-1", "env-2"),
140
+ new Map([["env-1" as EnvironmentId, hostAvailability(new Map([["bitbucket.org", false]]))]]),
141
+ );
142
+ expect(
143
+ queries.map(({ environmentId, projectIds }) => [environmentId, projectIds?.length]),
144
+ ).toEqual([
145
+ ["env-1", 100],
146
+ ["env-1", 1],
147
+ ["env-2", undefined],
148
+ ]);
149
+ expect(
150
+ queries
151
+ .filter(({ environmentId }) => environmentId === "env-1")
152
+ .flatMap(({ projectIds }) => projectIds ?? []),
153
+ ).toEqual(healthy.map(({ id }) => id));
154
+ for (const { projectIds } of queries)
155
+ expect(() =>
156
+ decodeListInput({
157
+ state: "open",
158
+ ...(projectIds === undefined ? {} : { projectIds }),
159
+ }),
160
+ ).not.toThrow();
161
+ });
162
+});
163
164
describe("one server per repository", () => {
165
it("lets the first server list a repository both hold", () => {
@@ -50,6 +188,138 @@ describe("one server per repository", () => {
188
expect(plain(assignment)).toEqual({ "env-2": ["a2"] });
189
});
190
191
+ it("falls back from an unreadable host without moving other repositories", () => {
192
+ const assignment = assignProjectsToEnvironments(
193
+ [
194
+ project("a1", "env-1", "bitbucket.org/acme/app"),
195
+ project("b1", "env-1", "github.com/acme/tools"),
196
+ project("a2", "env-2", "bitbucket.org/acme/app"),
197
+ project("b2", "env-2", "github.com/acme/tools"),
198
+ ],
199
+ envs("env-1", "env-2"),
200
+ "env-1" as EnvironmentId,
201
+ new Map([["env-1" as EnvironmentId, hostAvailability(new Map([["bitbucket.org", false]]))]]),
202
+ );
203
+ expect(plain(assignment)).toEqual({ "env-1": ["b1"], "env-2": ["a2"] });
204
+ });
205
+
206
+ it("keeps one stable owner and its error when every copy is unreadable", () => {
207
+ const projects = [
208
+ project("a1", "env-1", "bitbucket.org/acme/app"),
209
+ project("a2", "env-2", "bitbucket.org/acme/app"),
210
+ project("only1", "env-1", "bitbucket.org/acme/only"),
211
+ ];
212
+ const availability = new Map(
213
+ envs("env-1", "env-2").map((id) => [
214
+ id,
215
+ hostAvailability(new Map([["bitbucket.org", false]])),
216
+ ]),
217
+ );
218
+ expect(
219
+ plain(
220
+ assignProjectsToEnvironments(
221
+ projects,
222
+ envs("env-1", "env-2"),
223
+ "env-1" as EnvironmentId,
224
+ availability,
225
+ ),
226
+ ),
227
+ ).toEqual({ "env-1": ["a1", "only1"] });
228
+ expect(
229
+ plain(
230
+ assignProjectsToEnvironments(
231
+ projects,
232
+ envs("env-2"),
233
+ "env-2" as EnvironmentId,
234
+ availability,
235
+ ),
236
+ ),
237
+ ).toEqual({ "env-2": ["a2"] });
238
+ });
239
+
240
+ it("checks the owner's HTTP authority using its own identity in either project order", () => {
241
+ const projects = [
242
+ {
243
+ ...project("a1", "env-1", "forge.example/team/repo"),
244
+ repositoryIdentity: {
245
+ canonicalKey: "forge.example/team/repo",
246
+ provider: SourceControlProviderKind.make("forgejo"),
247
+ locator: {
248
+ source: "git-remote",
249
+ remoteName: "origin",
250
+ remoteUrl: "https://forge.example:3000/team/repo.git",
251
+ },
252
+ },
253
+ },
254
+ {
255
+ ...project("a2", "env-2", "forge.example/team/repo"),
256
+ repositoryIdentity: {
257
+ canonicalKey: "forge.example/team/repo",
258
+ provider: SourceControlProviderKind.make("forgejo"),
259
+ locator: {
260
+ source: "git-remote",
261
+ remoteName: "origin",
262
+ remoteUrl: "git@forge.example:team/repo.git",
263
+ },
264
+ },
265
+ },
266
+ ] as const;
267
+ const availability = new Map([
268
+ ["env-1" as EnvironmentId, hostAvailability(new Map([["forge.example:3000", false]]))],
269
+ ]);
270
+ for (const copies of [projects, projects.toReversed()]) {
271
+ expect(
272
+ plain(
273
+ assignProjectsToEnvironments(
274
+ copies,
275
+ envs("env-1", "env-2"),
276
+ "env-1" as EnvironmentId,
277
+ availability,
278
+ ),
279
+ ),
280
+ ).toEqual({ "env-2": ["a2"] });
281
+ }
282
+ });
283
+
284
+ it("uses a server-resolved host for SSH without conflating ports on that host", () => {
285
+ const projects = envs("env-1", "env-2").map((environmentId) => ({
286
+ ...project(`a-${environmentId}`, environmentId, "ssh.forge.example/team/repo"),
287
+ repositoryIdentity: {
288
+ canonicalKey: "ssh.forge.example/team/repo",
289
+ provider: SourceControlProviderKind.make("forgejo"),
290
+ locator: {
291
+ source: "git-remote" as const,
292
+ remoteName: "origin",
293
+ remoteUrl: "ssh://git@ssh.forge.example:2222/team/repo.git",
294
+ },
295
+ },
296
+ }));
297
+ const availability = rememberPullRequestHosts(new Map(), [
298
+ [
299
+ "env-1" as EnvironmentId,
300
+ {
301
+ providers: [
302
+ { ...provider("forge.example:3000", false), projectIds: ["a-env-1" as ProjectId] },
303
+ { ...provider("forge.example:4000", true), projectIds: ["unrelated" as ProjectId] },
304
+ ],
305
+ },
306
+ 100,
307
+ ],
308
+ ]);
309
+ for (const copies of [projects, projects.toReversed()]) {
310
+ expect(
311
+ plain(
312
+ assignProjectsToEnvironments(
313
+ copies,
314
+ envs("env-1", "env-2"),
315
+ "env-1" as EnvironmentId,
316
+ availability,
317
+ ),
318
+ ),
319
+ ).toEqual({ "env-2": ["a-env-2"] });
320
+ }
321
+ });
322
+
323
it("keeps every copy of a project that has no identity to compare", () => {
324
const assignment = assignProjectsToEnvironments(
325
[project("p1", "env-1"), project("p2", "env-2")],
apps/web/src/components/pullRequest/pullRequestProjectAssignment.logic.ts
+167
-8
@@ -1,9 +1,118 @@
1
-import type { EnvironmentId, EnvironmentMachineKind, ProjectId } from "@t3tools/contracts";
1
+import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
+import {
3
+ PULL_REQUEST_LIST_PROJECT_LIMIT,
4
+ type EnvironmentId,
5
+ type EnvironmentMachineKind,
6
+ type ProjectId,
7
+ type PullRequestProviderSummary,
8
+ type RepositoryIdentity,
9
+ type SourceControlProviderKind,
10
+} from "@t3tools/contracts";
11
12
export interface AssignableProject {
13
readonly id: ProjectId;
14
readonly environmentId: EnvironmentId;
6
- readonly repositoryIdentity?: { readonly canonicalKey?: string | undefined } | null | undefined;
15
+ readonly repositoryIdentity?:
16
+ | Partial<Pick<RepositoryIdentity, "canonicalKey" | "provider" | "locator">>
17
+ | null
18
+ | undefined;
19
+}
20
+
21
+export type PullRequestHostAvailability = ReadonlyMap<
22
+ EnvironmentId,
23
+ Pick<PullRequestHostRead, "hosts" | "projectHosts">
24
+>;
25
+
26
+export type PullRequestHostRead = {
27
+ readonly observedAt: number;
28
+ readonly resetAt?: number;
29
+ readonly hosts: ReadonlyMap<
30
+ string,
31
+ { readonly configured: boolean; readonly observedAt: number }
32
+ >;
33
+ readonly projectHosts: ReadonlyMap<
34
+ ProjectId,
35
+ { readonly host: string; readonly observedAt: number }
36
+ >;
37
+};
38
+
39
+export function resetPullRequestHosts(
40
+ previous: ReadonlyMap<EnvironmentId, PullRequestHostRead>,
41
+): ReadonlyMap<EnvironmentId, PullRequestHostRead> {
42
+ return new Map(
43
+ [...previous].map(([id, read]) => [
44
+ id,
45
+ { ...read, resetAt: read.observedAt, hosts: new Map(), projectHosts: new Map() },
46
+ ]),
47
+ );
48
+}
49
+
50
+export function rememberPullRequestHosts(
51
+ previous: ReadonlyMap<EnvironmentId, PullRequestHostRead>,
52
+ observations: ReadonlyArray<
53
+ readonly [
54
+ EnvironmentId,
55
+ { readonly providers: ReadonlyArray<PullRequestProviderSummary> },
56
+ number,
57
+ ]
58
+ >,
59
+): ReadonlyMap<EnvironmentId, PullRequestHostRead> {
60
+ const activeHosts = new Map<
61
+ EnvironmentId,
62
+ Map<string, { configured: boolean; observedAt: number }>
63
+ >();
64
+ for (const [environmentId, { providers }, observedAt] of observations) {
65
+ if (observedAt <= (previous.get(environmentId)?.resetAt ?? -Infinity)) continue;
66
+ let hosts = activeHosts.get(environmentId);
67
+ if (hosts === undefined) {
68
+ hosts = new Map();
69
+ activeHosts.set(environmentId, hosts);
70
+ }
71
+ for (const provider of providers) {
72
+ const host = provider.host.toLowerCase();
73
+ const held = hosts.get(host);
74
+ hosts.set(host, {
75
+ configured: provider.configured || held?.configured === true,
76
+ observedAt: Math.max(observedAt, held?.observedAt ?? -Infinity),
77
+ });
78
+ }
79
+ }
80
+ let next = previous;
81
+ for (const [environmentId, { providers }, observedAt] of observations) {
82
+ const before = next.get(environmentId);
83
+ if (observedAt <= (before?.resetAt ?? -Infinity)) continue;
84
+ const hosts = new Map(before?.hosts);
85
+ const projectHosts = new Map(before?.projectHosts);
86
+ let changed = false;
87
+ let latestObservedAt = observedAt;
88
+ for (const provider of providers) {
89
+ const host = provider.host.toLowerCase();
90
+ const active = activeHosts.get(environmentId)!.get(host)!;
91
+ const held = hosts.get(host);
92
+ if (
93
+ active.observedAt > (held?.observedAt ?? -Infinity) ||
94
+ (active.observedAt === held?.observedAt && active.configured && !held.configured)
95
+ ) {
96
+ hosts.set(host, active);
97
+ latestObservedAt = Math.max(latestObservedAt, active.observedAt);
98
+ changed = true;
99
+ }
100
+ for (const projectId of provider.projectIds ?? []) {
101
+ if (observedAt > (projectHosts.get(projectId)?.observedAt ?? -Infinity)) {
102
+ projectHosts.set(projectId, { host, observedAt });
103
+ changed = true;
104
+ }
105
+ }
106
+ }
107
+ if (!changed) continue;
108
+ next = new Map(next).set(environmentId, {
109
+ ...before,
110
+ observedAt: Math.max(before?.observedAt ?? -Infinity, latestObservedAt),
111
+ hosts,
112
+ projectHosts,
113
+ });
114
+ }
115
+ return next;
116
}
117
118
function repositoryKey(project: AssignableProject): string | undefined {
@@ -14,9 +123,20 @@ export function assignProjectsToEnvironments(
123
projects: ReadonlyArray<AssignableProject>,
124
environmentIds: ReadonlyArray<EnvironmentId>,
125
preferredEnvironmentId?: EnvironmentId | null,
126
+ hostAvailability?: PullRequestHostAvailability,
127
): Map<EnvironmentId, ProjectId[]> {
128
const rank = new Map(environmentIds.map((id, index) => [id, index] as const));
19
- const owner = new Map<string, EnvironmentId>();
129
+ const owner = new Map<string, AssignableProject>();
130
+ const unreadable = (project: AssignableProject) => {
131
+ const availability = hostAvailability?.get(project.environmentId);
132
+ const host =
133
+ availability?.projectHosts.get(project.id)?.host ??
134
+ sourceControlClients.changeRequestHost(
135
+ project.repositoryIdentity,
136
+ (project.repositoryIdentity?.provider ?? "unknown") as SourceControlProviderKind,
137
+ );
138
+ return availability?.hosts.get(host)?.configured === false;
139
+ };
140
for (const project of projects) {
141
const key = repositoryKey(project);
142
if (!key) continue;
@@ -24,22 +144,28 @@ export function assignProjectsToEnvironments(
144
if (environmentRank === undefined) continue;
145
const current = owner.get(key);
146
if (current === undefined) {
27
- owner.set(key, project.environmentId);
147
+ owner.set(key, project);
148
+ continue;
149
+ }
150
+ const currentUnreadable = unreadable(current);
151
+ const candidateUnreadable = unreadable(project);
152
+ if (currentUnreadable !== candidateUnreadable) {
153
+ if (currentUnreadable) owner.set(key, project);
154
continue;
155
}
30
- if (current === preferredEnvironmentId) continue;
156
+ if (current.environmentId === preferredEnvironmentId) continue;
157
if (
158
project.environmentId === preferredEnvironmentId ||
33
- environmentRank < (rank.get(current) ?? Number.MAX_SAFE_INTEGER)
159
+ environmentRank < (rank.get(current.environmentId) ?? Number.MAX_SAFE_INTEGER)
160
) {
35
- owner.set(key, project.environmentId);
161
+ owner.set(key, project);
162
}
163
}
164
const assignment = new Map<EnvironmentId, ProjectId[]>();
165
for (const project of projects) {
166
if (!rank.has(project.environmentId)) continue;
167
const key = repositoryKey(project);
42
- if (key && owner.get(key) !== project.environmentId) continue;
168
+ if (key && owner.get(key)?.environmentId !== project.environmentId) continue;
169
const listed = assignment.get(project.environmentId);
170
if (listed === undefined) assignment.set(project.environmentId, [project.id]);
171
else listed.push(project.id);
@@ -47,6 +173,39 @@ export function assignProjectsToEnvironments(
173
return assignment;
174
}
175
176
+export function pullRequestProjectQueries(
177
+ projects: ReadonlyArray<AssignableProject>,
178
+ environmentIds: ReadonlyArray<EnvironmentId>,
179
+ hostAvailability?: PullRequestHostAvailability,
180
+): ReadonlyArray<{
181
+ readonly environmentId: EnvironmentId;
182
+ readonly projectIds?: ReadonlyArray<ProjectId>;
183
+}> {
184
+ const assignment = assignProjectsToEnvironments(
185
+ projects,
186
+ environmentIds,
187
+ environmentIds[0],
188
+ hostAvailability,
189
+ );
190
+ const totals = new Map<EnvironmentId, number>();
191
+ for (const project of projects)
192
+ totals.set(project.environmentId, (totals.get(project.environmentId) ?? 0) + 1);
193
+ return environmentIds.flatMap((environmentId) => {
194
+ const projectIds = assignment.get(environmentId);
195
+ if (projectIds === undefined) return [];
196
+ if (projectIds.length === totals.get(environmentId)) return [{ environmentId }];
197
+ const queries: Array<{ environmentId: EnvironmentId; projectIds: ReadonlyArray<ProjectId> }> =
198
+ [];
199
+ for (let offset = 0; offset < projectIds.length; offset += PULL_REQUEST_LIST_PROJECT_LIMIT) {
200
+ queries.push({
201
+ environmentId,
202
+ projectIds: projectIds.slice(offset, offset + PULL_REQUEST_LIST_PROJECT_LIMIT),
203
+ });
204
+ }
205
+ return queries;
206
+ });
207
+}
208
+
209
export interface PickableEnvironment {
210
readonly environmentId: EnvironmentId;
211
readonly projectId: ProjectId;
apps/web/src/components/pullRequest/usePullRequestListView.ts
+17
-19
@@ -35,7 +35,10 @@ import {
35
} from "./pullRequestList.logic";
36
import type { PullRequestExpectedHost } from "./PullRequestListFilters";
37
import type { PullRequestListPreferences, PullRequestListSort } from "./pullRequestListPreferences";
38
-import { assignProjectsToEnvironments } from "./pullRequestProjectAssignment.logic";
38
+import {
39
+ pullRequestProjectQueries,
40
+ type PullRequestHostAvailability,
41
+} from "./pullRequestProjectAssignment.logic";
42
import { pullRequestFilterProjects } from "@t3tools/client-runtime/pull-request-project-filter";
43
import { pullRequestListEntryId } from "./pullRequestListGroups.logic";
44
@@ -54,7 +57,10 @@ export interface PullRequestsSearch extends PullRequestListPreferences {
57
const SEARCH_DEBOUNCE_MS = 250;
58
59
/** Which servers and projects the page reads, from the URL and what this client knows. */
57
-export function usePullRequestScope(search: PullRequestsSearch) {
60
+export function usePullRequestScope(
61
+ search: PullRequestsSearch,
62
+ hostAvailability: PullRequestHostAvailability,
63
+) {
64
const { environments } = useEnvironments();
65
const allProjects = useProjects();
66
const projectsKnown = useAllEnvironmentShellsBootstrapped();
@@ -115,28 +121,19 @@ export function usePullRequestScope(search: PullRequestsSearch) {
121
scopedProjectId,
122
projectsKnown,
123
);
118
- const environmentQueries = ((): ReadonlyArray<{
124
+ const queriesFor = (
125
+ availability?: PullRequestHostAvailability,
126
+ ): ReadonlyArray<{
127
readonly environmentId: EnvironmentId;
128
readonly projectIds?: ReadonlyArray<ProjectId>;
129
}> => {
130
const plain = queryEnvironmentIds.map((environmentId) => ({ environmentId }));
131
if (!projectsKnown || scopedProjectId !== undefined) return plain;
124
- const assignment = assignProjectsToEnvironments(
125
- projects,
126
- queryEnvironmentIds,
127
- queryEnvironmentIds[0],
128
- );
129
- const totals = new Map<EnvironmentId, number>();
130
- for (const project of projects) {
131
- totals.set(project.environmentId, (totals.get(project.environmentId) ?? 0) + 1);
132
- }
133
- return queryEnvironmentIds.flatMap((environmentId) => {
134
- const projectIds = assignment.get(environmentId);
135
- if (projectIds === undefined) return [];
136
- if (projectIds.length === (totals.get(environmentId) ?? 0)) return [{ environmentId }];
137
- return [{ environmentId, projectIds }];
138
- });
139
- })();
132
+ return pullRequestProjectQueries(projects, queryEnvironmentIds, availability);
133
+ };
134
+ const environmentQueries = queriesFor(hostAvailability);
135
+ // What the page reads once a refresh forgets host reads; refresh must refetch these too.
136
+ const preferredEnvironmentQueries = queriesFor();
137
const assignmentKey = environmentQueries
138
.map(({ environmentId, projectIds }) => `${environmentId}#${projectIds?.join("+") ?? "*"}`)
139
.join("|");
@@ -186,6 +183,7 @@ export function usePullRequestScope(search: PullRequestsSearch) {
183
selectedProject,
184
queryEnvironmentIds,
185
environmentQueries,
186
+ preferredEnvironmentQueries,
187
assignmentKey,
188
linkedSelection,
189
expectedHosts,
apps/web/src/state/pullRequests.test.ts
+34
@@ -4,10 +4,14 @@ import {
4
ProjectId,
5
type PullRequestListEntry,
6
type PullRequestListInput,
7
+ PullRequestUnavailableError,
8
+ PullRequestOperationError,
9
type PullRequestListResult,
10
type PullRequestSummary,
11
} from "@t3tools/contracts";
12
import { describe, expect, it, vi } from "vite-plus/test";
13
+import * as Cause from "effect/Cause";
14
+import { AsyncResult } from "effect/reactivity";
15
16
import {
17
newestPullRequestObservation,
@@ -19,8 +23,38 @@ import {
23
restorePullRequestList,
24
restoredPullRequestList,
25
threadPullRequestLinkToSummary,
26
+ observeFailedPullRequestList,
27
} from "./pullRequests";
28
29
+it("observes both typed list failures without changing their status or replaying cached timestamps", () => {
30
+ const listResult: PullRequestListResult = {
31
+ viewers: {},
32
+ providers: [],
33
+ entries: [],
34
+ errors: [],
35
+ truncated: false,
36
+ nextCursors: {},
37
+ };
38
+ using clock = vi.spyOn(Date, "now").mockReturnValue(100);
39
+ for (const error of [
40
+ new PullRequestUnavailableError({ reason: "cli-unauthenticated", listResult }),
41
+ new PullRequestOperationError({ operation: "list", detail: "HTTP 403", listResult }),
42
+ ]) {
43
+ clock.mockReturnValue(100);
44
+ const failure = AsyncResult.failure<PullRequestListResult, unknown>(Cause.fail(error));
45
+ expect(observeFailedPullRequestList(failure)).toEqual({ value: listResult, observedAt: 100 });
46
+ clock.mockReturnValue(200);
47
+ expect(observeFailedPullRequestList(failure)?.observedAt).toBe(100);
48
+ expect(failure._tag).toBe("Failure");
49
+ expect(observeFailedPullRequestList({ ...failure, waiting: true })).toBeUndefined();
50
+ }
51
+ expect(
52
+ observeFailedPullRequestList(
53
+ AsyncResult.failure(Cause.fail(new PullRequestUnavailableError({ reason: "cli-missing" }))),
54
+ ),
55
+ ).toBeUndefined();
56
+});
57
+
58
function summary(overrides: Partial<PullRequestSummary> = {}): PullRequestSummary {
59
return {
60
provider: SourceControlProviderKind.make("github"),
apps/web/src/state/pullRequests.ts
+57
-2
@@ -7,6 +7,8 @@ import {
7
} from "@t3tools/client-runtime/state/pull-requests";
8
import {
9
PullRequestListResult,
10
+ PullRequestOperationError,
11
+ PullRequestUnavailableError,
12
type EnvironmentId,
13
type ProjectId,
14
type PullRequestChecksState,
@@ -22,6 +24,7 @@ import {
24
threadPullRequestKeyOf,
25
visibleThreadPullRequests,
26
} from "@t3tools/client-runtime/thread-pull-requests";
27
+import * as Cause from "effect/Cause";
28
import * as Clock from "effect/Clock";
29
import * as Effect from "effect/Effect";
30
import * as Option from "effect/Option";
@@ -523,37 +526,81 @@ export interface EnvironmentQueryTarget<Input> {
526
}
527
528
interface MergedEnvironmentQueryView<A> {
529
+ readonly observations: ReadonlyArray<readonly [EnvironmentId, A, number]>;
530
readonly values: ReadonlyArray<readonly [EnvironmentId, A]>;
531
readonly error: string | null;
532
readonly isPending: boolean;
533
}
534
535
+const failedListObservedAt = new WeakMap<object, number>();
536
+const isUnavailableList = Schema.is(PullRequestUnavailableError);
537
+const isFailedList = Schema.is(PullRequestOperationError);
538
+
539
+export function observeFailedPullRequestList(
540
+ result: AsyncResult.Failure<PullRequestListResult, unknown>,
541
+): { readonly value: PullRequestListResult; readonly observedAt: number } | undefined {
542
+ if (result.waiting) return undefined;
543
+ const error = Option.getOrNull(Cause.findErrorOption(result.cause));
544
+ if ((!isUnavailableList(error) && !isFailedList(error)) || error.listResult === undefined) {
545
+ return undefined;
546
+ }
547
+ let observedAt = failedListObservedAt.get(result.cause);
548
+ if (observedAt === undefined) {
549
+ observedAt = Date.now();
550
+ failedListObservedAt.set(result.cause, observedAt);
551
+ }
552
+ return { value: error.listResult, observedAt };
553
+}
554
+
555
// Use one derived atom for variable fan-out; unreachable environments must not hide other rows.
556
function createMergedEnvironmentQuery<Input, A>(
557
label: string,
558
atomFor: (
559
target: EnvironmentQueryTarget<Input>,
560
) => Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
561
+ observeFailure?: (
562
+ result: AsyncResult.Failure<A, unknown>,
563
+ ) => { readonly value: A; readonly observedAt: number } | undefined,
564
) {
565
const family = Atom.family((key: string) =>
566
Atom.make((get): MergedEnvironmentQueryView<A> => {
567
const targets = JSON.parse(key) as ReadonlyArray<EnvironmentQueryTarget<Input>>;
568
const values: Array<readonly [EnvironmentId, A]> = [];
569
+ const observations: Array<readonly [EnvironmentId, A, number]> = [];
570
+ const pendingEnvironments = new Set<EnvironmentId>();
571
let error: string | null = null;
572
let isPending = false;
573
for (const target of targets) {
574
const result = get(atomFor(target));
575
isPending ||= result.waiting;
576
+ if (result.waiting) pendingEnvironments.add(target.environmentId);
577
if (result._tag === "Failure" && error === null) {
578
error = formatEnvironmentQueryError(result.cause);
579
}
580
const value = AsyncResult.getOrElse(result, () => null);
581
if (value !== null) values.push([target.environmentId, value]);
582
+ if (result._tag === "Success") {
583
+ observations.push([target.environmentId, result.value, result.timestamp]);
584
+ } else if (result._tag === "Failure") {
585
+ const observation = observeFailure?.(result);
586
+ if (observation !== undefined) {
587
+ observations.push([target.environmentId, observation.value, observation.observedAt]);
588
+ }
589
+ }
590
}
553
- return { values, error, isPending };
591
+ return {
592
+ values,
593
+ error,
594
+ isPending,
595
+ // Another batch can still find a readable checkout on this environment.
596
+ observations: observations.filter(
597
+ ([environmentId]) => !pendingEnvironments.has(environmentId),
598
+ ),
599
+ };
600
}).pipe(Atom.withLabel(`${label}:${key}`)),
601
);
602
const empty = Atom.make<MergedEnvironmentQueryView<A>>({
603
+ observations: [],
604
values: [],
605
error: null,
606
isPending: false,
@@ -575,6 +622,7 @@ function createMergedEnvironmentQuery<Input, A>(
622
const usePullRequestListsQuery = createMergedEnvironmentQuery(
623
"web-pull-requests:list",
624
pullRequestEnvironment.list,
625
+ observeFailedPullRequestList,
626
);
627
628
const usePullRequestStatsQuery = createMergedEnvironmentQuery(
@@ -610,6 +658,7 @@ export interface MergedPullRequestListView {
658
readonly data: MergedPullRequestList | null;
659
readonly error: string | null;
660
readonly isPending: boolean;
661
+ readonly observations: ReadonlyArray<readonly [EnvironmentId, PullRequestListResult, number]>;
662
readonly refresh: (targets?: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>>) => void;
663
}
664
@@ -618,7 +667,13 @@ export function usePullRequestList(
667
): MergedPullRequestListView {
668
const query = usePullRequestListsQuery(targets);
669
const data = mergePullRequestLists(query.values);
621
- return { data, error: query.error, isPending: query.isPending, refresh: query.refresh };
670
+ return {
671
+ data,
672
+ error: query.error,
673
+ isPending: query.isPending,
674
+ observations: query.observations,
675
+ refresh: query.refresh,
676
+ };
677
}
678
679
export function usePullRequestListStats(
packages/contracts/src/pullRequest.ts
+9
-1
@@ -371,12 +371,16 @@ export const PullRequestListCursors = Schema.Record(
371
);
372
export type PullRequestListCursors = typeof PullRequestListCursors.Type;
373
374
+export const PULL_REQUEST_LIST_PROJECT_LIMIT = 100;
375
+
376
export const PullRequestListInput = Schema.Struct({
377
state: PullRequestListState,
378
involvement: Schema.optional(PullRequestInvolvement),
379
filters: Schema.optional(PullRequestListFilters),
380
projectId: Schema.optional(ProjectId),
379
- projectIds: Schema.optional(Schema.Array(ProjectId).check(Schema.isMaxLength(100))),
381
+ projectIds: Schema.optional(
382
+ Schema.Array(ProjectId).check(Schema.isMaxLength(PULL_REQUEST_LIST_PROJECT_LIMIT)),
383
+ ),
384
host: Schema.optional(TrimmedNonEmptyString),
385
limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 500 }))),
386
cursors: Schema.optional(PullRequestListCursors),
@@ -390,6 +394,8 @@ export const PullRequestProviderSummary = Schema.Struct({
394
searchesOnHost: Schema.Boolean,
395
actions: Schema.optional(ForwardCompatibleArray(PullRequestAction)),
396
projectCount: PositiveInt,
397
+ /** SSH checkouts can resolve to an HTTP authority different from their stored identity. */
398
+ projectIds: Schema.optional(Schema.Array(ProjectId)),
399
configured: Schema.Boolean,
400
detail: Schema.NullOr(TrimmedNonEmptyString),
401
});
@@ -939,6 +945,7 @@ export class PullRequestUnavailableError extends Schema.TaggedError<PullRequestU
945
{
946
reason: PullRequestUnavailableReason,
947
provider: Schema.optional(SourceControlProviderKind),
948
+ listResult: Schema.optional(PullRequestListResult),
949
/**
950
* What the host needs on the server, in its own words. Absent from older servers, which
951
* shipped no such field, and for a host that names nothing.
@@ -970,6 +977,7 @@ export class PullRequestOperationError extends Schema.TaggedError<PullRequestOpe
977
operation: Schema.String,
978
detail: TrimmedNonEmptyString,
979
reason: Schema.optional(Schema.Literal("not-found")),
980
+ listResult: Schema.optional(PullRequestListResult),
981
cause: Schema.optional(Schema.Defect()),
982
},
983
{ httpApiStatus: 502 },