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

worktreeLayoutApproval.ts

146 lines5.4 KB

1import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
2import { runAtomCommand, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import {
4 AuthFilesystemReadScope,
5 AuthTerminalOperateScope,
6 type EnvironmentId,
7 type ProjectId,
8 type WorktreeLayoutCommand,
9} from "@t3tools/contracts";
10import { msg } from "gt-react";
11​
12import { m } from "./i18n/messages";
13import { appAtomRegistry } from "./rpc/atomRegistry";
14import { filesystemEnvironment } from "./state/filesystem";
15import { environmentPresentations } from "./state/presentation";
16import { readEnvironmentScope } from "./state/session";
17​
18export interface WorktreeLayoutApprovalRequest {
19 /** Names this request, so an answer reaches only the request whose commands were on screen. */
20 readonly id: number;
21 readonly projectTitle: string;
22 /** The commands that need approval, with the exact text that will be approved. */
23 readonly commands: ReadonlyArray<WorktreeLayoutCommand>;
25​
26/** `open` goes false on an answer while `request` stays, so the closing dialog keeps its text. */
27export interface WorktreeLayoutApprovalState {
28 readonly request: WorktreeLayoutApprovalRequest | null;
29 readonly open: boolean;
31​
32let state: WorktreeLayoutApprovalState = { request: null, open: false };
33let resolvePending: ((approved: boolean) => void) | null = null;
34let lastRequestId = 0;
35const listeners = new Set<() => void>();
36​
37function publish(next: WorktreeLayoutApprovalState): void {
38 state = next;
39 for (const listener of listeners) listener();
41​
42export function readWorktreeLayoutApprovalState(): WorktreeLayoutApprovalState {
43 return state;
45​
46/** Only the dialog host subscribes; when it unmounts, an open question resolves as declined. */
47export function subscribeWorktreeLayoutApprovalHost(listener: () => void): () => void {
48 listeners.add(listener);
49 return () => {
50 if (!listeners.delete(listener) || listeners.size > 0) return;
51 if (state.request !== null) respondToWorktreeLayoutApproval(state.request.id, false);
52 };
54​
55/** Answers the request `requestId` names. An answer to one that was since replaced is dropped. */
56export function respondToWorktreeLayoutApproval(requestId: number, approved: boolean): void {
57 if (state.request?.id !== requestId) return;
58 const resolve = resolvePending;
59 resolvePending = null;
60 if (state.open) publish({ ...state, open: false });
61 resolve?.(approved);
63​
64function requestWorktreeLayoutApproval(
65 input: Omit<WorktreeLayoutApprovalRequest, "id">,
66): Promise<boolean> {
67 // No host to show the commands means nobody saw them.
68 if (listeners.size === 0) return Promise.resolve(false);
69 resolvePending?.(false);
70 const request = { ...input, id: ++lastRequestId };
71 return new Promise((resolve) => {
72 resolvePending = resolve;
73 publish({ request, open: true });
74 });
76​
77export type WorktreeLayoutApprovalOutcome =
78 /** Nothing is left to ask here; the server decides. */
79 | { readonly status: "proceed" }
80 | { readonly status: "cancelled" }
81 | { readonly status: "blocked"; readonly message: string };
82​
83/**
84 * Before a worktree thread starts: when the project's layout commands are not approved as
85 * written, shows them and records the user's approval. The server refuses unapproved commands
86 * either way, so a read that fails here lets the send go on to that answer.
87 */
88export async function ensureWorktreeLayoutApproved(input: {
89 readonly environmentId: EnvironmentId;
90 readonly projectId: ProjectId;
91 readonly projectTitle: string;
92}): Promise<WorktreeLayoutApprovalOutcome> {
93 const { environmentId, projectId } = input;
94 if (!readEnvironmentScope(environmentId, AuthFilesystemReadScope)) return { status: "proceed" };
95 const read = await runAtomCommand(
96 appAtomRegistry,
97 filesystemEnvironment.readLayoutCommands,
98 { environmentId, input: { projectId } },
99 { reportFailure: false, reportDefect: false },
100 );
101 if (read._tag !== "Success") return { status: "proceed" };
102 const commands = read.value.commands.filter((command) => !command.approved);
103 if (commands.length === 0) return { status: "proceed" };
104 // An approval would change nothing; the server's refusal names the policy.
105 const policy = appAtomRegistry
106 .get(environmentPresentations.serverConfigsAtom)
107 .get(environmentId)?.managedPolicy;
108 if (managedCapabilityDenial(policy, "worktreeLayoutCommands", m) !== undefined)
109 return { status: "proceed" };
110 if (!readEnvironmentScope(environmentId, AuthTerminalOperateScope)) {
111 return {
112 status: "blocked",
113 message: m(
114 msg(
115 "This project sets up worktrees with its own command, which nobody has approved as it is written now. This connection cannot approve it: approve it from a client that can use the terminal.",
116 ),
117 ),
118 };
119 }
120 if (!(await requestWorktreeLayoutApproval({ projectTitle: input.projectTitle, commands }))) {
121 return { status: "cancelled" };
122 }
123 const approved = await runAtomCommand(
124 appAtomRegistry,
125 filesystemEnvironment.approveLayoutCommands,
126 {
127 environmentId,
128 input: {
129 projectId,
130 approvals: commands.map(({ kind, command }) => ({ kind, command })),
131 },
132 },
133 { reportFailure: false },
134 );
135 if (approved._tag !== "Success") {
136 const error = squashAtomCommandFailure(approved);
137 return {
138 status: "blocked",
139 message:
140 error instanceof Error
141 ? error.message
142 : m(msg("Could not approve the worktree layout command.")),
143 };
144 }
145 return { status: "proceed" };