Open History to see the last commit
1import {
2 EventId,
3 ProjectId,
4 ProviderInstanceId,
5 SourceControlProviderKind,
6 ThreadId,
7 type OrchestrationProjectShell,
8 type OrchestrationV2DomainEvent,
9 type OrchestrationV2ThreadShell,
10 type OrchestrationV2ServerCommand,
11} from "@t3tools/contracts";
12import { describe, expect, it } from "@effect/vitest";
13import * as Crypto from "effect/Crypto";
14import * as DateTime from "effect/DateTime";
15import * as Deferred from "effect/Deferred";
16import * as Effect from "effect/Effect";
17import * as FileSystem from "effect/FileSystem";
18import * as Layer from "effect/Layer";
19import * as Option from "effect/Option";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Stream from "effect/Stream";
23import * as TestClock from "effect/testing/TestClock";
24
25import * as GitManager from "../git/GitManager.ts";
26import * as ProjectStore from "./ProjectStore.ts";
27import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
28import * as PullRequestService from "../pullRequest/PullRequestService.ts";
29import * as ServerActivation from "../serverActivation.ts";
30import * as Orchestrator from "./Orchestrator.ts";
31import * as ThreadPullRequestService from "./ThreadPullRequestService.ts";
32
33describe("ThreadPullRequestServiceV2 project guard", () => {
34 it.effect("discovers a repository from a project shell without enrichment", () =>
35 Effect.gen(function* () {
36 const project: OrchestrationProjectShell = {
37 id: ProjectId.make("project-1"),
38 title: "Project",
39 workspaceRoot: "/workspace/project",
40 defaultModelSelection: null,
41 scripts: [],
42 repositoryIdentity: null,
43 createdAt: "2026-08-01T00:00:00.000Z",
44 updatedAt: "2026-08-01T00:00:00.000Z",
45 };
46 let resolvedRoot: string | null = null;
47 const result = yield* ThreadPullRequestService.resolveProjectForPullRequestDiscovery(
48 project,
49 {
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 );
67 expect(resolvedRoot).toBe("/workspace/project");
68 expect(result.repository).toBe("pingdotgg/t3code");
69 expect(result.project.repositoryIdentity?.canonicalKey).toBe("github.com/pingdotgg/t3code");
70 }),
71 );
72
73 it.effect("refreshes the cached repository identity only when asked", () =>
74 Effect.gen(function* () {
75 const project: OrchestrationProjectShell = {
76 id: ProjectId.make("project-1"),
77 title: "Project",
78 workspaceRoot: "/workspace/project",
79 defaultModelSelection: null,
80 scripts: [],
81 repositoryIdentity: null,
82 createdAt: "2026-08-01T00:00:00.000Z",
83 updatedAt: "2026-08-01T00:00:00.000Z",
84 };
85 const refreshes: Array<boolean | undefined> = [];
86 const resolver = {
87 resolve: (_root: string, options?: { readonly refresh?: boolean }) => {
88 refreshes.push(options?.refresh);
89 return Effect.succeed(null);
90 },
91 };
92 yield* ThreadPullRequestService.resolveProjectForPullRequestDiscovery(project, resolver);
93 yield* ThreadPullRequestService.resolveProjectForPullRequestDiscovery(project, resolver, {
94 refresh: true,
95 });
96 expect(refreshes).toEqual([false, true]);
97 }),
98 );
99
100 it("rejects a pull-request result when the project root changes before dispatch", () => {
101 const currentProject = Option.some({
102 workspaceRoot: "/workspace/replaced",
103 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
104
105 expect(
106 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
107 currentProject,
108 "/workspace/original",
109 ),
110 ).toBe(false);
111 });
112
113 it("rejects a pull-request result when the project was deleted before dispatch", () => {
114 expect(
115 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
116 Option.none<Pick<OrchestrationProjectShell, "workspaceRoot">>(),
117 "/workspace/original",
118 ),
119 ).toBe(false);
120 });
121
122 it("accepts a pull-request result while the project root is unchanged", () => {
123 const currentProject = Option.some({
124 workspaceRoot: "/workspace/original",
125 } satisfies Pick<OrchestrationProjectShell, "workspaceRoot">);
126
127 expect(
128 ThreadPullRequestService.projectWorkspaceMatchesSnapshot(
129 currentProject,
130 "/workspace/original",
131 ),
132 ).toBe(true);
133 });
134});
135
136describe("ThreadPullRequestServiceV2 reads", () => {
137 const NOW = DateTime.makeUnsafe("2026-09-20T00:00:00.000Z");
138 const threadShell = (id: string): OrchestrationV2ThreadShell => {
139 const threadId = ThreadId.make(id);
140 return {
141 id: threadId,
142 projectId: ProjectId.make("project-1"),
143 title: id,
144 providerInstanceId: ProviderInstanceId.make("codex"),
145 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
146 runtimeMode: "full-access",
147 interactionMode: "default",
148 branch: null,
149 worktreePath: null,
150 activeProviderThreadId: null,
151 lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
152 forkedFrom: null,
153 createdBy: "user",
154 creationSource: "web",
155 activeRunId: null,
156 latestRunId: null,
157 status: "idle",
158 pendingRuntimeRequest: null,
159 latestVisibleMessage: null,
160 latestUserMessageAt: null,
161 hasActionableProposedPlan: false,
162 itemCount: 0,
163 visibleItemCount: 0,
164 createdAt: NOW,
165 updatedAt: NOW,
166 archivedAt: null,
167 settledOverride: null,
168 settledAt: null,
169 lastVisitedAt: null,
170 deletedAt: null,
171 };
172 };
173
174 it.effect.each([
175 { state: "closed", sameBranch: false },
176 { state: "merged", sameBranch: false },
177 { state: "closed", sameBranch: true },
178 { state: "merged", sameBranch: true },
179 ] as const)(
180 "restores a $state automatic PR only for its own branch (sameBranch=$sameBranch)",
181 ({ state, sameBranch }) =>
182 Effect.scoped(
183 Effect.gen(function* () {
184 const savedReference = {
185 projectId: ProjectId.make("project-1"),
186 repository: "acme/project",
187 number: 42,
188 url: "https://github.com/acme/project/pull/42",
189 };
190 const thread = {
191 ...threadShell("branch-pr-thread"),
192 branch: "main",
193 branchPullRequest: savedReference,
194 linkedPullRequest: savedReference,
195 };
196 const project: OrchestrationProjectShell = {
197 id: thread.projectId,
198 title: "Project",
199 workspaceRoot: "/workspace/project",
200 defaultModelSelection: null,
201 scripts: [],
202 createdAt: "2026-08-01T00:00:00.000Z",
203 updatedAt: "2026-08-01T00:00:00.000Z",
204 };
205 const activation = yield* Deferred.make<void>();
206 const sweepStarted = yield* Deferred.make<void>();
207 const commands: Array<OrchestrationV2ServerCommand> = [];
208 const dependencies = Layer.mergeAll(
209 Layer.mock(Orchestrator.OrchestratorV2)({
210 streamDomainEvents: Stream.never,
211 getShellSnapshot: () =>
212 Deferred.succeed(sweepStarted, undefined).pipe(
213 Effect.as({
214 schemaVersion: 2,
215 snapshotSequence: 1,
216 threads: [thread],
217 archivedThreads: [],
218 }),
219 ),
220 dispatch: (command) =>
221 Effect.sync(() => {
222 commands.push(command);
223 return { sequence: 2, storedEvents: [] };
224 }),
225 }),
226 Layer.mock(ProjectStore.ProjectStoreV2)({
227 listShells: () => Effect.succeed([project]),
228 getShell: () => Effect.succeed(Option.some(project)),
229 }),
230 Layer.mock(GitManager.GitManager)({
231 branchPullRequest: () => Effect.succeed(null),
232 }),
233 Layer.mock(PullRequestService.PullRequestService)({
234 summary: () =>
235 Effect.succeed({
236 ...savedReference,
237 provider: SourceControlProviderKind.make("github"),
238 title: "Previous branch work",
239 state,
240 headBranch: sameBranch ? thread.branch : "feature/previous-work",
241 baseBranch: "release",
242 updatedAt: "2026-09-19T00:00:00.000Z",
243 }),
244 }),
245 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({
246 resolve: () =>
247 Effect.succeed({
248 canonicalKey: "github.com/acme/project",
249 locator: {
250 source: "git-remote" as const,
251 remoteName: "origin",
252 remoteUrl: "git@github.com:acme/project.git",
253 },
254 provider: "github" as const,
255 owner: "acme",
256 name: "project",
257 }),
258 }),
259 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
260 Layer.succeed(
261 Crypto.Crypto,
262 Crypto.make({
263 randomBytes: (size) => new Uint8Array(size).fill(1),
264 digest: (_algorithm, data) => Effect.succeed(data),
265 }),
266 ),
267 FileSystem.layerNoop({}),
268 );
269 yield* Effect.gen(function* () {
270 const service = yield* ThreadPullRequestService.make;
271 yield* service.start();
272 yield* Deferred.succeed(activation, undefined);
273 yield* Deferred.await(sweepStarted);
274 yield* service.drain;
275 }).pipe(Effect.provide(dependencies));
276
277 if (sameBranch) {
278 expect(commands).toEqual([]);
279 } else {
280 expect(commands).toHaveLength(1);
281 expect(commands[0]).toMatchObject({
282 type: "thread.pull-request.sync",
283 threadId: thread.id,
284 branchPullRequest: null,
285 });
286 expect(commands[0]).not.toHaveProperty("linkedPullRequest");
287 }
288 }),
289 ),
290 );
291
292 it.effect("an event for one thread reads that thread's shell, not every thread's", () =>
293 Effect.scoped(
294 Effect.gen(function* () {
295 const thread = threadShell("updated-thread");
296 const other = threadShell("other-thread");
297 const activation = yield* Deferred.make<void>();
298 const events = yield* PubSub.unbounded<OrchestrationV2DomainEvent>();
299 const reads = yield* Queue.unbounded<
300 ThreadId | { readonly location?: string; readonly unsettledOnly?: boolean }
301 >();
302 const layerDependencies = Layer.mergeAll(
303 Layer.mock(Orchestrator.OrchestratorV2)({
304 streamDomainEvents: Stream.fromPubSub(events),
305 getShellSnapshot: (options) =>
306 Queue.offer(reads, options ?? {}).pipe(
307 Effect.as({
308 schemaVersion: 2,
309 snapshotSequence: 1,
310 threads: [thread, other],
311 archivedThreads: [],
312 }),
313 ),
314 getThreadEventSequence: () => Effect.succeed(1),
315 getThreadShell: (threadId) =>
316 Queue.offer(reads, threadId).pipe(
317 Effect.as([thread, other].find((candidate) => candidate.id === threadId) ?? null),
318 ),
319 }),
320 Layer.mock(ProjectStore.ProjectStoreV2)({
321 listShells: () => Effect.succeed([]),
322 }),
323 Layer.mock(GitManager.GitManager)({}),
324 Layer.mock(PullRequestService.PullRequestService)({}),
325 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
326 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
327 Layer.succeed(
328 Crypto.Crypto,
329 Crypto.make({
330 randomBytes: (size) => new Uint8Array(size).fill(1),
331 digest: (_algorithm, data) => Effect.succeed(data),
332 }),
333 ),
334 FileSystem.layerNoop({}),
335 );
336
337 yield* Effect.gen(function* () {
338 const service = yield* ThreadPullRequestService.make;
339 yield* service.start();
340 yield* Deferred.succeed(activation, undefined);
341 // Startup backfill reads every active thread.
342 expect(yield* Queue.take(reads)).toEqual({
343 location: "active",
344 compactPullRequests: true,
345 unsettledOnly: false,
346 });
347 yield* service.drain;
348 yield* PubSub.publish(events, {
349 type: "thread.metadata-updated",
350 id: EventId.make("event:metadata"),
351 threadId: thread.id,
352 occurredAt: NOW,
353 payload: {
354 createdBy: thread.createdBy,
355 creationSource: thread.creationSource,
356 id: thread.id,
357 projectId: thread.projectId,
358 title: thread.title,
359 providerInstanceId: thread.providerInstanceId,
360 modelSelection: thread.modelSelection,
361 runtimeMode: thread.runtimeMode,
362 interactionMode: thread.interactionMode,
363 branch: thread.branch,
364 worktreePath: thread.worktreePath,
365 activeProviderThreadId: thread.activeProviderThreadId,
366 lineage: thread.lineage,
367 forkedFrom: null,
368 createdAt: thread.createdAt,
369 updatedAt: thread.updatedAt,
370 archivedAt: null,
371 settledOverride: null,
372 settledAt: null,
373 lastVisitedAt: null,
374 deletedAt: null,
375 },
376 });
377 expect(yield* Queue.take(reads)).toBe(thread.id);
378 yield* service.drain;
379 expect(yield* Queue.size(reads)).toBe(0);
380 }).pipe(Effect.provide(layerDependencies));
381 }),
382 ),
383 );
384
385 it.effect("periodic sweeps read only unsettled threads once backfill is done", () =>
386 Effect.scoped(
387 Effect.gen(function* () {
388 const settled = {
389 ...threadShell("settled-thread"),
390 branch: "feature/settled",
391 settledOverride: "settled" as const,
392 settledAt: NOW,
393 };
394 const activation = yield* Deferred.make<void>();
395 const reads = yield* Queue.unbounded<{
396 readonly location?: string;
397 readonly unsettledOnly?: boolean;
398 }>();
399 const layerDependencies = Layer.mergeAll(
400 Layer.mock(Orchestrator.OrchestratorV2)({
401 streamDomainEvents: Stream.never,
402 getShellSnapshot: (options) =>
403 Queue.offer(reads, options ?? {}).pipe(
404 Effect.as({
405 schemaVersion: 2,
406 snapshotSequence: 1,
407 threads: options?.unsettledOnly ? [] : [settled],
408 archivedThreads: [],
409 }),
410 ),
411 }),
412 Layer.mock(ProjectStore.ProjectStoreV2)({
413 listShells: () => Effect.succeed([]),
414 }),
415 Layer.mock(GitManager.GitManager)({}),
416 Layer.mock(PullRequestService.PullRequestService)({}),
417 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
418 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
419 Layer.succeed(
420 Crypto.Crypto,
421 Crypto.make({
422 randomBytes: (size) => new Uint8Array(size).fill(1),
423 digest: (_algorithm, data) => Effect.succeed(data),
424 }),
425 ),
426 FileSystem.layerNoop({}),
427 );
428
429 yield* Effect.gen(function* () {
430 const service = yield* ThreadPullRequestService.make;
431 yield* service.start();
432 yield* Deferred.succeed(activation, undefined);
433 // Backfill finds the settled branch thread and must read it again.
434 expect(yield* Queue.take(reads)).toEqual({
435 location: "active",
436 compactPullRequests: true,
437 unsettledOnly: false,
438 });
439 yield* service.drain;
440 yield* TestClock.adjust("1 minute");
441 expect(yield* Queue.take(reads)).toEqual({
442 location: "active",
443 compactPullRequests: true,
444 unsettledOnly: true,
445 });
446 yield* service.drain;
447 }).pipe(Effect.provide(layerDependencies));
448 }),
449 ),
450 );
451});