Skip to content

Commit 70e5e38

Browse files
authored
fix(server): sync pull request draft status changes (pingdotgg#22832)
1 parent 1befc71 commit 70e5e38

8 files changed

Lines changed: 268 additions & 76 deletions

File tree

‎apps/server/src/git/GitManager.test.ts‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import * as PlatformError from "effect/PlatformError";
1717
import * as Result from "effect/Result";
1818
import * as Schema from "effect/Schema";
1919
import * as Scope from "effect/Scope";
20+
import * as Stream from "effect/Stream";
2021
import { ChildProcessSpawner } from "effect/process";
2122
import { expect } from "vite-plus/test";
2223
import type {
@@ -1076,6 +1077,62 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
10761077
}),
10771078
);
10781079

1080+
it.effect("branch PR lookup notifies linked threads when draft status changes", () =>
1081+
Effect.gen(function* () {
1082+
const repoDir = yield* makeTempDir("t3code-git-manager-");
1083+
yield* initRepo(repoDir);
1084+
yield* runGit(repoDir, ["checkout", "-b", "feature/draft-status"]);
1085+
const remoteDir = yield* createBareRemote();
1086+
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
1087+
yield* runGit(repoDir, ["push", "-u", "origin", "feature/draft-status"]);
1088+
const drafts = [false, true, true, false, false, true];
1089+
const pullRequest = {
1090+
number: 1,
1091+
title: "Draft status",
1092+
url: "https://github.com/pingdotgg/codething-mvp/pull/1",
1093+
baseRefName: "main",
1094+
headRefName: "feature/draft-status",
1095+
state: "OPEN",
1096+
};
1097+
const { manager } = yield* makeManager({
1098+
ghScenario: {
1099+
prListSequence: [
1100+
...drafts.map((isDraft) => encodeCliJson([{ ...pullRequest, isDraft }])),
1101+
encodeCliJson([
1102+
{
1103+
...pullRequest,
1104+
number: 2,
1105+
url: "https://github.com/pingdotgg/codething-mvp/pull/2",
1106+
state: "MERGED",
1107+
},
1108+
]),
1109+
],
1110+
},
1111+
});
1112+
const changes = yield* manager.subscribePullRequestStateChanges;
1113+
for (const isDraft of drafts) {
1114+
const pr = yield* manager.branchPullRequest(
1115+
{ cwd: repoDir, branch: "feature/draft-status" },
1116+
{ refresh: true },
1117+
);
1118+
expect(pr?.isDraft === true).toBe(isDraft);
1119+
}
1120+
// A different PR ends collection without waiting on a background stream consumer.
1121+
yield* manager.branchPullRequest(
1122+
{ cwd: repoDir, branch: "feature/draft-status" },
1123+
{ refresh: true },
1124+
);
1125+
const events = yield* Stream.runCollect(
1126+
changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })),
1127+
);
1128+
expect(events).toEqual([
1129+
{ host: "github.com", repository: "pingdotgg/codething-mvp", number: 1 },
1130+
{ host: "github.com", repository: "pingdotgg/codething-mvp", number: 1 },
1131+
{ host: "github.com", repository: "pingdotgg/codething-mvp", number: 1 },
1132+
]);
1133+
}),
1134+
);
1135+
10791136
it.effect("branch PR lookup uses a saved tracked branch without changing checkout", () =>
10801137
Effect.gen(function* () {
10811138
const repoDir = yield* makeTempDir("t3code-git-manager-");

‎apps/server/src/git/GitManager.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1195,21 +1195,27 @@ export const make = Effect.gen(function* () {
11951195
return prLookupFailureTtl(streak);
11961196
};
11971197
const pullRequestStateChanges = yield* PubSub.sliding<ThreadPullRequestKey>(64);
1198-
const lookupStates = new Map<string, PullRequestInfo["state"]>();
1198+
const lookupStates = new Map<
1199+
string,
1200+
{ readonly state: PullRequestInfo["state"]; readonly isDraft: boolean }
1201+
>();
11991202
const noteLookupState = (pr: PullRequestInfo) =>
12001203
Effect.suspend(() => {
12011204
const parsed = parseChangeRequestUrl(pr.url);
12021205
if (parsed === null || parsed.number !== pr.number) return Effect.void;
12031206
const key = normalizeThreadPullRequestKey(parsed);
12041207
const id = threadPullRequestKeyOf(key);
1205-
const previous = lookupStates.get(id) ?? "open";
1208+
const previous = lookupStates.get(id);
12061209
lookupStates.delete(id);
12071210
if (lookupStates.size >= PR_LOOKUP_CACHE_CAPACITY) {
12081211
const oldest = lookupStates.keys().next().value;
12091212
if (oldest !== undefined) lookupStates.delete(oldest);
12101213
}
1211-
lookupStates.set(id, pr.state);
1212-
return previous === pr.state ? Effect.void : PubSub.publish(pullRequestStateChanges, key);
1214+
lookupStates.set(id, { state: pr.state, isDraft: pr.isDraft === true });
1215+
return (previous?.state ?? "open") === pr.state &&
1216+
(previous?.isDraft === true) === (pr.isDraft === true)
1217+
? Effect.void
1218+
: PubSub.publish(pullRequestStateChanges, key);
12131219
});
12141220
const prLookupCache = yield* Cache.makeWith(
12151221
(key: string) => {

‎apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,6 +913,43 @@ describe("PullRequestSyncReactor", () => {
913913
),
914914
);
915915

916+
it.effect.each([true, false])(
917+
"syncs linked draft status %s as soon as a reader reports a change",
918+
(isDraft) =>
919+
Effect.gen(function* () {
920+
yield* TestClock.setTime(Date.parse(NOW));
921+
const draft = yield* Ref.make(!isDraft);
922+
const invalidated = yield* Ref.make<ReadonlyArray<number>>([]);
923+
const fixture = yield* makeHarness({
924+
snapshot: makeSnapshot([
925+
makeThread("agent", { pullRequests: [makeLink(7, { isDraft: !isDraft })] }),
926+
]),
927+
summary: (input) =>
928+
Ref.get(draft).pipe(Effect.map((isDraft) => makeSummary(input, { isDraft }))),
929+
invalidate: ({ reference }) =>
930+
Ref.update(invalidated, (numbers) => [...numbers, reference?.number ?? -1]),
931+
});
932+
933+
yield* Effect.gen(function* () {
934+
const reactor = yield* startAndSweep(fixture);
935+
yield* Ref.set(draft, isDraft);
936+
yield* Queue.offer(fixture.stateChanges, {
937+
host: "github.com",
938+
repository: "owner/repository",
939+
number: 7,
940+
});
941+
yield* Queue.take(fixture.snapshotReads);
942+
yield* reactor.drain;
943+
944+
assert.deepStrictEqual(yield* Ref.get(invalidated), [7]);
945+
assert.deepStrictEqual(
946+
(yield* Ref.get(fixture.syncCommands)).map((command) => command.snapshot.isDraft),
947+
[isDraft],
948+
);
949+
}).pipe(Effect.provide(fixture.layer));
950+
}),
951+
);
952+
916953
it.effect("preserves a refresh requested while an older host read is in flight", () =>
917954
Effect.scoped(
918955
Effect.gen(function* () {

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2680,6 +2680,74 @@ it.effect(
26802680
}),
26812681
);
26822682

2683+
it.effect("notifies linked threads when detail changes draft status in either direction", () =>
2684+
Effect.gen(function* () {
2685+
let isDraft = true;
2686+
let updatedAt = "2026-07-02T00:00:00Z";
2687+
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
2688+
const service = yield* makeService({
2689+
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2690+
providers: [
2691+
fakeProvider(SourceControlProviderKind.make("github"), {
2692+
getChangeRequest: () =>
2693+
Effect.sync(() => ({ ...hostedChangeRequest("body"), isDraft, updatedAt })),
2694+
}),
2695+
],
2696+
});
2697+
const changes = yield* service.subscribeStateChanges;
2698+
const read = () => service.detail({ ...reference, allowStale: false });
2699+
yield* read();
2700+
yield* read();
2701+
isDraft = false;
2702+
yield* service.invalidate({ reference });
2703+
yield* read();
2704+
yield* read();
2705+
isDraft = true;
2706+
yield* service.invalidate({ reference });
2707+
yield* read();
2708+
2709+
isDraft = false;
2710+
updatedAt = "2026-07-01T00:00:00Z";
2711+
yield* service.invalidate({ reference });
2712+
yield* read();
2713+
2714+
// A different PR ends collection after all the synchronous notifications above.
2715+
yield* service.reportState({ reference: { ...reference, number: 2 }, state: "open" });
2716+
const events = yield* Stream.runCollect(
2717+
changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })),
2718+
);
2719+
assert.deepStrictEqual(events, [
2720+
{ host: "github.com", repository: "acme/web", number: 1 },
2721+
{ host: "github.com", repository: "acme/web", number: 1 },
2722+
{ host: "github.com", repository: "acme/web", number: 1 },
2723+
]);
2724+
}),
2725+
);
2726+
2727+
it.effect("deduplicates routed PR reports without dropping draft changes", () =>
2728+
Effect.gen(function* () {
2729+
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
2730+
const service = yield* makeService({
2731+
projects: [project({ id: "p1", title: "web", workspaceRoot: "/a", repository: "acme/web" })],
2732+
providers: [fakeProvider(SourceControlProviderKind.make("github"))],
2733+
});
2734+
const changes = yield* service.subscribeStateChanges;
2735+
for (const isDraft of [true, true, false, false, true]) {
2736+
yield* service.reportState({ reference, state: "open", isDraft });
2737+
}
2738+
yield* service.reportState({ reference, state: "open" });
2739+
yield* service.reportState({ reference, state: "open" });
2740+
yield* service.reportState({ reference: { ...reference, number: 2 }, state: "open" });
2741+
const events = yield* Stream.runCollect(
2742+
changes.pipe(Stream.takeUntil((event) => event.number === 2, { excludeLast: true })),
2743+
);
2744+
assert.deepStrictEqual(
2745+
events.map((event) => event.number),
2746+
[1, 1, 1, 1],
2747+
);
2748+
}),
2749+
);
2750+
26832751
it.effect("reuses an observed merged state for strict settlement reads", () =>
26842752
Effect.gen(function* () {
26852753
const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };

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

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,10 @@ export interface PullRequestMergeEvent extends PullRequestRef {
102102
readonly mergedAt: string;
103103
}
104104

105-
type PullRequestReading = Pick<PullRequestSummary, "state" | "updatedAt" | "observedAt">;
105+
type PullRequestReading = Pick<
106+
PullRequestSummary,
107+
"state" | "isDraft" | "updatedAt" | "observedAt"
108+
>;
106109

107110
function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) {
108111
if (current === undefined) return true;
@@ -2891,10 +2894,12 @@ export const make = Effect.gen(function* () {
28912894
}
28922895
detailStates.set(scope, {
28932896
state: next.state,
2897+
isDraft: next.isDraft,
28942898
updatedAt: next.updatedAt,
28952899
observedAt: next.observedAt,
28962900
});
2897-
return current?.state !== next.state && ref.host !== undefined
2901+
return (current?.state !== next.state || current?.isDraft !== next.isDraft) &&
2902+
ref.host !== undefined
28982903
? PubSub.publish(stateChanges, {
28992904
host: ref.host,
29002905
repository: ref.repository,
@@ -2906,22 +2911,34 @@ export const make = Effect.gen(function* () {
29062911
// must never outrank a reading this environment made itself.
29072912
const reportedStates = new Map<
29082913
string,
2909-
{ readonly state: PullRequestState; readonly atMs: number }
2914+
{
2915+
readonly state: PullRequestState;
2916+
readonly isDraft: boolean | undefined;
2917+
readonly atMs: number;
2918+
}
29102919
>();
2911-
const reportState: PullRequestService["Service"]["reportState"] = ({ reference, state }) =>
2920+
const reportState: PullRequestService["Service"]["reportState"] = ({
2921+
reference,
2922+
state,
2923+
isDraft,
2924+
}) =>
29122925
Effect.all([canonicalRef(reference), Clock.currentTimeMillis]).pipe(
29132926
Effect.flatMap(([ref, nowMs]) =>
29142927
Effect.suspend(() => {
29152928
const scope = refScope(ref);
29162929
const reported = reportedStates.get(scope);
2917-
if (reported?.state === state && nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS)
2930+
if (
2931+
reported?.state === state &&
2932+
reported.isDraft === isDraft &&
2933+
nowMs - reported.atMs < REPORTED_STATE_DEDUPE_MS
2934+
)
29182935
return Effect.void;
29192936
reportedStates.delete(scope);
29202937
if (reportedStates.size >= REF_EPOCH_CAPACITY) {
29212938
const oldest = reportedStates.keys().next().value;
29222939
if (oldest !== undefined) reportedStates.delete(oldest);
29232940
}
2924-
reportedStates.set(scope, { state, atMs: nowMs });
2941+
reportedStates.set(scope, { state, isDraft, atMs: nowMs });
29252942
return ref.host === undefined
29262943
? Effect.void
29272944
: PubSub.publish(stateChanges, {

‎packages/client-runtime/src/state/pullRequestRouting.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,9 @@ const writes = new Set<string>([
6161
WS_METHODS.pullRequestsSetLabels,
6262
]);
6363
const isRef = Schema.is(PullRequestRef);
64-
const hasState = Schema.is(Schema.Struct({ state: PullRequestState }));
64+
const hasState = Schema.is(
65+
Schema.Struct({ state: PullRequestState, isDraft: Schema.optional(Schema.Boolean) }),
66+
);
6567
const isInvalidation = Schema.is(PullRequestInvalidateInput);
6668
const readTimeout = (environmentId: EnvironmentId) =>
6769
Effect.timeoutOrElse({
@@ -223,14 +225,13 @@ const invalidateTarget = Effect.fn("PullRequestRouting.invalidateTarget")(functi
223225
*/
224226
const reportState = (
225227
{ allowStale: _allowStale, expectedAccountId: _expectedAccountId, ...reference }: PullRequestRef,
226-
state: PullRequestState,
228+
status: { readonly state: PullRequestState; readonly isDraft?: boolean | undefined },
227229
) =>
228-
request(WS_METHODS.pullRequestsReportState, { reference, state }).pipe(
229-
Effect.timeoutOption("5 seconds"),
230-
Effect.ignore,
231-
Effect.forkDetach,
232-
Effect.asVoid,
233-
);
230+
request(WS_METHODS.pullRequestsReportState, {
231+
reference,
232+
state: status.state,
233+
...(status.isDraft === undefined ? {} : { isDraft: status.isDraft }),
234+
}).pipe(Effect.timeoutOption("5 seconds"), Effect.ignore, Effect.forkDetach, Effect.asVoid);
234235

235236
/** Credentials stay on their environments. Only a verified host and account cross the wire. */
236237
export function createPullRequestRouter() {
@@ -378,7 +379,7 @@ export function createPullRequestRouter() {
378379
).pipe(
379380
Effect.tap((result) =>
380381
id !== origin.target.environmentId && hasState(result)
381-
? reportState(ref, result.state)
382+
? reportState(ref, result)
382383
: Effect.void,
383384
),
384385
Effect.tap(() =>

0 commit comments

Comments
 (0)