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 ...EMPTY_VCS_ACTION_STATE,
390 actionId: event.actionId,
391 action: event.action,
392 operation: "run_change_request",
393 };
394 case "action_failed":
395 return {
396 ...EMPTY_VCS_ACTION_STATE,
397 actionId: event.actionId,
398 action: event.action,
399 operation: "run_change_request",
400 error: event.message,
401 };
402 }
403}
404
405export function createVcsActionManager<R, E>(
406 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
407) {
408 const runStackedActionCommands = new Map<
409 string,
410 AtomCommand<RunVcsStackedActionInput, GitRunStackedActionResult, unknown>
411 >();
412 const getRunStackedActionCommand = (requestedTarget: VcsActionTarget) => {
413 const targetKey = getVcsActionTargetKey(requestedTarget);
414 const commandKey =
415 targetKey ??
416 JSON.stringify([
417 "vcs-action-target:unavailable",
418 requestedTarget.environmentId,
419 requestedTarget.cwd,
420 ]);
421 const existing = runStackedActionCommands.get(commandKey);
422 if (existing !== undefined) {
423 return existing;
424 }
425 const target = targetKey === null ? null : parseVcsActionTargetKey(targetKey);
426 const stateAtom = targetKey === null ? EMPTY_VCS_ACTION_ATOM : vcsActionStateAtom(targetKey);
427 const command = createRuntimeCommand<
428 EnvironmentRegistry | R,
429 E,
430 RunVcsStackedActionInput,
431 GitRunStackedActionResult,
432 unknown
433 >(runtime, {
434 label: `vcs-action:run-stacked:${commandKey}`,
435 scheduler: vcsCommandScheduler,
436 concurrency: { mode: "serial", key: () => commandKey },
437 execute: (input: RunVcsStackedActionInput, registry) => {
438 if (target === null) {
439 return Effect.fail(
440 new VcsActionUnavailableError({
441 operation: "run_change_request",
442 environmentId: requestedTarget.environmentId,
443 cwd: requestedTarget.cwd,
444 }),
445 );
446 }
447 const transportActionId = createVcsActionTransportId(target, input.actionId);
448 registry.set(
449 stateAtom,
450 beginVcsActionState({
451 operation: "run_change_request",
452 label: "Running source control action",
453 actionId: input.actionId,
454 }),
455 );
456
457 const rpcInput: GitRunStackedActionInput = {
458 actionId: transportActionId,
459 cwd: target.cwd,
460 action: input.action,
461 ...(input.commitMessage ? { commitMessage: input.commitMessage } : {}),
462 ...(input.featureBranch ? { featureBranch: true } : {}),
463 ...(input.filePaths?.length ? { filePaths: [...input.filePaths] } : {}),
464 };
465 return consumeVcsActionProgress(
466 runStreamInEnvironment(
467 target.environmentId,
468 runStream(WS_METHODS.gitRunStackedAction, rpcInput),
469 ),
470 {
471 target,
472 transportActionId,
473 actionId: input.actionId,
474 action: input.action,
475 onProgress: (event) =>
476 Effect.sync(() => {
477 const current = registry.get(stateAtom);
478 if (current.actionId !== input.actionId) {
479 return;
480 }
481 registry.set(stateAtom, applyVcsActionProgressEvent(current, event));
482 if (input.onProgress !== undefined) {
483 try {
484 input.onProgress(event);
485 } catch {
486 // Presentation callbacks must not fail the source-control operation.
487 }
488 }
489 }),
490 },
491 ).pipe(
492 Effect.tapError((error) =>
493 Effect.sync(() => {
494 const current = registry.get(stateAtom);
495 if (current.actionId === input.actionId && current.isRunning) {
496 registry.set(
497 stateAtom,
498 failVcsActionState("run_change_request", input.actionId, error),
499 );
500 }
501 }),
502 ),
503 );
504 },
505 });
506 runStackedActionCommands.set(commandKey, command);
507 return command;
508 };
509
510 const setState = (
511 registry: AtomRegistry.AtomRegistry,
512 target: VcsActionTarget,
513 update: (current: VcsActionState) => VcsActionState,
514 ): void => {
515 const key = getVcsActionTargetKey(target);
516 if (key === null) {
517 return;
518 }
519 const stateAtom = vcsActionStateAtom(key);
520 registry.set(stateAtom, update(registry.get(stateAtom)));
521 };
522
523 return {
524 stateAtom: getVcsActionStateAtom,
525 runStackedAction: (target: VcsActionTarget) => getRunStackedActionCommand(target),
526 track: async <A, E>(
527 registry: AtomRegistry.AtomRegistry,
528 target: VcsActionTarget,
529 input: BeginVcsActionInput,
530 action: () => Promise<AtomCommandResult<A, E>>,
531 ): Promise<AtomCommandResult<A, E | VcsActionUnavailableError>> => {
532 const key = getVcsActionTargetKey(target);
533 if (key === null) {
534 return AsyncResult.failure<never, VcsActionUnavailableError>(
535 Cause.fail(
536 new VcsActionUnavailableError({
537 operation: input.operation,
538 environmentId: target.environmentId,
539 cwd: target.cwd,
540 }),
541 ),
542 );
543 }
544 const stateAtom = vcsActionStateAtom(key);
545 const next = beginVcsActionState(input);
546 registry.set(stateAtom, next);
547 const result = await action();
548 const current = registry.get(stateAtom);
549 if (current.actionId !== next.actionId) {
550 return result;
551 }
552 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
553 registry.set(stateAtom, EMPTY_VCS_ACTION_STATE);
554 } else {
555 if (registry.get(stateAtom).actionId === next.actionId) {
556 registry.set(
557 stateAtom,
558 failVcsActionState(input.operation, next.actionId, Cause.squash(result.cause)),
559 );
560 }
561 }
562 return result;
563 },
564 resetError: (
565 registry: AtomRegistry.AtomRegistry,
566 target: VcsActionTarget,
567 operation: VcsActionOperation,
568 ): void => {
569 setState(registry, target, (current) =>
570 !current.isRunning && current.operation === operation ? EMPTY_VCS_ACTION_STATE : current,
571 );
572 },
573 };
574}