@devries-cameron20 / t3code Mirror · read-only / commits / 70e5e384da
Fork 0

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, 19:30 UTC

fix(server): sync pull request draft status changes (#22832)

Yash Singh committed Oct 21, 2026 at 17:23 UTC 70e5e384dab96a1d1e4a253ee5a9415ed5d8ce30
8 files changed +268 -76
apps/server/src/git/GitManager.test.ts
+57
@@ -17,6 +17,7 @@ import * as PlatformError from "effect/PlatformError";
17 import * as Result from "effect/Result";
18 import * as Schema from "effect/Schema";
19 import * as Scope from "effect/Scope";
20 +import * as Stream from "effect/Stream";
21 import { ChildProcessSpawner } from "effect/process";
22 import { expect } from "vite-plus/test";
23 import type {
@@ -1076,6 +1077,62 @@ it.layer(layerGitManagerTest)("GitManager", (it) => {
1077 }),
1078 );
1079
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 +
1136 it.effect("branch PR lookup uses a saved tracked branch without changing checkout", () =>
1137 Effect.gen(function* () {
1138 const repoDir = yield* makeTempDir("t3code-git-manager-");
apps/server/src/git/GitManager.ts
+10 -4
@@ -1195,21 +1195,27 @@ export const make = Effect.gen(function* () {
1195 return prLookupFailureTtl(streak);
1196 };
1197 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 + >();
1202 const noteLookupState = (pr: PullRequestInfo) =>
1203 Effect.suspend(() => {
1204 const parsed = parseChangeRequestUrl(pr.url);
1205 if (parsed === null || parsed.number !== pr.number) return Effect.void;
1206 const key = normalizeThreadPullRequestKey(parsed);
1207 const id = threadPullRequestKeyOf(key);
1205 - const previous = lookupStates.get(id) ?? "open";
1208 + const previous = lookupStates.get(id);
1209 lookupStates.delete(id);
1210 if (lookupStates.size >= PR_LOOKUP_CACHE_CAPACITY) {
1211 const oldest = lookupStates.keys().next().value;
1212 if (oldest !== undefined) lookupStates.delete(oldest);
1213 }
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);
1219 });
1220 const prLookupCache = yield* Cache.makeWith(
1221 (key: string) => {
apps/server/src/orchestration-v2/PullRequestSyncReactor.test.ts
+37
@@ -913,6 +913,43 @@ describe("PullRequestSyncReactor", () => {
913 ),
914 );
915
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 +
953 it.effect("preserves a refresh requested while an older host read is in flight", () =>
954 Effect.scoped(
955 Effect.gen(function* () {
apps/server/src/pullRequest/PullRequestService.test.ts
+68
@@ -2680,6 +2680,74 @@ it.effect(
2680 }),
2681 );
2682
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 +
2751 it.effect("reuses an observed merged state for strict settlement reads", () =>
2752 Effect.gen(function* () {
2753 const reference = { projectId: "p1" as ProjectId, repository: "acme/web", number: 1 };
apps/server/src/pullRequest/PullRequestService.ts
+23 -6
@@ -102,7 +102,10 @@ export interface PullRequestMergeEvent extends PullRequestRef {
102 readonly mergedAt: string;
103 }
104
105 -type PullRequestReading = Pick<PullRequestSummary, "state" | "updatedAt" | "observedAt">;
105 +type PullRequestReading = Pick<
106 + PullRequestSummary,
107 + "state" | "isDraft" | "updatedAt" | "observedAt"
108 +>;
109
110 function supersedesReading(current: PullRequestReading | undefined, next: PullRequestReading) {
111 if (current === undefined) return true;
@@ -2891,10 +2894,12 @@ export const make = Effect.gen(function* () {
2894 }
2895 detailStates.set(scope, {
2896 state: next.state,
2897 + isDraft: next.isDraft,
2898 updatedAt: next.updatedAt,
2899 observedAt: next.observedAt,
2900 });
2897 - return current?.state !== next.state && ref.host !== undefined
2901 + return (current?.state !== next.state || current?.isDraft !== next.isDraft) &&
2902 + ref.host !== undefined
2903 ? PubSub.publish(stateChanges, {
2904 host: ref.host,
2905 repository: ref.repository,
@@ -2906,22 +2911,34 @@ export const make = Effect.gen(function* () {
2911 // must never outrank a reading this environment made itself.
2912 const reportedStates = new Map<
2913 string,
2909 - { readonly state: PullRequestState; readonly atMs: number }
2914 + {
2915 + readonly state: PullRequestState;
2916 + readonly isDraft: boolean | undefined;
2917 + readonly atMs: number;
2918 + }
2919 >();
2911 - const reportState: PullRequestService["Service"]["reportState"] = ({ reference, state }) =>
2920 + const reportState: PullRequestService["Service"]["reportState"] = ({
2921 + reference,
2922 + state,
2923 + isDraft,
2924 + }) =>
2925 Effect.all([canonicalRef(reference), Clock.currentTimeMillis]).pipe(
2926 Effect.flatMap(([ref, nowMs]) =>
2927 Effect.suspend(() => {
2928 const scope = refScope(ref);
2929 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 + )
2935 return Effect.void;
2936 reportedStates.delete(scope);
2937 if (reportedStates.size >= REF_EPOCH_CAPACITY) {
2938 const oldest = reportedStates.keys().next().value;
2939 if (oldest !== undefined) reportedStates.delete(oldest);
2940 }
2924 - reportedStates.set(scope, { state, atMs: nowMs });
2941 + reportedStates.set(scope, { state, isDraft, atMs: nowMs });
2942 return ref.host === undefined
2943 ? Effect.void
2944 : PubSub.publish(stateChanges, {
packages/client-runtime/src/state/pullRequestRouting.ts
+10 -9
@@ -61,7 +61,9 @@ const writes = new Set<string>([
61 WS_METHODS.pullRequestsSetLabels,
62 ]);
63 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 +);
67 const isInvalidation = Schema.is(PullRequestInvalidateInput);
68 const readTimeout = (environmentId: EnvironmentId) =>
69 Effect.timeoutOrElse({
@@ -223,14 +225,13 @@ const invalidateTarget = Effect.fn("PullRequestRouting.invalidateTarget")(functi
225 */
226 const reportState = (
227 { allowStale: _allowStale, expectedAccountId: _expectedAccountId, ...reference }: PullRequestRef,
226 - state: PullRequestState,
228 + status: { readonly state: PullRequestState; readonly isDraft?: boolean | undefined },
229 ) =>
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);
235
236 /** Credentials stay on their environments. Only a verified host and account cross the wire. */
237 export function createPullRequestRouter() {
@@ -378,7 +379,7 @@ export function createPullRequestRouter() {
379 ).pipe(
380 Effect.tap((result) =>
381 id !== origin.target.environmentId && hasState(result)
381 - ? reportState(ref, result.state)
382 + ? reportState(ref, result)
383 : Effect.void,
384 ),
385 Effect.tap(() =>
packages/client-runtime/src/state/pullRequests.test.ts
+62 -57
@@ -818,63 +818,68 @@ it.effect.each(
818 ),
819 );
820
821 -it.live("keeps source workspace metadata when an alternate answers a detail read", () =>
822 - Effect.scoped(
823 - Effect.gen(function* () {
824 - const noted = yield* Deferred.make<unknown>();
825 - const clientFor = (local: boolean) =>
826 - ({
827 - [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
828 - Effect.succeed({
829 - host: "github.com",
830 - provider: "github",
831 - viewer: "maria-rcks",
832 - accountId: "123",
833 - projectTitle: local ? "local project" : "source project",
834 - workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
835 - }),
836 - [WS_METHODS.pullRequestsDetail]: () =>
837 - local
838 - ? Effect.succeed({
839 - projectId: "local-project",
840 - projectTitle: "local project",
841 - workspaceRoot: "/Users/local/repo",
842 - title: "github title",
843 - state: "closed",
844 - updatedAt: "2026-10-10T01:52:36Z",
845 - })
846 - : Effect.never,
847 - [WS_METHODS.pullRequestsReportState]: (input: unknown) =>
848 - Deferred.succeed(noted, input).pipe(Effect.asVoid),
849 - }) as unknown as WsRpcProtocolClient;
850 - const { environmentRegistry, supervisor } = yield* makeTestRuntime(
851 - clientFor(false),
852 - clientFor(true),
853 - );
854 - const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
855 - projectId: ProjectId.make("project-1"),
856 - repository: "acme/web",
857 - number: 7,
858 - }).pipe(
859 - Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
860 - Effect.provideService(GitHubRoutingPermissions, trustedRouting),
861 - Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
862 - Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
863 - );
864 - expect(result).toEqual({
865 - projectId: "project-1",
866 - projectTitle: "source project",
867 - workspaceRoot: "/srv/source/repo",
868 - title: "github title",
869 - state: "closed",
870 - updatedAt: "2026-10-10T01:52:36Z",
871 - });
872 - expect(yield* Deferred.await(noted)).toEqual({
873 - reference: { projectId: "project-1", repository: "acme/web", number: 7 },
874 - state: "closed",
875 - });
876 - }),
877 - ),
821 +it.live.each([undefined, true, false])(
822 + "keeps source workspace metadata and reports draft %s when an alternate answers a detail read",
823 + (isDraft) =>
824 + Effect.scoped(
825 + Effect.gen(function* () {
826 + const noted = yield* Deferred.make<unknown>();
827 + const clientFor = (local: boolean) =>
828 + ({
829 + [local ? WS_METHODS.pullRequestsRoutingIdentity : WS_METHODS.pullRequestsRouting]: () =>
830 + Effect.succeed({
831 + host: "github.com",
832 + provider: "github",
833 + viewer: "maria-rcks",
834 + accountId: "123",
835 + projectTitle: local ? "local project" : "source project",
836 + workspaceRoot: local ? "/Users/local/repo" : "/srv/source/repo",
837 + }),
838 + [WS_METHODS.pullRequestsDetail]: () =>
839 + local
840 + ? Effect.succeed({
841 + projectId: "local-project",
842 + projectTitle: "local project",
843 + workspaceRoot: "/Users/local/repo",
844 + title: "github title",
845 + state: "closed",
846 + ...(isDraft === undefined ? {} : { isDraft }),
847 + updatedAt: "2026-10-10T01:52:36Z",
848 + })
849 + : Effect.never,
850 + [WS_METHODS.pullRequestsReportState]: (input: unknown) =>
851 + Deferred.succeed(noted, input).pipe(Effect.asVoid),
852 + }) as unknown as WsRpcProtocolClient;
853 + const { environmentRegistry, supervisor } = yield* makeTestRuntime(
854 + clientFor(false),
855 + clientFor(true),
856 + );
857 + const result = yield* createPullRequestRouter()(WS_METHODS.pullRequestsDetail, {
858 + projectId: ProjectId.make("project-1"),
859 + repository: "acme/web",
860 + number: 7,
861 + }).pipe(
862 + Effect.provideService(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
863 + Effect.provideService(GitHubRoutingPermissions, trustedRouting),
864 + Effect.provideService(RpcPermissionGuard, { authorize: () => Effect.void }),
865 + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
866 + );
867 + expect(result).toEqual({
868 + projectId: "project-1",
869 + projectTitle: "source project",
870 + workspaceRoot: "/srv/source/repo",
871 + title: "github title",
872 + state: "closed",
873 + ...(isDraft === undefined ? {} : { isDraft }),
874 + updatedAt: "2026-10-10T01:52:36Z",
875 + });
876 + expect(yield* Deferred.await(noted)).toEqual({
877 + reference: { projectId: "project-1", repository: "acme/web", number: 7 },
878 + state: "closed",
879 + ...(isDraft === undefined ? {} : { isDraft }),
880 + });
881 + }),
882 + ),
883 );
884
885 it.live(
packages/contracts/src/pullRequest.ts
+1
@@ -538,6 +538,7 @@ export type PullRequestInvalidateInput = typeof PullRequestInvalidateInput.Type;
538 export const PullRequestReportStateInput = Schema.Struct({
539 reference: PullRequestRef,
540 state: PullRequestState,
541 + isDraft: Schema.optional(Schema.Boolean),
542 });
543 export type PullRequestReportStateInput = typeof PullRequestReportStateInput.Type;
544