From 160dba0aaffc0628a156390e5ca8ff713bcfacb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Wed, 18 Feb 2026 19:52:40 +0000 Subject: [PATCH] feat: improve comment system (#247) --- .../agentctl/server/process/manager.go | 19 +- .../agentctl/server/process/manager_test.go | 143 ++++++++++ apps/web/components/diff/comment-display.tsx | 4 +- apps/web/components/diff/diff-viewer.tsx | 2 +- .../diff/use-diff-annotation-renderer.tsx | 2 +- apps/web/components/diff/use-diff-comments.ts | 29 +- .../components/diff/use-diff-viewer-state.ts | 2 +- .../codemirror/use-codemirror-editor-state.ts | 17 +- .../editors/monaco/monaco-code-editor.tsx | 2 +- .../editors/monaco/use-diff-view-zones.ts | 2 +- .../monaco/use-diff-viewer-comments.ts | 2 +- .../editors/monaco/use-monaco-editor-state.ts | 25 +- apps/web/components/review/review-dialog.tsx | 29 +- .../chat/context-items/plan-comment-item.tsx | 2 +- .../messages/review-comments-attachment.tsx | 42 +-- .../components/task/comment-view-popover.tsx | 2 +- apps/web/components/task/plan-comments.tsx | 5 - .../components/task/task-changes-panel.tsx | 27 +- apps/web/components/task/task-chat-panel.tsx | 82 +++--- apps/web/components/task/task-plan-panel.tsx | 52 +--- .../domains/comments/use-diff-comments.ts | 54 ++++ .../domains/comments/use-pending-comments.ts | 62 ++++ .../domains/comments/use-plan-comments.ts | 80 ++++++ apps/web/hooks/use-message-handler.ts | 19 +- apps/web/lib/diff/comment-utils.ts | 7 +- apps/web/lib/diff/types.ts | 31 +- apps/web/lib/local-storage.ts | 1 + .../state/slices/comments/comments-store.ts | 156 ++++++++++ apps/web/lib/state/slices/comments/format.ts | 71 +++++ apps/web/lib/state/slices/comments/index.ts | 25 ++ .../lib/state/slices/comments/persistence.ts | 22 ++ apps/web/lib/state/slices/comments/types.ts | 88 ++++++ .../diff-comments/diff-comments-slice.ts | 267 ------------------ .../lib/state/slices/diff-comments/index.ts | 6 - apps/web/lib/state/slices/index.ts | 1 - apps/web/lib/state/slices/ui/types.ts | 8 - apps/web/lib/state/slices/ui/ui-slice.ts | 8 +- apps/web/lib/state/store.ts | 1 - apps/web/lib/types/context.ts | 5 +- 39 files changed, 870 insertions(+), 532 deletions(-) create mode 100644 apps/backend/internal/agentctl/server/process/manager_test.go delete mode 100644 apps/web/components/task/plan-comments.tsx create mode 100644 apps/web/hooks/domains/comments/use-diff-comments.ts create mode 100644 apps/web/hooks/domains/comments/use-pending-comments.ts create mode 100644 apps/web/hooks/domains/comments/use-plan-comments.ts create mode 100644 apps/web/lib/state/slices/comments/comments-store.ts create mode 100644 apps/web/lib/state/slices/comments/format.ts create mode 100644 apps/web/lib/state/slices/comments/index.ts create mode 100644 apps/web/lib/state/slices/comments/persistence.ts create mode 100644 apps/web/lib/state/slices/comments/types.ts delete mode 100644 apps/web/lib/state/slices/diff-comments/diff-comments-slice.ts delete mode 100644 apps/web/lib/state/slices/diff-comments/index.ts diff --git a/apps/backend/internal/agentctl/server/process/manager.go b/apps/backend/internal/agentctl/server/process/manager.go index 9b002d7016..18e7a6885c 100644 --- a/apps/backend/internal/agentctl/server/process/manager.go +++ b/apps/backend/internal/agentctl/server/process/manager.go @@ -228,18 +228,24 @@ func (m *Manager) Start(ctx context.Context) error { return err } - // Assemble final command and start the subprocess + // Assemble final command (does not start the process yet) if err := m.buildFinalCommand(); err != nil { m.status.Store(StatusError) return err } - // Set up stdin/stdout/stderr pipes + // Set up stdin/stdout/stderr pipes (must happen before process starts) if err := m.startProcessPipes(); err != nil { m.status.Store(StatusError) return err } + // Start the subprocess now that pipes are connected + if err := m.cmd.Start(); err != nil { + m.status.Store(StatusError) + return fmt.Errorf("failed to start agent: %w", err) + } + m.stopCh = make(chan struct{}) m.doneCh = make(chan struct{}) @@ -315,8 +321,8 @@ func (m *Manager) buildAdapterConfig() error { return nil } -// buildFinalCommand assembles the full command args, creates the exec.Cmd, and -// starts the subprocess. The process group is set so child processes can be killed together. +// buildFinalCommand assembles the full command args and creates the exec.Cmd. +// The process group is set so child processes can be killed together. func (m *Manager) buildFinalCommand() error { extraArgs := m.adapter.PrepareCommandArgs() @@ -341,15 +347,12 @@ func (m *Manager) buildFinalCommand() error { // (npx -> sh -> node -> opencode binary). setProcGroup(m.cmd) - m.logger.Info("starting agent process", + m.logger.Info("agent command prepared", zap.Strings("args", m.cfg.AgentArgs), zap.Strings("extra_args", extraArgs), zap.String("workdir", m.cfg.WorkDir), zap.Int("env_count", len(m.cfg.AgentEnv))) - if err := m.cmd.Start(); err != nil { - return fmt.Errorf("failed to start agent: %w", err) - } return nil } diff --git a/apps/backend/internal/agentctl/server/process/manager_test.go b/apps/backend/internal/agentctl/server/process/manager_test.go new file mode 100644 index 0000000000..121c6d2cbd --- /dev/null +++ b/apps/backend/internal/agentctl/server/process/manager_test.go @@ -0,0 +1,143 @@ +package process + +import ( + "context" + "io" + "os/exec" + "testing" + + "github.com/kandev/kandev/internal/agentctl/server/adapter" + "github.com/kandev/kandev/internal/agentctl/server/config" + "github.com/kandev/kandev/internal/agentctl/types" + v1 "github.com/kandev/kandev/pkg/api/v1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// stubAdapter is a minimal AgentAdapter for testing the startup sequence. +type stubAdapter struct { + connectCalled bool + updatesCh chan adapter.AgentEvent +} + +func newStubAdapter() *stubAdapter { + return &stubAdapter{updatesCh: make(chan adapter.AgentEvent, 10)} +} + +func (s *stubAdapter) PrepareEnvironment() (map[string]string, error) { return nil, nil } +func (s *stubAdapter) PrepareCommandArgs() []string { return nil } +func (s *stubAdapter) Connect(stdin io.Writer, stdout io.Reader) error { + s.connectCalled = true + return nil +} +func (s *stubAdapter) Initialize(context.Context) error { return nil } +func (s *stubAdapter) GetAgentInfo() *adapter.AgentInfo { return nil } +func (s *stubAdapter) NewSession(_ context.Context, _ []types.McpServer) (string, error) { + return "", nil +} +func (s *stubAdapter) LoadSession(context.Context, string) error { return nil } +func (s *stubAdapter) Prompt(context.Context, string, []v1.MessageAttachment) error { return nil } +func (s *stubAdapter) Cancel(context.Context) error { return nil } +func (s *stubAdapter) Updates() <-chan adapter.AgentEvent { return s.updatesCh } +func (s *stubAdapter) GetSessionID() string { return "" } +func (s *stubAdapter) GetOperationID() string { return "" } +func (s *stubAdapter) SetPermissionHandler(adapter.PermissionHandler) {} +func (s *stubAdapter) Close() error { + close(s.updatesCh) + return nil +} +func (s *stubAdapter) RequiresProcessKill() bool { return false } + +func TestStartProcessPipes_CreatesAllPipes(t *testing.T) { + m := &Manager{ + cmd: exec.Command("cat"), + } + + err := m.startProcessPipes() + require.NoError(t, err) + assert.NotNil(t, m.stdin, "stdin pipe should be created") + assert.NotNil(t, m.stdout, "stdout pipe should be created") + assert.NotNil(t, m.stderr, "stderr pipe should be created") + + // Clean up + _ = m.stdin.Close() +} + +func TestStartProcessPipes_FailsAfterProcessStarted(t *testing.T) { + // Regression test: documents the bug where cmd.Start() was called inside + // buildFinalCommand() before pipes were created. + // exec.Cmd pipes cannot be created after Start() is called. + cmd := exec.Command("sleep", "10") + require.NoError(t, cmd.Start()) + t.Cleanup(func() { _ = cmd.Process.Kill() }) + + _, err := cmd.StdinPipe() + assert.Error(t, err, "pipes cannot be created after process starts") +} + +func TestBuildFinalCommand_DoesNotStartProcess(t *testing.T) { + log := newTestLogger(t) + stub := newStubAdapter() + + m := &Manager{ + cfg: &config.InstanceConfig{ + AgentArgs: []string{"cat"}, + WorkDir: t.TempDir(), + }, + logger: log, + adapter: stub, + } + + err := m.buildFinalCommand() + require.NoError(t, err) + assert.NotNil(t, m.cmd, "cmd should be created") + assert.Nil(t, m.cmd.Process, "process should not be started yet") +} + +func TestManager_Start_PipesCreatedBeforeProcessStart(t *testing.T) { + log := newTestLogger(t) + stub := newStubAdapter() + workDir := t.TempDir() + + m := &Manager{ + cfg: &config.InstanceConfig{ + AgentArgs: []string{"cat"}, + WorkDir: workDir, + AgentEnv: []string{"PATH=/usr/bin:/bin"}, + }, + logger: log, + adapter: stub, + adapterCfg: &adapter.Config{WorkDir: workDir}, + updatesCh: make(chan adapter.AgentEvent, 100), + pendingPermissions: make(map[string]*PendingPermission), + workspaceTracker: NewWorkspaceTracker(workDir, log), + } + m.status.Store(StatusStopped) + m.exitCode.Store(-1) + + // Skip buildAdapterConfig since we already have a stub adapter. + // Call the sub-steps in the same order as Start() to verify correctness. + err := m.buildFinalCommand() + require.NoError(t, err) + assert.Nil(t, m.cmd.Process, "process must not be started after buildFinalCommand") + + err = m.startProcessPipes() + require.NoError(t, err) + assert.NotNil(t, m.stdin) + assert.NotNil(t, m.stdout) + assert.NotNil(t, m.stderr) + + // Now start the process โ€” this is the fix: Start() happens after pipes. + err = m.cmd.Start() + require.NoError(t, err) + assert.NotNil(t, m.cmd.Process, "process should be running") + + // Adapter connects after process starts. + err = stub.Connect(m.stdin, m.stdout) + require.NoError(t, err) + assert.True(t, stub.connectCalled) + + // Clean up: close stdin so cat exits, then wait. + _ = m.stdin.Close() + _ = m.cmd.Wait() +} diff --git a/apps/web/components/diff/comment-display.tsx b/apps/web/components/diff/comment-display.tsx index 33faadd35b..c5d945ee27 100644 --- a/apps/web/components/diff/comment-display.tsx +++ b/apps/web/components/diff/comment-display.tsx @@ -37,7 +37,7 @@ export function CommentDisplay({
{lineRange} ยท - {comment.annotation} + {comment.text}
{onEdit && ( @@ -111,7 +111,7 @@ export function CommentDisplay({ {/* Comment text */}

- {comment.annotation} + {comment.text}

); diff --git a/apps/web/components/diff/diff-viewer.tsx b/apps/web/components/diff/diff-viewer.tsx index a0bae124af..5535246b96 100644 --- a/apps/web/components/diff/diff-viewer.tsx +++ b/apps/web/components/diff/diff-viewer.tsx @@ -45,7 +45,7 @@ const DATA_KEYS: (keyof FileDiffData)[] = ['filePath', 'diff', 'oldContent', 'ne function areCommentsEqual(prev: DiffComment[] | undefined, next: DiffComment[] | undefined): boolean { if (prev === next) return true; if (!prev || !next || prev.length !== next.length) return false; - return prev.every((c, i) => c.id === next[i].id && c.annotation === next[i].annotation); + return prev.every((c, i) => c.id === next[i].id && c.text === next[i].text); } function arePropsEqual(prevProps: DiffViewerProps, nextProps: DiffViewerProps): boolean { diff --git a/apps/web/components/diff/use-diff-annotation-renderer.tsx b/apps/web/components/diff/use-diff-annotation-renderer.tsx index 9658499d58..8e6044d8fd 100644 --- a/apps/web/components/diff/use-diff-annotation-renderer.tsx +++ b/apps/web/components/diff/use-diff-annotation-renderer.tsx @@ -67,7 +67,7 @@ export function useAnnotationRenderer(opts: UseAnnotationRendererOpts) { return (
handleCommentUpdate(comment.id, content)} onCancel={() => setEditingComment(null)} isEditing diff --git a/apps/web/components/diff/use-diff-comments.ts b/apps/web/components/diff/use-diff-comments.ts index 6d93678bc8..8023a54f4d 100644 --- a/apps/web/components/diff/use-diff-comments.ts +++ b/apps/web/components/diff/use-diff-comments.ts @@ -3,10 +3,8 @@ import { useCallback, useMemo } from 'react'; import { toast } from 'sonner'; import type { SelectedLineRange } from '@pierre/diffs'; -import { - useDiffCommentsStore, - useFileComments, -} from '@/lib/state/slices/diff-comments'; +import { useCommentsStore } from '@/lib/state/slices/comments'; +import { useDiffFileComments } from '@/hooks/domains/comments/use-diff-comments'; import { commentsToAnnotations, extractCodeFromDiff, @@ -33,7 +31,7 @@ interface UseDiffCommentsReturn { /** Add a new comment */ addComment: ( range: SelectedLineRange, - annotation: string + text: string ) => void; /** Remove a comment */ removeComment: (commentId: string) => void; @@ -55,14 +53,14 @@ export function useDiffComments({ newContent, oldContent, }: UseDiffCommentsOptions): UseDiffCommentsReturn { - const comments = useFileComments(sessionId, filePath); - const editingCommentId = useDiffCommentsStore( + const comments = useDiffFileComments(sessionId, filePath); + const editingCommentId = useCommentsStore( (state) => state.editingCommentId ); - const storeAddComment = useDiffCommentsStore((state) => state.addComment); - const storeRemoveComment = useDiffCommentsStore((state) => state.removeComment); - const storeUpdateComment = useDiffCommentsStore((state) => state.updateComment); - const storeSetEditingComment = useDiffCommentsStore((state) => state.setEditingComment); + const storeAddComment = useCommentsStore((state) => state.addComment); + const storeRemoveComment = useCommentsStore((state) => state.removeComment); + const storeUpdateComment = useCommentsStore((state) => state.updateComment); + const storeSetEditingComment = useCommentsStore((state) => state.setEditingComment); const annotations = useMemo( () => commentsToAnnotations(comments), @@ -70,7 +68,7 @@ export function useDiffComments({ ); const addComment = useCallback( - (range: SelectedLineRange, annotation: string) => { + (range: SelectedLineRange, text: string) => { const side = (range.side || 'additions') as AnnotationSide; const startLine = Math.min(range.start, range.end); const endLine = Math.max(range.start, range.end); @@ -88,13 +86,14 @@ export function useDiffComments({ const comment: DiffComment = { id: `${filePath}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, + source: 'diff', sessionId, filePath, startLine, endLine, side, codeContent, - annotation, + text, createdAt: new Date().toISOString(), status: 'pending', }; @@ -110,9 +109,9 @@ export function useDiffComments({ const removeComment = useCallback( (commentId: string) => { - storeRemoveComment(sessionId, filePath, commentId); + storeRemoveComment(commentId); }, - [sessionId, filePath, storeRemoveComment] + [storeRemoveComment] ); const updateComment = useCallback( diff --git a/apps/web/components/diff/use-diff-viewer-state.ts b/apps/web/components/diff/use-diff-viewer-state.ts index db49ec72dd..77301cc177 100644 --- a/apps/web/components/diff/use-diff-viewer-state.ts +++ b/apps/web/components/diff/use-diff-viewer-state.ts @@ -188,7 +188,7 @@ export function useDiffViewerState(opts: UseDiffViewerStateOpts) { startLine: selectedLines.start, endLine: selectedLines.end, side: (selectedLines.side || 'additions') as DiffComment['side'], - annotation: content, + text: content, })); } else if (sessionId) { addComment(selectedLines, content); diff --git a/apps/web/components/editors/codemirror/use-codemirror-editor-state.ts b/apps/web/components/editors/codemirror/use-codemirror-editor-state.ts index ea2eb331be..0db967cbd5 100644 --- a/apps/web/components/editors/codemirror/use-codemirror-editor-state.ts +++ b/apps/web/components/editors/codemirror/use-codemirror-editor-state.ts @@ -4,7 +4,8 @@ import { EditorView, gutter, GutterMarker, ViewPlugin, type ViewUpdate } from '@ import type { Extension } from '@codemirror/state'; import { Decoration, type DecorationSet } from '@codemirror/view'; import { getCodeMirrorExtensionFromPath } from '@/lib/languages'; -import { useDiffCommentsStore, useFileComments } from '@/lib/state/slices/diff-comments/diff-comments-slice'; +import { useCommentsStore } from '@/lib/state/slices/comments'; +import { useDiffFileComments } from '@/hooks/domains/comments/use-diff-comments'; import type { DiffComment } from '@/lib/diff/types'; import { computeLineDiffStats } from '@/lib/diff'; import { useToast } from '@/components/toast-provider'; @@ -187,9 +188,9 @@ export function useCodeMirrorEditorState(opts: UseCodeMirrorEditorStateOpts) { const { toast } = useToast(); const { setOpen: setCommandPanelOpen } = useCommandPanelOpen(); - const addComment = useDiffCommentsStore((state) => state.addComment); - const removeComment = useDiffCommentsStore((state) => state.removeComment); - const comments = useFileComments(sessionId ?? '', path); + const addComment = useCommentsStore((state) => state.addComment); + const removeComment = useCommentsStore((state) => state.removeComment); + const comments = useDiffFileComments(sessionId ?? '', path); const langExt = getCodeMirrorExtensionFromPath(path); // Comment decorations plugin @@ -361,9 +362,9 @@ export function useCodeMirrorEditorState(opts: UseCodeMirrorEditorStateOpts) { if (!textSelection || !sessionId) return; const comment: DiffComment = { id: `${path}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, - sessionId, filePath: path, + source: 'diff', sessionId, filePath: path, startLine: textSelection.startLine, endLine: textSelection.endLine, - side: 'additions', codeContent: textSelection.text, annotation, + side: 'additions', codeContent: textSelection.text, text: annotation, createdAt: new Date().toISOString(), status: 'pending', }; addComment(comment); @@ -379,14 +380,14 @@ export function useCodeMirrorEditorState(opts: UseCodeMirrorEditorStateOpts) { const handleDeleteComment = useCallback((commentId: string) => { if (!sessionId) return; - removeComment(sessionId, path, commentId); + removeComment(commentId); if (commentView && commentView.comments.length <= 1) { setCommentView(null); } else if (commentView) { setCommentView({ ...commentView, comments: commentView.comments.filter(c => c.id !== commentId) }); } toast({ title: 'Comment deleted' }); - }, [sessionId, path, removeComment, commentView, toast]); + }, [sessionId, removeComment, commentView, toast]); const handleCommentViewClose = useCallback(() => { setCommentView(null); }, []); diff --git a/apps/web/components/editors/monaco/monaco-code-editor.tsx b/apps/web/components/editors/monaco/monaco-code-editor.tsx index 6017554dde..f3efae2523 100644 --- a/apps/web/components/editors/monaco/monaco-code-editor.tsx +++ b/apps/web/components/editors/monaco/monaco-code-editor.tsx @@ -84,7 +84,7 @@ export function MonacoCodeEditor({ for (const comment of state.comments) { const isEditing = state.editingCommentId === comment.id; const node = isEditing - ?
state.handleCommentUpdateRef.current(comment.id, c)} onCancel={() => state.setEditingComment(null)} isEditing />
+ ?
state.handleCommentUpdateRef.current(comment.id, c)} onCancel={() => state.setEditingComment(null)} isEditing />
:
state.handleCommentDeleteRef.current(comment.id)} onEdit={() => state.setEditingComment(comment.id)} showCode={false} compact />
; addZone(comment.endLine, isEditing ? 120 : 32, node); } diff --git a/apps/web/components/editors/monaco/use-diff-view-zones.ts b/apps/web/components/editors/monaco/use-diff-view-zones.ts index e8ab6b8d91..532240e3cd 100644 --- a/apps/web/components/editors/monaco/use-diff-view-zones.ts +++ b/apps/web/components/editors/monaco/use-diff-view-zones.ts @@ -91,7 +91,7 @@ export function useViewZones({ const node = isEditing ? createElement('div', { className: 'px-2 py-0.5' }, createElement(CommentForm, { - initialContent: comment.annotation, + initialContent: comment.text, onSubmit: (c: string) => handleCommentUpdateRef.current?.(comment.id, c), onCancel: () => setEditingComment(null), isEditing: true, diff --git a/apps/web/components/editors/monaco/use-diff-viewer-comments.ts b/apps/web/components/editors/monaco/use-diff-viewer-comments.ts index f2042a49be..789d34cf40 100644 --- a/apps/web/components/editors/monaco/use-diff-viewer-comments.ts +++ b/apps/web/components/editors/monaco/use-diff-viewer-comments.ts @@ -136,7 +136,7 @@ export function useDiffViewerComments(opts: UseDiffViewerCommentsOpts) { startLine: selectedLineRange.start, endLine: selectedLineRange.end, side: (selectedLineRange.side || 'additions') as DiffComment['side'], - annotation: content, + text: content, })); } else if (sessionId) { addComment( diff --git a/apps/web/components/editors/monaco/use-monaco-editor-state.ts b/apps/web/components/editors/monaco/use-monaco-editor-state.ts index 1edcc8b77c..adde0669fb 100644 --- a/apps/web/components/editors/monaco/use-monaco-editor-state.ts +++ b/apps/web/components/editors/monaco/use-monaco-editor-state.ts @@ -1,7 +1,8 @@ import { useCallback, useEffect, useState, useRef, type RefObject } from 'react'; import type { OnMount, OnChange } from '@monaco-editor/react'; import type { editor as monacoEditor, IDisposable } from 'monaco-editor'; -import { useDiffCommentsStore, useFileComments } from '@/lib/state/slices/diff-comments/diff-comments-slice'; +import { useCommentsStore } from '@/lib/state/slices/comments'; +import { useDiffFileComments } from '@/hooks/domains/comments/use-diff-comments'; import { buildDiffComment, useCommentedLines } from '@/lib/diff/comment-utils'; import { useToast } from '@/components/toast-provider'; import { useCommandPanelOpen } from '@/lib/commands/command-registry'; @@ -57,12 +58,12 @@ export function useMonacoEditorComments(opts: UseMonacoEditorStateOpts) { const { toast } = useToast(); const { setOpen: setCommandPanelOpen } = useCommandPanelOpen(); - const addComment = useDiffCommentsStore((state) => state.addComment); - const removeComment = useDiffCommentsStore((state) => state.removeComment); - const updateComment = useDiffCommentsStore((state) => state.updateComment); - const editingCommentId = useDiffCommentsStore((state) => state.editingCommentId); - const setEditingComment = useDiffCommentsStore((state) => state.setEditingComment); - const comments = useFileComments(sessionId ?? '', path); + const addComment = useCommentsStore((state) => state.addComment); + const removeComment = useCommentsStore((state) => state.removeComment); + const updateComment = useCommentsStore((state) => state.updateComment); + const editingCommentId = useCommentsStore((state) => state.editingCommentId); + const setEditingComment = useCommentsStore((state) => state.setEditingComment); + const comments = useDiffFileComments(sessionId ?? '', path); const commentedLines = useCommentedLines(comments); const handleGutterSelectionComplete = useCallback( @@ -111,7 +112,7 @@ export function useMonacoEditorComments(opts: UseMonacoEditorStateOpts) { if (e.target.type !== 3 && e.target.type !== 4) return; const lineNumber = e.target.position?.lineNumber; if (!lineNumber) return; - const storeState = useDiffCommentsStore.getState(); + const storeState = useCommentsStore.getState(); const fileComments = storeState.getCommentsForFile(sessionId ?? '', path); const lineComments = fileComments.filter((c) => lineNumber >= c.startLine && lineNumber <= c.endLine); if (lineComments.length > 0) { @@ -256,7 +257,7 @@ export function useMonacoEditorComments(opts: UseMonacoEditorStateOpts) { if (!formZoneRange || !sessionId) return; addComment(buildDiffComment({ filePath: path, sessionId, startLine: formZoneRange.startLine, endLine: formZoneRange.endLine, - side: 'additions', annotation, codeContent: formZoneRange.codeContent, + side: 'additions', text: annotation, codeContent: formZoneRange.codeContent, })); setFormZoneRange(null); clearGutterSelection(); const editor = editorRef.current; @@ -272,15 +273,15 @@ export function useMonacoEditorComments(opts: UseMonacoEditorStateOpts) { const handleDeleteComment = useCallback( (commentId: string) => { if (!sessionId) return; - removeComment(sessionId, path, commentId); + removeComment(commentId); toast({ title: 'Comment deleted' }); }, - [sessionId, path, removeComment, toast], + [sessionId, removeComment, toast], ); const handleUpdateComment = useCallback( (commentId: string, annotation: string) => { - updateComment(commentId, { annotation }); setEditingComment(null); + updateComment(commentId, { text: annotation }); setEditingComment(null); toast({ title: 'Comment updated' }); }, [updateComment, setEditingComment, toast], diff --git a/apps/web/components/review/review-dialog.tsx b/apps/web/components/review/review-dialog.tsx index dcb14e596a..8ee61dbbd4 100644 --- a/apps/web/components/review/review-dialog.tsx +++ b/apps/web/components/review/review-dialog.tsx @@ -4,7 +4,7 @@ import { memo, useMemo, useCallback, createRef, useState } from 'react'; import { Dialog, DialogContent, DialogTitle } from '@kandev/ui/dialog'; import type { DiffComment } from '@/lib/diff/types'; import type { FileInfo, CumulativeDiff } from '@/lib/state/slices/session-runtime/types'; -import { useDiffCommentsStore } from '@/lib/state/slices/diff-comments/diff-comments-slice'; +import { useCommentsStore, isDiffComment } from '@/lib/state/slices/comments'; import { useSessionFileReviews } from '@/hooks/use-session-file-reviews'; import { useGitOperations } from '@/hooks/use-git-operations'; import { useAppStore } from '@/components/state-provider'; @@ -62,11 +62,18 @@ function computeReviewSets(allFiles: ReviewFile[], reviews: ReturnType>, sessionId: string): Record { +function computeCommentCounts( + byId: Record, + sessionCommentIds: string[] | undefined, +): Record { const counts: Record = {}; - const sessionComments = bySession[sessionId]; - if (!sessionComments) return counts; - for (const [filePath, comments] of Object.entries(sessionComments)) { if (comments.length > 0) counts[filePath] = comments.length; } + if (!sessionCommentIds) return counts; + for (const id of sessionCommentIds) { + const comment = byId[id]; + if (comment && isDiffComment(comment)) { + counts[comment.filePath] = (counts[comment.filePath] ?? 0) + 1; + } + } return counts; } @@ -78,15 +85,19 @@ export const ReviewDialog = memo(function ReviewDialog({ const [wordWrap, setWordWrap] = useState(false); const autoMarkOnScroll = useAppStore((s) => s.userSettings.reviewAutoMarkOnScroll); const { reviews, markReviewed, markUnreviewed } = useSessionFileReviews(sessionId); - const bySession = useDiffCommentsStore((s) => s.bySession); - const getPendingComments = useDiffCommentsStore((s) => s.getPendingComments); - const markCommentsSent = useDiffCommentsStore((s) => s.markCommentsSent); + const byId = useCommentsStore((s) => s.byId); + const sessionCommentIds = useCommentsStore((s) => s.bySession[sessionId]); + const getStorePendingComments = useCommentsStore((s) => s.getPendingComments); + const getPendingComments = useCallback((): DiffComment[] => { + return getStorePendingComments().filter(isDiffComment); + }, [getStorePendingComments]); + const markCommentsSent = useCommentsStore((s) => s.markCommentsSent); const { discard } = useGitOperations(sessionId); const { toast } = useToast(); const allFiles = useMemo(() => buildAllFiles(gitStatusFiles, cumulativeDiff), [gitStatusFiles, cumulativeDiff]); const { reviewedFiles, staleFiles } = useMemo(() => computeReviewSets(allFiles, reviews), [allFiles, reviews]); - const commentCountByFile = useMemo(() => computeCommentCounts(bySession, sessionId), [bySession, sessionId]); + const commentCountByFile = useMemo(() => computeCommentCounts(byId, sessionCommentIds), [byId, sessionCommentIds]); const totalCommentCount = useMemo(() => Object.values(commentCountByFile).reduce((sum, c) => sum + c, 0), [commentCountByFile]); const fileRefs = useMemo(() => { const refs = new Map>(); for (const file of allFiles) refs.set(file.path, createRef()); return refs; }, [allFiles]); diff --git a/apps/web/components/task/chat/context-items/plan-comment-item.tsx b/apps/web/components/task/chat/context-items/plan-comment-item.tsx index 63f80bd2ec..e7af4395a6 100644 --- a/apps/web/components/task/chat/context-items/plan-comment-item.tsx +++ b/apps/web/components/task/chat/context-items/plan-comment-item.tsx @@ -14,7 +14,7 @@ export const PlanCommentItem = memo(function PlanCommentItem({ item }: { item: P “{comment.selectedText}”
)} -
{comment.comment}
+
{comment.text}
))} diff --git a/apps/web/components/task/chat/messages/review-comments-attachment.tsx b/apps/web/components/task/chat/messages/review-comments-attachment.tsx index 608afd3de1..565a49dce3 100644 --- a/apps/web/components/task/chat/messages/review-comments-attachment.tsx +++ b/apps/web/components/task/chat/messages/review-comments-attachment.tsx @@ -120,7 +120,7 @@ export function ReviewCommentsAttachment({ {/* Comment text */}

- {comment.annotation} + {comment.text}

))} @@ -134,41 +134,5 @@ export function ReviewCommentsAttachment({ ); } -/** - * Format review comments as human-readable markdown for sending to agent. - * This format is both agent-friendly and displays nicely in the chat UI. - */ -export function formatReviewCommentsAsMarkdown(comments: DiffComment[]): string { - if (!comments || comments.length === 0) { - return ''; - } - - const lines: string[] = ['### Review Comments', '']; - - // Group comments by file - const byFile = new Map(); - for (const comment of comments) { - const existing = byFile.get(comment.filePath) || []; - existing.push(comment); - byFile.set(comment.filePath, existing); - } - - for (const [filePath, fileComments] of byFile) { - for (const comment of fileComments) { - const lineRange = comment.startLine === comment.endLine - ? `${comment.startLine}` - : `${comment.startLine}-${comment.endLine}`; - - lines.push(`**${filePath}:${lineRange}**`); - lines.push('```'); - lines.push(comment.codeContent); - lines.push('```'); - lines.push(`> ${comment.annotation}`); - lines.push(''); - } - } - - lines.push('---'); - lines.push(''); - return lines.join('\n'); -} +// Re-export from unified comment system +export { formatReviewCommentsAsMarkdown } from '@/lib/state/slices/comments/format'; diff --git a/apps/web/components/task/comment-view-popover.tsx b/apps/web/components/task/comment-view-popover.tsx index da9999f6c6..55f7f8c9ba 100644 --- a/apps/web/components/task/comment-view-popover.tsx +++ b/apps/web/components/task/comment-view-popover.tsx @@ -91,7 +91,7 @@ function CommentItem({ comment, onDelete }: { comment: DiffComment; onDelete: (i {comment.codeContent} )} -

{comment.annotation}

+

{comment.text}

); } diff --git a/apps/web/components/task/plan-comments.tsx b/apps/web/components/task/plan-comments.tsx deleted file mode 100644 index 60c02885a5..0000000000 --- a/apps/web/components/task/plan-comments.tsx +++ /dev/null @@ -1,5 +0,0 @@ -export type PlanComment = { - id: string; - selectedText: string; - comment: string; -}; diff --git a/apps/web/components/task/task-changes-panel.tsx b/apps/web/components/task/task-changes-panel.tsx index a3083815aa..eedc21eade 100644 --- a/apps/web/components/task/task-changes-panel.tsx +++ b/apps/web/components/task/task-changes-panel.tsx @@ -25,10 +25,10 @@ import { useSessionGitStatus } from '@/hooks/domains/session/use-session-git-sta import { useCumulativeDiff } from '@/hooks/domains/session/use-cumulative-diff'; import { useGitOperations } from '@/hooks/use-git-operations'; import { useSessionFileReviews } from '@/hooks/use-session-file-reviews'; -import { useDiffCommentsStore } from '@/lib/state/slices/diff-comments/diff-comments-slice'; +import { useCommentsStore, isDiffComment } from '@/lib/state/slices/comments'; import { getWebSocketClient } from '@/lib/ws/connection'; import { updateUserSettings } from '@/lib/api'; -import { formatReviewCommentsAsMarkdown } from '@/components/task/chat/messages/review-comments-attachment'; +import { formatReviewCommentsAsMarkdown } from '@/lib/state/slices/comments/format'; import { ReviewDiffList } from '@/components/review/review-diff-list'; import type { ReviewFile } from '@/components/review/types'; import { hashDiff, normalizeDiffContent } from '@/components/review/types'; @@ -81,7 +81,8 @@ function useChangesData(selectedDiff: SelectedDiff | null, onClearSelected: () = const gitStatus = useSessionGitStatus(activeSessionId); const { diff: cumulativeDiff, loading: cumulativeLoading } = useCumulativeDiff(activeSessionId); const { reviews } = useSessionFileReviews(activeSessionId); - const bySession = useDiffCommentsStore((s) => s.bySession); + const byId = useCommentsStore((s) => s.byId); + const commentSessionIds = useCommentsStore((s) => activeSessionId ? s.bySession[activeSessionId] : undefined); const allFiles = useMemo(() => mergeReviewFiles(gitStatus, cumulativeDiff), [gitStatus, cumulativeDiff]); @@ -98,11 +99,14 @@ function useChangesData(selectedDiff: SelectedDiff | null, onClearSelected: () = }, [allFiles, reviews]); const totalCommentCount = useMemo(() => { - if (!activeSessionId) return 0; - const sessionComments = bySession[activeSessionId]; - if (!sessionComments) return 0; - return Object.values(sessionComments).reduce((sum, c) => sum + (c.length > 0 ? c.length : 0), 0); - }, [bySession, activeSessionId]); + if (!commentSessionIds || commentSessionIds.length === 0) return 0; + let count = 0; + for (const id of commentSessionIds) { + const comment = byId[id]; + if (comment && isDiffComment(comment)) count++; + } + return count; + }, [byId, commentSessionIds]); const fileRefs = useMemo(() => { const refs = new Map>(); @@ -131,8 +135,8 @@ function useChangesActions(activeSessionId: string | null | undefined, allFiles: const userSettings = useAppStore((state) => state.userSettings); const { discard } = useGitOperations(activeSessionId ?? null); const { markReviewed, markUnreviewed } = useSessionFileReviews(activeSessionId ?? null); - const getPendingComments = useDiffCommentsStore((s) => s.getPendingComments); - const markCommentsSent = useDiffCommentsStore((s) => s.markCommentsSent); + const getPendingComments = useCommentsStore((s) => s.getPendingComments); + const markCommentsSent = useCommentsStore((s) => s.markCommentsSent); const { toast } = useToast(); const [splitView, setSplitView] = useState(() => typeof window !== 'undefined' && localStorage.getItem('diff-view-mode') === 'split'); @@ -166,7 +170,8 @@ function useChangesActions(activeSessionId: string | null | undefined, allFiles: const handleFixComments = useCallback(() => { if (!activeSessionId || !activeTaskId) return; - const comments = getPendingComments(); + const allPending = getPendingComments(); + const comments = allPending.filter(isDiffComment); if (comments.length === 0) return; const markdown = formatReviewCommentsAsMarkdown(comments); if (!markdown) return; diff --git a/apps/web/components/task/task-chat-panel.tsx b/apps/web/components/task/task-chat-panel.tsx index 6dfe202a5c..ed73273306 100644 --- a/apps/web/components/task/task-chat-panel.tsx +++ b/apps/web/components/task/task-chat-panel.tsx @@ -21,18 +21,16 @@ import { useContextFilesStore, type ContextFile } from '@/lib/state/context-file import { VirtualizedMessageList } from '@/components/task/chat/virtualized-message-list'; import { ChatInputContainer, type ChatInputContainerHandle, type MessageAttachment } from '@/components/task/chat/chat-input-container'; import { type QueuedMessageIndicatorHandle } from '@/components/task/chat/queued-message-indicator'; -import { formatReviewCommentsAsMarkdown } from '@/components/task/chat/messages/review-comments-attachment'; -import { - useDiffCommentsStore, - usePendingCommentsByFile, -} from '@/lib/state/slices/diff-comments'; +import { formatReviewCommentsAsMarkdown } from '@/lib/state/slices/comments/format'; +import { useCommentsStore, isPlanComment } from '@/lib/state/slices/comments'; +import { usePendingDiffCommentsByFile } from '@/hooks/domains/comments/use-diff-comments'; +import { usePendingPlanComments } from '@/hooks/domains/comments/use-pending-comments'; import { getFileName } from '@/lib/utils/file-path'; import type { ContextItem } from '@/lib/types/context'; import { useIsTaskArchived } from './task-archived-context'; import type { DiffComment } from '@/lib/diff/types'; -import type { DocumentComment } from '@/lib/state/slices/ui/types'; +import type { PlanComment } from '@/lib/state/slices/comments'; -const EMPTY_COMMENTS: DocumentComment[] = []; const EMPTY_CONTEXT_FILES: ContextFile[] = []; const PLAN_CONTEXT_PATH = 'plan:context'; @@ -70,10 +68,10 @@ type BuildContextItemsParams = { onOpenFile?: (path: string) => void; pendingCommentsByFile: Record; handleRemoveCommentFile: (filePath: string) => void; - handleRemoveComment: (sid: string, filePath: string, commentId: string) => void; + handleRemoveComment: (commentId: string) => void; onOpenFileAtLine?: (filePath: string) => void; - documentComments: DocumentComment[]; - handleClearDocumentComments: () => void; + planComments: PlanComment[]; + handleClearPlanComments: () => void; taskId: string | null; }; @@ -137,7 +135,7 @@ function buildFileAndPromptItems(params: BuildContextItemsParams): ContextItem[] } function buildCommentItems(params: BuildContextItemsParams): ContextItem[] { - const { pendingCommentsByFile, resolvedSessionId: sid, handleRemoveCommentFile, handleRemoveComment, onOpenFileAtLine } = params; + const { pendingCommentsByFile, handleRemoveCommentFile, handleRemoveComment, onOpenFileAtLine } = params; const items: ContextItem[] = []; if (!pendingCommentsByFile) return items; for (const [filePath, comments] of Object.entries(pendingCommentsByFile)) { @@ -150,7 +148,7 @@ function buildCommentItems(params: BuildContextItemsParams): ContextItem[] { filePath, comments, onRemove: () => handleRemoveCommentFile(filePath), - onRemoveComment: (cid) => { if (sid) handleRemoveComment(sid, filePath, cid); }, + onRemoveComment: (cid) => handleRemoveComment(cid), onOpen: onOpenFileAtLine ? () => onOpenFileAtLine(filePath) : undefined, }); } @@ -164,13 +162,13 @@ function buildContextItems(params: BuildContextItemsParams): ContextItem[] { items.push(...buildFileAndPromptItems(params)); items.push(...buildCommentItems(params)); - if (params.documentComments.length > 0) { + if (params.planComments.length > 0) { items.push({ kind: 'plan-comment', id: 'plan-comments', - label: `${params.documentComments.length} plan comment${params.documentComments.length !== 1 ? 's' : ''}`, - comments: params.documentComments, - onRemove: params.handleClearDocumentComments, + label: `${params.planComments.length} plan comment${params.planComments.length !== 1 ? 's' : ''}`, + comments: params.planComments, + onRemove: params.handleClearPlanComments, onOpen: params.addPlan, }); } @@ -214,11 +212,24 @@ function useChatPanelState({ sessionId, onOpenFile, onOpenFileAtLine }: UseChatP const chatSubmitKey = useAppStore((state) => state.userSettings.chatSubmitKey); const agentCommands = useAppStore((state) => resolvedSessionId ? state.availableCommands.bySessionId[resolvedSessionId] : undefined); const { queuedMessage, isQueued, cancel: cancelQueue, updateContent: updateQueueContent } = useQueue(resolvedSessionId); - const documentComments = useAppStore((state) => resolvedSessionId ? state.documentPanel.commentsBySessionId[resolvedSessionId] ?? EMPTY_COMMENTS : EMPTY_COMMENTS); - const setDocumentComments = useAppStore((state) => state.setDocumentComments); - const pendingCommentsByFile = usePendingCommentsByFile(); - const markCommentsSent = useDiffCommentsStore((state) => state.markCommentsSent); - const removeComment = useDiffCommentsStore((state) => state.removeComment); + const hydrateComments = useCommentsStore((state) => state.hydrateSession); + useEffect(() => { + if (resolvedSessionId) hydrateComments(resolvedSessionId); + }, [resolvedSessionId, hydrateComments]); + const planComments = usePendingPlanComments(); + const pendingCommentsByFile = usePendingDiffCommentsByFile(); + const markCommentsSent = useCommentsStore((state) => state.markCommentsSent); + const removeComment = useCommentsStore((state) => state.removeComment); + const clearSessionPlanComments = useCallback(() => { + // Remove all pending plan comments for this session + const state = useCommentsStore.getState(); + const ids = resolvedSessionId ? state.bySession[resolvedSessionId] : undefined; + if (!ids) return; + for (const id of ids) { + const c = state.byId[id]; + if (c && isPlanComment(c)) state.removeComment(id); + } + }, [resolvedSessionId]); const { prompts } = useCustomPrompts(); const planContextEnabled = useMemo(() => contextFiles.some((f) => f.path === PLAN_CONTEXT_PATH), [contextFiles]); @@ -228,25 +239,20 @@ function useChatPanelState({ sessionId, onOpenFile, onOpenFileAtLine }: UseChatP return map; }, [prompts]); - const handleClearDocumentComments = useCallback(() => { - if (resolvedSessionId) setDocumentComments(resolvedSessionId, []); - }, [resolvedSessionId, setDocumentComments]); - const handleRemoveCommentFile = useCallback((filePath: string) => { - if (!resolvedSessionId) return; const comments = pendingCommentsByFile[filePath] || []; - for (const comment of comments) removeComment(resolvedSessionId, filePath, comment.id); - }, [resolvedSessionId, pendingCommentsByFile, removeComment]); + for (const comment of comments) removeComment(comment.id); + }, [pendingCommentsByFile, removeComment]); - const handleRemoveComment = useCallback((sid: string, filePath: string, commentId: string) => { - removeComment(sid, filePath, commentId); + const handleRemoveComment = useCallback((commentId: string) => { + removeComment(commentId); }, [removeComment]); const contextItems = useMemo(() => buildContextItems({ planContextEnabled, contextFiles, resolvedSessionId, removeContextFile, unpinFile, addPlan, promptsMap, onOpenFile, pendingCommentsByFile, handleRemoveCommentFile, handleRemoveComment, onOpenFileAtLine, - documentComments, handleClearDocumentComments, taskId, - }), [planContextEnabled, contextFiles, resolvedSessionId, removeContextFile, unpinFile, addPlan, promptsMap, onOpenFile, pendingCommentsByFile, handleRemoveCommentFile, handleRemoveComment, onOpenFileAtLine, documentComments, handleClearDocumentComments, taskId]); + planComments, handleClearPlanComments: clearSessionPlanComments, taskId, + }), [planContextEnabled, contextFiles, resolvedSessionId, removeContextFile, unpinFile, addPlan, promptsMap, onOpenFile, pendingCommentsByFile, handleRemoveCommentFile, handleRemoveComment, onOpenFileAtLine, planComments, clearSessionPlanComments, taskId]); return { resolvedSessionId, session, task, taskId, taskDescription, isStarting, isWorking, isAgentBusy, isFailed, @@ -255,8 +261,8 @@ function useChatPanelState({ sessionId, onOpenFile, onOpenFileAtLine }: UseChatP messages, messagesLoading, allMessages, groupedItems, permissionsByToolCallId, childrenByParentToolCallId, todoItems, agentMessageCount, pendingClarification, sessionModel, activeModel, chatSubmitKey, agentCommands, queuedMessage, isQueued, cancelQueue, updateQueueContent, - documentComments, pendingCommentsByFile, markCommentsSent, contextItems, planContextEnabled, prompts, - handleClearDocumentComments, handleRemoveCommentFile, handleRemoveComment, + planComments, pendingCommentsByFile, markCommentsSent, contextItems, planContextEnabled, prompts, + clearSessionPlanComments, handleRemoveCommentFile, handleRemoveComment, }; } @@ -393,8 +399,8 @@ function useContextFiles(resolvedSessionId: string | null) { function useSubmitHandler(panelState: ReturnType, onSend?: (message: string) => void) { const [isSending, setIsSending] = useState(false); - const { resolvedSessionId, sessionModel, activeModel, planContextEnabled, isAgentBusy, activeDocument, documentComments, contextFiles, prompts, markCommentsSent, handleClearDocumentComments, clearEphemeral } = panelState; - const { handleSendMessage } = useMessageHandler({ resolvedSessionId, taskId: panelState.taskId, sessionModel, activeModel, planMode: planContextEnabled, isAgentBusy, activeDocument, documentComments, contextFiles, prompts }); + const { resolvedSessionId, sessionModel, activeModel, planContextEnabled, isAgentBusy, activeDocument, planComments, contextFiles, prompts, markCommentsSent, clearSessionPlanComments, clearEphemeral } = panelState; + const { handleSendMessage } = useMessageHandler({ resolvedSessionId, taskId: panelState.taskId, sessionModel, activeModel, planMode: planContextEnabled, isAgentBusy, activeDocument, planComments, contextFiles, prompts }); const handleSubmit = useCallback(async (message: string, reviewComments?: DiffComment[], attachments?: MessageAttachment[], inlineMentions?: ContextFile[]) => { if (isSending) return; @@ -408,10 +414,10 @@ function useSubmitHandler(panelState: ReturnType, onSe const hasReviewComments = !!(reviewComments && reviewComments.length > 0); if (onSend) { await onSend(finalMessage); } else { await handleSendMessage(finalMessage, attachments, hasReviewComments, inlineMentions); } if (reviewComments && reviewComments.length > 0) markCommentsSent(reviewComments.map((c) => c.id)); - if (documentComments.length > 0) handleClearDocumentComments(); + if (planComments.length > 0) clearSessionPlanComments(); if (resolvedSessionId) clearEphemeral(resolvedSessionId); } finally { setIsSending(false); } - }, [isSending, onSend, handleSendMessage, markCommentsSent, documentComments.length, handleClearDocumentComments, resolvedSessionId, clearEphemeral]); + }, [isSending, onSend, handleSendMessage, markCommentsSent, planComments.length, clearSessionPlanComments, resolvedSessionId, clearEphemeral]); return { isSending, handleSubmit }; } diff --git a/apps/web/components/task/task-plan-panel.tsx b/apps/web/components/task/task-plan-panel.tsx index a6ffd62c5f..a209a4bb2c 100644 --- a/apps/web/components/task/task-plan-panel.tsx +++ b/apps/web/components/task/task-plan-panel.tsx @@ -10,11 +10,8 @@ import { Button } from '@kandev/ui/button'; import { useTaskPlan } from '@/hooks/domains/session/use-task-plan'; import { useAppStore } from '@/components/state-provider'; import { PlanSelectionPopover } from './plan-selection-popover'; -import type { PlanComment } from './plan-comments'; +import { usePlanComments } from '@/hooks/domains/comments/use-plan-comments'; import type { TextSelection, CommentHighlight } from '@/components/editors/tiptap/tiptap-plan-editor'; -import type { DocumentComment } from '@/lib/state/slices/ui/types'; - -const EMPTY_COMMENTS: DocumentComment[] = []; // Dynamic import to avoid SSR issues with TipTap const PlanEditor = dynamic( @@ -69,7 +66,7 @@ export const TaskPlanPanel = memo(function TaskPlanPanel({ taskId, visible = tru const isAgentCreatingPlan = isAgentBusy && !plan && draftContent.trim() === ''; const commentHighlights: CommentHighlight[] = commentState.comments.map((c) => ({ - id: c.id, selectedText: c.selectedText, comment: c.comment, + id: c.id, selectedText: c.selectedText, comment: c.text, })); const { textSelection, setTextSelection } = selectionState; @@ -132,7 +129,7 @@ function PlanSelectionPopoverWrapper({ }) { if (!textSelection || !activeSessionId) return null; const editingComment = commentState.editingCommentId - ? commentState.comments.find(c => c.id === commentState.editingCommentId)?.comment + ? commentState.comments.find(c => c.id === commentState.editingCommentId)?.text : undefined; const onDelete = commentState.editingCommentId ? () => commentState.handleDeleteComment(commentState.editingCommentId!) @@ -260,49 +257,6 @@ function usePlanDraft( return { draftContent, setDraftContent, editorKey, isEditorFocused, handleEmptyStateClick, hasUnsavedChanges }; } -/** Comment state and handlers */ -function usePlanComments(activeSessionId: string | null | undefined) { - const setDocumentComments = useAppStore((state) => state.setDocumentComments); - const storeComments = useAppStore((state) => - activeSessionId ? state.documentPanel.commentsBySessionId[activeSessionId] ?? EMPTY_COMMENTS : EMPTY_COMMENTS - ); - const [comments, setComments] = useState([]); - const [editingCommentId, setEditingCommentId] = useState(null); - - const handleAddComment = useCallback((comment: string, selectedText: string) => { - if (editingCommentId) { - setComments(prev => prev.map(c => c.id === editingCommentId ? { ...c, comment, selectedText } : c)); - setEditingCommentId(null); - } else { - setComments(prev => [...prev, { id: crypto.randomUUID(), selectedText, comment }]); - } - }, [editingCommentId]); - - const handleDeleteComment = useCallback((commentId: string) => { - setComments(prev => prev.filter(c => c.id !== commentId)); - }, []); - - // Sync to store - useEffect(() => { - if (activeSessionId) { - setDocumentComments(activeSessionId, comments.map(c => ({ id: c.id, selectedText: c.selectedText, comment: c.comment }))); - } - }, [activeSessionId, comments, setDocumentComments]); - - // Detect external clear - const prevStoreCommentsLenRef = useRef(storeComments.length); - useEffect(() => { - const prevLen = prevStoreCommentsLenRef.current; - prevStoreCommentsLenRef.current = storeComments.length; - if (prevLen > 0 && storeComments.length === 0 && comments.length > 0) { - // eslint-disable-next-line react-hooks/set-state-in-effect -- syncing store clear to local state - setComments([]); - } - }, [storeComments.length, comments.length]); - - return { comments, editingCommentId, setEditingCommentId, handleAddComment, handleDeleteComment }; -} - /** Text selection and floating button state */ function usePlanSelection( activeSessionId: string | null | undefined, diff --git a/apps/web/hooks/domains/comments/use-diff-comments.ts b/apps/web/hooks/domains/comments/use-diff-comments.ts new file mode 100644 index 0000000000..67cb0b041d --- /dev/null +++ b/apps/web/hooks/domains/comments/use-diff-comments.ts @@ -0,0 +1,54 @@ +import { useEffect, useMemo } from 'react'; +import { useCommentsStore } from '@/lib/state/slices/comments'; +import type { DiffComment } from '@/lib/state/slices/comments'; +import { isDiffComment } from '@/lib/state/slices/comments'; + +const EMPTY_COMMENTS: DiffComment[] = []; + +/** + * Get all diff comments for a specific file in a session. + */ +export function useDiffFileComments(sessionId: string, filePath: string): DiffComment[] { + const byId = useCommentsStore((state) => state.byId); + const sessionIds = useCommentsStore((state) => state.bySession[sessionId]); + const hydrateSession = useCommentsStore((state) => state.hydrateSession); + + useEffect(() => { + if (sessionId) hydrateSession(sessionId); + }, [sessionId, hydrateSession]); + + return useMemo(() => { + if (!sessionIds || sessionIds.length === 0) return EMPTY_COMMENTS; + const result: DiffComment[] = []; + for (const id of sessionIds) { + const comment = byId[id]; + if (comment && isDiffComment(comment) && comment.filePath === filePath) { + result.push(comment); + } + } + return result.length === 0 ? EMPTY_COMMENTS : result; + }, [byId, sessionIds, filePath]); +} + +const EMPTY_BY_FILE: Record = {}; + +/** + * Get all pending diff comments grouped by file path. + */ +export function usePendingDiffCommentsByFile(): Record { + const byId = useCommentsStore((state) => state.byId); + const pendingForChat = useCommentsStore((state) => state.pendingForChat); + + return useMemo(() => { + if (pendingForChat.length === 0) return EMPTY_BY_FILE; + const byFile: Record = {}; + for (const id of pendingForChat) { + const comment = byId[id]; + if (comment && isDiffComment(comment)) { + if (!byFile[comment.filePath]) byFile[comment.filePath] = []; + byFile[comment.filePath].push(comment); + } + } + return Object.keys(byFile).length === 0 ? EMPTY_BY_FILE : byFile; + }, [byId, pendingForChat]); +} diff --git a/apps/web/hooks/domains/comments/use-pending-comments.ts b/apps/web/hooks/domains/comments/use-pending-comments.ts new file mode 100644 index 0000000000..1a4c63352a --- /dev/null +++ b/apps/web/hooks/domains/comments/use-pending-comments.ts @@ -0,0 +1,62 @@ +import { useMemo } from 'react'; +import { useCommentsStore } from '@/lib/state/slices/comments'; +import type { Comment, DiffComment, PlanComment } from '@/lib/state/slices/comments'; +import { isDiffComment, isPlanComment } from '@/lib/state/slices/comments'; + +const EMPTY_COMMENTS: Comment[] = []; +const EMPTY_DIFF_COMMENTS: DiffComment[] = []; +const EMPTY_PLAN_COMMENTS: PlanComment[] = []; + +/** + * Get all pending comments (any source). + */ +export function usePendingComments(): Comment[] { + const byId = useCommentsStore((state) => state.byId); + const pendingForChat = useCommentsStore((state) => state.pendingForChat); + + return useMemo(() => { + if (pendingForChat.length === 0) return EMPTY_COMMENTS; + const pending: Comment[] = []; + for (const id of pendingForChat) { + const comment = byId[id]; + if (comment) pending.push(comment); + } + return pending.length === 0 ? EMPTY_COMMENTS : pending; + }, [byId, pendingForChat]); +} + +/** + * Get all pending diff comments. + */ +export function usePendingDiffComments(): DiffComment[] { + const byId = useCommentsStore((state) => state.byId); + const pendingForChat = useCommentsStore((state) => state.pendingForChat); + + return useMemo(() => { + if (pendingForChat.length === 0) return EMPTY_DIFF_COMMENTS; + const pending: DiffComment[] = []; + for (const id of pendingForChat) { + const comment = byId[id]; + if (comment && isDiffComment(comment)) pending.push(comment); + } + return pending.length === 0 ? EMPTY_DIFF_COMMENTS : pending; + }, [byId, pendingForChat]); +} + +/** + * Get all pending plan comments. + */ +export function usePendingPlanComments(): PlanComment[] { + const byId = useCommentsStore((state) => state.byId); + const pendingForChat = useCommentsStore((state) => state.pendingForChat); + + return useMemo(() => { + if (pendingForChat.length === 0) return EMPTY_PLAN_COMMENTS; + const pending: PlanComment[] = []; + for (const id of pendingForChat) { + const comment = byId[id]; + if (comment && isPlanComment(comment)) pending.push(comment); + } + return pending.length === 0 ? EMPTY_PLAN_COMMENTS : pending; + }, [byId, pendingForChat]); +} diff --git a/apps/web/hooks/domains/comments/use-plan-comments.ts b/apps/web/hooks/domains/comments/use-plan-comments.ts new file mode 100644 index 0000000000..e5aa4d7605 --- /dev/null +++ b/apps/web/hooks/domains/comments/use-plan-comments.ts @@ -0,0 +1,80 @@ +import { useCallback, useEffect, useMemo } from 'react'; +import { useCommentsStore } from '@/lib/state/slices/comments'; +import type { PlanComment } from '@/lib/state/slices/comments'; +import { isPlanComment } from '@/lib/state/slices/comments'; + +const EMPTY_COMMENTS: PlanComment[] = []; + +/** + * Hook for managing plan comments for a session. + * + * Replaces the local-state-then-sync pattern in task-plan-panel.tsx. + * The store IS the source of truth โ€” no local state needed. + */ +export function usePlanComments(sessionId: string | null | undefined) { + const byId = useCommentsStore((state) => state.byId); + const sessionIds = useCommentsStore((state) => + sessionId ? state.bySession[sessionId] : undefined + ); + const addCommentToStore = useCommentsStore((state) => state.addComment); + const updateCommentInStore = useCommentsStore((state) => state.updateComment); + const removeCommentFromStore = useCommentsStore((state) => state.removeComment); + const editingCommentId = useCommentsStore((state) => state.editingCommentId); + const setEditingComment = useCommentsStore((state) => state.setEditingComment); + const hydrateSession = useCommentsStore((state) => state.hydrateSession); + + // Hydrate on mount + useEffect(() => { + if (sessionId) hydrateSession(sessionId); + }, [sessionId, hydrateSession]); + + const comments = useMemo((): PlanComment[] => { + if (!sessionIds || sessionIds.length === 0) return EMPTY_COMMENTS; + const result: PlanComment[] = []; + for (const id of sessionIds) { + const comment = byId[id]; + if (comment && isPlanComment(comment)) { + result.push(comment); + } + } + return result.length === 0 ? EMPTY_COMMENTS : result; + }, [byId, sessionIds]); + + const handleAddComment = useCallback( + (commentText: string, selectedText: string) => { + if (!sessionId) return; + + if (editingCommentId) { + updateCommentInStore(editingCommentId, { text: commentText, selectedText } as Partial); + setEditingComment(null); + } else { + const comment: PlanComment = { + id: crypto.randomUUID(), + sessionId, + source: 'plan', + text: commentText, + selectedText, + createdAt: new Date().toISOString(), + status: 'pending', + }; + addCommentToStore(comment); + } + }, + [sessionId, editingCommentId, addCommentToStore, updateCommentInStore, setEditingComment] + ); + + const handleDeleteComment = useCallback( + (commentId: string) => { + removeCommentFromStore(commentId); + }, + [removeCommentFromStore] + ); + + return { + comments, + editingCommentId, + setEditingCommentId: setEditingComment, + handleAddComment, + handleDeleteComment, + }; +} diff --git a/apps/web/hooks/use-message-handler.ts b/apps/web/hooks/use-message-handler.ts index a3b7ba9f41..5bb5605b6c 100644 --- a/apps/web/hooks/use-message-handler.ts +++ b/apps/web/hooks/use-message-handler.ts @@ -2,20 +2,21 @@ import { useCallback } from 'react'; import { getWebSocketClient } from '@/lib/ws/connection'; import { useQueue } from './domains/session/use-queue'; import type { MessageAttachment } from '@/components/task/chat/chat-input-container'; -import type { ActiveDocument, DocumentComment } from '@/lib/state/slices/ui/types'; +import type { ActiveDocument } from '@/lib/state/slices/ui/types'; +import type { PlanComment } from '@/lib/state/slices/comments'; import type { ContextFile } from '@/lib/state/context-files-store'; import type { CustomPrompt } from '@/lib/types/http'; -function buildDocumentContext(activeDocument: ActiveDocument | null, comments?: DocumentComment[]): string { +function buildDocumentContext(activeDocument: ActiveDocument | null, planComments?: PlanComment[]): string { if (!activeDocument) return ''; if (activeDocument.type === 'plan') { let context = `\n\n\nACTIVE DOCUMENT: The user is editing the task plan side-by-side with this chat.\nRead the current plan using the plan_get MCP tool to understand the context before responding.\nAny plan modifications should use the plan_update MCP tool.`; - if (comments && comments.length > 0) { + if (planComments && planComments.length > 0) { context += `\n\nUser comments on the plan:`; - comments.forEach((c, i) => { - context += `\nComment ${i + 1}:\n- Selected text: "${c.selectedText}"\n- Comment: "${c.comment}"`; + planComments.forEach((c, i) => { + context += `\nComment ${i + 1}:\n- Selected text: "${c.selectedText}"\n- Comment: "${c.text}"`; }); } @@ -63,7 +64,7 @@ export interface UseMessageHandlerParams { planMode?: boolean; isAgentBusy?: boolean; activeDocument?: ActiveDocument | null; - documentComments?: DocumentComment[]; + planComments?: PlanComment[]; contextFiles?: ContextFile[]; prompts?: CustomPrompt[]; } @@ -110,7 +111,7 @@ export function useMessageHandler({ planMode = false, isAgentBusy = false, activeDocument = null, - documentComments = [], + planComments = [], contextFiles = [], prompts = [], }: UseMessageHandlerParams) { @@ -119,11 +120,11 @@ export function useMessageHandler({ const buildFinalMessage = useCallback( (message: string, inlineMentions?: ContextFile[]) => { const allContextFiles = [...contextFiles, ...(inlineMentions || [])]; - const documentContext = buildDocumentContext(activeDocument, documentComments); + const documentContext = buildDocumentContext(activeDocument, planComments); const contextFilesContext = buildContextFilesContext(allContextFiles, prompts); return { finalMessage: message.trim() + documentContext + contextFilesContext, allContextFiles }; }, - [contextFiles, activeDocument, documentComments, prompts] + [contextFiles, activeDocument, planComments, prompts] ); const handleSendMessage = useCallback( diff --git a/apps/web/lib/diff/comment-utils.ts b/apps/web/lib/diff/comment-utils.ts index ec83469950..9cb4d68c25 100644 --- a/apps/web/lib/diff/comment-utils.ts +++ b/apps/web/lib/diff/comment-utils.ts @@ -8,18 +8,19 @@ export function buildDiffComment(params: { startLine: number; endLine: number; side: DiffComment['side']; - annotation: string; + text: string; codeContent?: string; }): DiffComment { return { id: `${params.filePath}-${Date.now()}`, + source: 'diff', sessionId: params.sessionId, filePath: params.filePath, startLine: Math.min(params.startLine, params.endLine), endLine: Math.max(params.startLine, params.endLine), side: params.side, codeContent: params.codeContent ?? '', - annotation: params.annotation, + text: params.text, createdAt: new Date().toISOString(), status: 'pending', }; @@ -63,7 +64,7 @@ export function useCommentActions(params: { const handleCommentUpdate = useCallback( (commentId: string, content: string) => { - updateComment(commentId, { annotation: content }); + updateComment(commentId, { text: content }); setEditingComment(null); }, [updateComment, setEditingComment] diff --git a/apps/web/lib/diff/types.ts b/apps/web/lib/diff/types.ts index b20198811a..fc62d9d7ef 100644 --- a/apps/web/lib/diff/types.ts +++ b/apps/web/lib/diff/types.ts @@ -1,25 +1,8 @@ import type { DiffLineAnnotation } from '@pierre/diffs'; -/** - * Annotation side - matches @pierre/diffs AnnotationSide - */ -export type AnnotationSide = 'additions' | 'deletions'; - -/** - * Comment attached to a line range in a diff - */ -export interface DiffComment { - id: string; - sessionId: string; - filePath: string; - startLine: number; - endLine: number; - side: AnnotationSide; - codeContent: string; // The actual code lines the user selected - annotation: string; // User's comment text - createdAt: string; - status: 'pending' | 'sent'; -} +// Re-export DiffComment from unified comment system for backward compat +export type { DiffComment, AnnotationSide } from '@/lib/state/slices/comments/types'; +import type { DiffComment } from '@/lib/state/slices/comments/types'; /** * File diff data in a unified format for @pierre/diffs. @@ -43,19 +26,18 @@ export type CommentAnnotation = DiffLineAnnotation<{ }>; /** - * Store state for diff comments + * Store state for diff comments โ€” kept for backward compat type references. + * @deprecated Use CommentsState from '@/lib/state/slices/comments' instead. */ export interface DiffCommentsState { - // Comments by session and file: sessionId -> filePath -> comments bySession: Record>; - // Comments queued for next chat message (referenced by id) pendingForChat: string[]; - // Currently editing comment (null if none) editingCommentId: string | null; } /** * Actions for the diff comments store + * @deprecated Use CommentsActions from '@/lib/state/slices/comments' instead. */ export interface DiffCommentsActions { addComment: (comment: DiffComment) => void; @@ -73,6 +55,7 @@ export interface DiffCommentsActions { /** * Combined state and actions + * @deprecated Use CommentsSlice from '@/lib/state/slices/comments' instead. */ export type DiffCommentsSlice = DiffCommentsState & DiffCommentsActions; diff --git a/apps/web/lib/local-storage.ts b/apps/web/lib/local-storage.ts index e72d18516b..4d97788d17 100644 --- a/apps/web/lib/local-storage.ts +++ b/apps/web/lib/local-storage.ts @@ -526,5 +526,6 @@ export function cleanupTaskStorage(taskId: string, sessionIds: string[]): void { removeSessionStorage(`${OPEN_FILES_KEY}.${sessionId}`); removeSessionStorage(`${ACTIVE_TAB_KEY}.${sessionId}`); removeSessionStorage(`kandev.contextFiles.${sessionId}`); + removeSessionStorage(`kandev.comments.${sessionId}`); } } diff --git a/apps/web/lib/state/slices/comments/comments-store.ts b/apps/web/lib/state/slices/comments/comments-store.ts new file mode 100644 index 0000000000..9a77f0df01 --- /dev/null +++ b/apps/web/lib/state/slices/comments/comments-store.ts @@ -0,0 +1,156 @@ +import { create } from 'zustand'; +import { immer } from 'zustand/middleware/immer'; +import type { Comment, DiffComment, CommentsSlice, CommentsState } from './types'; +import { isDiffComment } from './types'; +import { persistSessionComments, loadSessionComments, clearPersistedSessionComments } from './persistence'; + +const defaultState: CommentsState = { + byId: {}, + bySession: {}, + pendingForChat: [], + editingCommentId: null, +}; + +/** Collect all comments for a given session from byId + bySession index. */ +function getSessionComments(state: CommentsState, sessionId: string): Comment[] { + const ids = state.bySession[sessionId]; + if (!ids || ids.length === 0) return []; + const comments: Comment[] = []; + for (const id of ids) { + const comment = state.byId[id]; + if (comment) comments.push(comment); + } + return comments; +} + +/** Persist all comments for a session to sessionStorage. */ +function persistSession(state: CommentsState, sessionId: string): void { + persistSessionComments(sessionId, getSessionComments(state, sessionId)); +} + +/** Remove a single comment from state and persist. */ +function removeCommentFromState(state: CommentsState, commentId: string): void { + const comment = state.byId[commentId]; + if (!comment) return; + const { sessionId } = comment; + delete state.byId[commentId]; + const sessionIds = state.bySession[sessionId]; + if (sessionIds) { + const idx = sessionIds.indexOf(commentId); + if (idx !== -1) sessionIds.splice(idx, 1); + if (sessionIds.length === 0) delete state.bySession[sessionId]; + } + state.pendingForChat = state.pendingForChat.filter((id) => id !== commentId); + if (state.editingCommentId === commentId) state.editingCommentId = null; + persistSession(state, sessionId); +} + +/** Mark a batch of comments as sent: remove from store + persist affected sessions. */ +function markSentInState(state: CommentsState, commentIds: string[]): void { + const idsToRemove = new Set(commentIds); + const affectedSessions = new Set(); + for (const id of commentIds) { + const comment = state.byId[id]; + if (comment) affectedSessions.add(comment.sessionId); + delete state.byId[id]; + } + for (const sessionId of Object.keys(state.bySession)) { + state.bySession[sessionId] = state.bySession[sessionId].filter((id) => !idsToRemove.has(id)); + if (state.bySession[sessionId].length === 0) delete state.bySession[sessionId]; + } + state.pendingForChat = state.pendingForChat.filter((id) => !idsToRemove.has(id)); + if (state.editingCommentId && idsToRemove.has(state.editingCommentId)) state.editingCommentId = null; + for (const sessionId of affectedSessions) persistSession(state, sessionId); +} + +/** Remove all comments for a session from state + storage. */ +function clearSessionInState(state: CommentsState, sessionId: string): void { + const ids = state.bySession[sessionId]; + if (!ids) return; + const idSet = new Set(ids); + for (const id of ids) delete state.byId[id]; + delete state.bySession[sessionId]; + state.pendingForChat = state.pendingForChat.filter((id) => !idSet.has(id)); + clearPersistedSessionComments(sessionId); +} + +/** Load comments from sessionStorage into state (no-op if already hydrated). */ +function hydrateSessionInState(state: CommentsState, sessionId: string): void { + if (state.bySession[sessionId] && state.bySession[sessionId].length > 0) return; + const comments = loadSessionComments(sessionId); + if (comments.length === 0) return; + const ids: string[] = []; + for (const comment of comments) { + state.byId[comment.id] = comment; + ids.push(comment.id); + if (comment.status === 'pending' && !state.pendingForChat.includes(comment.id)) { + state.pendingForChat.push(comment.id); + } + } + state.bySession[sessionId] = ids; +} + +export const useCommentsStore = create()( + immer((set, get) => ({ + ...defaultState, + + addComment: (comment: Comment) => + set((state) => { + state.byId[comment.id] = comment; + if (!state.bySession[comment.sessionId]) state.bySession[comment.sessionId] = []; + state.bySession[comment.sessionId].push(comment.id); + if (comment.status === 'pending') state.pendingForChat.push(comment.id); + persistSession(state, comment.sessionId); + }), + + updateComment: (commentId: string, updates: Partial) => + set((state) => { + const existing = state.byId[commentId]; + if (!existing) return; + Object.assign(existing, updates); + persistSession(state, existing.sessionId); + }), + + removeComment: (commentId: string) => set((state) => removeCommentFromState(state, commentId)), + + addToPending: (commentId: string) => + set((state) => { + if (!state.pendingForChat.includes(commentId)) state.pendingForChat.push(commentId); + }), + + removeFromPending: (commentId: string) => + set((state) => { state.pendingForChat = state.pendingForChat.filter((id) => id !== commentId); }), + + clearPending: () => set((state) => { state.pendingForChat = []; }), + + setEditingComment: (commentId: string | null) => set((state) => { state.editingCommentId = commentId; }), + + markCommentsSent: (commentIds: string[]) => set((state) => markSentInState(state, commentIds)), + + clearSessionComments: (sessionId: string) => set((state) => clearSessionInState(state, sessionId)), + + hydrateSession: (sessionId: string) => set((state) => hydrateSessionInState(state, sessionId)), + + getCommentsForFile: (sessionId: string, filePath: string): DiffComment[] => { + const state = get(); + const ids = state.bySession[sessionId]; + if (!ids) return []; + const result: DiffComment[] = []; + for (const id of ids) { + const comment = state.byId[id]; + if (comment && isDiffComment(comment) && comment.filePath === filePath) result.push(comment); + } + return result; + }, + + getPendingComments: (): Comment[] => { + const state = get(); + const pending: Comment[] = []; + for (const id of state.pendingForChat) { + const comment = state.byId[id]; + if (comment) pending.push(comment); + } + return pending; + }, + })) +); diff --git a/apps/web/lib/state/slices/comments/format.ts b/apps/web/lib/state/slices/comments/format.ts new file mode 100644 index 0000000000..276ff40678 --- /dev/null +++ b/apps/web/lib/state/slices/comments/format.ts @@ -0,0 +1,71 @@ +import type { Comment, DiffComment, PlanComment } from './types'; +import { isDiffComment, isPlanComment } from './types'; + +/** + * Format diff review comments as human-readable markdown for sending to agent. + */ +export function formatReviewCommentsAsMarkdown(comments: DiffComment[]): string { + if (!comments || comments.length === 0) return ''; + + const lines: string[] = ['### Review Comments', '']; + + const byFile = new Map(); + for (const comment of comments) { + const existing = byFile.get(comment.filePath) || []; + existing.push(comment); + byFile.set(comment.filePath, existing); + } + + for (const [filePath, fileComments] of byFile) { + for (const comment of fileComments) { + const lineRange = comment.startLine === comment.endLine + ? `${comment.startLine}` + : `${comment.startLine}-${comment.endLine}`; + + lines.push(`**${filePath}:${lineRange}**`); + lines.push('```'); + lines.push(comment.codeContent); + lines.push('```'); + lines.push(`> ${comment.text}`); + lines.push(''); + } + } + + lines.push('---'); + lines.push(''); + return lines.join('\n'); +} + +/** + * Format plan comments as markdown for sending to agent. + */ +export function formatPlanCommentsAsMarkdown(comments: PlanComment[]): string { + if (!comments || comments.length === 0) return ''; + + const lines: string[] = []; + for (let i = 0; i < comments.length; i++) { + const c = comments[i]; + lines.push(`Comment ${i + 1}:`); + lines.push(`- Selected text: "${c.selectedText}"`); + lines.push(`- Comment: "${c.text}"`); + } + return lines.join('\n'); +} + +/** + * Format all pending comments for inclusion in a chat message. + */ +export function formatCommentsForMessage(comments: Comment[]): { + diffComments: DiffComment[]; + planComments: PlanComment[]; +} { + const diffComments: DiffComment[] = []; + const planComments: PlanComment[] = []; + + for (const c of comments) { + if (isDiffComment(c)) diffComments.push(c); + else if (isPlanComment(c)) planComments.push(c); + } + + return { diffComments, planComments }; +} diff --git a/apps/web/lib/state/slices/comments/index.ts b/apps/web/lib/state/slices/comments/index.ts new file mode 100644 index 0000000000..d8467c8857 --- /dev/null +++ b/apps/web/lib/state/slices/comments/index.ts @@ -0,0 +1,25 @@ +export { useCommentsStore } from './comments-store'; +export { + type Comment, + type DiffComment, + type PlanComment, + type FileEditorComment, + type AnnotationSide, + type CommentsState, + type CommentsActions, + type CommentsSlice, + isDiffComment, + isPlanComment, + isFileEditorComment, +} from './types'; +export { + formatReviewCommentsAsMarkdown, + formatPlanCommentsAsMarkdown, + formatCommentsForMessage, +} from './format'; +export { + persistSessionComments, + loadSessionComments, + clearPersistedSessionComments, + COMMENTS_STORAGE_PREFIX, +} from './persistence'; diff --git a/apps/web/lib/state/slices/comments/persistence.ts b/apps/web/lib/state/slices/comments/persistence.ts new file mode 100644 index 0000000000..d3eba01b87 --- /dev/null +++ b/apps/web/lib/state/slices/comments/persistence.ts @@ -0,0 +1,22 @@ +import { getSessionStorage, setSessionStorage, removeSessionStorage } from '@/lib/local-storage'; +import type { Comment } from './types'; + +const STORAGE_PREFIX = 'kandev.comments.'; + +export function persistSessionComments(sessionId: string, comments: Comment[]): void { + if (comments.length === 0) { + removeSessionStorage(`${STORAGE_PREFIX}${sessionId}`); + return; + } + setSessionStorage(`${STORAGE_PREFIX}${sessionId}`, JSON.parse(JSON.stringify(comments))); +} + +export function loadSessionComments(sessionId: string): Comment[] { + return getSessionStorage(`${STORAGE_PREFIX}${sessionId}`, [] as Comment[]) as Comment[]; +} + +export function clearPersistedSessionComments(sessionId: string): void { + removeSessionStorage(`${STORAGE_PREFIX}${sessionId}`); +} + +export const COMMENTS_STORAGE_PREFIX = STORAGE_PREFIX; diff --git a/apps/web/lib/state/slices/comments/types.ts b/apps/web/lib/state/slices/comments/types.ts new file mode 100644 index 0000000000..fbe0e4f437 --- /dev/null +++ b/apps/web/lib/state/slices/comments/types.ts @@ -0,0 +1,88 @@ +/** + * Unified comment system types. + * + * All comment types (diff, plan, file-editor) share a common base and are + * distinguished via a `source` discriminant. + */ + +// --------------------------------------------------------------------------- +// Comment union +// --------------------------------------------------------------------------- + +export type AnnotationSide = 'additions' | 'deletions'; + +type CommentBase = { + id: string; + sessionId: string; + text: string; + createdAt: string; + status: 'pending' | 'sent'; +}; + +export type DiffComment = CommentBase & { + source: 'diff'; + filePath: string; + startLine: number; + endLine: number; + side: AnnotationSide; + codeContent: string; +}; + +export type PlanComment = CommentBase & { + source: 'plan'; + selectedText: string; +}; + +export type FileEditorComment = CommentBase & { + source: 'file-editor'; + filePath: string; + selectedText: string; + startLine?: number; + endLine?: number; +}; + +export type Comment = DiffComment | PlanComment | FileEditorComment; + +// --------------------------------------------------------------------------- +// Type guards +// --------------------------------------------------------------------------- + +export function isDiffComment(c: Comment): c is DiffComment { + return c.source === 'diff'; +} + +export function isPlanComment(c: Comment): c is PlanComment { + return c.source === 'plan'; +} + +export function isFileEditorComment(c: Comment): c is FileEditorComment { + return c.source === 'file-editor'; +} + +// --------------------------------------------------------------------------- +// Store state & actions +// --------------------------------------------------------------------------- + +export type CommentsState = { + byId: Record; + bySession: Record; + pendingForChat: string[]; + editingCommentId: string | null; +}; + +export type CommentsActions = { + addComment: (comment: Comment) => void; + updateComment: (commentId: string, updates: Partial) => void; + removeComment: (commentId: string) => void; + addToPending: (commentId: string) => void; + removeFromPending: (commentId: string) => void; + clearPending: () => void; + setEditingComment: (commentId: string | null) => void; + markCommentsSent: (commentIds: string[]) => void; + clearSessionComments: (sessionId: string) => void; + hydrateSession: (sessionId: string) => void; + getCommentsForFile: (sessionId: string, filePath: string) => DiffComment[]; + getPendingComments: () => Comment[]; +}; + +export type CommentsSlice = CommentsState & CommentsActions; diff --git a/apps/web/lib/state/slices/diff-comments/diff-comments-slice.ts b/apps/web/lib/state/slices/diff-comments/diff-comments-slice.ts deleted file mode 100644 index 26649a5f9f..0000000000 --- a/apps/web/lib/state/slices/diff-comments/diff-comments-slice.ts +++ /dev/null @@ -1,267 +0,0 @@ -import { useMemo } from 'react'; -import { create } from 'zustand'; -import { persist, createJSONStorage } from 'zustand/middleware'; -import { immer } from 'zustand/middleware/immer'; -import type { - DiffCommentsState, - DiffCommentsSlice, - DiffComment, -} from '@/lib/diff/types'; - -const STORAGE_KEY = 'kandev-diff-comments'; - -// Stable empty references to avoid creating new objects on every render -const EMPTY_COMMENTS: DiffComment[] = []; -const EMPTY_COMMENTS_BY_FILE: Record = {}; - -const defaultState: DiffCommentsState = { - bySession: {}, - pendingForChat: [], - editingCommentId: null, -}; - -/** Find and update a comment by ID across all sessions/files. */ -function findAndUpdateComment( - bySession: DiffCommentsState['bySession'], - commentId: string, - updates: Partial, -): void { - for (const sessionId of Object.keys(bySession)) { - for (const filePath of Object.keys(bySession[sessionId])) { - const comments = bySession[sessionId][filePath]; - const index = comments.findIndex((c) => c.id === commentId); - if (index !== -1) { - bySession[sessionId][filePath][index] = { ...comments[index], ...updates }; - return; - } - } - } -} - -/** Remove comments by ID set, cleaning up empty file/session entries. */ -function removeCommentsByIds( - bySession: DiffCommentsState['bySession'], - idsToRemove: Set, -): void { - for (const sessionId of Object.keys(bySession)) { - for (const filePath of Object.keys(bySession[sessionId])) { - bySession[sessionId][filePath] = bySession[sessionId][filePath] - .filter((comment) => !idsToRemove.has(comment.id)); - if (bySession[sessionId][filePath].length === 0) { - delete bySession[sessionId][filePath]; - } - } - if (Object.keys(bySession[sessionId]).length === 0) { - delete bySession[sessionId]; - } - } -} - -/** Collect all pending DiffComment objects matching the pendingForChat IDs. */ -function collectPendingComments( - bySession: DiffCommentsState['bySession'], - pendingForChat: string[], -): DiffComment[] { - const pending: DiffComment[] = []; - for (const sessionId of Object.keys(bySession)) { - for (const filePath of Object.keys(bySession[sessionId])) { - for (const comment of bySession[sessionId][filePath]) { - if (pendingForChat.includes(comment.id)) { - pending.push(comment); - } - } - } - } - return pending; -} - -/** - * Standalone Zustand store for diff comments with localStorage persistence. - * Comments are organized by sessionId and filePath. - */ -export const useDiffCommentsStore = create()( - persist( - immer((set, get) => ({ - ...defaultState, - - addComment: (comment: DiffComment) => - set((state) => { - const { sessionId, filePath } = comment; - if (!state.bySession[sessionId]) { - state.bySession[sessionId] = {}; - } - if (!state.bySession[sessionId][filePath]) { - state.bySession[sessionId][filePath] = []; - } - state.bySession[sessionId][filePath].push(comment); - - // Auto-add to pending for chat - if (comment.status === 'pending') { - state.pendingForChat.push(comment.id); - } - }), - - updateComment: (commentId: string, updates: Partial) => - set((state) => { - findAndUpdateComment(state.bySession, commentId, updates); - }), - - removeComment: (sessionId: string, filePath: string, commentId: string) => - set((state) => { - if (!state.bySession[sessionId]?.[filePath]) return; - state.bySession[sessionId][filePath] = state.bySession[sessionId][ - filePath - ].filter((c) => c.id !== commentId); - - // Remove from pending if present - state.pendingForChat = state.pendingForChat.filter( - (id) => id !== commentId - ); - - // Clear editing if this was the editing comment - if (state.editingCommentId === commentId) { - state.editingCommentId = null; - } - }), - - addToPending: (commentId: string) => - set((state) => { - if (!state.pendingForChat.includes(commentId)) { - state.pendingForChat.push(commentId); - } - }), - - removeFromPending: (commentId: string) => - set((state) => { - state.pendingForChat = state.pendingForChat.filter( - (id) => id !== commentId - ); - }), - - clearPending: () => - set((state) => { - state.pendingForChat = []; - }), - - setEditingComment: (commentId: string | null) => - set((state) => { - state.editingCommentId = commentId; - }), - - markCommentsSent: (commentIds: string[]) => - set((state) => { - const idsToRemove = new Set(commentIds); - removeCommentsByIds(state.bySession, idsToRemove); - state.pendingForChat = state.pendingForChat.filter( - (id) => !idsToRemove.has(id) - ); - if (state.editingCommentId && idsToRemove.has(state.editingCommentId)) { - state.editingCommentId = null; - } - }), - - getCommentsForFile: (sessionId: string, filePath: string): DiffComment[] => { - const state = get(); - return state.bySession[sessionId]?.[filePath] ?? EMPTY_COMMENTS; - }, - - getPendingComments: (): DiffComment[] => { - const state = get(); - return collectPendingComments(state.bySession, state.pendingForChat); - }, - - clearSessionComments: (sessionId: string) => - set((state) => { - // Collect comment IDs BEFORE deleting the session - const sessionCommentIds = new Set(); - if (state.bySession[sessionId]) { - for (const filePath of Object.keys(state.bySession[sessionId])) { - for (const comment of state.bySession[sessionId][filePath]) { - sessionCommentIds.add(comment.id); - } - } - } - // Now delete the session and filter pending - delete state.bySession[sessionId]; - state.pendingForChat = state.pendingForChat.filter( - (id) => !sessionCommentIds.has(id) - ); - }), - })), - { - name: STORAGE_KEY, - storage: createJSONStorage(() => localStorage), - partialize: (state) => ({ - bySession: state.bySession, - // Don't persist pendingForChat or editingCommentId - }), - } - ) -); - -/** - * Hook to get comments for a specific file. - * Returns stable reference from store (or stable empty array). - */ -export function useFileComments(sessionId: string, filePath: string) { - const fileComments = useDiffCommentsStore((state) => - state.bySession[sessionId]?.[filePath] - ); - return fileComments ?? EMPTY_COMMENTS; -} - -/** - * Hook to get pending comments for chat. - * Uses useMemo with stable store subscriptions to prevent infinite re-renders. - */ -export function usePendingComments() { - const bySession = useDiffCommentsStore((state) => state.bySession); - const pendingForChat = useDiffCommentsStore((state) => state.pendingForChat); - - return useMemo(() => { - if (pendingForChat.length === 0) return EMPTY_COMMENTS; - const pending: DiffComment[] = []; - for (const sessionId of Object.keys(bySession)) { - for (const filePath of Object.keys(bySession[sessionId])) { - for (const comment of bySession[sessionId][filePath]) { - if (pendingForChat.includes(comment.id)) { - pending.push(comment); - } - } - } - } - return pending; - }, [bySession, pendingForChat]); -} - -function addPendingCommentToFileMap( - byFile: Record, - comment: DiffComment, - pendingForChat: string[], -): void { - if (!pendingForChat.includes(comment.id)) return; - if (!byFile[comment.filePath]) byFile[comment.filePath] = []; - byFile[comment.filePath].push(comment); -} - -/** - * Hook to get pending comments grouped by file. - * Uses useMemo with stable store subscriptions to prevent infinite re-renders. - */ -export function usePendingCommentsByFile() { - const bySession = useDiffCommentsStore((state) => state.bySession); - const pendingForChat = useDiffCommentsStore((state) => state.pendingForChat); - - return useMemo(() => { - if (pendingForChat.length === 0) return EMPTY_COMMENTS_BY_FILE; - const byFile: Record = {}; - for (const sessionId of Object.keys(bySession)) { - for (const filePath of Object.keys(bySession[sessionId])) { - for (const comment of bySession[sessionId][filePath]) { - addPendingCommentToFileMap(byFile, comment, pendingForChat); - } - } - } - return byFile; - }, [bySession, pendingForChat]); -} diff --git a/apps/web/lib/state/slices/diff-comments/index.ts b/apps/web/lib/state/slices/diff-comments/index.ts deleted file mode 100644 index 23cbee613b..0000000000 --- a/apps/web/lib/state/slices/diff-comments/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export { - useDiffCommentsStore, - useFileComments, - usePendingComments, - usePendingCommentsByFile, -} from './diff-comments-slice'; diff --git a/apps/web/lib/state/slices/index.ts b/apps/web/lib/state/slices/index.ts index f98f34816e..dfc1e799ee 100644 --- a/apps/web/lib/state/slices/index.ts +++ b/apps/web/lib/state/slices/index.ts @@ -93,7 +93,6 @@ export type { MobileSessionPanel, MobileSessionState, ActiveDocument, - DocumentComment, DocumentPanelState, } from './ui/types'; export type { Repository, Branch } from '@/lib/types/http'; diff --git a/apps/web/lib/state/slices/ui/types.ts b/apps/web/lib/state/slices/ui/types.ts index 9e9806bdcd..2bc51cca05 100644 --- a/apps/web/lib/state/slices/ui/types.ts +++ b/apps/web/lib/state/slices/ui/types.ts @@ -44,15 +44,8 @@ export type ActiveDocument = | { type: 'plan'; taskId: string } | { type: 'file'; path: string; name: string }; -export type DocumentComment = { - id: string; - selectedText: string; - comment: string; -}; - export type DocumentPanelState = { activeDocumentBySessionId: Record; - commentsBySessionId: Record; }; export type UISliceState = { @@ -82,7 +75,6 @@ export type UISliceActions = { setMobileSessionTaskSwitcherOpen: (open: boolean) => void; setPlanMode: (sessionId: string, enabled: boolean) => void; setActiveDocument: (sessionId: string, doc: ActiveDocument | null) => void; - setDocumentComments: (sessionId: string, comments: DocumentComment[]) => void; }; export type UISlice = UISliceState & UISliceActions; diff --git a/apps/web/lib/state/slices/ui/ui-slice.ts b/apps/web/lib/state/slices/ui/ui-slice.ts index c43dcefb47..812cc167b8 100644 --- a/apps/web/lib/state/slices/ui/ui-slice.ts +++ b/apps/web/lib/state/slices/ui/ui-slice.ts @@ -1,6 +1,6 @@ import type { StateCreator } from 'zustand'; import { setLocalStorage } from '@/lib/local-storage'; -import type { ActiveDocument, DocumentComment, UISlice, UISliceState } from './types'; +import type { ActiveDocument, UISlice, UISliceState } from './types'; export const defaultUIState: UISliceState = { previewPanel: { @@ -17,7 +17,7 @@ export const defaultUIState: UISliceState = { mobileKanban: { activeColumnIndex: 0, isMenuOpen: false }, mobileSession: { activePanelBySessionId: {}, isTaskSwitcherOpen: false }, chatInput: { planModeBySessionId: {} }, - documentPanel: { activeDocumentBySessionId: {}, commentsBySessionId: {} }, + documentPanel: { activeDocumentBySessionId: {} }, }; export const createUISlice: StateCreator = ( @@ -94,8 +94,4 @@ export const createUISlice: StateCreator - set((draft) => { - draft.documentPanel.commentsBySessionId[sessionId] = comments as DocumentComment[]; - }), }); diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts index 0c248ae590..d9cfe05433 100644 --- a/apps/web/lib/state/store.ts +++ b/apps/web/lib/state/store.ts @@ -219,7 +219,6 @@ export type AppState = { setMobileSessionTaskSwitcherOpen: (open: boolean) => void; setPlanMode: (sessionId: string, enabled: boolean) => void; setActiveDocument: (sessionId: string, doc: import('./slices/ui/types').ActiveDocument | null) => void; - setDocumentComments: (sessionId: string, comments: import('./slices/ui/types').DocumentComment[]) => void; setMessages: ( sessionId: string, messages: Message[], diff --git a/apps/web/lib/types/context.ts b/apps/web/lib/types/context.ts index c710e63f67..391a69f045 100644 --- a/apps/web/lib/types/context.ts +++ b/apps/web/lib/types/context.ts @@ -1,5 +1,4 @@ -import type { DiffComment } from '@/lib/diff/types'; -import type { DocumentComment } from '@/lib/state/slices/ui/types'; +import type { DiffComment, PlanComment } from '@/lib/state/slices/comments'; import type { ImageAttachment } from '@/components/task/chat/image-attachment-preview'; type ContextItemBase = { @@ -38,7 +37,7 @@ export type CommentContextItem = ContextItemBase & { export type PlanCommentContextItem = ContextItemBase & { kind: 'plan-comment'; - comments: DocumentComment[]; + comments: PlanComment[]; onOpen: () => void; };