Open History to see the last commit
1import {
2 EnvironmentId,
3 WS_METHODS,
4 type GitActionProgressEvent,
5 type GitRunStackedActionResult,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "@effect/vitest";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as SubscriptionRef from "effect/SubscriptionRef";
15import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
16
17import {
18 AVAILABLE_CONNECTION_STATE,
19 PrimaryConnectionTarget,
20 type PreparedConnection,
21 type SupervisorConnectionState,
22} from "../connection/model.ts";
23import * as EnvironmentRegistry from "../connection/registry.ts";
24import * as EnvironmentSupervisor from "../connection/supervisor.ts";
25import * as Persistence from "../platform/persistence.ts";
26import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
27import type { RpcSession } from "../rpc/session.ts";
28import type { AtomCommandResult } from "./runtime.ts";
29import {
30 applyVcsActionProgressEvent,
31 beginVcsActionState,
32 consumeVcsActionProgress,
33 createVcsActionManager,
34 createVcsActionTransportId,
35 EMPTY_VCS_ACTION_STATE,
36 getVcsActionTargetKey,
37 normalizeVcsActionProgressEvent,
38 parseVcsActionTargetKey,
39 VcsActionMissingTerminalEventError,
40 VcsActionRemoteFailureError,
41 VcsActionTargetKeyParseError,
42 VcsActionUnavailableError,
43} from "./vcsAction.ts";
44import { vcsRefsCacheStateAtom } from "./vcsRefInvalidation.ts";
45
46const actionId = "action-123";
47const action = "commit_push" as const;
48const cwd = "/repo";
49const environmentId = EnvironmentId.make("environment-1");
50const isVcsActionUnavailableError = Schema.is(VcsActionUnavailableError);
51const result: GitRunStackedActionResult = {
52 action,
53 branch: {
54 status: "skipped_not_requested",
55 },
56 commit: {
57 status: "created",
58 commitSha: "abc123",
59 subject: "Test commit",
60 },
61 push: {
62 status: "pushed",
63 branch: "feature",
64 },
65 pr: {
66 status: "skipped_not_requested",
67 },
68 toast: {
69 title: "Changes pushed",
70 cta: {
71 kind: "none",
72 },
73 },
74};
75
76const target = new PrimaryConnectionTarget({
77 environmentId,
78 label: "Test environment",
79 httpBaseUrl: "https://environment.example.test",
80 wsBaseUrl: "wss://environment.example.test",
81});
82
83function session(client: WsRpcProtocolClient): RpcSession {
84 return {
85 client,
86 initialConfig: Effect.never,
87 ready: Effect.void,
88 probe: Effect.void,
89 closed: Effect.never,
90 };
91}
92
93function progress<T extends GitActionProgressEvent>(event: T): T {
94 return event;
95}
96
97function cacheStore(onClearVcsRefs: (environmentId: EnvironmentId) => void) {
98 return Persistence.EnvironmentCacheStore.of({
99 loadShell: () => Effect.succeed(Option.none()),
100 saveShell: () => Effect.void,
101 loadThread: () => Effect.succeed(Option.none()),
102 saveThread: () => Effect.void,
103 removeThread: () => Effect.void,
104 loadServerConfig: () => Effect.succeed(Option.none()),
105 saveServerConfig: () => Effect.void,
106 loadVcsRefs: () => Effect.succeed(Option.none()),
107 saveVcsRefs: () => Effect.void,
108 removeVcsRefs: () => Effect.void,
109 clearVcsRefs: (environmentId) => Effect.sync(() => onClearVcsRefs(environmentId)),
110 clear: () => Effect.void,
111 });
112}
113
114describe("vcsActionState", () => {
115 it("preserves malformed target key diagnostics and the native cause without copying the key", () => {
116 const key = "not-json-with-credential=do-not-log";
117 let error: unknown;
118
119 try {
120 parseVcsActionTargetKey(key);
121 } catch (cause) {
122 error = cause;
123 }
124
125 expect(error).toBeInstanceOf(VcsActionTargetKeyParseError);
126 expect(error).toMatchObject({ keyLength: key.length, cause: expect.any(SyntaxError) });
127 expect(error).not.toHaveProperty("key");
128 expect((error as Error).message).not.toContain(key);
129 });
130
131 it("rejects invalid target key shapes", () => {
132 const key = JSON.stringify([environmentId]);
133
134 expect(() => parseVcsActionTargetKey(key)).toThrowError(VcsActionTargetKeyParseError);
135 });
136
137 it("projects phase and hook progress without owning the async operation", () => {
138 const initial = beginVcsActionState({
139 operation: "run_change_request",
140 label: "Running source control action",
141 actionId,
142 });
143 const phase = applyVcsActionProgressEvent(
144 initial,
145 progress({
146 actionId,
147 action,
148 cwd,
149 kind: "phase_started",
150 phase: "commit",
151 label: "Committing...",
152 }),
153 );
154 const hook = applyVcsActionProgressEvent(
155 phase,
156 progress({
157 actionId,
158 action,
159 cwd,
160 kind: "hook_started",
161 hookName: "post-commit",
162 }),
163 );
164 const output = applyVcsActionProgressEvent(
165 hook,
166 progress({
167 actionId,
168 action,
169 cwd,
170 kind: "hook_output",
171 hookName: "post-commit",
172 stream: "stdout",
173 text: "hook output",
174 }),
175 );
176 const finished = applyVcsActionProgressEvent(
177 output,
178 progress({
179 actionId,
180 action,
181 cwd,
182 kind: "hook_finished",
183 hookName: "post-commit",
184 exitCode: 0,
185 durationMs: 12,
186 }),
187 );
188
189 expect(phase).toMatchObject({
190 isRunning: true,
191 currentLabel: "Committing...",
192 currentPhaseLabel: "Committing...",
193 });
194 expect(output).toMatchObject({
195 currentLabel: "Running post-commit...",
196 hookName: "post-commit",
197 lastOutputLine: "hook output",
198 });
199 expect(finished).toMatchObject({
200 currentLabel: "Committing...",
201 hookName: null,
202 lastOutputLine: null,
203 });
204 });
205
206 it("clears running presentation state once the action finishes", () => {
207 const initial = beginVcsActionState({
208 operation: "run_change_request",
209 label: "Running source control action",
210 actionId,
211 });
212 const pushing = applyVcsActionProgressEvent(
213 initial,
214 progress({
215 actionId,
216 action,
217 cwd,
218 kind: "phase_started",
219 phase: "push",
220 label: "Pushing...",
221 }),
222 );
223 const finished = applyVcsActionProgressEvent(
224 pushing,
225 progress({
226 actionId,
227 action,
228 cwd,
229 kind: "action_finished",
230 result,
231 }),
232 );
233
234 expect(finished).toMatchObject({
235 isRunning: false,
236 operation: "run_change_request",
237 actionId,
238 action,
239 currentLabel: null,
240 currentPhaseLabel: null,
241 lastOutputLine: null,
242 error: null,
243 });
244 });
245
246 it("retains a terminal action error for presentation", () => {
247 const initial = beginVcsActionState({
248 operation: "run_change_request",
249 label: "Running source control action",
250 actionId,
251 });
252 const failed = applyVcsActionProgressEvent(
253 initial,
254 progress({
255 actionId,
256 action,
257 cwd,
258 kind: "action_failed",
259 phase: null,
260 message: "Push failed.",
261 }),
262 );
263
264 expect(failed).toMatchObject({
265 isRunning: false,
266 operation: "run_change_request",
267 actionId,
268 action,
269 error: "Push failed.",
270 });
271 });
272
273 it("ignores progress after a newer action owns the target", () => {
274 const current = beginVcsActionState({
275 operation: "pull",
276 label: "Pulling latest changes",
277 actionId: "newer-action",
278 });
279
280 expect(
281 applyVcsActionProgressEvent(
282 current,
283 progress({
284 actionId,
285 action,
286 cwd,
287 kind: "phase_started",
288 phase: "push",
289 label: "Pushing...",
290 }),
291 ),
292 ).toBe(current);
293 });
294
295 it("keys presentation state only when the environment and repository are known", () => {
296 expect(
297 getVcsActionTargetKey({
298 environmentId,
299 cwd,
300 }),
301 ).toBe(JSON.stringify([environmentId, cwd]));
302 expect(getVcsActionTargetKey({ environmentId: null, cwd })).toBeNull();
303 expect(
304 getVcsActionTargetKey({
305 environmentId,
306 cwd: null,
307 }),
308 ).toBeNull();
309 });
310
311 it("normalizes progress only for the matching environment-scoped action", () => {
312 const target = { environmentId, cwd };
313 const otherTarget = {
314 environmentId: EnvironmentId.make("environment-2"),
315 cwd,
316 };
317 const transportActionId = createVcsActionTransportId(target, actionId);
318 const event = progress({
319 actionId: createVcsActionTransportId(otherTarget, actionId),
320 action,
321 cwd,
322 kind: "phase_started",
323 phase: "push",
324 label: "Pushing...",
325 });
326
327 expect(normalizeVcsActionProgressEvent(target, transportActionId, actionId, event)).toBeNull();
328 expect(
329 normalizeVcsActionProgressEvent(target, transportActionId, actionId, {
330 ...event,
331 actionId: transportActionId,
332 }),
333 ).toEqual({
334 ...event,
335 actionId,
336 });
337 });
338
339 it.effect("consumes progress through the terminal event and returns its result", () =>
340 Effect.gen(function* () {
341 const target = { environmentId, cwd };
342 const transportActionId = createVcsActionTransportId(target, actionId);
343 const observed: GitActionProgressEvent[] = [];
344 const events: GitActionProgressEvent[] = [
345 {
346 actionId: "unrelated-action",
347 action,
348 cwd,
349 kind: "phase_started",
350 phase: "commit",
351 label: "Ignored",
352 },
353 {
354 actionId: transportActionId,
355 action,
356 cwd,
357 kind: "phase_started",
358 phase: "push",
359 label: "Pushing...",
360 },
361 {
362 actionId: transportActionId,
363 action,
364 cwd,
365 kind: "action_finished",
366 result,
367 },
368 ];
369
370 const actual = yield* consumeVcsActionProgress(Stream.fromIterable(events), {
371 target,
372 transportActionId,
373 actionId,
374 action,
375 onProgress: (event) =>
376 Effect.sync(() => {
377 observed.push(event);
378 }),
379 });
380
381 expect(actual).toEqual(result);
382 expect(observed.map((event) => event.actionId)).toEqual([actionId, actionId]);
383 expect(observed.map((event) => event.kind)).toEqual(["phase_started", "action_finished"]);
384 }),
385 );
386
387 it.effect("retains structural remote failure context without copying the remote payload", () =>
388 Effect.gen(function* () {
389 const target = { environmentId, cwd };
390 const transportActionId = createVcsActionTransportId(target, actionId);
391 const remoteMessage = "The remote rejected the push with credential=do-not-log.";
392 const error = yield* consumeVcsActionProgress(
393 Stream.fromIterable<GitActionProgressEvent>([
394 {
395 actionId: transportActionId,
396 action,
397 cwd,
398 kind: "action_failed",
399 phase: "push",
400 message: remoteMessage,
401 },
402 ]),
403 {
404 target,
405 transportActionId,
406 actionId,
407 action,
408 onProgress: () => Effect.void,
409 },
410 ).pipe(Effect.flip);
411
412 expect(error).toBeInstanceOf(VcsActionRemoteFailureError);
413 expect(error).toMatchObject({
414 actionId,
415 transportActionId,
416 action,
417 environmentId,
418 cwd,
419 phase: "push",
420 remoteMessageLength: remoteMessage.length,
421 });
422 expect(error).not.toHaveProperty("detail");
423 expect(error.message).toBe("Source control action 'commit_push' failed during push.");
424 expect(error.message).not.toContain(remoteMessage);
425 }),
426 );
427
428 it.effect("reports a missing terminal event as a protocol failure", () =>
429 Effect.gen(function* () {
430 const target = { environmentId, cwd };
431 const transportActionId = createVcsActionTransportId(target, actionId);
432 const error = yield* consumeVcsActionProgress(
433 Stream.fromIterable<GitActionProgressEvent>([
434 {
435 actionId: transportActionId,
436 action,
437 cwd,
438 kind: "phase_started",
439 phase: "commit",
440 label: "Committing...",
441 },
442 ]),
443 {
444 target,
445 transportActionId,
446 actionId,
447 action,
448 onProgress: () => Effect.void,
449 },
450 ).pipe(Effect.flip);
451
452 expect(error).toBeInstanceOf(VcsActionMissingTerminalEventError);
453 expect(error).toMatchObject({
454 actionId,
455 transportActionId,
456 action,
457 environmentId,
458 cwd,
459 });
460 expect(error.message).toBe(
461 "Source control action 'commit_push' ended without a terminal result.",
462 );
463 }),
464 );
465
466 it("keys mutation ownership by environment and cwd", () => {
467 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
468 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore,
469 never
470 >;
471 const manager = createVcsActionManager(runtime);
472 const registry = AtomRegistry.make();
473 const target = { environmentId, cwd };
474 const otherTarget = {
475 environmentId: EnvironmentId.make("environment-2"),
476 cwd,
477 };
478
479 expect(manager.runStackedAction(target)).toBe(manager.runStackedAction({ ...target }));
480 expect(manager.runStackedAction(target)).not.toBe(manager.runStackedAction(otherTarget));
481 expect(registry.get(manager.stateAtom(target))).toEqual(EMPTY_VCS_ACTION_STATE);
482
483 registry.dispose();
484 });
485
486 it("retains the incomplete target and operation when tracking is unavailable", async () => {
487 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
488 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore,
489 never
490 >;
491 const manager = createVcsActionManager(runtime);
492 const registry = AtomRegistry.make();
493 const result = await manager.track(
494 registry,
495 { environmentId, cwd: null },
496 { operation: "pull", label: "Pulling latest changes" },
497 async () => AsyncResult.success(undefined),
498 );
499
500 expect(AsyncResult.isFailure(result)).toBe(true);
501 if (AsyncResult.isFailure(result)) {
502 const error = Cause.squash(result.cause);
503 expect(error).toBeInstanceOf(VcsActionUnavailableError);
504 if (!isVcsActionUnavailableError(error)) {
505 throw error;
506 }
507 expect(error).toMatchObject({
508 operation: "pull",
509 environmentId,
510 cwd: null,
511 });
512 expect(error.message).toBe("Source control operation 'pull' is unavailable.");
513 }
514
515 registry.dispose();
516 });
517
518 it("tracks finite mutations without letting an older completion clear newer state", async () => {
519 const runtime = Atom.runtime(Layer.empty) as unknown as Atom.AtomRuntime<
520 EnvironmentRegistry.EnvironmentRegistry | Persistence.EnvironmentCacheStore,
521 never
522 >;
523 const manager = createVcsActionManager(runtime);
524 const registry = AtomRegistry.make();
525 const target = { environmentId, cwd };
526 let finishFirst!: () => void;
527 let failSecond!: (error: Error) => void;
528 const firstAction = new Promise<AtomCommandResult<void, never>>((resolve) => {
529 finishFirst = () => resolve(AsyncResult.success(undefined));
530 });
531 const secondAction = new Promise<AtomCommandResult<void, Error>>((resolve) => {
532 failSecond = (error) => resolve(AsyncResult.failure(Cause.fail(error)));
533 });
534
535 const first = manager.track(
536 registry,
537 target,
538 { operation: "pull", label: "Pulling latest changes" },
539 () => firstAction,
540 );
541 const firstActionId = registry.get(manager.stateAtom(target)).actionId;
542 const second = manager.track(
543 registry,
544 target,
545 { operation: "switch_ref", label: "Switching branch" },
546 () => secondAction,
547 );
548 const secondActionId = registry.get(manager.stateAtom(target)).actionId;
549
550 finishFirst();
551 await first;
552 expect(registry.get(manager.stateAtom(target))).toMatchObject({
553 actionId: secondActionId,
554 isRunning: true,
555 operation: "switch_ref",
556 });
557 expect(secondActionId).not.toBe(firstActionId);
558
559 failSecond(new Error("switch failed"));
560 const secondFailure = await second;
561 expect(AsyncResult.isFailure(secondFailure)).toBe(true);
562 expect(registry.get(manager.stateAtom(target))).toMatchObject({
563 actionId: secondActionId,
564 error: "switch failed",
565 isRunning: false,
566 operation: "switch_ref",
567 });
568
569 registry.dispose();
570 });
571
572 it.effect("invalidates persisted refs after successful and failed stacked actions", () =>
573 Effect.scoped(
574 Effect.gen(function* () {
575 const connectionState: SupervisorConnectionState = {
576 ...AVAILABLE_CONNECTION_STATE,
577 desired: true,
578 network: "online",
579 phase: "connected",
580 attempt: 1,
581 generation: 1,
582 };
583 const targetKey = { environmentId, cwd };
584 const successfulActionId = "invalidate-success";
585 const failedActionId = "invalidate-failure";
586 const successfulTransportActionId = createVcsActionTransportId(
587 targetKey,
588 successfulActionId,
589 );
590 const failedTransportActionId = createVcsActionTransportId(targetKey, failedActionId);
591 const client = {
592 [WS_METHODS.gitRunStackedAction]: (input: { readonly actionId: string }) =>
593 input.actionId === successfulTransportActionId
594 ? Stream.make(
595 progress({
596 kind: "action_finished",
597 actionId: successfulTransportActionId,
598 cwd,
599 action,
600 result,
601 }),
602 )
603 : Stream.make(
604 progress({
605 kind: "action_failed",
606 actionId: failedTransportActionId,
607 cwd,
608 action,
609 phase: "push",
610 message: "push failed after creating the branch",
611 }),
612 ),
613 } as unknown as WsRpcProtocolClient;
614 const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({
615 target,
616 state: yield* SubscriptionRef.make(connectionState),
617 session: yield* SubscriptionRef.make(Option.some(session(client))),
618 prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),
619 connect: Effect.void,
620 disconnect: Effect.void,
621 retryNow: Effect.void,
622 } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
623 const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (
624 _environmentId,
625 effect,
626 ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
627 const runStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["runStream"] = (
628 _environmentId,
629 stream,
630 ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);
631 const environmentRegistry = EnvironmentRegistry.EnvironmentRegistry.of({
632 run,
633 runStream,
634 } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]);
635 const removed = new Array<string>();
636 const runtime = Atom.runtime(
637 Layer.merge(
638 Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, environmentRegistry),
639 Layer.succeed(
640 Persistence.EnvironmentCacheStore,
641 cacheStore((removedEnvironmentId) => {
642 removed.push(`${removedEnvironmentId}:*`);
643 }),
644 ),
645 ),
646 );
647 const manager = createVcsActionManager(runtime);
648 const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>
649 Effect.sync(() => registry.dispose()),
650 );
651 const state = vcsRefsCacheStateAtom({ environmentId });
652
653 expect(registry.get(state).revision).toBe(0);
654 const successfulResult = yield* Effect.promise(() =>
655 manager.runStackedAction(targetKey).run(registry, {
656 actionId: successfulActionId,
657 action,
658 }),
659 );
660
661 expect(AsyncResult.isSuccess(successfulResult)).toBe(true);
662 expect(registry.get(state).revision).toBe(1);
663 expect(removed).toEqual([`${environmentId}:*`]);
664
665 const failedResult = yield* Effect.promise(() =>
666 manager.runStackedAction(targetKey).run(registry, {
667 actionId: failedActionId,
668 action,
669 }),
670 );
671
672 expect(AsyncResult.isFailure(failedResult)).toBe(true);
673 expect(registry.get(state).revision).toBe(2);
674 expect(removed).toEqual([`${environmentId}:*`, `${environmentId}:*`]);
675 }),
676 ),
677 );
678});