Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadPullRequestService.test.ts

311 lines11.7 KB

1import {
2 EventId,
3 ProjectId,
4 ProviderInstanceId,
5 ThreadId,
6 type OrchestrationProjectShell,
7 type OrchestrationV2DomainEvent,
8 type OrchestrationV2ThreadShell,
9} from "@t3tools/contracts";
10import { describe, expect, it } from "@effect/vitest";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Deferred from "effect/Deferred";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Layer from "effect/Layer";
17import * as Option from "effect/Option";
18import * as PubSub from "effect/PubSub";
19import * as Queue from "effect/Queue";
20import * as Stream from "effect/Stream";
21import * as TestClock from "effect/testing/TestClock";
22​
23import { GitManager } from "../git/GitManager.ts";
24import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
25import { RepositoryIdentityResolver } from "../project/RepositoryIdentityResolver.ts";
26import { PullRequestService } from "../pullRequest/PullRequestService.ts";
27import { ServerActivation } from "../serverActivation.ts";
28import { OrchestratorV2 } from "./Orchestrator.ts";
29import {
30 make,
31 projectWorkspaceMatchesSnapshot,
32 resolveProjectForPullRequestDiscovery,
33} from "./ThreadPullRequestService.ts";
34​
35describe("ThreadPullRequestServiceV2 project guard", () => {
36 it.effect("discovers a repository from a project shell without enrichment", () =>
37 Effect.gen(function* () {
38 const project: OrchestrationProjectShell = {
39 id: ProjectId.make("project-1"),
40 title: "Project",
41 workspaceRoot: "/workspace/project",
42 defaultModelSelection: null,
43 scripts: [],
44 repositoryIdentity: null,
45 createdAt: "2026-08-01T00:00:00.000Z",
46 updatedAt: "2026-08-01T00:00:00.000Z",
47 };
48 let resolvedRoot: string | null = null;
49 const result = yield* resolveProjectForPullRequestDiscovery(project, {
50 resolve: (root) => {
51 resolvedRoot = root;
52 return Effect.succeed({
53 canonicalKey: "github.com/pingdotgg/t3code",
54 locator: {
55 source: "git-remote" as const,
56 remoteName: "origin",
57 remoteUrl: "git@github.com:pingdotgg/t3code.git",
58 },
59 provider: "github" as const,
60 displayName: "pingdotgg/t3code",
61 owner: "pingdotgg",
62 name: "t3code",
63 });
64 },
65 });
66 expect(resolvedRoot).toBe("/workspace/project");
67 expect(result.repository).toBe("pingdotgg/t3code");
68 expect(result.project.repositoryIdentity?.canonicalKey).toBe("github.com/pingdotgg/t3code");
69 }),
70 );
71​
72 it.effect("refreshes the cached repository identity only when asked", () =>
73 Effect.gen(function* () {
74 const project: OrchestrationProjectShell = {
75 id: ProjectId.make("project-1"),
76 title: "Project",
77 workspaceRoot: "/workspace/project",
78 defaultModelSelection: null,
79 scripts: [],
80 repositoryIdentity: null,
81 createdAt: "2026-08-01T00:00:00.000Z",
82 updatedAt: "2026-08-01T00:00:00.000Z",
83 };
84 const refreshes: Array<boolean | undefined> = [];
85 const resolver = {
86 resolve: (_root: string, options?: { readonly refresh?: boolean }) => {
87 refreshes.push(options?.refresh);
88 return Effect.succeed(null);
89 },
90 };
91 yield* resolveProjectForPullRequestDiscovery(project, resolver);
92 yield* resolveProjectForPullRequestDiscovery(project, resolver, { refresh: true });
93 expect(refreshes).toEqual([false, true]);
94 }),
95 );
96​
97 it("rejects a pull-request result when the project root changes before dispatch", () => {
98 const currentProject = Option.some({
99 workspaceRoot: "/workspace/replaced",
100 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
101​
102 expect(projectWorkspaceMatchesSnapshot(currentProject, "/workspace/original")).toBe(false);
103 });
104​
105 it("rejects a pull-request result when the project was deleted before dispatch", () => {
106 expect(
107 projectWorkspaceMatchesSnapshot(
108 Option.none<Pick<OrchestrationProjectShell, "workspaceRoot">>(),
109 "/workspace/original",
110 ),
111 ).toBe(false);
112 });
113​
114 it("accepts a pull-request result while the project root is unchanged", () => {
115 const currentProject = Option.some({
116 workspaceRoot: "/workspace/original",
117 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
118​
119 expect(projectWorkspaceMatchesSnapshot(currentProject, "/workspace/original")).toBe(true);
120 });
121});
122​
123describe("ThreadPullRequestServiceV2 reads", () => {
124 const NOW = DateTime.makeUnsafe("2026-09-20T00:00:00.000Z");
125 const threadShell = (id: string): OrchestrationV2ThreadShell => {
126 const threadId = ThreadId.make(id);
127 return {
128 id: threadId,
129 projectId: ProjectId.make("project-1"),
130 title: id,
131 providerInstanceId: ProviderInstanceId.make("codex"),
132 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
133 runtimeMode: "full-access",
134 interactionMode: "default",
135 branch: null,
136 worktreePath: null,
137 activeProviderThreadId: null,
138 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
139 forkedFrom: null,
140 createdBy: "user",
141 creationSource: "web",
142 activeRunId: null,
143 latestRunId: null,
144 status: "idle",
145 pendingRuntimeRequest: null,
146 latestVisibleMessage: null,
147 latestUserMessageAt: null,
148 hasActionableProposedPlan: false,
149 itemCount: 0,
150 visibleItemCount: 0,
151 createdAt: NOW,
152 updatedAt: NOW,
153 archivedAt: null,
154 settledOverride: null,
155 settledAt: null,
156 lastVisitedAt: null,
157 deletedAt: null,
158 };
159 };
160​
161 it.effect("an event for one thread reads that thread's shell, not every thread's", () =>
162 Effect.scoped(
163 Effect.gen(function* () {
164 const thread = threadShell("updated-thread");
165 const other = threadShell("other-thread");
166 const activation = yield* Deferred.make<void>();
167 const events = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
168 // Each read: the thread id for a one-thread read, or the full read's options.
169 const reads = yield* Queue.unbounded<
170 ThreadId | { readonly location?: string; readonly unsettledOnly?: boolean }
171 >();
172 const dependencies = Layer.mergeAll(
173 Layer.mock(OrchestratorV2)({
174 streamDomainEvents: Stream.fromPubSub(events),
175 getShellSnapshot: (options) =>
176 Queue.offer(reads, options ?? {}).pipe(
177 Effect.as({
178 schemaVersion: 2,
179 snapshotSequence: 1,
180 threads: [thread, other],
181 archivedThreads: [],
182 }),
183 ),
184 getThreadEventSequence: () => Effect.succeed(1),
185 getThreadShell: (threadId) =>
186 Queue.offer(reads, threadId).pipe(
187 Effect.as([thread, other].find((candidate) => candidate.id === threadId) ?? null),
188 ),
189 }),
190 Layer.mock(ProjectionSnapshotQuery)({
191 getProjectShellsWithoutEnrichment: () => Effect.succeed([]),
192 }),
193 Layer.mock(GitManager)({}),
194 Layer.mock(PullRequestService)({}),
195 Layer.mock(RepositoryIdentityResolver)({}),
196 Layer.succeed(ServerActivation, Deferred.await(activation)),
197 Layer.succeed(
198 Crypto.Crypto,
199 Crypto.make({
200 randomBytes: (size) => new Uint8Array(size).fill(1),
201 digest: (_algorithm, data) => Effect.succeed(data),
202 }),
203 ),
204 FileSystem.layerNoop({}),
205 );
206​
207 yield* Effect.gen(function* () {
208 const service = yield* make;
209 yield* service.start();
210 yield* Deferred.succeed(activation, undefined);
211 // Startup backfill reads every active thread.
212 expect(yield* Queue.take(reads)).toEqual({ location: "active", unsettledOnly: false });
213 yield* service.drain;
214 yield* PubSub.publish(events, {
215 type: "thread.metadata-updated",
216 id: EventId.make("event:metadata"),
217 threadId: thread.id,
218 occurredAt: NOW,
219 payload: {
220 createdBy: thread.createdBy,
221 creationSource: thread.creationSource,
222 id: thread.id,
223 projectId: thread.projectId,
224 title: thread.title,
225 providerInstanceId: thread.providerInstanceId,
226 modelSelection: thread.modelSelection,
227 runtimeMode: thread.runtimeMode,
228 interactionMode: thread.interactionMode,
229 branch: thread.branch,
230 worktreePath: thread.worktreePath,
231 activeProviderThreadId: thread.activeProviderThreadId,
232 lineage: thread.lineage,
233 forkedFrom: null,
234 createdAt: thread.createdAt,
235 updatedAt: thread.updatedAt,
236 archivedAt: null,
237 settledOverride: null,
238 settledAt: null,
239 lastVisitedAt: null,
240 deletedAt: null,
241 },
242 });
243 expect(yield* Queue.take(reads)).toBe(thread.id);
244 yield* service.drain;
245 expect(yield* Queue.size(reads)).toBe(0);
246 }).pipe(Effect.provide(dependencies));
247 }),
248 ),
249 );
250​
251 it.effect("periodic sweeps read only unsettled threads once backfill is done", () =>
252 Effect.scoped(
253 Effect.gen(function* () {
254 const settled = {
255 ...threadShell("settled-thread"),
256 branch: "feature/settled",
257 settledOverride: "settled" as const,
258 settledAt: NOW,
259 };
260 const activation = yield* Deferred.make<void>();
261 const reads = yield* Queue.unbounded<{
262 readonly location?: string;
263 readonly unsettledOnly?: boolean;
264 }>();
265 const dependencies = Layer.mergeAll(
266 Layer.mock(OrchestratorV2)({
267 streamDomainEvents: Stream.never,
268 getShellSnapshot: (options) =>
269 Queue.offer(reads, options ?? {}).pipe(
270 Effect.as({
271 schemaVersion: 2,
272 snapshotSequence: 1,
273 // The fake honors unsettledOnly like the store does.
274 threads: options?.unsettledOnly ? [] : [settled],
275 archivedThreads: [],
276 }),
277 ),
278 }),
279 Layer.mock(ProjectionSnapshotQuery)({
280 getProjectShellsWithoutEnrichment: () => Effect.succeed([]),
281 }),
282 Layer.mock(GitManager)({}),
283 Layer.mock(PullRequestService)({}),
284 Layer.mock(RepositoryIdentityResolver)({}),
285 Layer.succeed(ServerActivation, Deferred.await(activation)),
286 Layer.succeed(
287 Crypto.Crypto,
288 Crypto.make({
289 randomBytes: (size) => new Uint8Array(size).fill(1),
290 digest: (_algorithm, data) => Effect.succeed(data),
291 }),
292 ),
293 FileSystem.layerNoop({}),
294 );
295​
296 yield* Effect.gen(function* () {
297 const service = yield* make;
298 yield* service.start();
299 yield* Deferred.succeed(activation, undefined);
300 // Backfill finds the settled branch thread and must read it again.
301 expect(yield* Queue.take(reads)).toEqual({ location: "active", unsettledOnly: false });
302 yield* service.drain;
303 // Its project is gone, so backfill finishes it on the first pass.
304 yield* TestClock.adjust("1 minute");
305 expect(yield* Queue.take(reads)).toEqual({ location: "active", unsettledOnly: true });
306 yield* service.drain;
307 }).pipe(Effect.provide(dependencies));
308 }),
309 ),
310 );
311});