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