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