Open History to see the last commit
1import {
2 EnvironmentId,
3 type EnvironmentId as EnvironmentIdType,
4 GitActionProgressPhase,
5 type GitActionProgressEvent,
6 type GitRunStackedActionInput,
7 type GitRunStackedActionResult,
8 GitStackedAction,
9 WS_METHODS,
10} from "@t3tools/contracts";
11import * as Cause from "effect/Cause";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
17
18import type { EnvironmentRegistry } from "../connection/registry.ts";
19import { runStream } from "../rpc/client.ts";
20import {
21 createRuntimeCommand,
22 runStreamInEnvironment,
23 type AtomCommand,
24 type AtomCommandResult,
25} from "./runtime.ts";
26import { vcsCommandScheduler } from "./vcsCommandScheduler.ts";
27
28export const VcsActionOperation = Schema.Literals([
29 "refresh_status",
30 "run_change_request",
31 "pull",
32 "switch_ref",
33 "create_ref",
34 "create_worktree",
35 "init",
36 "publish_repository",
37 "prepare_pull_request_thread",
38]);
39export type VcsActionOperation = typeof VcsActionOperation.Type;
40
41export interface VcsActionState {
42 readonly isRunning: boolean;
43 readonly operation: VcsActionOperation | null;
44 readonly actionId: string | null;
45 readonly action: GitStackedAction | null;
46 readonly currentLabel: string | null;
47 readonly currentPhaseLabel: string | null;
48 readonly hookName: string | null;
49 readonly lastOutputLine: string | null;
50 readonly phaseStartedAtMs: number | null;
51 readonly hookStartedAtMs: number | null;
52 readonly error: string | null;
53}
54
55export interface VcsActionTarget {
56 readonly environmentId: EnvironmentIdType | null;
57 readonly cwd: string | null;
58}
59
60export interface ResolvedVcsActionTarget {
61 readonly environmentId: EnvironmentIdType;
62 readonly cwd: string;
63}
64
65export interface BeginVcsActionInput {
66 readonly operation: VcsActionOperation;
67 readonly label: string;
68 readonly actionId?: string;
69}
70
71export interface RunVcsStackedActionInput {
72 readonly actionId: string;
73 readonly action: GitStackedAction;
74 readonly commitMessage?: string;
75 readonly featureBranch?: boolean;
76 readonly filePaths?: ReadonlyArray<string>;
77 readonly onProgress?: (event: GitActionProgressEvent) => void;
78}
79
80export class VcsActionUnavailableError extends Schema.TaggedErrorClass<VcsActionUnavailableError>()(
81 "VcsActionUnavailableError",
82 {
83 operation: VcsActionOperation,
84 environmentId: Schema.NullOr(EnvironmentId),
85 cwd: Schema.NullOr(Schema.String),
86 },
87) {
88 override get message(): string {
89 return `Source control operation '${this.operation.replaceAll("_", " ")}' is unavailable.`;
90 }
91}
92
93export class VcsActionRemoteFailureError extends Schema.TaggedErrorClass<VcsActionRemoteFailureError>()(
94 "VcsActionRemoteFailureError",
95 {
96 actionId: Schema.String,
97 transportActionId: Schema.String,
98 action: GitStackedAction,
99 environmentId: EnvironmentId,
100 cwd: Schema.String,
101 phase: Schema.NullOr(GitActionProgressPhase),
102 remoteMessageLength: Schema.Number,
103 },
104) {
105 override get message(): string {
106 const phase = this.phase === null ? "execution" : this.phase;
107 return `Source control action '${this.action}' failed during ${phase}.`;
108 }
109}
110
111export class VcsActionMissingTerminalEventError extends Schema.TaggedErrorClass<VcsActionMissingTerminalEventError>()(
112 "VcsActionMissingTerminalEventError",
113 {
114 actionId: Schema.String,
115 transportActionId: Schema.String,
116 action: GitStackedAction,
117 environmentId: EnvironmentId,
118 cwd: Schema.String,
119 },
120) {
121 override get message(): string {
122 return `Source control action '${this.action}' ended without a terminal result.`;
123 }
124}
125
126export class VcsActionTargetKeyParseError extends Schema.TaggedErrorClass<VcsActionTargetKeyParseError>()(
127 "VcsActionTargetKeyParseError",
128 {
129 keyLength: Schema.Number,
130 cause: Schema.Defect(),
131 },
132) {
133 override get message(): string {
134 return `Invalid source control action target key (${this.keyLength} characters).`;
135 }
136}
137
138export const VcsActionExecutionError = Schema.Union([
139 VcsActionRemoteFailureError,
140 VcsActionMissingTerminalEventError,
141]);
142export type VcsActionExecutionError = typeof VcsActionExecutionError.Type;
143
144export const EMPTY_VCS_ACTION_STATE = Object.freeze<VcsActionState>({
145 isRunning: false,
146 operation: null,
147 actionId: null,
148 action: null,
149 currentLabel: null,
150 currentPhaseLabel: null,
151 hookName: null,
152 lastOutputLine: null,
153 phaseStartedAtMs: null,
154 hookStartedAtMs: null,
155 error: null,
156});
157
158const nowMs = (): number => DateTime.toEpochMillis(DateTime.nowUnsafe());
159let nextLocalActionId = 0;
160const decodeVcsActionTargetKey = Schema.decodeUnknownSync(
161 Schema.Tuple([EnvironmentId, Schema.String]),
162);
163
164export const vcsActionStateAtom = Atom.family((key: string) => {
165 return Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
166 Atom.keepAlive,
167 Atom.withLabel(`vcs-action:${key}`),
168 );
169});
170
171export const EMPTY_VCS_ACTION_ATOM = Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
172 Atom.keepAlive,
173 Atom.withLabel("vcs-action:null"),
174);
175
176export function getVcsActionTargetKey(target: VcsActionTarget): string | null {
177 if (target.environmentId === null || target.cwd === null) {
178 return null;
179 }
180 return JSON.stringify([target.environmentId, target.cwd]);
181}
182
183export function parseVcsActionTargetKey(key: string): ResolvedVcsActionTarget {
184 try {
185 const [environmentId, cwd] = decodeVcsActionTargetKey(JSON.parse(key));
186 return { environmentId, cwd };
187 } catch (cause) {
188 throw new VcsActionTargetKeyParseError({ keyLength: key.length, cause });
189 }
190}
191
192export function getVcsActionStateAtom(target: VcsActionTarget) {
193 const key = getVcsActionTargetKey(target);
194 return key === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(key);
195}
196
197function createLocalActionId(): string {
198 nextLocalActionId += 1;
199 return `local-vcs-action:${nextLocalActionId}`;
200}
201
202export function beginVcsActionState(
203 input: BeginVcsActionInput,
204): VcsActionState & { readonly actionId: string } {
205 const actionId = input.actionId ?? createLocalActionId();
206 const startedAt = nowMs();
207 return {
208 ...EMPTY_VCS_ACTION_STATE,
209 isRunning: true,
210 operation: input.operation,
211 actionId,
212 currentLabel: input.label,
213 currentPhaseLabel: input.label,
214 phaseStartedAtMs: startedAt,
215 };
216}
217
218export function failVcsActionState(
219 operation: VcsActionOperation,
220 actionId: string,
221 error: unknown,
222): VcsActionState {
223 return {
224 ...EMPTY_VCS_ACTION_STATE,
225 operation,
226 actionId,
227 error: error instanceof Error ? error.message : "Source control action failed.",
228 };
229}
230
231export function createVcsActionTransportId(
232 target: ResolvedVcsActionTarget,
233 actionId: string,
234): string {
235 const targetKey = JSON.stringify([target.environmentId, target.cwd]);
236 return `${targetKey.length}:${targetKey}${actionId}`;
237}
238
239export function normalizeVcsActionProgressEvent(
240 target: ResolvedVcsActionTarget,
241 transportActionId: string,
242 actionId: string,
243 event: GitActionProgressEvent,
244): GitActionProgressEvent | null {
245 if (event.actionId !== transportActionId || event.cwd !== target.cwd) {
246 return null;
247 }
248 return {
249 ...event,
250 actionId,
251 };
252}
253
254export function consumeVcsActionProgress<E, R>(
255 stream: Stream.Stream<GitActionProgressEvent, E, R>,
256 input: {
257 readonly target: ResolvedVcsActionTarget;
258 readonly transportActionId: string;
259 readonly actionId: string;
260 readonly action: GitStackedAction;
261 readonly onProgress: (event: GitActionProgressEvent) => Effect.Effect<void>;
262 },
263): Effect.Effect<GitRunStackedActionResult, E | VcsActionExecutionError, R> {
264 return Effect.suspend(() => {
265 let terminalEvent: GitActionProgressEvent | null = null;
266 return stream.pipe(
267 Stream.runForEach((event) => {
268 const normalized = normalizeVcsActionProgressEvent(
269 input.target,
270 input.transportActionId,
271 input.actionId,
272 event,
273 );
274 if (normalized === null) {
275 return Effect.void;
276 }
277 if (normalized.kind === "action_finished" || normalized.kind === "action_failed") {
278 terminalEvent = normalized;
279 }
280 return input.onProgress(normalized);
281 }),
282 Effect.flatMap(() => {
283 if (terminalEvent?.kind === "action_finished") {
284 return Effect.succeed(terminalEvent.result);
285 }
286 if (terminalEvent?.kind === "action_failed") {
287 return Effect.fail<VcsActionExecutionError>(
288 new VcsActionRemoteFailureError({
289 actionId: input.actionId,
290 transportActionId: input.transportActionId,
291 action: terminalEvent.action,
292 environmentId: input.target.environmentId,
293 cwd: input.target.cwd,
294 phase: terminalEvent.phase,
295 remoteMessageLength: terminalEvent.message.length,
296 }),
297 );
298 }
299 return Effect.fail<VcsActionExecutionError>(
300 new VcsActionMissingTerminalEventError({
301 actionId: input.actionId,
302 transportActionId: input.transportActionId,
303 action: input.action,
304 environmentId: input.target.environmentId,
305 cwd: input.target.cwd,
306 }),
307 );
308 }),
309 );
310 });
311}
312
313export function applyVcsActionProgressEvent(
314 current: VcsActionState,
315 event: GitActionProgressEvent,
316): VcsActionState {
317 if (current.actionId !== event.actionId) {
318 return current;
319 }
320 const now = nowMs();
321
322 switch (event.kind) {
323 case "action_started":
324 return {
325 ...current,
326 isRunning: true,
327 actionId: event.actionId,
328 action: event.action,
329 operation: "run_change_request",
330 phaseStartedAtMs: now,
331 hookStartedAtMs: null,
332 hookName: null,
333 lastOutputLine: null,
334 error: null,
335 };
336 case "phase_started":
337 return {
338 ...current,
339 isRunning: true,
340 actionId: event.actionId,
341 action: event.action,
342 operation: "run_change_request",
343 currentLabel: event.label,
344 currentPhaseLabel: event.label,
345 phaseStartedAtMs: now,
346 hookStartedAtMs: null,
347 hookName: null,
348 lastOutputLine: null,
349 error: null,
350 };
351 case "hook_started":
352 return {
353 ...current,
354 isRunning: true,
355 actionId: event.actionId,
356 action: event.action,
357 operation: "run_change_request",
358 currentLabel: `Running ${event.hookName}...`,
359 hookName: event.hookName,
360 hookStartedAtMs: now,
361 lastOutputLine: null,
362 error: null,
363 };
364 case "hook_output":
365 return {
366 ...current,
367 isRunning: true,
368 actionId: event.actionId,
369 action: event.action,
370 operation: "run_change_request",
371 lastOutputLine: event.text,
372 error: null,
373 };
374 case "hook_finished":
375 return {
376 ...current,
377 isRunning: true,
378 actionId: event.actionId,
379 action: event.action,
380 operation: "run_change_request",
381 currentLabel: current.currentPhaseLabel,
382 hookName: null,
383 hookStartedAtMs: null,
384 lastOutputLine: null,
385 error: null,
386 };
387 case "action_finished":
388 return {
389 ...current,
390 isRunning: false,
391 actionId: event.actionId,
392 action: event.action,
393 operation: "run_change_request",
394 error: null,
395 };
396 case "action_failed":
397 return {
398 ...EMPTY_VCS_ACTION_STATE,
399 actionId: event.actionId,
400 action: event.action,
401 operation: "run_change_request",
402 error: event.message,
403 };
404 }
405}
406
407export function createVcsActionManager<R, E>(
408 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
409) {
410 const runStackedActionCommands = new Map<
411 string,
412 AtomCommand<RunVcsStackedActionInput, GitRunStackedActionResult, unknown>
413 >();
414 const getRunStackedActionCommand = (requestedTarget: VcsActionTarget) => {
415 const targetKey = getVcsActionTargetKey(requestedTarget);
416 const commandKey =
417 targetKey ??
418 JSON.stringify([
419 "vcs-action-target:unavailable",
420 requestedTarget.environmentId,
421 requestedTarget.cwd,
422 ]);
423 const existing = runStackedActionCommands.get(commandKey);
424 if (existing !== undefined) {
425 return existing;
426 }
427 const target = targetKey === null ? null : parseVcsActionTargetKey(targetKey);
428 const stateAtom = targetKey === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(targetKey);
429 const command = createRuntimeCommand<
430 EnvironmentRegistry | R,
431 E,
432 RunVcsStackedActionInput,
433 GitRunStackedActionResult,
434 unknown
435 >(runtime, {
436 label: `vcs-action:run-stacked:${commandKey}`,
437 scheduler: vcsCommandScheduler,
438 concurrency: { mode: "serial", key: () => commandKey },
439 execute: (input: RunVcsStackedActionInput, registry) => {
440 if (target === null) {
441 return Effect.fail(
442 new VcsActionUnavailableError({
443 operation: "run_change_request",
444 environmentId: requestedTarget.environmentId,
445 cwd: requestedTarget.cwd,
446 }),
447 );
448 }
449 const transportActionId = createVcsActionTransportId(target, input.actionId);
450 registry.set(
451 stateAtom,
452 beginVcsActionState({
453 operation: "run_change_request",
454 label: "Running source control action",
455 actionId: input.actionId,
456 }),
457 );
458
459 const rpcInput: GitRunStackedActionInput = {
460 actionId: transportActionId,
461 cwd: target.cwd,
462 action: input.action,
463 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
464 ...(input.featureBranch ? { featureBranch: true } : {}),
465 ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
466 };
467 return consumeVcsActionProgress(
468 runStreamInEnvironment(
469 target.environmentId,
470 runStream(WS_METHODS.gitRunStackedAction, rpcInput),
471 ),
472 {
473 target,
474 transportActionId,
475 actionId: input.actionId,
476 action: input.action,
477 onProgress: (event) =>
478 Effect.sync(() => {
479 const current = registry.get(stateAtom);
480 if (current.actionId !== input.actionId) {
481 return;
482 }
483 registry.set(stateAtom, applyVcsActionProgressEvent(current, event));
484 if (input.onProgress !== undefined) {
485 try {
486 input.onProgress(event);
487 } catch {
488 // Presentation callbacks must not fail the source-control operation.
489 }
490 }
491 }),
492 },
493 ).pipe(
494 Effect.tapError((error) =>
495 Effect.sync(() => {
496 const current = registry.get(stateAtom);
497 if (current.actionId === input.actionId && current.isRunning) {
498 registry.set(
499 stateAtom,
500 failVcsActionState("run_change_request", input.actionId, error),
501 );
502 }
503 }),
504 ),
505 );
506 },
507 });
508 runStackedActionCommands.set(commandKey, command);
509 return command;
510 };
511
512 const setState = (
513 registry: AtomRegistry.AtomRegistry,
514 target: VcsActionTarget,
515 update: (current: VcsActionState) => VcsActionState,
516 ): void => {
517 const key = getVcsActionTargetKey(target);
518 if (key === null) {
519 return;
520 }
521 const stateAtom = vcsActionStateAtom(key);
522 registry.set(stateAtom, update(registry.get(stateAtom)));
523 };
524
525 return {
526 stateAtom: getVcsActionStateAtom,
527 runStackedAction: (target: VcsActionTarget) => getRunStackedActionCommand(target),
528 track: async <A, E>(
529 registry: AtomRegistry.AtomRegistry,
530 target: VcsActionTarget,
531 input: BeginVcsActionInput,
532 action: () => Promise<AtomCommandResult<A, E>>,
533 ): Promise<AtomCommandResult<A, E | VcsActionUnavailableError>> => {
534 const key = getVcsActionTargetKey(target);
535 if (key === null) {
536 return AsyncResult.failure<never, VcsActionUnavailableError>(
537 Cause.fail(
538 new VcsActionUnavailableError({
539 operation: input.operation,
540 environmentId: target.environmentId,
541 cwd: target.cwd,
542 }),
543 ),
544 );
545 }
546 const stateAtom = vcsActionStateAtom(key);
547 const next = beginVcsActionState(input);
548 registry.set(stateAtom, next);
549 const result = await action();
550 const current = registry.get(stateAtom);
551 if (current.actionId !== next.actionId) {
552 return result;
553 }
554 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
555 registry.set(stateAtom, EMPTY_VCS_ACTION_STATE);
556 } else {
557 if (registry.get(stateAtom).actionId === next.actionId) {
558 registry.set(
559 stateAtom,
560 failVcsActionState(input.operation, next.actionId, Cause.squash(result.cause)),
561 );
562 }
563 }
564 return result;
565 },
566 resetError: (
567 registry: AtomRegistry.AtomRegistry,
568 target: VcsActionTarget,
569 operation: VcsActionOperation,
570 ): void => {
571 setState(registry, target, (current) =>
572 !current.isRunning && current.operation === operation ? EMPTY_VCS_ACTION_STATE : current,
573 );
574 },
575 };
576}