Open History to see the last commit
1import {
2 EnvironmentId,
3 type GitActionProgressEvent,
4 type GitRunStackedActionResult,
5} from "@t3tools/contracts";
6import { describe, expect, it } from "@effect/vitest";
7import * as Cause from "effect/Cause";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10import * as Schema from "effect/Schema";
11import * as Stream from "effect/Stream";
12import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
13
14import type { EnvironmentRegistry } from "../connection/registry.ts";
15import type { AtomCommandResult } from "./runtime.ts";
16import {
17 applyVcsActionProgressEvent,
18 beginVcsActionState,
19 consumeVcsActionProgress,
20 createVcsActionManager,
21 createVcsActionTransportId,
22 EMPTY_VCS_ACTION_STATE,
23 getVcsActionTargetKey,
24 normalizeVcsActionProgressEvent,
25 parseVcsActionTargetKey,
26 VcsActionMissingTerminalEventError,
27 VcsActionRemoteFailureError,
28 VcsActionTargetKeyParseError,
29 VcsActionUnavailableError,
30} from "./vcsAction.ts";
31
32const actionId = "action-123";
33const action = "commit_push" as const;
34const cwd = "/repo";
35const environmentId = EnvironmentId.make("environment-1");
36const isVcsActionUnavailableError = Schema.is(VcsActionUnavailableError);
37const result: GitRunStackedActionResult = {
38 action,
39 branch: {
40 status: "skipped_not_requested",
41 },
42 commit: {
43 status: "created",
44 commitSha: "abc123",
45 subject: "Test commit",
46 },
47 push: {
48 status: "pushed",
49 branch: "feature",
50 },
51 pr: {
52 status: "skipped_not_requested",
53 },
54 toast: {
55 title: "Changes pushed",
56 cta: {
57 kind: "none",
58 },
59 },
60};
61
62function progress<T extends GitActionProgressEvent>(event: T): T {
63 return event;
64}
65
66describe("vcsActionState", () => {
67 it("preserves malformed target key diagnostics and the native cause without copying the key", () => {
68 const key = "not-json-with-credential=do-not-log";
69 let error: unknown;
70
71 try {
72 parseVcsActionTargetKey(key);
73 } catch (cause) {
74 error = cause;
75 }
76
77 expect(error).toBeInstanceOf(VcsActionTargetKeyParseError);
78 expect(error).toMatchObject({ keyLength: key.length, cause: expect.any(SyntaxError) });
79 expect(error).not.toHaveProperty("key");
80 expect((error as Error).message).not.toContain(key);
81 });
82
83 it("rejects invalid target key shapes", () => {
84 const key = JSON.stringify([environmentId]);
85
86 expect(() => parseVcsActionTargetKey(key)).toThrowError(VcsActionTargetKeyParseError);
87 });
88
89 it("projects phase and hook progress without owning the async operation", () => {
90 const initial = beginVcsActionState({
91 operation: "run_change_request",
92 label: "Running source control action",
93 actionId,
94 });
95 const phase = applyVcsActionProgressEvent(
96 initial,
97 progress({
98 actionId,
99 action,
100 cwd,
101 kind: "phase_started",
102 phase: "commit",
103 label: "Committing...",
104 }),
105 );
106 const hook = applyVcsActionProgressEvent(
107 phase,
108 progress({
109 actionId,
110 action,
111 cwd,
112 kind: "hook_started",
113 hookName: "post-commit",
114 }),
115 );
116 const output = applyVcsActionProgressEvent(
117 hook,
118 progress({
119 actionId,
120 action,
121 cwd,
122 kind: "hook_output",
123 hookName: "post-commit",
124 stream: "stdout",
125 text: "hook output",
126 }),
127 );
128 const finished = applyVcsActionProgressEvent(
129 output,
130 progress({
131 actionId,
132 action,
133 cwd,
134 kind: "hook_finished",
135 hookName: "post-commit",
136 exitCode: 0,
137 durationMs: 12,
138 }),
139 );
140
141 expect(phase).toMatchObject({
142 isRunning: true,
143 currentLabel: "Committing...",
144 currentPhaseLabel: "Committing...",
145 });
146 expect(output).toMatchObject({
147 currentLabel: "Running post-commit...",
148 hookName: "post-commit",
149 lastOutputLine: "hook output",
150 });
151 expect(finished).toMatchObject({
152 currentLabel: "Committing...",
153 hookName: null,
154 lastOutputLine: null,
155 });
156 });
157
158 it("retains a terminal action error for presentation", () => {
159 const initial = beginVcsActionState({
160 operation: "run_change_request",
161 label: "Running source control action",
162 actionId,
163 });
164 const failed = applyVcsActionProgressEvent(
165 initial,
166 progress({
167 actionId,
168 action,
169 cwd,
170 kind: "action_failed",
171 phase: null,
172 message: "Push failed.",
173 }),
174 );
175
176 expect(failed).toMatchObject({
177 isRunning: false,
178 operation: "run_change_request",
179 actionId,
180 action,
181 error: "Push failed.",
182 });
183 });
184
185 it("ignores progress after a newer action owns the target", () => {
186 const current = beginVcsActionState({
187 operation: "pull",
188 label: "Pulling latest changes",
189 actionId: "newer-action",
190 });
191
192 expect(
193 applyVcsActionProgressEvent(
194 current,
195 progress({
196 actionId,
197 action,
198 cwd,
199 kind: "phase_started",
200 phase: "push",
201 label: "Pushing...",
202 }),
203 ),
204 ).toBe(current);
205 });
206
207 it("keys presentation state only when the environment and repository are known", () => {
208 expect(
209 getVcsActionTargetKey({
210 environmentId,
211 cwd,
212 }),
213 ).toBe(JSON.stringify([environmentId, cwd]));
214 expect(getVcsActionTargetKey({ environmentId: null, cwd })).toBeNull();
215 expect(
216 getVcsActionTargetKey({
217 environmentId,
218 cwd: null,
219 }),
220 ).toBeNull();
221 });
222
223 it("normalizes progress only for the matching environment-scoped action", () => {
224 const target = { environmentId, cwd };
225 const otherTarget = {
226 environmentId: EnvironmentId.make("environment-2"),
227 cwd,
228 };
229 const transportActionId = createVcsActionTransportId(target, actionId);
230 const event = progress({
231 actionId: createVcsActionTransportId(otherTarget, actionId),
232 action,
233 cwd,
234 kind: "phase_started",
235 phase: "push",
236 label: "Pushing...",
237 });
238
239 expect(normalizeVcsActionProgressEvent(target, transportActionId, actionId, event)).toBeNull();
240 expect(
241 normalizeVcsActionProgressEvent(target, transportActionId, actionId, {
242 ...event,
243 actionId: transportActionId,
244 }),
245 ).toEqual({
246 ...event,
247 actionId,
248 });
249 });
250
251 it.effect("consumes progress through the terminal event and returns its result", () =>
252 Effect.gen(function* () {
253 const target = { environmentId, cwd };
254 const transportActionId = createVcsActionTransportId(target, actionId);
255 const observed: GitActionProgressEvent[] = [];
256 const events: GitActionProgressEvent[] = [
257 {
258 actionId: "unrelated-action",
259 action,
260 cwd,
261 kind: "phase_started",
262 phase: "commit",
263 label: "Ignored",
264 },
265 {
266 actionId: transportActionId,
267 action,
268 cwd,
269 kind: "phase_started",
270 phase: "push",
271 label: "Pushing...",
272 },
273 {
274 actionId: transportActionId,
275 action,
276 cwd,
277 kind: "action_finished",
278 result,
279 },
280 ];
281
282 const actual = yield* consumeVcsActionProgress(Stream.fromIterable(events), {
283 target,
284 transportActionId,
285 actionId,
286 action,
287 onProgress: (event) =>
288 Effect.sync(() => {
289 observed.push(event);
290 }),
291 });
292
293 expect(actual).toEqual(result);
294 expect(observed.map((event) => event.actionId)).toEqual([actionId, actionId]);
295 expect(observed.map((event) => event.kind)).toEqual(["phase_started", "action_finished"]);
296 }),
297 );
298
299 it.effect("retains structural remote failure context without copying the remote payload", () =>
300 Effect.gen(function* () {
301 const target = { environmentId, cwd };
302 const transportActionId = createVcsActionTransportId(target, actionId);
303 const remoteMessage = "The remote rejected the push with credential=do-not-log.";
304 const error = yield* consumeVcsActionProgress(
305 Stream.fromIterable<GitActionProgressEvent>([
306 {
307 actionId: transportActionId,
308 action,
309 cwd,
310 kind: "action_failed",
311 phase: "push",
312 message: remoteMessage,
313 },
314 ]),
315 {
316 target,
317 transportActionId,
318 actionId,
319 action,
320 onProgress: () => Effect.void,
321 },
322 ).pipe(Effect.flip);
323
324 expect(error).toBeInstanceOf(VcsActionRemoteFailureError);
325 expect(error).toMatchObject({
326 actionId,
327 transportActionId,
328 action,
329 environmentId,
330 cwd,
331 phase: "push",
332 remoteMessageLength: remoteMessage.length,
333 });
334 expect(error).not.toHaveProperty("detail");
335 expect(error.message).toBe("Source control action 'commit_push' failed during push.");
336 expect(error.message).not.toContain(remoteMessage);
337 }),
338 );
339
340 it.effect("reports a missing terminal event as a protocol failure", () =>
341 Effect.gen(function* () {
342 const target = { environmentId, cwd };
343 const transportActionId = createVcsActionTransportId(target, actionId);
344 const error = yield* consumeVcsActionProgress(
345 Stream.fromIterable<GitActionProgressEvent>([
346 {
347 actionId: transportActionId,
348 action,
349 cwd,
350 kind: "phase_started",
351 phase: "commit",
352 label: "Committing...",
353 },
354 ]),
355 {
356 target,
357 transportActionId,
358 actionId,
359 action,
360 onProgress: () => Effect.void,
361 },
362 ).pipe(Effect.flip);
363
364 expect(error).toBeInstanceOf(VcsActionMissingTerminalEventError);
365 expect(error).toMatchObject({
366 actionId,
367 transportActionId,
368 action,
369 environmentId,
370 cwd,
371 });
372 expect(error.message).toBe(
373 "Source control action 'commit_push' ended without a terminal result.",
374 );
375 }),
376 );
377
378 it("keys mutation ownership by environment and cwd", () => {
379 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
380 EnvironmentRegistry,
381 never
382 >;
383 const manager = createVcsActionManager(runtime);
384 const registry = AtomRegistry.make();
385 const target = { environmentId, cwd };
386 const otherTarget = {
387 environmentId: EnvironmentId.make("environment-2"),
388 cwd,
389 };
390
391 expect(manager.runStackedAction(target)).toBe(manager.runStackedAction({ ...target }));
392 expect(manager.runStackedAction(target)).not.toBe(manager.runStackedAction(otherTarget));
393 expect(registry.get(manager.stateAtom(target))).toEqual(EMPTY_VCS_ACTION_STATE);
394
395 registry.dispose();
396 });
397
398 it("retains the incomplete target and operation when tracking is unavailable", async () => {
399 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
400 EnvironmentRegistry,
401 never
402 >;
403 const manager = createVcsActionManager(runtime);
404 const registry = AtomRegistry.make();
405 const result = await manager.track(
406 registry,
407 { environmentId, cwd: null },
408 { operation: "pull", label: "Pulling latest changes" },
409 async () => AsyncResult.success(undefined),
410 );
411
412 expect(AsyncResult.isFailure(result)).toBe(true);
413 if (AsyncResult.isFailure(result)) {
414 const error = Cause.squash(result.cause);
415 expect(error).toBeInstanceOf(VcsActionUnavailableError);
416 if (!isVcsActionUnavailableError(error)) {
417 throw error;
418 }
419 expect(error).toMatchObject({
420 operation: "pull",
421 environmentId,
422 cwd: null,
423 });
424 expect(error.message).toBe("Source control operation 'pull' is unavailable.");
425 }
426
427 registry.dispose();
428 });
429
430 it("tracks finite mutations without letting an older completion clear newer state", async () => {
431 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
432 EnvironmentRegistry,
433 never
434 >;
435 const manager = createVcsActionManager(runtime);
436 const registry = AtomRegistry.make();
437 const target = { environmentId, cwd };
438 let finishFirst!: () => void;
439 let failSecond!: (error: Error) => void;
440 const firstAction = new Promise<AtomCommandResult<void, never>>((resolve) => {
441 finishFirst = () => resolve(AsyncResult.success(undefined));
442 });
443 const secondAction = new Promise<AtomCommandResult<void, Error>>((resolve) => {
444 failSecond = (error) => resolve(AsyncResult.failure(Cause.fail(error)));
445 });
446
447 const first = manager.track(
448 registry,
449 target,
450 { operation: "pull", label: "Pulling latest changes" },
451 () => firstAction,
452 );
453 const firstActionId = registry.get(manager.stateAtom(target)).actionId;
454 const second = manager.track(
455 registry,
456 target,
457 { operation: "switch_ref", label: "Switching branch" },
458 () => secondAction,
459 );
460 const secondActionId = registry.get(manager.stateAtom(target)).actionId;
461
462 finishFirst();
463 await first;
464 expect(registry.get(manager.stateAtom(target))).toMatchObject({
465 actionId: secondActionId,
466 isRunning: true,
467 operation: "switch_ref",
468 });
469 expect(secondActionId).not.toBe(firstActionId);
470
471 failSecond(new Error("switch failed"));
472 const secondFailure = await second;
473 expect(AsyncResult.isFailure(secondFailure)).toBe(true);
474 expect(registry.get(manager.stateAtom(target))).toMatchObject({
475 actionId: secondActionId,
476 error: "switch failed",
477 isRunning: false,
478 operation: "switch_ref",
479 });
480
481 registry.dispose();
482 });
483});