@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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