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

ProposedPlanCard.tsx

368 lines11.7 KB

1import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "@t3tools/shared/proposedPlanText";
2import { msg, T, useGT, useMessages, Var } from "gt-react";
3import { memo, useState, useId, type ComponentProps } from "react";
4import { AssistantCitationSource } from "./AssistantCitationSource";
5import { findRevealRef } from "./markdownFindContext";
6import {
7 isAtomCommandInterrupted,
8 squashAtomCommandFailure,
9} from "@t3tools/client-runtime/state/runtime";
10import {
11 AuthFilesystemWriteScope,
12 type EnvironmentId,
13 type ScopedThreadRef,
14} from "@t3tools/contracts";
15import {
16 buildCollapsedProposedPlanPreviewMarkdown,
17 buildProposedPlanMarkdownFilename,
18 downloadPlanAsTextFile,
19 normalizePlanMarkdownForExport,
20} from "../../proposedPlan";
21import ChatMarkdown from "../ChatMarkdown";
22import { EllipsisIcon } from "lucide-react";
23import { Button } from "../ui/button";
24import { Input } from "../ui/input";
25import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
26import { cn } from "~/lib/utils";
27import { Badge } from "../ui/badge";
28import {
29 Dialog,
30 DialogDescription,
31 DialogFooter,
32 DialogHeader,
33 DialogPanel,
34 DialogPopup,
35 DialogTitle,
36} from "../ui/dialog";
37import { stackedThreadToast, toastManager } from "../ui/toast";
38import { projectEnvironment } from "~/state/projects";
39import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
40import { useAtomCommand } from "~/state/use-atom-command";
41import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
42​
43export const ProposedPlanCard = memo(function ProposedPlanCard({
44 planMarkdown,
45 environmentId,
46 threadRef,
47 cwd,
48 workspaceRoot,
49 findActive = false,
50 citationSource,
51}: {
52 planMarkdown: string;
53 environmentId: EnvironmentId;
54 threadRef?: ScopedThreadRef | undefined;
55 cwd: string | undefined;
56 workspaceRoot: string | undefined;
57 findActive?: boolean;
58 citationSource?: Omit<ComponentProps<typeof AssistantCitationSource>, "children">;
59}) {
60 const gt = useGT();
61 const messages = useMessages();
62 const [expanded, setExpanded] = useState(false);
63 const expandKey =
64 citationSource?.request?.citation.messageId === citationSource?.messageId
65 ? (citationSource?.request?.key ?? null)
66 : null;
67 // A row remounted after its jump landed must not reopen a plan the user collapsed.
68 const [lastExpandKey, setLastExpandKey] = useState<string | null>(() =>
69 citationSource?.request?.activationRef.current.scrolled ? expandKey : null,
70 );
71 if (expandKey !== lastExpandKey) {
72 setLastExpandKey(expandKey);
73 if (expandKey !== null) setExpanded(true);
74 }
75 const canWriteFiles = useEnvironmentScope(environmentId, AuthFilesystemWriteScope);
76 const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
77 const [lastSavePath, setLastSavePath] = useState("");
78 const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
79 const writeProjectFile = useAtomCommand(projectEnvironment.writeFile, {
80 reportFailure: false,
81 });
82 const { copyToClipboard, isCopied } = useCopyToClipboard({
83 target: {
84 target: "plan",
85 unavailableMessage: msg("Clipboard API is unavailable while copying plan."),
86 failureMessage: msg("Failed to copy plan to the clipboard."),
87 },
88 onError: (error) => {
89 toastManager.add(
90 stackedThreadToast({
91 type: "error",
92 title: gt`Could not copy plan`,
93 description:
94 error instanceof Error ? error.message : gt`An error occurred while copying.`,
95 }),
96 );
97 },
98 });
99 const title = proposedPlanTitle(planMarkdown) ?? gt`Proposed plan`;
100 const lineCount = planMarkdown.split("\n").length;
101 const canCollapse = planMarkdown.length > 900 || lineCount > 20;
102 const displayedPlanMarkdown = stripDisplayedPlanMarkdown(planMarkdown);
103 const collapsedPreview = canCollapse
104 ? buildCollapsedProposedPlanPreviewMarkdown(planMarkdown, { maxLines: 10 }, messages)
105 : null;
106 const isCollapsed = canCollapse && !expanded;
107 // Mount clipped plans during find to count hidden matches without revealing them.
108 const showPreview = isCollapsed && !findActive;
109 const revealRef = findRevealRef(() => setExpanded(true));
110 const downloadFilename = buildProposedPlanMarkdownFilename(planMarkdown);
111 const saveContents = normalizePlanMarkdownForExport(planMarkdown);
112​
113 const handleDownload = () => {
114 downloadPlanAsTextFile(downloadFilename, saveContents);
115 };
116​
117 const handleCopyPlan = () => {
118 copyToClipboard(saveContents);
119 };
120​
121 const openSaveDialog = () => {
122 if (!canWriteFiles) return;
123 if (!workspaceRoot) {
124 toastManager.add(
125 stackedThreadToast({
126 type: "error",
127 title: gt`Workspace path is unavailable`,
128 description: gt`This thread does not have a workspace path to save into.`,
129 }),
130 );
131 return;
132 }
133 setIsSaveDialogOpen(true);
134 };
135​
136 const handleSaveToWorkspace = (savePath: string) => {
137 const relativePath = savePath.trim();
138 if (!workspaceRoot || !readEnvironmentScope(environmentId, AuthFilesystemWriteScope)) {
139 return;
140 }
141 if (!relativePath) {
142 toastManager.add({
143 type: "warning",
144 title: gt`Enter a workspace path`,
145 });
146 return;
147 }
148​
149 setLastSavePath(savePath);
150 setIsSavingToWorkspace(true);
151 void (async () => {
152 const result = await writeProjectFile({
153 environmentId,
154 input: {
155 cwd: workspaceRoot,
156 relativePath,
157 contents: saveContents,
158 },
159 });
160 setIsSavingToWorkspace(false);
161 if (result._tag === "Success") {
162 setIsSaveDialogOpen(false);
163 toastManager.add({
164 type: "success",
165 title: gt`Plan saved to workspace`,
166 description: result.value.relativePath,
167 });
168 return;
169 }
170 if (!isAtomCommandInterrupted(result)) {
171 const error = squashAtomCommandFailure(result);
172 toastManager.add(
173 stackedThreadToast({
174 type: "error",
175 title: gt`Could not save plan`,
176 description:
177 error instanceof Error ? error.message : gt`An error occurred while saving.`,
178 }),
179 );
180 }
181 })();
182 };
183​
184 return (
185 <div className="rounded-2xl border border-border/80 bg-card/70 p-4 sm:p-5">
186 <div className="flex flex-wrap items-center justify-between gap-3">
187 <div className="flex min-w-0 items-center gap-2">
188 <Badge variant="secondary">{gt({ context: "badge, noun" })`Plan`}</Badge>
189 {}
190 <h3 data-thread-find-text="true" className="truncate text-sm font-medium text-foreground">
191 {title}
192 </h3>
193 </div>
194 <Menu>
195 <MenuTrigger
196 render={<Button aria-label={gt`Plan actions`} size="icon-xs" variant="outline" />}
197 >
198 <EllipsisIcon aria-hidden="true" className="size-4" />
199 </MenuTrigger>
200 <MenuPopup align="end">
201 <MenuItem onClick={handleCopyPlan}>
202 {isCopied ? gt`Copied!` : gt`Copy to clipboard`}
203 </MenuItem>
204 <MenuItem onClick={handleDownload}>
205 <T>Download as markdown</T>
206 </MenuItem>
207 <MenuItem
208 onClick={openSaveDialog}
209 disabled={!canWriteFiles || !workspaceRoot || isSavingToWorkspace}
210 >
211 <T>Save to workspace</T>
212 </MenuItem>
213 </MenuPopup>
214 </Menu>
215 </div>
216 <div className="mt-4">
217 <div
218 ref={revealRef}
219 className={cn("relative", isCollapsed && "max-h-104 overflow-hidden")}
220 data-thread-find-text="true"
221 data-thread-find-fold={isCollapsed ? "" : undefined}
222 >
223 {showPreview ? (
224 <ChatMarkdown
225 text={collapsedPreview ?? ""}
226 cwd={cwd}
227 environmentId={environmentId}
228 threadRef={threadRef}
229 isStreaming={false}
230 headingLevelOffset={3}
231 />
232 ) : citationSource ? (
233 <AssistantCitationSource {...citationSource}>
234 <ChatMarkdown
235 text={displayedPlanMarkdown}
236 cwd={cwd}
237 environmentId={environmentId}
238 threadRef={threadRef}
239 isStreaming={false}
240 headingLevelOffset={3}
241 />
242 </AssistantCitationSource>
243 ) : (
244 <ChatMarkdown
245 text={displayedPlanMarkdown}
246 cwd={cwd}
247 environmentId={environmentId}
248 threadRef={threadRef}
249 isStreaming={false}
250 headingLevelOffset={3}
251 />
252 )}
253 {isCollapsed ? (
254 <div className="pointer-events-none absolute inset-x-0 bottom-0 h-24 bg-linear-to-t from-card/95 via-card/80 to-transparent" />
255 ) : null}
256 </div>
257 {canCollapse ? (
258 <div className="mt-4 flex justify-center">
259 <Button
260 size="sm"
261 variant="outline"
262 data-scroll-anchor-ignore
263 onClick={() => setExpanded((value) => !value)}
264 >
265 {expanded ? gt`Collapse plan` : gt`Expand plan`}
266 </Button>
267 </div>
268 ) : null}
269 </div>
270​
271 <Dialog
272 open={isSaveDialogOpen}
273 onOpenChange={(open) => {
274 if (!isSavingToWorkspace) {
275 setIsSaveDialogOpen(open);
276 }
277 }}
278 >
279 <DialogPopup className="max-w-xl">
280 <SavePlanToWorkspaceForm
281 initialPath={lastSavePath || downloadFilename}
282 placeholder={downloadFilename}
283 workspaceRoot={workspaceRoot}
284 canWriteFiles={canWriteFiles}
285 saving={isSavingToWorkspace}
286 onCancel={() => setIsSaveDialogOpen(false)}
287 onSave={handleSaveToWorkspace}
288 />
289 </DialogPopup>
290 </Dialog>
291 </div>
292 );
293});
294​
295function SavePlanToWorkspaceForm({
296 initialPath,
297 placeholder,
298 workspaceRoot,
299 canWriteFiles,
300 saving,
301 onCancel,
302 onSave,
303}: {
304 initialPath: string;
305 placeholder: string;
306 workspaceRoot: string | undefined;
307 canWriteFiles: boolean;
308 saving: boolean;
309 onCancel: () => void;
310 onSave: (path: string) => void;
311}) {
312 const gt = useGT();
313 const [savePath, setSavePath] = useState(initialPath);
314 const savePathInputId = useId();
315 return (
316 <form
317 className="flex min-h-0 flex-col"
318 onSubmit={(event) => {
319 event.preventDefault();
320 if (canWriteFiles && !saving) onSave(savePath);
321 }}
322 >
323 <DialogHeader>
324 <DialogTitle>
325 <T>Save plan to workspace</T>
326 </DialogTitle>
327 <DialogDescription>
328 {workspaceRoot !== undefined ? (
329 <T>
330 Enter a path relative to{" "}
331 <code>
332 <Var>{workspaceRoot}</Var>
333 </code>
334 .
335 </T>
336 ) : (
337 <T>
338 Enter a path relative to <code>the workspace</code>.
339 </T>
340 )}
341 </DialogDescription>
342 </DialogHeader>
343 <DialogPanel>
344 <label htmlFor={savePathInputId} className="grid gap-1.5">
345 <span className="text-xs font-medium text-foreground">
346 <T>Workspace path</T>
347 </span>
348 <Input
349 id={savePathInputId}
350 value={savePath}
351 onChange={(event) => setSavePath(event.target.value)}
352 placeholder={placeholder}
353 spellCheck={false}
354 disabled={saving}
355 />
356 </label>
357 </DialogPanel>
358 <DialogFooter>
359 <Button variant="outline" size="sm" onClick={onCancel} disabled={saving}>
360 <T>Cancel</T>
361 </Button>
362 <Button type="submit" size="sm" disabled={!canWriteFiles || saving}>
363 {saving ? gt`Saving...` : gt`Save`}
364 </Button>
365 </DialogFooter>
366 </form>
367 );