@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
tsx 231 lines 8.2 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { m } from "~/i18n/messages";
3 import { useAtomValue } from "@effect/atom-react";
4 import {
5 isAtomCommandInterrupted,
6 squashAtomCommandFailure,
7 } from "@t3tools/client-runtime/state/runtime";
8 import {
9 databaseReclaimMinutes,
10 type DatabaseStorageStatus,
11 type EnvironmentId,
12 } from "@t3tools/contracts";
13 import * as Schema from "effect/Schema";
14 import { msg, T, useGT, Var } from "gt-react";
15 import { type ReactNode, useState } from "react";
16
17 import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
18 import { useLocalStorage } from "../../hooks/useLocalStorage";
19 import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
20 import { serverEnvironment } from "../../state/server";
21 import { useAtomCommand } from "../../state/use-atom-command";
22 import {
23 AlertDialog,
24 AlertDialogClose,
25 AlertDialogDescription,
26 AlertDialogFooter,
27 AlertDialogHeader,
28 AlertDialogPopup,
29 AlertDialogTitle,
30 } from "../ui/alert-dialog";
31 import { Button } from "../ui/button";
32 import { toastManager } from "../ui/toast";
33 import { SettingsRow, SettingsSection } from "./settingsLayout";
34
35 const DismissedEnvironmentIds = Schema.Array(Schema.String);
36 const reclaimPermissionsAtom = environmentAtomList(
37 "web-database-reclaim-permissions",
38 serverEnvironment.reclaimDatabaseSpace.permissionAtom,
39 );
40
41 const formatGiB = (bytes: number) => `${(bytes / 1024 ** 3).toFixed(1)} GiB`;
42
43 /** Offers to reclaim the space on every machine whose database still holds at least 1 GiB of freed pages. */
44 export function DatabaseStorageNotice({
45 environments,
46 }: {
47 environments: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly label: string }>;
48 }) {
49 const gt = useGT();
50 const environmentIds = environments.map((environment) => environment.environmentId);
51 const recommendations = useAtomValue(
52 serverEnvironment.databaseCompactionRecommendations(JSON.stringify(environmentIds)),
53 );
54 const permissions = useAtomValue(reclaimPermissionsAtom(environmentIdsKey(environmentIds)));
55 const [dismissed, setDismissed] = useLocalStorage(
56 "database-storage-notice-dismissed",
57 [],
58 DismissedEnvironmentIds,
59 );
60 const { copyToClipboard } = useCopyToClipboard({
61 target: {
62 target: "command",
63 unavailableMessage: msg("Clipboard API is unavailable while copying command."),
64 failureMessage: msg("Failed to copy command to the clipboard."),
65 },
66 });
67 const visible = recommendations
68 .filter((recommendation) => !dismissed.includes(recommendation.environmentId))
69 .map((recommendation) => ({
70 ...recommendation,
71 label:
72 environments.find(
73 (environment) => environment.environmentId === recommendation.environmentId,
74 )?.label ?? recommendation.environmentId,
75 reclaimable:
76 recommendation.status.canReclaim === true &&
77 permissions[environmentIds.indexOf(recommendation.environmentId)] === true,
78 }));
79 if (visible.length === 0) return null;
80 return (
81 <SettingsSection id="storage-database" title={gt("Database")}>
82 <SettingsRow
83 title={gt("Reclaim freed database space")}
84 description={
85 visible.every((recommendation) => recommendation.reclaimable)
86 ? gt("These databases still hold space freed by history cleanup.")
87 : gt(
88 "These databases still hold space freed by history cleanup. Run the command on each machine to reclaim it. It restarts the background service. Quit the desktop app first if it hosts the environment.",
89 )
90 }
91 />
92 {visible.map(({ environmentId, status, label, reclaimable }) => {
93 const dismiss = (
94 <Button
95 variant="ghost"
96 size="xs"
97 onClick={() => setDismissed((current) => [...current, environmentId])}
98 >
99 <T>Dismiss</T>
100 </Button>
101 );
102 return reclaimable ? (
103 <ReclaimRow
104 key={environmentId}
105 environmentId={environmentId}
106 label={label}
107 status={status}
108 dismiss={dismiss}
109 />
110 ) : (
111 <SettingsRow
112 key={environmentId}
113 title={gt("{amount} on {environment}", {
114 amount: formatGiB(status.reclaimableBytes),
115 environment: label,
116 })}
117 description={<code className="select-text break-all">{status.compactCommand}</code>}
118 control={
119 <div className="flex flex-wrap items-center gap-1.5">
120 <Button
121 variant="outline"
122 size="xs"
123 onClick={() => copyToClipboard(status.compactCommand, undefined)}
124 >
125 <T>Copy command</T>
126 </Button>
127 {dismiss}
128 </div>
129 }
130 />
131 );
132 })}
133 </SettingsSection>
134 );
135 }
136
137 function ReclaimRow({
138 environmentId,
139 label,
140 status,
141 dismiss,
142 }: {
143 readonly environmentId: EnvironmentId;
144 readonly label: string;
145 readonly status: DatabaseStorageStatus;
146 readonly dismiss: ReactNode;
147 }) {
148 const gt = useGT();
149 const reclaim = useAtomCommand(serverEnvironment.reclaimDatabaseSpace);
150 const [confirming, setConfirming] = useState(false);
151 const [requested, setRequested] = useState(false);
152 // A failed repair reports back after the restart, which ends the wait.
153 const restarting = requested && status.reclaimFailure === undefined;
154 const minutes = databaseReclaimMinutes(status);
155 const amount = formatGiB(status.reclaimableBytes);
156 const start = async () => {
157 setConfirming(false);
158 setRequested(true);
159 const result = await reclaim({ environmentId, input: {} });
160 if (result._tag === "Success") {
161 toastManager.add({
162 type: "success",
163 title: gt("Reclaiming {amount} on {environment}", { amount, environment: label }),
164 description: gt("T3 Code there restarts and is back in about {minutes} min.", {
165 minutes,
166 }),
167 });
168 return;
169 }
170 setRequested(false);
171 if (isAtomCommandInterrupted(result)) return;
172 const error = squashAtomCommandFailure(result);
173 toastManager.add({
174 type: "error",
175 title: gt("Could not reclaim space on {environment}", { environment: label }),
176 description:
177 error instanceof Error
178 ? (thrownErrorMessage(error, m) ?? error.message)
179 : gt("An error occurred."),
180 });
181 };
182 return (
183 <SettingsRow
184 title={gt("{amount} on {environment}", { amount, environment: label })}
185 description={
186 status.reclaimFailure === undefined
187 ? gt("Restarts T3 Code there. It will be offline for about {minutes} min.", { minutes })
188 : gt("The last attempt failed: {reason}", { reason: status.reclaimFailure })
189 }
190 control={
191 <div className="flex flex-wrap items-center gap-1.5">
192 <Button
193 variant="outline"
194 size="xs"
195 disabled={restarting}
196 onClick={() => setConfirming(true)}
197 >
198 {restarting ? gt("Restarting…") : gt("Reclaim")}
199 </Button>
200 {dismiss}
201 <AlertDialog open={confirming} onOpenChange={setConfirming}>
202 <AlertDialogPopup>
203 <AlertDialogHeader>
204 <AlertDialogTitle>
205 <T>
206 Reclaim <Var>{amount}</Var> on <Var>{label}</Var>?
207 </T>
208 </AlertDialogTitle>
209 <AlertDialogDescription>
210 <T>
211 T3 Code on <Var>{label}</Var> stops, rebuilds its database, and starts again. It
212 will be offline for about <Var>{minutes}</Var> min. Running agents stop when it
213 restarts.
214 </T>
215 </AlertDialogDescription>
216 </AlertDialogHeader>
217 <AlertDialogFooter>
218 <AlertDialogClose render={<Button variant="outline" />}>
219 <T>Cancel</T>
220 </AlertDialogClose>
221 <Button onClick={() => void start()}>
222 <T>Restart and reclaim</T>
223 </Button>
224 </AlertDialogFooter>
225 </AlertDialogPopup>
226 </AlertDialog>
227 </div>
228 }
229 />
230 );
231 }