Open History to see the last commit
1import { memo, useCallback, useMemo, useState } from "react";
2import {
3 DndContext,
4 KeyboardSensor,
5 PointerSensor,
6 closestCenter,
7 type DragCancelEvent,
8 type DragEndEvent,
9 useSensor,
10 useSensors,
11} from "@dnd-kit/core";
12import {
13 SortableContext,
14 sortableKeyboardCoordinates,
15 useSortable,
16 verticalListSortingStrategy,
17} from "@dnd-kit/sortable";
18import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
19import { CSS } from "@dnd-kit/utilities";
20import {
21 isAtomCommandInterrupted,
22 squashAtomCommandFailure,
23} from "@v12/client-runtime/state/runtime";
24import type { EnvironmentId, ScopedThreadRef } from "@v12/contracts";
25import { type TimestampFormat } from "@v12/contracts/settings";
26import { Badge } from "./ui/badge";
27import { Button } from "./ui/button";
28import { ScrollArea } from "./ui/scroll-area";
29import ChatMarkdown from "./ChatMarkdown";
30import {
31 CheckIcon,
32 ChevronDownIcon,
33 ChevronRightIcon,
34 EllipsisIcon,
35 GripVerticalIcon,
36 LoaderIcon,
37 XIcon,
38} from "lucide-react";
39import { cn } from "~/lib/utils";
40import type { ActivePlanState } from "../session-logic";
41import type { LatestProposedPlanState } from "../session-logic";
42import { formatTimestamp } from "../timestampFormat";
43import {
44 proposedPlanTitle,
45 buildProposedPlanMarkdownFilename,
46 normalizePlanMarkdownForExport,
47 downloadPlanAsTextFile,
48 stripDisplayedPlanMarkdown,
49} from "../proposedPlan";
50import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
51import { projectEnvironment } from "~/state/projects";
52import { stackedThreadToast, toastManager } from "./ui/toast";
53import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
54import { useAtomCommand } from "~/state/use-atom-command";
55
56function stepStatusIcon(status: string): React.ReactNode {
57 if (status === "completed") {
58 return (
59 <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-success/10 text-success-foreground">
60 <CheckIcon className="size-3" />
61 </span>
62 );
63 }
64 if (status === "inProgress") {
65 return (
66 <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
67 <LoaderIcon className="size-3 animate-spin" />
68 </span>
69 );
70 }
71 return (
72 <span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border/60 bg-muted/30">
73 <span className="size-1.5 rounded-full bg-muted-foreground/30" />
74 </span>
75 );
76}
77
78interface PlanSidebarProps {
79 activePlan: ActivePlanState | null;
80 activeProposedPlan: LatestProposedPlanState | null;
81 label?: string;
82 environmentId: EnvironmentId;
83 threadRef?: ScopedThreadRef | undefined;
84 markdownCwd: string | undefined;
85 workspaceRoot: string | undefined;
86 timestampFormat: TimestampFormat;
87 mode?: "sheet" | "sidebar" | "embedded" | "popover" | "summary";
88 onToggleStep?: ((index: number) => void) | undefined;
89 onRemoveStep?: ((index: number) => void) | undefined;
90 onReorderStep?: ((fromIndex: number, toIndex: number) => void) | undefined;
91}
92
93interface SortablePlanStepRowProps {
94 readonly taskId: string;
95 readonly step: ActivePlanState["steps"][number];
96 readonly index: number;
97 readonly canReorder: boolean;
98 readonly onToggleStep: ((index: number) => void) | undefined;
99 readonly onRemoveStep: ((index: number) => void) | undefined;
100}
101
102function SortablePlanStepRow({
103 taskId,
104 step,
105 index,
106 canReorder,
107 onToggleStep,
108 onRemoveStep,
109}: SortablePlanStepRowProps) {
110 const {
111 attributes,
112 listeners,
113 setActivatorNodeRef,
114 setNodeRef,
115 transform,
116 transition,
117 isDragging,
118 } = useSortable({ id: taskId, disabled: !canReorder });
119
120 return (
121 <div
122 ref={setNodeRef}
123 style={{ transform: CSS.Translate.toString(transform), transition }}
124 className={cn(
125 "group/task flex select-none items-center gap-2 rounded-lg px-2 py-2 transition-colors duration-200",
126 step.status === "inProgress" && "bg-blue-500/5",
127 step.status === "completed" && "bg-emerald-500/5",
128 isDragging && "relative z-10 opacity-70 shadow-sm",
129 )}
130 >
131 {onToggleStep ? (
132 <button
133 type="button"
134 aria-label={
135 step.status === "completed"
136 ? `Mark task incomplete: ${step.step}`
137 : `Mark task complete: ${step.step}`
138 }
139 className="shrink-0 rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
140 onClick={() => onToggleStep(index)}
141 >
142 {stepStatusIcon(step.status)}
143 </button>
144 ) : (
145 stepStatusIcon(step.status)
146 )}
147 <p
148 className={cn(
149 "min-w-0 flex-1 text-[13px] leading-snug",
150 step.status === "completed"
151 ? "text-muted-foreground/50 line-through decoration-muted-foreground/20"
152 : step.status === "inProgress"
153 ? "text-foreground/90"
154 : "text-muted-foreground/70",
155 )}
156 >
157 {step.step}
158 </p>
159 {canReorder || onRemoveStep ? (
160 <div className="flex shrink-0 items-center opacity-0 transition-opacity group-hover/task:opacity-100 group-focus-within/task:opacity-100">
161 {canReorder ? (
162 <button
163 ref={setActivatorNodeRef}
164 type="button"
165 aria-label={`Reorder task: ${step.step}`}
166 className="inline-flex size-6 touch-none cursor-grab items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground active:cursor-grabbing focus-visible:ring-2 focus-visible:ring-ring"
167 {...attributes}
168 {...listeners}
169 >
170 <GripVerticalIcon className="size-3" />
171 </button>
172 ) : null}
173 {onRemoveStep ? (
174 <Button
175 type="button"
176 size="icon-xs"
177 variant="ghost"
178 aria-label={`Remove task: ${step.step}`}
179 onClick={() => onRemoveStep(index)}
180 >
181 <XIcon className="size-3" />
182 </Button>
183 ) : null}
184 </div>
185 ) : null}
186 </div>
187 );
188}
189
190function releasePointerDragFocus(event: DragEndEvent | DragCancelEvent): void {
191 if (typeof PointerEvent === "undefined" || !(event.activatorEvent instanceof PointerEvent)) {
192 return;
193 }
194 const focusedElement =
195 document.activeElement instanceof HTMLElement ? document.activeElement : null;
196 requestAnimationFrame(() => {
197 if (focusedElement && document.activeElement === focusedElement) {
198 focusedElement.blur();
199 }
200 });
201}
202
203const PlanSidebar = memo(function PlanSidebar({
204 activePlan,
205 activeProposedPlan,
206 label = "Plan",
207 environmentId,
208 threadRef,
209 markdownCwd,
210 workspaceRoot,
211 timestampFormat,
212 mode = "sidebar",
213 onToggleStep,
214 onRemoveStep,
215 onReorderStep,
216}: PlanSidebarProps) {
217 const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
218 const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
219 const writeProjectFile = useAtomCommand(projectEnvironment.writeFile, {
220 reportFailure: false,
221 });
222 const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "plan" });
223
224 const planMarkdown = activeProposedPlan?.planMarkdown ?? null;
225 const displayedPlanMarkdown = planMarkdown ? stripDisplayedPlanMarkdown(planMarkdown) : null;
226 const planTitle = planMarkdown ? proposedPlanTitle(planMarkdown) : null;
227 const renderedPlanSteps = useMemo(() => {
228 const occurrenceByText = new Map<string, number>();
229 return (activePlan?.steps ?? []).map((step) => {
230 const occurrence = occurrenceByText.get(step.step) ?? 0;
231 occurrenceByText.set(step.step, occurrence + 1);
232 return { key: `${step.step}\u0000${occurrence}`, step };
233 });
234 }, [activePlan?.steps]);
235 const reorderSensors = useSensors(
236 useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
237 useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
238 );
239 const handleStepDragEnd = useCallback(
240 (event: DragEndEvent) => {
241 releasePointerDragFocus(event);
242 if (!onReorderStep || !event.over || event.active.id === event.over.id) return;
243 const fromIndex = renderedPlanSteps.findIndex(({ key }) => key === event.active.id);
244 const toIndex = renderedPlanSteps.findIndex(({ key }) => key === event.over?.id);
245 if (fromIndex < 0 || toIndex < 0) return;
246 onReorderStep(fromIndex, toIndex);
247 },
248 [onReorderStep, renderedPlanSteps],
249 );
250 const handleStepDragCancel = useCallback((event: DragCancelEvent) => {
251 releasePointerDragFocus(event);
252 }, []);
253
254 const handleCopyPlan = useCallback(() => {
255 if (!planMarkdown) return;
256 copyToClipboard(planMarkdown);
257 }, [planMarkdown, copyToClipboard]);
258
259 const handleDownload = useCallback(() => {
260 if (!planMarkdown) return;
261 const filename = buildProposedPlanMarkdownFilename(planMarkdown);
262 downloadPlanAsTextFile(filename, normalizePlanMarkdownForExport(planMarkdown));
263 }, [planMarkdown]);
264
265 const handleSaveToWorkspace = useCallback(() => {
266 if (!workspaceRoot || !planMarkdown) return;
267 const filename = buildProposedPlanMarkdownFilename(planMarkdown);
268 setIsSavingToWorkspace(true);
269 void (async () => {
270 const result = await writeProjectFile({
271 environmentId,
272 input: {
273 cwd: workspaceRoot,
274 relativePath: filename,
275 contents: normalizePlanMarkdownForExport(planMarkdown),
276 },
277 });
278 setIsSavingToWorkspace(false);
279 if (result._tag === "Success") {
280 toastManager.add({
281 type: "success",
282 title: "Plan saved",
283 description: result.value.relativePath,
284 });
285 return;
286 }
287 if (!isAtomCommandInterrupted(result)) {
288 const error = squashAtomCommandFailure(result);
289 toastManager.add(
290 stackedThreadToast({
291 type: "error",
292 title: "Could not save plan",
293 description: error instanceof Error ? error.message : "An error occurred.",
294 }),
295 );
296 }
297 })();
298 }, [environmentId, planMarkdown, workspaceRoot, writeProjectFile]);
299
300 return (
301 <div
302 className={cn(
303 "flex min-h-0 flex-col bg-card/50",
304 mode === "sidebar"
305 ? "h-full w-[340px] shrink-0 border-l border-border/70"
306 : mode === "summary"
307 ? "h-auto w-full bg-transparent"
308 : "h-full w-full",
309 )}
310 >
311 {/* Header */}
312 <div
313 className={cn(
314 "flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3",
315 mode === "summary" && "hidden",
316 )}
317 >
318 <div className="flex items-center gap-2">
319 <Badge
320 variant="info"
321 size="sm"
322 className="rounded-md px-1.5 py-0 font-semibold tracking-wide uppercase"
323 >
324 {label}
325 </Badge>
326 {activePlan ? (
327 <span className="text-[11px] text-muted-foreground/60 tabular-nums">
328 {formatTimestamp(activePlan.createdAt, timestampFormat)}
329 </span>
330 ) : null}
331 </div>
332 <div className="flex items-center gap-1">
333 {planMarkdown ? (
334 <Menu>
335 <MenuTrigger
336 render={
337 <Button
338 size="icon-xs"
339 variant="ghost"
340 className="text-muted-foreground/50 hover:text-foreground/70"
341 aria-label="Plan actions"
342 />
343 }
344 >
345 <EllipsisIcon className="size-3.5" />
346 </MenuTrigger>
347 <MenuPopup align="end">
348 <MenuItem onClick={handleCopyPlan}>
349 {isCopied ? "Copied!" : "Copy to clipboard"}
350 </MenuItem>
351 <MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
352 <MenuItem
353 onClick={handleSaveToWorkspace}
354 disabled={!workspaceRoot || isSavingToWorkspace}
355 >
356 Save to workspace
357 </MenuItem>
358 </MenuPopup>
359 </Menu>
360 ) : null}
361 </div>
362 </div>
363
364 {/* Content */}
365 <ScrollArea className={mode === "summary" ? "max-h-[calc(100vh-12rem)]" : "min-h-0 flex-1"}>
366 <div className={cn("space-y-4", mode === "summary" ? "p-2.5" : "p-3")}>
367 {/* Explanation */}
368 {activePlan?.explanation ? (
369 <p className="text-[13px] leading-relaxed text-muted-foreground/80">
370 {activePlan.explanation}
371 </p>
372 ) : null}
373
374 {/* Plan Steps */}
375 {activePlan && activePlan.steps.length > 0 ? (
376 <div className="space-y-1">
377 <p className="mb-2 text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase">
378 Steps
379 </p>
380 <DndContext
381 sensors={reorderSensors}
382 collisionDetection={closestCenter}
383 modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
384 onDragEnd={handleStepDragEnd}
385 onDragCancel={handleStepDragCancel}
386 >
387 <SortableContext
388 items={renderedPlanSteps.map(({ key }) => key)}
389 strategy={verticalListSortingStrategy}
390 >
391 {renderedPlanSteps.map(({ key, step }, index) => (
392 <SortablePlanStepRow
393 key={key}
394 taskId={key}
395 step={step}
396 index={index}
397 canReorder={Boolean(onReorderStep)}
398 onToggleStep={onToggleStep}
399 onRemoveStep={onRemoveStep}
400 />
401 ))}
402 </SortableContext>
403 </DndContext>
404 </div>
405 ) : null}
406
407 {/* Proposed Plan Markdown */}
408 {planMarkdown ? (
409 <div className="space-y-2">
410 <button
411 type="button"
412 className="group flex w-full items-center gap-1.5 text-left"
413 onClick={() => setProposedPlanExpanded((v) => !v)}
414 >
415 {proposedPlanExpanded ? (
416 <ChevronDownIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
417 ) : (
418 <ChevronRightIcon className="size-3 shrink-0 text-muted-foreground/40 transition-transform" />
419 )}
420 <span className="text-[10px] font-semibold tracking-widest text-muted-foreground/40 uppercase group-hover:text-muted-foreground/60">
421 {planTitle ?? "Full Plan"}
422 </span>
423 </button>
424 {proposedPlanExpanded ? (
425 <div className="rounded-lg border border-border/50 bg-background/50 p-3">
426 <ChatMarkdown
427 text={displayedPlanMarkdown ?? ""}
428 cwd={markdownCwd}
429 threadRef={threadRef}
430 isStreaming={false}
431 />
432 </div>
433 ) : null}
434 </div>
435 ) : null}
436
437 {/* Empty state */}
438 {!activePlan && !planMarkdown ? (
439 <div className="flex flex-col items-center justify-center py-12 text-center">
440 <p className="text-[13px] text-muted-foreground/40">No active plan yet.</p>
441 <p className="mt-1 text-[11px] text-muted-foreground/30">
442 Plans will appear here when generated.
443 </p>
444 </div>
445 ) : null}
446 </div>
447 </ScrollArea>
448 </div>
449 );
450});
451
452export default PlanSidebar;
453export type { PlanSidebarProps };