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

vcsAction.test.ts

523 lines14.5 KB

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;
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("clears running presentation state once the action finishes", () => {
159 const initial = beginVcsActionState({
160 operation: "run_change_request",
161 label: "Running source control action",
162 actionId,
163 });
164 const pushing = applyVcsActionProgressEvent(
165 initial,
166 progress({
167 actionId,
168 action,
169 cwd,
170 kind: "phase_started",
171 phase: "push",
172 label: "Pushing...",
173 }),
174 );
175 const finished = applyVcsActionProgressEvent(
176 pushing,
177 progress({
178 actionId,
179 action,
180 cwd,
181 kind: "action_finished",
182 result,
183 }),
184 );
185​
186 expect(finished).toMatchObject({
187 isRunning: false,
188 operation: "run_change_request",
189 actionId,
190 action,
191 currentLabel: null,
192 currentPhaseLabel: null,
193 lastOutputLine: null,
194 error: null,
195 });
196 });
197​
198 it("retains a terminal action error for presentation", () => {
199 const initial = beginVcsActionState({
200 operation: "run_change_request",
201 label: "Running source control action",
202 actionId,
203 });
204 const failed = applyVcsActionProgressEvent(
205 initial,
206 progress({
207 actionId,
208 action,
209 cwd,
210 kind: "action_failed",
211 phase: null,
212 message: "Push failed.",
213 }),
214 );
215​
216 expect(failed).toMatchObject({
217 isRunning: false,
218 operation: "run_change_request",
219 actionId,
220 action,
221 error: "Push failed.",
222 });
223 });
224​
225 it("ignores progress after a newer action owns the target", () => {
226 const current = beginVcsActionState({
227 operation: "pull",
228 label: "Pulling latest changes",
229 actionId: "newer-action",
230 });
231​
232 expect(
233 applyVcsActionProgressEvent(
234 current,
235 progress({
236 actionId,
237 action,
238 cwd,
239 kind: "phase_started",
240 phase: "push",
241 label: "Pushing...",
242 }),
243 ),
244 ).toBe(current);
245 });
246​
247 it("keys presentation state only when the environment and repository are known", () => {
248 expect(
249 getVcsActionTargetKey({
250 environmentId,
251 cwd,
252 }),
253 ).toBe(JSON.stringify([environmentId, cwd]));
254 expect(getVcsActionTargetKey({ environmentId: null, cwd })).toBeNull();
255 expect(
256 getVcsActionTargetKey({
257 environmentId,
258 cwd: null,
259 }),
260 ).toBeNull();
261 });
262​
263 it("normalizes progress only for the matching environment-scoped action", () => {
264 const target = { environmentId, cwd };
265 const otherTarget = {
266 environmentId: EnvironmentId.make("environment-2"),
267 cwd,
268 };
269 const transportActionId = createVcsActionTransportId(target, actionId);
270 const event = progress({
271 actionId: createVcsActionTransportId(otherTarget, actionId),
272 action,
273 cwd,
274 kind: "phase_started",
275 phase: "push",
276 label: "Pushing...",
277 });
278​
279 expect(normalizeVcsActionProgressEvent(target, transportActionId, actionId, event)).toBeNull();
280 expect(
281 normalizeVcsActionProgressEvent(target, transportActionId, actionId, {
282 ...event,
283 actionId: transportActionId,
284 }),
285 ).toEqual({
286 ...event,
287 actionId,
288 });
289 });
290​
291 it.effect("consumes progress through the terminal event and returns its result", () =>
292 Effect.gen(function* () {
293 const target = { environmentId, cwd };
294 const transportActionId = createVcsActionTransportId(target, actionId);
295 const observed: GitActionProgressEvent[] = [];
296 const events: GitActionProgressEvent[] = [
297 {
298 actionId: "unrelated-action",
299 action,
300 cwd,
301 kind: "phase_started",
302 phase: "commit",
303 label: "Ignored",
304 },
305 {
306 actionId: transportActionId,
307 action,
308 cwd,
309 kind: "phase_started",
310 phase: "push",
311 label: "Pushing...",
312 },
313 {
314 actionId: transportActionId,
315 action,
316 cwd,
317 kind: "action_finished",
318 result,
319 },
320 ];
321​
322 const actual = yield* consumeVcsActionProgress(Stream.fromIterable(events), {
323 target,
324 transportActionId,
325 actionId,
326 action,
327 onProgress: (event) =>
328 Effect.sync(() => {
329 observed.push(event);
330 }),
331 });
332​
333 expect(actual).toEqual(result);
334 expect(observed.map((event) => event.actionId)).toEqual([actionId, actionId]);
335 expect(observed.map((event) => event.kind)).toEqual(["phase_started", "action_finished"]);
336 }),
337 );
338​
339 it.effect("retains structural remote failure context without copying the remote payload", () =>
340 Effect.gen(function* () {
341 const target = { environmentId, cwd };
342 const transportActionId = createVcsActionTransportId(target, actionId);
343 const remoteMessage = "The remote rejected the push with credential=do-not-log.";
344 const error = yield* consumeVcsActionProgress(
345 Stream.fromIterable<GitActionProgressEvent>([
346 {
347 actionId: transportActionId,
348 action,
349 cwd,
350 kind: "action_failed",
351 phase: "push",
352 message: remoteMessage,
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(VcsActionRemoteFailureError);
365 expect(error).toMatchObject({
366 actionId,
367 transportActionId,
368 action,
369 environmentId,
370 cwd,
371 phase: "push",
372 remoteMessageLength: remoteMessage.length,
373 });
374 expect(error).not.toHaveProperty("detail");
375 expect(error.message).toBe("Source control action 'commit_push' failed during push.");
376 expect(error.message).not.toContain(remoteMessage);
377 }),
378 );
379​
380 it.effect("reports a missing terminal event as a protocol failure", () =>
381 Effect.gen(function* () {
382 const target = { environmentId, cwd };
383 const transportActionId = createVcsActionTransportId(target, actionId);
384 const error = yield* consumeVcsActionProgress(
385 Stream.fromIterable<GitActionProgressEvent>([
386 {
387 actionId: transportActionId,
388 action,
389 cwd,
390 kind: "phase_started",
391 phase: "commit",
392 label: "Committing...",
393 },
394 ]),
395 {
396 target,
397 transportActionId,
398 actionId,
399 action,
400 onProgress: () => Effect.void,
401 },
402 ).pipe(Effect.flip);
403​
404 expect(error).toBeInstanceOf(VcsActionMissingTerminalEventError);
405 expect(error).toMatchObject({
406 actionId,
407 transportActionId,
408 action,
409 environmentId,
410 cwd,
411 });
412 expect(error.message).toBe(
413 "Source control action 'commit_push' ended without a terminal result.",
414 );
415 }),
416 );
417​
418 it("keys mutation ownership by environment and cwd", () => {
419 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
420 EnvironmentRegistry,
421 never
422 >;
423 const manager = createVcsActionManager(runtime);
424 const registry = AtomRegistry.make();
425 const target = { environmentId, cwd };
426 const otherTarget = {
427 environmentId: EnvironmentId.make("environment-2"),
428 cwd,
429 };
430​
431 expect(manager.runStackedAction(target)).toBe(manager.runStackedAction({ ...target }));
432 expect(manager.runStackedAction(target)).not.toBe(manager.runStackedAction(otherTarget));
433 expect(registry.get(manager.stateAtom(target))).toEqual(EMPTY_VCS_ACTION_STATE);
434​
435 registry.dispose();
436 });
437​
438 it("retains the incomplete target and operation when tracking is unavailable", async () => {
439 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
440 EnvironmentRegistry,
441 never
442 >;
443 const manager = createVcsActionManager(runtime);
444 const registry = AtomRegistry.make();
445 const result = await manager.track(
446 registry,
447 { environmentId, cwd: null },
448 { operation: "pull", label: "Pulling latest changes" },
449 async () => AsyncResult.success(undefined),
450 );
451​
452 expect(AsyncResult.isFailure(result)).toBe(true);
453 if (AsyncResult.isFailure(result)) {
454 const error = Cause.squash(result.cause);
455 expect(error).toBeInstanceOf(VcsActionUnavailableError);
456 if (!isVcsActionUnavailableError(error)) {
457 throw error;
458 }
459 expect(error).toMatchObject({
460 operation: "pull",
461 environmentId,
462 cwd: null,
463 });
464 expect(error.message).toBe("Source control operation 'pull' is unavailable.");
465 }
466​
467 registry.dispose();
468 });
469​
470 it("tracks finite mutations without letting an older completion clear newer state", async () => {
471 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
472 EnvironmentRegistry,
473 never
474 >;
475 const manager = createVcsActionManager(runtime);
476 const registry = AtomRegistry.make();
477 const target = { environmentId, cwd };
478 let finishFirst!: () => void;
479 let failSecond!: (error: Error) => void;
480 const firstAction = new Promise<AtomCommandResult<void, never>>((resolve) => {
481 finishFirst = () => resolve(AsyncResult.success(undefined));
482 });
483 const secondAction = new Promise<AtomCommandResult<void, Error>>((resolve) => {
484 failSecond = (error) => resolve(AsyncResult.failure(Cause.fail(error)));
485 });
486​
487 const first = manager.track(
488 registry,
489 target,
490 { operation: "pull", label: "Pulling latest changes" },
491 () => firstAction,
492 );
493 const firstActionId = registry.get(manager.stateAtom(target)).actionId;
494 const second = manager.track(
495 registry,
496 target,
497 { operation: "switch_ref", label: "Switching branch" },
498 () => secondAction,
499 );
500 const secondActionId = registry.get(manager.stateAtom(target)).actionId;
501​
502 finishFirst();
503 await first;
504 expect(registry.get(manager.stateAtom(target))).toMatchObject({
505 actionId: secondActionId,
506 isRunning: true,
507 operation: "switch_ref",
508 });
509 expect(secondActionId).not.toBe(firstActionId);
510​
511 failSecond(new Error("switch failed"));
512 const secondFailure = await second;
513 expect(AsyncResult.isFailure(secondFailure)).toBe(true);
514 expect(registry.get(manager.stateAtom(target))).toMatchObject({
515 actionId: secondActionId,
516 error: "switch failed",
517 isRunning: false,
518 operation: "switch_ref",
519 });
520​
521 registry.dispose();
522 });
523});