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