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