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