feat: add agent-authored code walkthroughs (#1647)

* feat: add code-walkthrough backend (MCP tool, service, persistence, WS events)

* feat: render agent code walkthroughs as line-anchored cards + editor window

* test: add code-walkthrough re-emit mock-agent scenario

* fix: rework code-walkthrough UX (floating card, line reveal, minimize, clickable file)

* fix: improve code walkthrough editor UX

* fix: backfill walkthrough launcher after websocket connect

* fix: improve walkthrough requests and editor anchors

* fix: clear walkthrough highlights on close

* feat: add walkthrough discard and prompt customization

* fix: send walkthrough requests through saved prompt

* fix: support postgres built-in prompt seeding

* fix: address walkthrough review feedback

* fix: address walkthrough review follow-ups

* fix: harden walkthrough lifecycle races

* fix: reuse walkthrough notification cleanup

* fix: guard stale walkthrough file opens

* fix: abort stale file opens before paint

* fix: stabilize github settings e2e readiness

* fix: use stable github settings e2e selector
This commit is contained in:
José Almeida
2026-07-10 08:34:57 +01:00
committed by GitHub
parent 4eae00964d
commit 3e237e177a
124 changed files with 6485 additions and 430 deletions
+35 -2
View File
@@ -123,6 +123,32 @@ function NoDiffPlaceholder({ className }: { className?: string }) {
);
}
function useScrollWalkthroughRangeIntoView(
wrapperRef: React.RefObject<HTMLDivElement | null>,
selectedLines: ReturnType<typeof useDiffViewerState>["walkthroughSelectedLines"],
filePath: string,
) {
useEffect(() => {
if (!selectedLines) return;
let innerFrame: number | null = null;
const frame = requestAnimationFrame(() => {
innerFrame = requestAnimationFrame(() => {
const container = wrapperRef.current?.querySelector("diffs-container");
const shadow = container?.shadowRoot;
const selected = shadow?.querySelector<HTMLElement>(
'[data-selected-line="first"], [data-selected-line="single"], [data-selected-line]',
);
const fallback = shadow?.querySelector<HTMLElement>(`[data-line="${selectedLines.start}"]`);
(selected ?? fallback)?.scrollIntoView({ block: "center", behavior: "smooth" });
});
});
return () => {
cancelAnimationFrame(frame);
if (innerFrame !== null) cancelAnimationFrame(innerFrame);
};
}, [wrapperRef, selectedLines, filePath]);
}
type WiringArgs = {
data: FileDiffData;
state: ReturnType<typeof useDiffViewerState>;
@@ -239,6 +265,7 @@ export const DiffViewer = memo(function DiffViewer({
baseRef,
repo,
});
useScrollWalkthroughRangeIntoView(wrapperRef, state.walkthroughSelectedLines, data.filePath);
const { options, renderHeaderMetadata, renderHoverUtility, renderAnnotation } =
useDiffViewerWiring({
@@ -260,14 +287,20 @@ export const DiffViewer = memo(function DiffViewer({
repo,
});
const controlledSelection = state.showCommentForm ? state.selectedLines : null;
const controlledSelection = state.showCommentForm
? state.selectedLines
: state.walkthroughSelectedLines;
if (!state.fileDiffMetadata) {
return <NoDiffPlaceholder className={className} />;
}
return (
<div ref={wrapperRef} className={cn("diff-viewer", className)}>
<div
ref={wrapperRef}
className={cn("diff-viewer", className)}
data-walkthrough-active={state.walkthroughSelectedLines ? "true" : undefined}
>
<FileDiff
fileDiff={state.fileDiffMetadata}
options={options}
@@ -4,9 +4,10 @@ import type { DiffComment } from "@/lib/diff/types";
import { CommentForm } from "./comment-form";
import { CommentDisplay } from "./comment-display";
import { HunkActionBar } from "./hunk-action-bar";
import { WalkthroughStepCard } from "./walkthrough-step-card";
type AnnotationMetadata = {
type: "comment" | "new-comment-form" | "hunk-actions";
type: "comment" | "new-comment-form" | "hunk-actions" | "walkthrough-step";
comment?: DiffComment;
isEditing?: boolean;
changeBlockId?: string;
@@ -47,6 +48,10 @@ export function useAnnotationRenderer(opts: UseAnnotationRendererOpts) {
(annotation: DiffLineAnnotation<AnnotationMetadata>): ReactNode => {
const { type, comment, isEditing, changeBlockId } = annotation.metadata;
if (type === "walkthrough-step") {
return <WalkthroughStepCard key="walkthrough-step" />;
}
if (type === "hunk-actions" && changeBlockId) {
return (
<HunkActionBar
@@ -25,6 +25,8 @@ const DIFF_UNSAFE_CSS = `
--diffs-bg-deletion-number: rgb(var(--git-deletion) / 0.15) !important;
--diffs-bg-addition-emphasis: rgb(var(--git-addition) / 0.3) !important;
--diffs-bg-deletion-emphasis: rgb(var(--git-deletion) / 0.3) !important;
--diffs-bg-selection-override: color-mix(in lab, var(--background) 74%, var(--primary)) !important;
--diffs-bg-selection-number-override: color-mix(in lab, var(--background) 60%, var(--primary)) !important;
--diffs-line-height: 24px !important;
--diffs-font-size: ${FONT.size}px !important;
--diffs-font-family: ${FONT.mono} !important;
@@ -36,6 +38,9 @@ const DIFF_UNSAFE_CSS = `
min-height: 24px !important;
line-height: 24px !important;
}
[data-selected-line]:is([data-line], [data-line-annotation]) {
box-shadow: inset 2px 0 0 var(--primary) !important;
}
[data-separator='metadata'],
[data-separator]:empty {
height: 24px !important;
@@ -2,7 +2,11 @@ import { describe, it, expect } from "vitest";
import { parsePatchFiles } from "@pierre/diffs";
import type { FileDiffMetadata, DiffLineAnnotation } from "@pierre/diffs";
import { buildHunkAnnotations, type HunkOutputs } from "./use-diff-viewer-state";
import {
buildHunkAnnotations,
buildWalkthroughSelectedLines,
type HunkOutputs,
} from "./use-diff-viewer-state";
import type { RevertBlockInfo } from "./diff-viewer";
import type { AnnotationMetadata } from "./use-diff-annotation-renderer";
@@ -110,3 +114,32 @@ describe("buildHunkAnnotations", () => {
expect(out.result[0].side).toBe("additions");
});
});
describe("buildWalkthroughSelectedLines", () => {
it("returns the active walkthrough line range for a matching file", () => {
expect(
buildWalkthroughSelectedLines(
{ path: "apps/web/main.ts", repository_name: "frontend" },
{ file: "main.ts", repo: "frontend", line: 10, line_end: 12, text: "explain" },
),
).toEqual({ side: "additions", start: 10, end: 12 });
});
it("returns null for mismatched repos", () => {
expect(
buildWalkthroughSelectedLines(
{ path: "apps/web/main.ts", repository_name: "backend" },
{ file: "main.ts", repo: "frontend", line: 10, text: "explain" },
),
).toBeNull();
});
it("defaults line_end to line when the walkthrough step has no line_end", () => {
expect(
buildWalkthroughSelectedLines(
{ path: "apps/web/main.ts", repository_name: "frontend" },
{ file: "main.ts", repo: "frontend", line: 15, text: "see this" },
),
).toEqual({ side: "additions", start: 15, end: 15 });
});
});
@@ -13,6 +13,12 @@ import { useDiffMetadata } from "./use-diff-metadata";
import { useExpandableDiff } from "./use-expandable-diff";
import type { RevertBlockInfo } from "./diff-viewer";
import type { AnnotationMetadata } from "./use-diff-annotation-renderer";
import { useOptionalAppStore } from "@/components/state-provider";
import {
walkthroughStepMatchesFile,
type WalkthroughTargetFile,
} from "@/lib/diff/walkthrough-match";
import type { WalkthroughStep } from "@/lib/types/http";
type BuildAnnotationsOpts = {
comments: DiffComment[];
@@ -149,6 +155,57 @@ type UseDiffViewerStateOpts = {
repo?: string;
};
/**
* Returns a `walkthrough-step` annotation anchored to the active walkthrough
* step's line when that step targets this file, else null. Additive and gated:
* with no active walkthrough it returns null and the diff is unaffected.
*/
export function buildWalkthroughSelectedLines(
file: WalkthroughTargetFile,
step: WalkthroughStep | null | undefined,
): SelectedLineRange | null {
if (!step || !walkthroughStepMatchesFile(file, step)) return null;
return {
side: "additions",
start: step.line,
end: step.line_end ?? step.line,
};
}
function useWalkthroughSelection(
filePath: string,
repo: string | undefined,
): {
annotation: DiffLineAnnotation<AnnotationMetadata> | null;
selectedLines: SelectedLineRange | null;
} {
const activeTaskId = useOptionalAppStore((s) => s.tasks.activeTaskId, null);
const walkthrough = useOptionalAppStore(
(s) => (activeTaskId ? s.walkthroughs.byTaskId[activeTaskId] : null),
null,
);
const activeStep = useOptionalAppStore(
(s) => (activeTaskId ? (s.walkthroughs.activeStepByTaskId[activeTaskId] ?? 0) : 0),
0,
);
return useMemo(() => {
const step = walkthrough?.steps[activeStep];
const selectedLines = buildWalkthroughSelectedLines(
{ path: filePath, repository_name: repo },
step,
);
if (!selectedLines) return { annotation: null, selectedLines: null };
return {
annotation: {
side: "additions" as AnnotationSide,
lineNumber: Math.max(selectedLines.start, selectedLines.end),
metadata: { type: "walkthrough-step" as const },
},
selectedLines,
};
}, [walkthrough, activeStep, filePath, repo]);
}
function useDiffViewerAnnotations({
comments,
editingCommentId,
@@ -156,9 +213,13 @@ function useDiffViewerAnnotations({
selectedLines,
enableAcceptReject,
fileDiffMetadata,
filePath,
repo,
changeLineMapRef,
revertInfoRef,
}: BuildAnnotationsOpts & {
filePath: string;
repo?: string;
changeLineMapRef: RefObject<Map<string, string>>;
revertInfoRef: RefObject<Map<string, RevertBlockInfo>>;
}) {
@@ -182,12 +243,18 @@ function useDiffViewerAnnotations({
],
);
const walkthrough = useWalkthroughSelection(filePath, repo);
const withWalkthrough = useMemo(
() => (walkthrough.annotation ? [...annotations, walkthrough.annotation] : annotations),
[annotations, walkthrough.annotation],
);
useEffect(() => {
changeLineMapRef.current = lineMap;
revertInfoRef.current = revertMap;
}, [lineMap, revertMap, changeLineMapRef, revertInfoRef]);
return annotations;
return { annotations: withWalkthrough, walkthroughSelectedLines: walkthrough.selectedLines };
}
type CommentHandlerOpts = {
@@ -372,13 +439,15 @@ export function useDiffViewerState(opts: UseDiffViewerStateOpts) {
const changeLineMapRef = useRef<Map<string, string>>(new Map());
const hideTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const annotations = useDiffViewerAnnotations({
const { annotations, walkthroughSelectedLines } = useDiffViewerAnnotations({
comments,
editingCommentId,
showCommentForm,
selectedLines,
enableAcceptReject,
fileDiffMetadata: expansion.metadata,
filePath: data.filePath,
repo,
changeLineMapRef,
revertInfoRef,
});
@@ -405,6 +474,7 @@ export function useDiffViewerState(opts: UseDiffViewerStateOpts) {
comments,
fileDiffMetadata: expansion.metadata,
annotations,
walkthroughSelectedLines,
selectedLines,
showCommentForm,
setShowCommentForm,
@@ -0,0 +1,249 @@
"use client";
import {
useEffect,
useRef,
useState,
type PointerEvent as ReactPointerEvent,
type RefObject,
} from "react";
import { useAppStore } from "@/components/state-provider";
import { useFileEditors } from "@/hooks/use-file-editors";
import { revealFileAtLine, type OpenFileFn } from "@/lib/diff/walkthrough-reveal";
import {
clearWalkthroughEditorAnchor,
computeWalkthroughConnectorPath,
isWalkthroughAnchorTargetVisible,
useWalkthroughEditorAnchor,
type WalkthroughViewportRect,
} from "@/lib/walkthrough-editor-anchor";
import { WalkthroughStepInner, useHasActiveWalkthroughStep } from "./walkthrough-step-card";
import { cn } from "@kandev/ui/lib/utils";
const DESKTOP_QUERY = "(min-width: 640px)";
const CARD_WIDTH = 400;
const VIEWPORT_MARGIN = 16;
function viewportRectFromDomRect(rect: DOMRect): WalkthroughViewportRect {
return {
left: rect.left,
top: rect.top,
right: rect.right,
bottom: rect.bottom,
width: rect.width,
height: rect.height,
};
}
function clampPosition(pos: { x: number; y: number }, width: number, height: number) {
return {
x: Math.min(window.innerWidth - width - VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, pos.x)),
y: Math.min(window.innerHeight - height - VIEWPORT_MARGIN, Math.max(VIEWPORT_MARGIN, pos.y)),
};
}
function defaultDesktopPosition() {
return {
x: Math.max(VIEWPORT_MARGIN, window.innerWidth - CARD_WIDTH - 24),
y: 80,
};
}
function useIsDesktop() {
const [isDesktop, setIsDesktop] = useState(false);
useEffect(() => {
const media = window.matchMedia(DESKTOP_QUERY);
const update = () => setIsDesktop(media.matches);
update();
media.addEventListener("change", update);
return () => media.removeEventListener("change", update);
}, []);
return isDesktop;
}
function useDraggableWindow(cardRef: RefObject<HTMLDivElement | null>, isDesktop: boolean) {
const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
useEffect(() => {
if (!isDesktop) return;
setPosition((current) => current ?? defaultDesktopPosition());
}, [isDesktop]);
const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
if (!isDesktop) return;
const target = event.target as HTMLElement;
if (!target.closest("[data-walkthrough-drag-handle]")) return;
if (target.closest("button,input,textarea,a")) return;
const card = cardRef.current;
if (!card) return;
event.preventDefault();
card.setPointerCapture(event.pointerId);
const rect = card.getBoundingClientRect();
const offset = { x: event.clientX - rect.left, y: event.clientY - rect.top };
const onMove = (moveEvent: PointerEvent) => {
setPosition(
clampPosition(
{ x: moveEvent.clientX - offset.x, y: moveEvent.clientY - offset.y },
rect.width,
rect.height,
),
);
};
const onUp = () => {
card.releasePointerCapture(event.pointerId);
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
};
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
};
return { position, onPointerDown };
}
function useCardRect(
cardRef: RefObject<HTMLDivElement | null>,
position: { x: number; y: number } | null,
anchorKey: string | undefined,
) {
const [rect, setRect] = useState<WalkthroughViewportRect | null>(null);
useEffect(() => {
const card = cardRef.current;
if (!card) return;
const update = () => setRect(viewportRectFromDomRect(card.getBoundingClientRect()));
update();
const observer = new ResizeObserver(update);
observer.observe(card);
window.addEventListener("resize", update);
return () => {
observer.disconnect();
window.removeEventListener("resize", update);
};
}, [cardRef, position, anchorKey]);
return rect;
}
function useVisibleWalkthroughAnchor() {
const anchor = useWalkthroughEditorAnchor();
useEffect(() => {
if (!anchor?.container) return;
const check = () => {
if (!isWalkthroughAnchorTargetVisible(anchor.container ?? null, anchor.rect)) {
clearWalkthroughEditorAnchor(anchor.key);
}
};
check();
const interval = window.setInterval(check, 150);
window.addEventListener("resize", check);
window.addEventListener("scroll", check, true);
return () => {
window.clearInterval(interval);
window.removeEventListener("resize", check);
window.removeEventListener("scroll", check, true);
};
}, [anchor]);
return anchor;
}
function WalkthroughConnector({ cardRect }: { cardRect: WalkthroughViewportRect | null }) {
const anchor = useVisibleWalkthroughAnchor();
if (!anchor || !cardRect) return null;
if (anchor.container && !isWalkthroughAnchorTargetVisible(anchor.container, anchor.rect)) {
return null;
}
const path = computeWalkthroughConnectorPath(cardRect, anchor.rect);
if (!path) return null;
return (
<svg
aria-hidden="true"
data-testid="walkthrough-connector"
className="pointer-events-none fixed inset-0 z-[65] hidden h-screen w-screen sm:block"
>
<path
d={path}
fill="none"
stroke="var(--primary)"
strokeLinecap="round"
strokeWidth="2"
opacity="0.72"
/>
<circle
cx={anchor.rect.right}
cy={anchor.rect.top + anchor.rect.height / 2}
r="4"
fill="var(--primary)"
/>
</svg>
);
}
/**
* The primary walkthrough surface: a floating card that, for each step, opens the
* step's file in its *current state* and reveals/centers the anchored line in the
* editor. Works uniformly for changed and unchanged files (onboarding / whole-repo
* tours), so it does not depend on the file being part of a diff.
*/
export function WalkthroughFloatingWindow({
onClose,
onSelectFile,
}: {
onClose: () => void;
onSelectFile?: OpenFileFn;
}) {
const hasStep = useHasActiveWalkthroughStep();
const { openFile: defaultOpenFile } = useFileEditors();
const openFile = onSelectFile ?? defaultOpenFile;
const cardRef = useRef<HTMLDivElement>(null);
const isDesktop = useIsDesktop();
const { position, onPointerDown } = useDraggableWindow(cardRef, isDesktop);
const anchor = useWalkthroughEditorAnchor();
const cardRect = useCardRect(cardRef, position, anchor?.key);
// Select primitives (not a fresh object) so the selector stays referentially
// stable — returning a new object here would loop the store subscription.
const stepFile = useAppStore((s) => {
const taskId = s.tasks.activeTaskId;
if (!taskId) return null;
const wt = s.walkthroughs.byTaskId[taskId];
const idx = s.walkthroughs.activeStepByTaskId[taskId] ?? 0;
return wt?.steps[idx]?.file ?? null;
});
const stepLine = useAppStore((s) => {
const taskId = s.tasks.activeTaskId;
if (!taskId) return 0;
const wt = s.walkthroughs.byTaskId[taskId];
const idx = s.walkthroughs.activeStepByTaskId[taskId] ?? 0;
return wt?.steps[idx]?.line ?? 0;
});
const stepRepo = useAppStore((s) => {
const taskId = s.tasks.activeTaskId;
if (!taskId) return undefined;
const wt = s.walkthroughs.byTaskId[taskId];
const idx = s.walkthroughs.activeStepByTaskId[taskId] ?? 0;
return wt?.steps[idx]?.repo;
});
// Open the step's file (current state) and reveal its line whenever the step changes.
useEffect(() => {
if (stepFile) revealFileAtLine(openFile, stepFile, stepLine, stepRepo);
}, [stepFile, stepLine, stepRepo, openFile]);
if (!hasStep) return null;
return (
<>
{isDesktop ? <WalkthroughConnector cardRect={cardRect} /> : null}
<div
ref={cardRef}
data-testid="walkthrough-floating"
data-mobile-variant="bottom-sheet"
className={cn(
"fixed inset-x-2 bottom-2 z-[70] max-h-[calc(100dvh-1rem)] overflow-y-auto rounded-xl",
"sm:inset-x-auto sm:bottom-auto sm:w-[400px] sm:max-w-[calc(100vw-2rem)]",
)}
style={isDesktop && position ? { left: position.x, top: position.y } : undefined}
onPointerDown={onPointerDown}
>
<WalkthroughStepInner onClose={onClose} onSelectFile={openFile} />
</div>
</>
);
}
@@ -0,0 +1,11 @@
import { describe, expect, it } from "vitest";
import { WALKTHROUGH_STEP_BODY_CLASS } from "./walkthrough-step-card";
describe("walkthrough step card", () => {
it("keeps walkthrough description text left-aligned", () => {
expect(WALKTHROUGH_STEP_BODY_CLASS).toContain("text-left");
expect(WALKTHROUGH_STEP_BODY_CLASS).toContain("[text-align:left]");
expect(WALKTHROUGH_STEP_BODY_CLASS).toContain("[&_p]:text-left");
expect(WALKTHROUGH_STEP_BODY_CLASS).toContain("[&_li]:text-left");
});
});
@@ -0,0 +1,327 @@
"use client";
import { useEffect, useState } from "react";
import ReactMarkdown from "react-markdown";
import { IconX, IconFileCode } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { useAppStore } from "@/components/state-provider";
import { useCommentsStore } from "@/lib/state/slices/comments";
import { useFileEditors } from "@/hooks/use-file-editors";
import { useRunComment } from "@/hooks/domains/comments/use-run-comment";
import { revealFileAtLine, type OpenFileFn } from "@/lib/diff/walkthrough-reveal";
import { generateUUID } from "@/lib/utils";
import { useToast } from "@/components/toast-provider";
import {
markdownComponents,
normalizeMarkdown,
remarkPlugins,
} from "@/components/shared/markdown-components";
import type { TaskWalkthrough, WalkthroughStep } from "@/lib/types/http";
import type { WalkthroughComment } from "@/lib/state/slices/comments";
import { CommentForm } from "./comment-form";
export const WALKTHROUGH_STEP_BODY_CLASS =
"prose prose-sm dark:prose-invert max-w-none text-left text-sm leading-6 [overflow-wrap:anywhere] [text-align:left] [&_li]:text-left [&_p]:my-2 [&_p]:text-left";
function StepBody({ step, onOpenFile }: { step: WalkthroughStep; onOpenFile: () => void }) {
const lineLabel = step.line_end ? `${step.line}–${step.line_end}` : `${step.line}`;
const fileName = step.file.split("/").pop() || step.file;
return (
<div className="min-h-0 flex-1 overflow-y-auto px-4 py-3">
{step.title ? (
<h4 className="text-sm font-semibold mb-1.5" data-testid="walkthrough-step-title">
{step.title}
</h4>
) : null}
<button
type="button"
onClick={onOpenFile}
title={`Open ${step.file}:${step.line}`}
data-testid="walkthrough-step-file"
className="mb-2.5 flex max-w-full cursor-pointer items-center gap-1.5 rounded-md bg-muted/60 px-2 py-1 text-xs font-medium hover:bg-muted"
>
<IconFileCode className="size-3.5 shrink-0 text-primary" />
<span className="truncate font-mono">{fileName}</span>
<span className="shrink-0 text-muted-foreground">:{lineLabel}</span>
</button>
<div className={WALKTHROUGH_STEP_BODY_CLASS} data-testid="walkthrough-step-body">
<ReactMarkdown remarkPlugins={remarkPlugins} components={markdownComponents}>
{normalizeMarkdown(step.text)}
</ReactMarkdown>
</div>
</div>
);
}
function StepHeader({
activeStep,
stepCount,
lineLabel,
onClose,
}: {
activeStep: number;
stepCount: number;
lineLabel: string;
onClose: () => void;
}) {
return (
<div
className="flex cursor-move touch-none items-center gap-2 border-b border-border px-3 pt-2 pb-1.5"
data-testid="walkthrough-drag-handle"
data-walkthrough-drag-handle
>
<Badge variant="secondary" data-testid="walkthrough-badge">
Walkthrough
</Badge>
<span className="text-xs text-muted-foreground" data-testid="walkthrough-step-header">
Step {activeStep + 1} / {stepCount} · {lineLabel}
</span>
<Button
variant="ghost"
size="icon"
className="ml-auto size-6 cursor-pointer"
aria-label="Close walkthrough"
data-testid="walkthrough-close"
onClick={onClose}
>
<IconX className="size-4" />
</Button>
</div>
);
}
function StepNavigation({
activeStep,
stepCount,
onPrevious,
onNext,
}: {
activeStep: number;
stepCount: number;
onPrevious: () => void;
onNext: () => void;
}) {
return (
<div className="flex items-center gap-2 px-4 py-2 border-t border-border">
<Button
variant="outline"
size="sm"
className="cursor-pointer"
disabled={activeStep <= 0}
data-testid="walkthrough-prev"
onClick={onPrevious}
>
Previous
</Button>
<Button
size="sm"
className="cursor-pointer"
disabled={activeStep >= stepCount - 1}
data-testid="walkthrough-next"
onClick={onNext}
>
Next
</Button>
</div>
);
}
/** True when the active task has a walkthrough with a valid active step. */
export function useHasActiveWalkthroughStep(): boolean {
return useAppStore((s) => {
const taskId = s.tasks.activeTaskId;
if (!taskId) return false;
const wt = s.walkthroughs.byTaskId[taskId];
const idx = s.walkthroughs.activeStepByTaskId[taskId] ?? 0;
return !!wt?.steps[idx];
});
}
function useWalkthroughStepFeedback(params: {
activeStep: number;
activeTaskId: string | null;
sessionId: string | null | undefined;
step: WalkthroughStep | undefined;
stepCount: number;
walkthrough: TaskWalkthrough | null | undefined;
}) {
const { activeStep, activeTaskId, sessionId, step, stepCount, walkthrough } = params;
const addComment = useCommentsStore((s) => s.addComment);
const { runComment } = useRunComment({ sessionId: sessionId ?? null, taskId: activeTaskId });
const { toast } = useToast();
const buildComment = (text: string): WalkthroughComment | null => {
if (!sessionId || !activeTaskId || !walkthrough || !step) return null;
return buildWalkthroughComment({
sessionId,
taskId: activeTaskId,
walkthrough,
step,
activeStep,
stepCount,
text,
});
};
const showMissingSessionError = () => {
toast({ title: "No active session for walkthrough note", variant: "error" });
};
const addWalkthroughFeedback = (text: string) => {
const comment = buildComment(text);
if (!comment) {
showMissingSessionError();
return;
}
addComment(comment);
toast({ title: "Walkthrough note added", variant: "success" });
};
const runWalkthroughFeedback = (text: string) => {
const comment = buildComment(text);
if (!comment) {
showMissingSessionError();
return;
}
addComment(comment);
void runComment(comment)
.then(({ queued }) => {
toast({
title: queued ? "Walkthrough note queued" : "Walkthrough note sent",
variant: "success",
});
})
.catch(() => {
toast({ title: "Failed to send walkthrough note", variant: "error" });
});
};
return { addWalkthroughFeedback, runWalkthroughFeedback };
}
/**
* The shared inner card body (header, markdown, Prev/Next, ask box) used by both
* the inline diff-anchored card and the editor-mode floating window. Reads all
* state from the store; renders nothing when there is no active step. The note
* box mirrors other agent feedback surfaces: "Add" creates a pending
* walkthrough context item, and "Run" sends the same context to the agent.
*/
export function WalkthroughStepInner({
onClose,
onSelectFile,
}: {
onClose: () => void;
onSelectFile?: OpenFileFn;
}) {
const activeTaskId = useAppStore((s) => s.tasks.activeTaskId);
const sessionId = useAppStore((s) => s.tasks.activeSessionId);
const walkthrough = useAppStore((s) =>
activeTaskId ? s.walkthroughs.byTaskId[activeTaskId] : null,
);
const activeStep = useAppStore((s) =>
activeTaskId ? (s.walkthroughs.activeStepByTaskId[activeTaskId] ?? 0) : 0,
);
const setActiveStep = useAppStore((s) => s.setWalkthroughActiveStep);
const markSeen = useAppStore((s) => s.markWalkthroughSeen);
const { openFile: defaultOpenFile } = useFileEditors();
const openFile = onSelectFile ?? defaultOpenFile;
const stepCount = walkthrough?.steps.length ?? 0;
const step = walkthrough?.steps[activeStep];
const { addWalkthroughFeedback, runWalkthroughFeedback } = useWalkthroughStepFeedback({
activeStep,
activeTaskId,
sessionId,
step,
stepCount,
walkthrough,
});
useEffect(() => {
if (activeTaskId && walkthrough) markSeen(activeTaskId);
}, [activeTaskId, walkthrough, markSeen]);
if (!activeTaskId || !walkthrough) return null;
if (!step) return null;
const lineLabel = step.line_end ? `Lines ${step.line}–${step.line_end}` : `Line ${step.line}`;
return (
<div className="flex max-h-[calc(100dvh-2rem)] flex-col rounded-xl border-l-2 border-primary/60 border border-border bg-card shadow-lg sm:max-h-[min(78vh,720px)]">
<StepHeader
activeStep={activeStep}
stepCount={stepCount}
lineLabel={lineLabel}
onClose={onClose}
/>
<StepBody
step={step}
onOpenFile={() => revealFileAtLine(openFile, step.file, step.line, step.repo)}
/>
<StepNavigation
activeStep={activeStep}
stepCount={stepCount}
onPrevious={() => setActiveStep(activeTaskId, activeStep - 1)}
onNext={() => setActiveStep(activeTaskId, activeStep + 1)}
/>
<div className="px-4 pb-3 pt-1">
<CommentForm
key={`${walkthrough.id}:${activeStep}`}
onSubmit={addWalkthroughFeedback}
onSubmitAndRun={runWalkthroughFeedback}
onCancel={() => {}}
autoFocus={false}
/>
</div>
</div>
);
}
function buildWalkthroughComment(params: {
sessionId: string;
taskId: string;
walkthrough: TaskWalkthrough;
step: WalkthroughStep;
activeStep: number;
stepCount: number;
text: string;
}): WalkthroughComment {
const { sessionId, taskId, walkthrough, step, activeStep, stepCount, text } = params;
const startLine = step.line;
const endLine = step.line_end ?? step.line;
return {
id: generateUUID(),
source: "walkthrough",
sessionId,
taskId,
walkthroughId: walkthrough.id,
walkthroughTitle: walkthrough.title,
stepIndex: activeStep,
stepCount,
repo: step.repo,
filePath: step.file,
startLine: Math.min(startLine, endLine),
endLine: Math.max(startLine, endLine),
stepText: step.text,
text,
createdAt: new Date().toISOString(),
status: "pending",
};
}
/**
* Inline walkthrough popover rendered as a diff annotation, anchored directly
* beneath the step's line. A caret + left accent visually bind it to the line
* above.
*/
export function WalkthroughStepCard() {
const hasStep = useHasActiveWalkthroughStep();
const activeTaskId = useAppStore((s) => s.tasks.activeTaskId);
const activeStep = useAppStore((s) =>
activeTaskId ? (s.walkthroughs.activeStepByTaskId[activeTaskId] ?? 0) : 0,
);
const updatedAt = useAppStore((s) =>
activeTaskId ? s.walkthroughs.byTaskId[activeTaskId]?.updated_at : undefined,
);
const [dismissedKey, setDismissedKey] = useState<string | null>(null);
const stepKey = activeTaskId ? `${activeTaskId}:${updatedAt ?? ""}:${activeStep}` : "";
if (!hasStep || dismissedKey === stepKey) return null;
return (
<div className="relative my-2 ml-2 mr-2" data-testid="walkthrough-overlay">
<div className="absolute -top-1.5 left-6 size-3 rotate-45 border-l border-t border-primary/60 bg-card" />
<WalkthroughStepInner onClose={() => setDismissedKey(stepKey)} />
</div>
);
}