Files
kandev/apps/web/lib/state/store.ts
T
João Salavisa a1013342a3 feat: Real-time Git Status Integration (#8)
* feat: implement real-time git status integration

- Add workspace tracker to monitor git changes every 2 seconds
- Implement WebSocket streaming for git status updates
- Add database persistence for git status in agent session metadata
- Compute diffs backend-side with additions/deletions per file
- Integrate git status into frontend UI (top bar, files panel, changes panel)
- Display real-time ahead/behind commits and line changes
- Show file diffs with syntax highlighting in task view
- Add retry logic for WebSocket connections during reconciliation
- Fix context lifecycle issue in workspace tracker

* refactor: remove debug and unnecessary logging

- Remove debug logs from workspace tracker
- Remove info logs from WebSocket handlers
- Remove verbose git status update logs
- Keep only essential error logs

* fix: compare git diff against remote branch instead of HEAD

- Changed git diff comparison from HEAD to remote tracking branch
- Now shows all changes including committed files that haven't been pushed
- Files committed locally but not pushed will appear in the diff
- Falls back to HEAD if no remote branch is configured

* fix: prevent stale git status when switching tasks

- Clear git status when switching to a new task
- Only accept git.status WebSocket updates for the current task
- Prevents showing git data from previous task when switching

* refactor: remove unused diff stream client code

- Remove diffConn field from agentctl Client struct
- Remove StreamDiff() method (never called)
- Remove CloseDiffStream() method
- Remove DiffUpdate type from client.go
- All diff data is already included in GitStatusUpdate.Files
- Keep server-side diff endpoint in agentctl for potential future use

* refactor: remove unused diff stream server-side code

- Remove /workspace/diff/stream endpoint from agentctl API
- Remove handleDiffStreamWS handler
- Remove DiffUpdate type from workspace_tracker.go
- Remove DiffSubscriber type
- Remove updateDiff() and getDiff() methods
- Remove SubscribeDiff(), UnsubscribeDiff() methods
- Remove notifyDiffSubscribers() method
- Remove GetCurrentDiff() method
- Remove currentDiff field and diffSubscribers map
- All diff data is already included in GitStatusUpdate.Files

* refactor: remove unused output stream code

- Remove /output and /output/stream endpoints from agentctl API
- Remove handleGetOutput and handleOutputStreamWS handlers
- Delete output.go file entirely
- Remove OutputBuffer and related code (buffer.go deleted)
- Remove outputConn field from agentctl Client
- Remove StreamOutput() and CloseOutputStream() methods
- Remove OutputLine type from client.go
- Remove OutputBufferSize config option
- Update readStderr to just log instead of buffering

Output data flows through ACP stream (StreamUpdates) which includes
all session notifications. The separate output stream was never used.
2026-01-12 23:44:29 +00:00

283 lines
9.1 KiB
TypeScript

import type { ReactNode } from 'react';
import type { TaskState as TaskStatus, Comment } from '@/lib/types/http';
import { createStore } from 'zustand/vanilla';
import { immer } from 'zustand/middleware/immer';
export type KanbanState = {
boardId: string | null;
columns: Array<{ id: string; title: string; color: string; position: number }>;
tasks: Array<{
id: string;
columnId: string;
title: string;
description?: string;
position: number;
state?: TaskStatus;
}>;
};
export type WorkspaceState = {
items: Array<{ id: string; name: string }>;
activeId: string | null;
};
export type BoardState = {
items: Array<{ id: string; workspaceId: string; name: string }>;
activeId: string | null;
};
export type TaskState = {
activeTaskId: string | null;
};
export type AgentState = {
agents: Array<{ id: string; status: 'idle' | 'running' | 'error' }>;
};
export type TerminalState = {
terminals: Array<{ id: string; output: string[] }>;
};
export type FileInfo = {
path: string;
status: 'modified' | 'added' | 'deleted' | 'untracked' | 'renamed';
additions?: number;
deletions?: number;
old_path?: string;
diff?: string;
};
export type GitStatusState = {
taskId: string | null;
branch: string | null;
remote_branch: string | null;
modified: string[];
added: string[];
deleted: string[];
untracked: string[];
renamed: string[];
ahead: number;
behind: number;
files: Record<string, FileInfo>;
timestamp: string | null;
};
export type DiffState = {
files: Array<{ path: string; status: 'A' | 'M' | 'D'; plus: number; minus: number }>;
};
export type ConnectionState = {
status: 'disconnected' | 'connecting' | 'connected' | 'error' | 'reconnecting';
error: string | null;
};
export type CommentsState = {
taskId: string | null;
items: Comment[];
isLoading: boolean;
};
export type AppState = {
kanban: KanbanState;
workspaces: WorkspaceState;
boards: BoardState;
tasks: TaskState;
agents: AgentState;
terminal: TerminalState;
diffs: DiffState;
gitStatus: GitStatusState;
connection: ConnectionState;
comments: CommentsState;
hydrate: (state: Partial<AppState>) => void;
setActiveWorkspace: (workspaceId: string | null) => void;
setWorkspaces: (workspaces: WorkspaceState['items']) => void;
setActiveBoard: (boardId: string | null) => void;
setBoards: (boards: BoardState['items']) => void;
setTerminalOutput: (terminalId: string, data: string) => void;
setConnectionStatus: (status: ConnectionState['status'], error?: string | null) => void;
setComments: (taskId: string, comments: Comment[]) => void;
setCommentsTaskId: (taskId: string | null) => void;
addComment: (comment: Comment) => void;
setCommentsLoading: (loading: boolean) => void;
setGitStatus: (taskId: string, gitStatus: Omit<GitStatusState, 'taskId'>) => void;
clearGitStatus: () => void;
};
export type AppStore = ReturnType<typeof createAppStore>;
const defaultState: AppState = {
kanban: { boardId: null, columns: [], tasks: [] },
workspaces: { items: [], activeId: null },
boards: { items: [], activeId: null },
tasks: { activeTaskId: null },
agents: { agents: [] },
terminal: { terminals: [] },
diffs: { files: [] },
gitStatus: {
taskId: null,
branch: null,
remote_branch: null,
modified: [],
added: [],
deleted: [],
untracked: [],
renamed: [],
ahead: 0,
behind: 0,
files: {},
timestamp: null,
},
connection: { status: 'disconnected', error: null },
comments: { taskId: null, items: [], isLoading: false },
hydrate: () => undefined,
setActiveWorkspace: () => undefined,
setWorkspaces: () => undefined,
setActiveBoard: () => undefined,
setBoards: () => undefined,
setTerminalOutput: () => undefined,
setConnectionStatus: () => undefined,
setComments: () => undefined,
setCommentsTaskId: () => undefined,
addComment: () => undefined,
setCommentsLoading: () => undefined,
setGitStatus: () => undefined,
clearGitStatus: () => undefined,
};
function mergeInitialState(initialState?: Partial<AppState>): Omit<AppState, 'hydrate' | 'setActiveWorkspace' | 'setWorkspaces' | 'setActiveBoard' | 'setBoards' | 'setTerminalOutput' | 'setConnectionStatus' | 'setComments' | 'setCommentsTaskId' | 'addComment' | 'setCommentsLoading' | 'setGitStatus' | 'clearGitStatus'> {
if (!initialState) return defaultState;
return {
workspaces: { ...defaultState.workspaces, ...initialState.workspaces },
boards: { ...defaultState.boards, ...initialState.boards },
kanban: { ...defaultState.kanban, ...initialState.kanban },
tasks: { ...defaultState.tasks, ...initialState.tasks },
agents: { ...defaultState.agents, ...initialState.agents },
terminal: { ...defaultState.terminal, ...initialState.terminal },
diffs: { ...defaultState.diffs, ...initialState.diffs },
gitStatus: { ...defaultState.gitStatus, ...initialState.gitStatus },
connection: { ...defaultState.connection, ...initialState.connection },
comments: { ...defaultState.comments, ...initialState.comments },
};
}
export function createAppStore(initialState?: Partial<AppState>) {
const merged = mergeInitialState(initialState);
return createStore<AppState>()(
immer((set) => ({
...merged,
hydrate: (state) =>
set((draft) => {
// Deep merge to avoid overwriting nested objects with undefined
if (state.workspaces) Object.assign(draft.workspaces, state.workspaces);
if (state.boards) Object.assign(draft.boards, state.boards);
if (state.kanban) Object.assign(draft.kanban, state.kanban);
if (state.tasks) Object.assign(draft.tasks, state.tasks);
if (state.agents) Object.assign(draft.agents, state.agents);
if (state.terminal) Object.assign(draft.terminal, state.terminal);
if (state.diffs) Object.assign(draft.diffs, state.diffs);
if (state.connection) Object.assign(draft.connection, state.connection);
if (state.comments) Object.assign(draft.comments, state.comments);
}),
setActiveWorkspace: (workspaceId) =>
set((draft) => {
draft.workspaces.activeId = workspaceId;
}),
setWorkspaces: (workspaces) =>
set((draft) => {
draft.workspaces.items = workspaces;
if (!draft.workspaces.activeId && workspaces.length) {
draft.workspaces.activeId = workspaces[0].id;
}
}),
setBoards: (boards) =>
set((draft) => {
draft.boards.items = boards;
if (!draft.boards.activeId && boards.length) {
draft.boards.activeId = boards[0].id;
}
}),
setActiveBoard: (boardId) =>
set((draft) => {
draft.boards.activeId = boardId;
}),
setTerminalOutput: (terminalId, data) =>
set((draft) => {
const existing = draft.terminal.terminals.find((terminal) => terminal.id === terminalId);
if (existing) {
existing.output.push(data);
} else {
draft.terminal.terminals.push({ id: terminalId, output: [data] });
}
}),
setConnectionStatus: (status, error = null) =>
set((draft) => {
draft.connection.status = status;
draft.connection.error = error;
}),
setComments: (taskId, comments) =>
set((draft) => {
draft.comments.taskId = taskId;
draft.comments.items = comments;
draft.comments.isLoading = false;
}),
setCommentsTaskId: (taskId) =>
set((draft) => {
draft.comments.taskId = taskId;
// Initialize items array if null to allow addComment to work
// before setComments is called
if (draft.comments.items === null) {
draft.comments.items = [];
}
}),
addComment: (comment) =>
set((draft) => {
// Initialize items array if null
if (draft.comments.items === null) {
draft.comments.items = [];
}
// Only add if this comment is for the current task
if (draft.comments.taskId === comment.task_id) {
// Check if comment already exists (avoid duplicates)
const exists = draft.comments.items.some((c) => c.id === comment.id);
if (!exists) {
draft.comments.items.push(comment);
}
}
}),
setCommentsLoading: (loading) =>
set((draft) => {
draft.comments.isLoading = loading;
}),
setGitStatus: (taskId, gitStatus) =>
set((draft) => {
draft.gitStatus = {
taskId,
...gitStatus,
};
}),
clearGitStatus: () =>
set((draft) => {
draft.gitStatus = {
taskId: null,
branch: null,
remote_branch: null,
modified: [],
added: [],
deleted: [],
untracked: [],
renamed: [],
ahead: 0,
behind: 0,
files: {},
timestamp: null,
};
}),
}))
);
}
export type StoreProviderProps = {
children: ReactNode;
initialState?: Partial<AppState>;
};