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 ...EMPTY_VCS_ACTION_STATE,
395 actionId: event.actionId,
396 action: event.action,
397 operation: "run_change_request",
398 };
399 case "action_failed":
400 return {
401 ...EMPTY_VCS_ACTION_STATE,
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 ...(input.threadId !== undefined ? { threadId: input.threadId } : {}),
470 };
471 return consumeVcsActionProgress(
472 runStreamInEnvironment(
473 target.environmentId,
474 runStream(WS_METHODS.gitRunStackedAction, rpcInput),
475 ),
476 {
477 target,
478 transportActionId,
479 actionId: input.actionId,
480 action: input.action,
481 onProgress: (event) =>
482 Effect.sync(() => {
483 const current = registry.get(stateAtom);
484 if (current.actionId !== input.actionId) {
485 return;
486 }
487 registry.set(stateAtom, applyVcsActionProgressEvent(current, event));
488 if (input.onProgress !== undefined) {
489 try {
490 input.onProgress(event);
491 } catch {
492 // Presentation callbacks must not fail the source-control operation.
493 }
494 }
495 }),
496 },
497 ).pipe(
498 Effect.ensuring(invalidateCachedVcsRefs(registry, target)),
499 Effect.tapError((error) =>
500 Effect.sync(() => {
501 const current = registry.get(stateAtom);
502 if (current.actionId === input.actionId && current.isRunning) {
503 registry.set(
504 stateAtom,
505 failVcsActionState("run_change_request", input.actionId, error),
506 );
507 }
508 }),
509 ),
510 );
511 },
512 });
513 runStackedActionCommands.set(commandKey, command);
514 return command;
515 };
516
517 const setState = (
518 registry: AtomRegistry.AtomRegistry,
519 target: VcsActionTarget,
520 update: (current: VcsActionState) => VcsActionState,
521 ): void => {
522 const key = getVcsActionTargetKey(target);
523 if (key === null) {
524 return;
525 }
526 const stateAtom = vcsActionStateAtom(key);
527 registry.set(stateAtom, update(registry.get(stateAtom)));
528 };
529
530 return {
531 stateAtom: getVcsActionStateAtom,
532 runStackedAction: (target: VcsActionTarget) => getRunStackedActionCommand(target),
533 track: async <A, E>(
534 registry: AtomRegistry.AtomRegistry,
535 target: VcsActionTarget,
536 input: BeginVcsActionInput,
537 action: () => Promise<AtomCommandResult<A, E>>,
538 ): Promise<AtomCommandResult<A, E | VcsActionUnavailableError>> => {
539 const key = getVcsActionTargetKey(target);
540 if (key === null) {
541 return AsyncResult.failure<never, VcsActionUnavailableError>(
542 Cause.fail(
543 new VcsActionUnavailableError({
544 operation: input.operation,
545 environmentId: target.environmentId,
546 cwd: target.cwd,
547 }),
548 ),
549 );
550 }
551 const stateAtom = vcsActionStateAtom(key);
552 const next = beginVcsActionState(input);
553 registry.set(stateAtom, next);
554 const result = await action();
555 const current = registry.get(stateAtom);
556 if (current.actionId !== next.actionId) {
557 return result;
558 }
559 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
560 registry.set(stateAtom, EMPTY_VCS_ACTION_STATE);
561 } else {
562 if (registry.get(stateAtom).actionId === next.actionId) {
563 registry.set(
564 stateAtom,
565 failVcsActionState(input.operation, next.actionId, Cause.squash(result.cause)),
566 );
567 }
568 }
569 return result;
570 },
571 resetError: (
572 registry: AtomRegistry.AtomRegistry,
573 target: VcsActionTarget,
574 operation: VcsActionOperation,
575 ): void => {
576 setState(registry, target, (current) =>
577 !current.isRunning && current.operation === operation ? EMPTY_VCS_ACTION_STATE : current,
578 );
579 },
580 };
581}