mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-02-15 13:17:32 +00:00
* feat: improve version comparison logic in useVersionCheck hook
* refactor: useVersionCheck.js to typescript
* refactor: move VersionUpgradeModal component to its own file and remove it from AppContent component
* refactor: improve VersionUpgradeModal props and extract ReleaseInfo type
Using useVersionCheck hook in 2 places caused github requests to be made twice, which is not ideal.
* refactor: handleUpdateNow function with useCallback and error display in VersionUpgradeModal
* refactor: move isOpen check to the correct position in VersionUpgradeModal
* refactor: move VersionUpgradeModal and collapsed sidebar to Sidebar component from App.jsx
* refactor: remove unused SettingsIcon import from App.jsx
* refactor: move formatTimeAgo function to dateUtils.ts
* refactor: replace useLocalStorage with useUiPreferences for better state management in AppContent
* refactor: use shared props for Sidebar props in AppContent
* refactor: remove showQuickSettings state and toggle from AppContent, manage isOpen state directly in QuickSettingsPanel
* refactor: move preference props directly to QuickSettingsPanel and MainContent
* refactor: remove unused isPWA prop
* refactor: remove unused isPWA prop from AppContent
* refactor: remove unused generatingSummary state from Sidebar component
* refactor: remove unused isPWA prop from MainContent component
* refactor: use usePrefrences for sidebar visibility in Sidebar component
* refactor: extract device detection into hook and localize PWA handling to Sidebar
- Add new `useDeviceSettings` hook (`src/hooks/useDeviceSettings.ts`) to centralize
device-related state:
- exposes `isMobile` and `isPWA`
- supports options: `mobileBreakpoint`, `trackMobile`, `trackPWA`
- listens to window resize for mobile updates
- listens to `display-mode: standalone` changes for PWA updates
- includes `matchMedia.addListener/removeListener` fallback for older environments
- Update `AppContent` (`src/App.jsx`) to consume `isMobile` from
`useDeviceSettings({ trackPWA: false })`:
- remove local `isMobile` state/effect
- remove local `isPWA` state/effect
- keep existing `isMobile` behavior for layout and mobile sidebar flow
- stop passing `isPWA` into `Sidebar` props
- Update `Sidebar` (`src/components/Sidebar.jsx`) to own PWA detection:
- consume `isPWA` from `useDeviceSettings({ trackMobile: false })`
- add effect to toggle `pwa-mode` class on `document.documentElement` and `document.body`
- retain use of `isMobile` prop from `App` for sidebar/mobile rendering decisions
Why:
- removes duplicated device-detection logic from `AppContent`
- makes device-state logic reusable and easier to maintain
- keeps PWA-specific behavior where it is actually used (`Sidebar`)
* chore(to-remove): comment todo's
* refactor: remove unused createNewProject and cancelNewProject functions from Sidebar component
* refactor(sidebar): extract typed app/sidebar architecture and split Sidebar into modular components
- Replace `src/App.jsx` with `src/App.tsx` and move route-level UI orchestration into `src/components/app/AppContent.tsx`.
This separates provider/bootstrap concerns from runtime app layout logic, keeps route definitions minimal, and improves readability of the root app entry.
- Introduce `src/hooks/useProjectsState.ts` to centralize project/session/sidebar state management previously embedded in `App.jsx`.
This keeps the existing behavior for:
project loading,
Cursor session hydration,
WebSocket `loading_progress` handling,
additive-update protection for active sessions,
URL-based session selection,
sidebar refresh/delete/new-session flows.
The hook now exposes a typed `sidebarSharedProps` contract and typed handlers used by `AppContent`.
- Introduce `src/hooks/useSessionProtection.ts` for active/processing session lifecycle logic.
This preserves session-protection behavior while isolating `activeSessions`, `processingSessions`, and temporary-session replacement into a dedicated reusable hook.
- Replace monolithic `src/components/Sidebar.jsx` with typed `src/components/Sidebar.tsx` as a thin orchestrator.
`Sidebar.tsx` now focuses on wiring controller state/actions, modal visibility, collapsed mode, and version modal behavior instead of rendering every UI branch inline.
- Add `src/hooks/useSidebarController.ts` to encapsulate sidebar interaction/state logic.
This includes expand/collapse state, inline project/session editing state, project starring/sorting/filtering, lazy session pagination, delete confirmations, rename/delete actions, refresh state, and mobile touch click handling.
- Add strongly typed sidebar domain models in `src/components/sidebar/types.ts` and move sidebar-derived helpers into `src/components/sidebar/utils.ts`.
Utility coverage now includes:
session provider normalization,
session view-model creation (name/time/activity/message count),
project sorting/filtering,
task indicator status derivation,
starred-project persistence and readbacks.
- Split sidebar rendering into focused components under `src/components/sidebar/`:
`SidebarContent.tsx` for top-level sidebar layout composition.
`SidebarProjectList.tsx` for project-state branching and project iteration.
`SidebarProjectsState.tsx` for loading/empty/no-search-result placeholders.
`SidebarProjectItem.tsx` for per-project desktop/mobile header rendering and actions.
`SidebarProjectSessions.tsx` for expanded session area, skeletons, pagination, and new-session controls.
`SidebarSessionItem.tsx` for per-session desktop/mobile item rendering and session actions.
`SessionProviderIcon.tsx` for provider icon normalization.
`SidebarHeader.tsx`, `SidebarFooter.tsx`, `SidebarCollapsed.tsx`, and `SidebarModals.tsx` as dedicated typed UI surfaces.
This keeps rendering responsibilities local and significantly improves traceability.
- Convert shared UI primitives from JSX to TSX:
`src/components/ui/button.tsx`,
`src/components/ui/input.tsx`,
`src/components/ui/badge.tsx`,
`src/components/ui/scroll-area.tsx`.
These now provide typed props/variants (`forwardRef` where appropriate) while preserving existing class/behavior.
- Add shared app typings in `src/types/app.ts` for projects/sessions/websocket/loading contracts used by new hooks/components.
- Add global window declarations in `src/types/global.d.ts` for `__ROUTER_BASENAME__`, `refreshProjects`, and `openSettings`, removing implicit `any` usage for global integration points.
- Update `src/main.jsx` to import `App.tsx` and keep app bootstrap consistent with the TS migration.
- Update `src/components/QuickSettingsPanel.jsx` to self-resolve mobile state via `useDeviceSettings` (remove `isMobile` prop dependency), and update `src/components/ChatInterface.jsx` to render `QuickSettingsPanel` directly.
This reduces prop drilling and keeps quick settings colocated with chat UI concerns.
* refactor(sidebar): integrate settings modal into SidebarModals and update props
* fix(mobile): prevent menu tap from triggering unintended dashboard navigation
The mobile sidebar menu button redirects users to `cloudcli.ai/dashboard` when a
session was active. The redirect happened because
the menu was opened on `touchstart`, which mounted the sidebar before the touch
sequence completed; the follow-up tap/click then landed on the sidebar header
anchor.
This change rewrites mobile menu interaction handling in `MainContent.jsx` to
eliminate touch/click event leakage and ghost-click behavior.
Key changes:
- Added `suppressNextMenuClickRef` to guard against synthetic click events that
fire after a touch interaction.
- Added `openMobileMenu(event)` helper to centralize `preventDefault`,
`stopPropagation`, and `onMenuClick()` invocation.
- Added `handleMobileMenuTouchEnd(event)`:
- opens the menu on `touchend` instead of `touchstart`
- sets a short suppression window (350ms) for the next click.
- Added `handleMobileMenuClick(event)`:
- ignores/suppresses click events during the suppression window
- otherwise opens the menu normally.
- Updated all mobile menu button instances in `MainContent.jsx` (loading state,
no-project state, active header state) to use:
- `onTouchEnd={handleMobileMenuTouchEnd}`
- `onClick={handleMobileMenuClick}`
- Removed the previous `onTouchStart` path that caused premature DOM mutation.
Behavioral impact:
- Mobile sidebar still opens reliably with one tap.
- Tap no longer leaks to newly-mounted sidebar header links.
- Prevents accidental redirects while preserving existing menu UX.
* refactor(main-content): migrate MainContent to TypeScript and modularize UI/state boundaries
Replace the previous monolithic MainContent.jsx with a typed one and
extract focused subcomponents/hooks to improve readability, local state ownership,
and maintainability while keeping runtime behavior unchanged.
Key changes:
- Replace `src/components/MainContent.jsx` with `src/components/MainContent.tsx`.
- Add typed contracts for main-content domain in `src/components/main-content/types.ts`.
- Extract header composition into:
- `MainContentHeader.tsx`
- `MainContentTitle.tsx`
- `MainContentTabSwitcher.tsx`
- `MobileMenuButton.tsx`
- Extract loading/empty project views into `MainContentStateView.tsx`.
- Extract editor presentation into `EditorSidebar.tsx`.
- Move editor file-open + resize behavior into `useEditorSidebar.ts`.
- Move mobile menu touch/click suppression logic into `useMobileMenuHandlers.ts`.
- Extract TaskMaster-specific concerns into `TaskMasterPanel.tsx`:
- task detail modal state
- PRD editor modal state
- PRD list loading/refresh
- PRD save notification lifecycle
Behavior/compatibility notes:
- Preserve existing tab behavior, session passthrough props, and Chat/Git/File flows.
- Keep interop with existing JS components via boundary `as any` casts where needed.
- No intentional functional changes; this commit is structural/type-oriented refactor.
Validation:
- `npm run typecheck` passes.
- `npm run build` passes (existing unrelated CSS minify warnings remain).
* refactor(chat): split monolithic chat interface into typed modules and hooks
Replace the legacy monolithic ChatInterface.jsx implementation with a modular TypeScript architecture centered around a small orchestration component (ChatInterface.tsx).
Core architecture changes:
- Remove src/components/ChatInterface.jsx and add src/components/ChatInterface.tsx as a thin coordinator that wires provider state, session state, realtime WebSocket handlers, and composer behavior via dedicated hooks.
- Update src/components/MainContent.tsx to use typed ChatInterface directly (remove AnyChatInterface cast).
State ownership and hook extraction:
- Add src/hooks/chat/useChatProviderState.ts to centralize provider/model/permission-mode state, provider/session synchronization, cursor model bootstrap from backend config, and pending permission request scoping.
- Add src/hooks/chat/useChatSessionState.ts to own chat/session lifecycle state: session loading, cursor/claude/codex history loading, pagination, scroll restoration, visible-window slicing, token budget loading, persisted chat hydration, and processing-state restoration.
- Add src/hooks/chat/useChatRealtimeHandlers.ts to isolate WebSocket event processing for Claude/Cursor/Codex, including session filtering, streaming chunk buffering, session-created/pending-session transitions, permission request queueing/cancellation, completion/error handling, and session status updates.
- Add src/hooks/chat/useChatComposerState.ts to own composer-local state and interactions: input/draft persistence, textarea sizing and keyboard behavior, slash command execution, file mentions, image attachment/drop/paste workflow, submit/abort flows, permission decision responses, and transcript insertion.
UI modularization under src/components/chat:
- Add view/ChatMessagesPane.tsx for message list rendering, loading/empty states, pagination affordances, and thinking indicator.
- Add view/ChatComposer.tsx for composer shell layout and input area composition.
- Add view/ChatInputControls.tsx for mode toggles, token display, command launcher, clear-input, and scroll-to-bottom controls.
- Add view/PermissionRequestsBanner.tsx for explicit tool-permission review actions (allow once / allow & remember / deny).
- Add view/ProviderSelectionEmptyState.tsx for provider and model selection UX plus task starter integration.
- Add messages/MessageComponent.tsx and markdown/Markdown.tsx to isolate message rendering concerns, markdown/code rendering, and rich tool-output presentation.
- Add input/ImageAttachment.tsx for attachment previews/removal/progress/error overlay rendering.
Shared chat typing and utilities:
- Add src/components/chat/types.ts with shared types for providers, permission mode, message/tool payloads, pending permission requests, and ChatInterfaceProps.
- Add src/components/chat/utils/chatFormatting.ts for html decoding, code fence normalization, regex escaping, math-safe unescaping, and usage-limit text formatting.
- Add src/components/chat/utils/chatPermissions.ts for permission rule derivation, suggestion generation, and grant flow.
- Add src/components/chat/utils/chatStorage.ts for resilient localStorage access, quota handling, and normalized Claude settings retrieval.
- Add src/components/chat/utils/messageTransforms.ts for session message normalization (Claude/Codex/Cursor) and cached diff computation utilities.
Command/file input ergonomics:
- Add src/hooks/chat/useSlashCommands.ts for slash command fetching, usage-based ranking, fuzzy filtering, keyboard navigation, and command history persistence.
- Add src/hooks/chat/useFileMentions.tsx for project file flattening, @mention suggestions, mention highlighting, and keyboard/file insertion behavior.
TypeScript support additions:
- Add src/types/react-syntax-highlighter.d.ts module declarations to type-check markdown code highlighting imports.
Behavioral intent:
- Preserve existing chat behavior and provider flows while improving readability, separation of concerns, and future refactorability.
- Move state closer to the components/hooks that own it, reducing cross-cutting concerns in the top-level chat component.
* perf(project-loading): eliminate repeated Codex session rescans and duplicate cursor fetches
The staged changes remove the main source of project-load latency by avoiding repeated full scans of ~/.codex/sessions for every project and by removing redundant client-side cursor session refetches.
Server changes (server/projects.js):\n- Add a per-request Codex index reference in getProjects so Codex metadata is built once and reused across all projects, including manually added ones.\n- Introduce normalizeComparablePath() to canonicalize project paths (including Windows long-path prefixes and case-insensitive matching on Windows).\n- Introduce findCodexJsonlFiles() + buildCodexSessionsIndex() to perform a single recursive Codex scan and group sessions by normalized cwd.\n- Update getCodexSessions() to accept indexRef and read from the prebuilt index, with fallback index construction when no ref is provided.\n- Preserve existing session limiting behavior (limit=5 default, limit=0 returns all).
Client changes (src/hooks/useProjectsState.ts):\n- Remove loadCursorSessionsForProjects(), which previously triggered one extra /api/cursor/sessions request per project after /api/projects.\n- Use /api/projects response directly during initial load and refresh.\n- Expand projectsHaveChanges() to treat both cursorSessions and codexSessions as external session deltas.\n- Keep refresh comparison aligned with external session updates by using includeExternalSessions=true in sidebar refresh path.
Impact:\n- Reduces backend work from roughly O(projects * codex_session_files) to O(codex_session_files + projects) for Codex discovery during a project load cycle.\n- Removes an additional client-side O(projects) network fan-out for Cursor session fetches.\n- Improves perceived and actual sidebar project-loading time, especially in large session datasets.
* fix(chat): make Stop and Esc reliably abort active sessions
Problem
Stop requests were unreliable because aborting depended on currentSessionId being set, Esc had no actual global abort binding, stale pending session ids could be reused, and abort failures were surfaced as successful interruptions. Codex sessions also used a soft abort flag without wiring SDK cancellation.
Changes
- Add global Escape key handler in chat while a run is loading/cancellable to trigger the same abort path as the Stop button.
- Harden abort session target selection in composer by resolving from multiple active session id sources (current, pending view, pending storage, cursor storage, selected session) and ignoring temporary new-session-* ids.
- Clear stale pendingSessionId when launching a brand-new session to prevent aborting an old run.
- Update realtime abort handling to respect backend success=false responses: keep loading state when abort fails and emit an explicit failure message instead of pretending interruption succeeded.
- Improve websocket send reliability by checking socket.readyState === WebSocket.OPEN directly before send.
- Implement real Codex cancellation via AbortController + runStreamed(..., { signal }), propagate aborted status, and suppress expected abort-error noise.
Impact
This makes both UI Stop and Esc-to-stop materially more reliable across Claude/Cursor/Codex flows, especially during early-session windows before currentSessionId is finalized, and prevents false-positive interrupted states when backend cancellation fails.
Validation
- npm run -s typecheck
- npm run -s build
- node --check server/openai-codex.js
* refactor: tool components
* refactor: tool components
* fix: remove one-line logic from messagecomponent
* refactor(design): change the design of bash
* refactor(design): fix bash design and config
* refactor(design): change the design of tools and introduce todo list and task list.
* refactor(improvement):add memo on diffviewer, cleanup messsagecomponent
* refactor: update readme and remove unusedfiles.
* refactor(sidebar): remove duplicate loading message in SidebarProjectsState
* refactor(sidebar): move VersionUpgradeModal into SidebarModals
* refactor: replace individual provider logos with a unified SessionProviderLogo component
* fix(commands): restore /cost slash command and improve command execution errors
The /cost command was listed as built-in but had no handler, causing execution to
fall through to custom command logic and return 400 ("command path is required").
- Add a built-in /cost handler in server/routes/commands.js
- Return the expected payload shape for the chat UI (`action: "cost"`, token usage,
estimated cost, model)
- Normalize token usage inputs and compute usage percentage
- Add provider-based default pricing for cost estimation
- Fix model selection in command execution context so codex uses `codexModel`
instead of `claudeModel`
- Improve frontend command error handling by parsing backend error responses and
showing meaningful error messages instead of a generic failure
* fix(command-menu): correct slash command selection with frequent commands
When the “Frequently Used” section is visible, command clicks/hover could use a
UI-local index instead of the canonical `filteredCommands` index, causing the
wrong command to execute (e.g. clicking `/help` running `/clear`).
- map rendered menu items back to canonical command indices using a stable key
(`name + namespace/type + path`)
- use canonical index for hover/click selection callbacks
- deduplicate frequent commands from other grouped sections to avoid duplicate
rows and selection ambiguity
- keep and restore original inline comments, with clarifications where needed
* refactor(sidebar): update sessionMeta handling for session loading logic
- This fixes an issue where the sidebar was showing 6+ even when there were only 5 sessions, due to the hasMore logic not accounting for the case where there are exactly 6 sessions.
It was also showing "Show more sessions" even where there were no more sessions to load.
- This was because `hasMore` was sometimes `undefined` and the logic checked for hasMore !== false, which treated undefined as true.
Now we explicitly check for hasMore === true to determine if there are more sessions to load.
* refactor(project-watcher): add codex and cursor file watchers
* fix: chat session scroll to bottom error even when scrolled up
* fix(chat): clear stuck loading state across realtime lifecycle events
The chat UI could remain in a stale "Thinking/Processing" state when session IDs
did not line up exactly between view state (`currentSessionId`), selected route
session, pending session IDs, and provider lifecycle events. This was most visible
with Codex completion/abort flows, but the same mismatch risk existed in shared
handlers.
Unify lifecycle cleanup behavior in realtime handlers and make processing tracking
key off the active viewed session identity.
Changes:
- src/hooks/chat/useChatRealtimeHandlers.ts
- src/components/ChatInterface.tsx
- src/hooks/chat/useChatSessionState.ts
What changed:
- Added shared helpers in realtime handling:
- `collectSessionIds(...)` to normalize and dedupe candidate session IDs.
- `clearLoadingIndicators()` to consistently clear `isLoading`, abort UI, and status.
- `markSessionsAsCompleted(...)` to consistently notify inactive/not-processing state.
- Updated lifecycle branches to use shared cleanup logic:
- `cursor-result`
- `claude-complete`
- `codex-response` (`turn_complete` and `turn_failed`)
- `codex-complete`
- `session-aborted`
- Expanded completion/abort cleanup to include all relevant session IDs
(`latestMessage.sessionId`, `currentSessionId`, `selectedSession?.id`,
`pendingSessionId`, and Codex `actualSessionId` when present).
- Switched processing-session marking in `ChatInterface` to use
`selectedSession?.id || currentSessionId` instead of `currentSessionId` alone.
- Switched processing-session rehydration in `useChatSessionState` to use
the same active-view session identity fallback.
Result:
- Prevents stale loading indicators after completion/abort when IDs differ.
- Keeps processing session bookkeeping aligned with the currently viewed session.
- Reduces provider-specific drift by using one lifecycle cleanup pattern.
* fix(chat): stabilize long-history scroll-up pagination behavior
- fix top-pagination lockups by only locking when older messages are actually fetched
- make fetched older messages visible immediately by increasing `visibleMessageCount` on prepend
- prevent unintended auto-scroll-to-bottom during older-message loading and scroll restore
- replace state-based pagination offset with a ref to avoid stale offset/reload side effects
- ensure initial auto-scroll runs only after initial session load completes
- reset top-load lock/restore state and visible window when switching sessions
- loosen top-lock release near the top to avoid requiring a full down/up cycle
* refactor: Restructure files and folders to better mimic feature-based architecture
* refactor: reorganize chat view components and types
* feat(chat): move thinking modes, token usage pie, and related logic into chat folder
* refactor(tools): add agent category for Task tool
Add visual distinction for the Task tool (subagent invocation) by
introducing a new 'agent' category with purple border styling. This
separates subagent tasks from regular task management tools
(TaskCreate, TaskUpdate, etc.) for clearer user feedback.
Also refactor terminal command layout in OneLineDisplay to properly
nest flex containers, fixing copy button alignment issues.
* refactor(tools): improve Task tool display formatting
Update Task tool config to show cleaner subagent information in the UI.
Simplifies the input display by showing only the prompt when no
optional fields are present, reducing visual clutter. Updates title
format to "Subagent / {type}" for better categorization. Enhances
result display to better handle complex agent response structures with
array content types, extracting text blocks for cleaner presentation.
* fix: show auth url panel in shell only on mobile
- use static url: https://auth.openai.com/codex/device, for codex login.
- add an option for hiding the panel
* fix(chat): escape command name in regex to prevent unintended matches
* fix(chat): handle JSON parsing errors for saved chat messages
* refactor(chat): replace localStorage provider retrieval with prop usage in MessageComponent
* fix(chat): handle potential null content in message before splitting lines
* refactor(todo): update TodoListContentProps to include optional id and priority fields that are used in TodoList.jsx
* fix(watcher): ensure provider folders exist before creating watchers to maintain active watching
* refactor(chat): improve message handling by cloning state updates and improving structured message parsing
* refactor(chat): exclude currentSessionId from dependency array to prevent unnecessary reloading of messages
* refactor(useFileMentions): implement abort controller for fetch requests
* refactor(MessageComponent): add types
* refactor(calculateDiff): optimize LCS algorithm for improved diff calculation
* refactor(createCachedDiffCalculator): use both newStr and oldStr as cache keys
* refactor(useSidebarController): manage project session overrides in local state
* refactor(ScrollArea): adjust ref placement and className order
* fix: type annotations
* refactor(ChatInputControls): update import statement for ThinkingModeSelector
* refactor(dateUtils): update type annotation for formatTimeAgo function
* refactor(ToolRenderer): ensure stable hook order
* refactor(useProjectsState): normalize refreshed session metadata to maintain provider stability; use getProjectSessions helper for session retrieval.
* refactor(useChatComposerState): improve input handling and command execution flow
* refactor(useChatRealtimeHandlers): normalize interactive prompt content to string for consistent ChatMessage shape
* refactor(OneLineDisplay): improve clipboard functionality with fallback for unsupported environments
* refactor(QuickSettingsPanel): simplify state management by removing localIsOpen and using isOpen directly
* refactor(ChatMessagesPane): use stable message key
* refactor:: move AssistantThinkingIndicator component to its own file
* refactor(ChatMessagesPane): extract message key generation logic to a utility function
* refactor(SidebarModals): move normalizeProjectForSettings into utils file
* refactor(ToolConfigs): use optional chaining for content retrieval
* fix(chat): stabilize provider/message handling and complete chat i18n coverage
Unify provider typing, harden realtime message effects, normalize tool input
serialization, and finish i18n/a11y updates across chat UI components.
- tighten provider contracts from `Provider | string` to `SessionProvider` in:
- `useChatProviderState`
- `useChatComposerState`
- `useChatRealtimeHandlers`
- `ChatMessagesPane`
- `ProviderSelectionEmptyState`
- refactor `AssistantThinkingIndicator` to accept `selectedProvider` via props
instead of reading provider from local storage during render
- fix stale-closure risk in `useChatRealtimeHandlers` by:
- adding missing effect dependencies
- introducing `lastProcessedMessageRef` to prevent duplicate processing when
dependencies change without a new message object
- standardize `toolInput` shape in `messageTransforms`:
- add `normalizeToolInput(...)`
- ensure all conversion paths produce consistent string output
- remove mixed `null`/raw/stringified variants across cursor/session branches
- harden tool display fallback in `CollapsibleDisplay`:
- default border class now falls back safely for unknown categories
- improve chat i18n consistency:
- localize hardcoded strings in `MessageComponent`
(`permissions.*`, `interactive.*`, `thinking.emoji`, `json.response`,
`messageTypes.error`)
- localize button titles in `ChatInputControls`
(`input.clearInput`, `input.scrollToBottom`)
- localize provider-specific empty-project prompt in `ChatInterface`
(`projectSelection.startChatWithProvider`)
- localize repeated “Start the next task” prompt in
`ProviderSelectionEmptyState` (`tasks.nextTaskPrompt`)
- add missing translation keys in all supported chat locales:
- `src/i18n/locales/en/chat.json`
- `src/i18n/locales/ko/chat.json`
- `src/i18n/locales/zh-CN/chat.json`
- new keys:
- `input.clearInput`
- `input.scrollToBottom`
- `projectSelection.startChatWithProvider`
- `tasks.nextTaskPrompt`
- improve attachment remove-button accessibility in `ImageAttachment`:
- add `type="button"` and `aria-label`
- make control visible on touch/small screens and focusable states
- preserve hover behavior on larger screens
Validation:
- `npm run typecheck`
* fix(chat): sync quick settings state and stabilize thinking toggle
Synchronize useUiPreferences instances via custom sync events and storage listeners so Quick Settings updates apply across UI consumers immediately.
Also hide standalone thinking messages when showThinking is disabled, while preserving hook order to avoid Rendered fewer hooks runtime errors.
* refactor(validateGitRepository): improve directory validation for git work tree
* refactor(GitPanel): clear stale state on project change and improve error handling
* refactor(git): use spawnAsync for command execution and improve commit log retrieval
* fix: iOS pwa bottom margin
* fix: pass diff information to code editor
* refactor(sidebar): remove touch event handlers from project and session items
* bumping node to v22
* Release 1.17.0
---------
Co-authored-by: Haileyesus <something@gmail.com>
Co-authored-by: simosmik <simosmik@gmail.com>
1169 lines
39 KiB
JavaScript
Executable File
1169 lines
39 KiB
JavaScript
Executable File
import express from 'express';
|
|
import { exec, spawn } from 'child_process';
|
|
import { promisify } from 'util';
|
|
import path from 'path';
|
|
import { promises as fs } from 'fs';
|
|
import { extractProjectDirectory } from '../projects.js';
|
|
import { queryClaudeSDK } from '../claude-sdk.js';
|
|
import { spawnCursor } from '../cursor-cli.js';
|
|
|
|
const router = express.Router();
|
|
const execAsync = promisify(exec);
|
|
|
|
function spawnAsync(command, args, options = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn(command, args, {
|
|
...options,
|
|
shell: false,
|
|
});
|
|
|
|
let stdout = '';
|
|
let stderr = '';
|
|
|
|
child.stdout.on('data', (data) => {
|
|
stdout += data.toString();
|
|
});
|
|
|
|
child.stderr.on('data', (data) => {
|
|
stderr += data.toString();
|
|
});
|
|
|
|
child.on('error', (error) => {
|
|
reject(error);
|
|
});
|
|
|
|
child.on('close', (code) => {
|
|
if (code === 0) {
|
|
resolve({ stdout, stderr });
|
|
return;
|
|
}
|
|
|
|
const error = new Error(`Command failed: ${command} ${args.join(' ')}`);
|
|
error.code = code;
|
|
error.stdout = stdout;
|
|
error.stderr = stderr;
|
|
reject(error);
|
|
});
|
|
});
|
|
}
|
|
|
|
// Helper function to get the actual project path from the encoded project name
|
|
async function getActualProjectPath(projectName) {
|
|
try {
|
|
return await extractProjectDirectory(projectName);
|
|
} catch (error) {
|
|
console.error(`Error extracting project directory for ${projectName}:`, error);
|
|
// Fallback to the old method
|
|
return projectName.replace(/-/g, '/');
|
|
}
|
|
}
|
|
|
|
// Helper function to strip git diff headers
|
|
function stripDiffHeaders(diff) {
|
|
if (!diff) return '';
|
|
|
|
const lines = diff.split('\n');
|
|
const filteredLines = [];
|
|
let startIncluding = false;
|
|
|
|
for (const line of lines) {
|
|
// Skip all header lines including diff --git, index, file mode, and --- / +++ file paths
|
|
if (line.startsWith('diff --git') ||
|
|
line.startsWith('index ') ||
|
|
line.startsWith('new file mode') ||
|
|
line.startsWith('deleted file mode') ||
|
|
line.startsWith('---') ||
|
|
line.startsWith('+++')) {
|
|
continue;
|
|
}
|
|
|
|
// Start including lines from @@ hunk headers onwards
|
|
if (line.startsWith('@@') || startIncluding) {
|
|
startIncluding = true;
|
|
filteredLines.push(line);
|
|
}
|
|
}
|
|
|
|
return filteredLines.join('\n');
|
|
}
|
|
|
|
// Helper function to validate git repository
|
|
async function validateGitRepository(projectPath) {
|
|
try {
|
|
// Check if directory exists
|
|
await fs.access(projectPath);
|
|
} catch {
|
|
throw new Error(`Project path not found: ${projectPath}`);
|
|
}
|
|
|
|
try {
|
|
// Allow any directory that is inside a work tree (repo root or nested folder).
|
|
const { stdout: insideWorkTreeOutput } = await execAsync('git rev-parse --is-inside-work-tree', { cwd: projectPath });
|
|
const isInsideWorkTree = insideWorkTreeOutput.trim() === 'true';
|
|
if (!isInsideWorkTree) {
|
|
throw new Error('Not inside a git work tree');
|
|
}
|
|
|
|
// Ensure git can resolve the repository root for this directory.
|
|
await execAsync('git rev-parse --show-toplevel', { cwd: projectPath });
|
|
} catch {
|
|
throw new Error('Not a git repository. This directory does not contain a .git folder. Initialize a git repository with "git init" to use source control features.');
|
|
}
|
|
}
|
|
|
|
// Get git status for a project
|
|
router.get('/status', async (req, res) => {
|
|
const { project } = req.query;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Validate git repository
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get current branch - handle case where there are no commits yet
|
|
let branch = 'main';
|
|
let hasCommits = true;
|
|
try {
|
|
const { stdout: branchOutput } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
|
branch = branchOutput.trim();
|
|
} catch (error) {
|
|
// No HEAD exists - repository has no commits yet
|
|
if (error.message.includes('unknown revision') || error.message.includes('ambiguous argument')) {
|
|
hasCommits = false;
|
|
branch = 'main';
|
|
} else {
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
// Get git status
|
|
const { stdout: statusOutput } = await execAsync('git status --porcelain', { cwd: projectPath });
|
|
|
|
const modified = [];
|
|
const added = [];
|
|
const deleted = [];
|
|
const untracked = [];
|
|
|
|
statusOutput.split('\n').forEach(line => {
|
|
if (!line.trim()) return;
|
|
|
|
const status = line.substring(0, 2);
|
|
const file = line.substring(3);
|
|
|
|
if (status === 'M ' || status === ' M' || status === 'MM') {
|
|
modified.push(file);
|
|
} else if (status === 'A ' || status === 'AM') {
|
|
added.push(file);
|
|
} else if (status === 'D ' || status === ' D') {
|
|
deleted.push(file);
|
|
} else if (status === '??') {
|
|
untracked.push(file);
|
|
}
|
|
});
|
|
|
|
res.json({
|
|
branch,
|
|
hasCommits,
|
|
modified,
|
|
added,
|
|
deleted,
|
|
untracked
|
|
});
|
|
} catch (error) {
|
|
console.error('Git status error:', error);
|
|
res.json({
|
|
error: error.message.includes('not a git repository') || error.message.includes('Project directory is not a git repository')
|
|
? error.message
|
|
: 'Git operation failed',
|
|
details: error.message.includes('not a git repository') || error.message.includes('Project directory is not a git repository')
|
|
? error.message
|
|
: `Failed to get git status: ${error.message}`
|
|
});
|
|
}
|
|
});
|
|
|
|
// Get diff for a specific file
|
|
router.get('/diff', async (req, res) => {
|
|
const { project, file } = req.query;
|
|
|
|
if (!project || !file) {
|
|
return res.status(400).json({ error: 'Project name and file path are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Validate git repository
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Check if file is untracked or deleted
|
|
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
|
const isUntracked = statusOutput.startsWith('??');
|
|
const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
|
|
|
|
let diff;
|
|
if (isUntracked) {
|
|
// For untracked files, show the entire file content as additions
|
|
const filePath = path.join(projectPath, file);
|
|
const stats = await fs.stat(filePath);
|
|
|
|
if (stats.isDirectory()) {
|
|
// For directories, show a simple message
|
|
diff = `Directory: ${file}\n(Cannot show diff for directories)`;
|
|
} else {
|
|
const fileContent = await fs.readFile(filePath, 'utf-8');
|
|
const lines = fileContent.split('\n');
|
|
diff = `--- /dev/null\n+++ b/${file}\n@@ -0,0 +1,${lines.length} @@\n` +
|
|
lines.map(line => `+${line}`).join('\n');
|
|
}
|
|
} else if (isDeleted) {
|
|
// For deleted files, show the entire file content from HEAD as deletions
|
|
const { stdout: fileContent } = await execAsync(`git show HEAD:"${file}"`, { cwd: projectPath });
|
|
const lines = fileContent.split('\n');
|
|
diff = `--- a/${file}\n+++ /dev/null\n@@ -1,${lines.length} +0,0 @@\n` +
|
|
lines.map(line => `-${line}`).join('\n');
|
|
} else {
|
|
// Get diff for tracked files
|
|
// First check for unstaged changes (working tree vs index)
|
|
const { stdout: unstagedDiff } = await execAsync(`git diff -- "${file}"`, { cwd: projectPath });
|
|
|
|
if (unstagedDiff) {
|
|
// Show unstaged changes if they exist
|
|
diff = stripDiffHeaders(unstagedDiff);
|
|
} else {
|
|
// If no unstaged changes, check for staged changes (index vs HEAD)
|
|
const { stdout: stagedDiff } = await execAsync(`git diff --cached -- "${file}"`, { cwd: projectPath });
|
|
diff = stripDiffHeaders(stagedDiff) || '';
|
|
}
|
|
}
|
|
|
|
res.json({ diff });
|
|
} catch (error) {
|
|
console.error('Git diff error:', error);
|
|
res.json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Get file content with diff information for CodeEditor
|
|
router.get('/file-with-diff', async (req, res) => {
|
|
const { project, file } = req.query;
|
|
|
|
if (!project || !file) {
|
|
return res.status(400).json({ error: 'Project name and file path are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Validate git repository
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Check file status
|
|
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
|
const isUntracked = statusOutput.startsWith('??');
|
|
const isDeleted = statusOutput.trim().startsWith('D ') || statusOutput.trim().startsWith(' D');
|
|
|
|
let currentContent = '';
|
|
let oldContent = '';
|
|
|
|
if (isDeleted) {
|
|
// For deleted files, get content from HEAD
|
|
const { stdout: headContent } = await execAsync(`git show HEAD:"${file}"`, { cwd: projectPath });
|
|
oldContent = headContent;
|
|
currentContent = headContent; // Show the deleted content in editor
|
|
} else {
|
|
// Get current file content
|
|
const filePath = path.join(projectPath, file);
|
|
const stats = await fs.stat(filePath);
|
|
|
|
if (stats.isDirectory()) {
|
|
// Cannot show content for directories
|
|
return res.status(400).json({ error: 'Cannot show diff for directories' });
|
|
}
|
|
|
|
currentContent = await fs.readFile(filePath, 'utf-8');
|
|
|
|
if (!isUntracked) {
|
|
// Get the old content from HEAD for tracked files
|
|
try {
|
|
const { stdout: headContent } = await execAsync(`git show HEAD:"${file}"`, { cwd: projectPath });
|
|
oldContent = headContent;
|
|
} catch (error) {
|
|
// File might be newly added to git (staged but not committed)
|
|
oldContent = '';
|
|
}
|
|
}
|
|
}
|
|
|
|
res.json({
|
|
currentContent,
|
|
oldContent,
|
|
isDeleted,
|
|
isUntracked
|
|
});
|
|
} catch (error) {
|
|
console.error('Git file-with-diff error:', error);
|
|
res.json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Create initial commit
|
|
router.post('/initial-commit', async (req, res) => {
|
|
const { project } = req.body;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Validate git repository
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Check if there are already commits
|
|
try {
|
|
await execAsync('git rev-parse HEAD', { cwd: projectPath });
|
|
return res.status(400).json({ error: 'Repository already has commits. Use regular commit instead.' });
|
|
} catch (error) {
|
|
// No HEAD - this is good, we can create initial commit
|
|
}
|
|
|
|
// Add all files
|
|
await execAsync('git add .', { cwd: projectPath });
|
|
|
|
// Create initial commit
|
|
const { stdout } = await execAsync('git commit -m "Initial commit"', { cwd: projectPath });
|
|
|
|
res.json({ success: true, output: stdout, message: 'Initial commit created successfully' });
|
|
} catch (error) {
|
|
console.error('Git initial commit error:', error);
|
|
|
|
// Handle the case where there's nothing to commit
|
|
if (error.message.includes('nothing to commit')) {
|
|
return res.status(400).json({
|
|
error: 'Nothing to commit',
|
|
details: 'No files found in the repository. Add some files first.'
|
|
});
|
|
}
|
|
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Commit changes
|
|
router.post('/commit', async (req, res) => {
|
|
const { project, message, files } = req.body;
|
|
|
|
if (!project || !message || !files || files.length === 0) {
|
|
return res.status(400).json({ error: 'Project name, commit message, and files are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Validate git repository
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Stage selected files
|
|
for (const file of files) {
|
|
await execAsync(`git add "${file}"`, { cwd: projectPath });
|
|
}
|
|
|
|
// Commit with message
|
|
const { stdout } = await execAsync(`git commit -m "${message.replace(/"/g, '\\"')}"`, { cwd: projectPath });
|
|
|
|
res.json({ success: true, output: stdout });
|
|
} catch (error) {
|
|
console.error('Git commit error:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Get list of branches
|
|
router.get('/branches', async (req, res) => {
|
|
const { project } = req.query;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Validate git repository
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get all branches
|
|
const { stdout } = await execAsync('git branch -a', { cwd: projectPath });
|
|
|
|
// Parse branches
|
|
const branches = stdout
|
|
.split('\n')
|
|
.map(branch => branch.trim())
|
|
.filter(branch => branch && !branch.includes('->')) // Remove empty lines and HEAD pointer
|
|
.map(branch => {
|
|
// Remove asterisk from current branch
|
|
if (branch.startsWith('* ')) {
|
|
return branch.substring(2);
|
|
}
|
|
// Remove remotes/ prefix
|
|
if (branch.startsWith('remotes/origin/')) {
|
|
return branch.substring(15);
|
|
}
|
|
return branch;
|
|
})
|
|
.filter((branch, index, self) => self.indexOf(branch) === index); // Remove duplicates
|
|
|
|
res.json({ branches });
|
|
} catch (error) {
|
|
console.error('Git branches error:', error);
|
|
res.json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Checkout branch
|
|
router.post('/checkout', async (req, res) => {
|
|
const { project, branch } = req.body;
|
|
|
|
if (!project || !branch) {
|
|
return res.status(400).json({ error: 'Project name and branch are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Checkout the branch
|
|
const { stdout } = await execAsync(`git checkout "${branch}"`, { cwd: projectPath });
|
|
|
|
res.json({ success: true, output: stdout });
|
|
} catch (error) {
|
|
console.error('Git checkout error:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Create new branch
|
|
router.post('/create-branch', async (req, res) => {
|
|
const { project, branch } = req.body;
|
|
|
|
if (!project || !branch) {
|
|
return res.status(400).json({ error: 'Project name and branch name are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Create and checkout new branch
|
|
const { stdout } = await execAsync(`git checkout -b "${branch}"`, { cwd: projectPath });
|
|
|
|
res.json({ success: true, output: stdout });
|
|
} catch (error) {
|
|
console.error('Git create branch error:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Get recent commits
|
|
router.get('/commits', async (req, res) => {
|
|
const { project, limit = 10 } = req.query;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
const parsedLimit = Number.parseInt(String(limit), 10);
|
|
const safeLimit = Number.isFinite(parsedLimit) && parsedLimit > 0
|
|
? Math.min(parsedLimit, 100)
|
|
: 10;
|
|
|
|
// Get commit log with stats
|
|
const { stdout } = await spawnAsync(
|
|
'git',
|
|
['log', '--pretty=format:%H|%an|%ae|%ad|%s', '--date=relative', '-n', String(safeLimit)],
|
|
{ cwd: projectPath },
|
|
);
|
|
|
|
const commits = stdout
|
|
.split('\n')
|
|
.filter(line => line.trim())
|
|
.map(line => {
|
|
const [hash, author, email, date, ...messageParts] = line.split('|');
|
|
return {
|
|
hash,
|
|
author,
|
|
email,
|
|
date,
|
|
message: messageParts.join('|')
|
|
};
|
|
});
|
|
|
|
// Get stats for each commit
|
|
for (const commit of commits) {
|
|
try {
|
|
const { stdout: stats } = await execAsync(
|
|
`git show --stat --format='' ${commit.hash}`,
|
|
{ cwd: projectPath }
|
|
);
|
|
commit.stats = stats.trim().split('\n').pop(); // Get the summary line
|
|
} catch (error) {
|
|
commit.stats = '';
|
|
}
|
|
}
|
|
|
|
res.json({ commits });
|
|
} catch (error) {
|
|
console.error('Git commits error:', error);
|
|
res.json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Get diff for a specific commit
|
|
router.get('/commit-diff', async (req, res) => {
|
|
const { project, commit } = req.query;
|
|
|
|
if (!project || !commit) {
|
|
return res.status(400).json({ error: 'Project name and commit hash are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Get diff for the commit
|
|
const { stdout } = await execAsync(
|
|
`git show ${commit}`,
|
|
{ cwd: projectPath }
|
|
);
|
|
|
|
res.json({ diff: stdout });
|
|
} catch (error) {
|
|
console.error('Git commit diff error:', error);
|
|
res.json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Generate commit message based on staged changes using AI
|
|
router.post('/generate-commit-message', async (req, res) => {
|
|
const { project, files, provider = 'claude' } = req.body;
|
|
|
|
if (!project || !files || files.length === 0) {
|
|
return res.status(400).json({ error: 'Project name and files are required' });
|
|
}
|
|
|
|
// Validate provider
|
|
if (!['claude', 'cursor'].includes(provider)) {
|
|
return res.status(400).json({ error: 'provider must be "claude" or "cursor"' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
|
|
// Get diff for selected files
|
|
let diffContext = '';
|
|
for (const file of files) {
|
|
try {
|
|
const { stdout } = await execAsync(
|
|
`git diff HEAD -- "${file}"`,
|
|
{ cwd: projectPath }
|
|
);
|
|
if (stdout) {
|
|
diffContext += `\n--- ${file} ---\n${stdout}`;
|
|
}
|
|
} catch (error) {
|
|
console.error(`Error getting diff for ${file}:`, error);
|
|
}
|
|
}
|
|
|
|
// If no diff found, might be untracked files
|
|
if (!diffContext.trim()) {
|
|
// Try to get content of untracked files
|
|
for (const file of files) {
|
|
try {
|
|
const filePath = path.join(projectPath, file);
|
|
const stats = await fs.stat(filePath);
|
|
|
|
if (!stats.isDirectory()) {
|
|
const content = await fs.readFile(filePath, 'utf-8');
|
|
diffContext += `\n--- ${file} (new file) ---\n${content.substring(0, 1000)}\n`;
|
|
} else {
|
|
diffContext += `\n--- ${file} (new directory) ---\n`;
|
|
}
|
|
} catch (error) {
|
|
console.error(`Error reading file ${file}:`, error);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Generate commit message using AI
|
|
const message = await generateCommitMessageWithAI(files, diffContext, provider, projectPath);
|
|
|
|
res.json({ message });
|
|
} catch (error) {
|
|
console.error('Generate commit message error:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Generates a commit message using AI (Claude SDK or Cursor CLI)
|
|
* @param {Array<string>} files - List of changed files
|
|
* @param {string} diffContext - Git diff content
|
|
* @param {string} provider - 'claude' or 'cursor'
|
|
* @param {string} projectPath - Project directory path
|
|
* @returns {Promise<string>} Generated commit message
|
|
*/
|
|
async function generateCommitMessageWithAI(files, diffContext, provider, projectPath) {
|
|
// Create the prompt
|
|
const prompt = `Generate a conventional commit message for these changes.
|
|
|
|
REQUIREMENTS:
|
|
- Format: type(scope): subject
|
|
- Include body explaining what changed and why
|
|
- Types: feat, fix, docs, style, refactor, perf, test, build, ci, chore
|
|
- Subject under 50 chars, body wrapped at 72 chars
|
|
- Focus on user-facing changes, not implementation details
|
|
- Consider what's being added AND removed
|
|
- Return ONLY the commit message (no markdown, explanations, or code blocks)
|
|
|
|
FILES CHANGED:
|
|
${files.map(f => `- ${f}`).join('\n')}
|
|
|
|
DIFFS:
|
|
${diffContext.substring(0, 4000)}
|
|
|
|
Generate the commit message:`;
|
|
|
|
try {
|
|
// Create a simple writer that collects the response
|
|
let responseText = '';
|
|
const writer = {
|
|
send: (data) => {
|
|
try {
|
|
const parsed = typeof data === 'string' ? JSON.parse(data) : data;
|
|
console.log('🔍 Writer received message type:', parsed.type);
|
|
|
|
// Handle different message formats from Claude SDK and Cursor CLI
|
|
// Claude SDK sends: {type: 'claude-response', data: {message: {content: [...]}}}
|
|
if (parsed.type === 'claude-response' && parsed.data) {
|
|
const message = parsed.data.message || parsed.data;
|
|
console.log('📦 Claude response message:', JSON.stringify(message, null, 2).substring(0, 500));
|
|
if (message.content && Array.isArray(message.content)) {
|
|
// Extract text from content array
|
|
for (const item of message.content) {
|
|
if (item.type === 'text' && item.text) {
|
|
console.log('✅ Extracted text chunk:', item.text.substring(0, 100));
|
|
responseText += item.text;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Cursor CLI sends: {type: 'cursor-output', output: '...'}
|
|
else if (parsed.type === 'cursor-output' && parsed.output) {
|
|
console.log('✅ Cursor output:', parsed.output.substring(0, 100));
|
|
responseText += parsed.output;
|
|
}
|
|
// Also handle direct text messages
|
|
else if (parsed.type === 'text' && parsed.text) {
|
|
console.log('✅ Direct text:', parsed.text.substring(0, 100));
|
|
responseText += parsed.text;
|
|
}
|
|
} catch (e) {
|
|
// Ignore parse errors
|
|
console.error('Error parsing writer data:', e);
|
|
}
|
|
},
|
|
setSessionId: () => {}, // No-op for this use case
|
|
};
|
|
|
|
console.log('🚀 Calling AI agent with provider:', provider);
|
|
console.log('📝 Prompt length:', prompt.length);
|
|
|
|
// Call the appropriate agent
|
|
if (provider === 'claude') {
|
|
await queryClaudeSDK(prompt, {
|
|
cwd: projectPath,
|
|
permissionMode: 'bypassPermissions',
|
|
model: 'sonnet'
|
|
}, writer);
|
|
} else if (provider === 'cursor') {
|
|
await spawnCursor(prompt, {
|
|
cwd: projectPath,
|
|
skipPermissions: true
|
|
}, writer);
|
|
}
|
|
|
|
console.log('📊 Total response text collected:', responseText.length, 'characters');
|
|
console.log('📄 Response preview:', responseText.substring(0, 200));
|
|
|
|
// Clean up the response
|
|
const cleanedMessage = cleanCommitMessage(responseText);
|
|
console.log('🧹 Cleaned message:', cleanedMessage.substring(0, 200));
|
|
|
|
return cleanedMessage || 'chore: update files';
|
|
} catch (error) {
|
|
console.error('Error generating commit message with AI:', error);
|
|
// Fallback to simple message
|
|
return `chore: update ${files.length} file${files.length !== 1 ? 's' : ''}`;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Cleans the AI-generated commit message by removing markdown, code blocks, and extra formatting
|
|
* @param {string} text - Raw AI response
|
|
* @returns {string} Clean commit message
|
|
*/
|
|
function cleanCommitMessage(text) {
|
|
if (!text || !text.trim()) {
|
|
return '';
|
|
}
|
|
|
|
let cleaned = text.trim();
|
|
|
|
// Remove markdown code blocks
|
|
cleaned = cleaned.replace(/```[a-z]*\n/g, '');
|
|
cleaned = cleaned.replace(/```/g, '');
|
|
|
|
// Remove markdown headers
|
|
cleaned = cleaned.replace(/^#+\s*/gm, '');
|
|
|
|
// Remove leading/trailing quotes
|
|
cleaned = cleaned.replace(/^["']|["']$/g, '');
|
|
|
|
// If there are multiple lines, take everything (subject + body)
|
|
// Just clean up extra blank lines
|
|
cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
|
|
|
|
// Remove any explanatory text before the actual commit message
|
|
// Look for conventional commit pattern and start from there
|
|
const conventionalCommitMatch = cleaned.match(/(feat|fix|docs|style|refactor|perf|test|build|ci|chore)(\(.+?\))?:.+/s);
|
|
if (conventionalCommitMatch) {
|
|
cleaned = cleaned.substring(cleaned.indexOf(conventionalCommitMatch[0]));
|
|
}
|
|
|
|
return cleaned.trim();
|
|
}
|
|
|
|
// Get remote status (ahead/behind commits with smart remote detection)
|
|
router.get('/remote-status', async (req, res) => {
|
|
const { project } = req.query;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get current branch
|
|
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
|
const branch = currentBranch.trim();
|
|
|
|
// Check if there's a remote tracking branch (smart detection)
|
|
let trackingBranch;
|
|
let remoteName;
|
|
try {
|
|
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
|
trackingBranch = stdout.trim();
|
|
remoteName = trackingBranch.split('/')[0]; // Extract remote name (e.g., "origin/main" -> "origin")
|
|
} catch (error) {
|
|
// No upstream branch configured - but check if we have remotes
|
|
let hasRemote = false;
|
|
let remoteName = null;
|
|
try {
|
|
const { stdout } = await execAsync('git remote', { cwd: projectPath });
|
|
const remotes = stdout.trim().split('\n').filter(r => r.trim());
|
|
if (remotes.length > 0) {
|
|
hasRemote = true;
|
|
remoteName = remotes.includes('origin') ? 'origin' : remotes[0];
|
|
}
|
|
} catch (remoteError) {
|
|
// No remotes configured
|
|
}
|
|
|
|
return res.json({
|
|
hasRemote,
|
|
hasUpstream: false,
|
|
branch,
|
|
remoteName,
|
|
message: 'No remote tracking branch configured'
|
|
});
|
|
}
|
|
|
|
// Get ahead/behind counts
|
|
const { stdout: countOutput } = await execAsync(
|
|
`git rev-list --count --left-right ${trackingBranch}...HEAD`,
|
|
{ cwd: projectPath }
|
|
);
|
|
|
|
const [behind, ahead] = countOutput.trim().split('\t').map(Number);
|
|
|
|
res.json({
|
|
hasRemote: true,
|
|
hasUpstream: true,
|
|
branch,
|
|
remoteBranch: trackingBranch,
|
|
remoteName,
|
|
ahead: ahead || 0,
|
|
behind: behind || 0,
|
|
isUpToDate: ahead === 0 && behind === 0
|
|
});
|
|
} catch (error) {
|
|
console.error('Git remote status error:', error);
|
|
res.json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Fetch from remote (using smart remote detection)
|
|
router.post('/fetch', async (req, res) => {
|
|
const { project } = req.body;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get current branch and its upstream remote
|
|
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
|
const branch = currentBranch.trim();
|
|
|
|
let remoteName = 'origin'; // fallback
|
|
try {
|
|
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
|
remoteName = stdout.trim().split('/')[0]; // Extract remote name
|
|
} catch (error) {
|
|
// No upstream, try to fetch from origin anyway
|
|
console.log('No upstream configured, using origin as fallback');
|
|
}
|
|
|
|
const { stdout } = await execAsync(`git fetch ${remoteName}`, { cwd: projectPath });
|
|
|
|
res.json({ success: true, output: stdout || 'Fetch completed successfully', remoteName });
|
|
} catch (error) {
|
|
console.error('Git fetch error:', error);
|
|
res.status(500).json({
|
|
error: 'Fetch failed',
|
|
details: error.message.includes('Could not resolve hostname')
|
|
? 'Unable to connect to remote repository. Check your internet connection.'
|
|
: error.message.includes('fatal: \'origin\' does not appear to be a git repository')
|
|
? 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
|
: error.message
|
|
});
|
|
}
|
|
});
|
|
|
|
// Pull from remote (fetch + merge using smart remote detection)
|
|
router.post('/pull', async (req, res) => {
|
|
const { project } = req.body;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get current branch and its upstream remote
|
|
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
|
const branch = currentBranch.trim();
|
|
|
|
let remoteName = 'origin'; // fallback
|
|
let remoteBranch = branch; // fallback
|
|
try {
|
|
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
|
const tracking = stdout.trim();
|
|
remoteName = tracking.split('/')[0]; // Extract remote name
|
|
remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
|
|
} catch (error) {
|
|
// No upstream, use fallback
|
|
console.log('No upstream configured, using origin/branch as fallback');
|
|
}
|
|
|
|
const { stdout } = await execAsync(`git pull ${remoteName} ${remoteBranch}`, { cwd: projectPath });
|
|
|
|
res.json({
|
|
success: true,
|
|
output: stdout || 'Pull completed successfully',
|
|
remoteName,
|
|
remoteBranch
|
|
});
|
|
} catch (error) {
|
|
console.error('Git pull error:', error);
|
|
|
|
// Enhanced error handling for common pull scenarios
|
|
let errorMessage = 'Pull failed';
|
|
let details = error.message;
|
|
|
|
if (error.message.includes('CONFLICT')) {
|
|
errorMessage = 'Merge conflicts detected';
|
|
details = 'Pull created merge conflicts. Please resolve conflicts manually in the editor, then commit the changes.';
|
|
} else if (error.message.includes('Please commit your changes or stash them')) {
|
|
errorMessage = 'Uncommitted changes detected';
|
|
details = 'Please commit or stash your local changes before pulling.';
|
|
} else if (error.message.includes('Could not resolve hostname')) {
|
|
errorMessage = 'Network error';
|
|
details = 'Unable to connect to remote repository. Check your internet connection.';
|
|
} else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
|
|
errorMessage = 'Remote not configured';
|
|
details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
|
|
} else if (error.message.includes('diverged')) {
|
|
errorMessage = 'Branches have diverged';
|
|
details = 'Your local branch and remote branch have diverged. Consider fetching first to review changes.';
|
|
}
|
|
|
|
res.status(500).json({
|
|
error: errorMessage,
|
|
details: details
|
|
});
|
|
}
|
|
});
|
|
|
|
// Push commits to remote repository
|
|
router.post('/push', async (req, res) => {
|
|
const { project } = req.body;
|
|
|
|
if (!project) {
|
|
return res.status(400).json({ error: 'Project name is required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get current branch and its upstream remote
|
|
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
|
const branch = currentBranch.trim();
|
|
|
|
let remoteName = 'origin'; // fallback
|
|
let remoteBranch = branch; // fallback
|
|
try {
|
|
const { stdout } = await execAsync(`git rev-parse --abbrev-ref ${branch}@{upstream}`, { cwd: projectPath });
|
|
const tracking = stdout.trim();
|
|
remoteName = tracking.split('/')[0]; // Extract remote name
|
|
remoteBranch = tracking.split('/').slice(1).join('/'); // Extract branch name
|
|
} catch (error) {
|
|
// No upstream, use fallback
|
|
console.log('No upstream configured, using origin/branch as fallback');
|
|
}
|
|
|
|
const { stdout } = await execAsync(`git push ${remoteName} ${remoteBranch}`, { cwd: projectPath });
|
|
|
|
res.json({
|
|
success: true,
|
|
output: stdout || 'Push completed successfully',
|
|
remoteName,
|
|
remoteBranch
|
|
});
|
|
} catch (error) {
|
|
console.error('Git push error:', error);
|
|
|
|
// Enhanced error handling for common push scenarios
|
|
let errorMessage = 'Push failed';
|
|
let details = error.message;
|
|
|
|
if (error.message.includes('rejected')) {
|
|
errorMessage = 'Push rejected';
|
|
details = 'The remote has newer commits. Pull first to merge changes before pushing.';
|
|
} else if (error.message.includes('non-fast-forward')) {
|
|
errorMessage = 'Non-fast-forward push';
|
|
details = 'Your branch is behind the remote. Pull the latest changes first.';
|
|
} else if (error.message.includes('Could not resolve hostname')) {
|
|
errorMessage = 'Network error';
|
|
details = 'Unable to connect to remote repository. Check your internet connection.';
|
|
} else if (error.message.includes('fatal: \'origin\' does not appear to be a git repository')) {
|
|
errorMessage = 'Remote not configured';
|
|
details = 'No remote repository configured. Add a remote with: git remote add origin <url>';
|
|
} else if (error.message.includes('Permission denied')) {
|
|
errorMessage = 'Authentication failed';
|
|
details = 'Permission denied. Check your credentials or SSH keys.';
|
|
} else if (error.message.includes('no upstream branch')) {
|
|
errorMessage = 'No upstream branch';
|
|
details = 'No upstream branch configured. Use: git push --set-upstream origin <branch>';
|
|
}
|
|
|
|
res.status(500).json({
|
|
error: errorMessage,
|
|
details: details
|
|
});
|
|
}
|
|
});
|
|
|
|
// Publish branch to remote (set upstream and push)
|
|
router.post('/publish', async (req, res) => {
|
|
const { project, branch } = req.body;
|
|
|
|
if (!project || !branch) {
|
|
return res.status(400).json({ error: 'Project name and branch are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Get current branch to verify it matches the requested branch
|
|
const { stdout: currentBranch } = await execAsync('git rev-parse --abbrev-ref HEAD', { cwd: projectPath });
|
|
const currentBranchName = currentBranch.trim();
|
|
|
|
if (currentBranchName !== branch) {
|
|
return res.status(400).json({
|
|
error: `Branch mismatch. Current branch is ${currentBranchName}, but trying to publish ${branch}`
|
|
});
|
|
}
|
|
|
|
// Check if remote exists
|
|
let remoteName = 'origin';
|
|
try {
|
|
const { stdout } = await execAsync('git remote', { cwd: projectPath });
|
|
const remotes = stdout.trim().split('\n').filter(r => r.trim());
|
|
if (remotes.length === 0) {
|
|
return res.status(400).json({
|
|
error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
|
});
|
|
}
|
|
remoteName = remotes.includes('origin') ? 'origin' : remotes[0];
|
|
} catch (error) {
|
|
return res.status(400).json({
|
|
error: 'No remote repository configured. Add a remote with: git remote add origin <url>'
|
|
});
|
|
}
|
|
|
|
// Publish the branch (set upstream and push)
|
|
const { stdout } = await execAsync(`git push --set-upstream ${remoteName} ${branch}`, { cwd: projectPath });
|
|
|
|
res.json({
|
|
success: true,
|
|
output: stdout || 'Branch published successfully',
|
|
remoteName,
|
|
branch
|
|
});
|
|
} catch (error) {
|
|
console.error('Git publish error:', error);
|
|
|
|
// Enhanced error handling for common publish scenarios
|
|
let errorMessage = 'Publish failed';
|
|
let details = error.message;
|
|
|
|
if (error.message.includes('rejected')) {
|
|
errorMessage = 'Publish rejected';
|
|
details = 'The remote branch already exists and has different commits. Use push instead.';
|
|
} else if (error.message.includes('Could not resolve hostname')) {
|
|
errorMessage = 'Network error';
|
|
details = 'Unable to connect to remote repository. Check your internet connection.';
|
|
} else if (error.message.includes('Permission denied')) {
|
|
errorMessage = 'Authentication failed';
|
|
details = 'Permission denied. Check your credentials or SSH keys.';
|
|
} else if (error.message.includes('fatal:') && error.message.includes('does not appear to be a git repository')) {
|
|
errorMessage = 'Remote not configured';
|
|
details = 'Remote repository not properly configured. Check your remote URL.';
|
|
}
|
|
|
|
res.status(500).json({
|
|
error: errorMessage,
|
|
details: details
|
|
});
|
|
}
|
|
});
|
|
|
|
// Discard changes for a specific file
|
|
router.post('/discard', async (req, res) => {
|
|
const { project, file } = req.body;
|
|
|
|
if (!project || !file) {
|
|
return res.status(400).json({ error: 'Project name and file path are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Check file status to determine correct discard command
|
|
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
|
|
|
if (!statusOutput.trim()) {
|
|
return res.status(400).json({ error: 'No changes to discard for this file' });
|
|
}
|
|
|
|
const status = statusOutput.substring(0, 2);
|
|
|
|
if (status === '??') {
|
|
// Untracked file or directory - delete it
|
|
const filePath = path.join(projectPath, file);
|
|
const stats = await fs.stat(filePath);
|
|
|
|
if (stats.isDirectory()) {
|
|
await fs.rm(filePath, { recursive: true, force: true });
|
|
} else {
|
|
await fs.unlink(filePath);
|
|
}
|
|
} else if (status.includes('M') || status.includes('D')) {
|
|
// Modified or deleted file - restore from HEAD
|
|
await execAsync(`git restore "${file}"`, { cwd: projectPath });
|
|
} else if (status.includes('A')) {
|
|
// Added file - unstage it
|
|
await execAsync(`git reset HEAD "${file}"`, { cwd: projectPath });
|
|
}
|
|
|
|
res.json({ success: true, message: `Changes discarded for ${file}` });
|
|
} catch (error) {
|
|
console.error('Git discard error:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Delete untracked file
|
|
router.post('/delete-untracked', async (req, res) => {
|
|
const { project, file } = req.body;
|
|
|
|
if (!project || !file) {
|
|
return res.status(400).json({ error: 'Project name and file path are required' });
|
|
}
|
|
|
|
try {
|
|
const projectPath = await getActualProjectPath(project);
|
|
await validateGitRepository(projectPath);
|
|
|
|
// Check if file is actually untracked
|
|
const { stdout: statusOutput } = await execAsync(`git status --porcelain "${file}"`, { cwd: projectPath });
|
|
|
|
if (!statusOutput.trim()) {
|
|
return res.status(400).json({ error: 'File is not untracked or does not exist' });
|
|
}
|
|
|
|
const status = statusOutput.substring(0, 2);
|
|
|
|
if (status !== '??') {
|
|
return res.status(400).json({ error: 'File is not untracked. Use discard for tracked files.' });
|
|
}
|
|
|
|
// Delete the untracked file or directory
|
|
const filePath = path.join(projectPath, file);
|
|
const stats = await fs.stat(filePath);
|
|
|
|
if (stats.isDirectory()) {
|
|
// Use rm with recursive option for directories
|
|
await fs.rm(filePath, { recursive: true, force: true });
|
|
res.json({ success: true, message: `Untracked directory ${file} deleted successfully` });
|
|
} else {
|
|
await fs.unlink(filePath);
|
|
res.json({ success: true, message: `Untracked file ${file} deleted successfully` });
|
|
}
|
|
} catch (error) {
|
|
console.error('Git delete untracked error:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
export default router;
|