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