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