Skip to content

Commit 53e0f47

Browse files
versecafeclaude
andcommitted
fix(gitcafe): settle the PR list, explain paused stacks, respect locks, harden transport
- The PR list hears every finished action again, as before GitCafe's durable merges scoped its own refresh to the visible pull request. - Paused restacks and landings say they are waiting on the reader. - A locked conversation offers its composer to moderators only. - API calls and attachment downloads never follow a redirect with the token. - A refused token from a refreshed cafe login is retried once. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f43f8b1 commit 53e0f47

9 files changed

Lines changed: 144 additions & 61 deletions

File tree

‎apps/server/src/assets/GitCafeAttachment.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import * as Effect from "effect/Effect";
22
import * as Redacted from "effect/Redacted";
33
import * as Schema from "effect/Schema";
44
import * as Stream from "effect/Stream";
5-
import { HttpClient, HttpClientRequest } from "effect/http";
5+
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
66

77
import * as GitCafeCredentials from "../sourceControl/GitCafeCredentials.ts";
88

@@ -44,7 +44,11 @@ export const downloadGitCafeAttachment = Effect.fn("GitCafeAttachment.download")
4444
HttpClientRequest.setHeader("user-agent", "t3code"),
4545
),
4646
)
47-
.pipe(Effect.provideService(HttpClient.TracerDisabledWhen, () => true));
47+
.pipe(
48+
Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
49+
// GitCafe serves attachment bytes in place; a redirect is never followed with the token.
50+
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
51+
);
4852
if (response.status === 401) yield* credentials.invalidate(host);
4953
if (response.status < 200 || response.status >= 300) return null;
5054
return yield* collectBounded(response.stream, MAX_ATTACHMENT_BYTES);

‎apps/server/src/pullRequest/GitCafePullRequestProvider.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,20 @@ describe("deployed GitCafe PR API", () => {
8484
expect(permissions.actions).toEqual([]);
8585
});
8686

87+
it("keeps a locked conversation's composer for moderators only", () => {
88+
const locked = (moderate: boolean) =>
89+
gitCafeViewerPermissions({
90+
...detail,
91+
state: "open",
92+
author: { ...detail.author, kind: "local" },
93+
mergeRoute: "native",
94+
lockedAt: time,
95+
capabilities: { comment: false, review: false, merge: false, edit: false, moderate },
96+
}).comment;
97+
expect(locked(false)).toBe(false);
98+
expect(locked(true)).toBe(true);
99+
});
100+
87101
it.effect.each([
88102
["merged", 404, true],
89103
["closed", 404, true],

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,9 @@ export function gitCafeViewerPermissions(
223223
],
224224
stackRebase: merge,
225225
// Pull projections cannot attest to a grant's independent comment selectors. Like cafe pr
226-
// comment, offer the write and let the comment endpoint authorize it.
227-
comment: true,
226+
// comment, offer the write and let the comment endpoint authorize it, except on a locked
227+
// conversation, where only moderators may still speak.
228+
comment: pull?.lockedAt == null || moderate,
228229
resolve: moderate,
229230
verdicts: review ? ["approve", "request-changes", "comment"] : [],
230231
requestReviewers: moderate,

‎apps/server/src/pullRequest/gitCafeActionWrites.test.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,10 @@ describe("GitCafe action writes", () => {
231231
state: "pending",
232232
operation: { kind: "stack-restack", id: "prsrop_01bbbbbbbbbbbbbbbbbbbbbbbb" },
233233
});
234+
// Pending, but it says the reader has to act rather than wait.
235+
expect(pending?.detail).toBe(
236+
"Stack restack is paused on a conflict and needs you on GitCafe: 1/2 pull requests restacked; Resolve conflicts.",
237+
);
234238
expect(latest.calls[0]?.endpoint.endsWith("/pulls/stacks/3/restacks/latest")).toBe(true);
235239
expect(latest.calls[0]?.method).toBeUndefined();
236240
}),

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,13 @@ interface MergeBody {
124124
readonly strategy: string;
125125
}
126126

