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 expect(yield* Queue.take(reads)).toEqual({ location: "active", unsettledOnly: false });
342 yield* service.drain;
343 yield* PubSub.publish(events, {
344 type: "thread.metadata-updated",
345 id: EventId.make("event:metadata"),
346 threadId: thread.id,
347 occurredAt: NOW,
348 payload: {
349 createdBy: thread.createdBy,
350 creationSource: thread.creationSource,
351 id: thread.id,
352 projectId: thread.projectId,
353 title: thread.title,
354 providerInstanceId: thread.providerInstanceId,
355 modelSelection: thread.modelSelection,
356 runtimeMode: thread.runtimeMode,
357 interactionMode: thread.interactionMode,
358 branch: thread.branch,
359 worktreePath: thread.worktreePath,
360 activeProviderThreadId: thread.activeProviderThreadId,
361 lineage: thread.lineage,
362 forkedFrom: null,
363 createdAt: thread.createdAt,
364 updatedAt: thread.updatedAt,
365 archivedAt: null,
366 settledOverride: null,
367 settledAt: null,
368 lastVisitedAt: null,
369 deletedAt: null,
370 },
371 });
372 expect(yield* Queue.take(reads)).toBe(thread.id);
373 yield* service.drain;
374 expect(yield* Queue.size(reads)).toBe(0);
375 }).pipe(Effect.provide(layerDependencies));
376 }),
377 ),
378 );
379
380 it.effect("periodic sweeps read only unsettled threads once backfill is done", () =>
381 Effect.scoped(
382 Effect.gen(function* () {
383 const settled = {
384 ...threadShell("settled-thread"),
385 branch: "feature/settled",
386 settledOverride: "settled" as const,
387 settledAt: NOW,
388 };
389 const activation = yield* Deferred.make<void>();
390 const reads = yield* Queue.unbounded<{
391 readonly location?: string;
392 readonly unsettledOnly?: boolean;
393 }>();
394 const layerDependencies = Layer.mergeAll(
395 Layer.mock(Orchestrator.OrchestratorV2)({
396 streamDomainEvents: Stream.never,
397 getShellSnapshot: (options) =>
398 Queue.offer(reads, options ?? {}).pipe(
399 Effect.as({
400 schemaVersion: 2,
401 snapshotSequence: 1,
402 threads: options?.unsettledOnly ? [] : [settled],
403 archivedThreads: [],
404 }),
405 ),
406 }),
407 Layer.mock(ProjectStore.ProjectStoreV2)({
408 listShells: () => Effect.succeed([]),
409 }),
410 Layer.mock(GitManager.GitManager)({}),
411 Layer.mock(PullRequestService.PullRequestService)({}),
412 Layer.mock(RepositoryIdentityResolver.RepositoryIdentityResolver)({}),
413 Layer.succeed(ServerActivation.ServerActivation, Deferred.await(activation)),
414 Layer.succeed(
415 Crypto.Crypto,
416 Crypto.make({
417 randomBytes: (size) => new Uint8Array(size).fill(1),
418 digest: (_algorithm, data) => Effect.succeed(data),
419 }),
420 ),
421 FileSystem.layerNoop({}),
422 );
423
424 yield* Effect.gen(function* () {
425 const service = yield* ThreadPullRequestService.make;
426 yield* service.start();
427 yield* Deferred.succeed(activation, undefined);
428 expect(yield* Queue.take(reads)).toEqual({ location: "active", unsettledOnly: false });
429 yield* service.drain;
430 yield* TestClock.adjust("1 minute");
431 expect(yield* Queue.take(reads)).toEqual({ location: "active", unsettledOnly: true });
432 yield* service.drain;
433 }).pipe(Effect.provide(layerDependencies));
434 }),
435 ),
436 );
437});