Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

vcsActionState.ts

458 lines12.9 KB

1import type {
2 GitActionProgressEvent,
3 GitRunStackedActionInput,
4 GitRunStackedActionResult,
5 GitStackedAction,
6 EnvironmentId,
7 VcsCreateRefInput,
8 VcsCreateRefResult,
9 VcsCreateWorktreeInput,
10 VcsCreateWorktreeResult,
11 VcsPullInput,
12 VcsPullResult,
13 VcsStatusResult,
14 VcsSwitchRefInput,
15 VcsSwitchRefResult,
16} from "@t3tools/contracts";
17import * as DateTime from "effect/DateTime";
18import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
19​
20import { buildGitActionProgressStages } from "./gitActions.ts";
21import type { WsRpcClient } from "./wsRpcClient.ts";
22​
23export type VcsActionOperation =
24 | "refresh_status"
25 | "run_change_request"
26 | "pull"
27 | "switch_ref"
28 | "create_ref"
29 | "create_worktree"
30 | "init";
31​
32export interface VcsActionState {
33 readonly isRunning: boolean;
34 readonly operation: VcsActionOperation | null;
35 readonly actionId: string | null;
36 readonly action: GitStackedAction | null;
37 readonly currentLabel: string | null;
38 readonly currentPhaseLabel: string | null;
39 readonly hookName: string | null;
40 readonly lastOutputLine: string | null;
41 readonly phaseStartedAtMs: number | null;
42 readonly hookStartedAtMs: number | null;
43 readonly error: string | null;
45​
46export interface VcsActionTarget {
47 readonly environmentId: EnvironmentId | null;
48 readonly cwd: string | null;
50​
51export type VcsActionClient = Pick<
52 WsRpcClient["vcs"],
53 "refreshStatus" | "pull" | "switchRef" | "createRef" | "createWorktree" | "init"
54> & {
55 readonly runChangeRequest: WsRpcClient["git"]["runStackedAction"];
56};
57​
58export const EMPTY_VCS_ACTION_STATE = Object.freeze<VcsActionState>({
59 isRunning: false,
60 operation: null,
61 actionId: null,
62 action: null,
63 currentLabel: null,
64 currentPhaseLabel: null,
65 hookName: null,
66 lastOutputLine: null,
67 phaseStartedAtMs: null,
68 hookStartedAtMs: null,
69 error: null,
70});
71​
72const knownVcsActionKeys = new Set<string>();
73let nextGeneratedActionId = 0;
74const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
75​
76export const vcsActionStateAtom = Atom.family((key: string) => {
77 knownVcsActionKeys.add(key);
78 return Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
79 Atom.keepAlive,
80 Atom.withLabel(`vcs-action:${key}`),
81 );
82});
83​
84export const EMPTY_VCS_ACTION_ATOM = Atom.make(EMPTY_VCS_ACTION_STATE).pipe(
85 Atom.keepAlive,
86 Atom.withLabel("vcs-action:null"),
87);
88​
89export function getVcsActionTargetKey(target: VcsActionTarget): string | null {
90 if (target.environmentId === null || target.cwd === null) {
91 return null;
92 }
93 return `${target.environmentId}:${target.cwd}`;
95​
96export function applyVcsActionProgressEvent(
97 current: VcsActionState,
98 event: GitActionProgressEvent,
99): VcsActionState {
100 const now = nowMs();
101​
102 switch (event.kind) {
103 case "action_started":
104 return {
105 ...current,
106 isRunning: true,
107 actionId: event.actionId,
108 action: event.action,
109 operation: "run_change_request",
110 phaseStartedAtMs: now,
111 hookStartedAtMs: null,
112 hookName: null,
113 lastOutputLine: null,
114 error: null,
115 };
116 case "phase_started":
117 return {
118 ...current,
119 isRunning: true,
120 actionId: event.actionId,
121 action: event.action,
122 operation: "run_change_request",
123 currentLabel: event.label,
124 currentPhaseLabel: event.label,
125 phaseStartedAtMs: now,
126 hookStartedAtMs: null,
127 hookName: null,
128 lastOutputLine: null,
129 error: null,
130 };
131 case "hook_started":
132 return {
133 ...current,
134 isRunning: true,
135 actionId: event.actionId,
136 action: event.action,
137 operation: "run_change_request",
138 currentLabel: `Running ${event.hookName}...`,
139 hookName: event.hookName,
140 hookStartedAtMs: now,
141 lastOutputLine: null,
142 error: null,
143 };
144 case "hook_output":
145 return {
146 ...current,
147 isRunning: true,
148 actionId: event.actionId,
149 action: event.action,
150 operation: "run_change_request",
151 lastOutputLine: event.text,
152 error: null,
153 };
154 case "hook_finished":
155 return {
156 ...current,
157 isRunning: true,
158 actionId: event.actionId,
159 action: event.action,
160 operation: "run_change_request",
161 currentLabel: current.currentPhaseLabel,
162 hookName: null,
163 hookStartedAtMs: null,
164 lastOutputLine: null,
165 error: null,
166 };
167 case "action_finished":
168 return {
169 ...current,
170 isRunning: false,
171 actionId: event.actionId,
172 action: event.action,
173 operation: "run_change_request",
174 error: null,
175 };
176 case "action_failed":
177 return {
178 ...EMPTY_VCS_ACTION_STATE,
179 actionId: event.actionId,
180 action: event.action,
181 operation: "run_change_request",
182 error: event.message,
183 };
184 }
186​
187export interface VcsActionManagerConfig {
188 readonly getRegistry: () => AtomRegistry.AtomRegistry;
189 readonly getClient: (environmentId: EnvironmentId) => VcsActionClient | null;
190 readonly getActionId?: () => string;
191 readonly onInvalidate?: (target: VcsActionTarget) => void | Promise<void>;
193​
194export function createVcsActionManager(config: VcsActionManagerConfig) {
195 function setState(targetKey: string, nextState: VcsActionState): void {
196 config.getRegistry().set(vcsActionStateAtom(targetKey), nextState);
197 }
198​
199 function startOperation(
200 targetKey: string,
201 input: {
202 readonly operation: VcsActionOperation;
203 readonly actionId?: string;
204 readonly action?: GitStackedAction;
205 readonly label: string;
206 },
207 ): void {
208 setState(targetKey, {
209 isRunning: true,
210 operation: input.operation,
211 actionId: input.actionId ?? null,
212 action: input.action ?? null,
213 currentLabel: input.label,
214 currentPhaseLabel: input.label,
215 hookName: null,
216 lastOutputLine: null,
217 phaseStartedAtMs: nowMs(),
218 hookStartedAtMs: null,
219 error: null,
220 });
221 }
222​
223 function finishOperation(targetKey: string): void {
224 setState(targetKey, EMPTY_VCS_ACTION_STATE);
225 }
226​
227 function failOperation(
228 targetKey: string,
229 error: unknown,
230 input: {
231 readonly operation: VcsActionOperation;
232 readonly actionId?: string;
233 readonly action?: GitStackedAction;
234 },
235 ): void {
236 setState(targetKey, {
237 ...EMPTY_VCS_ACTION_STATE,
238 operation: input.operation,
239 actionId: input.actionId ?? null,
240 action: input.action ?? null,
241 error: error instanceof Error ? error.message : "Source control action failed.",
242 });
243 }
244​
245 async function runOperation<TResult>(
246 target: VcsActionTarget,
247 input: {
248 readonly operation: VcsActionOperation;
249 readonly label: string;
250 readonly actionId?: string;
251 readonly action?: GitStackedAction;
252 readonly client?: VcsActionClient | undefined;
253 readonly invalidateOnSuccess?: boolean;
254 readonly execute: (client: VcsActionClient) => Promise<TResult>;
255 },
256 ): Promise<TResult | null> {
257 const targetKey = getVcsActionTargetKey(target);
258 if (targetKey === null || target.environmentId === null || target.cwd === null) {
259 return null;
260 }
261​
262 const resolved = input.client ?? config.getClient(target.environmentId);
263 if (!resolved) {
264 return null;
265 }
266​
267 startOperation(targetKey, input);
268 try {
269 const result = await input.execute(resolved);
270 finishOperation(targetKey);
271 if (input.invalidateOnSuccess ?? true) {
272 await config.onInvalidate?.(target);
273 }
274 return result;
275 } catch (error) {
276 failOperation(targetKey, error, input);
277 throw error;
278 }
279 }
280​
281 function getSnapshot(target: VcsActionTarget): VcsActionState {
282 const targetKey = getVcsActionTargetKey(target);
283 if (targetKey === null) {
284 return EMPTY_VCS_ACTION_STATE;
285 }
286​
287 return config.getRegistry().get(vcsActionStateAtom(targetKey));
288 }
289​
290 async function refreshStatus(
291 target: VcsActionTarget,
292 client?: VcsActionClient,
293 options?: { readonly quiet?: boolean },
294 ): Promise<Awaited<ReturnType<VcsActionClient["refreshStatus"]>> | null> {
295 if (options?.quiet) {
296 if (target.environmentId === null || target.cwd === null) {
297 return null;
298 }
299 const resolved = client ?? config.getClient(target.environmentId);
300 return resolved ? resolved.refreshStatus({ cwd: target.cwd }) : null;
301 }
302​
303 return runOperation(target, {
304 operation: "refresh_status",
305 label: "Refreshing source control status",
306 client,
307 invalidateOnSuccess: false,
308 execute: (resolved) => resolved.refreshStatus({ cwd: target.cwd! }),
309 });
310 }
311​
312 async function pull(
313 target: VcsActionTarget,
314 client?: VcsActionClient,
315 options?: { readonly label?: string },
316 ): Promise<VcsPullResult | null> {
317 return runOperation(target, {
318 operation: "pull",
319 label: options?.label ?? "Pulling latest changes",
320 client,
321 execute: (resolved) => resolved.pull({ cwd: target.cwd! } satisfies VcsPullInput),
322 });
323 }
324​
325 async function switchRef(
326 target: VcsActionTarget,
327 input: Omit<VcsSwitchRefInput, "cwd">,
328 client?: VcsActionClient,
329 options?: { readonly label?: string },
330 ): Promise<VcsSwitchRefResult | null> {
331 return runOperation(target, {
332 operation: "switch_ref",
333 label: options?.label ?? "Switching branch",
334 client,
335 execute: (resolved) => resolved.switchRef({ cwd: target.cwd!, ...input }),
336 });
337 }
338​
339 async function createRef(
340 target: VcsActionTarget,
341 input: Omit<VcsCreateRefInput, "cwd">,
342 client?: VcsActionClient,
343 options?: { readonly label?: string },
344 ): Promise<VcsCreateRefResult | null> {
345 return runOperation(target, {
346 operation: "create_ref",
347 label: options?.label ?? "Creating branch",
348 client,
349 execute: (resolved) => resolved.createRef({ cwd: target.cwd!, ...input }),
350 });
351 }
352​
353 async function createWorktree(
354 target: VcsActionTarget,
355 input: Omit<VcsCreateWorktreeInput, "cwd">,
356 client?: VcsActionClient,
357 options?: { readonly label?: string },
358 ): Promise<VcsCreateWorktreeResult | null> {
359 return runOperation(target, {
360 operation: "create_worktree",
361 label: options?.label ?? "Creating worktree",
362 client,
363 execute: (resolved) => resolved.createWorktree({ cwd: target.cwd!, ...input }),
364 });
365 }
366​
367 async function init(
368 target: VcsActionTarget,
369 client?: VcsActionClient,
370 options?: { readonly label?: string },
371 ): Promise<Awaited<ReturnType<VcsActionClient["init"]>> | null> {
372 return runOperation(target, {
373 operation: "init",
374 label: options?.label ?? "Initializing repository",
375 client,
376 execute: (resolved) => resolved.init({ cwd: target.cwd! }),
377 });
378 }
379​
380 async function runChangeRequest(
381 target: VcsActionTarget,
382 input: Omit<GitRunStackedActionInput, "cwd" | "actionId"> & { readonly actionId?: string },
383 options?: {
384 readonly client?: VcsActionClient;
385 readonly gitStatus?: VcsStatusResult | null;
386 readonly onProgress?: (event: GitActionProgressEvent) => void;
387 },
388 ): Promise<GitRunStackedActionResult | null> {
389 const actionId =
390 input.actionId ??
391 config.getActionId?.() ??
392 `vcs-action-${nowMs()}-${++nextGeneratedActionId}`;
393 const targetKey = getVcsActionTargetKey(target);
394​
395 return runOperation(target, {
396 operation: "run_change_request",
397 label:
398 buildGitActionProgressStages({
399 action: input.action,
400 hasCustomCommitMessage: Boolean(input.commitMessage?.trim()),
401 hasWorkingTreeChanges: options?.gitStatus?.hasWorkingTreeChanges ?? false,
402 featureBranch: input.featureBranch ?? false,
403 shouldPushBeforePr:
404 input.action === "create_pr" &&
405 (!(options?.gitStatus?.hasUpstream ?? false) ||
406 (options?.gitStatus?.aheadCount ?? 0) > 0),
407 })[0] ?? "Running source control action",
408 actionId,
409 action: input.action,
410 client: options?.client,
411 execute: async (resolved) => {
412 const result = await resolved.runChangeRequest(
413 {
414 cwd: target.cwd!,
415 actionId,
416 ...input,
417 },
418 {
419 onProgress: (event) => {
420 if (targetKey !== null) {
421 const current = getSnapshot(target);
422 setState(targetKey, applyVcsActionProgressEvent(current, event));
423 }
424 options?.onProgress?.(event);
425 },
426 },
427 );
428 return result;
429 },
430 });
431 }
432​
433 function reset(target?: VcsActionTarget): void {
434 if (target) {
435 const targetKey = getVcsActionTargetKey(target);
436 if (targetKey !== null) {
437 setState(targetKey, EMPTY_VCS_ACTION_STATE);
438 }
439 return;
440 }
441​
442 for (const key of knownVcsActionKeys) {
443 setState(key, EMPTY_VCS_ACTION_STATE);
444 }
445 }
446​
447 return {
448 getSnapshot,
449 refreshStatus,
450 pull,
451 switchRef,
452 createRef,
453 createWorktree,
454 init,
455 runChangeRequest,
456 reset,
457 };