feat: improve comment system (#247)

This commit is contained in:
Carlos Florêncio
2026-02-18 19:52:40 +00:00
committed by GitHub
parent 53ae8d57e3
commit 160dba0aaf
39 changed files with 870 additions and 532 deletions
@@ -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
}
@@ -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()
}
+2 -2
View File
@@ -37,7 +37,7 @@ export function CommentDisplay({
<div className="min-w-0 flex-1">
<span className="text-muted-foreground">{lineRange}</span>
<span className="mx-1 text-muted-foreground">·</span>
<span className="break-words">{comment.annotation}</span>
<span className="break-words">{comment.text}</span>
</div>
<div className="flex shrink-0 gap-0.5 opacity-0 group-hover:opacity-100">
{onEdit && (
@@ -111,7 +111,7 @@ export function CommentDisplay({
{/* Comment text */}
<p className="whitespace-pre-wrap text-xs leading-relaxed text-foreground">
{comment.annotation}
{comment.text}
</p>
</div>
);
+1 -1
View File
@@ -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 {
@@ -67,7 +67,7 @@ export function useAnnotationRenderer(opts: UseAnnotationRendererOpts) {
return (
<div className="my-1 px-2">
<CommentForm
initialContent={comment.annotation}
initialContent={comment.text}
onSubmit={(content) => handleCommentUpdate(comment.id, content)}
onCancel={() => setEditingComment(null)}
isEditing
+14 -15
View File
@@ -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(
@@ -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);
@@ -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); }, []);
@@ -84,7 +84,7 @@ export function MonacoCodeEditor({
for (const comment of state.comments) {
const isEditing = state.editingCommentId === comment.id;
const node = isEditing
? <div className="px-2 py-0.5" data-comment-zone><CommentForm initialContent={comment.annotation} onSubmit={(c) => state.handleCommentUpdateRef.current(comment.id, c)} onCancel={() => state.setEditingComment(null)} isEditing /></div>
? <div className="px-2 py-0.5" data-comment-zone><CommentForm initialContent={comment.text} onSubmit={(c) => state.handleCommentUpdateRef.current(comment.id, c)} onCancel={() => state.setEditingComment(null)} isEditing /></div>
: <div className="px-2 py-0.5" data-comment-zone><CommentDisplay comment={comment} onDelete={() => state.handleCommentDeleteRef.current(comment.id)} onEdit={() => state.setEditingComment(comment.id)} showCode={false} compact /></div>;
addZone(comment.endLine, isEditing ? 120 : 32, node);
}
@@ -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,
@@ -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(
@@ -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],
+20 -9
View File
@@ -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<typeof us
return { reviewedFiles: reviewed, staleFiles: stale };
}
function computeCommentCounts(bySession: Record<string, Record<string, DiffComment[]>>, sessionId: string): Record<string, number> {
function computeCommentCounts(
byId: Record<string, import('@/lib/state/slices/comments').Comment>,
sessionCommentIds: string[] | undefined,
): Record<string, number> {
const counts: Record<string, number> = {};
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<ReviewFile[]>(() => 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<string, React.RefObject<HTMLDivElement | null>>(); for (const file of allFiles) refs.set(file.path, createRef<HTMLDivElement>()); return refs; }, [allFiles]);
@@ -14,7 +14,7 @@ export const PlanCommentItem = memo(function PlanCommentItem({ item }: { item: P
&ldquo;{comment.selectedText}&rdquo;
</div>
)}
<div className="break-words">{comment.comment}</div>
<div className="break-words">{comment.text}</div>
</div>
))}
</div>
@@ -120,7 +120,7 @@ export function ReviewCommentsAttachment({
{/* Comment text */}
<p className="whitespace-pre-wrap text-xs leading-relaxed">
{comment.annotation}
{comment.text}
</p>
</div>
))}
@@ -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<string, DiffComment[]>();
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';
@@ -91,7 +91,7 @@ function CommentItem({ comment, onDelete }: { comment: DiffComment; onDelete: (i
{comment.codeContent}
</pre>
)}
<p className="text-xs text-foreground leading-relaxed">{comment.annotation}</p>
<p className="text-xs text-foreground leading-relaxed">{comment.text}</p>
</div>
);
}
@@ -1,5 +0,0 @@
export type PlanComment = {
id: string;
selectedText: string;
comment: string;
};
+16 -11
View File
@@ -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<ReviewFile[]>(() => 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<string, React.RefObject<HTMLDivElement | null>>();
@@ -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;
+44 -38
View File
@@ -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<string, DiffComment[]>;
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<typeof useChatPanelState>, 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<typeof useChatPanelState>, 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 };
}
+3 -49
View File
@@ -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<PlanComment[]>([]);
const [editingCommentId, setEditingCommentId] = useState<string | null>(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,
@@ -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<string, DiffComment[]> = {};
/**
* Get all pending diff comments grouped by file path.
*/
export function usePendingDiffCommentsByFile(): Record<string, DiffComment[]> {
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<string, DiffComment[]> = {};
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]);
}
@@ -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]);
}
@@ -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<PlanComment>);
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,
};
}
+10 -9
View File
@@ -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<kandev-system>\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(
+4 -3
View File
@@ -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]
+7 -24
View File
@@ -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<string, Record<string, DiffComment[]>>;
// 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;
+1
View File
@@ -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}`);
}
}
@@ -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<string>();
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<CommentsSlice>()(
immer<CommentsSlice>((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<Comment>) =>
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;
},
}))
);
@@ -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<string, DiffComment[]>();
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 };
}
@@ -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';
@@ -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;
@@ -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<string, Comment>;
bySession: Record<string, string[]>;
pendingForChat: string[];
editingCommentId: string | null;
};
export type CommentsActions = {
addComment: (comment: Comment) => void;
updateComment: (commentId: string, updates: Partial<Comment>) => 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;
@@ -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<string, DiffComment[]> = {};
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<DiffComment>,
): 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<string>,
): 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<DiffCommentsSlice>()(
persist(
immer<DiffCommentsSlice>((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<DiffComment>) =>
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<string>();
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<string, DiffComment[]>,
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<string, DiffComment[]> = {};
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]);
}
@@ -1,6 +0,0 @@
export {
useDiffCommentsStore,
useFileComments,
usePendingComments,
usePendingCommentsByFile,
} from './diff-comments-slice';
-1
View File
@@ -93,7 +93,6 @@ export type {
MobileSessionPanel,
MobileSessionState,
ActiveDocument,
DocumentComment,
DocumentPanelState,
} from './ui/types';
export type { Repository, Branch } from '@/lib/types/http';
-8
View File
@@ -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<string, ActiveDocument | null>;
commentsBySessionId: Record<string, DocumentComment[]>;
};
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;
+2 -6
View File
@@ -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<UISlice, [['zustand/immer', never]], [], UISlice> = (
@@ -94,8 +94,4 @@ export const createUISlice: StateCreator<UISlice, [['zustand/immer', never]], []
draft.documentPanel.activeDocumentBySessionId[sessionId] = doc;
setLocalStorage(`active-document-${sessionId}`, doc as ActiveDocument | null);
}),
setDocumentComments: (sessionId, comments) =>
set((draft) => {
draft.documentPanel.commentsBySessionId[sessionId] = comments as DocumentComment[];
}),
});
-1
View File
@@ -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[],
+2 -3
View File
@@ -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;
};