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

ProjectWorktreeLayoutSettings.tsx

194 lines7.1 KB

1import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels";
2import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
3import {
4 AuthTerminalOperateScope,
5 type WorktreeLayoutCommand,
6 type WorktreeLayoutCommandKind,
7} from "@t3tools/contracts";
8import { msg, T, useGT, useMessages } from "gt-react";
9import { useState } from "react";
10​
11import type { SidebarProjectGroupMember } from "../../sidebarProjectGrouping";
12import { useEnvironments } from "../../state/environments";
13import { filesystemEnvironment, useFilesystemReadAccess } from "../../state/filesystem";
14import { useManagedPolicy } from "../../state/managedPolicy";
15import { useEnvironmentQuery } from "../../state/query";
16import { useEnvironmentScope } from "../../state/session";
17import { useAtomCommand } from "../../state/use-atom-command";
18import { Badge } from "../ui/badge";
19import { Button } from "../ui/button";
20import { toastManager } from "../ui/toast";
21import { WORKTREE_LAYOUT_COMMAND_LABELS } from "../WorktreeLayoutApprovalDialogHost";
22import { SettingsRow, SettingsSection } from "./settingsLayout";
23​
24const COMMAND_TITLES: Record<WorktreeLayoutCommandKind, string> = {
25 create: msg("Create command"),
26 remove: msg("Remove command"),
27};
28​
29/** The `worktreeLayout` commands each checkout's `t3.json` declares, and whether they may run. */
30export function ProjectWorktreeLayoutSettings({
31 members,
32}: {
33 members: ReadonlyArray<SidebarProjectGroupMember>;
34}) {
35 const checkouts = members.filter((member) => !member.isScratch);
36 return checkouts.map((member) => (
37 <CheckoutWorktreeLayout
38 key={member.physicalProjectKey}
39 member={member}
40 showCheckout={checkouts.length > 1}
41 />
42 ));
44​
45function CheckoutWorktreeLayout({
46 member,
47 showCheckout,
48}: {
49 member: SidebarProjectGroupMember;
50 showCheckout: boolean;
51}) {
52 const gt = useGT();
53 const m = useMessages();
54 const environmentId = member.environmentId;
55 const { environments } = useEnvironments();
56 const isConnected =
57 environments.find((entry) => entry.environmentId === environmentId)?.connection.phase ===
58 "connected";
59 const access = useFilesystemReadAccess(environmentId);
60 const canApprove = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
61 const policyDenial = managedCapabilityDenial(
62 useManagedPolicy(environmentId),
63 "worktreeLayoutCommands",
64 m,
65 );
66 const query = useEnvironmentQuery(
67 access.canReadFiles
68 ? filesystemEnvironment.layoutCommands({ environmentId, input: { projectId: member.id } })
69 : null,
70 );
71 const approve = useAtomCommand(filesystemEnvironment.approveLayoutCommands, {
72 reportFailure: false,
73 });
74 const [savingKind, setSavingKind] = useState<WorktreeLayoutCommandKind | null>(null);
75 const commands = query.data?.commands ?? [];
76 // A failed first read is not a project without commands.
77 if (query.data === null && query.error !== null) {
78 return (
79 <SettingsSection id="project-worktree-layout" title={gt("Worktree layout")}>
80 <SettingsRow
81 title={gt("Could not load the worktree layout commands")}
82 description={query.error}
83 control={
84 <Button size="xs" variant="outline" onClick={query.refresh}>
85 <T>Retry</T>
86 </Button>
87 }
88 />
89 </SettingsSection>
90 );
91 }
92 // Most projects declare none, and then there is nothing to show.
93 if (commands.length === 0) return null;
94​
95 // Approving sends the text on screen, so a file that changed since is not approved unseen.
96 const save = async (command: WorktreeLayoutCommand, approved: boolean) => {
97 setSavingKind(command.kind);
98 const result = await approve({
99 environmentId,
100 input: {
101 projectId: member.id,
102 approvals: [{ kind: command.kind, command: approved ? command.command : null }],
103 },
104 });
105 setSavingKind(null);
106 if (result._tag === "Failure") {
107 const error = squashAtomCommandFailure(result);
108 toastManager.add({
109 type: "error",
110 title: approved ? gt("Could not approve the command") : gt("Could not revoke the approval"),
111 ...(error instanceof Error ? { description: error.message } : {}),
112 });
113 }
114 query.refresh();
115 };
116​
117 return (
118 <SettingsSection id="project-worktree-layout" title={gt("Worktree layout")}>
119 <p className="px-3 py-2.5 text-xs text-muted-foreground sm:px-4">
120 {policyDenial ?? (
121 <T>
122 This project's <code>t3.json</code> sets up worktree threads with its own commands. They
123 run on this environment's machine with your permissions, and only as approved here: a
124 command whose text changes needs approval again.
125 </T>
126 )}
127 {showCheckout ? (
128 <span className="mt-1 block truncate">
129 {member.environmentLabel ?? gt("Environment")} · {member.workspaceRoot}
130 </span>
131 ) : null}
132 </p>
133 {commands.map((command) => (
134 <SettingsRow
135 key={command.kind}
136 title={
137 <span className="flex min-w-0 items-center gap-2">
138 <span className="min-w-0 truncate">{m(COMMAND_TITLES[command.kind])}</span>
139 {policyDenial !== undefined ? (
140 <Badge size="sm" variant="outline">
141 <T>Off</T>
142 </Badge>
143 ) : command.approved ? (
144 <Badge size="sm" variant="success">
145 <T>Approved</T>
146 </Badge>
147 ) : (
148 <Badge size="sm" variant="warning">
149 <T>Needs approval</T>
150 </Badge>
151 )}
152 </span>
153 }
154 description={m(WORKTREE_LAYOUT_COMMAND_LABELS[command.kind])}
155 control={
156 <Button
157 size="xs"
158 variant={command.approved ? "ghost" : "outline"}
159 disabled={
160 !canApprove ||
161 !isConnected ||
162 savingKind !== null ||
163 query.isPending ||
164 (!command.approved && policyDenial !== undefined)
165 }
166 aria-label={
167 command.approved
168 ? gt("Revoke approval of the {kind} command", { kind: command.kind })
169 : gt("Approve the {kind} command", { kind: command.kind })
170 }
171 onClick={() => void save(command, !command.approved)}
172 >
173 {command.approved ? <T>Revoke</T> : <T>Approve</T>}
174 </Button>
175 }
176 >
177 <pre className="mb-2 max-h-48 overflow-auto whitespace-pre-wrap wrap-anywhere rounded-md border bg-muted/40 px-3 py-2 font-mono text-xs">
178 {command.command}
179 </pre>
180 </SettingsRow>
181 ))}
182 {!canApprove ? (
183 <p className="px-3 py-2 text-xs text-muted-foreground sm:px-4">
184 <T>This connection cannot approve commands. Use a client that can use the terminal.</T>
185 </p>
186 ) : null}
187 {query.error ? (
188 <p role="alert" className="px-3 py-2 text-xs text-warning-foreground sm:px-4">
189 {query.error}
190 </p>
191 ) : null}
192 </SettingsSection>
193 );