127+
/** Paused stack states that only a person can move on, by what they are waiting for. */
128+
const NEEDS_ATTENTION: Partial<Record<string, string>> = {
129+
paused_conflict: "paused on a conflict",
130+
paused_policy: "paused by a branch policy",
131+
awaiting_credential: "waiting for a credential",
132+
};
133+
127134
export function makeGitCafeActionWrites(cli: GitCafeCli.GitCafeCli["Service"]) {
128135
const request = gitCafeWriteApi(cli);
129136
/**
@@ -162,10 +169,16 @@ export function makeGitCafeActionWrites(cli: GitCafeCli.GitCafeCli["Service"]) {
162169
: `${outcome.completedStepCount}/${outcome.stepCount} pull requests restacked`;
163170
const problem =
164171
"error" in outcome ? (outcome.error ?? outcome.stopReason) : outcome.pauseReason;
172+
const label = kind === "stack-land" ? "Stack landing" : "Stack restack";
173+
// Still pending, because GitCafe resumes it, but waiting on the reader rather than on time.
174+
const waitingOn = NEEDS_ATTENTION[outcome.state];
165175
return {
166176
operation: { kind, id: outcome.id },
167177
state: outcome.state === "completed" ? "completed" : failed ? "failed" : "pending",
168-
detail: `${kind === "stack-land" ? "Stack landing" : "Stack restack"} ${outcome.state}: ${progress}${problem ? `; ${problem.message}` : ""}.`,
178+
detail:
179+
waitingOn === undefined
180+
? `${label} ${outcome.state}: ${progress}${problem ? `; ${problem.message}` : ""}.`
181+
: `${label} is ${waitingOn} and needs you on GitCafe: ${progress}${problem ? `; ${problem.message}` : ""}.`,
169182
};
170183
};
171184
const continueStackLand = Effect.fn("GitCafeActionWrites.continueStackLand")(function* (

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ export const PullDetailSchema = Schema.Struct({
7676
sourceRepo: Schema.NullOr(Schema.Struct({ owner: Schema.String, name: Schema.String })),
7777
observedBaseOid: Schema.optional(Schema.NullOr(Schema.String)),
7878
mergeRoute: Schema.optional(Schema.Literals(["native", "provider", "unsupported"])),
79+
lockedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
7980
capabilities: Schema.Struct({
8081
comment: Schema.Boolean,
8182
review: Schema.Boolean,

‎apps/server/src/sourceControl/GitCafeCli.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,34 @@ layer("GitCafeCli", (it) => {
430430
]);
431431
}),
432432
);
433+
it.effect.each([
434+
{ name: "a refreshed cafe login is retried once", source: "cafe", rotates: true, calls: 2 },
435+
{ name: "an unchanged cafe login is not retried", source: "cafe", rotates: false, calls: 1 },
436+
{ name: "an environment token is not retried", source: "env", rotates: true, calls: 1 },
437+
] as const)("after a 401, $name", (scenario) =>
438+
Effect.gen(function* () {
439+
let lookups = 0;
440+
getCredential.mockImplementation((host) =>
441+
Effect.succeed({
442+
host,
443+
token: Redacted.make(scenario.rotates && lookups++ > 0 ? "new-token" : "old-token"),
444+
source: scenario.source,
445+
}),
446+
);
447+
http.mockImplementation((request) =>
448+
request.headers.authorization === "Bearer new-token"
449+
? reply({ handle: "alice" })
450+
: reply({ type: "https://cafe.sh/errors/authentication-required" }, 401),
451+
);
452+
const cafe = yield* GitCafeCli.GitCafeCli;
453+
const result = yield* cafe
454+
.api({ cwd: "/repo", endpoint: "/auth/principal" })
455+
.pipe(Effect.result);
456+
expect(http).toHaveBeenCalledTimes(scenario.calls);
457+
expect(result._tag).toBe(scenario.calls === 2 ? "Success" : "Failure");
458+
expect(invalidateCredential).toHaveBeenCalledWith("git.cafe");
459+
}),
460+
);
433461
it.effect("maps problem documents to codes and drops a refused token", () =>
434462
Effect.gen(function* () {
435463
const cafe = yield* GitCafeCli.GitCafeCli;

‎apps/server/src/sourceControl/GitCafeCli.ts‎

Lines changed: 71 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import * as PlatformError from "effect/PlatformError";
77
import * as Redacted from "effect/Redacted";
88
import * as Result from "effect/Result";
99
import * as Schema from "effect/Schema";
10-
import { HttpClient, HttpClientRequest } from "effect/http";
10+
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
1111
import { PositiveInt, TrimmedNonEmptyString, type ChangeRequest } from "@t3tools/contracts";
1212

1313
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
@@ -258,70 +258,86 @@ export const make = Effect.gen(function* () {
258258
detail,
259259
...(cause === undefined ? {} : { cause }),
260260
});
261-
const { token } = yield* credentials
262-
.get(host)
263-
.pipe(
264-
Effect.mapError((cause) =>
265-
failed(
266-
cause._tag === "GitCafeCliMissingError"
267-
? "CLI_UNAVAILABLE"
268-
: cause._tag === "GitCafeNotSignedInError"
269-
? "AUTHENTICATION_REQUIRED"
270-
: "COMMAND_FAILED",
271-
null,
272-
cause.message,
273-
cause,
261+
const credential = () =>
262+
credentials
263+
.get(host)
264+
.pipe(
265+
Effect.mapError((cause) =>
266+
failed(
267+
cause._tag === "GitCafeCliMissingError"
268+
? "CLI_UNAVAILABLE"
269+
: cause._tag === "GitCafeNotSignedInError"
270+
? "AUTHENTICATION_REQUIRED"
271+
: "COMMAND_FAILED",
272+
null,
273+
cause.message,
274+
cause,
275+
),
274276
),
275-
),
277+
);
278+
const send = (token: Redacted.Redacted<string>) => {
279+
const base = HttpClientRequest.make(
280+
(input.method ?? "GET") as HttpClientRequest.HttpClientRequest["method"],
281+
)(`https://${host}/api${input.endpoint}`).pipe(
282+
HttpClientRequest.bearerToken(Redacted.value(token)),
283+
HttpClientRequest.setHeaders({
284+
accept: "application/json",
285+
"user-agent": "t3code",
286+
...input.headers,
287+
}),
276288
);
277-
const base = HttpClientRequest.make(
278-
(input.method ?? "GET") as HttpClientRequest.HttpClientRequest["method"],
279-
)(`https://${host}/api${input.endpoint}`).pipe(
280-
HttpClientRequest.bearerToken(Redacted.value(token)),
281-
HttpClientRequest.setHeaders({
282-
accept: "application/json",
283-
"user-agent": "t3code",
284-
...input.headers,
285-
}),
286-
);
287-
const request =
288-
input.body === undefined ? base : HttpClientRequest.bodyJsonUnsafe(base, input.body);
289-
const { status, collected } = yield* Effect.gen(function* () {
290-
const response = yield* httpClient
291-
.execute(request)
292-
// The client's own span would record the query string, which can carry branch names.
293-
.pipe(Effect.provideService(HttpClient.TracerDisabledWhen, () => true));
294-
const collected = yield* collectUint8StreamText({
295-
stream: response.stream,
296-
maxBytes: input.maxOutputBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
289+
return input.body === undefined ? base : HttpClientRequest.bodyJsonUnsafe(base, input.body);
290+
};
291+
const exchange = (request: HttpClientRequest.HttpClientRequest) =>
292+
Effect.gen(function* () {
293+
const response = yield* httpClient.execute(request).pipe(
294+
// The client's own span would record the query string, which can carry branch names.
295+
Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
296+
// A redirect is never followed with the token attached; GitCafe's API answers in place.
297+
Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }),
298+
);
299+
const collected = yield* collectUint8StreamText({
300+
stream: response.stream,
301+
maxBytes: input.maxOutputBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
302+
}).pipe(
303+
// 204 and many refusals carry no body at all, which is an empty answer.
304+
Effect.catchIf(
305+
(cause) => cause.reason._tag === "EmptyBodyError",
306+
() => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
307+
),
308+
);
309+
return { status: response.status, collected };
297310
}).pipe(
298-
// 204 and many refusals carry no body at all, which is an empty answer.
299-
Effect.catchIf(
300-
(cause) => cause.reason._tag === "EmptyBodyError",
301-
() => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
311+
Effect.timeout(API_TIMEOUT),
312+
Effect.mapError((cause) =>
313+
cause._tag === "TimeoutError"
314+
? failed(
315+
"TIMEOUT",
316+
null,
317+
`GitCafe did not answer within ${Duration.toSeconds(API_TIMEOUT)} seconds. Check the connection and try refreshing.`,
318+
cause,
319+
)
320+
: failed("COMMAND_FAILED", null, "Could not reach GitCafe.", cause),
302321
),
303322
);
304-
return { status: response.status, collected };
305-
}).pipe(
306-
Effect.timeout(API_TIMEOUT),
307-
Effect.mapError((cause) =>
308-
cause._tag === "TimeoutError"
309-
? failed(
310-
"TIMEOUT",
311-
null,
312-
`GitCafe did not answer within ${Duration.toSeconds(API_TIMEOUT)} seconds. Check the connection and try refreshing.`,
313-
cause,
314-
)
315-
: failed("COMMAND_FAILED", null, "Could not reach GitCafe.", cause),
316-
),
317-
);
323+
const first = yield* credential();
324+
let answer = yield* exchange(send(first.token));
325+
// The source may hold a newer token than the one that was refused. A `cafe` login that was
326+
// just refreshed answers again with the new one, once; an environment token cannot change.
327+
if (answer.status === 401) {
328+
yield* credentials.invalidate(host);
329+
if (first.source === "cafe") {
330+
const fresh = yield* credential();
331+
if (Redacted.value(fresh.token) !== Redacted.value(first.token))
332+
answer = yield* exchange(send(fresh.token));
333+
}
334+
}
335+
const { status, collected } = answer;
318336
if (status >= 200 && status < 300) {
319337
if (collected.truncated)
320338
return yield* failed("RESPONSE_TOO_LARGE", status, "GitCafe's response was too large.");
321339
return collected.text;
322340
}
323-
// The source may hold a newer token than the one that was refused.
324-
if (status === 401) yield* credentials.invalidate(host);
325341
const problem = Option.getOrUndefined(decodeProblem(collected.text));
326342
return yield* failed(
327343
problemCode(problem?.type, status),

‎apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1115,14 +1115,16 @@ export function PullRequestDetailPanel({
11151115
// through that path rather than a second one. Every other action here only changes metadata;
11161116
// a merge does move the branch too, but it also closes the pull request, where the diff is
11171117
// no longer what anyone is looking at.
1118+
// Only the panel's own reads are scoped to the pull request still on screen; the list hears
1119+
// about every finished action, so its note on the acted row is always settled.
11181120
if (isCurrentScope) {
11191121
if (pullRequestActionNeedsHostRefresh(action)) {
11201122
void refreshFromHost();
11211123
} else {
11221124
refreshDetail();
11231125
}
1124-
onActed?.(action, "done");
11251126
}
1127+
onActed?.(action, "done");
11261128
return true;
11271129
};
11281130

0 commit comments

Comments
 (0)