Compare commits

..

1 Commits

Author SHA1 Message Date
Jordan Bentley
967e7d2c10
Reported in Discord:
strin — 3:56 PM
Hi anyone...

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-21 18:30:35 -04:00
344 changed files with 9697 additions and 70924 deletions

View File

@ -1,10 +0,0 @@
node_modules
dist
dist-electron
*.min.js
vite.config.ts
*.config.js
*.config.cjs
frontend/public
main/dist
backend

View File

@ -1,8 +1,8 @@
name: Build and Publish Canary
name: Build Crystal
on:
push:
branches: [ main, 'release/**' ]
branches: [ main ]
pull_request:
branches: [ main ]
workflow_dispatch:
@ -11,28 +11,24 @@ jobs:
build:
strategy:
matrix:
# Build both platforms for validation, but use different commands for speed
# Build both platforms with -dev suffix to prevent auto-updater cache conflicts
os: [macos-latest, ubuntu-latest]
include:
- os: macos-latest
build_cmd: build:mac:universal
artifact_name: crystal-macos-canary
artifact_path: |
dist-electron/*.dmg
dist-electron/*.zip
dist-electron/latest-mac.yml
build_cmd: build:mac:ci:dev
artifact_name: crystal-macos-dev
artifact_path: dist-electron/*.dmg
- os: ubuntu-latest
build_cmd: canary:linux
artifact_name: crystal-linux-canary
build_cmd: build:linux:ci:dev
artifact_name: crystal-linux-dev
artifact_path: |
dist-electron/*.deb
dist-electron/*.AppImage
dist-electron/latest-linux.yml
runs-on: ${{ matrix.os }}
permissions:
contents: write # Required for creating releases and accessing repository contents
contents: read # Required for accessing repository contents
steps:
- name: Checkout code
@ -52,7 +48,19 @@ jobs:
node-version: '22.15.1'
cache: 'pnpm'
# Cache electron binaries to speed up builds
# Cache native modules and electron binaries to speed up rebuilds
- name: Cache native modules
uses: actions/cache@v4
with:
path: |
main/node_modules/.bin
main/build
~/.electron
~/.electron-gyp
key: ${{ runner.os }}-native-modules-${{ hashFiles('**/pnpm-lock.yaml') }}
restore-keys: |
${{ runner.os }}-native-modules-
- name: Cache Electron binaries
uses: actions/cache@v4
with:
@ -93,16 +101,24 @@ jobs:
echo "Using cached frontend and main builds"
fi
- name: Rebuild native modules (if needed)
run: |
# Only rebuild if native modules cache missed or build files changed
if [ ! -f "main/node_modules/.bin/electron-rebuild" ] || [ ! -f "main/build/Release/better_sqlite3.node" ]; then
echo "Rebuilding native modules..."
pnpm run electron:rebuild
else
echo "Using cached native modules"
fi
- name: Generate NOTICES file
run: pnpm run generate-notices
- name: Build and publish canary release
- name: Build application
run: pnpm run ${{ matrix.build_cmd }}
env:
# GitHub token (required by electron-builder for publishing)
# GitHub token (required by electron-builder even for non-publish builds)
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Mark this as a canary build
CANARY_BUILD: true
# macOS code signing (optional for CI builds)
CSC_LINK: ${{ matrix.os == 'macos-latest' && secrets.APPLE_CERTIFICATE || '' }}
CSC_KEY_PASSWORD: ${{ matrix.os == 'macos-latest' && secrets.APPLE_CERTIFICATE_PASSWORD || '' }}
@ -112,8 +128,6 @@ jobs:
APPLE_TEAM_ID: ${{ matrix.os == 'macos-latest' && secrets.APPLE_TEAM_ID || '' }}
# Only enable signing when certificates are available
CSC_IDENTITY_AUTO_DISCOVERY: ${{ matrix.os == 'macos-latest' && 'true' || 'false' }}
# Disable signing entirely when no certificates are present
CSC_DISABLE: ${{ (matrix.os == 'macos-latest' && !secrets.APPLE_CERTIFICATE) && 'true' || 'false' }}
- name: List build artifacts
run: ls -la dist-electron/
@ -130,5 +144,5 @@ jobs:
name: ${{ matrix.artifact_name }}
path: ${{ matrix.artifact_path }}
if-no-files-found: error
retention-days: 30
retention-days: 7

View File

@ -99,5 +99,5 @@ jobs:
- name: Validate license compatibility
run: |
# Use our more sophisticated license compatibility check
chmod +x ./check-license-compatibility.sh
./check-license-compatibility.sh
chmod +x ./scripts/check-license-compatibility.sh
./scripts/check-license-compatibility.sh

View File

@ -9,10 +9,11 @@ jobs:
release:
strategy:
matrix:
# Official release builds (no version suffix) - triggered by version tags
os: [macos-latest, ubuntu-latest]
include:
- os: macos-latest
release_cmd: release:mac:universal
release_cmd: release:mac
artifact_name: crystal-macos
artifact_path: |
dist-electron/*.dmg
@ -55,6 +56,9 @@ jobs:
- name: Build main process
run: pnpm run build:main
- name: Rebuild native modules
run: pnpm run electron:rebuild
- name: Build and publish application
run: pnpm run ${{ matrix.release_cmd }}
env:

1
.gitignore vendored
View File

@ -13,6 +13,7 @@ node_modules/
dist/
build/
!build/entitlements.mac.plist
!build/linux/
*.tsbuildinfo
dist-electron/
main/dist/

View File

@ -1 +0,0 @@
22.15.1

3
.npmrc
View File

@ -1,4 +1,3 @@
public-hoist-pattern[]=*
public-hoist-pattern[]=!better-sqlite3
public-hoist-pattern[]=!@homebridge/node-pty-prebuilt-multiarch
auto-install-peers=false
public-hoist-pattern[]=!@homebridge/node-pty-prebuilt-multiarch

View File

@ -1,42 +0,0 @@
# Repository Guidelines
## Project Structure & Module Organization
- Root `pnpm` workspace with packages: `main/` (Electron main process, TypeScript), `frontend/` (React + Vite), `shared/` (shared types), and `tests/` (Playwright E2E).
- Key paths: `main/src/{services,ipc,utils}/`, `frontend/src/{components,hooks,stores,utils}/`, `main/assets/`, `scripts/`.
- Build artifacts: `frontend/dist/`, `main/dist/`, packaged output `dist-electron/`.
## Build, Test, and Development Commands
- Dev app: `pnpm dev` (spawns frontend + Electron).
- Build all: `pnpm build` (frontend, main, then electron package).
- Package (examples): `pnpm build:mac`, `pnpm build:linux`.
- Lint: `pnpm lint`; Type-check: `pnpm typecheck` (runs per package).
- Tests (E2E): `pnpm test`, `pnpm test:ui`, CI configs in `playwright.ci*.config.ts`.
- Main unit tests (if added): `pnpm --filter main test`, coverage: `pnpm --filter main run test:coverage`.
## Coding Style & Naming Conventions
- Use TypeScript throughout; follow ESLint configs in `frontend/eslint.config.js` and `main/eslint.config.js`.
- Indentation 2 spaces; prefer explicit types at module boundaries.
- Naming: `camelCase` for variables/functions, `PascalCase` for React components/types, `kebab-case` for filenames (React files may match component name).
- Run `pnpm lint && pnpm typecheck` before sending PRs.
## Testing Guidelines
- E2E tests live in `tests/*.spec.ts` (Playwright). Example: `pnpm test -- tests/smoke.spec.ts`.
- Add Playwright tests for user-visible flows; mock external services where possible.
- For backend logic in `main/`, use Vitest colocated under `main/src/**/__tests__` or `*.spec.ts`.
## Commit & Pull Request Guidelines
- Commits: present tense, focused, reference issues (e.g., "Fix session diff flicker, closes #123").
- PRs must include: clear description, linked issues, testing notes; screenshots/GIFs for UI changes.
- If dependencies change, run `pnpm run generate-notices` and commit updated `NOTICES`.
## Security & Configuration Tips
- Node >= `22.14`; `pnpm` >= `8`. Use `pnpm` only.
- Secrets via `.env` (dotenv) for local dev; never commit secrets.
- To avoid clobbering local data when hacking on Crystal with Crystal: `CRYSTAL_DIR=~/.crystal_test pnpm dev`.
## Agent Notes (for automation)
- Keep changes minimal and scoped; prefer small patches.
- Update docs alongside code; do not alter build targets without discussion.
- Use repository scripts (pnpm) and keep formatting consistent with existing files.
- Always review the root `CLAUDE.md` before beginning any work.
- Scan the repository for every `CLAUDE.md`, and when working in a folder or any of its subfolders that has one, read and follow that file too.

View File

@ -1,212 +1,6 @@
All notable changes to Crystal will be documented in this file.
## [0.3.5] - 2026-02-26
### We recommend migrating to Nimbalyst, our successor product to Crystal.
https://nimbalyst.com/
You may continue to use Crystal but it will not be updated in the future.
## [0.3.4] - 2025-12-19
### Added
- **Merge and archive**: New "merge and archive" button that merges changes and archives the session in one action
- **Archive folders on merge**: Ability to archive entire folders when merging
- **Nimbalyst integration**: Open Nimbalyst directly from Crystal with worktree filter support
- **Resizable UI elements**: File changes panel and prompt box/panel can now be resized
### Changed
- **Multiple agents per worktree**: Run multiple agents in one worktree at a time for more flexible workflows
### Fixed
- **Token usage parsing**: Fixed issues with token usage parsing
- **Run script command**: Fixed wrong script command for run script ([#226](https://github.com/stravu/crystal/issues/226))
- **Run script state**: Fixed run script state management issues
- **Graceful degradation**: Application no longer fails to load if Codex or Claude Code are not installed
- **Dependencies and linting**: Fixed various dependency and linting errors
### Documentation
- **Windows build requirements**: Added Windows build requirements documentation
## [0.3.3] - 2025-10-12
### Added
- **Prompt navigation**: Click on a prompt in the prompt history to snap to it in the output
- **Reverse sort order**: Ability to reverse the sort order of sessions
- **Multi-agent session creation**: Can now create both Codex and Claude Code sessions with one prompt
### Changed
- **Git merge strategy**: Now uses merge to main instead of rebase for safer operations
- **Folder sorting**: Folders are no longer always pinned to the top in sort order
### Fixed
- **Light mode persistence**: Fixed light mode setting not persisting across sessions
- **Light mode UI**: Various light mode visual fixes
- **Automatic /context**: Fixed automatic /context command handling
- **Codex parsing**: Fixed parsing issues with new Codex format
## [0.3.2] - 2025-10-10
### Fixed
- **Mermaid diagram error handling**: Application no longer crashes when Mermaid diagrams fail to render
- **Error boundary improvements**: Better error boundaries throughout the application for more graceful error handling
- **Tool panels database error**: Fixed "no such table: tool_panels" database error
- **Claude panels model selection**: Fixed bug where Claude panels were not respecting the selected model choice
- **Timestamp handling**: Fixed timestamp handling issues in messaging view
- **Git operations**: Optimized git operations by removing unnecessary process.chdir() calls for better performance
## [0.3.1] - 2025-09-30
### Major Changes
- **Setup Tasks Panel**: New guided setup panel on project pane with auto-navigation to incomplete tasks
- **Major Performance Improvements**: 40%+ CPU reduction through git status polling optimizations and terminal output processing enhancements
- **Tool calls collapsed by default**: Cleaner output view with expandable tool call details
- **Attribution messages in commits**: "Co-Authored-By: Crystal" attribution footer for commits made through Crystal. These can be disabled in the settings menu.
- **Slash Commands in Claude Code**: You can now use commands such as /context in Claude Code panels
### Added
- **Keyboard navigation between panels**: Use Cmd+Option+Arrow to quickly jump between panels
- **Tool calls collapsed by default**: Cleaner output view with expandable tool call details
- **Copy to clipboard for messages**: Copy individual messages directly from the output view
- **New renderer for TODO lists**: Display Claude's todo lists directly in the output
- **Cmd+Click for quick session creation**: Quick way to create new sessions without opening dialog
- **GitHub status loading indicator**: Shows when GitHub integration is loading
### Changed
- **Claude Code SDK updated to 2.0.0**: Latest SDK version with improved features
- **Electron temporarily upgraded to 37.6.0** (Previous version had performance issues on OSX Tahoe)
- **Reduced logging**: Less verbose console output for cleaner logs
- **Panel state saving improvements**: Better persistence of panel states across sessions
- **Library updates**: Updated dependencies based on Dependabot security warnings
### Fixed
- **Run scripts don't auto-start on startup**: Prevents unwanted script execution on app launch
- **Critical session bugs**: Fixed new sessions stuck on initializing, multiple sessions not appearing, and worktree deletion failures
- **UI/UX fixes**: Slash command rendering, panel navigation, missing session IDs, and project settings clearing
- **Performance fixes**: Fixed 2800ms+ frame drops, EventEmitter memory leaks, React infinite loops, and unnecessary re-renders
- **Editor tab state persistence**: Editor now properly reloads state when switching sessions
- **Terminal state preservation**: Terminal state no longer lost when switching between sessions
- **Logs panel disappearing**: Fixed bug where closed logs panel wouldn't reappear
- **Build fixes**: Multiple GitHub build fixes, Electron version mismatch, type errors, and linting errors
- **Git operations**: Optimized git status refresh, reduced unnecessary checks, and centralized PATH management
### Performance
- **Reduced CPU usage by 40%+**: Through git status polling optimizations with smart polling system
- **Eliminated frame drops**: Fixed 2800ms+ frame drops during terminal output processing
- **Memory leak fixes**: Fixed EventEmitter leaks in session list
- **Optimized rendering**: Prevented unnecessary re-renders and improved terminal processing with adaptive debouncing
## [0.3.0] - 2025-09-21
### Major Changes
- **OpenAI Codex support** - Run OpenAI Codex as well as Claude Code
- **Panel-based workspace** - You may now create multiple agent and terminal panels inside a single session
### Added
- **Session attachments & shortcuts** - Add text attachment support alongside images when starting sessions and Cmd+Click to spin up a new session.
- **Clipboard actions** - Copy-to-clipboard icons for session messages and run-script logs.
### Changed
- **New session dialog** - Remembers preferences, allows promptless sessions, stabilizes prompts when switching models, and improves model selection.
- **Environment reliability** - Centralized PATH handling and refreshed git actions after commits for more accurate status updates.
- **Session naming** - Session names can now have spaces for better flexibility.
### Fixed
- **Session UX issues** - Fixed session rename regressions, prompt box glitches, duplicate key errors, and ensured git actions only appear on the right session.
- **Attachments & prompts** - Corrected handling for image/text attachments, wrong prompts in dialogs, and Codex conversation continuation.
- **Performance improvements** - Improved scroll behavior on diff viewer commits and better worktree deletion queuing.
### Security
- **Race condition hardening** - Added session validation, mutex locks, and database transactions to prevent cross-session data leaks.
## [0.2.3] - 2025-08-25
### Fixed
- **Session completion status updates** - Fixed "Rebase to main" button not updating when a session completed
- **Session archiving performance** - Made session archiving operation much quicker
## [0.2.2] - 2025-08-23
### Added
- **Homebrew install** - Crystal can now be installed with `brew install --cask stravu-crystal` on OSX
### Changed
- **Performance improvements** - Optimized application performance for faster response times and smoother operation
## [0.2.1] - 2025-08-21
### Added
- **'Auto' model selection** - New automatic model selection option that lets Claude Code choose the best model
- **Sub-agent output visualization** - Enhanced UX for displaying sub-agent task outputs
- **Terminal/Logs separation** - Logs from run scripts now have their own dedicated tab with filter and search
- **Dev mode for debugging** - New developer mode to view raw Claude Code messages in the Messages tab
- **Canary channel publishing** - Automatic canary builds from main branch for early testing
### Changed
- **Performance improvements** - Various optimizations for better responsiveness
- **Auto-scroll reliability** - More reliable auto-scrolling behavior that only activates when at bottom of output
- **Project panel usage** - Now uses project panel instead of special (main) session
- **Git branch actions labeling** - Renamed "Branch Actions" to "Git Branch Actions" for clarity
### Fixed
- **Double prompt submission prevention** - Fixed issue where prompts could be submitted twice
- **Commit message display** - Fixed showing commit messages in diff viewer
- **Worktree file references** - Don't show worktree files when using @ to reference files
- **Git status indicators** - Fixed "Behind Only - No unique changes" status marker
- **Revert button backend** - Updated backend to use after_commit_hash for revert button functionality
- **Run script log clearing** - Clear logs on fresh run script execution
- **Canary build process** - Fixed canary build issues
### Documentation
- **Demo video updated** - Updated demo video to showcase latest features
- **Markdown cleanup** - Cleaned up and reorganized documentation structure
## [0.2.0] - 2025-08-05
### Added
- Rich Output for Claude Code to replace text-only output
- Light/Dark modes
- Compact context
- AWS Bedrock model support
- Git status indicators in session sidebar
- Always use the latest versions of Opus/Sonnet/Haiku, including Opus 4.1
### Changed
- Terminal scrollback increased to 100,000 lines for better debugging
- Project dashboard loading improvements
- Enhanced IDE integration with loading states and command validation
### Fixed
- Duplicate right-click context menus issue
- IDE button not opening IDE properly
- Context compaction now actually restarts conversations instead of just showing status
- GTK 3 forced on Linux to resolve Electron 36 compatibility issues
## [0.1.17] - 2025-07-23
### Added
- Project Dashboard view
- Multi-mode auto-commit system
- Visual refinements to Projects & Sessions sidebar with tree lines
- Slider to select session count when creating multiple sessions
### Changed
- Improved indentation levels in UI
### Fixed
- ReferenceError: ReadableStream is not defined
- Bug where navigation away from dashboard was blocked
- Index issue with session navigation
- Messages tab functionality restored for debugging Claude Code JSON output
- Subfolder creation issues
### Internal/Development
- Multiple code refactoring attempts (some reverted for stability)
- Build artifacts now show commit hash
- Added strict port checking for Vite dev server
- CI/CD improvements including GitHub Actions for testing and building
- Frontend console debugging for developing Crystal on Crystal
## [0.1.16] - 2025-07-18
Special thanks to eshaffer321 who contributed almost all the code in this release.

606
CLAUDE.md
View File

@ -4,15 +4,12 @@ Created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_cam
## Project Overview
Crystal is a fully-implemented Electron desktop application for managing multiple AI code assistant instances (Claude Code and Codex) against a single directory using git worktrees. It provides a streamlined interface for running parallel AI assistant sessions with different approaches to the same problem.
Crystal is a fully-implemented Electron desktop application for managing multiple Claude Code instances against a single directory using git worktrees. It provides a streamlined interface for running parallel Claude Code sessions with different approaches to the same problem.
## References
Use these reference pages for more information:
- How to invoke Claude Code through the command line as an SDK: https://docs.anthropic.com/en/docs/claude-code/sdk
- How to run multiple Claude Code instances with Git Worktrees: https://docs.anthropic.com/en/docs/claude-code/tutorials#run-parallel-claude-code-sessions-with-git-worktrees
- [**Adding New CLI Tools**](./docs/ADDING_NEW_CLI_TOOLS.md): Guide for extending Crystal to support additional CLI tools beyond Claude Code
- [**Implementing New CLI Agents**](./docs/IMPLEMENTING_NEW_CLI_AGENTS.md): Step-by-step instructions for adding new CLI agent tools with code examples and best practices
- [**Codex Configuration**](./main/src/services/panels/codex/CODEX_CONFIG.md): Configuration guide for Codex CLI integration
## Implementation Status: ✅ COMPLETE
@ -52,15 +49,12 @@ All core features have been successfully implemented with significant enhancemen
- **Active project**: Persistent active project selection
### User Interface
- **Dual tab system**: Main view tabs (Output | Diff | Logs | Editor) with tool panel bar underneath
- **Tool Panel System**: Flexible panel framework supporting multiple terminal instances per session
- **Professional terminal**: XTerm.js with 50,000 line scrollback buffer
- **Multiple view modes**:
- Output View: Formatted terminal output with syntax highlighting
- Messages View: Raw JSON message inspection for debugging
- View Diff View: Git diff viewer with file statistics
- Editor View: File editor with syntax highlighting
- **Multi-instance terminals**: Multiple XTerm.js terminals per session with 50,000 line scrollback
- **Panel management**: Create, switch, rename, and close tool panels dynamically
- Terminal View: Dedicated terminal for running project scripts
- **Sidebar navigation**: Session list, project selector, prompt history
- **Real-time updates**: IPC-based live output streaming
- **Status indicators**: Color-coded badges with animations
@ -74,27 +68,11 @@ All core features have been successfully implemented with significant enhancemen
- **Clipboard support**: Copy prompts to clipboard
### Advanced Terminal Features
- **Panel-based terminals**: Each terminal runs in its own panel with independent state
- **Multi-instance support**: Multiple terminal panels per session for parallel workflows
- **Multi-line input**: Auto-resizing textarea with keyboard shortcuts
- **Smart formatting**: Automatic formatting of JSON messages
- **Tool call display**: Clear visual structure for Claude's tool usage
- **Script execution**: Run project scripts with real-time output
- **Process management**: Start/stop script processes
- **State persistence**: Terminal scrollback, working directory, and history persist across app restarts
- **Lazy initialization**: Terminal processes only start when panels are first viewed
### Tool Panel System ✨ NEW
- **Flexible architecture**: Extensible panel framework supporting multiple panel types
- **Multi-instance terminals**: Run multiple terminal instances per session in separate panels
- **Lazy initialization**: Panels only start processes when first viewed for memory efficiency
- **State persistence**: Terminal scrollback, working directories, and panel configurations persist across restarts
- **Panel lifecycle management**: Create, switch, rename, and delete panels dynamically
- **Event-driven communication**: Panel event bus enabling future inter-panel communication
- **Always-visible panel bar**: Tool panel tabs always visible below main view tabs
- **Seamless integration**: Panels integrate with existing session and view management
- **Memory efficient**: Inactive panels suspend rendering while maintaining background processes
- **Future extensibility**: Architecture designed to support Claude, Diff, and Editor panels in future releases
### Settings & Configuration
- **Global settings**:
@ -113,22 +91,15 @@ All core features have been successfully implemented with significant enhancemen
### Data Persistence
- **SQLite Database**:
- `projects`: Project configurations, paths, and commit settings
- `sessions`: Core session metadata with active_panel_id, folder_id, tool_type ('claude'|'codex'|'none'), and status tracking
- `session_outputs`: Terminal output history (linked to panels via panel_id)
- `conversation_messages`: Conversation history with tool calls/results (linked to panels via panel_id)
- `execution_diffs`: Git diff tracking per execution (linked to panels via panel_id)
- `prompt_markers`: Navigation markers for prompts with completion timestamps (linked to panels via panel_id)
- `tool_panels`: Panel configurations, state, metadata, and settings (JSON)
- `folders`: Hierarchical folder structure for organizing sessions (supports nesting via parent_folder_id)
- `project_run_commands`: Multiple configurable run commands per project
- `claude_panel_settings`: Claude-specific panel configuration (legacy, being migrated to tool_panels.settings)
- `ui_state`: UI state persistence for application preferences
- `app_opens`: Application launch tracking for analytics
- `user_preferences`: User preference storage for application behavior
- `projects`: Project configurations and paths
- `sessions`: Core session metadata
- `session_outputs`: Terminal output history
- `conversation_messages`: Conversation history for continuations
- `execution_diffs`: Git diff tracking per execution
- `prompt_markers`: Navigation markers for prompts
- **Automatic initialization**: `~/.crystal` directory created on first run
- **Migration system**: Dual migration system (TypeScript and SQL) for schema evolution
- **JSON Configuration**: Application configuration stored in ~/.crystal/config.json
- **Migration system**: SQL migrations for schema evolution
- **Electron Store**: Application configuration persistence
### Developer Experience
- **Task Queue**: Bull queue with optional Redis support
@ -142,7 +113,7 @@ All core features have been successfully implemented with significant enhancemen
### Electron Application
- **Main Process**: Electron main process with IPC communication
- Window management with native OS integration
- Custom ConfigManager for configuration persistence (~/.crystal/config.json)
- Electron Store for configuration persistence
- IPC handlers for renderer communication
### Frontend (React 19 + TypeScript)
@ -168,7 +139,7 @@ All core features have been successfully implemented with significant enhancemen
## Architecture
```javascript
```
┌─────────────────────────────────────────────────────────┐
│ Electron Desktop Application │
├─────────────────────────────────────────────────────────┤
@ -215,69 +186,350 @@ All core features have been successfully implemented with significant enhancemen
### Modular Architecture (Refactored)
The main process has been refactored from a monolithic `index.ts` file into a comprehensive modular structure:
The main process has been refactored from a monolithic `index.ts` file (previously 2,705 lines) into a modular structure:
**Core Main Process:**
- **`index.ts`** (776 lines): Core Electron setup and initialization
- **`events.ts`** (1,108 lines): Event handling and coordination
- **`index.ts`** (414 lines): Core Electron setup and initialization
- **`ipc/git.ts`** (843 lines): All git-related IPC handlers
- **`ipc/session.ts`** (428 lines): Session management IPC handlers
- **`events.ts`** (359 lines): Event handling and coordination
**IPC Handlers** (`main/src/ipc/`):
- **`session.ts`** (1,872 lines): Session management IPC handlers
- **`git.ts`** (1,391 lines): Git-related IPC handlers
- **`file.ts`** (865 lines): File operations (read/write/delete/list)
- **`dashboard.ts`** (741 lines): Dashboard overview and project status
- **`codexPanel.ts`** (496 lines): Codex AI panel management
- **`baseAIPanelHandler.ts`** (382 lines): Base class for AI panel handlers
- **`project.ts`** (349 lines): Project CRUD operations
- **`claudePanel.ts`** (268 lines): Claude AI panel management
- **`script.ts`** (230 lines): Script execution handlers
- **`panels.ts`** (228 lines): General panel lifecycle management
- Plus 13 additional specialized handlers
**Service Layer** (`main/src/services/`):
- **`sessionManager.ts`** (1,598 lines): Core session lifecycle management
- **`worktreeManager.ts`** (931 lines): Git worktree operations
- **`gitStatusManager.ts`** (872 lines): Git status tracking
- **`taskQueue.ts`** (671 lines): Async task queue management
- **`gitDiffManager.ts`** (606 lines): Diff generation and tracking
- **`cliToolRegistry.ts`** (532 lines): CLI tool registration system
- **`panelManager.ts`** (374 lines): Panel lifecycle coordinator
- **`terminalPanelManager.ts`** (370 lines): Terminal panel processes
- Plus 8 additional service modules
**Panel Services** (`main/src/services/panels/`):
- **`codex/codexManager.ts`** (1,251 lines): Codex CLI integration
- **`cli/AbstractCliManager.ts`** (994 lines): Abstract CLI manager base class
- **`claude/claudeCodeManager.ts`** (741 lines): Claude CLI integration
- **`logPanel/logsManager.ts`** (496 lines): Log panel management
- **`ai/AbstractAIPanelManager.ts`** (395 lines): Abstract AI panel base class
- **`codex/codexPanelManager.ts`** (403 lines): Codex panel lifecycle
- **`claude/claudePanelManager.ts`** (135 lines): Claude panel lifecycle
**Frontend Hooks** (`frontend/src/hooks/`):
- **`useSessionView.ts`** (1,694 lines): Session view logic and state management
- **`useClaudePanel.ts`** (475 lines): Claude panel state management
- **`useCliPanel.ts`** (452 lines): CLI panel state management
- **`useIPCEvents.ts`** (349 lines): IPC event handling
- **`useCodexPanel.ts`** (343 lines): Codex panel state management
- **`useAIInputPanel.ts`** (311 lines): AI input panel logic
- **`useNotifications.ts`** (212 lines): Notification system
**Frontend Stores** (`frontend/src/stores/`):
- **`sessionStore.ts`** (699 lines): Session state management with Zustand
- **`sessionPreferencesStore.ts`** (154 lines): User session preferences
- **`panelStore.ts`** (109 lines): Panel state management
- **`sessionHistoryStore.ts`** (93 lines): Session history tracking
**Major Frontend Components** (`frontend/src/components/`):
- **`DraggableProjectTreeView.tsx`** (2,565 lines): Main project/session tree UI
- **`CreateSessionDialog.tsx`** (1,293 lines): Session creation dialog
- **`ProjectTreeView.tsx`** (612 lines): Project tree display
- **`Settings.tsx`** (589 lines): Settings management UI
- **`SessionView.tsx`** (587 lines): Session display (uses useSessionView hook)
The frontend has also been modularized:
- **`useSessionView.ts`** (941 lines): Extracted session view logic from the previous monolithic SessionView component
This modular structure improves maintainability and makes it easier to locate and modify specific functionality.
### Session Output Handling (DO NOT MODIFY WITHOUT EXPLICIT PERMISSION)
⚠️ **WARNING**: The session output handling system is complex and fragile. Modifying it frequently causes issues like duplicate messages, disappearing content, or blank screens. Any changes require explicit user permission.
#### How It Works:
1. **Database Storage**:
- Raw JSON messages from Claude are stored as-is in the database
- Stdout/stderr outputs are stored directly
- No formatting or transformation happens at storage time
2. **Real-time Streaming**:
- When Claude outputs data, it's saved to the database immediately
- For JSON messages, a formatted stdout version is sent to the frontend for the Output view
- The original JSON is also sent for the Messages view
- This provides immediate visual feedback during active sessions
3. **Session Loading**:
- When navigating to a session, outputs are loaded from the database
- The `sessions:get-output` handler transforms JSON messages to formatted stdout on-the-fly
- Uses `setSessionOutputs` for atomic updates to prevent race conditions
4. **Frontend Display**:
- The useSessionView hook manages session view logic and state (extracted from SessionView component)
- A mutex lock (`loadingRef`) prevents concurrent loads
- Timing is carefully managed with `requestAnimationFrame` and delays
- The `formattedOutput` state is NOT cleared on session switch - it updates naturally
5. **Key Principles**:
- Database is the single source of truth
- Transformations happen on-the-fly, not at storage time
- Real-time updates supplement but don't replace database data
- Session switches always reload from database to ensure consistency
#### Common Issues and Solutions:
- **Duplicate messages**: Usually caused by sending both formatted and raw versions
- **Disappearing content**: Often due to clearing output states at the wrong time
- **Black screens**: Typically from race conditions during session switching
- **Content only loads once**: Results from improper state management or missing dependencies
The current implementation carefully balances real-time updates with data persistence to provide a smooth user experience.
### Timestamp Handling Guidelines
⚠️ **IMPORTANT**: Proper timestamp handling is critical for the application to function correctly, especially for prompt duration calculations.
#### Overview
Crystal uses timestamps throughout the application for tracking session activity, prompt execution times, and displaying time-based information. Due to the mix of SQLite database storage and JavaScript Date objects, special care must be taken to ensure timezone consistency.
#### Key Principles
1. **Database Storage**: All timestamps are stored in UTC using SQLite's `CURRENT_TIMESTAMP` or `datetime()` functions
2. **Frontend Display**: Timestamps are parsed as UTC and converted to local time only for display
3. **Consistency**: Always use the timestamp utility functions instead of manual date parsing
4. **Validation**: Always validate timestamps before using them in calculations
#### Timestamp Formats
- **SQLite DATETIME**: `YYYY-MM-DD HH:MM:SS` (stored in UTC without timezone indicator)
- **ISO 8601**: `YYYY-MM-DDTHH:MM:SS.sssZ` (with explicit UTC timezone)
- **JavaScript Date**: Local timezone by default (be careful!)
#### Utility Functions
Crystal provides timestamp utilities in both frontend and backend:
**Backend** (`main/src/utils/timestampUtils.ts`):
```typescript
import { formatForDatabase, getCurrentTimestamp } from '../utils/timestampUtils';
// For database storage
const timestamp = formatForDatabase(); // Returns ISO string
const now = getCurrentTimestamp(); // Alias for formatForDatabase()
// For display formatting
const displayTime = formatForDisplay(timestamp);
```
**Frontend** (`frontend/src/utils/timestampUtils.ts`):
```typescript
import { parseTimestamp, formatDuration, getTimeDifference } from '../utils/timestampUtils';
// Parse SQLite timestamps correctly
const date = parseTimestamp("2024-01-01 12:00:00"); // Handles UTC conversion
// Calculate durations
const durationMs = getTimeDifference(startTime, endTime);
const formatted = formatDuration(durationMs); // "2m 34s"
// Display relative time
const ago = formatDistanceToNow(timestamp); // "5 minutes ago"
```
#### Database Operations
When working with timestamps in SQLite:
```sql
-- Use datetime() for UTC timestamps
INSERT INTO prompt_markers (timestamp) VALUES (datetime('now'));
-- When selecting, append 'Z' for proper UTC parsing
SELECT datetime(timestamp) || 'Z' as timestamp FROM prompt_markers;
-- For completion timestamps with NULL handling
SELECT
CASE
WHEN completion_timestamp IS NOT NULL
THEN datetime(completion_timestamp) || 'Z'
ELSE NULL
END as completion_timestamp
FROM prompt_markers;
```
#### Common Patterns
**Creating a new timestamp**:
```typescript
// Backend - for database storage
const timestamp = formatForDatabase();
// Frontend - for immediate use
const now = new Date();
```
**Tracking prompt execution time**:
```typescript
// When prompt starts
db.addPromptMarker(sessionId, promptText, outputIndex);
// When prompt completes
db.updatePromptMarkerCompletion(sessionId);
```
**Calculating duration**:
```typescript
// With completion timestamp
if (prompt.completion_timestamp) {
const duration = getTimeDifference(prompt.timestamp, prompt.completion_timestamp);
return formatDuration(duration);
}
// For ongoing prompts
const duration = getTimeDifference(prompt.timestamp); // Uses current time as end
return formatDuration(duration) + ' (ongoing)';
```
#### Common Pitfalls to Avoid
1. **Never parse SQLite timestamps directly with `new Date()`**:
```typescript
// ❌ WRONG - treats UTC as local time
const date = new Date("2024-01-01 12:00:00");
// ✅ CORRECT - uses parseTimestamp utility
const date = parseTimestamp("2024-01-01 12:00:00");
```
2. **Always validate timestamps before calculations**:
```typescript
if (!isValidTimestamp(timestamp)) {
return 'Unknown duration';
}
```
3. **Be careful with timezone conversions**:
```typescript
// Database stores UTC, display shows local
const dbTime = "2024-01-01 12:00:00"; // UTC
const parsed = parseTimestamp(dbTime); // Correctly handled as UTC
const display = formatForDisplay(parsed); // Converts to local for display
```
4. **Handle negative durations gracefully**:
```typescript
const duration = endTime - startTime;
if (duration < 0) {
console.warn('Negative duration detected');
return 'Invalid duration';
}
```
#### Testing Timestamp Code
When testing timestamp-related features:
1. Test with different timezones (especially negative UTC offsets)
2. Test with daylight saving time transitions
3. Test with very old and future timestamps
4. Test with invalid/malformed timestamps
5. Verify duration calculations are always positive
### State Management Guidelines
⚠️ **IMPORTANT**: Crystal follows a targeted update pattern for state management to minimize unnecessary re-renders and network requests.
#### Overview
Crystal uses a combination of Zustand stores, IPC events, and targeted updates to manage application state efficiently. The application prioritizes specific, targeted updates over global refreshes to improve performance and user experience.
#### Key Principles
1. **Targeted Updates**: Always update only the specific data that changed
2. **Event-Driven Updates**: Use IPC events to communicate changes between processes
3. **Avoid Global Refreshes**: Never reload entire lists when only one item changes
4. **Database as Source of Truth**: Frontend state should reflect backend state, not override it
#### State Update Patterns
**Session Updates**:
```typescript
// ❌ BAD: Global refresh
const handleSessionCreated = () => {
loadProjectsWithSessions(); // Reloads everything
};
// ✅ GOOD: Targeted update
const handleSessionCreated = (newSession: Session) => {
setProjectsWithSessions(prevProjects => {
return prevProjects.map(project => {
if (project.id === newSession.projectId) {
return {
...project,
sessions: [...project.sessions, newSession]
};
}
return project;
});
});
};
```
**Project Updates**:
```typescript
// ❌ BAD: Reload all projects
const handleProjectDeleted = () => {
fetchProjects(); // Network request for all projects
};
// ✅ GOOD: Remove from local state
const handleProjectDeleted = () => {
setProjects(prev => prev.filter(p => p.id !== deletedId));
};
```
#### IPC Event Handling
The application uses IPC events to synchronize state between the main process and renderer:
1. **Session Events**:
- `session:created` - Add new session to appropriate project
- `session:updated` - Update specific session properties
- `session:deleted` - Remove session from project list
2. **Project Events** (if implemented):
- `project:created` - Add new project to list
- `project:updated` - Update specific project properties
- `project:deleted` - Remove project from list
#### When Global Refreshes Are Acceptable
- **Initial Load**: When component mounts for the first time
- **User-Triggered Refresh**: When user explicitly requests a refresh
- **Error Recovery**: After connection loss or critical errors
- **Complex State Changes**: When multiple interdependent items change
#### Implementation Examples
**DraggableProjectTreeView.tsx**:
- Uses targeted updates for session creation, update, and deletion
- Only reloads all data on initial mount or when critical errors occur
- Maintains local state synchronized with backend through IPC events
**ProjectSelector.tsx**:
- Updates project list locally when projects are deleted
- Falls back to refresh only when necessary (e.g., complex updates)
#### Best Practices
1. **Use State Setters with Callbacks**: Always use the callback form of setState to ensure you're working with the latest state
2. **Merge Updates**: When updating objects, spread existing properties to preserve data
3. **Handle Edge Cases**: Always check if the item exists before updating
4. **Log State Changes**: Add console logs for debugging state updates in development
5. **Validate IPC Data**: Ensure IPC events contain expected data structure
### Diff Viewer CSS Troubleshooting
⚠️ **IMPORTANT**: The diff viewer (react-diff-viewer-continued) has specific CSS requirements that can be tricky to debug.
#### Common Issue: No Scrollbars on Diff Viewer
If the diff viewer content is cut off and scrollbars don't appear:
1. **DO NOT add complex CSS overrides** - This often makes the problem worse
2. **Check parent containers for `overflow-hidden`** - This is usually the root cause
3. **Use simple `overflow: 'auto'`** on the immediate diff container
4. **Remove any forced widths or min-widths** unless absolutely necessary
#### The Solution That Works:
```tsx
// In DiffViewer.tsx - Keep it simple!
<div className="border border-t-0 border-gray-600 rounded-b-lg" style={{ overflow: 'auto', maxHeight: '600px' }}>
<ReactDiffViewer
oldValue={file.oldValue || ''}
newValue={file.newValue || ''}
splitView={viewType === 'split'}
useDarkTheme={isDarkMode}
styles={currentStyles}
// Don't add complex style overrides here
/>
</div>
```
#### What NOT to Do:
- Don't add multiple wrapper divs with conflicting overflow settings
- Don't use CSS-in-JS to override react-diff-viewer's internal styles
- Don't add global CSS selectors targeting generated class names
- Don't use JavaScript hacks to force reflows
#### Root Cause:
The issue is typically caused by parent containers having `overflow-hidden` which prevents child scrollbars from appearing. Check these files:
- `SessionView.tsx` - Look for `overflow-hidden` classes
- `CombinedDiffView.tsx` - Check both the main container and flex containers
- `App.tsx` - Sometimes the issue starts at the app root level
The react-diff-viewer-continued library uses emotion/styled-components internally, which makes CSS overrides unreliable. The best approach is to ensure proper overflow handling in parent containers and keep the diff viewer wrapper simple.
## API Endpoints
### Session Management
@ -319,112 +571,68 @@ This modular structure improves maintainability and makes it easier to locate an
## Available Commands
### Setup & Installation
```bash
pnpm run setup # One-time setup (install, build, and rebuild native modules)
```
# One-time setup (install, build, and rebuild native modules)
pnpm run setup
### Development
```bash
pnpm electron-dev # Run as Electron app in development mode
pnpm run dev # Shorthand for electron-dev
pnpm dev # Run frontend only (without Electron shell)
# Run as Electron app in development mode
pnpm electron-dev
# Or use the shorthand:
pnpm run dev
# Run frontend only (without Electron shell)
pnpm dev
# Build for production
pnpm build
# Type checking
pnpm typecheck
# Linting
pnpm lint
```
**Note:** You must run `pnpm run build:main` at least once before running `pnpm electron-dev` to compile the main process.
### Building
```bash
pnpm build # Build for production (all platforms)
pnpm build:main # Build main process only
pnpm build:frontend # Build frontend only
```
### Building Packaged Electron App
```bash
pnpm build:mac # Build for macOS (universal)
pnpm build:mac:x64 # Build for macOS (Intel only)
pnpm build:mac:arm64 # Build for macOS (Apple Silicon only)
pnpm build:linux # Build for Linux
```
### Testing
```bash
pnpm test # Run Playwright tests
pnpm test:ui # Run tests with Playwright UI
pnpm test:headed # Run tests in headed browser mode
```
### Code Quality
```bash
pnpm typecheck # Type checking across all workspaces
pnpm lint # Linting across all workspaces
# Build for macOS
pnpm build:mac # macOS (only works on macOS)
```
## Project Structure
```javascript
```
crystal/
├── frontend/ # React renderer process
│ ├── src/
│ │ ├── components/ # React components (50+ files)
│ │ │ ├── panels/ # Panel components (Terminal, Claude, Codex, Diff, Editor, Logs, Dashboard, SetupTasks)
│ │ ├── components/ # React components
│ │ │ ├── Help.tsx # Help dialog
│ │ │ ├── DraggableProjectTreeView.tsx # Main project/session tree UI
│ │ │ └── ... # Other UI components
│ │ ├── hooks/ # Custom React hooks (9 hooks)
│ │ │ ├── useSessionView.ts # Session view logic (1,694 lines)
│ │ │ ├── useClaudePanel.ts # Claude panel state
│ │ │ ├── useCodexPanel.ts # Codex panel state
│ │ │ └── ... # Other hooks
│ │ │ └── ... # Other UI components
│ │ ├── hooks/ # Custom React hooks
│ │ │ └── useSessionView.ts # Session view logic (941 lines)
│ │ ├── stores/ # Zustand state stores
│ │ │ ├── sessionStore.ts # Session state (699 lines)
│ │ │ ├── panelStore.ts # Panel state
│ │ │ └── ... # Other stores
│ │ ├── contexts/ # React context providers
│ │ ├── services/ # Frontend services
│ │ └── utils/ # Utility functions
│ │ └── timestampUtils.ts # Timestamp handling
├── main/ # Electron main process
│ ├── src/
│ │ ├── index.ts # Main entry point (776 lines)
│ │ ├── index.ts # Main entry point (reduced to 414 lines)
│ │ ├── preload.ts # Preload script
│ │ ├── events.ts # Event handling (1,108 lines)
│ │ ├── events.ts # Event handling (359 lines)
│ │ ├── database/ # SQLite database
│ │ │ └── migrations/ # Database migration files
│ │ ├── ipc/ # IPC handlers (23 handlers)
│ │ │ ├── git.ts # Git operations (1,391 lines)
│ │ │ ├── session.ts # Session management (1,872 lines)
│ │ │ ├── file.ts # File operations (865 lines)
│ │ │ ├── claudePanel.ts # Claude panel management
│ │ │ ├── codexPanel.ts # Codex panel management
│ │ │ └── ... # 18 more IPC handlers
│ │ ├── services/ # Business logic services (33 modules)
│ │ │ ├── sessionManager.ts # Core session lifecycle (1,598 lines)
│ │ │ ├── worktreeManager.ts # Git worktree operations (931 lines)
│ │ │ ├── panelManager.ts # Panel lifecycle coordinator
│ │ │ ├── terminalPanelManager.ts # Terminal panel processes
│ │ │ ├── taskQueue.ts # Bull queue
│ │ │ └── panels/ # Panel-specific services
│ │ │ ├── claude/ # Claude CLI integration
│ │ │ ├── codex/ # Codex CLI integration
│ │ │ ├── cli/ # Abstract CLI manager
│ │ │ └── ai/ # Abstract AI panel base
│ │ ├── polyfills/ # Node.js polyfills
│ │ ├── types/ # TypeScript types
│ │ └── utils/ # Utility functions
│ │ └── timestampUtils.ts # Timestamp handling
│ │ ├── ipc/ # IPC handlers (modular)
│ │ │ ├── git.ts # Git operation handlers (843 lines)
│ │ │ ├── session.ts # Session operation handlers (428 lines)
│ │ │ └── ... # Other IPC handlers
│ │ ├── services/ # Business logic services
│ │ │ ├── taskQueue.ts # Bull queue for async tasks
│ │ │ └── ... # Other service modules
│ │ ├── routes/ # API routes
│ │ └── types/ # TypeScript types
│ └── dist/ # Compiled output
├── shared/ # Shared TypeScript types
│ └── types/
│ └── panels.ts # Panel type definitions
├── tests/ # E2E tests (Playwright)
├── scripts/ # Build and utility scripts
├── docs/ # Documentation
│ ├── troubleshooting/ # Troubleshooting guides
│ ├── ADDING_NEW_CLI_TOOLS.md
│ └── IMPLEMENTING_NEW_CLI_AGENTS.md
├── dist-electron/ # Packaged Electron app (generated during build)
├── dist-electron/ # Packaged Electron app
├── package.json # Root workspace configuration
└── pnpm-workspace.yaml
```
@ -477,40 +685,30 @@ Enable verbose logging in Settings to see detailed logs for troubleshooting.
In development mode, Crystal automatically captures all frontend console logs and writes them to a file that Claude Code can read for debugging purposes.
**Location**: `crystal-frontend-debug.log` and `crystal-backend-debug.log`in the project root directory
**Location**: `crystal-frontend-debug.log` in the project root directory
**What gets logged**:
- All `console.log`, `console.warn`, `console.error`, `console.info`, and `console.debug` calls from the React frontend
- Automatic console messages from Electron's webContents (warnings, errors)
- Timestamp, log level, and source information for each message
**Example log format**:
```
[2024-07-21T15:30:45.123Z] [RENDERER LOG] User clicked session creation button
[2024-07-21T15:30:45.234Z] [FRONTEND WARNING] Session validation failed: missing prompt
[2024-07-21T15:30:45.345Z] [FRONTEND ERROR] Failed to create session (SessionView.tsx:123)
```
**Usage for Claude Code debugging**:
1. Add debug console.log statements to frontend components
2. Reproduce the issue in the Crystal app
3. Read `crystal-frontend-debug.log` and `crystal-backend-debug.log` to see what happened
3. Read `crystal-frontend-debug.log` to see what happened
4. No need to manually check Chrome DevTools or ask humans to copy logs
`crystal-frontend-debug.log` and `crystal-backend-debug.log` are reset every time the user runs in development mode, so if they report that a change is not working, you can look at those logs and they will represent the session they tested the change.
**IMPORTANT** Logs are best investigated in a sub-agent
**File rotation**: The log file grows continuously during development. Delete or truncate it manually if it gets too large.
**Note**: This feature is only active in development mode and will not affect production builds.
## TypeScript Coding Standards
### NO 'ANY' TYPE USAGE
**IMPORTANT**: This codebase enforces a strict no-any policy. The TypeScript 'any' type is NOT allowed.
- ❌ **NEVER use \****`any`**\*\* type** - ESLint will error and CI/CD will fail
- ✅ Use `unknown` when the type is truly unknown (requires type guards before use)
- ✅ Use specific types or interfaces whenever possible
- ✅ Use generics with type constraints for flexible but type-safe code
**Enforcement**:
- ESLint rule `@typescript-eslint/no-explicit-any` is set to `'error'`
- GitHub Actions quality workflow enforces this on all PRs
- Local development will show errors immediately
## Disclaimer
Crystal is an independent project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Claude™ is a trademark of Anthropic, PBC. Crystal is not affiliated with, endorsed by, or sponsored by Anthropic. This tool is designed to work with Claude Code, which must be installed separately.

View File

@ -4,10 +4,6 @@ Thank you for your interest in contributing to Crystal! We welcome contributions
Crystal is an open source project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Stravu is the way AI-first teams collaborate.
## Right to Contribute this Code
- You represent and warrant that You are legally entitled to contribute the code you contribute to Crystal
- You represent and warrant that each of Your Contributions is Your original creation. You represent and warrant that, to Your knowledge, none of Your Contributions infringe, violate, or misappropriate any third party intellectual property or other proprietary rights.
## Getting Started
1. Fork the repository on GitHub

609
NOTICES

File diff suppressed because it is too large Load Diff

190
README.md
View File

@ -1,56 +1,150 @@
# Crystal - Multi-Session Claude Code Manager
<div align="center">
<a href="https://nimbalyst.com/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://nimbalyst.com/nimbalyst-logo-white.svg" />
<img src="https://nimbalyst.com/nimbalyst-logo.svg" alt="Nimbalyst Logo" width="260" />
</picture>
</a>
<p><a href="https://nimbalyst.com/">https://nimbalyst.com/</a></p>
<p><a href="https://nimbalyst.com/download/">Download here</a></p>
<h3><a href="https://github.com/stravu/crystal/releases/latest">**Get the Latest Release Here**</a></h3>
</div>
<div align="center">
<h1>Crystal Is Now Nimbalyst</h1>
<p>Crystal (formerly a multi-session AI code assistant manager) has been deprecated and replaced by <strong>Nimbalyst</strong>.</p>
<p>Deprecated: February 2026.</p>
[![Build](https://github.com/stravu/crystal/actions/workflows/build.yml/badge.svg)](https://github.com/stravu/crystal/actions/workflows/build.yml)
[![Quality](https://github.com/stravu/crystal/actions/workflows/quality.yml/badge.svg)](https://github.com/stravu/crystal/actions/workflows/quality.yml)
[![Join our Discord](https://img.shields.io/badge/Join%20our-Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white)](https://discord.gg/XrVa6q7DPY)
</div>
Crystal is an Electron desktop application that lets you run, inspect, and test multiple Claude Code instances simultaneously using git worktrees. Crystal is an independent project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Stravu provides editable, collaborate AI notebooks with text, tables, diagrams.
https://github.com/user-attachments/assets/e32f0ee7-c25a-43d6-a704-8a39878032eb
## The Crystal Workflow
1. Create sessions from prompts, each in an isolated git worktree
2. Iterate with Claude Code inside your sessions. Each iteration will make a commit so you can always go back.
3. Review the diff changes and make manual edits as needed
4. Squash your commits together with a new message and rebase to your main branch.
## ✨ Key Features
- **🚀 Parallel Sessions** - Run multiple Claude Code instances at once
- **🌳 Git Worktree Isolation** - Each session gets its own branch
- **💾 Session Persistence** - Resume conversations anytime
- **🔧 Git Integration** - Built-in rebase and squash operations
- **📊 Change Tracking** - View diffs and track modifications
- **🔔 Notifications** - Desktop alerts when sessions need input
- **🏗️ Run Scripts** - Test changes instantly without leaving Crystal
## 🚀 Quick Start
### Prerequisites
- Claude Code installed and logged in or API key provided
- Git installed
- Git repository (Crystal will initialize one if needed)
### 1. Create a Project
Create a new project if you haven't already. This can be an empty folder or an existing git repository. Crystal will initialize git if needed.
### 2. Create Sessions from a Prompt
For any feature you're working on, create one or multiple new sessions:
- Each session will be an isolated git worktree
### 3. Monitor and Test Your Changes
As sessions complete:
- **Configure run scripts** in project settings to test your application without leaving Crystal
- **Use the diff viewer** to review all changes and make manual edits as needed
- **Continue conversations** with Claude Code if you need additional changes
### 4. Finalize Your Changes
When everything looks good:
- Click **"Rebase to main"** to squash all commits with a new message and rebase them to your main branch
- This creates a clean commit history on your main branch
### Git Operations
- **Rebase from main**: Pull latest changes from main into your worktree
- **Squash and rebase to main**: Combine all commits and rebase onto main
- Always preview commands with tooltips before executing
## Installation
### Download Pre-built Binaries
- **macOS**: Download `Crystal-{version}.dmg` from the [latest release](https://github.com/stravu/crystal/releases/latest)
- Open the DMG file and drag Crystal to your Applications folder
- On first launch, you may need to right-click and select "Open" due to macOS security settings
## Building from Source
```bash
# Clone the repository
git clone https://github.com/stravu/crystal.git
cd crystal
# One-time setup
pnpm run setup
# Run in development
pnpm run electron-dev
```
## Building for Production
```bash
# Build for macOS
pnpm build:mac
```
## 🤝 Contributing
We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.
### Developing Crystal with Crystal
If you're using Crystal to develop Crystal itself, you need to use a separate data directory to avoid conflicts with your main Crystal instance:
```bash
# Set the run script in your Crystal project settings to:
pnpm run setup && pnpm run build:main && CRYSTAL_DIR=~/.crystal_test pnpm electron-dev
```
This ensures:
- Your development Crystal instance uses `~/.crystal_test` for its data
- Your main Crystal instance continues using `~/.crystal`
- Worktrees won't conflict between the two instances
- You can safely test changes without affecting your primary Crystal setup
## Additional Documentation
For a full project overview, see [CLAUDE.md](CLAUDE.md). Additional diagrams, database schema details, release instructions, and license notes can be found in the [docs](./docs) directory.
## 📄 License
Crystal is open source software licensed under the [MIT License](LICENSE).
### Third-Party Licenses
Crystal includes third-party software components. All third-party licenses are documented in the [NOTICES](NOTICES) file. This file is automatically generated and kept up-to-date with our dependencies.
To regenerate the NOTICES file after updating dependencies:
```bash
pnpm run generate-notices
```
## Disclaimer
Crystal is an independent project created by [Stravu](https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1). Claude™ is a trademark of Anthropic, PBC. Crystal is not affiliated with, endorsed by, or sponsored by Anthropic. This tool is designed to work with Claude Code, which must be installed separately.
---
<div align="center">
<a href="https://nimbalyst.com/">
<img src="https://nimbalyst.com/_astro/ai-agent-transcript.Bd8j1G0q_BQpgv.webp" alt="Nimbalyst Agent Window" width="960" />
</a>
<img src="frontend/public/stravu-logo.png" alt="Stravu Logo" width="80" height="80">
<br>
Made with ❤️ by <a href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1">Stravu</a>
</div>
## Migration
- Download Nimbalyst: https://nimbalyst.com/
- Documentation: https://docs.nimbalyst.com/
- GitHub repository: https://github.com/Nimbalyst/nimbalyst
## Nimbalyst Features
- AI-native workspace for human + AI collaboration
- AI agents that stream edits directly into open editors in real time
- Multi-editor environment for code, markdown, spreadsheets, diagrams, and visual docs
- Extension-first architecture for custom editor/file-type support
- Local-first file model using open formats like Markdown, JSON, and CSV
- Code-aware agent orchestration for implementation planning and task execution
- Git worktree isolation for safer parallel AI coding sessions
- Rich markdown editing with tables, code blocks, embeds, and formatting tools
- Monaco-based code editing experience for programming workflows
- RevoGrid-powered spreadsheet editing for CSV and tabular workflows
- Excalidraw integration for diagram and whiteboard workflows
- Visual data modeling tools for schema-centric work
- Visual mockup editing for interface ideation and iteration
- Unified editor lifecycle with consistent AI integration across editor types
- Auto-save and file watching for reliable local development workflows
- Project-level workspace management and AI session tracking
- Built on production-grade desktop foundations with Electron
## FAQ
- **Is Crystal discontinued?** Yes. Crystal is deprecated and replaced by Nimbalyst.
- **Can I still use Crystal?** Yes. You can continue using Crystal, but we recommend moving to Nimbalyst for active updates.
- **Where is Nimbalyst?** https://nimbalyst.com/
For downloads, documentation, and updates, go to **https://nimbalyst.com/**.

View File

@ -9,12 +9,6 @@ exports.default = async function(context) {
return;
}
// Check if we have signing certificates - if not, skip signing-related operations
const hasSigningCredentials = process.env.CSC_LINK || process.env.CSC_KEY_PASSWORD;
if (!hasSigningCredentials) {
console.log('AfterSign: No signing credentials found, skipping certificate-dependent operations');
}
console.log('AfterSign: Starting JAR cleanup process...');
console.log('AfterSign: appOutDir =', appOutDir);
console.log('AfterSign: productName =', packager.appInfo.productName);

View File

@ -1,720 +0,0 @@
# Adding New CLI Tools to Crystal
This guide explains how to extend Crystal to support additional CLI tools beyond Claude Code. Crystal's architecture has been designed with extensibility in mind, using abstract base classes and a registry pattern.
## Table of Contents
- [Overview](#overview)
- [Architecture](#architecture)
- [Step-by-Step Implementation](#step-by-step-implementation)
- [Testing Your Integration](#testing-your-integration)
- [Database Considerations](#database-considerations)
- [Best Practices](#best-practices)
## Overview
Crystal uses a modular architecture that allows you to add support for new CLI tools (like Aider, Continue, Cursor, etc.) by:
1. Creating a manager class that extends `AbstractCliManager`
2. Registering the tool in the CLI tool registry
3. Adding frontend panel components
4. Updating type definitions
## Architecture
### Key Components
```
┌─────────────────────────────────────────────────────┐
│ Frontend (React) │
├─────────────────────────────────────────────────────┤
│ CliPanelFactory → YourCliPanel → BaseCliPanel │
└─────────────────────────────────────────────────────┘
↕ IPC
┌─────────────────────────────────────────────────────┐
│ Main Process (Electron) │
├─────────────────────────────────────────────────────┤
│ CliToolRegistry → YourCliManager → AbstractCliManager │
└─────────────────────────────────────────────────────┘
```
### Core Classes
- **`AbstractCliManager`**: Base class providing common CLI management functionality
- **`CliToolRegistry`**: Singleton registry for managing CLI tools
- **`CliPanelFactory`**: Factory for rendering appropriate CLI panels
- **`BaseCliPanel`**: (Optional) Base React component with common UI elements
## Step-by-Step Implementation
### Step 1: Create Your CLI Manager
Create a new manager class in `main/src/services/panels/[your-cli]/`:
```typescript
// main/src/services/panels/aider/aiderManager.ts
import { AbstractCliManager } from '../cli/AbstractCliManager';
import type { Logger } from '../../../utils/logger';
import type { ConfigManager } from '../../configManager';
interface AiderSpawnOptions {
panelId: string;
sessionId: string;
worktreePath: string;
prompt: string;
conversationHistory?: string[];
// Add your CLI-specific options
model?: string;
editFormat?: 'whole' | 'diff' | 'patch';
}
export class AiderManager extends AbstractCliManager {
constructor(
sessionManager: any,
logger?: Logger,
configManager?: ConfigManager
) {
super(sessionManager, logger, configManager);
}
// Required abstract method implementations
protected getCliToolName(): string {
return 'Aider';
}
protected async testCliAvailability(customPath?: string): Promise<{
available: boolean;
error?: string;
version?: string;
path?: string;
}> {
// Implement CLI availability test
try {
const { execSync } = require('child_process');
const command = customPath || 'aider';
const version = execSync(`${command} --version`, { encoding: 'utf8' }).trim();
return {
available: true,
version,
path: command
};
} catch (error) {
return {
available: false,
error: `Aider not found: ${error}`
};
}
}
protected buildCommandArgs(options: AiderSpawnOptions): string[] {
const args: string[] = [];
// Add your CLI-specific arguments
if (options.model) {
args.push('--model', options.model);
}
if (options.editFormat) {
args.push('--edit-format', options.editFormat);
}
// Add the prompt
if (options.prompt) {
args.push('--message', options.prompt);
}
return args;
}
protected async getCliExecutablePath(): Promise<string> {
// Check for custom path in config
const customPath = this.configManager?.getConfig()?.aiderExecutablePath;
if (customPath) {
return customPath;
}
// Otherwise find in PATH
const { findExecutableInPath } = require('../../../utils/shellPath');
const foundPath = findExecutableInPath('aider');
if (!foundPath) {
throw new Error('Aider not found in PATH');
}
return foundPath;
}
protected parseCliOutput(
data: string,
panelId: string,
sessionId: string
): Array<{
panelId: string;
sessionId: string;
type: 'json' | 'stdout' | 'stderr';
data: any;
timestamp: Date;
}> {
// Parse your CLI's output format
const events = [];
// Example: if your CLI outputs JSON
try {
const jsonMessage = JSON.parse(data.trim());
events.push({
panelId,
sessionId,
type: 'json' as const,
data: jsonMessage,
timestamp: new Date()
});
} catch {
// Treat as regular output
events.push({
panelId,
sessionId,
type: 'stdout' as const,
data,
timestamp: new Date()
});
}
return events;
}
protected async initializeCliEnvironment(options: AiderSpawnOptions): Promise<{
[key: string]: string;
}> {
// Set up environment variables for your CLI
return {
AIDER_AUTO_COMMITS: 'false',
// Add other environment variables
};
}
protected async cleanupCliResources(sessionId: string): Promise<void> {
// Clean up any resources specific to your CLI
// e.g., temp files, cache, etc.
}
protected getCliNotAvailableMessage(error?: string): string {
return [
`Error: ${error}`,
'',
'Aider is not installed or not found in your PATH.',
'',
'Please install Aider:',
'1. Run: pip install aider-chat',
'2. Verify installation by running "aider --version" in your terminal',
'',
'If Aider is installed but not in your PATH:',
'- Add the Aider installation directory to your PATH',
'- Or set a custom Aider path in Crystal Settings'
].join('\n');
}
// Public methods for panel interaction
async startPanel(
panelId: string,
sessionId: string,
worktreePath: string,
prompt: string,
model?: string
): Promise<void> {
const options: AiderSpawnOptions = {
panelId,
sessionId,
worktreePath,
prompt,
model
};
return this.spawnCliProcess(options);
}
async continuePanel(
panelId: string,
sessionId: string,
worktreePath: string,
prompt: string,
conversationHistory: any[]
): Promise<void> {
// Implement continuation logic for your CLI
const options: AiderSpawnOptions = {
panelId,
sessionId,
worktreePath,
prompt,
conversationHistory
};
return this.spawnCliProcess(options);
}
async stopPanel(panelId: string): Promise<void> {
return this.killProcess(panelId);
}
}
```
### Step 2: Register Your CLI Tool
Add your tool to the registry in `main/src/services/cliManagerFactory.ts`:
```typescript
// main/src/services/cliManagerFactory.ts
import { AiderManager } from './panels/aider/aiderManager';
export function registerBuiltInTools(
registry: CliToolRegistry,
sessionManager: any,
logger?: Logger,
configManager?: ConfigManager,
permissionIpcPath?: string | null
): void {
// Existing Claude registration...
// Register Aider
registry.registerTool({
id: 'aider',
name: 'Aider',
description: 'AI pair programming in your terminal',
managerClass: AiderManager,
icon: 'terminal', // or custom icon
config: {
executablePath: 'aider',
defaultModel: 'gpt-4',
// Add other default config
}
});
}
```
### Step 3: Add Type Definitions
Update the shared types in `shared/types/`:
```typescript
// shared/types/panels.ts
export type ToolPanelType =
| 'terminal'
| 'claude'
| 'aider' // Add your tool here
| 'diff'
| 'editor'
| 'logs'
| 'dashboard';
// shared/types/cliPanels.ts
export type CliPanelType = 'claude' | 'aider'; // Add your tool here
// Add specific state interfaces if needed
export interface AiderPanelState {
model?: string;
editFormat?: 'whole' | 'diff' | 'patch';
autoCommits?: boolean;
}
```
### Step 4: Create Frontend Panel Component
Create your panel component in `frontend/src/components/panels/[your-cli]/`:
```typescript
// frontend/src/components/panels/aider/AiderPanel.tsx
import React, { useEffect, useState } from 'react';
import { Terminal } from 'lucide-react';
import { BaseCliPanel } from '../cli/BaseCliPanel'; // Optional
import { usePanelStore } from '../../../stores/panelStore';
interface AiderPanelProps {
panelId: string;
sessionId: string;
}
export const AiderPanel: React.FC<AiderPanelProps> = ({
panelId,
sessionId
}) => {
const { activePanel, panels } = usePanelStore();
const [output, setOutput] = useState<string[]>([]);
useEffect(() => {
// Set up IPC listeners for output
const handleOutput = (event: any, data: any) => {
if (data.panelId === panelId) {
setOutput(prev => [...prev, data.data]);
}
};
window.electron.on('panel:output', handleOutput);
// Initialize panel if needed
if (activePanel === panelId) {
window.electron.invoke('panels:initialize', panelId);
}
return () => {
window.electron.off('panel:output', handleOutput);
};
}, [panelId, activePanel]);
const handleInput = async (input: string) => {
await window.electron.invoke('panels:send-input', panelId, input);
};
return (
<div className="flex flex-col h-full">
<div className="flex items-center justify-between p-4 border-b border-border-primary">
<div className="flex items-center gap-2">
<Terminal className="w-4 h-4" />
<span className="font-medium">Aider</span>
</div>
</div>
<div className="flex-1 overflow-auto p-4">
{output.map((line, index) => (
<div key={index} className="font-mono text-sm">
{line}
</div>
))}
</div>
<div className="border-t border-border-primary p-4">
<input
type="text"
placeholder="Type your message..."
className="w-full px-3 py-2 bg-surface-secondary rounded"
onKeyPress={(e) => {
if (e.key === 'Enter') {
handleInput(e.currentTarget.value);
e.currentTarget.value = '';
}
}}
/>
</div>
</div>
);
};
```
### Step 5: Update Panel Factory
Add your panel to the factory in `frontend/src/components/panels/cli/CliPanelFactory.tsx`:
```typescript
// frontend/src/components/panels/cli/CliPanelFactory.tsx
import { AiderPanel } from '../aider/AiderPanel';
export const CliPanelFactory: React.FC<CliPanelFactoryProps> = ({
panel
}) => {
switch (panel.type) {
case 'claude':
return <ClaudePanel panelId={panel.id} sessionId={panel.session_id} />;
case 'aider':
return <AiderPanel panelId={panel.id} sessionId={panel.session_id} />;
default:
return (
<div className="p-4 text-text-secondary">
Unknown panel type: {panel.type}
</div>
);
}
};
```
### Step 6: Add IPC Handlers
Create IPC handlers for your CLI in `main/src/ipc/[your-cli].ts`:
```typescript
// main/src/ipc/aider.ts
import { ipcMain } from 'electron';
import { getCliManagerFactory } from '../services/cliManagerFactory';
export function registerAiderHandlers() {
const factory = getCliManagerFactory();
const registry = factory.getRegistry();
ipcMain.handle('aider:start', async (event, panelId, sessionId, options) => {
const manager = registry.createManager('aider');
return manager.startPanel(
panelId,
sessionId,
options.worktreePath,
options.prompt,
options.model
);
});
ipcMain.handle('aider:send-input', async (event, panelId, input) => {
const manager = registry.getManager('aider');
return manager.sendInput(panelId, input);
});
ipcMain.handle('aider:stop', async (event, panelId) => {
const manager = registry.getManager('aider');
return manager.stopPanel(panelId);
});
}
```
## Testing Your Integration
### 1. Test CLI Availability
```typescript
// In your test file or console
const manager = new AiderManager(sessionManager, logger, configManager);
const result = await manager.testCliAvailability();
console.log('Aider available:', result);
```
### 2. Test Process Spawning
```typescript
// Test spawning a process
await manager.startPanel(
'test-panel-1',
'test-session-1',
'/path/to/project',
'Hello from Aider'
);
```
### 3. Test Output Parsing
```typescript
// Test your output parser
const output = manager.parseCliOutput(
'{"type": "message", "content": "Hello"}',
'panel-1',
'session-1'
);
console.log('Parsed output:', output);
```
## Database Considerations
Crystal's database schema is flexible and can accommodate new CLI tools without migration:
- The `tool_panels` table has a `type` column that accepts any string value
- Panel-specific state is stored as JSON in the `state` column
- No schema changes are needed for new CLI tools
### Storing CLI-Specific Data
```typescript
// When creating a panel
const panelData = {
id: generateId(),
session_id: sessionId,
type: 'aider', // Your CLI type
name: 'Aider Session',
state: JSON.stringify({
model: 'gpt-4',
editFormat: 'diff',
// Your CLI-specific state
})
};
```
## Best Practices
### 1. Error Handling
Always provide clear error messages and recovery paths:
```typescript
protected async testCliAvailability(): Promise<CliAvailabilityResult> {
try {
// Test CLI
} catch (error) {
return {
available: false,
error: this.getCliNotAvailableMessage(error.message)
};
}
}
```
### 2. Resource Cleanup
Always clean up resources when panels are closed:
```typescript
protected async cleanupCliResources(sessionId: string): Promise<void> {
// Clean up temp files
const tempDir = path.join(os.tmpdir(), `aider-${sessionId}`);
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true });
}
// Clear any caches
this.clearCache(sessionId);
}
```
### 3. Output Formatting
Provide consistent output formatting for better UX:
```typescript
protected parseCliOutput(data: string): OutputEvent[] {
// Detect different output types
if (this.isToolCall(data)) {
return this.formatToolCall(data);
}
if (this.isError(data)) {
return this.formatError(data);
}
return this.formatStandard(data);
}
```
### 4. Configuration
Allow users to customize CLI behavior:
```typescript
// In your manager
const getCliConfig = () => {
return {
executablePath: this.configManager?.getConfig()?.aiderPath,
defaultModel: this.configManager?.getConfig()?.aiderModel || 'gpt-4',
autoCommits: this.configManager?.getConfig()?.aiderAutoCommits ?? false
};
};
```
### 5. Process Management
Handle process lifecycle properly:
```typescript
// Override spawnCliProcess if needed for special handling
async spawnCliProcess(options: AiderSpawnOptions): Promise<void> {
// Pre-spawn setup
await this.validateEnvironment(options);
// Call parent implementation
await super.spawnCliProcess(options);
// Post-spawn setup
await this.initializeSession(options);
}
```
## Common Patterns
### Stream Processing
For CLIs that stream output:
```typescript
protected handleStreamData(chunk: Buffer, panelId: string): void {
const lines = chunk.toString().split('\n');
for (const line of lines) {
if (line.trim()) {
const events = this.parseCliOutput(line, panelId, this.getSessionId(panelId));
events.forEach(event => this.emit('output', event));
}
}
}
```
### Session Persistence
To support session resumption:
```typescript
async continuePanel(panelId: string, sessionId: string, ...args): Promise<void> {
// Load previous session state
const sessionState = await this.loadSessionState(sessionId);
// Reconstruct command with session context
const options = this.buildContinuationOptions(sessionState, ...args);
return this.spawnCliProcess(options);
}
```
### Interactive Commands
For CLIs that require interaction:
```typescript
async sendInput(panelId: string, input: string): Promise<void> {
const process = this.processes.get(panelId);
if (!process) {
throw new Error(`No process found for panel ${panelId}`);
}
// Handle special commands
if (this.isSpecialCommand(input)) {
return this.handleSpecialCommand(panelId, input);
}
// Send to CLI
process.write(input + '\n');
}
```
## Troubleshooting
### Common Issues
1. **CLI not found**: Ensure the CLI is installed and in PATH
2. **Process won't start**: Check permissions and working directory
3. **Output not displaying**: Verify output parsing and event emission
4. **Panel not updating**: Check IPC event listeners and handlers
### Debug Tips
1. Enable verbose logging in your manager
2. Add console.log statements in critical paths
3. Use Chrome DevTools for frontend debugging
4. Check the main process console for backend errors
## Examples
### Minimal CLI Integration
For a simple CLI that just needs basic I/O:
```typescript
export class SimpleCliManager extends AbstractCliManager {
protected getCliToolName(): string {
return 'SimpleCLI';
}
protected buildCommandArgs(options: any): string[] {
return [options.prompt];
}
protected async getCliExecutablePath(): Promise<string> {
return 'simple-cli';
}
// Use default implementations for other methods
}
```
### Advanced CLI Integration
For complex CLIs with multiple features:
```typescript
export class AdvancedCliManager extends AbstractCliManager {
private sessions = new Map<string, SessionContext>();
private configCache = new Map<string, any>();
// Override multiple methods for advanced behavior
// Add session management, caching, etc.
}
```
## Contributing
When adding a new CLI tool to Crystal:
1. Follow the existing code style and patterns
2. Add comprehensive error handling
3. Include debug logging for troubleshooting
4. Test thoroughly with different scenarios
5. Update this documentation if you discover new patterns
## Support
For questions or issues with CLI integration:
1. Check existing CLI implementations (ClaudeCodeManager) for examples
2. Review the AbstractCliManager base class documentation
3. Open an issue on the Crystal GitHub repository

View File

@ -1,304 +0,0 @@
# Analytics UI Events Integration Guide
This document describes how to integrate UI interaction event tracking into Crystal's frontend components.
## Overview
The analytics system has been implemented with:
1. Backend IPC handlers in `/main/src/ipc/analytics.ts`
2. AnalyticsManager service enhancements to support string arrays
3. Frontend service utility in `/frontend/src/services/analyticsService.ts`
4. Preload script exposure for secure IPC communication
## Backend Implementation
### IPC Handlers
- **File**: `/main/src/ipc/analytics.ts`
- **Registered**: In `/main/src/ipc/index.ts`
- **Service Integration**: AnalyticsManager added to AppServices in `/main/src/ipc/types.ts`
### IPC Endpoints
1. `analytics:track-ui-event` - Track UI interaction events
2. `analytics:categorize-result-count` - Helper to categorize search result counts
3. `analytics:hash-session-id` - Helper to hash session IDs for privacy
## Frontend Integration Points
### Using the AnalyticsService
Import the service:
```typescript
import { AnalyticsService } from '@/services/analyticsService';
```
### Event 1: view_switched
**Track when users switch between tabs (Output, Diff, Logs, Editor, etc.)**
**Where to implement:**
- Component: `/frontend/src/components/SessionView.tsx` or `/frontend/src/hooks/useSessionView.ts`
- Trigger: When user clicks on a tab to switch views
- Implementation example:
```typescript
const handleViewSwitch = async (fromView: string, toView: string, sessionId?: string) => {
// Hash the session ID for privacy
const sessionIdHash = sessionId
? await AnalyticsService.hashSessionId(sessionId)
: undefined;
await AnalyticsService.trackViewSwitched({
from_view: fromView,
to_view: toView,
session_id_hash: sessionIdHash,
});
};
```
**View names to use:**
- `output` - Main output view
- `diff` - Git diff view
- `logs` - Logs/terminal view
- `editor` - Editor view
- `dashboard` - Dashboard view
### Event 2: help_dialog_opened
**Track when users open the help dialog**
**Where to implement:**
- Component: `/frontend/src/components/Help.tsx` (or wherever the help dialog trigger is)
- Trigger: When the help button/icon is clicked
- Implementation example:
```typescript
const handleHelpOpen = async (location: string) => {
await AnalyticsService.trackHelpDialogOpened({
from_location: location,
});
// Then open the help dialog
setShowHelp(true);
};
```
**Location values to use:**
- `sidebar` - From sidebar help button
- `toolbar` - From toolbar help button
- `settings` - From settings page
- `keyboard_shortcut` - From keyboard shortcut
### Event 3: settings_opened
**Track when users open settings**
**Where to implement:**
- Component: `/frontend/src/components/Settings.tsx` (or wherever settings trigger is)
- Trigger: When settings dialog/page is opened
- Implementation example:
```typescript
const handleSettingsOpen = async (location: string) => {
await AnalyticsService.trackSettingsOpened({
from_location: location,
});
// Then open settings
setShowSettings(true);
};
```
**Location values to use:**
- `sidebar` - From sidebar settings button
- `menu` - From menu bar
- `keyboard_shortcut` - From keyboard shortcut
### Event 4: settings_saved
**Track when users save settings changes**
**Where to implement:**
- Component: `/frontend/src/components/Settings.tsx`
- Trigger: When user clicks "Save" or settings are persisted
- Implementation example:
```typescript
const handleSettingsSave = async (category: string, changedKeys: string[]) => {
await AnalyticsService.trackSettingsSaved({
category: category,
setting_keys: changedKeys,
});
// Then save the settings
await window.electronAPI.config.update(updatedSettings);
};
```
**Category values to use:**
- `general` - General settings
- `notifications` - Notification settings
- `project` - Project-specific settings
- `appearance` - UI/appearance settings
- `advanced` - Advanced settings
**Setting keys examples:**
- `verbose_logging`
- `api_key`
- `notification_enabled`
- `notification_sound`
- `custom_prompt`
- `main_branch`
### Event 5: sidebar_toggled
**Track when users show/hide the sidebar**
**Where to implement:**
- Component: Main layout component (likely in `/frontend/src/App.tsx` or similar)
- Trigger: When sidebar visibility changes
- Implementation example:
```typescript
const handleSidebarToggle = async (isVisible: boolean) => {
await AnalyticsService.trackSidebarToggled({
is_visible: isVisible,
});
// Then toggle sidebar
setSidebarVisible(isVisible);
};
```
### Event 6: search_used
**Track when users use search functionality**
**Where to implement:**
- Component: Search components (likely in `/frontend/src/components/DraggableProjectTreeView.tsx` or search bar component)
- Trigger: When search is executed (on Enter or search button click)
- Implementation example:
```typescript
const handleSearch = async (searchTerm: string, searchType: string, resultCount: number) => {
// Categorize the result count for privacy (don't track exact numbers)
const resultCategory = await AnalyticsService.categorizeResultCount(resultCount);
await AnalyticsService.trackSearchUsed({
search_type: searchType,
result_count_category: resultCategory,
});
// Note: Do NOT track the actual search term for privacy
};
```
**Search type values to use:**
- `sessions` - Searching sessions
- `prompts` - Searching prompts
- `files` - Searching files
- `projects` - Searching projects
**Result count categories** (automatically categorized by backend):
- `0-0` - No results
- `1-5` - Few results
- `6-10` - Some results
- `11-25` - Many results
- `26-50` - Lots of results
- `51-100` - Very many results
- `101+` - Tons of results
## Privacy Considerations
### Do NOT Track:
- ❌ Actual search terms
- ❌ File names or paths
- ❌ Prompt content
- ❌ User identifiable information
- ❌ Exact counts (use categories)
- ❌ Raw session IDs (always hash them)
### DO Track:
- ✅ Event types (which button was clicked)
- ✅ Categories and types
- ✅ Hashed/anonymized identifiers
- ✅ Boolean states (visible/hidden, enabled/disabled)
- ✅ Categorized counts (0-5, 6-10, etc.)
## Testing
To test analytics integration:
1. **Enable analytics** in settings
2. **Enable verbose logging** to see analytics events in the console
3. **Perform actions** that should trigger events
4. **Check logs** for messages like:
```
[Analytics] Tracked event: view_switched { from_view: 'output', to_view: 'diff', ... }
```
## Type Safety
The `AnalyticsService` class provides type-safe methods for all events. TypeScript will enforce:
- Correct event names
- Required properties for each event type
- Proper value types for each property
If you try to pass invalid data, you'll get a TypeScript error at compile time.
## Error Handling
All analytics methods:
- Are non-blocking (use `async/await` but don't wait for responses)
- Fail silently (errors are logged but don't break functionality)
- Check if analytics is enabled before tracking
- Handle cases where the electronAPI is not available
## Example: Complete Integration
Here's a complete example of integrating view switching in a component:
```typescript
import React, { useState } from 'react';
import { AnalyticsService } from '@/services/analyticsService';
export function SessionView({ sessionId }: { sessionId: string }) {
const [currentView, setCurrentView] = useState<'output' | 'diff' | 'logs' | 'editor'>('output');
const switchView = async (newView: typeof currentView) => {
// Track the view switch
const sessionIdHash = await AnalyticsService.hashSessionId(sessionId);
await AnalyticsService.trackViewSwitched({
from_view: currentView,
to_view: newView,
session_id_hash: sessionIdHash,
});
// Update the view
setCurrentView(newView);
};
return (
<div>
<div className="tabs">
<button onClick={() => switchView('output')}>Output</button>
<button onClick={() => switchView('diff')}>Diff</button>
<button onClick={() => switchView('logs')}>Logs</button>
<button onClick={() => switchView('editor')}>Editor</button>
</div>
{/* View content here */}
</div>
);
}
```
## Summary
All backend infrastructure is complete. Frontend developers should:
1. Import `AnalyticsService` from `/frontend/src/services/analyticsService.ts`
2. Call the appropriate tracking method when user actions occur
3. Follow the privacy guidelines (no PII, use hashing/categorization)
4. Test with verbose logging enabled to verify events are tracked
The tracking is opt-in (users can disable analytics in settings) and respects user privacy by design.

View File

@ -1,336 +0,0 @@
# Feature Usage Tracking Integration Guide
This document provides guidance on integrating the remaining feature usage tracking events into Crystal's frontend.
## Overview
The following feature usage events have been fully implemented:
- ✅ `run_script_executed` - Tracked in backend (logsManager)
- ✅ `notification_shown` - Tracked in frontend (useNotifications hook)
The following events require frontend integration:
- ⏳ `keyboard_shortcut_used` - Integration points documented below
- ⏳ `drag_drop_used` - Integration points documented below
## Keyboard Shortcut Tracking
### Event Properties
```typescript
{
shortcut_key: string; // e.g., "Cmd+Enter", "Ctrl+K", "Escape"
action: string; // e.g., "submit_input", "focus_search", "close_dialog"
}
```
### Integration Points
#### 1. AI Input Panels (Cmd/Ctrl+Enter)
**File**: `/frontend/src/hooks/useAIInputPanel.ts` (line ~311)
**Current Code**:
```typescript
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
handleSubmit();
}
};
```
**Add Tracking**:
```typescript
import { AnalyticsService } from '../services/analyticsService';
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
handleSubmit();
// Track keyboard shortcut usage
AnalyticsService.trackKeyboardShortcut({
shortcut_key: `${e.metaKey ? 'Cmd' : 'Ctrl'}+Enter`,
action: 'submit_ai_input',
}).catch(console.error);
}
};
```
#### 2. Session Input (Cmd/Ctrl+Enter)
**File**: `/frontend/src/components/session/SessionInput.tsx` (line ~50-60)
**Similar pattern** - Add tracking when Cmd/Ctrl+Enter is pressed to submit session input.
#### 3. File Editor Shortcuts
**File**: `/frontend/src/components/panels/editor/FileEditor.tsx`
**Keyboard shortcuts to track**:
- Save file: `Cmd/Ctrl+S`
- Close editor: `Escape`
- Any other Monaco editor keyboard shortcuts
**Add event listener**:
```typescript
// In useEffect or Monaco configuration
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
handleSave();
AnalyticsService.trackKeyboardShortcut({
shortcut_key: 'Cmd+S',
action: 'save_file',
}).catch(console.error);
});
```
#### 4. Dialog Shortcuts (Escape to close)
**Files to check**:
- `/frontend/src/components/CreateSessionDialog.tsx`
- `/frontend/src/components/CommitDialog.tsx`
- `/frontend/src/components/ConfirmDialog.tsx`
- `/frontend/src/components/Help.tsx`
**Pattern**:
```typescript
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
handleClose();
AnalyticsService.trackKeyboardShortcut({
shortcut_key: 'Escape',
action: 'close_dialog',
}).catch(console.error);
}
};
```
#### 5. Search/Navigation Shortcuts
**File**: `/frontend/src/components/DraggableProjectTreeView.tsx`
If implementing keyboard shortcuts for search or navigation (e.g., `/` to focus search, arrow keys for navigation), track them here.
### Analytics Service Method to Add
**File**: `/frontend/src/services/analyticsService.ts`
```typescript
export interface KeyboardShortcutProperties {
shortcut_key: string;
action: string;
}
// In UIEventName type
export type UIEventName =
| 'view_switched'
| 'help_dialog_opened'
| 'settings_opened'
| 'settings_saved'
| 'sidebar_toggled'
| 'search_used'
| 'notification_shown'
| 'keyboard_shortcut_used'; // Add this
// Add method to class
static async trackKeyboardShortcut(properties: KeyboardShortcutProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'keyboard_shortcut_used',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track keyboard_shortcut_used:', error);
}
}
```
### Backend IPC Handler Update
**File**: `/main/src/ipc/analytics.ts`
```typescript
interface KeyboardShortcutUsedEvent extends Record<string, string | number | boolean | string[] | undefined> {
shortcut_key: string;
action: string;
}
type AnalyticsEventData =
| { event: 'view_switched'; properties: ViewSwitchedEvent }
| { event: 'help_dialog_opened'; properties: HelpDialogOpenedEvent }
| { event: 'settings_opened'; properties: SettingsOpenedEvent }
| { event: 'settings_saved'; properties: SettingsSavedEvent }
| { event: 'sidebar_toggled'; properties: SidebarToggledEvent }
| { event: 'search_used'; properties: SearchUsedEvent }
| { event: 'notification_shown'; properties: NotificationShownEvent }
| { event: 'keyboard_shortcut_used'; properties: KeyboardShortcutUsedEvent };
```
---
## Drag and Drop Tracking
### Event Properties
```typescript
{
item_type: string; // "session" | "folder" | "project"
target_type: string; // "session" | "folder" | "project" | "root"
}
```
### Integration Point
**File**: `/frontend/src/components/DraggableProjectTreeView.tsx`
This component already has comprehensive drag-and-drop functionality. The drag state is managed in the `dragState` state variable.
#### Key Handlers to Instrument
**1. handleDrop handler** (line ~800-1000)
This is the main drop handler where drag-and-drop actions are completed. Add tracking here.
**Current pattern**:
```typescript
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
// ... existing drop logic ...
if (dragState.type && dragState.overType) {
// Handle different drop scenarios
// ... move session, move folder, etc. ...
}
// Reset drag state
setDragState({ ... });
};
```
**Add Tracking**:
```typescript
import { AnalyticsService } from '../services/analyticsService';
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
const sourceType = dragState.type;
const targetType = dragState.overType;
// ... existing drop logic ...
if (sourceType && targetType) {
// Track successful drag and drop
AnalyticsService.trackDragDrop({
item_type: sourceType,
target_type: targetType,
}).catch(console.error);
}
// Reset drag state
setDragState({ ... });
};
```
**2. Track only successful drops**
Make sure to only track when the drop is successful and changes are saved to the database. Place the tracking call after successful API calls:
```typescript
// After successful session move
await API.sessions.update(dragState.sessionId, { folder_id: targetFolderId });
// Track the drag-drop action
AnalyticsService.trackDragDrop({
item_type: 'session',
target_type: targetType || 'root',
}).catch(console.error);
```
### Analytics Service Method to Add
**File**: `/frontend/src/services/analyticsService.ts`
```typescript
export interface DragDropUsedProperties {
item_type: string;
target_type: string;
}
// In UIEventName type
export type UIEventName =
| 'view_switched'
| 'help_dialog_opened'
| 'settings_opened'
| 'settings_saved'
| 'sidebar_toggled'
| 'search_used'
| 'notification_shown'
| 'keyboard_shortcut_used'
| 'drag_drop_used'; // Add this
// Add method to class
static async trackDragDrop(properties: DragDropUsedProperties): Promise<void> {
if (!this.isEnabled()) return;
try {
await window.electronAPI.analytics.trackUIEvent({
event: 'drag_drop_used',
properties,
});
} catch (error) {
console.error('[Analytics] Failed to track drag_drop_used:', error);
}
}
```
### Backend IPC Handler Update
**File**: `/main/src/ipc/analytics.ts`
```typescript
interface DragDropUsedEvent extends Record<string, string | number | boolean | string[] | undefined> {
item_type: string;
target_type: string;
}
type AnalyticsEventData =
| { event: 'view_switched'; properties: ViewSwitchedEvent }
| { event: 'help_dialog_opened'; properties: HelpDialogOpenedEvent }
| { event: 'settings_opened'; properties: SettingsOpenedEvent }
| { event: 'settings_saved'; properties: SettingsSavedEvent }
| { event: 'sidebar_toggled'; properties: SidebarToggledEvent }
| { event: 'search_used'; properties: SearchUsedEvent }
| { event: 'notification_shown'; properties: NotificationShownEvent }
| { event: 'keyboard_shortcut_used'; properties: KeyboardShortcutUsedEvent }
| { event: 'drag_drop_used'; properties: DragDropUsedEvent };
```
---
## Testing
After implementing the above tracking:
1. **Enable analytics** in Crystal settings
2. **Configure PostHog API key** in settings
3. **Use the features** that trigger the events:
- Press keyboard shortcuts
- Drag and drop sessions/folders
4. **Verify in PostHog dashboard** that events are being tracked
5. **Check console logs** for any tracking errors
## Privacy Considerations
- ✅ No user-identifiable information is tracked
- ✅ All session IDs are hashed before sending
- ✅ Only event counts and categorical data are tracked
- ✅ Users can disable analytics in settings
- ✅ Analytics respect the user's privacy preferences
## Summary
| Event | Status | Implementation |
|-------|--------|---------------|
| `run_script_executed` | ✅ Complete | Backend (logsManager.ts) |
| `notification_shown` | ✅ Complete | Frontend (useNotifications.ts) |
| `keyboard_shortcut_used` | ⏳ Documentation Ready | Follow integration guide above |
| `drag_drop_used` | ⏳ Documentation Ready | Follow integration guide above |

View File

@ -1,521 +0,0 @@
# Implementing New CLI Agents in Crystal
This guide provides step-by-step instructions for adding support for new CLI agent tools (like Aider, Continue, Cursor, etc.) to Crystal's architecture.
## Table of Contents
- [Overview](#overview)
- [Architecture Summary](#architecture-summary)
- [Implementation Steps](#implementation-steps)
- [File Structure](#file-structure)
- [Code Examples](#code-examples)
- [Testing Your Implementation](#testing-your-implementation)
- [Common Patterns](#common-patterns)
- [Troubleshooting](#troubleshooting)
## Overview
Crystal's architecture is designed to be extensible, allowing new CLI agents to be added with minimal modifications to existing code. The system follows a plugin-like pattern where each CLI tool is self-contained in its own directory structure.
### What You'll Need to Build
1. **New Files (90% of the work)**
- Backend manager class extending `AbstractCliManager`
- Frontend React panel component
- Protocol handlers (if needed)
- Utility functions specific to your CLI
2. **Minimal Modifications (10% of the work)**
- Register your tool (~4 lines)
- Update UI factory (~3 lines)
- Add type definitions (~2 lines)
## Architecture Summary
```
┌─────────────────────────────────────────────────┐
│ Crystal Application │
├─────────────────────────────────────────────────┤
│ │
│ Frontend (React) Backend (Electron) │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │ YourCliPanel │◄──IPC──►│ YourCliManager │ │
│ └──────────────┘ └──────────────────┘ │
│ ▲ │ │
│ │ ▼ │
│ ┌──────────────┐ ┌──────────────────┐ │
│ │CliPanelFactory│ │AbstractCliManager│ │
│ └──────────────┘ └──────────────────┘ │
│ │ │
└────────────────────────────────────┼────────────┘
▼
┌──────────────┐
│ Your CLI │
│ (External) │
└──────────────┘
```
## Implementation Steps
### Step 1: Create the Backend Manager
Create a new directory for your CLI in `main/src/services/panels/[your-cli]/` and implement the manager class:
```typescript
// main/src/services/panels/aider/aiderManager.ts
import { AbstractCliManager } from '../cli/AbstractCliManager';
export class AiderManager extends AbstractCliManager {
// Implement required abstract methods
protected getCliToolName(): string {
return 'Aider';
}
protected async testCliAvailability(customPath?: string): Promise<{
available: boolean;
error?: string;
version?: string;
path?: string;
}> {
// Test if CLI is installed
}
protected buildCommandArgs(options: any): string[] {
// Build command-line arguments
}
protected async getCliExecutablePath(): Promise<string> {
// Return path to CLI executable
}
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
// Parse CLI output into events
}
}
```
### Step 2: Create the Frontend Panel Component
Create React components in `frontend/src/components/panels/[your-cli]/`:
```typescript
// frontend/src/components/panels/aider/AiderPanel.tsx
import React from 'react';
export const AiderPanel: React.FC<{ panel: ToolPanel; isActive: boolean }> = ({ panel, isActive }) => {
// Implement your panel UI
return (
<div className="h-full flex flex-col">
{/* Your UI here */}
</div>
);
};
// Make it the default export for lazy loading
export default AiderPanel;
```
### Step 3: Register Your CLI Tool
Modify `main/src/services/cliManagerFactory.ts` to register your tool:
```typescript
// In registerBuiltInTools() method around line 149-159:
private registerBuiltInTools(): void {
// Existing registrations...
this.registerClaudeTool();
// Add your registration
this.registerAiderTool(); // ADD THIS LINE
}
// Add a new registration method:
private registerAiderTool(): void {
const aiderDefinition: CliToolDefinition = {
id: 'aider',
name: 'Aider',
description: 'AI pair programming in your terminal',
// ... other configuration
managerFactory: (sessionManager, logger, configManager) =>
new AiderManager(sessionManager, logger, configManager)
};
this.registry.registerTool(aiderDefinition);
}
```
### Step 4: Update the Frontend Panel Factory
Modify `frontend/src/components/panels/cli/CliPanelFactory.tsx`:
```typescript
// Add lazy import at the top (around line 82-83):
const AiderPanel = lazy(() => import('../aider/AiderPanel'));
// Add case in renderPanel() switch statement (around line 104-118):
case 'aider':
return (
<Suspense fallback={<LoadingFallback cliToolId={cliToolId} />}>
<AiderPanel panel={panel} isActive={isActive} />
</Suspense>
);
// Update supported tools list (around line 149):
const supportedTools = ['claude', 'codex', 'aider']; // ADD 'aider'
```
### Step 5: Update Type Definitions
Modify `shared/types/panels.ts`:
```typescript
// Update ToolPanelType union (line 10):
export type ToolPanelType = 'terminal' | 'claude' | 'codex' | 'aider' | 'diff' | 'editor' | 'logs' | 'dashboard';
// Add panel state interface if needed (optional):
export interface AiderPanelState extends BaseAIPanelState {
// Aider-specific state
editFormat?: 'whole' | 'diff' | 'patch';
autoCommits?: boolean;
}
```
## File Structure
Your implementation should follow this structure:
```
crystal/
├── main/src/services/panels/aider/ # Backend implementation
│ ├── aiderManager.ts # Main manager class (required)
│ ├── aiderProtocol.ts # Protocol handling (if needed)
│ ├── aiderMessageParser.ts # Output parsing utilities
│ └── types.ts # TypeScript interfaces
│
├── frontend/src/components/panels/aider/ # Frontend implementation
│ ├── AiderPanel.tsx # Main panel component (required)
│ ├── AiderOutput.tsx # Output display component
│ ├── AiderInput.tsx # Input component
│ ├── AiderToolCalls.tsx # Tool call visualization
│ └── styles.css # Component-specific styles
│
└── shared/types/ # Shared type definitions
└── aiderTypes.ts # Aider-specific types (optional)
```
## Code Examples
### Example: Simple CLI Manager
For a basic CLI that just needs stdin/stdout:
```typescript
export class SimpleCliManager extends AbstractCliManager {
protected getCliToolName(): string {
return 'SimpleCLI';
}
protected async testCliAvailability(customPath?: string): Promise<any> {
try {
const { execSync } = require('child_process');
const cmd = customPath || 'simple-cli';
const version = execSync(`${cmd} --version`, { encoding: 'utf8' });
return { available: true, version: version.trim(), path: cmd };
} catch {
return { available: false, error: 'CLI not found' };
}
}
protected buildCommandArgs(options: any): string[] {
return [options.prompt]; // Simple args
}
protected async getCliExecutablePath(): Promise<string> {
return 'simple-cli';
}
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
return [{
panelId,
sessionId,
type: 'stdout',
data,
timestamp: new Date()
}];
}
}
```
### Example: Protocol-Based CLI Manager
For CLIs using JSON-RPC or similar protocols:
```typescript
export class ProtocolCliManager extends AbstractCliManager {
private protocol: ProtocolHandler;
constructor(sessionManager: any, logger?: Logger, configManager?: ConfigManager) {
super(sessionManager, logger, configManager);
this.protocol = new ProtocolHandler();
}
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
try {
const message = JSON.parse(data);
return this.protocol.handleMessage(message, panelId, sessionId);
} catch {
// Fallback to plain text
return super.parseCliOutput(data, panelId, sessionId);
}
}
async sendInput(panelId: string, input: string): Promise<void> {
const message = this.protocol.createInputMessage(input);
const process = this.processes.get(panelId);
process?.write(JSON.stringify(message) + '\n');
}
}
```
### Example: Minimal Panel Component
```typescript
import React, { useEffect, useState } from 'react';
import { Terminal } from 'lucide-react';
export const MinimalPanel: React.FC<{ panel: any; isActive: boolean }> = ({ panel, isActive }) => {
const [output, setOutput] = useState<string[]>([]);
const [input, setInput] = useState('');
useEffect(() => {
// Listen for output
const handleOutput = (event: any, data: any) => {
if (data.panelId === panel.id) {
setOutput(prev => [...prev, data.data]);
}
};
window.electron.on('panel:output', handleOutput);
// Initialize panel when active
if (isActive && !panel.state.isInitialized) {
window.electron.invoke('panels:initialize', panel.id);
}
return () => {
window.electron.off('panel:output', handleOutput);
};
}, [panel.id, isActive]);
const handleSubmit = async () => {
if (input.trim()) {
await window.electron.invoke('panels:send-input', panel.id, input);
setInput('');
}
};
return (
<div className="h-full flex flex-col bg-surface-primary">
<div className="flex items-center gap-2 p-4 border-b border-border-primary">
<Terminal className="w-4 h-4" />
<span className="font-medium">My CLI Tool</span>
</div>
<div className="flex-1 overflow-auto p-4 font-mono text-sm">
{output.map((line, i) => (
<div key={i}>{line}</div>
))}
</div>
<div className="p-4 border-t border-border-primary">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSubmit()}
placeholder="Enter command..."
className="w-full px-3 py-2 bg-surface-secondary rounded"
/>
</div>
</div>
);
};
export default MinimalPanel;
```
## Testing Your Implementation
### 1. Test CLI Availability
```bash
# In the Electron dev console or a test file
const factory = require('./main/src/services/cliManagerFactory');
const manager = factory.createManager('aider', { sessionManager });
const result = await manager.testCliAvailability();
console.log('Aider available:', result);
```
### 2. Test Process Spawning
```typescript
// Test spawning a process
await manager.startPanel(
'test-panel-1',
'test-session-1',
'/path/to/project',
'Test prompt'
);
```
### 3. Test Frontend Integration
1. Run Crystal in development mode
2. Create a new session
3. Add a tool panel and select your CLI
4. Verify the panel renders and accepts input
## Common Patterns
### Pattern: Handling Authentication
If your CLI requires authentication:
```typescript
protected async initializeCliEnvironment(options: any): Promise<Record<string, string>> {
const apiKey = this.configManager?.getConfig()?.aiderApiKey;
if (!apiKey) {
throw new Error('API key required. Please configure in Settings.');
}
return {
AIDER_API_KEY: apiKey,
...process.env
};
}
```
### Pattern: Session Resumption
For CLIs that support resuming conversations:
```typescript
async continuePanel(panelId: string, sessionId: string, conversationHistory: any[]): Promise<void> {
const resumeArgs = this.buildResumeArgs(conversationHistory);
const options = {
panelId,
sessionId,
additionalArgs: resumeArgs
};
return this.spawnCliProcess(options);
}
private buildResumeArgs(history: any[]): string[] {
// Convert history to CLI-specific format
return ['--resume', JSON.stringify(history)];
}
```
### Pattern: Handling Tool Calls
For CLIs that perform file operations:
```typescript
protected parseCliOutput(data: string, panelId: string, sessionId: string): Array<any> {
const events = [];
// Detect tool calls
if (this.isToolCall(data)) {
const toolCall = this.parseToolCall(data);
events.push({
type: 'tool_call',
tool: toolCall.name,
args: toolCall.args
});
// Emit file change event if applicable
if (toolCall.name === 'write_file') {
this.emit('files:changed', {
panelId,
files: [toolCall.args.path]
});
}
}
return events;
}
```
## Troubleshooting
### Common Issues and Solutions
1. **CLI not found**
- Ensure the CLI is installed and in PATH
- Check `getCliExecutablePath()` returns correct path
- Verify `testCliAvailability()` handles errors properly
2. **Panel not rendering**
- Verify lazy import path is correct
- Check panel is registered in `CliPanelFactory`
- Ensure component has default export
3. **No output displayed**
- Check `parseCliOutput()` returns proper event format
- Verify IPC event listeners are set up
- Ensure panel ID matches in events
4. **Input not working**
- Verify process is running (`this.processes.get(panelId)`)
- Check input formatting matches CLI expectations
- Ensure write permissions on process stdin
### Debug Tips
1. **Enable verbose logging**:
```typescript
this.logger?.debug('[YourCli] Spawning process:', { command, args });
```
2. **Add console output in frontend**:
```typescript
console.log('[YourCliPanel] Received output:', data);
```
3. **Use Chrome DevTools**:
- Open DevTools in Electron (Cmd/Ctrl+Shift+I)
- Check Network tab for IPC calls
- Monitor Console for errors
4. **Test CLI directly**:
```bash
# Test your CLI works outside Crystal
your-cli --version
echo "test prompt" | your-cli
```
## Best Practices
1. **Error Handling**: Always provide clear error messages
2. **Resource Cleanup**: Implement proper cleanup in `cleanupCliResources()`
3. **State Persistence**: Store CLI-specific state for session resumption
4. **User Feedback**: Show loading states and error messages in UI
5. **Configuration**: Allow users to customize CLI behavior via settings
6. **Documentation**: Comment complex parsing or protocol logic
7. **Type Safety**: Use TypeScript interfaces for all data structures
8. **Testing**: Write unit tests for parsing and protocol logic
## Next Steps
After implementing your CLI:
1. Test thoroughly in development mode
2. Add configuration options to Settings UI
3. Update Help documentation
4. Consider contributing back to Crystal repository
5. Share your implementation with the community
For more details on specific aspects:
- [Abstract CLI Manager API](../main/src/services/panels/cli/AbstractCliManager.ts)
- [CLI Tool Registry](../main/src/services/cliToolRegistry.ts)
- [Example: Claude Implementation](../main/src/services/panels/claude/)
- [Example: Codex Implementation](../main/src/services/panels/codex/)

View File

@ -35,7 +35,7 @@ The following licenses are **not** compatible with MIT distribution:
## How We Check
The `check-license-compatibility.sh` script automatically validates that all dependencies use compatible licenses. It:
The `scripts/check-license-compatibility.sh` script automatically validates that all dependencies use compatible licenses. It:
1. Checks for truly incompatible licenses (GPL, AGPL, SSPL)
2. Notes LGPL dependencies (compatible but worth tracking)

204
docs/MESSAGES_TAB_FIX.md Normal file
View File

@ -0,0 +1,204 @@
# Messages Tab Fix Documentation
## Overview
This document details the fix implemented for the Messages tab in Crystal's session window. The Messages tab was intended to show JSON output from Claude Code for debugging purposes but was broken and not displaying any data.
## Problem Description
The Messages tab in the session view was supposed to display JSON messages from Claude Code instances for debugging, but it was showing "No messages yet" even when sessions had active Claude Code conversations. The issue was that there was no mechanism to load and populate the JSON messages data.
## Root Cause Analysis
1. **Missing Data Flow**: The `JsonMessageView` component expected `activeSession.jsonMessages` to be populated, but this array was always empty
2. **No Loading Mechanism**: There was no IPC handler or frontend logic to fetch JSON messages separately from regular output
3. **Data Transformation Issue**: The existing `sessions:get-output` handler was transforming JSON messages to formatted stdout for the Output tab, losing the original JSON structure
## Solution Architecture
The fix implements a complete end-to-end data flow:
```
Frontend (Messages Tab) → API Layer → IPC Handler → Session Manager → Database
```
### Key Components
1. **New IPC Handler**: `sessions:get-json-messages`
2. **Frontend API Method**: `API.sessions.getJsonMessages()`
3. **Session Store Method**: `setSessionJsonMessages()`
4. **Auto-loading Logic**: Effect hook that loads JSON messages when switching to Messages view
## Implementation Details
### 1. Backend IPC Handler (`main/src/ipc/session.ts`)
```typescript
ipcMain.handle('sessions:get-json-messages', async (_event, sessionId: string) => {
try {
const outputs = await sessionManager.getSessionOutputs(sessionId);
// Filter to only JSON messages and include timestamp
const jsonMessages = outputs
.filter(output => output.type === 'json')
.map(output => ({
...output.data,
timestamp: output.timestamp.toISOString()
}));
return { success: true, data: jsonMessages };
} catch (error) {
return { success: false, error: 'Failed to get JSON messages' };
}
});
```
**Purpose**: Extracts and returns only JSON-type outputs from session data, preserving the original JSON structure with timestamps.
### 2. Preload Script Update (`main/src/preload.ts`)
```typescript
getJsonMessages: (sessionId: string): Promise<IPCResponse> =>
ipcRenderer.invoke('sessions:get-json-messages', sessionId),
```
**Purpose**: Exposes the new IPC handler to the frontend through the secure preload script.
### 3. Frontend API Layer (`frontend/src/utils/api.ts`)
```typescript
async getJsonMessages(sessionId: string) {
if (!isElectron()) throw new Error('Electron API not available');
return window.electronAPI.sessions.getJsonMessages(sessionId);
}
```
**Purpose**: Provides a consistent API interface with error handling for the frontend to use.
### 4. Session Store Enhancement (`frontend/src/stores/sessionStore.ts`)
```typescript
setSessionJsonMessages: (sessionId, jsonMessages) => set((state) => {
// Update both regular sessions and activeMainRepoSession
const updatedSessions = state.sessions.map(session => {
if (session.id === sessionId) {
return { ...session, jsonMessages };
}
return session;
});
let updatedActiveMainRepoSession = state.activeMainRepoSession;
if (state.activeMainRepoSession?.id === sessionId) {
updatedActiveMainRepoSession = { ...state.activeMainRepoSession, jsonMessages };
}
return { ...state, sessions: updatedSessions, activeMainRepoSession: updatedActiveMainRepoSession };
})
```
**Purpose**: Updates session state with JSON messages while maintaining consistency between regular sessions and main repo sessions.
### 5. Session View Hook (`frontend/src/hooks/useSessionView.ts`)
```typescript
// Load JSON messages for the Messages tab
const loadJsonMessages = useCallback(async (sessionId: string) => {
try {
const response = await API.sessions.getJsonMessages(sessionId);
if (response.success) {
const jsonMessages = response.data || [];
useSessionStore.getState().setSessionJsonMessages(sessionId, jsonMessages);
}
} catch (error) {
console.error(`Error loading JSON messages:`, error);
}
}, []);
// Load JSON messages when switching to messages view
useEffect(() => {
if (!activeSession || viewMode !== 'messages') return;
loadJsonMessages(activeSession.id);
}, [activeSession?.id, viewMode, loadJsonMessages]);
```
**Purpose**: Automatically loads JSON messages when the user switches to the Messages tab, ensuring data is available when needed.
### 6. TypeScript Definitions (`frontend/src/types/electron.d.ts`)
```typescript
interface ElectronAPI {
sessions: {
// ... other methods
getJsonMessages: (sessionId: string) => Promise<IPCResponse>;
// ... other methods
};
}
```
**Purpose**: Provides type safety for the new IPC method in TypeScript.
## Data Flow
1. **User Action**: User clicks on "Messages" tab in session view
2. **View Mode Change**: `viewMode` state changes to 'messages'
3. **Effect Trigger**: useEffect hook detects the view mode change
4. **API Call**: `loadJsonMessages()` function calls `API.sessions.getJsonMessages()`
5. **IPC Communication**: Frontend calls the `sessions:get-json-messages` IPC handler
6. **Data Retrieval**: Backend fetches session outputs and filters for JSON messages
7. **Response**: Filtered JSON messages returned to frontend
8. **State Update**: `setSessionJsonMessages()` updates the session store
9. **UI Update**: `JsonMessageView` component re-renders with the new data
## Message Structure
JSON messages are formatted with the following structure:
```typescript
interface JsonMessage {
type: string; // e.g., 'system', 'user', 'assistant'
subtype?: string; // e.g., 'init', 'result'
content?: string; // Message content
data?: any; // Additional structured data
timestamp: string; // ISO timestamp
[key: string]: any; // Other fields from Claude Code
}
```
## Benefits
1. **Debugging Capability**: Developers can now inspect raw JSON messages from Claude Code
2. **Performance**: JSON messages are only loaded when the Messages tab is viewed
3. **Real-time**: Messages are loaded fresh each time the tab is accessed
4. **Type Safety**: Full TypeScript support for the new functionality
5. **Consistency**: Follows existing patterns in the codebase
## Testing
The fix was tested by:
1. **Type Checking**: `pnpm typecheck` passes without errors
2. **Compilation**: `pnpm build:main` succeeds
3. **Runtime Testing**: Application starts successfully in development mode
4. **Integration**: IPC handlers are properly registered and accessible
## Files Modified
- `main/src/ipc/session.ts` - Added new IPC handler
- `main/src/preload.ts` - Exposed new method to frontend
- `frontend/src/utils/api.ts` - Added API method
- `frontend/src/stores/sessionStore.ts` - Added state management method
- `frontend/src/hooks/useSessionView.ts` - Added loading logic
- `frontend/src/types/electron.d.ts` - Added TypeScript definitions
## Future Enhancements
Potential improvements could include:
1. **Caching**: Cache JSON messages to avoid repeated API calls
2. **Real-time Updates**: Listen for new JSON messages and update the tab live
3. **Filtering**: Add filtering/search capabilities within the Messages tab
4. **Export**: Allow exporting JSON messages for external debugging tools
## Conclusion
The Messages tab fix provides a complete solution for debugging Claude Code sessions by making the raw JSON messages accessible through a clean, type-safe interface. The implementation follows Crystal's architectural patterns and maintains consistency with existing code.

View File

@ -1,47 +0,0 @@
# Session Output Handling System
⚠️ **WARNING**: The session output handling system is complex and fragile. Modifying it frequently causes issues like duplicate messages, disappearing content, or blank screens. Any changes require explicit user permission.
## How It Works
### 1. Database Storage
- Raw JSON messages from Claude are stored as-is in the database
- Stdout/stderr outputs are stored directly
- No formatting or transformation happens at storage time
### 2. Real-time Streaming
- When Claude outputs data, it's saved to the database immediately
- For JSON messages, a formatted stdout version is sent to the frontend for the Output view
- The original JSON is also sent for the Messages view
- This provides immediate visual feedback during active sessions
### 3. Session Loading
- When navigating to a session, outputs are loaded from the database
- The `sessions:get-output` handler transforms JSON messages to formatted stdout on-the-fly
- Uses `setSessionOutputs` for atomic updates to prevent race conditions
### 4. Frontend Display
- The useSessionView hook manages session view logic and state (extracted from SessionView component)
- A mutex lock (`loadingRef`) prevents concurrent loads
- Timing is carefully managed with `requestAnimationFrame` and delays
- The `formattedOutput` state is NOT cleared on session switch - it updates naturally
### 5. Key Principles
- Database is the single source of truth
- Transformations happen on-the-fly, not at storage time
- Real-time updates supplement but don't replace database data
- Session switches always reload from database to ensure consistency
## Common Issues and Solutions
- **Duplicate messages**: Usually caused by sending both formatted and raw versions
- **Disappearing content**: Often due to clearing output states at the wrong time
- **Black screens**: Typically from race conditions during session switching
- **Content only loads once**: Results from improper state management or missing dependencies
The current implementation carefully balances real-time updates with data persistence to provide a smooth user experience.

View File

@ -1,98 +0,0 @@
# State Management Guidelines
⚠️ **IMPORTANT**: Crystal follows a targeted update pattern for state management to minimize unnecessary re-renders and network requests.
## Overview
Crystal uses a combination of Zustand stores, IPC events, and targeted updates to manage application state efficiently. The application prioritizes specific, targeted updates over global refreshes to improve performance and user experience.
## Key Principles
1. **Targeted Updates**: Always update only the specific data that changed
2. **Event-Driven Updates**: Use IPC events to communicate changes between processes
3. **Avoid Global Refreshes**: Never reload entire lists when only one item changes
4. **Database as Source of Truth**: Frontend state should reflect backend state, not override it
## State Update Patterns
### Session Updates
```typescript
// ❌ BAD: Global refresh
const handleSessionCreated = () => {
loadProjectsWithSessions(); // Reloads everything
};
// ✅ GOOD: Targeted update
const handleSessionCreated = (newSession: Session) => {
setProjectsWithSessions(prevProjects => {
return prevProjects.map(project => {
if (project.id === newSession.projectId) {
return {
...project,
sessions: [...project.sessions, newSession]
};
}
return project;
});
});
};
```
### Project Updates
```typescript
// ❌ BAD: Reload all projects
const handleProjectDeleted = () => {
fetchProjects(); // Network request for all projects
};
// ✅ GOOD: Remove from local state
const handleProjectDeleted = () => {
setProjects(prev => prev.filter(p => p.id !== deletedId));
};
```
## IPC Event Handling
The application uses IPC events to synchronize state between the main process and renderer:
### Session Events
- `session:created` - Add new session to appropriate project
- `session:updated` - Update specific session properties
- `session:deleted` - Remove session from project list
### Project Events (if implemented)
- `project:created` - Add new project to list
- `project:updated` - Update specific project properties
- `project:deleted` - Remove project from list
## When Global Refreshes Are Acceptable
- **Initial Load**: When component mounts for the first time
- **User-Triggered Refresh**: When user explicitly requests a refresh
- **Error Recovery**: After connection loss or critical errors
- **Complex State Changes**: When multiple interdependent items change
## Implementation Examples
### DraggableProjectTreeView.tsx
- Uses targeted updates for session creation, update, and deletion
- Only reloads all data on initial mount or when critical errors occur
- Maintains local state synchronized with backend through IPC events
### ProjectSelector.tsx
- Updates project list locally when projects are deleted
- Falls back to refresh only when necessary (e.g., complex updates)
## Best Practices
1. **Use State Setters with Callbacks**: Always use the callback form of setState to ensure you're working with the latest state
2. **Merge Updates**: When updating objects, spread existing properties to preserve data
3. **Handle Edge Cases**: Always check if the item exists before updating
4. **Log State Changes**: Add console logs for debugging state updates in development
5. **Validate IPC Data**: Ensure IPC events contain expected data structure

View File

@ -1,159 +0,0 @@
# Timestamp Handling Guidelines
⚠️ **IMPORTANT**: Proper timestamp handling is critical for the application to function correctly, especially for prompt duration calculations.
## Overview
Crystal uses timestamps throughout the application for tracking session activity, prompt execution times, and displaying time-based information. Due to the mix of SQLite database storage and JavaScript Date objects, special care must be taken to ensure timezone consistency.
## Key Principles
1. **Database Storage**: All timestamps are stored in UTC using SQLite's `CURRENT_TIMESTAMP` or `datetime()` functions
2. **Frontend Display**: Timestamps are parsed as UTC and converted to local time only for display
3. **Consistency**: Always use the timestamp utility functions instead of manual date parsing
4. **Validation**: Always validate timestamps before using them in calculations
## Timestamp Formats
- **SQLite DATETIME**: `YYYY-MM-DD HH:MM:SS` (stored in UTC without timezone indicator)
- **ISO 8601**: `YYYY-MM-DDTHH:MM:SS.sssZ` (with explicit UTC timezone)
- **JavaScript Date**: Local timezone by default (be careful!)
## Utility Functions
Crystal provides timestamp utilities in both frontend and backend:
### Backend (`main/src/utils/timestampUtils.ts`)
```typescript
import { formatForDatabase, getCurrentTimestamp } from '../utils/timestampUtils';
// For database storage
const timestamp = formatForDatabase(); // Returns ISO string
const now = getCurrentTimestamp(); // Alias for formatForDatabase()
// For display formatting
const displayTime = formatForDisplay(timestamp);
```
### Frontend (`frontend/src/utils/timestampUtils.ts`)
```typescript
import { parseTimestamp, formatDuration, getTimeDifference } from '../utils/timestampUtils';
// Parse SQLite timestamps correctly
const date = parseTimestamp("2024-01-01 12:00:00"); // Handles UTC conversion
// Calculate durations
const durationMs = getTimeDifference(startTime, endTime);
const formatted = formatDuration(durationMs); // "2m 34s"
// Display relative time
const ago = formatDistanceToNow(timestamp); // "5 minutes ago"
```
## Database Operations
When working with timestamps in SQLite:
```sql
-- Use datetime() for UTC timestamps
INSERT INTO prompt_markers (timestamp) VALUES (datetime('now'));
-- When selecting, append 'Z' for proper UTC parsing
SELECT datetime(timestamp) || 'Z' as timestamp FROM prompt_markers;
-- For completion timestamps with NULL handling
SELECT
CASE
WHEN completion_timestamp IS NOT NULL
THEN datetime(completion_timestamp) || 'Z'
ELSE NULL
END as completion_timestamp
FROM prompt_markers;
```
## Common Patterns
### Creating a new timestamp
```typescript
// Backend - for database storage
const timestamp = formatForDatabase();
// Frontend - for immediate use
const now = new Date();
```
### Tracking prompt execution time
```typescript
// When prompt starts
db.addPromptMarker(sessionId, promptText, outputIndex);
// When prompt completes
db.updatePromptMarkerCompletion(sessionId);
```
### Calculating duration
```typescript
// With completion timestamp
if (prompt.completion_timestamp) {
const duration = getTimeDifference(prompt.timestamp, prompt.completion_timestamp);
return formatDuration(duration);
}
// For ongoing prompts
const duration = getTimeDifference(prompt.timestamp); // Uses current time as end
return formatDuration(duration) + ' (ongoing)';
```
## Common Pitfalls to Avoid
### 1. Never parse SQLite timestamps directly with `new Date()`
```typescript
// ❌ WRONG - treats UTC as local time
const date = new Date("2024-01-01 12:00:00");
// ✅ CORRECT - uses parseTimestamp utility
const date = parseTimestamp("2024-01-01 12:00:00");
```
### 2. Always validate timestamps before calculations
```typescript
if (!isValidTimestamp(timestamp)) {
return 'Unknown duration';
}
```
### 3. Be careful with timezone conversions
```typescript
// Database stores UTC, display shows local
const dbTime = "2024-01-01 12:00:00"; // UTC
const parsed = parseTimestamp(dbTime); // Correctly handled as UTC
const display = formatForDisplay(parsed); // Converts to local for display
```
### 4. Handle negative durations gracefully
```typescript
const duration = endTime - startTime;
if (duration < 0) {
console.warn('Negative duration detected');
return 'Invalid duration';
}
```
## Testing Timestamp Code
When testing timestamp-related features:
1. Test with different timezones (especially negative UTC offsets)
2. Test with daylight saving time transitions
3. Test with very old and future timestamps
4. Test with invalid/malformed timestamps
5. Verify duration calculations are always positive

View File

@ -1,106 +0,0 @@
# Tool Panel System Implementation Guidelines
⚠️ **IMPORTANT**: The tool panel system implements a flexible, extensible architecture for managing multiple tool instances per session.
## Architecture Overview
The tool panel system consists of several key components:
1. **Panel Manager** (`main/src/services/panelManager.ts`): Central coordinator for panel lifecycle management
2. **Terminal Panel Manager** (`main/src/services/terminalPanelManager.ts`): Specialized handler for terminal panel processes
3. **Panel Event Bus** (`main/src/services/panelEventBus.ts`): Event communication system between panels
4. **Panel Store** (`frontend/src/stores/panelStore.ts`): Frontend state management with Zustand
5. **Panel Components**: React components for rendering different panel types
## Key Implementation Principles
1. **Lazy Initialization**: Panels are created in the database immediately but background processes (like terminal PTY) only start when the panel is first viewed
2. **State Persistence**: All panel state including terminal scrollback, working directories, and configurations persist across application restarts
3. **Memory Efficiency**: Inactive panels suspend rendering but maintain background processes
4. **Event-Driven Updates**: Uses IPC events to synchronize state between main and renderer processes
5. **Extensible Design**: Architecture supports future panel types beyond terminals
## Panel Lifecycle
1. **Creation**: User clicks "Add Tool" → Panel entry created in database → Added to UI
2. **First View**: User clicks panel tab → Background process initializes → XTerm.js mounts
3. **Switching**: User switches panels → Previous panel unmounts XTerm → New panel mounts
4. **Background Operation**: Processes continue running even when panel is not visible
5. **Deletion**: Panel closed → Process terminated → Database entry removed → UI updated
## Terminal Panel Specifics
- Each terminal panel spawns an independent PTY process using node-pty
- Terminal state (scrollback, history, dimensions) persists in `tool_panels.state` as JSON
- XTerm.js instances mount/unmount based on panel visibility to save memory
- Working directories are maintained independently per panel
- Command history and environment variables can be preserved across restarts
## Database Schema
- `tool_panels` table stores panel configuration and state
- `sessions.active_panel_id` tracks the currently active panel per session
- Foreign key constraints ensure panels are cleaned up when sessions are deleted
## Event System
- Terminal panels emit `terminal:command_executed`, `terminal:exit`, and `files:changed` events
- Event bus routes events to subscribed panels (planned for future panel types)
- Events support future inter-panel communication (e.g., diff panels reacting to file changes)
## Implemented Panel Types
The tool panel system currently supports 8 panel types:
1. **Terminal** (`terminal`) - Multiple PTY shells per session
- Independent processes with command history and scrollback
- File operation detection triggers `files:changed` events
2. **Claude** (`claude`) - Multiple Claude Code instances
- Managed by `claudePanelManager.ts`
- Permission mode: approve/ignore
- Automatic context tracking with token usage display
3. **Codex** (`codex`) - Multiple Codex CLI instances
- Managed by `codexPanelManager.ts`
- Configurable model provider and approval policy
- Sandbox mode and web search support
4. **Diff** (`diff`) - Git diff viewer (singleton, permanent)
- View modes: split/unified
- Whitespace and context line configuration
- Auto-refreshes on file changes
5. **Editor** (`editor`) - In-app file editor
- Syntax highlighting with Monaco
- File tree with expanded directory tracking
- Cursor position and scroll persistence
6. **Logs** (`logs`) - Script execution panel (singleton)
- Process management with PID tracking
- Output buffer with error/warning counts
- Start/end time and exit code tracking
7. **Dashboard** (`dashboard`) - Project overview (singleton, permanent, projects-only)
- Session health monitoring
- Filter by status: all/stale/changes/pr
- Cached data persistence
8. **Setup Tasks** (`setup-tasks`) - Project setup checklist (singleton, permanent, projects-only)
- Task completion tracking
- Dismissible tasks
- Last check timestamp
## Panel Capabilities
Each panel type has specific capabilities defined in `PANEL_CAPABILITIES`:
- **requiresProcess**: Whether panel needs background process (terminal, claude, codex, logs)
- **singleton**: Only one instance per session (diff, logs, dashboard, setup-tasks)
- **permanent**: Cannot be closed by user (diff, dashboard, setup-tasks)
- **canAppearInProjects**: Available in project view (all except diff)
- **canAppearInWorktrees**: Available in worktree sessions (all except dashboard, setup-tasks)
- **canEmit**: Events this panel can produce
- **canConsume**: Events this panel listens to
Example: Diff panels are singleton + permanent + worktree-only, consuming `files:changed` and `terminal:command_executed` events to auto-refresh.

View File

@ -1,45 +0,0 @@
# Diff Viewer CSS Troubleshooting
⚠️ **IMPORTANT**: The diff viewer (react-diff-viewer-continued) has specific CSS requirements that can be tricky to debug.
## Common Issue: No Scrollbars on Diff Viewer
If the diff viewer content is cut off and scrollbars don't appear:
1. **DO NOT add complex CSS overrides** - This often makes the problem worse
2. **Check parent containers for `overflow-hidden`** - This is usually the root cause
3. **Use simple `overflow: 'auto'`** on the immediate diff container
4. **Remove any forced widths or min-widths** unless absolutely necessary
## The Solution That Works
```tsx
// In DiffViewer.tsx - Keep it simple!
<div className="border border-t-0 border-gray-600 rounded-b-lg" style={{ overflow: 'auto', maxHeight: '600px' }}>
<ReactDiffViewer
oldValue={file.oldValue || ''}
newValue={file.newValue || ''}
splitView={viewType === 'split'}
useDarkTheme={isDarkMode}
styles={currentStyles}
// Don't add complex style overrides here
/>
</div>
```
## What NOT to Do
- Don't add multiple wrapper divs with conflicting overflow settings
- Don't use CSS-in-JS to override react-diff-viewer's internal styles
- Don't add global CSS selectors targeting generated class names
- Don't use JavaScript hacks to force reflows
## Root Cause
The issue is typically caused by parent containers having `overflow-hidden` which prevents child scrollbars from appearing. Check these files:
- `SessionView.tsx` - Look for `overflow-hidden` classes
- `CombinedDiffView.tsx` - Check both the main container and flex containers
- `App.tsx` - Sometimes the issue starts at the app root level
The react-diff-viewer-continued library uses emotion/styled-components internally, which makes CSS overrides unreliable. The best approach is to ensure proper overflow handling in parent containers and keep the diff viewer wrapper simple.

View File

@ -1,75 +0,0 @@
# Setup Troubleshooting Guide
## Python distutils Error
If you encounter this error during `pnpm run setup`:
```
ModuleNotFoundError: No module named 'distutils'
```
This happens because Python 3.12+ removed the `distutils` module that `node-gyp` depends on.
### Quick Fix:
```bash
brew install python-setuptools
```
### Alternative Solutions:
1. **Use Python 3.11 with pyenv**:
```bash
brew install pyenv
pyenv install 3.11.9
pyenv global 3.11.9
```
2. **Use the setup script**:
```bash
./setup-dev.sh
```
## Other Common Issues
### electron-rebuild failures
- Ensure Xcode Command Line Tools are installed: `xcode-select --install`
- Clear node_modules and reinstall: `rm -rf node_modules && pnpm install`
### pnpm permission errors
- Never use `sudo` with pnpm
- Fix npm permissions: `npm config set prefix ~/.npm-global`
## Windows Build Requirements
### Spectre-mitigated Libraries Error
If you encounter this error during `pnpm run setup` on Windows:
```
LINK : fatal error LNK1181: cannot open input file 'MSVCRT.lib'
```
Or similar errors mentioning missing `.lib` files, this means you need to install the Spectre-mitigated libraries in Visual Studio.
### Solution:
1. **Install Visual Studio 2022** (Community Edition is free):
- Download from [https://visualstudio.microsoft.com/](https://visualstudio.microsoft.com/)
2. **Install Required Components**:
- Open **Visual Studio Installer**
- Click **Modify** on your Visual Studio 2022 installation
- Go to the **Individual components** tab
- Search for "Spectre" in the search box
- Check the following components:
- `MSVC v143 - VS 2022 C++ x64/x86 Spectre-mitigated libs (Latest)`
- `MSVC v143 - VS 2022 C++ ARM64/ARM64EC Spectre-mitigated libs (Latest)` (if building for ARM64)
- Click **Modify** to install
3. **Restart your terminal** and run `pnpm run setup` again
### Why is this needed?
Node.js native modules on Windows are built with Visual Studio's C++ compiler. Recent security updates require Spectre-mitigated libraries to be installed separately. These libraries provide protection against Spectre vulnerability exploits.
### Alternative: Use Pre-built Binaries
If you're having trouble with the build process, consider waiting for official Windows binaries to be released in future versions of Crystal.

View File

@ -27,7 +27,7 @@ export default [
'react-hooks/exhaustive-deps': 'warn',
'react-refresh/only-export-components': ['warn', { allowConstantExport: true }],
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'no-console': ['warn', { allow: ['warn', 'error'] }],
'no-useless-escape': 'warn' // Downgrade to warning for now

View File

@ -7,18 +7,8 @@
<link rel="apple-touch-icon" sizes="180x180" href="./apple-touch-icon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Crystal</title>
<script>
// Apply theme class before React loads to prevent flash
const savedTheme = localStorage.getItem('theme');
const theme = savedTheme === 'light' ? 'light' : 'dark';
document.documentElement.classList.add(theme);
</script>
</head>
<body>
<script>
// Also apply to body
document.body.classList.add(localStorage.getItem('theme') === 'light' ? 'light' : 'dark');
</script>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "frontend",
"version": "0.3.5",
"version": "0.1.16",
"private": true,
"type": "module",
"scripts": {
@ -21,30 +21,25 @@
"@radix-ui/react-switch": "^1.1.2",
"@radix-ui/react-tabs": "^1.1.2",
"@types/dompurify": "^3.0.5",
"@types/uuid": "^10.0.0",
"@xterm/addon-fit": "^0.10.0",
"@xterm/addon-search": "^0.15.0",
"@xterm/addon-web-links": "^0.11.0",
"@xterm/xterm": "^5.5.0",
"ansi-to-html": "^0.7.2",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.1.0",
"dompurify": "^3.2.6",
"immer": "^10.1.3",
"lucide-react": "^0.468.0",
"mermaid": "^11.10.0",
"mermaid": "^11.8.1",
"monaco-editor": "^0.52.2",
"react": "^19.0.0",
"react-diff-viewer-continued": "^3.4.0",
"react-dom": "^19.0.0",
"react-error-boundary": "^6.0.0",
"react-json-view-lite": "^1.5.0",
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"tailwind-merge": "^2.6.0",
"tailwindcss-animate": "^1.0.7",
"uuid": "^13.0.0",
"zustand": "^5.0.2"
},
"devDependencies": {

Binary file not shown.

Before

Width:  |  Height:  |  Size: 68 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 KiB

After

Width:  |  Height:  |  Size: 15 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 1.9 MiB

View File

@ -1,58 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="940.23798mm"
height="259.70303mm"
viewBox="0 0 940.2378 259.70299"
version="1.1"
id="svg1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1">
<linearGradient
id="swatch194">
<stop
style="stop-color:#4d4d4d;stop-opacity:1;"
offset="0"
id="stop194" />
</linearGradient>
<linearGradient
id="swatch39">
<stop
style="stop-color:#999999;stop-opacity:1;"
offset="0"
id="stop39" />
</linearGradient>
</defs>
<g
id="layer1"
transform="translate(-106.07445,-87.677157)">
<g
id="g1"
transform="matrix(0.25222225,0,0,0.25222225,142.37667,88.683763)">
<path
style="fill:#6395ff;fill-opacity:1;stroke:none;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:fill markers stroke"
id="path65-5-5-5-5-5-7-5"
d="m 196.40239,23.285532 c -0.54602,8.293741 -12.43549,6.934573 -14.77155,14.911232 -1.80051,6.147936 9.8144,9.871544 6.00441,15.021586 -4.94327,6.681938 -14.21051,-0.889398 -20.48824,4.558023 -4.8385,4.198549 2.91945,13.610539 -3.07004,15.883196 -7.77108,2.948667 -11.4738,-8.430992 -19.70006,-7.242327 -6.34031,0.916152 -4.90242,13.028284 -11.16979,11.702004 -8.13162,-1.720786 -5.09423,-13.295805 -12.65725,-16.74329 -5.82912,-2.657116 -11.1678,8.309642 -15.7232,3.80551 C 98.916245,59.337564 107.72938,51.24217 103.23082,44.253089 99.763598,38.86632 89.343337,45.205836 87.946205,38.953881 86.133492,30.842262 97.924274,28.796724 97.918427,20.48503 97.913921,14.078869 85.720439,13.77839 87.925159,7.7635646 90.785679,-0.04039043 101.81062,4.613372 106.29934,-2.3820311 c 3.45964,-5.3916419 -6.635717,-12.2367149 -1.52913,-16.1047469 6.62556,-5.01859 13.38432,4.856936 20.94247,1.398815 5.82538,-2.665315 1.03335,-13.881719 7.4205,-14.374885 8.28703,-0.639859 8.63374,11.322021 16.86167,12.499111 6.34159,0.907231 8.37433,-11.119376 14.01417,-8.081098 7.31742,3.942023 1.14202,14.192444 7.42741,19.6310273 4.8444,4.1917375 13.05652,-4.8267093 16.15844,0.7783797 4.02459,7.27234109 -6.71229,12.5568672 -4.365,20.530232 1.80914,6.145397 13.59336,2.998403 13.17252,9.390728 z"
transform="matrix(7.5995429,0,0,7.5995429,-560.09045,326.96861)" />
<text
xml:space="preserve"
style="font-weight:bold;font-size:527.974px;font-family:'Chalkboard SE';-inkscape-font-specification:'Chalkboard SE Bold';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:markers fill stroke"
x="306.01437"
y="668.91577"
id="text7-7-2-7-5-0-9-1"><tspan
id="tspan7-5-2-2-5-2-7-0"
style="fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-opacity:1"
x="306.01437"
y="668.91577">#</tspan></text>
</g>
<path
d="m 1382.5082,590.27527 h 36.5334 v 15.20002 q 5.3333,-8.00001 15.2,-13.06668 9.8667,-5.06668 22.9334,-5.06668 12,0 21.6,4.26668 9.6,4.26667 16.2667,12.00001 6.6667,7.46668 10.1333,18.13336 3.4667,10.66668 3.4667,23.73336 v 78.13343 h -36.5334 v -72.00009 q 0,-14.40002 -6.1333,-22.6667 -5.8667,-8.26667 -17.3334,-8.26667 -12.8,0 -21.3333,9.33334 -8.2667,9.33335 -8.2667,28.53337 v 65.06675 h -36.5334 z m 177.8672,-21.86669 q -4.8,0 -9.0667,-1.86667 -4,-1.86667 -7.2,-4.80001 -3.2,-3.2 -5.0667,-7.46667 -1.8667,-4.26668 -1.8667,-9.06668 0,-4.80001 1.8667,-9.06668 1.8667,-4.26667 5.0667,-7.20001 3.2,-3.2 7.2,-5.06667 4.2667,-1.86667 9.0667,-1.86667 9.8666,0 16.5333,6.93334 6.9334,6.66668 6.9334,16.26669 0,9.60001 -6.9334,16.53335 -6.6667,6.66668 -16.5333,6.66668 z m -18.1334,21.86669 h 36.5334 v 133.3335 h -36.5334 z m 239.7334,62.13341 q 0,-14.93335 -5.0667,-23.20003 -4.8,-8.53334 -15.7333,-8.53334 -11.7334,0 -18.9334,8.80001 -7.2,8.80001 -7.7333,27.20003 v 66.93342 h -36.5334 v -71.20009 q 0,-14.93335 -5.0667,-23.20003 -4.8,-8.53334 -15.7333,-8.53334 -12.0001,0 -19.4667,9.33334 -7.2,9.33335 -7.2,28.53337 v 65.06675 h -36.5334 v -133.3335 h 36.5334 v 15.20002 q 5.3333,-7.73334 14.1333,-12.80002 9.0667,-5.33334 21.3334,-5.33334 14.4,0 24.8,6.66668 10.4,6.40001 16.5333,17.86669 3.2,-6.13334 7.7334,-10.66668 4.8,-4.53334 10.4,-7.46668 5.6,-3.2 11.4667,-4.8 6.1333,-1.60001 11.7333,-1.60001 24.0001,0 36.8001,16.00002 13.0667,15.73336 13.0667,42.93339 v 77.33343 h -36.5334 z m 145.3334,74.13342 q -13.8667,0 -24,-5.6 -10.1334,-5.86668 -14.6667,-12.26668 v 14.93335 h -36.5334 V 523.60852 h 36.5334 v 81.6001 q 4.5333,-6.40001 14.6667,-12.00001 10.1333,-5.86668 24,-5.86668 13.3334,0 24.8,5.60001 11.4667,5.60001 19.7334,15.20002 8.5333,9.33334 13.3333,22.13336 4.8001,12.53335 4.8001,26.6667 0,14.13335 -4.8001,26.93336 -4.8,12.53335 -13.3333,22.13337 -8.2667,9.33334 -19.7334,14.93335 -11.4666,5.6 -24.8,5.6 z m -8,-33.33337 q 15.2,0 24.2667,-10.13335 9.3333,-10.40001 9.3333,-26.13336 0,-15.73335 -9.3333,-25.8667 -9.0667,-10.40001 -24.2667,-10.40001 -15.2,0 -24.5334,10.40001 -9.0666,10.13335 -9.0666,25.8667 0,15.73335 9.0666,26.13336 9.3334,10.13335 24.5334,10.13335 z m 151.467,33.33337 q -13.3334,0 -24.8001,-5.6 -11.4666,-5.60001 -20,-14.93335 -8.2667,-9.60002 -13.0667,-22.13337 -4.8,-12.80001 -4.8,-26.93336 0,-14.13335 4.8,-26.6667 4.8,-12.80002 13.0667,-22.13336 8.5334,-9.60001 20,-15.20002 11.4667,-5.60001 24.8001,-5.60001 13.8667,0 23.7333,5.86668 10.1334,5.6 14.6667,12.00001 v -14.93335 h 36.5334 v 133.3335 h -36.5334 v -14.93335 q -4.5333,6.4 -14.6667,12.26668 -9.8666,5.6 -23.7333,5.6 z m 7.7333,-33.33337 q 15.2,0 24.2667,-10.13335 9.3334,-10.40001 9.3334,-26.13336 0,-15.73335 -9.3334,-25.8667 -9.0667,-10.40001 -24.2667,-10.40001 -15.2,0 -24.5333,10.40001 -9.0667,10.13335 -9.0667,25.8667 0,15.73335 9.0667,26.13336 9.3333,10.13335 24.5333,10.13335 z m 102.667,-169.60021 h 36.5333 v 200.00025 h -36.5333 z m 82.6665,255.73365 28.0001,-63.20008 -56.0001,-125.86682 h 40 l 35.7334,86.40011 35.4667,-86.40011 h 40.2668 l -83.7335,189.0669 z m 190.1333,-52.80007 q -12.8,0 -23.7333,-3.46667 -10.9334,-3.46667 -18.9334,-9.33334 -7.7333,-6.13334 -12.5333,-14.40002 -4.5334,-8.26668 -5.0667,-18.13336 h 38.1334 q 1.0666,8.80002 7.7333,13.06669 6.6667,4.26667 15.4667,4.26667 8.5333,0 12.8,-2.93334 4.5334,-2.93333 4.5334,-7.73334 0,-5.33334 -4.0001,-8.26668 -4,-2.93333 -12.8,-5.06667 l -25.0667,-6.40001 q -17.6,-4.53334 -25.8667,-15.46668 -8,-11.20002 -8,-25.8667 0,-8.53335 3.7334,-15.73335 3.7333,-7.46668 10.6666,-12.53335 6.9334,-5.33334 16.8001,-8.26668 9.8666,-2.93334 22.4,-2.93334 10.9333,0 20.2667,2.93334 9.6,2.66667 16.8,8.26668 7.2,5.33334 11.4667,13.33335 4.5333,7.73334 5.3333,17.60002 h -36.8 q -1.3334,-7.73334 -6.4,-10.66668 -5.0667,-2.93334 -11.2,-2.93334 -6.9334,0 -11.4667,2.66667 -4.2667,2.66667 -4.2667,7.46668 0,5.6 4.5333,8.26667 4.5334,2.66667 10.6667,4.00001 l 23.4667,6.40001 q 19.7334,5.06667 28.2667,15.46668 8.8,10.13335 8.8,25.8667 0,9.33335 -4.2666,17.06669 -4,7.46667 -11.4667,12.80001 -7.4667,5.06668 -17.8667,7.73335 -10.1334,2.93333 -22.1334,2.93333 z m 143.4669,-1.33333 q -10.6667,0 -20.0001,-2.93334 -9.0666,-2.93334 -16,-8.80001 -6.9333,-6.13334 -10.9333,-15.20002 -4,-9.06668 -4,-21.33336 v -54.66673 h -26.9334 v -32.00004 h 26.9334 v -37.06671 h 36.5333 v 37.06671 h 37.6001 v 32.00004 h -37.6001 v 47.46672 q 0,12.26669 5.3334,17.60003 5.3333,5.06667 17.3333,5.06667 8.5334,0 14.9334,-2.4 v 32.2667 q -4.5334,1.33334 -10.1334,2.13334 -5.3333,0.8 -13.0666,0.8 z"
id="text1"
style="font-weight:600;font-size:266.667px;font-family:'Euclid Circular A';-inkscape-font-specification:'Euclid Circular A, Semi-Bold';white-space:pre;fill:#241d71;stroke-width:22.9493;stroke-linecap:round;stroke-linejoin:round;paint-order:fill markers stroke"
transform="matrix(0.46320516,0,0,0.46320516,-237.3201,-85.864407)"
aria-label="nimbalyst" />
</g>
</svg>

Before

Width:  |  Height:  |  Size: 7.9 KiB

View File

@ -7,7 +7,6 @@ import { SessionView } from './components/SessionView';
import { PromptHistoryModal } from './components/PromptHistoryModal';
import Help from './components/Help';
import Welcome from './components/Welcome';
import AnalyticsConsentDialog from './components/AnalyticsConsentDialog';
import { AboutDialog } from './components/AboutDialog';
import { UpdateDialog } from './components/UpdateDialog';
import { MainProcessLogger } from './components/MainProcessLogger';
@ -16,46 +15,31 @@ import { PermissionDialog } from './components/PermissionDialog';
import { DiscordPopup } from './components/DiscordPopup';
import { useErrorStore } from './stores/errorStore';
import { useSessionStore } from './stores/sessionStore';
import { useConfigStore } from './stores/configStore';
import { API } from './utils/api';
import { ContextMenuProvider } from './contexts/ContextMenuContext';
import { TokenTest } from './components/TokenTest';
import type { VersionUpdateInfo, PermissionInput } from './types/session';
// Type for IPC response
interface IPCResponse<T = unknown> {
success: boolean;
data?: T;
error?: string;
}
interface PermissionRequest {
id: string;
sessionId: string;
toolName: string;
input: PermissionInput;
input: any;
timestamp: number;
}
function App() {
const [isHelpOpen, setIsHelpOpen] = useState(false);
const [isWelcomeOpen, setIsWelcomeOpen] = useState(false);
const [isAnalyticsConsentOpen, setIsAnalyticsConsentOpen] = useState(false);
const [hasCheckedAnalyticsConsent, setHasCheckedAnalyticsConsent] = useState(false);
const [isAboutOpen, setIsAboutOpen] = useState(false);
const [isUpdateDialogOpen, setIsUpdateDialogOpen] = useState(false);
const [updateVersionInfo, setUpdateVersionInfo] = useState<VersionUpdateInfo | null>(null);
const [updateVersionInfo, setUpdateVersionInfo] = useState<any>(null);
const [currentPermissionRequest, setCurrentPermissionRequest] = useState<PermissionRequest | null>(null);
const [isDiscordOpen, setIsDiscordOpen] = useState(false);
const [hasCheckedWelcome, setHasCheckedWelcome] = useState(false);
const [isPromptHistoryOpen, setIsPromptHistoryOpen] = useState(false);
const [isTokenTestOpen, setIsTokenTestOpen] = useState(false);
const { currentError, clearError } = useErrorStore();
const { sessions, isLoaded } = useSessionStore();
const { fetchConfig } = useConfigStore();
const { width: sidebarWidth, startResize } = useResizable({
defaultWidth: 500, // Increased to show git status labels without truncation
defaultWidth: 320, // Increased from 256px (w-64)
minWidth: 200,
maxWidth: 600,
storageKey: 'crystal-sidebar-width'
@ -63,81 +47,6 @@ function App() {
useIPCEvents();
const { showNotification } = useNotifications();
// Load config on app startup
useEffect(() => {
fetchConfig();
}, [fetchConfig]);
// Check if analytics consent dialog should be shown (before other dialogs)
useEffect(() => {
if (hasCheckedAnalyticsConsent) {
return;
}
const checkAnalyticsConsent = async () => {
if (!window.electron?.invoke) {
return;
}
try {
// Check if consent has already been shown
const consentResult = await window.electron.invoke('preferences:get', 'analytics_consent_shown') as IPCResponse<string>;
const hasShownConsent = consentResult?.data === 'true';
if (!hasShownConsent) {
// Show consent dialog
setIsAnalyticsConsentOpen(true);
}
} catch (error) {
console.error('[App] Error checking analytics consent:', error);
}
};
setHasCheckedAnalyticsConsent(true);
checkAnalyticsConsent();
}, [hasCheckedAnalyticsConsent]);
// CRITICAL PERFORMANCE FIX: Very aggressive cleanup to prevent V8 array iteration issues
useEffect(() => {
// Run cleanup every 30 seconds to prevent array buildup that causes CPU spikes
const cleanupInterval = setInterval(() => {
const store = useSessionStore.getState();
// Always cleanup when we have multiple sessions to prevent memory issues
if (store.sessions.length > 0) {
store.cleanupInactiveSessions();
}
}, 30 * 1000); // 30 seconds - much more frequent to prevent V8 optimization failures
// Immediate cleanup when switching sessions
const handleSessionSwitch = () => {
// Immediate cleanup to free memory right away
const store = useSessionStore.getState();
if (store.sessions.length > 0) {
store.cleanupInactiveSessions();
}
};
window.addEventListener('session-switched', handleSessionSwitch);
// Also cleanup on visibility change to free memory when app is in background
const handleVisibilityChange = () => {
if (document.hidden) {
const store = useSessionStore.getState();
if (store.sessions.length > 0) {
store.cleanupInactiveSessions();
}
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
clearInterval(cleanupInterval);
window.removeEventListener('session-switched', handleSessionSwitch);
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
// Add keyboard shortcut for prompt history
useEffect(() => {
@ -156,33 +65,37 @@ function App() {
useEffect(() => {
// Show welcome screen and Discord popup intelligently based on user state
// This should only run once when the app is loaded, not when sessions change
// Don't show welcome while analytics consent dialog is open
if (!isLoaded || hasCheckedWelcome || isAnalyticsConsentOpen) {
return;
}
const checkInitialState = async () => {
if (!window.electron?.invoke) {
console.log('[Welcome Debug] Electron API not available');
return;
}
// Get preferences from database
const hideWelcomeResult = await window.electron.invoke('preferences:get', 'hide_welcome') as IPCResponse<string>;
const welcomeShownResult = await window.electron.invoke('preferences:get', 'welcome_shown') as IPCResponse<string>;
const hideDiscordResult = await window.electron.invoke('preferences:get', 'hide_discord') as IPCResponse<string>;
const hideWelcomeResult = await window.electron.invoke('preferences:get', 'hide_welcome');
const welcomeShownResult = await window.electron.invoke('preferences:get', 'welcome_shown');
const hideDiscordResult = await window.electron.invoke('preferences:get', 'hide_discord');
const hideWelcome = hideWelcomeResult?.data === 'true';
const hasSeenWelcome = welcomeShownResult?.data === 'true';
const hideDiscord = hideDiscordResult?.data === 'true';
console.log('[Welcome Debug] Checking welcome screen state:', {
hideWelcomeRaw: hideWelcomeResult?.data,
hideWelcome,
hasSeenWelcome,
hideDiscord,
isLoaded
});
// Track whether we're showing the welcome screen
let welcomeScreenShown = false;
// If user explicitly said "don't show again", respect that preference
if (hideWelcome) {
console.log('[Welcome Debug] User has hidden welcome screen, not showing');
welcomeScreenShown = false;
} else {
} else if (isLoaded) {
try {
const projectsResponse = await API.projects.getAll();
const hasProjects = projectsResponse.success && projectsResponse.data && projectsResponse.data.length > 0;
@ -196,13 +109,21 @@ function App() {
const isFirstTimeUser = !hasProjects && !hasSeenWelcome;
const isReturningUserWithNoData = !hasProjects && !hasSessions && hasSeenWelcome;
console.log('[Welcome Debug] Conditions:', {
hasProjects,
hasSessions,
isFirstTimeUser,
isReturningUserWithNoData
});
if (isFirstTimeUser || isReturningUserWithNoData) {
console.log('[Welcome Debug] Showing welcome screen');
setIsWelcomeOpen(true);
welcomeScreenShown = true;
// Mark that welcome has been shown at least once
await window.electron.invoke('preferences:set', 'welcome_shown', 'true');
} else {
console.log('[Welcome Debug] Not showing welcome screen');
welcomeScreenShown = false;
}
} catch (error) {
@ -212,40 +133,46 @@ function App() {
}
// If welcome screen is not shown and Discord hasn't been hidden, check if we should show Discord popup
if (!welcomeScreenShown && !hideDiscord) {
if (!welcomeScreenShown && !hideDiscord && isLoaded) {
console.log('[Discord Debug] Welcome screen not shown, checking Discord popup...');
try {
// Get the last app open to see if Discord was already shown
const result = await window.electron.invoke('app:get-last-open') as IPCResponse<{ discord_shown?: boolean }>;
const result = await window.electron.invoke('app:get-last-open');
console.log('[Discord Debug] Last app open result:', result);
if (result?.success && result.data) {
const lastOpen = result.data;
console.log('[Discord Debug] Last app open data:', lastOpen);
// Show Discord popup if it hasn't been shown yet
if (!lastOpen.discord_shown) {
console.log('[Discord Debug] Showing Discord popup!');
setIsDiscordOpen(true);
// Mark that we're showing the Discord popup
if (window.electron?.invoke) {
await window.electron.invoke('app:update-discord-shown');
}
} else {
// Discord already shown
console.log('[Discord Debug] Not showing Discord popup because it was already shown');
}
} else {
// No previous app open - show Discord popup
console.log('[Discord Debug] No previous app open found, showing Discord popup');
setIsDiscordOpen(true);
// Will update discord shown status after recording app open
}
} catch (error) {
// Error checking Discord popup
console.error('[Discord Debug] Error checking Discord popup:', error);
}
// Record this app open
console.log('[Discord Debug] Recording current app open');
if (window.electron?.invoke) {
await window.electron.invoke('app:record-open', hideWelcome, false);
// If we showed Discord popup and there was no previous app open, update the status
const result = await window.electron.invoke('app:get-last-open') as IPCResponse<{ discord_shown?: boolean }>;
const result = await window.electron.invoke('app:get-last-open');
if (!result?.data?.discord_shown && isDiscordOpen) {
await window.electron.invoke('app:update-discord-shown');
}
@ -253,17 +180,18 @@ function App() {
}
};
// Set the flag first to prevent re-runs
setHasCheckedWelcome(true);
checkInitialState();
}, [isLoaded, isAnalyticsConsentOpen]); // Also wait for analytics consent dialog to close
if (isLoaded && !hasCheckedWelcome) {
checkInitialState();
setHasCheckedWelcome(true);
}
}, [isLoaded, hasCheckedWelcome]); // Remove sessions.length from dependencies to prevent re-runs
// Discord popup logic is now combined with welcome screen logic above
useEffect(() => {
// Set up permission request listener
const handlePermissionRequest = (...args: unknown[]) => {
const request = args[0] as PermissionRequest;
const handlePermissionRequest = (request: PermissionRequest) => {
console.log('[App] Received permission request:', request);
setCurrentPermissionRequest(request);
};
@ -278,16 +206,14 @@ function App() {
// Set up version update listener
if (!window.electronAPI?.events) return;
const handleVersionUpdate = (versionInfo: VersionUpdateInfo) => {
const handleVersionUpdate = (versionInfo: any) => {
console.log('[App] Version update available:', versionInfo);
setUpdateVersionInfo(versionInfo);
setIsUpdateDialogOpen(true);
showNotification(
`🚀 Update Available - Crystal v${versionInfo.latest}`,
'A new version of Crystal is available!',
'/favicon.ico',
'version_update',
`update:${versionInfo.latest}` // Deduplicate by version - only track once per version
'/favicon.ico'
);
};
@ -300,28 +226,13 @@ function App() {
}
};
}, [showNotification]);
// Add keyboard shortcut for token test page (Cmd/Ctrl + Shift + T) - Development only
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.shiftKey && e.key === 'T') {
// Only allow in development mode
if (process.env.NODE_ENV === 'development') {
e.preventDefault();
setIsTokenTestOpen(prev => !prev);
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
const handlePermissionResponse = async (requestId: string, behavior: 'allow' | 'deny', _updatedInput?: PermissionInput, message?: string) => {
const handlePermissionResponse = async (requestId: string, behavior: 'allow' | 'deny', updatedInput?: any, message?: string) => {
try {
await API.permissions.respond(requestId, {
allow: behavior === 'allow',
reason: message
behavior,
updatedInput,
message
});
setCurrentPermissionRequest(null);
} catch (error) {
@ -330,79 +241,52 @@ function App() {
};
return (
<ContextMenuProvider>
<div className="h-screen flex overflow-hidden bg-bg-primary">
<MainProcessLogger />
{/* Draggable title bar area */}
<div
className="fixed top-0 left-0 right-0 h-8 z-50 flex items-center justify-end pr-4"
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
>
</div>
<Sidebar
onHelpClick={() => setIsHelpOpen(true)}
onAboutClick={() => setIsAboutOpen(true)}
onPromptHistoryClick={() => setIsPromptHistoryOpen(true)}
width={sidebarWidth}
onResize={startResize}
/>
<SessionView />
<Help isOpen={isHelpOpen} onClose={() => setIsHelpOpen(false)} />
<AnalyticsConsentDialog
isOpen={isAnalyticsConsentOpen}
onClose={() => setIsAnalyticsConsentOpen(false)}
/>
<Welcome isOpen={isWelcomeOpen} onClose={() => setIsWelcomeOpen(false)} />
<AboutDialog isOpen={isAboutOpen} onClose={() => setIsAboutOpen(false)} />
<UpdateDialog
isOpen={isUpdateDialogOpen}
onClose={() => setIsUpdateDialogOpen(false)}
versionInfo={updateVersionInfo || undefined}
/>
<ErrorDialog
isOpen={!!currentError}
onClose={clearError}
title={currentError?.title}
error={currentError?.error || ''}
details={currentError?.details}
command={currentError?.command}
/>
<PermissionDialog
request={currentPermissionRequest}
onRespond={handlePermissionResponse}
session={currentPermissionRequest ? sessions.find(s => s.id === currentPermissionRequest.sessionId) : undefined}
/>
<DiscordPopup
isOpen={isDiscordOpen}
onClose={() => setIsDiscordOpen(false)}
/>
<PromptHistoryModal
isOpen={isPromptHistoryOpen}
onClose={() => setIsPromptHistoryOpen(false)}
/>
{/* Token Test Modal - Toggle with Cmd/Ctrl + Shift + T (Development Only) */}
{isTokenTestOpen && process.env.NODE_ENV === 'development' && (
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50 p-4 overflow-y-auto">
<div className="bg-bg-primary w-full max-w-6xl max-h-[90vh] overflow-y-auto rounded-lg relative border border-border-primary shadow-2xl">
<button
onClick={() => setIsTokenTestOpen(false)}
className="absolute top-4 right-4 p-2 hover:bg-surface-hover rounded-lg transition-colors text-text-secondary hover:text-text-primary"
title="Close Token Test (Cmd/Ctrl + Shift + T)"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<div className="absolute top-4 left-4 text-xs text-text-muted bg-surface-secondary px-2 py-1 rounded">
DEV ONLY
</div>
<TokenTest />
</div>
</div>
)}
<div className="h-screen flex overflow-hidden bg-gray-50 dark:bg-gray-900">
<MainProcessLogger />
{/* Draggable title bar area */}
<div
className="fixed top-0 left-0 right-0 h-8 z-50 flex items-center justify-end pr-4"
style={{ WebkitAppRegion: 'drag' } as React.CSSProperties}
>
</div>
</ContextMenuProvider>
<Sidebar
onHelpClick={() => setIsHelpOpen(true)}
onAboutClick={() => setIsAboutOpen(true)}
onPromptHistoryClick={() => setIsPromptHistoryOpen(true)}
width={sidebarWidth}
onResize={startResize}
/>
<SessionView />
<Help isOpen={isHelpOpen} onClose={() => setIsHelpOpen(false)} />
<Welcome isOpen={isWelcomeOpen} onClose={() => setIsWelcomeOpen(false)} />
<AboutDialog isOpen={isAboutOpen} onClose={() => setIsAboutOpen(false)} />
<UpdateDialog
isOpen={isUpdateDialogOpen}
onClose={() => setIsUpdateDialogOpen(false)}
versionInfo={updateVersionInfo}
/>
<ErrorDialog
isOpen={!!currentError}
onClose={clearError}
title={currentError?.title}
error={currentError?.error || ''}
details={currentError?.details}
command={currentError?.command}
/>
<PermissionDialog
request={currentPermissionRequest}
onRespond={handlePermissionResponse}
session={currentPermissionRequest ? sessions.find(s => s.id === currentPermissionRequest.sessionId) : undefined}
/>
<DiscordPopup
isOpen={isDiscordOpen}
onClose={() => setIsDiscordOpen(false)}
/>
<PromptHistoryModal
isOpen={isPromptHistoryOpen}
onClose={() => setIsPromptHistoryOpen(false)}
/>
</div>
);
}

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 2.6 KiB

After

Width:  |  Height:  |  Size: 1.9 MiB

View File

@ -1,47 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
width="1024mm"
height="1024mm"
viewBox="0 0 1024 1024"
version="1.1"
id="svg1"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs1">
<linearGradient
id="swatch194">
<stop
style="stop-color:#4d4d4d;stop-opacity:1;"
offset="0"
id="stop194" />
</linearGradient>
<linearGradient
id="swatch39">
<stop
style="stop-color:#999999;stop-opacity:1;"
offset="0"
id="stop39" />
</linearGradient>
</defs>
<g
id="layer1">
<path
style="fill:#6395ff;fill-opacity:1;stroke:none;stroke-width:6;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:fill markers stroke"
id="path65-5-5-5-5-5-7-5"
d="m 196.40239,23.285532 c -0.54602,8.293741 -12.43549,6.934573 -14.77155,14.911232 -1.80051,6.147936 9.8144,9.871544 6.00441,15.021586 -4.94327,6.681938 -14.21051,-0.889398 -20.48824,4.558023 -4.8385,4.198549 2.91945,13.610539 -3.07004,15.883196 -7.77108,2.948667 -11.4738,-8.430992 -19.70006,-7.242327 -6.34031,0.916152 -4.90242,13.028284 -11.16979,11.702004 -8.13162,-1.720786 -5.09423,-13.295805 -12.65725,-16.74329 -5.82912,-2.657116 -11.1678,8.309642 -15.7232,3.80551 C 98.916245,59.337564 107.72938,51.24217 103.23082,44.253089 99.763598,38.86632 89.343337,45.205836 87.946205,38.953881 86.133492,30.842262 97.924274,28.796724 97.918427,20.48503 97.913921,14.078869 85.720439,13.77839 87.925159,7.7635646 90.785679,-0.04039043 101.81062,4.613372 106.29934,-2.3820311 c 3.45964,-5.3916419 -6.635717,-12.2367149 -1.52913,-16.1047469 6.62556,-5.01859 13.38432,4.856936 20.94247,1.398815 5.82538,-2.665315 1.03335,-13.881719 7.4205,-14.374885 8.28703,-0.639859 8.63374,11.322021 16.86167,12.499111 6.34159,0.907231 8.37433,-11.119376 14.01417,-8.081098 7.31742,3.942023 1.14202,14.192444 7.42741,19.6310273 4.8444,4.1917375 13.05652,-4.8267093 16.15844,0.7783797 4.02459,7.27234109 -6.71229,12.5568672 -4.365,20.530232 1.80914,6.145397 13.59336,2.998403 13.17252,9.390728 z"
transform="matrix(7.5995429,0,0,7.5995429,-560.09045,326.96861)" />
<text
xml:space="preserve"
style="font-weight:bold;font-size:527.974px;font-family:'Chalkboard SE';-inkscape-font-specification:'Chalkboard SE Bold';text-align:start;writing-mode:lr-tb;direction:ltr;text-anchor:start;fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-linecap:round;stroke-linejoin:round;stroke-dasharray:none;stroke-opacity:1;paint-order:markers fill stroke"
x="306.01437"
y="668.91577"
id="text7-7-2-7-5-0-9-1"><tspan
id="tspan7-5-2-2-5-2-7-0"
style="fill:#ffffff;fill-opacity:1;stroke:#999999;stroke-width:0;stroke-opacity:1"
x="306.01437"
y="668.91577">#</tspan></text>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.9 KiB

View File

@ -10,11 +10,9 @@ interface VersionInfo {
releaseNotes?: string;
publishedAt?: string;
workingDirectory?: string;
crystalDirectory?: string;
buildDate?: string;
gitCommit?: string;
buildTimestamp?: number;
worktreeName?: string;
}
interface AboutDialogProps {
@ -44,11 +42,9 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
latest: result.data.current,
hasUpdate: false,
workingDirectory: result.data.workingDirectory,
crystalDirectory: result.data.crystalDirectory,
buildDate: result.data.buildDate,
gitCommit: result.data.gitCommit,
buildTimestamp: result.data.buildTimestamp,
worktreeName: result.data.worktreeName
buildTimestamp: result.data.buildTimestamp
});
}
} catch (error) {
@ -110,10 +106,10 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50">
<div className="bg-surface-primary rounded-lg shadow-xl max-w-md w-full mx-4 max-h-[80vh] overflow-hidden">
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 max-h-[80vh] overflow-hidden">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-border-primary">
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-3">
<img
src="/crystal-logo.svg"
@ -124,13 +120,13 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
<h2 className="text-xl font-semibold text-text-primary">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">
About Crystal
</h2>
</div>
<button
onClick={onClose}
className="text-text-tertiary hover:text-text-secondary transition-colors"
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="w-5 h-5" />
</button>
@ -140,19 +136,19 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
<div className="p-6 space-y-6">
{/* App Info */}
<div className="text-center space-y-2">
<h3 className="text-lg font-medium text-text-primary">
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
Crystal
</h3>
<p className="text-sm text-text-secondary">
<p className="text-sm text-gray-600 dark:text-gray-400">
Multi-Session Claude Code Manager
</p>
<p className="text-xs text-text-tertiary">
<p className="text-xs text-gray-500 dark:text-gray-500">
Created by{' '}
<a
href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1"
target="_blank"
rel="noopener noreferrer"
className="text-interactive hover:underline"
className="text-blue-600 dark:text-blue-400 hover:underline"
>
Stravu
</a>
@ -162,53 +158,31 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
{/* Version Info */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-text-secondary">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
Current Version
</span>
<span className="text-sm text-text-primary font-mono">
<span className="text-sm text-gray-900 dark:text-white font-mono">
{versionInfo?.current || 'Loading...'}
</span>
</div>
{versionInfo?.crystalDirectory && (
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-text-secondary">
Crystal Directory
</span>
<span className="text-sm text-text-primary font-mono truncate max-w-[200px]" title={versionInfo.crystalDirectory}>
{versionInfo.crystalDirectory.replace(/^\/Users\/[^/]+/, '~')}
</span>
</div>
)}
{versionInfo?.workingDirectory && (
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-text-secondary">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
Working Directory
</span>
<span className="text-sm text-text-primary font-mono truncate max-w-[200px]" title={versionInfo.workingDirectory}>
<span className="text-sm text-gray-900 dark:text-white font-mono truncate max-w-[200px]" title={versionInfo.workingDirectory}>
{versionInfo.workingDirectory.split('/').pop() || versionInfo.workingDirectory}
</span>
</div>
)}
{versionInfo?.worktreeName && (
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
Worktree
</span>
<span className="text-sm text-gray-900 dark:text-white font-mono">
{versionInfo.worktreeName}
</span>
</div>
)}
{versionInfo?.gitCommit && (
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-text-secondary">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
Git Commit
</span>
<span className="text-sm text-text-primary font-mono">
<span className="text-sm text-gray-900 dark:text-white font-mono">
{versionInfo.gitCommit}
</span>
</div>
@ -216,26 +190,26 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
{versionInfo?.buildDate && (
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-text-secondary">
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
Build Date
</span>
<span className="text-sm text-text-primary">
<span className="text-sm text-gray-900 dark:text-white">
{formatDateTime(versionInfo.buildDate)}
</span>
</div>
)}
{versionInfo?.hasUpdate && (
<div className="bg-interactive/10 border border-interactive/30 rounded-lg p-4">
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex items-start space-x-3">
<Download className="w-5 h-5 text-interactive mt-0.5 flex-shrink-0" />
<Download className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
<div className="flex-1 space-y-3">
<div className="space-y-2">
<p className="text-sm font-medium text-interactive">
<p className="text-sm font-medium text-blue-900 dark:text-blue-100">
Update Available: v{versionInfo.latest}
</p>
{versionInfo.publishedAt && (
<p className="text-xs text-interactive/80">
<p className="text-xs text-blue-700 dark:text-blue-300">
Released {formatDate(versionInfo.publishedAt)}
</p>
)}
@ -243,7 +217,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
<div className="flex flex-col sm:flex-row gap-2">
<button
onClick={() => setShowUpdateDialog(true)}
className="inline-flex items-center justify-center space-x-2 px-3 py-1.5 bg-interactive hover:bg-interactive-hover text-on-interactive text-sm font-medium rounded-md transition-colors"
className="inline-flex items-center justify-center space-x-2 px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-md transition-colors"
>
<Download className="w-4 h-4" />
<span>Download Update</span>
@ -253,7 +227,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
href={versionInfo.releaseUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center justify-center space-x-1 px-3 py-1.5 text-sm text-interactive hover:underline"
className="inline-flex items-center justify-center space-x-1 px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 hover:underline"
>
<span>View Release Notes</span>
<ExternalLink className="w-3 h-3" />
@ -266,14 +240,14 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
)}
{!versionInfo?.hasUpdate && versionInfo?.current && !isChecking && (
<div className="flex items-center space-x-2 text-sm text-status-success">
<div className="flex items-center space-x-2 text-sm text-green-600 dark:text-green-400">
<Check className="w-4 h-4" />
<span>You're running the latest version</span>
</div>
)}
{error && (
<div className="flex items-center space-x-2 text-sm text-status-error">
<div className="flex items-center space-x-2 text-sm text-red-600 dark:text-red-400">
<AlertCircle className="w-4 h-4" />
<span>{error}</span>
</div>
@ -283,7 +257,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
<button
onClick={checkForUpdates}
disabled={isChecking}
className="w-full flex items-center justify-center space-x-2 px-4 py-2 bg-interactive hover:bg-interactive-hover disabled:bg-interactive/50 text-on-interactive text-sm font-medium rounded-lg transition-colors"
className="w-full flex items-center justify-center space-x-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white text-sm font-medium rounded-lg transition-colors"
>
{isChecking ? (
<>
@ -300,7 +274,7 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
</div>
{/* Discord Community Button */}
<div className="pt-4 border-t border-border-primary">
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
<a
href="https://discord.gg/XrVa6q7DPY"
target="_blank"
@ -320,7 +294,8 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
href="https://github.com/stravu/crystal"
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-between w-full text-sm text-text-secondary hover:text-text-primary transition-colors">
className="flex items-center justify-between w-full text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
>
<span>View on GitHub</span>
<ExternalLink className="w-4 h-4" />
</a>
@ -328,15 +303,16 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
href="https://docs.anthropic.com/en/docs/claude-code"
target="_blank"
rel="noopener noreferrer"
className="flex items-center justify-between w-full text-sm text-text-secondary hover:text-text-primary transition-colors">
className="flex items-center justify-between w-full text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
>
<span>Claude Code Documentation</span>
<ExternalLink className="w-4 h-4" />
</a>
</div>
{/* Disclaimer */}
<div className="pt-4 border-t border-border-primary">
<p className="text-xs text-text-tertiary leading-relaxed">
<div className="pt-4 border-t border-gray-200 dark:border-gray-700">
<p className="text-xs text-gray-500 dark:text-gray-500 leading-relaxed">
Crystal is an independent project created by Stravu. Claude™ is a trademark of Anthropic, PBC.
Crystal is not affiliated with, endorsed by, or sponsored by Anthropic.
</p>

View File

@ -1,120 +0,0 @@
import React from 'react';
import { BarChart3 } from 'lucide-react';
import crystalLogo from '../assets/crystal-logo.svg';
import { Modal, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
import { useConfigStore } from '../stores/configStore';
import { analyticsService } from '../services/analyticsService';
interface AnalyticsConsentDialogProps {
isOpen: boolean;
onClose: (accepted: boolean) => void;
}
export default function AnalyticsConsentDialog({ isOpen, onClose }: AnalyticsConsentDialogProps) {
const [isSubmitting, setIsSubmitting] = React.useState(false);
const { config, updateConfig } = useConfigStore();
const handleAccept = async () => {
setIsSubmitting(true);
try {
// Enable analytics
await updateConfig({
analytics: {
...config?.analytics,
enabled: true,
},
});
// Track opt-in event
await analyticsService.trackAnalyticsOptedIn();
// Mark consent as shown
if (window.electron?.invoke) {
await window.electron.invoke('preferences:set', 'analytics_consent_shown', 'true');
}
onClose(true);
} catch (error) {
console.error('[AnalyticsConsent] Error accepting analytics:', error);
} finally {
setIsSubmitting(false);
}
};
const handleDecline = async () => {
setIsSubmitting(true);
try {
// Track opt-out event FIRST (before disabling analytics)
// This uses a special minimal tracking that works even when analytics is being disabled
await analyticsService.trackAnalyticsOptedOut();
// Disable analytics (keep it disabled since it's opt-in)
await updateConfig({
analytics: {
...config?.analytics,
enabled: false,
},
});
// Mark consent as shown
if (window.electron?.invoke) {
await window.electron.invoke('preferences:set', 'analytics_consent_shown', 'true');
}
onClose(false);
} catch (error) {
console.error('[AnalyticsConsent] Error declining analytics:', error);
} finally {
setIsSubmitting(false);
}
};
if (!isOpen) return null;
return (
<Modal isOpen={isOpen} onClose={() => {}} size="md" closeOnOverlayClick={false} closeOnEscape={false} showCloseButton={false}>
{/* Header with gradient */}
<div className="bg-gradient-to-r from-interactive to-interactive-active p-6 text-on-interactive rounded-t-lg">
<div className="flex items-center">
<img src={crystalLogo} alt="Crystal" className="h-10 w-10 mr-3" />
<h1 className="text-2xl font-bold">Help Improve Crystal</h1>
</div>
</div>
<ModalBody>
<div className="space-y-4">
<div className="flex items-start gap-3">
<BarChart3 className="h-6 w-6 text-interactive flex-shrink-0 mt-0.5" />
<div className="space-y-3">
<p className="text-text-primary">
We do not collect any code, prompts, or identifying information.
</p>
<p className="text-text-secondary">
Your data helps us make Crystal better. You can change this anytime in Settings.
</p>
</div>
</div>
</div>
</ModalBody>
<ModalFooter className="flex justify-between items-center">
<Button
onClick={handleDecline}
variant="ghost"
disabled={isSubmitting}
>
No thanks
</Button>
<Button
onClick={handleAccept}
variant="primary"
disabled={isSubmitting}
loading={isSubmitting}
>
Enable analytics
</Button>
</ModalFooter>
</Modal>
);
}

View File

@ -1,197 +0,0 @@
import { useState, useEffect } from 'react';
import type { IpcRendererEvent } from 'electron';
import { Loader2, Archive, CheckCircle, AlertCircle } from 'lucide-react';
interface ArchiveTask {
sessionId: string;
sessionName: string;
worktreeName: string;
projectName: string;
status: 'pending' | 'queued' | 'removing-worktree' | 'cleaning-artifacts' | 'completed' | 'failed';
startTime: string;
endTime?: string;
error?: string;
}
interface ArchiveProgressData {
tasks: ArchiveTask[];
activeCount: number;
totalCount: number;
}
export function ArchiveProgress() {
const [progress, setProgress] = useState<ArchiveProgressData | null>(null);
const [isExpanded, setIsExpanded] = useState(false);
useEffect(() => {
// Initial load
loadProgress();
// Listen for progress updates
const handleProgress = (_event: IpcRendererEvent, data: ArchiveProgressData) => {
setProgress(data);
// Auto-expand when there are active tasks
if (data.activeCount > 0 && !isExpanded) {
setIsExpanded(true);
}
};
window.electron?.on('archive:progress', handleProgress);
// Poll for initial state in case we missed events
const interval = setInterval(loadProgress, 2000);
return () => {
window.electron?.off('archive:progress', handleProgress);
clearInterval(interval);
};
}, [isExpanded]);
const loadProgress = async () => {
if (!window.electron) return;
try {
const response = await window.electron.invoke('archive:get-progress');
if (response.success) {
setProgress(response.data);
}
} catch (error) {
console.error('Failed to load archive progress:', error);
}
};
if (!progress || progress.totalCount === 0) {
return null;
}
const getStatusIcon = (status: ArchiveTask['status']) => {
switch (status) {
case 'completed':
return <CheckCircle className="w-3 h-3 text-status-success" />;
case 'failed':
return <AlertCircle className="w-3 h-3 text-status-error" />;
case 'queued':
return <Archive className="w-3 h-3 text-status-waiting" />;
default:
return <Loader2 className="w-3 h-3 text-status-info animate-spin" />;
}
};
const getStatusText = (status: ArchiveTask['status']) => {
switch (status) {
case 'queued':
return 'Queued (waiting for other archives to complete)...';
case 'pending':
return 'Preparing...';
case 'removing-worktree':
return 'Removing worktree (this may take a while)...';
case 'cleaning-artifacts':
return 'Cleaning artifacts...';
case 'completed':
return 'Completed';
case 'failed':
return 'Failed';
default:
return status;
}
};
const formatElapsedTime = (startTime: string, endTime?: string) => {
const start = new Date(startTime).getTime();
const end = endTime ? new Date(endTime).getTime() : Date.now();
const elapsed = Math.floor((end - start) / 1000);
if (elapsed < 60) {
return `${elapsed}s`;
}
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
return `${minutes}m ${seconds}s`;
};
return (
<div className="border-t border-border-primary flex-shrink-0">
<button
onClick={() => setIsExpanded(!isExpanded)}
className="w-full px-4 py-2 flex items-center justify-between hover:bg-surface-hover transition-colors"
>
<div className="flex items-center gap-2">
<Archive className="w-3.5 h-3.5 text-text-tertiary" />
<span className="text-xs text-text-tertiary">
Archive Tasks
</span>
{progress.activeCount > 0 && (
<span className="px-1.5 py-0.5 bg-status-info/20 text-status-info text-xs rounded-full animate-pulse">
{progress.activeCount} active
</span>
)}
{progress.tasks.filter(t => t.status === 'queued').length > 0 && (
<span className="px-1.5 py-0.5 bg-status-waiting/20 text-status-waiting text-xs rounded-full">
{progress.tasks.filter(t => t.status === 'queued').length} queued
</span>
)}
</div>
<svg
className={`w-3.5 h-3.5 text-text-tertiary transition-transform ${
isExpanded ? 'rotate-180' : ''
}`}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</svg>
</button>
{isExpanded && (
<div className="border-t border-border-primary max-h-48 overflow-y-auto bg-surface-secondary">
{progress.tasks.length === 0 ? (
<div className="px-4 py-2 text-xs text-text-tertiary">
No archive tasks
</div>
) : (
<div className="divide-y divide-border-primary">
{progress.tasks.map((task) => (
<div key={task.sessionId} className="px-4 py-2 space-y-1">
<div className="flex items-start justify-between gap-2">
<div className="flex items-start gap-2 flex-1 min-w-0">
{getStatusIcon(task.status)}
<div className="flex-1 min-w-0">
<div className="text-xs text-text-secondary truncate" title={task.sessionName}>
{task.sessionName}
</div>
<div className="text-xs text-text-tertiary truncate">
{task.projectName} / {task.worktreeName}
</div>
</div>
</div>
<span className="text-xs text-text-tertiary whitespace-nowrap">
{formatElapsedTime(task.startTime, task.endTime)}
</span>
</div>
<div className="text-xs text-text-tertiary pl-5">
{getStatusText(task.status)}
</div>
{task.error && (
<div className="text-xs text-status-error pl-5 mt-1">
{task.error}
</div>
)}
{task.status === 'removing-worktree' && (
<div className="text-xs text-status-warning/80 pl-5 mt-1 italic">
⚠️ Worktree removal can take several minutes for large repositories
</div>
)}
</div>
))}
</div>
)}
</div>
)}
</div>
);
}

View File

@ -1,22 +1,15 @@
import React, { useState, useEffect, memo, useCallback, useRef, useMemo } from 'react';
import DiffViewer, { DiffViewerHandle } from './DiffViewer';
import ExecutionList from '../../ExecutionList';
import { CommitDialog } from '../../CommitDialog';
import { FileList } from '../../FileList';
import { API } from '../../../utils/api';
import type { CombinedDiffViewProps } from '../../../types/diff';
import type { ExecutionDiff, GitDiffResult } from '../../../types/diff';
import ExecutionList from './ExecutionList';
import { CommitDialog } from './CommitDialog';
import { FileList } from './FileList';
import { API } from '../utils/api';
import type { CombinedDiffViewProps } from '../types/diff';
import type { ExecutionDiff, GitDiffResult } from '../types/diff';
import { Maximize2, Minimize2, RefreshCw } from 'lucide-react';
const HISTORY_LIMIT = 50;
const SIDEBAR_STORAGE_KEY = 'diff-panel-sidebar-width';
const DEFAULT_SIDEBAR_WIDTH = 300;
const MIN_SIDEBAR_WIDTH = 150;
const MAX_SIDEBAR_WIDTH = 600;
const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
sessionId,
const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
sessionId,
selectedExecutions: initialSelected,
isGitOperationRunning = false,
isMainRepo = false,
@ -32,79 +25,19 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
const [modifiedFiles, setModifiedFiles] = useState<Set<string>>(new Set());
const [showCommitDialog, setShowCommitDialog] = useState(false);
const [mainBranch, setMainBranch] = useState<string>('main');
const [historySource, setHistorySource] = useState<'remote' | 'local' | 'branch'>(isMainRepo ? 'remote' : 'branch');
const [lastVisibleState, setLastVisibleState] = useState<boolean>(isVisible);
const [forceRefresh, setForceRefresh] = useState<number>(0);
const [selectedFile, setSelectedFile] = useState<string | undefined>();
// Resizable sidebar state
const [sidebarWidth, setSidebarWidth] = useState<number>(() => {
const stored = localStorage.getItem(SIDEBAR_STORAGE_KEY);
if (stored) {
const width = parseInt(stored, 10);
if (!isNaN(width) && width >= MIN_SIDEBAR_WIDTH && width <= MAX_SIDEBAR_WIDTH) {
return width;
}
}
return DEFAULT_SIDEBAR_WIDTH;
});
const [isResizing, setIsResizing] = useState(false);
const diffViewerRef = useRef<DiffViewerHandle>(null);
// Save sidebar width to localStorage
useEffect(() => {
localStorage.setItem(SIDEBAR_STORAGE_KEY, sidebarWidth.toString());
}, [sidebarWidth]);
// Handle resize mouse events
useEffect(() => {
if (!isResizing) return;
const handleMouseMove = (e: MouseEvent) => {
const container = document.querySelector('.combined-diff-view');
if (!container) return;
const containerRect = container.getBoundingClientRect();
const newWidth = e.clientX - containerRect.left;
const constrainedWidth = Math.max(MIN_SIDEBAR_WIDTH, Math.min(MAX_SIDEBAR_WIDTH, newWidth));
setSidebarWidth(constrainedWidth);
};
const handleMouseUp = () => {
setIsResizing(false);
};
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
// Change cursor globally while resizing
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.body.style.cursor = '';
document.body.style.userSelect = '';
};
}, [isResizing]);
const handleResizeStart = useCallback((e: React.MouseEvent) => {
e.preventDefault();
setIsResizing(true);
}, []);
// Load git commands to get main branch
useEffect(() => {
const loadGitCommands = async () => {
try {
const response = await API.sessions.getGitCommands(sessionId);
if (response.success && response.data) {
const baseBranch = response.data.originBranch || response.data.mainBranch || 'main';
setMainBranch(baseBranch);
if (isMainRepo) {
setHistorySource(response.data.originBranch ? 'remote' : 'local');
}
setMainBranch(response.data.mainBranch || 'main');
}
} catch (err) {
console.error('Failed to load git commands:', err);
@ -112,7 +45,7 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
};
loadGitCommands();
}, [sessionId, isMainRepo]);
}, [sessionId]);
// Reset selection when session changes
useEffect(() => {
@ -123,15 +56,14 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
setCombinedDiff(null);
setExecutions([]);
setSelectedFile(undefined);
setHistorySource(isMainRepo ? 'remote' : 'branch');
}
}, [sessionId, lastSessionId, isMainRepo]);
}, [sessionId, lastSessionId]);
// Detect when tab becomes visible and force refresh
useEffect(() => {
if (isVisible && !lastVisibleState) {
// Tab just became visible - force refresh to get latest git state
console.log('Diff panel became visible, forcing refresh of git data...');
console.log('View Diff tab became visible, forcing refresh of git data...');
setForceRefresh(prev => prev + 1); // Increment to trigger reload
setCombinedDiff(null); // Clear diff data
setSelectedExecutions([]); // Clear selection to force re-selection
@ -154,33 +86,21 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
const loadExecutions = async () => {
try {
setLoading(true);
const response = await API.sessions.getExecutions(sessionId);
let response;
if (isMainRepo) {
// For main repo sessions, get the last 20 commits
response = await API.sessions.getLastCommits(sessionId, 20);
} else {
// For regular sessions, get executions
response = await API.sessions.getExecutions(sessionId);
}
if (!response.success) {
throw new Error(response.error || 'Failed to load executions');
}
const data: ExecutionDiff[] = response.data || [];
setError(null);
const data = response.data;
setExecutions(data);
if (data.length > 0) {
const metadata = data.find(exec => exec.comparison_branch || exec.history_source) || data[0];
if (metadata?.comparison_branch) {
setMainBranch(metadata.comparison_branch);
}
if (metadata?.history_source) {
setHistorySource(metadata.history_source);
} else {
setHistorySource(isMainRepo ? 'remote' : 'branch');
}
} else {
setHistorySource(prev => {
if (isMainRepo) {
return prev;
}
return 'branch';
});
}
// If no initial selection and session just changed, select all executions by default
if (selectedExecutions.length === 0 && data.length > 0) {
@ -208,7 +128,7 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
}, 100); // Reduced to 100ms for more responsive loading
return () => clearTimeout(timeoutId);
}, [sessionId, isMainRepo, isVisible, forceRefresh]);
}, [sessionId, initialSelected, isMainRepo, isVisible, forceRefresh]); // Added isVisible and forceRefresh to dependencies
// Load combined diff when selection changes
useEffect(() => {
@ -220,6 +140,12 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
// Add debouncing to prevent rapid API calls
const timeoutId = setTimeout(() => {
const loadCombinedDiff = async () => {
// For main repo sessions, we don't show diffs, just commit history
if (isMainRepo) {
setCombinedDiff(null);
return;
}
if (selectedExecutions.length === 0) {
setCombinedDiff(null);
return;
@ -232,7 +158,8 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
console.log('CombinedDiffView loadCombinedDiff called:', {
sessionId,
selectedExecutions,
executionsLength: executions.length
executionsLength: executions.length,
isMainRepo
});
let response;
@ -281,7 +208,7 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
}, 100); // Reduced to 100ms for more responsive loading
return () => clearTimeout(timeoutId);
}, [selectedExecutions, sessionId, executions.length, isVisible]);
}, [selectedExecutions, sessionId, executions.length, isMainRepo, isVisible]);
const handleSelectionChange = (newSelection: number[]) => {
setSelectedExecutions(newSelection);
@ -392,11 +319,6 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
setSelectedFile(undefined);
}, [combinedDiff]);
const limitReached = useMemo(
() => executions.some(exec => exec.history_limit_reached),
[executions]
);
// Parse files from the diff
const filesFromDiff = useMemo(() => {
if (!combinedDiff?.diff) return [];
@ -540,14 +462,14 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
if (loading && executions.length === 0) {
return (
<div className="flex items-center justify-center p-8">
<div className="text-text-secondary">Loading executions...</div>
<div className="text-gray-600 dark:text-gray-400">Loading executions...</div>
</div>
);
}
if (error && executions.length === 0) {
return (
<div className="p-4 text-status-error bg-status-error/10 border border-status-error/30 rounded">
<div className="p-4 text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded">
<h3 className="font-medium mb-2">Error</h3>
<p>{error}</p>
</div>
@ -555,24 +477,13 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
}
return (
<div className={`combined-diff-view flex flex-col ${isFullscreen ? 'fixed inset-0 z-50 bg-bg-primary' : 'h-full'}`}>
<div className={`combined-diff-view flex flex-col ${isFullscreen ? 'fixed inset-0 z-50 bg-white dark:bg-gray-900' : 'h-full'}`}>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-border-primary bg-surface-secondary">
<div className="flex flex-col">
<h2 className="text-xl font-semibold text-text-primary">File Changes</h2>
{isMainRepo && (
<span
className={`text-xs mt-1 ${historySource === 'local' ? 'text-status-warning' : 'text-text-tertiary'}`}
>
{historySource === 'remote'
? `Comparing to ${mainBranch}`
: 'Origin remote not found; showing latest local commits'}
</span>
)}
</div>
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-100 dark:bg-gray-800">
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">File Changes</h2>
<div className="flex items-center space-x-4">
{isGitOperationRunning && (
<div className="flex items-center space-x-2 text-sm text-interactive">
<div className="flex items-center space-x-2 text-sm text-blue-600">
<svg className="animate-spin h-4 w-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
@ -582,28 +493,28 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
)}
{combinedDiff && (
<div className="flex items-center space-x-4 text-sm">
<span className="text-status-success">+{combinedDiff.stats.additions}</span>
<span className="text-status-error">-{combinedDiff.stats.deletions}</span>
<span className="text-text-tertiary">{combinedDiff.stats.filesChanged} {combinedDiff.stats.filesChanged === 1 ? 'file' : 'files'}</span>
<span className="text-green-600">+{combinedDiff.stats.additions}</span>
<span className="text-red-600">-{combinedDiff.stats.deletions}</span>
<span className="text-gray-400">{combinedDiff.stats.filesChanged} {combinedDiff.stats.filesChanged === 1 ? 'file' : 'files'}</span>
</div>
)}
<button
onClick={handleManualRefresh}
className="p-2 rounded hover:bg-surface-hover transition-colors"
className="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
title="Refresh git data"
disabled={loading}
>
<RefreshCw className={`w-5 h-5 text-text-secondary ${loading ? 'animate-spin' : ''}`} />
<RefreshCw className={`w-5 h-5 text-gray-600 dark:text-gray-400 ${loading ? 'animate-spin' : ''}`} />
</button>
<button
onClick={toggleFullscreen}
className="p-2 rounded hover:bg-surface-hover transition-colors"
className="p-2 rounded hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors"
title={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
>
{isFullscreen ? (
<Minimize2 className="w-5 h-5 text-text-secondary" />
<Minimize2 className="w-5 h-5 text-gray-600 dark:text-gray-400" />
) : (
<Maximize2 className="w-5 h-5 text-text-secondary" />
<Maximize2 className="w-5 h-5 text-gray-600 dark:text-gray-400" />
)}
</button>
</div>
@ -612,69 +523,53 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
<div className="flex-1 flex min-h-0">
{/* Commits selection sidebar */}
{!isFullscreen && (
<>
<div
className="border-r border-border-primary bg-surface-secondary overflow-hidden flex flex-col flex-shrink-0"
style={{ width: sidebarWidth }}
>
{/* File list - show only when we have a diff */}
{filesFromDiff.length > 0 && (
<div className="h-1/3 border-b border-border-primary overflow-y-auto">
<FileList
files={filesFromDiff}
onFileClick={handleFileClick}
onFileDelete={handleFileDelete}
selectedFile={selectedFile}
/>
</div>
)}
{/* Execution list */}
<div className={filesFromDiff.length > 0 ? "flex-1 overflow-hidden" : "h-full"}>
<ExecutionList
sessionId={sessionId}
executions={executions}
selectedExecutions={selectedExecutions}
onSelectionChange={handleSelectionChange}
onCommit={() => setShowCommitDialog(true)}
onRevert={handleRevert}
onRestore={handleRestore}
historyLimitReached={limitReached}
historyLimit={HISTORY_LIMIT}
<div className="w-1/3 border-r border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800 overflow-hidden flex flex-col">
{/* File list - show only when we have a diff */}
{filesFromDiff.length > 0 && (
<div className="h-1/3 border-b border-gray-200 dark:border-gray-700 overflow-hidden">
<FileList
files={filesFromDiff}
onFileClick={handleFileClick}
onFileDelete={handleFileDelete}
selectedFile={selectedFile}
/>
</div>
)}
{/* Execution list */}
<div className={filesFromDiff.length > 0 ? "flex-1 overflow-hidden" : "h-full"}>
<ExecutionList
sessionId={sessionId}
executions={executions}
selectedExecutions={selectedExecutions}
onSelectionChange={handleSelectionChange}
onCommit={() => setShowCommitDialog(true)}
onRevert={handleRevert}
onRestore={handleRestore}
/>
</div>
{/* Resize handle */}
<div
className={`w-1 hover:bg-interactive cursor-col-resize flex-shrink-0 transition-colors ${
isResizing ? 'bg-interactive' : 'bg-transparent'
}`}
onMouseDown={handleResizeStart}
title="Drag to resize sidebar"
/>
</>
</div>
)}
{/* Diff preview */}
<div className={`${isFullscreen ? 'w-full' : 'flex-1'} overflow-auto bg-bg-primary min-w-0 flex flex-col`}>
<div className={`${isFullscreen ? 'w-full' : 'flex-1'} overflow-auto bg-white dark:bg-gray-900 min-w-0 flex flex-col`}>
{isGitOperationRunning ? (
<div className="flex flex-col items-center justify-center h-full p-8">
<svg className="animate-spin h-12 w-12 text-interactive mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<svg className="animate-spin h-12 w-12 text-blue-600 mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<div className="text-text-secondary text-center">
<div className="text-gray-600 dark:text-gray-400 text-center">
<p className="font-medium">Git operation in progress</p>
<p className="text-sm text-text-tertiary mt-1">Please wait while the operation completes...</p>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Please wait while the operation completes...</p>
</div>
</div>
) : loading && combinedDiff === null ? (
<div className="flex items-center justify-center h-32">
<div className="text-text-secondary">Loading diff...</div>
<div className="text-gray-600 dark:text-gray-400">Loading diff...</div>
</div>
) : error ? (
<div className="p-4 text-status-error bg-status-error/10 border border-status-error/30 rounded m-4">
<div className="p-4 text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded m-4">
<h3 className="font-medium mb-2">Error loading diff</h3>
<p>{error}</p>
</div>
@ -708,25 +603,15 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
})()}
mainBranch={mainBranch}
/>
) : executions.length === 0 ? (
<div className="flex items-center justify-center h-full text-text-secondary">
<div className="text-center space-y-2">
<p>
{isMainRepo
? historySource === 'remote'
? `No commits ahead of ${mainBranch}`
: 'Origin remote not found; showing recent local commits'
: 'No commits found for this session'}
</p>
{isMainRepo && historySource === 'remote' && (
<p className="text-sm text-text-tertiary">
Create new commits to see them here.
</p>
)}
) : isMainRepo ? (
<div className="flex items-center justify-center h-full text-gray-600 dark:text-gray-400">
<div className="text-center">
<p className="mb-2">Showing last 20 commits from the main repository</p>
<p className="text-sm">Select commits to view details</p>
</div>
</div>
) : (
<div className="flex items-center justify-center h-32 text-text-secondary">
<div className="flex items-center justify-center h-32 text-gray-600 dark:text-gray-400">
Select commits to view changes
</div>
)}
@ -757,4 +642,4 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
CombinedDiffView.displayName = 'CombinedDiffView';
export default CombinedDiffView;
export default CombinedDiffView;

View File

@ -1,8 +1,5 @@
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { GitCommit } from 'lucide-react';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
import { Textarea } from './ui/Textarea';
import { GitCommit, X } from 'lucide-react';
interface CommitDialogProps {
isOpen: boolean;
@ -66,53 +63,89 @@ export const CommitDialog: React.FC<CommitDialogProps> = ({
}
}, [handleCommit, onClose]);
if (!isOpen) return null;
return (
<Modal isOpen={isOpen} onClose={onClose} size="md">
<ModalHeader
icon={<GitCommit className="w-5 h-5" />}
title="Commit Changes"
onClose={onClose}
<div className="fixed inset-0 z-50 flex items-center justify-center">
{/* Backdrop */}
<div
className="absolute inset-0 bg-black bg-opacity-50"
onClick={onClose}
/>
<ModalBody>
<p className="text-sm text-text-secondary mb-4">
Committing {fileCount} file{fileCount > 1 ? 's' : ''} with changes
</p>
<Textarea
ref={textareaRef}
value={commitMessage}
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setCommitMessage(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Enter commit message..."
rows={4}
error={error}
/>
<p className="mt-2 text-xs text-text-tertiary">
Press Ctrl+Enter (Cmd+Enter on Mac) to commit
</p>
</ModalBody>
{/* Dialog */}
<div className="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md mx-4">
{/* Header */}
<div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<GitCommit className="w-5 h-5 text-gray-700 dark:text-gray-300" />
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
Commit Changes
</h3>
</div>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
>
<X className="w-5 h-5" />
</button>
</div>
<ModalFooter>
<Button
onClick={onClose}
disabled={isCommitting}
variant="secondary"
>
Cancel
</Button>
<Button
onClick={handleCommit}
disabled={isCommitting || !commitMessage.trim()}
variant="primary"
loading={isCommitting}
loadingText="Committing..."
>
<GitCommit className="w-4 h-4" />
Commit
</Button>
</ModalFooter>
</Modal>
{/* Body */}
<div className="px-6 py-4">
<p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
Committing {fileCount} file{fileCount > 1 ? 's' : ''} with changes
</p>
<textarea
ref={textareaRef}
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Enter commit message..."
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-900 text-gray-900 dark:text-gray-100 focus:outline-none focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-400"
rows={4}
/>
{error && (
<p className="mt-2 text-sm text-red-600 dark:text-red-400">
{error}
</p>
)}
<p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
Press Ctrl+Enter (Cmd+Enter on Mac) to commit
</p>
</div>
{/* Footer */}
<div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 dark:border-gray-700">
<button
onClick={onClose}
disabled={isCommitting}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors disabled:opacity-50"
>
Cancel
</button>
<button
onClick={handleCommit}
disabled={isCommitting || !commitMessage.trim()}
className="px-4 py-2 text-sm font-medium text-white bg-blue-500 hover:bg-blue-600 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
>
{isCommitting ? (
<>
<div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
Committing...
</>
) : (
<>
<GitCommit className="w-4 h-4" />
Commit
</>
)}
</button>
</div>
</div>
</div>
);
};

View File

@ -2,12 +2,6 @@ import { useState, useEffect } from 'react';
import { GitCommit, Shield, Zap, AlertTriangle, Info } from 'lucide-react';
import type { CommitMode, CommitModeSettings, ProjectCharacteristics } from '../../../shared/types';
import { DEFAULT_STRUCTURED_PROMPT_TEMPLATE, DEFAULT_COMMIT_MODE_SETTINGS } from '../../../shared/types';
import { Card } from './ui/Card';
import { Badge } from './ui/Badge';
import { Input } from './ui/Input';
import { Textarea } from './ui/Textarea';
import { Checkbox } from './ui/Input';
import { cn } from '../utils/cn';
interface CommitModeSettingsProps {
projectId?: number;
@ -47,7 +41,7 @@ export function CommitModeSettings({
onChange(chars.suggestedMode, newSettings);
}
})
.catch((error: unknown) => {
.catch((error: any) => {
console.error('Failed to detect project characteristics:', error);
})
.finally(() => {
@ -63,7 +57,7 @@ export function CommitModeSettings({
.then((result: { shouldWarn: boolean; reason?: string }) => {
setShowWarning(result.shouldWarn);
})
.catch((error: unknown) => {
.catch((error: any) => {
console.error('Failed to check checkpoint warning:', error);
});
} else {
@ -90,16 +84,16 @@ export function CommitModeSettings({
<div className={`space-y-4 ${className}`}>
{/* Mode Selection */}
<div>
<label className="block text-sm font-medium text-text-primary mb-2">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Commit Mode
</label>
{/* Recommendation Banner */}
{characteristics && !loadingCharacteristics && (
<Card variant="bordered" className="mb-3 bg-interactive/10 border-interactive/30" padding="sm">
<div className="mb-3 p-3 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
<div className="flex items-start gap-2">
<Info className="w-4 h-4 text-interactive mt-0.5 flex-shrink-0" />
<div className="text-sm text-interactive">
<Info className="w-4 h-4 text-blue-600 dark:text-blue-400 mt-0.5 flex-shrink-0" />
<div className="text-sm text-blue-700 dark:text-blue-300">
<p className="font-medium">Recommended: {characteristics.suggestedMode} mode</p>
<p className="text-xs mt-1 opacity-90">
{characteristics.hasHusky && 'Pre-commit hooks detected (.husky). '}
@ -110,169 +104,151 @@ export function CommitModeSettings({
</p>
</div>
</div>
</Card>
</div>
)}
<div className="space-y-2">
{/* Structured Mode */}
<Card
variant="interactive"
className={cn(
"cursor-pointer transition-all",
localSettings.mode === 'structured'
? "bg-interactive/10 border-interactive"
: "hover:border-interactive/30"
)}
onClick={() => handleModeChange('structured')}
padding="md"
>
<label className="relative flex items-start cursor-pointer">
<input
type="radio"
name="commitMode"
value="structured"
checked={localSettings.mode === 'structured'}
onChange={() => handleModeChange('structured')}
className="mt-1 mr-3 text-interactive focus:ring-interactive"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<Shield className="w-4 h-4 text-interactive" />
<span className="font-medium text-text-primary">Structured Mode</span>
{characteristics?.suggestedMode === 'structured' && (
<Badge variant="primary" size="sm">
Recommended
</Badge>
)}
</div>
<p className="text-sm text-text-secondary mt-1">
Claude creates commits with proper messages. Respects pre-commit hooks and project conventions.
</p>
<label className="relative flex items-start p-3 border rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
<input
type="radio"
name="commitMode"
value="structured"
checked={localSettings.mode === 'structured'}
onChange={() => handleModeChange('structured')}
className="mt-1 mr-3"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<Shield className="w-4 h-4 text-blue-600 dark:text-blue-400" />
<span className="font-medium text-gray-900 dark:text-gray-100">Structured Mode</span>
{characteristics?.suggestedMode === 'structured' && (
<span className="text-xs bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 px-2 py-0.5 rounded">
Recommended
</span>
)}
</div>
</label>
</Card>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Claude creates commits with proper messages. Respects pre-commit hooks and project conventions.
</p>
</div>
</label>
{/* Checkpoint Mode */}
<Card
variant="interactive"
className={cn(
"cursor-pointer transition-all",
localSettings.mode === 'checkpoint'
? "bg-status-success/10 border-status-success"
: "hover:border-status-success/30"
)}
onClick={() => handleModeChange('checkpoint')}
padding="md"
>
<label className="relative flex items-start cursor-pointer">
<input
type="radio"
name="commitMode"
value="checkpoint"
checked={localSettings.mode === 'checkpoint'}
onChange={() => handleModeChange('checkpoint')}
className="mt-1 mr-3 text-status-success focus:ring-status-success"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<Zap className="w-4 h-4 text-status-success" />
<span className="font-medium text-text-primary">Checkpoint Mode</span>
{characteristics?.suggestedMode === 'checkpoint' && (
<Badge variant="success" size="sm">
Recommended
</Badge>
)}
</div>
<p className="text-sm text-text-secondary mt-1">
Auto-commit after each prompt. Fast and simple, bypasses hooks with --no-verify.
</p>
<label className="relative flex items-start p-3 border rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
<input
type="radio"
name="commitMode"
value="checkpoint"
checked={localSettings.mode === 'checkpoint'}
onChange={() => handleModeChange('checkpoint')}
className="mt-1 mr-3"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<Zap className="w-4 h-4 text-green-600 dark:text-green-400" />
<span className="font-medium text-gray-900 dark:text-gray-100">Checkpoint Mode</span>
{characteristics?.suggestedMode === 'checkpoint' && (
<span className="text-xs bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300 px-2 py-0.5 rounded">
Recommended
</span>
)}
</div>
</label>
</Card>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Auto-commit after each prompt. Fast and simple, bypasses hooks with --no-verify.
</p>
</div>
</label>
{/* Disabled Mode */}
<Card
variant="interactive"
className={cn(
"cursor-pointer transition-all",
localSettings.mode === 'disabled'
? "bg-surface-tertiary border-border-secondary"
: "hover:border-border-primary"
)}
onClick={() => handleModeChange('disabled')}
padding="md"
>
<label className="relative flex items-start cursor-pointer">
<input
type="radio"
name="commitMode"
value="disabled"
checked={localSettings.mode === 'disabled'}
onChange={() => handleModeChange('disabled')}
className="mt-1 mr-3 text-text-tertiary focus:ring-text-tertiary"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<GitCommit className="w-4 h-4 text-text-muted" />
<span className="font-medium text-text-primary">Disabled Mode</span>
</div>
<p className="text-sm text-text-secondary mt-1">
No auto-commits. You handle all commits manually.
</p>
<label className="relative flex items-start p-3 border rounded-lg cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors">
<input
type="radio"
name="commitMode"
value="disabled"
checked={localSettings.mode === 'disabled'}
onChange={() => handleModeChange('disabled')}
className="mt-1 mr-3"
/>
<div className="flex-1">
<div className="flex items-center gap-2">
<GitCommit className="w-4 h-4 text-gray-600 dark:text-gray-400" />
<span className="font-medium text-gray-900 dark:text-gray-100">Disabled Mode</span>
</div>
</label>
</Card>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
No auto-commits. You handle all commits manually.
</p>
</div>
</label>
</div>
</div>
{/* Warning for checkpoint mode */}
{showWarning && localSettings.mode === 'checkpoint' && (
<Card variant="bordered" className="bg-status-warning/10 border-status-warning/30" padding="sm">
<div className="p-3 bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg">
<div className="flex items-start gap-2">
<AlertTriangle className="w-4 h-4 text-status-warning mt-0.5 flex-shrink-0" />
<div className="text-sm text-status-warning">
<AlertTriangle className="w-4 h-4 text-amber-600 dark:text-amber-400 mt-0.5 flex-shrink-0" />
<div className="text-sm text-amber-700 dark:text-amber-300">
<p className="font-medium">Warning: Pre-commit hooks detected</p>
<p className="text-xs mt-1 opacity-90">
<p className="text-xs mt-1">
Checkpoint commits will bypass pre-commit hooks. This may cause CI failures.
Consider using Structured mode for this project.
</p>
</div>
</div>
</Card>
</div>
)}
{/* Mode-specific settings */}
{localSettings.mode === 'structured' && (
<div className="space-y-3 pt-2">
<Textarea
label="Commit Prompt Template"
value={localSettings.structuredPromptTemplate || DEFAULT_STRUCTURED_PROMPT_TEMPLATE}
onChange={(e) => handleSettingChange('structuredPromptTemplate', e.target.value)}
rows={4}
placeholder="Instructions for Claude on how to commit..."
helperText="This will be appended to Claude's prompts to guide commit behavior."
fullWidth
/>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Commit Prompt Template
</label>
<textarea
value={localSettings.structuredPromptTemplate || DEFAULT_STRUCTURED_PROMPT_TEMPLATE}
onChange={(e) => handleSettingChange('structuredPromptTemplate', e.target.value)}
rows={4}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700 text-sm"
placeholder="Instructions for Claude on how to commit..."
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
This will be appended to Claude's prompts to guide commit behavior.
</p>
</div>
<Checkbox
id="allowClaudeTools"
label="Allow Claude to run tools (e.g., pnpm changeset)"
checked={localSettings.allowClaudeTools || false}
onChange={(e) => handleSettingChange('allowClaudeTools', e.target.checked)}
/>
<div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={localSettings.allowClaudeTools || false}
onChange={(e) => handleSettingChange('allowClaudeTools', e.target.checked)}
className="h-4 w-4 text-blue-600 rounded border-gray-300 dark:border-gray-600 focus:ring-blue-500"
/>
<span className="text-sm text-gray-700 dark:text-gray-300">
Allow Claude to run tools (e.g., pnpm changeset)
</span>
</label>
</div>
</div>
)}
{localSettings.mode === 'checkpoint' && (
<div className="pt-2">
<Input
label="Commit Prefix"
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Commit Prefix
</label>
<input
type="text"
value={localSettings.checkpointPrefix || DEFAULT_COMMIT_MODE_SETTINGS.checkpointPrefix}
onChange={(e) => handleSettingChange('checkpointPrefix', e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700"
placeholder="checkpoint: "
helperText="Prefix for automatic checkpoint commits."
fullWidth
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Prefix for automatic checkpoint commits.
</p>
</div>
)}
</div>

View File

@ -1,12 +1,7 @@
import React, { useState } from 'react';
import { FileText, RotateCcw, ChevronDown, Settings, GitCommit } from 'lucide-react';
import { GitCommit, Shield, Zap, ChevronDown, Settings } from 'lucide-react';
import type { CommitMode, CommitModeSettings } from '../../../shared/types';
import { CommitModeSettings as CommitModeSettingsComponent } from './CommitModeSettings';
import { Dropdown, DropdownMenuItem, type DropdownItem } from './ui/Dropdown';
import { Button } from './ui/Button';
import { Pill } from './ui/Pill';
import { SwitchSimple as Switch } from './ui/SwitchSimple';
import { cn } from '../utils/cn';
interface CommitModeToggleProps {
sessionId: string;
@ -17,26 +12,7 @@ interface CommitModeToggleProps {
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
}
interface CommitModePillProps {
sessionId: string;
currentMode?: CommitMode;
currentSettings?: string;
autoCommit?: boolean;
projectId?: number;
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
isAutoCommitEnabled?: boolean; // Made optional since it's no longer used
}
interface AutoCommitSwitchProps {
sessionId: string;
currentMode?: CommitMode;
currentSettings?: string;
autoCommit?: boolean;
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
}
// Auto-Commit Mode Pill Component
export const CommitModePill: React.FC<CommitModePillProps> = ({
export const CommitModeToggle: React.FC<CommitModeToggleProps> = ({
sessionId,
currentMode,
currentSettings,
@ -57,31 +33,37 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
// Determine effective mode (backwards compatibility)
const effectiveMode = currentMode || (autoCommit === false ? 'disabled' : 'checkpoint');
// Get the active commit mode
const activeCommitMode: CommitMode = effectiveMode;
const getModeConfig = (mode: CommitMode) => {
switch (mode) {
const getModeConfig = () => {
switch (effectiveMode) {
case 'structured':
return {
icon: FileText,
icon: Shield,
label: 'Structured',
color: 'bg-blue-50 dark:bg-blue-950/20 text-blue-700 dark:text-blue-300 hover:bg-blue-100 dark:hover:bg-blue-950/30 border-blue-200 dark:border-blue-800',
iconColor: 'text-blue-600 dark:text-blue-400',
};
case 'checkpoint':
return {
icon: RotateCcw,
icon: Zap,
label: 'Checkpoint',
color: 'bg-green-50 dark:bg-green-950/20 text-green-700 dark:text-green-300 hover:bg-green-100 dark:hover:bg-green-950/30 border-green-200 dark:border-green-800',
iconColor: 'text-green-600 dark:text-green-400',
};
case 'disabled':
return {
icon: GitCommit,
label: 'Disabled',
color: 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600 border-gray-300 dark:border-gray-600',
iconColor: 'text-gray-600 dark:text-gray-400',
};
}
};
const handleCommitModeChange = async (newMode: CommitMode) => {
const config = getModeConfig();
const Icon = config.icon;
const handleQuickModeChange = async (newMode: CommitMode) => {
const newSettings: CommitModeSettings = {
...parsedSettings,
mode: newMode,
@ -114,88 +96,107 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
}
};
// Create dropdown items for commit modes
const dropdownItems: DropdownItem[] = [
{
id: 'structured',
label: 'Structured',
description: 'Claude creates commits',
icon: FileText,
iconColor: 'text-text-secondary',
onClick: () => handleCommitModeChange('structured'),
variant: 'default',
},
{
id: 'checkpoint',
label: 'Checkpoint',
description: 'Auto-commit after each prompt',
icon: RotateCcw,
iconColor: 'text-text-secondary',
onClick: () => handleCommitModeChange('checkpoint'),
variant: 'success',
},
{
id: 'disabled',
label: 'Disabled',
description: 'No automatic commits',
icon: GitCommit,
iconColor: 'text-text-secondary',
onClick: () => handleCommitModeChange('disabled'),
variant: 'default',
},
];
const config = getModeConfig(activeCommitMode);
const Icon = config.icon;
const modeSelectorPill = (
<Pill
variant="default"
isActive={activeCommitMode !== 'disabled'} // Show active styling when commits are enabled
icon={<Icon className={cn(
'w-3.5 h-3.5',
activeCommitMode !== 'disabled' ? 'text-text-on-interactive' : 'text-text-secondary'
)} />}
className="transition-all duration-200 shadow-sm"
>
{config.label}
<ChevronDown className={cn(
'w-3 h-3 transition-transform',
showDropdown ? 'rotate-180' : '',
activeCommitMode !== 'disabled' ? 'text-text-on-interactive' : 'text-text-secondary'
)} />
</Pill>
);
// Create the footer with settings button
const dropdownFooter = (
<DropdownMenuItem
icon={Settings}
label="Commit Mode Settings..."
onClick={() => {
setShowDropdown(false);
setShowSettings(true);
}}
/>
);
return (
<>
<Dropdown
trigger={modeSelectorPill}
items={dropdownItems}
selectedId={activeCommitMode}
footer={dropdownFooter}
position="auto"
onOpenChange={setShowDropdown}
/>
<div className="relative" style={{ overflow: 'visible' }}>
<button
onClick={() => setShowDropdown(!showDropdown)}
className={`
px-3.5 py-1.5 rounded-full text-xs font-medium
transition-all duration-200 flex items-center gap-1.5
hover:scale-105 active:scale-95
focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-50 dark:focus:ring-offset-gray-950
border ${config.color}
`}
>
<Icon className={`w-3.5 h-3.5 ${config.iconColor}`} />
<span className="leading-none">{config.label}</span>
<ChevronDown className={`w-3 h-3 ${showDropdown ? 'rotate-180' : ''} transition-transform`} />
</button>
{/* Dropdown Menu */}
{showDropdown && (
<>
<div
className="fixed inset-0 z-[9998]"
onClick={() => setShowDropdown(false)}
/>
<div className="absolute right-0 bottom-full mb-2 w-56 bg-white dark:bg-gray-800 rounded-lg shadow-2xl border border-gray-200 dark:border-gray-600 z-[9999]">
<div className="p-1.5">
{/* Quick Mode Selection */}
<button
onClick={() => handleQuickModeChange('structured')}
className={`w-full text-left px-3 py-2.5 rounded-md transition-colors flex items-center gap-2 ${
effectiveMode === 'structured' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-700 dark:text-blue-300' : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Shield className="w-4 h-4 text-blue-600 dark:text-blue-400" />
<div className="flex-1">
<div className="text-sm font-semibold">Structured</div>
<div className="text-xs text-gray-600 dark:text-gray-300">Claude creates commits</div>
</div>
{effectiveMode === 'structured' && (
<div className="w-2 h-2 bg-blue-500 rounded-full" />
)}
</button>
<button
onClick={() => handleQuickModeChange('checkpoint')}
className={`w-full text-left px-3 py-2.5 rounded-md transition-colors flex items-center gap-2 ${
effectiveMode === 'checkpoint' ? 'bg-green-50 dark:bg-green-900/20 text-green-700 dark:text-green-300' : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Zap className="w-4 h-4 text-green-600 dark:text-green-400" />
<div className="flex-1">
<div className="text-sm font-semibold">Checkpoint</div>
<div className="text-xs text-gray-600 dark:text-gray-300">Auto-commit after each prompt</div>
</div>
{effectiveMode === 'checkpoint' && (
<div className="w-2 h-2 bg-green-500 rounded-full" />
)}
</button>
<button
onClick={() => handleQuickModeChange('disabled')}
className={`w-full text-left px-3 py-2.5 rounded-md transition-colors flex items-center gap-2 ${
effectiveMode === 'disabled' ? 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300' : 'text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<GitCommit className="w-4 h-4 text-gray-600 dark:text-gray-400" />
<div className="flex-1">
<div className="text-sm font-semibold">Disabled</div>
<div className="text-xs text-gray-600 dark:text-gray-300">Manual commits only</div>
</div>
{effectiveMode === 'disabled' && (
<div className="w-2 h-2 bg-gray-500 rounded-full" />
)}
</button>
<div className="border-t border-gray-200 dark:border-gray-600 my-1.5" />
{/* Settings Button */}
<button
onClick={() => {
setShowDropdown(false);
setShowSettings(true);
}}
className="w-full text-left px-3 py-2.5 rounded-md text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center gap-2"
>
<Settings className="w-4 h-4 text-gray-600 dark:text-gray-400" />
<span className="text-sm font-medium">Commit Mode Settings...</span>
</button>
</div>
</div>
</>
)}
</div>
{/* Settings Dialog */}
{showSettings && (
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-modal-backdrop">
<div className="bg-surface-primary rounded-lg shadow-modal max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto z-modal">
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[10000]">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
<div className="p-6">
<h2 className="text-xl font-bold mb-4 text-text-primary">Commit Mode Settings</h2>
<h2 className="text-xl font-bold mb-4">Commit Mode Settings</h2>
<CommitModeSettingsComponent
projectId={projectId}
@ -205,12 +206,12 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
/>
<div className="flex justify-end gap-3 mt-6">
<Button
<button
onClick={() => setShowSettings(false)}
variant="secondary"
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-300 dark:hover:bg-gray-600"
>
Done
</Button>
</button>
</div>
</div>
</div>
@ -218,97 +219,4 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
)}
</>
);
};
// Auto-Commit Switch Component
//
// NOTE: This component is currently HIDDEN from the UI (commented out in input panels).
//
// REASON: The autoCommit boolean field is a legacy system that has been superseded
// by the more sophisticated CommitMode system (structured/checkpoint/disabled).
//
// BACKWARDS COMPATIBILITY: The legacy autoCommit field still works through the
// executionTracker.ts conversion logic, but this UI component actually calls the
// modern commit-mode system rather than updating the legacy autoCommit field.
//
// CURRENT STATE:
// - UI shows AutoCommitSwitch (when enabled) -> calls commit-mode:update-session-settings
// - Legacy autoCommit field may become stale
// - executionTracker.ts converts legacy autoCommit to commitMode for backwards compatibility
//
// DECISION: Hide the toggle to avoid confusion. Users should use the CommitModePill
// to select between structured/checkpoint/disabled modes instead of a simple on/off toggle.
//
// FUTURE: The autoCommit database column will be dropped as part of the database cleanup.
export const AutoCommitSwitch: React.FC<AutoCommitSwitchProps> = ({
sessionId,
currentMode,
currentSettings,
autoCommit,
onModeChange,
}) => {
// Parse current settings or use defaults
let parsedSettings: CommitModeSettings;
try {
parsedSettings = currentSettings ? JSON.parse(currentSettings) : { mode: 'checkpoint' };
} catch {
parsedSettings = { mode: 'checkpoint' };
}
// Determine effective mode (backwards compatibility)
const effectiveMode = currentMode || (autoCommit === false ? 'disabled' : 'checkpoint');
// Auto-Commit is enabled when mode is not 'disabled'
const isAutoCommitEnabled = effectiveMode !== 'disabled';
// Get the active commit mode (defaults to checkpoint if enabled)
const activeCommitMode: 'structured' | 'checkpoint' = isAutoCommitEnabled
? (effectiveMode === 'structured' ? 'structured' : 'checkpoint')
: 'checkpoint'; // Default for when auto-commit gets enabled
const handleAutoCommitToggle = async (enabled: boolean) => {
const newMode: CommitMode = enabled ? activeCommitMode : 'disabled';
const newSettings: CommitModeSettings = {
...parsedSettings,
mode: newMode,
};
// Update via IPC
try {
await window.electronAPI.invoke('commit-mode:update-session-settings', sessionId, newSettings);
// Notify parent component
if (onModeChange) {
onModeChange(newMode, newSettings);
}
} catch (error) {
console.error('Failed to update commit mode:', error);
}
};
return (
<Switch
checked={isAutoCommitEnabled}
onCheckedChange={handleAutoCommitToggle}
label="Auto-Commit"
icon={<GitCommit />}
size="sm"
/>
);
};
// Legacy wrapper component for backwards compatibility
export const CommitModeToggle: React.FC<CommitModeToggleProps> = (props) => {
// Determine effective mode for isAutoCommitEnabled calculation
const effectiveMode = props.currentMode || (props.autoCommit === false ? 'disabled' : 'checkpoint');
const isAutoCommitEnabled = effectiveMode !== 'disabled';
return (
<div className="inline-flex flex-col items-start gap-0.5">
<AutoCommitSwitch {...props} />
<div className="ml-5 mt-0">
<CommitModePill {...props} isAutoCommitEnabled={isAutoCommitEnabled} />
</div>
</div>
);
};

View File

@ -1,99 +0,0 @@
import { useEffect } from 'react';
import { X } from 'lucide-react';
interface ConfirmDialogProps {
isOpen: boolean;
onClose: () => void;
onConfirm: () => void;
title: string;
message: string;
confirmText?: string;
cancelText?: string;
confirmButtonClass?: string;
icon?: React.ReactNode;
}
export function ConfirmDialog({
isOpen,
onClose,
onConfirm,
title,
message,
confirmText = 'Confirm',
cancelText = 'Cancel',
confirmButtonClass = 'bg-red-600 hover:bg-red-700 text-white',
icon
}: ConfirmDialogProps) {
// Handle keyboard events
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Enter') {
event.preventDefault();
onConfirm();
onClose();
} else if (event.key === 'Escape') {
event.preventDefault();
onClose();
}
};
if (isOpen) {
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}
}, [isOpen, onConfirm, onClose]);
if (!isOpen) return null;
const handleConfirm = () => {
onConfirm();
onClose();
};
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full mx-4 p-6">
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-3">
{icon && (
<div className="flex-shrink-0">
{icon}
</div>
)}
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
{title}
</h3>
</div>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="mb-6">
<p className="text-gray-700 dark:text-gray-300 whitespace-pre-line leading-relaxed">
{message}
</p>
</div>
<div className="flex justify-end space-x-3">
<button
onClick={onClose}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
>
{cancelText}
</button>
<button
onClick={handleConfirm}
className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${confirmButtonClass}`}
autoFocus
>
{confirmText}
</button>
</div>
</div>
</div>
);
}

View File

@ -1,13 +1,9 @@
import { useState } from 'react';
import { CreateSessionDialog } from './CreateSessionDialog';
import { API } from '../utils/api';
import { Button } from './ui/Button';
import { Plus, Zap } from 'lucide-react';
import { getCodexModelConfig } from '../../../shared/types/models';
export function CreateSessionButton() {
const [isOpen, setIsOpen] = useState(false);
const [isCreatingQuick, setIsCreatingQuick] = useState(false);
const handleClick = async () => {
try {
@ -27,77 +23,18 @@ export function CreateSessionButton() {
alert('Error checking project status. Please try again.');
}
};
const handleQuickAdd = async () => {
try {
setIsCreatingQuick(true);
// Check if there's an active project
const projectResponse = await API.projects.getActive();
if (!projectResponse.success || !projectResponse.data) {
alert('Please select or create a project first before creating a session.');
return;
}
const activeProject = projectResponse.data;
// Create a session with minimal configuration
// The backend will handle making "untitled" unique (untitled-1, untitled-2, etc.)
const lastModel = activeProject.lastUsedModel || 'auto';
const toolType = getCodexModelConfig(lastModel) ? 'codex' : 'claude';
const response = await API.sessions.create({
prompt: '', // No initial prompt
worktreeTemplate: 'untitled', // Simple name - backend will make it unique
count: 1,
permissionMode: 'ignore', // Use default permission mode
toolType,
projectId: activeProject.id,
autoCommit: true,
commitMode: 'checkpoint',
commitModeSettings: JSON.stringify({
mode: 'checkpoint',
checkpointPrefix: 'checkpoint: '
})
});
if (!response.success) {
console.error('Failed to create quick session:', response.error);
alert('Failed to create session. Please try again.');
}
} catch (error) {
console.error('Error creating quick session:', error);
alert('Error creating session. Please try again.');
} finally {
setIsCreatingQuick(false);
}
};
return (
<>
<div className="flex gap-2">
<Button
onClick={handleClick}
data-testid="create-session-button"
variant="primary"
fullWidth
>
<Plus className="w-4 h-4 mr-1" />
New Session
</Button>
<Button
onClick={handleQuickAdd}
data-testid="quick-add-session-button"
variant="secondary"
disabled={isCreatingQuick}
title="Quick add new session"
>
<Zap className="w-4 h-4" />
</Button>
</div>
<button
onClick={handleClick}
data-testid="create-session-button"
className="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
>
New Session
</button>
<CreateSessionDialog isOpen={isOpen} onClose={() => setIsOpen(false)} />
</>
);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,8 @@
import { useState, useEffect, useMemo, memo, useCallback, forwardRef, useImperativeHandle, useRef } from 'react';
import { MonacoDiffViewer } from './MonacoDiffViewer';
import { FileText, ChevronRight, ChevronDown } from 'lucide-react';
import type { DiffViewerProps } from '../../../types/diff';
import type { FileDiff } from '../../../types/diff';
import { useTheme } from '../../../contexts/ThemeContext';
import type { DiffViewerProps } from '../types/diff';
import type { FileDiff } from '../types/diff';
// Parse unified diff format to extract individual file diffs
const parseUnifiedDiff = (diff: string): FileDiff[] => {
@ -137,7 +136,6 @@ export interface DiffViewerHandle {
}
const DiffViewer = memo(forwardRef<DiffViewerHandle, DiffViewerProps>(({ diff, sessionId, className = '', onFileSave, isAllCommitsSelected = true, mainBranch = 'main' }, ref) => {
const { theme } = useTheme();
const [viewType, setViewType] = useState<'split' | 'inline'>('split');
const [expandedFiles, setExpandedFiles] = useState<Set<string>>(new Set());
const [filesWithFullContent, setFilesWithFullContent] = useState<FileDiff[]>([]);
@ -331,19 +329,19 @@ const DiffViewer = memo(forwardRef<DiffViewerHandle, DiffViewerProps>(({ diff, s
if (!diff || diff.trim() === '' || files.length === 0) {
return (
<div className={`p-4 text-text-secondary text-center ${className}`}>
<div className={`p-4 text-gray-500 dark:text-gray-400 text-center ${className}`}>
No changes to display
</div>
);
}
const isDarkMode = theme === 'dark';
const isDarkMode = document.documentElement.classList.contains('dark');
// Show loading state while fetching full content
if (loadingFullContent && isAllCommitsSelected) {
return (
<div className={`flex items-center justify-center p-8 ${className}`}>
<div className="text-text-secondary">Loading file contents for editing...</div>
<div className="text-gray-600 dark:text-gray-400">Loading file contents for editing...</div>
</div>
);
}
@ -354,22 +352,22 @@ const DiffViewer = memo(forwardRef<DiffViewerHandle, DiffViewerProps>(({ diff, s
return (
<div className={`diff-viewer ${className}`} style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
{/* Header */}
<div className="flex justify-between items-center px-4 py-2 flex-shrink-0 bg-surface-secondary border-b border-border-primary">
<div className="flex justify-between items-center px-4 py-2 flex-shrink-0 bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-4">
<span className="text-sm text-text-secondary">
<span className="text-sm text-gray-600 dark:text-gray-400">
{filesToRender.length} {filesToRender.length === 1 ? 'file' : 'files'} changed
</span>
</div>
<div className="flex items-center space-x-4">
{/* Split/Unified Toggle */}
<div className="inline-flex rounded-lg border border-border-primary bg-surface-primary">
<div className="inline-flex rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700">
<button
onClick={() => handleViewTypeChange('inline')}
className={`px-3 py-1 text-sm font-medium rounded-l-lg transition-colors ${
viewType === 'inline'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
>
Unified
@ -378,8 +376,8 @@ const DiffViewer = memo(forwardRef<DiffViewerHandle, DiffViewerProps>(({ diff, s
onClick={() => handleViewTypeChange('split')}
className={`px-3 py-1 text-sm font-medium rounded-r-lg transition-colors ${
viewType === 'split'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
>
Split
@ -403,14 +401,14 @@ const DiffViewer = memo(forwardRef<DiffViewerHandle, DiffViewerProps>(({ diff, s
if (file.isBinary || (!file.oldValue && !file.newValue && file.type !== 'added' && file.type !== 'deleted')) {
return (
<div key={fileKey} className="border-b border-border-primary">
<div className="px-4 py-3 bg-surface-secondary">
<div key={fileKey} className="border-b border-gray-200 dark:border-gray-700">
<div className="px-4 py-3 bg-gray-50 dark:bg-gray-800">
<div className="flex items-center justify-between">
<span className="font-medium text-text-primary flex items-center gap-2">
<span className="font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2">
<FileText className="w-4 h-4" />
{file.path}
</span>
<span className="text-xs text-text-tertiary">
<span className="text-xs text-gray-500 dark:text-gray-400">
{file.isBinary ? 'Binary file' : file.type}
</span>
</div>
@ -424,53 +422,53 @@ const DiffViewer = memo(forwardRef<DiffViewerHandle, DiffViewerProps>(({ diff, s
key={fileKey}
id={`file-${index}`}
data-file-path={file.path}
className="border-b border-border-primary"
className="border-b border-gray-200 dark:border-gray-700"
>
{/* File header */}
<div
className="px-4 py-3 bg-surface-secondary hover:bg-surface-hover cursor-pointer transition-colors"
className="px-4 py-3 bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer transition-colors"
onClick={() => toggleFile(fileKey)}
>
<div className="flex items-center justify-between">
<span className="font-medium text-text-primary flex items-center gap-2">
<span className="font-medium text-gray-900 dark:text-gray-100 flex items-center gap-2">
{isExpanded ? <ChevronDown className="w-4 h-4" /> : <ChevronRight className="w-4 h-4" />}
<FileText className="w-4 h-4" />
{file.path}
{isModified && (
<span className="text-xs bg-status-warning text-white px-2 py-0.5 rounded">Modified</span>
<span className="text-xs bg-yellow-500 text-white px-2 py-0.5 rounded">Modified</span>
)}
{file.type === 'deleted' && (
<span className="text-xs bg-status-error text-white px-2 py-0.5 rounded">Deleted</span>
<span className="text-xs bg-red-500 text-white px-2 py-0.5 rounded">Deleted</span>
)}
</span>
<span className="text-xs text-text-tertiary flex items-center gap-2">
{file.additions > 0 && <span className="text-status-success">+{file.additions}</span>}
{file.deletions > 0 && <span className="text-status-error">-{file.deletions}</span>}
<span className="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-2">
{file.additions > 0 && <span className="text-green-600">+{file.additions}</span>}
{file.deletions > 0 && <span className="text-red-600">-{file.deletions}</span>}
</span>
</div>
</div>
{/* Diff content */}
{isExpanded && (
<div className="border-t border-border-primary">
<div className="border-t border-gray-200 dark:border-gray-700">
{file.type === 'deleted' ? (
<div className="p-4 bg-surface-secondary text-text-secondary">
<div className="p-4 bg-gray-50 dark:bg-gray-800 text-gray-600 dark:text-gray-400">
<p className="text-sm">This file has been deleted from the filesystem.</p>
</div>
) : (
<>
{loadErrors[file.path] && isAllCommitsSelected ? (
<div className="p-4 bg-status-error/10 border-b border-status-error/30">
<div className="flex items-center gap-2 text-status-error">
<div className="p-4 bg-red-50 dark:bg-red-900/20 border-b border-red-200 dark:border-red-700">
<div className="flex items-center gap-2 text-red-700 dark:text-red-300">
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span className="font-medium">Failed to load full file content</span>
</div>
<p className="mt-1 text-sm text-status-error/80">
<p className="mt-1 text-sm text-red-600 dark:text-red-400">
{loadErrors[file.path]}
</p>
<p className="mt-2 text-sm text-status-error/80">
<p className="mt-2 text-sm text-red-600 dark:text-red-400">
⚠️ Auto-save is disabled for this file to prevent data loss. Only the diff is shown below.
</p>
</div>

View File

@ -1,12 +1,5 @@
import React, { useState, useEffect } from 'react';
import { Modal, ModalBody } from './ui/Modal';
// Type for preferences IPC response
interface IPCResponse<T = unknown> {
success: boolean;
data?: T;
error?: string;
}
import { X } from 'lucide-react';
interface DiscordPopupProps {
isOpen: boolean;
@ -22,7 +15,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
if (window.electron?.invoke) {
try {
console.log('[Discord] Loading hide_discord preference...');
const result = await window.electron.invoke('preferences:get', 'hide_discord') as IPCResponse<string>;
const result = await window.electron.invoke('preferences:get', 'hide_discord');
console.log('[Discord] Preference result:', result);
if (result?.success) {
@ -46,7 +39,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
const handleClose = async () => {
if (window.electron?.invoke) {
try {
const result = await window.electron.invoke('preferences:set', 'hide_discord', dontShowAgain ? 'true' : 'false') as IPCResponse;
const result = await window.electron.invoke('preferences:set', 'hide_discord', dontShowAgain ? 'true' : 'false');
if (!result?.success) {
console.error('[Discord] Failed to set preference on close:', result?.error);
}
@ -61,7 +54,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
// Just close without setting the hide flag
if (window.electron?.invoke) {
try {
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'false') as IPCResponse;
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'false');
if (!result?.success) {
console.error('[Discord] Failed to set preference on remind later:', result?.error);
}
@ -82,7 +75,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
}
if (dontShowAgain && window.electron?.invoke) {
try {
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'true') as IPCResponse;
const result = await window.electron.invoke('preferences:set', 'hide_discord', 'true');
if (!result?.success) {
console.error('[Discord] Failed to set preference on join discord:', result?.error);
}
@ -93,34 +86,45 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
onClose();
};
return (
<Modal isOpen={isOpen} onClose={handleClose} size="md">
<div className="relative overflow-hidden -m-6 mb-0">
<div className="absolute inset-0 bg-gradient-to-r from-[#5865F2] to-[#7289DA] opacity-90" />
<div className="relative px-6 py-8 text-center">
<div className="flex items-center justify-center mb-4">
<svg className="w-12 h-12 text-white" viewBox="0 0 24 24" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z"/>
</svg>
</div>
<h2 className="text-2xl font-bold text-white mb-2">Join the Crystal Community!</h2>
<p className="text-white/90">Connect with other Crystal users, get help, and stay updated</p>
</div>
</div>
if (!isOpen) return null;
<ModalBody>
return (
<div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
<div className="bg-[#1e1e1e] rounded-xl border border-gray-700 max-w-md w-full shadow-2xl transform transition-all">
{/* Header */}
<div className="relative overflow-hidden rounded-t-xl">
<div className="absolute inset-0 bg-gradient-to-r from-[#5865F2] to-[#7289DA] opacity-90" />
<div className="relative px-6 py-8 text-center">
<div className="flex items-center justify-center mb-4">
<svg className="w-12 h-12 text-white" viewBox="0 0 24 24" fill="currentColor">
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515a.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0a12.64 12.64 0 0 0-.617-1.25a.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057a19.9 19.9 0 0 0 5.993 3.03a.078.078 0 0 0 .084-.028a14.09 14.09 0 0 0 1.226-1.994a.076.076 0 0 0-.041-.106a13.107 13.107 0 0 1-1.872-.892a.077.077 0 0 1-.008-.128a10.2 10.2 0 0 0 .372-.292a.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127a12.299 12.299 0 0 1-1.873.892a.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028a19.839 19.839 0 0 0 6.002-3.03a.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.956-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419c0-1.333.955-2.419 2.157-2.419c1.21 0 2.176 1.096 2.157 2.42c0 1.333-.946 2.418-2.157 2.418z"/>
</svg>
</div>
<h2 className="text-2xl font-bold text-white mb-2">Join the Crystal Community!</h2>
<p className="text-white/90">Connect with other Crystal users, get help, and stay updated</p>
</div>
<button
onClick={handleClose}
className="absolute top-4 right-4 text-white/80 hover:text-white transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
{/* Content */}
<div className="px-6 py-6">
<div className="space-y-4 mb-6">
<div className="flex items-start space-x-3">
<div className="w-2 h-2 rounded-full bg-[#5865F2] mt-2 flex-shrink-0" />
<p className="text-text-secondary">Get help with Crystal and Claude Code</p>
<p className="text-gray-300">Get help with Crystal and Claude Code</p>
</div>
<div className="flex items-start space-x-3">
<div className="w-2 h-2 rounded-full bg-[#5865F2] mt-2 flex-shrink-0" />
<p className="text-text-secondary">Share your workflows and learn from others</p>
<p className="text-gray-300">Share your workflows and learn from others</p>
</div>
<div className="flex items-start space-x-3">
<div className="w-2 h-2 rounded-full bg-[#5865F2] mt-2 flex-shrink-0" />
<p className="text-text-secondary">Be the first to know about updates and features</p>
<p className="text-gray-300">Be the first to know about updates and features</p>
</div>
</div>
@ -138,7 +142,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
<button
onClick={handleRemindLater}
className="w-full px-4 py-3 bg-surface-tertiary hover:bg-surface-hover text-text-secondary font-medium rounded-lg transition-colors"
className="w-full px-4 py-3 bg-gray-700 hover:bg-gray-600 text-gray-300 font-medium rounded-lg transition-colors"
>
Remind Me Later
</button>
@ -152,7 +156,7 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
setDontShowAgain(newValue);
if (window.electron?.invoke) {
try {
const result = await window.electron.invoke('preferences:set', 'hide_discord', newValue ? 'true' : 'false') as IPCResponse;
const result = await window.electron.invoke('preferences:set', 'hide_discord', newValue ? 'true' : 'false');
if (result?.success) {
console.log('[Discord] Successfully set hide_discord preference to', newValue);
} else {
@ -169,14 +173,15 @@ export const DiscordPopup: React.FC<DiscordPopupProps> = ({ isOpen, onClose }) =
}}
className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
dontShowAgain
? 'bg-surface-tertiary text-text-primary hover:bg-surface-hover'
: 'bg-surface-primary text-text-tertiary hover:bg-surface-secondary hover:text-text-secondary'
? 'bg-gray-700 text-gray-100 hover:bg-gray-600'
: 'bg-gray-800 text-gray-400 hover:bg-gray-700 hover:text-gray-300'
}`}
>
{dontShowAgain ? "Will hide permanently" : "Don't show this again"}
</button>
</div>
</ModalBody>
</Modal>
</div>
</div>
</div>
);
};

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,4 @@
import { LucideIcon } from 'lucide-react';
import { Button } from './ui/Button';
import { cn } from '../utils/cn';
interface EmptyStateProps {
icon: LucideIcon;
@ -13,18 +11,21 @@ interface EmptyStateProps {
className?: string;
}
export function EmptyState({ icon: Icon, title, description, action, className }: EmptyStateProps) {
export function EmptyState({ icon: Icon, title, description, action, className = '' }: EmptyStateProps) {
return (
<div className={cn('flex flex-col items-center justify-center p-12 text-center', className)}>
<div className="w-16 h-16 bg-surface-secondary rounded-full flex items-center justify-center mb-4">
<Icon className="w-8 h-8 text-text-tertiary" />
<div className={`flex flex-col items-center justify-center p-12 text-center ${className}`}>
<div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mb-4">
<Icon className="w-8 h-8 text-gray-600 dark:text-gray-400" />
</div>
<h3 className="text-lg font-semibold text-text-primary mb-2">{title}</h3>
<p className="text-sm text-text-secondary max-w-sm mb-6">{description}</p>
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">{title}</h3>
<p className="text-sm text-gray-600 dark:text-gray-400 max-w-sm mb-6">{description}</p>
{action && (
<Button onClick={action.onClick} variant="primary">
<button
onClick={action.onClick}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
>
{action.label}
</Button>
</button>
)}
</div>
);

View File

@ -1,6 +1,5 @@
import React, { Component, ReactNode } from 'react';
import { AlertCircle } from 'lucide-react';
import { Button } from './ui/Button';
interface ErrorBoundaryProps {
children: ReactNode;
@ -25,17 +24,7 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
console.error('Component stack:', errorInfo.componentStack);
this.setState({ errorInfo });
// Log to file in development mode for debugging
if (process.env.NODE_ENV === 'development') {
console.log('[ErrorBoundary] Full error details:', {
message: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack
});
}
}
render() {
@ -47,56 +36,21 @@ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundarySt
// Default error UI
return (
<div className="flex items-center justify-center h-screen p-8 bg-bg-primary">
<div className="text-center max-w-2xl">
<AlertCircle className="w-16 h-16 text-status-error mx-auto mb-6" />
<h2 className="text-2xl font-semibold text-text-primary mb-3">
<div className="flex items-center justify-center h-full p-8">
<div className="text-center">
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
Something went wrong
</h2>
<p className="text-text-secondary mb-6">
Crystal encountered an unexpected error and needs to reload.
</p>
{/* Error details */}
{this.state.error && (
<div className="bg-surface-secondary border border-border-primary rounded-lg p-4 mb-6 text-left">
<p className="font-mono text-sm text-status-error mb-2">
{this.state.error.message}
</p>
{process.env.NODE_ENV === 'development' && this.state.error.stack && (
<details className="text-xs text-text-muted mt-2">
<summary className="cursor-pointer hover:text-text-secondary">
Stack trace (dev only)
</summary>
<pre className="mt-2 overflow-x-auto whitespace-pre-wrap">
{this.state.error.stack}
</pre>
</details>
)}
</div>
)}
<div className="flex gap-3 justify-center">
<Button
onClick={() => window.location.reload()}
variant="primary"
>
Reload Application
</Button>
<Button
onClick={() => {
// Try to reset state and recover
this.setState({ hasError: false, error: null, errorInfo: null });
}}
variant="secondary"
>
Try to Continue
</Button>
</div>
<p className="text-xs text-text-muted mt-6">
If this keeps happening, please report it on GitHub
<p className="text-gray-600 dark:text-gray-400 mb-4">
The editor encountered an error. Please try refreshing the page.
</p>
<button
onClick={() => window.location.reload()}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
Refresh Page
</button>
</div>
</div>
);

View File

@ -1,8 +1,5 @@
import { useState } from 'react';
import { AlertCircle, ChevronDown, ChevronUp } from 'lucide-react';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
import { Card } from './ui/Card';
import { AlertCircle, X, ChevronDown, ChevronUp } from 'lucide-react';
interface ErrorDialogProps {
isOpen: boolean;
@ -23,6 +20,8 @@ export function ErrorDialog({
}: ErrorDialogProps) {
const [isDetailsExpanded, setIsDetailsExpanded] = useState(false);
if (!isOpen) return null;
// Check if details are long enough to warrant collapsing
const shouldCollapse = details && details.length > 500;
const displayDetails = shouldCollapse && !isDetailsExpanded
@ -30,71 +29,74 @@ export function ErrorDialog({
: details;
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalHeader>
<div className="flex items-center space-x-3">
<AlertCircle className="w-6 h-6 text-status-error flex-shrink-0" />
<span>{title}</span>
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[80vh] flex flex-col border border-gray-200 dark:border-gray-700">
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-3">
<AlertCircle className="w-6 h-6 text-red-500 flex-shrink-0" />
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-200">{title}</h3>
</div>
<button
onClick={onClose}
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
</ModalHeader>
<ModalBody>
<div className="space-y-4">
<div className="space-y-4 overflow-y-auto">
<div>
<p className="text-text-secondary">{error}</p>
<p className="text-gray-700 dark:text-gray-300">{error}</p>
</div>
{command && (
<div>
<h4 className="text-sm font-medium text-text-tertiary mb-1">Command:</h4>
<Card variant="bordered" padding="sm" className="bg-surface-secondary">
<pre className="text-sm text-text-primary font-mono overflow-x-auto">
{command}
</pre>
</Card>
<h4 className="text-sm font-medium text-gray-600 dark:text-gray-400 mb-1">Command:</h4>
<pre className="bg-gray-100 dark:bg-gray-900 p-3 rounded text-sm text-gray-800 dark:text-gray-300 font-mono overflow-x-auto border border-gray-200 dark:border-gray-700">
{command}
</pre>
</div>
)}
{details && (
<div>
<div className="flex items-center justify-between mb-1">
<h4 className="text-sm font-medium text-text-tertiary">Error Details:</h4>
<h4 className="text-sm font-medium text-gray-600 dark:text-gray-400">Error Details:</h4>
{shouldCollapse && (
<Button
<button
onClick={() => setIsDetailsExpanded(!isDetailsExpanded)}
variant="ghost"
size="sm"
className="text-xs"
className="text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 flex items-center space-x-1"
>
{isDetailsExpanded ? (
<>
<span>Show less</span>
<ChevronUp className="w-3 h-3 ml-1" />
<ChevronUp className="w-3 h-3" />
</>
) : (
<>
<span>Show more</span>
<ChevronDown className="w-3 h-3 ml-1" />
<ChevronDown className="w-3 h-3" />
</>
)}
</Button>
</button>
)}
</div>
<Card variant="bordered" padding="sm" className="bg-status-error/10 border-status-error/30">
<pre className="text-sm text-status-error font-mono overflow-x-auto whitespace-pre-wrap">
{displayDetails}
</pre>
</Card>
<pre className="bg-red-50 dark:bg-gray-900 p-3 rounded text-sm text-red-700 dark:text-red-400 font-mono overflow-x-auto whitespace-pre-wrap border border-red-200 dark:border-gray-700">
{displayDetails}
</pre>
</div>
)}
</div>
</ModalBody>
<ModalFooter>
<Button onClick={onClose} variant="secondary">
Close
</Button>
</ModalFooter>
</Modal>
<div className="mt-6 flex justify-end">
<button
onClick={onClose}
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-white rounded-md transition-colors"
>
Close
</button>
</div>
</div>
</div>
);
}

View File

@ -1,8 +1,6 @@
import React, { useState, memo } from 'react';
import { GitCommit, RotateCcw, RefreshCw } from 'lucide-react';
import type { ExecutionListProps } from '../types/diff';
import { Button } from './ui/Button';
import { Card } from './ui/Card';
const ExecutionList: React.FC<ExecutionListProps> = memo(({
executions,
@ -10,12 +8,9 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
onSelectionChange,
onCommit,
onRevert,
onRestore,
historyLimitReached = false,
historyLimit
onRestore
}) => {
const [rangeStart, setRangeStart] = useState<number | null>(null);
const limitDisplay = historyLimit ?? 50;
const handleCommitClick = (executionId: number, event: React.MouseEvent) => {
if (event.shiftKey && rangeStart !== null) {
@ -51,14 +46,14 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
const getStatsDisplay = (exec: { stats_additions: number; stats_deletions: number; stats_files_changed: number }) => {
const { stats_additions, stats_deletions, stats_files_changed } = exec;
if (stats_files_changed === 0) {
return <span className="text-text-tertiary text-sm">No changes</span>;
return <span className="text-gray-500 dark:text-gray-400 text-sm">No changes</span>;
}
return (
<div className="text-sm space-x-3">
<span className="text-status-success">+{stats_additions}</span>
<span className="text-status-error">-{stats_deletions}</span>
<span className="text-text-tertiary">{stats_files_changed} {stats_files_changed === 1 ? 'file' : 'files'}</span>
<span className="text-green-600 dark:text-green-400">+{stats_additions}</span>
<span className="text-red-600 dark:text-red-400">-{stats_deletions}</span>
<span className="text-gray-600 dark:text-gray-400">{stats_files_changed} {stats_files_changed === 1 ? 'file' : 'files'}</span>
</div>
);
};
@ -75,7 +70,7 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
if (executions.length === 0) {
return (
<div className="p-4 text-text-tertiary text-center">
<div className="p-4 text-gray-500 dark:text-gray-400 text-center">
No commits found for this session
</div>
);
@ -84,23 +79,20 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
return (
<div className="execution-list h-full flex flex-col">
{/* Header */}
<Card variant="bordered" className="rounded-b-none border-b-0">
<div className="flex items-center justify-between">
<h3 className="text-lg font-medium text-text-primary">
Commits ({executions.filter(e => e.id !== 0).length})
</h3>
<Button
onClick={handleSelectAll}
size="sm"
variant="ghost"
>
Select All Commits
</Button>
</div>
</Card>
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800">
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100">
Commits ({executions.filter(e => e.id !== 0).length})
</h3>
<button
onClick={handleSelectAll}
className="text-sm px-3 py-1 border border-gray-300 dark:border-gray-600 rounded hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-gray-700 dark:text-gray-300"
>
Select All Commits
</button>
</div>
{/* Instructions */}
<div className="px-4 py-2 bg-bg-secondary text-xs text-text-tertiary border-b border-border-secondary">
<div className="px-4 py-2 bg-gray-100 dark:bg-gray-700 text-xs text-gray-600 dark:text-gray-400 border-b border-gray-300 dark:border-gray-600">
Click to select a single commit, Shift+Click to select a range
</div>
@ -114,63 +106,59 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
<div
key={execution.id}
className={`
flex items-center p-4 border-b border-border-secondary cursor-pointer hover:bg-bg-hover transition-colors
${isSelected ? 'bg-bg-accent border-l-4 border-l-interactive' : ''}
${isUncommitted ? 'bg-status-warning/20' : ''}
flex items-center p-4 border-b border-gray-200 dark:border-gray-700 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors
${isSelected ? 'bg-blue-100 dark:bg-blue-900/20 border-l-4 border-l-blue-500' : ''}
${isUncommitted ? 'bg-yellow-100 dark:bg-yellow-900/20' : ''}
`}
onClick={(e) => handleCommitClick(execution.id, e)}
>
<div className="mr-3 w-4 h-4 flex items-center justify-center">
{isSelected && (
<div className="w-3 h-3 bg-interactive rounded-full" />
<div className="w-3 h-3 bg-blue-600 rounded-full" />
)}
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2">
<div className="text-sm font-medium text-text-primary">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
{isUncommitted ? (
<span className="text-status-warning">Uncommitted changes</span>
<span className="text-yellow-700 dark:text-yellow-300">Uncommitted changes</span>
) : (
<span>{truncateMessage(execution.commit_message || execution.prompt_text || `Commit ${execution.execution_sequence}`)}</span>
<span>{truncateMessage(execution.prompt_text || `Commit ${execution.execution_sequence}`)}</span>
)}
</div>
{isUncommitted && (
<div className="flex items-center gap-2">
{onCommit && execution.stats_files_changed > 0 && (
<Button
<button
onClick={(e) => {
e.stopPropagation();
onCommit();
}}
size="sm"
variant="primary"
className="!bg-status-success hover:!bg-status-success-hover !text-white text-xs"
className="text-xs bg-green-600 hover:bg-green-700 text-white px-2 py-1 rounded flex items-center gap-1 transition-colors"
>
<GitCommit className="w-3 h-3" />
Commit
</Button>
</button>
)}
{onRestore && execution.stats_files_changed > 0 && (
<Button
<button
onClick={(e) => {
e.stopPropagation();
onRestore();
}}
size="sm"
variant="secondary"
className="!bg-status-warning hover:!bg-status-warning-hover !text-white text-xs"
className="text-xs bg-orange-600 hover:bg-orange-700 text-white px-2 py-1 rounded flex items-center gap-1 transition-colors"
title="Restore all uncommitted changes to their last committed state"
>
<RefreshCw className="w-3 h-3" />
Restore
</Button>
</button>
)}
</div>
)}
</div>
<div className="text-xs text-text-tertiary">
<div className="text-xs text-gray-500 dark:text-gray-400">
{formatTimestamp(execution.timestamp)}
</div>
</div>
@ -183,23 +171,21 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
<div className="flex items-center gap-2">
{execution.after_commit_hash && execution.after_commit_hash !== 'UNCOMMITTED' && (
<>
<div className="text-xs text-text-tertiary font-mono">
<div className="text-xs text-gray-500 dark:text-gray-400 font-mono">
{execution.after_commit_hash.substring(0, 7)}
</div>
{onRevert && !isUncommitted && (
<Button
<button
onClick={(e) => {
e.stopPropagation();
onRevert(execution.after_commit_hash!);
}}
size="sm"
variant="danger"
className="text-xs"
className="text-xs bg-red-600 hover:bg-red-700 text-white px-2 py-1 rounded flex items-center gap-1 transition-colors"
title="Revert this commit"
>
<RotateCcw className="w-3 h-3" />
Revert
</Button>
</button>
)}
</>
)}
@ -209,19 +195,12 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
</div>
);
})}
{historyLimitReached && (
<div
className="flex items-center p-4 border-b border-border-secondary bg-bg-secondary text-text-tertiary text-xs"
>
Showing the most recent {limitDisplay} commits. Older commits are hidden.
</div>
)}
</div>
{/* Selection summary */}
{selectedExecutions.length > 0 && (
<div className="p-4 bg-bg-accent border-t border-interactive">
<div className="text-sm text-text-accent">
<div className="p-4 bg-blue-100 dark:bg-blue-900/20 border-t border-blue-300 dark:border-blue-800">
<div className="text-sm text-blue-800 dark:text-blue-200">
{selectedExecutions.length === 1 ? (
`1 commit selected`
) : selectedExecutions.length === 2 ? (
@ -238,4 +217,4 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
ExecutionList.displayName = 'ExecutionList';
export default ExecutionList;
export default ExecutionList;

View File

@ -1,14 +1,12 @@
import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { flushSync } from 'react-dom';
import Editor from '@monaco-editor/react';
import type * as monaco from 'monaco-editor';
import { ChevronRight, ChevronDown, File, Folder, RefreshCw, Plus, Trash2, FolderPlus, Search, X, Eye, Code } from 'lucide-react';
import { MonacoErrorBoundary } from '../../MonacoErrorBoundary';
import { useTheme } from '../../../contexts/ThemeContext';
import { debounce } from '../../../utils/debounce';
import { MarkdownPreview } from '../../MarkdownPreview';
import { useResizablePanel } from '../../../hooks/useResizablePanel';
import { EditorPanelState } from '../../../../../shared/types/panels';
import { MonacoErrorBoundary } from './MonacoErrorBoundary';
import { useTheme } from '../contexts/ThemeContext';
import { debounce } from '../utils/debounce';
import { MarkdownPreview } from './MarkdownPreview';
import { useResizablePanel } from '../hooks/useResizablePanel';
interface FileItem {
name: string;
@ -65,7 +63,7 @@ function FileTreeNode({ file, level, onFileClick, onRefresh, onDelete, selectedP
<>
{parts.map((part, index) =>
part.toLowerCase() === searchQuery.toLowerCase() ? (
<span key={index} className="bg-status-warning text-text-primary">
<span key={index} className="bg-yellow-600 text-gray-900">
{part}
</span>
) : (
@ -79,8 +77,8 @@ function FileTreeNode({ file, level, onFileClick, onRefresh, onDelete, selectedP
return (
<div onClick={(e) => e.stopPropagation()}>
<div
className={`flex items-center px-2 py-1 hover:bg-surface-hover cursor-pointer group ${
isSelected ? 'bg-interactive' : ''
className={`flex items-center px-2 py-1 hover:bg-gray-700 cursor-pointer group ${
isSelected ? 'bg-blue-600' : ''
}`}
style={{ paddingLeft: `${level * 16 + 8}px` }}
onClick={handleClick}
@ -89,23 +87,23 @@ function FileTreeNode({ file, level, onFileClick, onRefresh, onDelete, selectedP
{file.isDirectory ? (
<>
{isExpanded ? (
<ChevronDown className="w-4 h-4 mr-1 text-text-tertiary" />
<ChevronDown className="w-4 h-4 mr-1 text-gray-400" />
) : (
<ChevronRight className="w-4 h-4 mr-1 text-text-tertiary" />
<ChevronRight className="w-4 h-4 mr-1 text-gray-400" />
)}
<Folder className="w-4 h-4 mr-2 text-interactive" />
<Folder className="w-4 h-4 mr-2 text-blue-400" />
</>
) : (
<>
<div className="w-4 h-4 mr-1" />
<File className="w-4 h-4 mr-2 text-text-tertiary" />
<File className="w-4 h-4 mr-2 text-gray-400" />
</>
)}
<span className="flex-1 text-sm truncate text-text-primary">{highlightText(file.name)}</span>
<span className="flex-1 text-sm truncate text-gray-200">{highlightText(file.name)}</span>
{file.isDirectory && (
<button
onClick={handleRefresh}
className="opacity-0 group-hover:opacity-100 p-1 hover:bg-surface-hover rounded text-text-tertiary hover:text-text-primary"
className="opacity-0 group-hover:opacity-100 p-1 hover:bg-gray-600 rounded text-gray-400 hover:text-gray-200"
title="Refresh folder"
>
<RefreshCw className="w-3 h-3" />
@ -113,10 +111,10 @@ function FileTreeNode({ file, level, onFileClick, onRefresh, onDelete, selectedP
)}
<button
onClick={handleDelete}
className="opacity-0 group-hover:opacity-100 p-1 hover:bg-surface-hover rounded ml-1"
className="opacity-0 group-hover:opacity-100 p-1 hover:bg-gray-600 rounded ml-1"
title={`Delete ${file.isDirectory ? 'folder' : 'file'}`}
>
<Trash2 className="w-3 h-3 text-status-error" />
<Trash2 className="w-3 h-3 text-red-400" />
</button>
</div>
</div>
@ -125,31 +123,17 @@ function FileTreeNode({ file, level, onFileClick, onRefresh, onDelete, selectedP
interface FileTreeProps {
sessionId: string;
onFileSelect: (file: FileItem | null) => void;
onFileSelect: (file: FileItem) => void;
selectedPath: string | null;
initialExpandedDirs?: string[];
initialSearchQuery?: string;
initialShowSearch?: boolean;
onTreeStateChange?: (state: { expandedDirs: string[]; searchQuery: string; showSearch: boolean }) => void;
}
function FileTree({
sessionId,
onFileSelect,
selectedPath,
initialExpandedDirs,
initialSearchQuery,
initialShowSearch,
onTreeStateChange
}: FileTreeProps) {
function FileTree({ sessionId, onFileSelect, selectedPath }: FileTreeProps) {
const [files, setFiles] = useState<Map<string, FileItem[]>>(new Map());
const [expandedDirs, setExpandedDirs] = useState<Set<string>>(
new Set(initialExpandedDirs || [''])
);
const [expandedDirs, setExpandedDirs] = useState<Set<string>>(new Set(['']));
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [searchQuery, setSearchQuery] = useState(initialSearchQuery || '');
const [showSearch, setShowSearch] = useState(initialShowSearch || false);
const [searchQuery, setSearchQuery] = useState('');
const [showSearch, setShowSearch] = useState(false);
const searchInputRef = useRef<HTMLInputElement>(null);
const [showNewItemDialog, setShowNewItemDialog] = useState<'file' | 'folder' | null>(null);
const [newItemName, setNewItemName] = useState('');
@ -239,7 +223,7 @@ function FileTree({
// If the deleted file was selected, clear the selection
if (selectedPath === file.path) {
onFileSelect(null);
onFileSelect(null as any);
}
} else {
setError(`Failed to delete ${file.isDirectory ? 'folder' : 'file'}: ${result.error}`);
@ -385,35 +369,6 @@ function FileTree({
}
}, [showSearch]);
// Notify parent about tree state changes
// Use a ref to track if this is the initial mount to avoid calling on first render
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
console.log('[FileTree] Skipping initial mount state update');
return; // Skip the first render
}
console.log('[FileTree] State changed:', {
expandedDirs: Array.from(expandedDirs),
searchQuery,
showSearch
});
if (onTreeStateChange) {
console.log('[FileTree] Calling onTreeStateChange');
onTreeStateChange({
expandedDirs: Array.from(expandedDirs),
searchQuery,
showSearch
});
} else {
console.log('[FileTree] No onTreeStateChange callback');
}
}, [expandedDirs, searchQuery, showSearch]); // Remove onTreeStateChange from deps to avoid loops
// Handle keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@ -445,42 +400,42 @@ function FileTree({
}, [showSearch, searchQuery, showNewItemDialog]);
if (loading && files.size === 0) {
return <div className="p-4 text-text-secondary">Loading files...</div>;
return <div className="p-4 text-gray-400">Loading files...</div>;
}
if (error) {
return <div className="p-4 text-status-error">Error: {error}</div>;
return <div className="p-4 text-red-400">Error: {error}</div>;
}
return (
<div className="h-full flex flex-col">
<div className="flex items-center justify-between p-2 border-b border-border-primary">
<span className="text-sm font-medium text-text-primary">Files</span>
<div className="flex items-center justify-between p-2 border-b border-gray-700">
<span className="text-sm font-medium text-gray-200">Files</span>
<div className="flex gap-1">
<button
onClick={() => setShowSearch(!showSearch)}
className={`p-1 rounded text-text-tertiary hover:text-text-primary ${showSearch ? 'bg-surface-tertiary' : 'hover:bg-surface-hover'}`}
className={`p-1 rounded text-gray-400 hover:text-gray-200 ${showSearch ? 'bg-gray-700' : 'hover:bg-gray-700'}`}
title="Search files (Cmd/Ctrl+F)"
>
<Search className="w-4 h-4" />
</button>
<button
onClick={handleNewFile}
className="p-1 hover:bg-surface-hover rounded text-text-tertiary hover:text-text-primary"
className="p-1 hover:bg-gray-700 rounded text-gray-400 hover:text-gray-200"
title="New file"
>
<Plus className="w-4 h-4" />
</button>
<button
onClick={handleNewFolder}
className="p-1 hover:bg-surface-hover rounded text-text-tertiary hover:text-text-primary"
className="p-1 hover:bg-gray-700 rounded text-gray-400 hover:text-gray-200"
title="New folder"
>
<FolderPlus className="w-4 h-4" />
</button>
<button
onClick={() => loadFiles('')}
className="p-1 hover:bg-surface-hover rounded text-text-tertiary hover:text-text-primary"
className="p-1 hover:bg-gray-700 rounded text-gray-400 hover:text-gray-200"
title="Refresh all"
>
<RefreshCw className="w-4 h-4" />
@ -488,7 +443,7 @@ function FileTree({
</div>
</div>
{showSearch && (
<div className="p-2 border-b border-border-primary">
<div className="p-2 border-b border-gray-700">
<div className="relative">
<input
ref={searchInputRef}
@ -496,27 +451,27 @@ function FileTree({
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search files..."
className="w-full pl-8 pr-8 py-1 bg-surface-primary border border-border-primary rounded text-sm text-text-primary placeholder-text-tertiary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive"
className="w-full pl-8 pr-8 py-1 bg-gray-900 border border-gray-600 rounded text-sm text-gray-200 placeholder-gray-500 focus:outline-none focus:border-blue-500"
/>
<Search className="absolute left-2 top-1/2 transform -translate-y-1/2 w-4 h-4 text-text-tertiary" />
<Search className="absolute left-2 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-500" />
{searchQuery && (
<button
onClick={() => setSearchQuery('')}
className="absolute right-2 top-1/2 transform -translate-y-1/2 p-0.5 hover:bg-surface-hover rounded"
className="absolute right-2 top-1/2 transform -translate-y-1/2 p-0.5 hover:bg-gray-700 rounded"
>
<X className="w-3 h-3 text-text-tertiary" />
<X className="w-3 h-3 text-gray-400" />
</button>
)}
</div>
{searchQuery && (
<div className="mt-1 text-xs text-text-tertiary">
<div className="mt-1 text-xs text-gray-500">
Press ESC to clear • Cmd/Ctrl+F to toggle search
</div>
)}
</div>
)}
{showNewItemDialog && (
<div className="p-2 border-b border-border-primary bg-surface-secondary">
<div className="p-2 border-b border-gray-700 bg-gray-900">
<form onSubmit={(e) => { e.preventDefault(); handleCreateNewItem(); }}>
<div className="flex items-center gap-2">
<input
@ -525,19 +480,19 @@ function FileTree({
value={newItemName}
onChange={(e) => setNewItemName(e.target.value)}
placeholder={`Enter ${showNewItemDialog} name...`}
className="flex-1 px-2 py-1 bg-surface-primary border border-border-primary rounded text-sm text-text-primary placeholder-text-tertiary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive"
className="flex-1 px-2 py-1 bg-gray-800 border border-gray-600 rounded text-sm text-gray-200 placeholder-gray-500 focus:outline-none focus:border-blue-500"
/>
<button
type="submit"
disabled={!newItemName.trim()}
className="px-3 py-1 bg-interactive hover:bg-interactive-hover disabled:bg-surface-tertiary disabled:text-text-tertiary text-white rounded text-sm transition-colors"
className="px-3 py-1 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-700 disabled:text-gray-500 text-white rounded text-sm"
>
Create
</button>
<button
type="button"
onClick={() => { setShowNewItemDialog(null); setNewItemName(''); }}
className="px-3 py-1 bg-surface-tertiary hover:bg-surface-hover text-text-secondary rounded text-sm transition-colors"
className="px-3 py-1 bg-gray-700 hover:bg-gray-600 text-gray-300 rounded text-sm"
>
Cancel
</button>
@ -546,7 +501,7 @@ function FileTree({
</div>
)}
{error && (
<div className="px-3 py-2 bg-status-error/20 text-status-error text-sm border-b border-status-error/30">
<div className="px-3 py-2 bg-red-900 text-red-200 text-sm border-b border-red-800">
{error}
</div>
)}
@ -559,54 +514,27 @@ function FileTree({
interface FileEditorProps {
sessionId: string;
initialFilePath?: string;
initialState?: EditorPanelState;
onFileChange?: (filePath: string | undefined, isDirty: boolean) => void;
onStateChange?: (state: Partial<EditorPanelState>) => void;
}
export function FileEditor({
sessionId,
initialFilePath,
initialState,
onFileChange,
onStateChange
}: FileEditorProps) {
console.log('[FileEditor] Mounting with:', {
sessionId,
initialFilePath,
initialState,
hasOnStateChange: !!onStateChange
});
export function FileEditor({ sessionId }: FileEditorProps) {
const [selectedFile, setSelectedFile] = useState<FileItem | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [originalContent, setOriginalContent] = useState<string>('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<'edit' | 'preview'>('edit');
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
const monacoRef = useRef<typeof monaco | null>(null);
const editorRef = useRef<unknown>(null);
const { theme } = useTheme();
const isDarkMode = theme === 'dark';
const hasUnsavedChanges = fileContent !== originalContent;
// Wrap onResize callback to avoid recreating
const handleTreeResize = useCallback((width: number) => {
console.log('[FileEditor] Tree resized to:', width);
if (onStateChange) {
onStateChange({ fileTreeWidth: width });
}
}, [onStateChange]);
// Add resizable hook for file tree column
const { width: fileTreeWidth, startResize } = useResizablePanel({
defaultWidth: initialState?.fileTreeWidth || 256, // Use saved width or default
defaultWidth: 256, // Same as w-64
minWidth: 200,
maxWidth: 400,
storageKey: 'crystal-file-tree-width',
onResize: handleTreeResize
storageKey: 'crystal-file-tree-width'
});
// Check if this is a markdown file
@ -616,8 +544,8 @@ export function FileEditor({
return ext === 'md' || ext === 'markdown';
}, [selectedFile]);
const loadFile = useCallback(async (file: FileItem | null) => {
if (!file || file.isDirectory) return;
const loadFile = useCallback(async (file: FileItem) => {
if (file.isDirectory) return;
setLoading(true);
setError(null);
@ -632,51 +560,6 @@ export function FileEditor({
setOriginalContent(result.content);
setSelectedFile(file);
setViewMode('edit'); // Reset to edit mode when opening a new file
// Notify parent about file change
if (onFileChange) {
onFileChange(file.path, false);
}
// After loading new file, we need to restore its position
// This happens in handleEditorMount when editor re-renders
// But we also need to tell parent the file path changed
if (onStateChange) {
onStateChange({
filePath: file.path,
isDirty: false
});
}
// If we have saved position for this file, restore it
// The actual restoration happens in handleEditorMount
// but we need to trigger a re-render with the right state
if (editorRef.current && initialState?.filePath === file.path) {
const monacoEditor = editorRef.current;
// Restore cursor position
if (initialState.cursorPosition && monacoEditor.setPosition) {
const { line, column } = initialState.cursorPosition;
setTimeout(() => {
monacoEditor.setPosition({
lineNumber: line,
column: column
});
monacoEditor.revealPositionInCenter({
lineNumber: line,
column: column
});
}, 50);
}
// Restore scroll position
if (initialState.scrollPosition !== undefined && monacoEditor.setScrollTop) {
const scrollPos = initialState.scrollPosition;
setTimeout(() => {
monacoEditor.setScrollTop(scrollPos);
}, 100);
}
}
} else {
setError(result.error);
}
@ -685,81 +568,15 @@ export function FileEditor({
} finally {
setLoading(false);
}
}, [sessionId, onFileChange, onStateChange, initialState]);
}, [sessionId]);
const handleEditorMount = (editor: monaco.editor.IStandaloneCodeEditor, monacoInstance: typeof monaco) => {
const handleEditorMount = (editor: unknown) => {
editorRef.current = editor;
monacoRef.current = monacoInstance;
// Now we have properly typed Monaco editor
const monacoEditor = editor;
// Track cursor position changes with debouncing
const saveCursorPosition = debounce((position: { lineNumber: number; column: number }) => {
if (onStateChange) {
onStateChange({
cursorPosition: {
line: position.lineNumber,
column: position.column
}
});
}
}, 500); // Debounce cursor position saves
// Track scroll position changes with debouncing
const saveScrollPosition = debounce((scrollTop: number) => {
if (onStateChange) {
onStateChange({
scrollPosition: scrollTop
});
}
}, 500); // Debounce scroll position saves
// Listen for cursor position changes
monacoEditor.onDidChangeCursorPosition?.((e: monaco.editor.ICursorPositionChangedEvent) => {
saveCursorPosition(e.position);
});
// Listen for scroll position changes
monacoEditor.onDidScrollChange?.((e: { scrollTop?: number; scrollLeft?: number }) => {
if (e.scrollTop !== undefined) {
saveScrollPosition(e.scrollTop);
}
});
// Restore cursor and scroll position if available
if (initialState?.cursorPosition && monacoEditor.setPosition) {
const { line, column } = initialState.cursorPosition;
setTimeout(() => {
monacoEditor.setPosition({
lineNumber: line,
column: column
});
monacoEditor.revealPositionInCenter({
lineNumber: line,
column: column
});
}, 50); // Small delay to ensure editor is ready
}
if (initialState?.scrollPosition !== undefined && monacoEditor.setScrollTop) {
// Delay to ensure editor is fully rendered and content is loaded
const scrollPos = initialState.scrollPosition;
setTimeout(() => {
monacoEditor.setScrollTop(scrollPos);
}, 100);
}
};
const handleEditorChange = (value: string | undefined) => {
setFileContent(value || '');
// Notify parent about dirty state
if (onFileChange && selectedFile) {
const isDirty = (value || '') !== originalContent;
onFileChange(selectedFile.path, isDirty);
}
};
// Auto-save functionality
@ -776,19 +593,6 @@ export function FileEditor({
if (result.success) {
setOriginalContent(fileContent);
// Notify parent that file is saved
if (onFileChange && selectedFile) {
onFileChange(selectedFile.path, false);
}
// Emit file saved event
if (onStateChange) {
onStateChange({
filePath: selectedFile.path,
isDirty: false
});
}
} else {
setError(result.error);
}
@ -796,7 +600,7 @@ export function FileEditor({
setError(err instanceof Error ? err.message : 'Failed to auto-save file');
}
}, 1000), // Auto-save after 1 second of inactivity
[sessionId, selectedFile, fileContent, originalContent, onFileChange, onStateChange]
[sessionId, selectedFile, fileContent, originalContent]
);
// Trigger auto-save when content changes
@ -805,68 +609,18 @@ export function FileEditor({
autoSave();
}
}, [fileContent, originalContent, selectedFile, autoSave]);
// Load initial file if provided
useEffect(() => {
if (initialFilePath && !selectedFile) {
const file: FileItem = {
name: initialFilePath.split('/').pop() || '',
path: initialFilePath,
isDirectory: false
};
loadFile(file);
}
}, [initialFilePath, selectedFile, loadFile]);
// Memoize the tree state change handler to prevent infinite loops
const handleTreeStateChange = useCallback((treeState: { expandedDirs: string[]; searchQuery: string; showSearch: boolean }) => {
console.log('[FileEditor] handleTreeStateChange called with:', treeState);
if (onStateChange) {
console.log('[FileEditor] Calling onStateChange');
onStateChange({
expandedDirs: treeState.expandedDirs,
searchQuery: treeState.searchQuery,
showSearch: treeState.showSearch
});
} else {
console.log('[FileEditor] No onStateChange callback');
}
}, [onStateChange]);
// Cleanup effect for Monaco editor models
useEffect(() => {
return () => {
// Cleanup Monaco editor models when component unmounts or file changes
try {
if (editorRef.current && typeof editorRef.current === 'object' && editorRef.current !== null && 'getModel' in editorRef.current) {
const editor = editorRef.current as { getModel: () => unknown, dispose?: () => void };
const model = editor.getModel();
if (model && typeof model === 'object' && model !== null && 'dispose' in model) {
const typedModel = model as { dispose: () => void };
console.log('[FileEditor] Disposing Monaco model');
typedModel.dispose();
}
}
} catch (error) {
console.warn('[FileEditor] Error during Monaco cleanup:', error);
}
};
}, [selectedFile?.path]); // Run cleanup when file changes
return (
<div className="h-full flex">
<div
className="bg-surface-secondary border-r border-border-primary relative flex-shrink-0"
className="bg-gray-800 border-r border-gray-700 relative flex-shrink-0"
style={{ width: `${fileTreeWidth}px` }}
>
<FileTree
sessionId={sessionId}
onFileSelect={loadFile}
selectedPath={selectedFile?.path || null}
initialExpandedDirs={initialState?.expandedDirs}
initialSearchQuery={initialState?.searchQuery}
initialShowSearch={initialState?.showSearch}
onTreeStateChange={handleTreeStateChange}
/>
{/* Resize handle */}
@ -875,15 +629,15 @@ export function FileEditor({
onMouseDown={startResize}
>
{/* Visual indicator */}
<div className="absolute inset-0 bg-border-primary group-hover:bg-interactive transition-colors" />
<div className="absolute inset-0 bg-gray-700 group-hover:bg-blue-500 transition-colors" />
{/* Larger grab area */}
<div className="absolute -left-2 -right-2 top-0 bottom-0" />
{/* Drag indicator dots */}
<div className="absolute top-1/2 -translate-y-1/2 right-0 transform translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity">
<div className="flex flex-col gap-1">
<div className="w-1 h-1 bg-interactive rounded-full" />
<div className="w-1 h-1 bg-interactive rounded-full" />
<div className="w-1 h-1 bg-interactive rounded-full" />
<div className="w-1 h-1 bg-blue-400 rounded-full" />
<div className="w-1 h-1 bg-blue-400 rounded-full" />
<div className="w-1 h-1 bg-blue-400 rounded-full" />
</div>
</div>
</div>
@ -891,24 +645,24 @@ export function FileEditor({
<div className="flex-1 flex flex-col">
{selectedFile ? (
<>
<div className="flex items-center justify-between px-4 py-2 bg-surface-secondary border-b border-border-primary">
<div className="flex items-center justify-between px-4 py-2 bg-gray-800 border-b border-gray-700">
<div className="flex items-center gap-2">
<File className="w-4 h-4 text-text-tertiary" />
<span className="text-sm text-text-primary">
<File className="w-4 h-4 text-gray-400" />
<span className="text-sm text-gray-200">
{selectedFile.path}
{hasUnsavedChanges && <span className="text-status-warning ml-2">●</span>}
{hasUnsavedChanges && <span className="text-yellow-400 ml-2">●</span>}
</span>
</div>
<div className="flex items-center gap-2">
{/* Preview Toggle for Markdown Files */}
{isMarkdownFile && (
<div className="flex items-center rounded-lg border border-border-primary bg-surface-tertiary">
<div className="flex items-center rounded-lg border border-gray-600 bg-gray-700">
<button
onClick={() => setViewMode('edit')}
className={`px-2 py-1 text-xs font-medium rounded-l-lg transition-colors flex items-center gap-1 ${
viewMode === 'edit'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-300 hover:bg-gray-600'
}`}
title="Edit mode"
>
@ -919,8 +673,8 @@ export function FileEditor({
onClick={() => setViewMode('preview')}
className={`px-2 py-1 text-xs font-medium rounded-r-lg transition-colors flex items-center gap-1 ${
viewMode === 'preview'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-300 hover:bg-gray-600'
}`}
title="Preview mode"
>
@ -932,26 +686,26 @@ export function FileEditor({
<div className="flex items-center gap-2 text-sm">
{hasUnsavedChanges ? (
<>
<div className="w-2 h-2 bg-status-warning rounded-full animate-pulse" />
<span className="text-status-warning">Auto-saving...</span>
<div className="w-2 h-2 bg-yellow-400 rounded-full animate-pulse" />
<span className="text-yellow-400">Auto-saving...</span>
</>
) : (
<>
<div className="w-2 h-2 bg-status-success rounded-full" />
<span className="text-status-success">All changes saved</span>
<div className="w-2 h-2 bg-green-400 rounded-full" />
<span className="text-green-400">All changes saved</span>
</>
)}
</div>
</div>
</div>
{error && (
<div className="px-4 py-2 bg-status-error/20 text-status-error text-sm">
<div className="px-4 py-2 bg-red-900 text-red-200 text-sm">
Error: {error}
</div>
)}
<div className="flex-1 overflow-hidden">
{viewMode === 'preview' && isMarkdownFile ? (
<div className="h-full overflow-auto bg-bg-primary">
<div className="h-full overflow-auto bg-white dark:bg-gray-900">
<MarkdownPreview
content={fileContent}
className="min-h-full"
@ -979,7 +733,7 @@ export function FileEditor({
</div>
</>
) : (
<div className="flex-1 flex items-center justify-center text-text-secondary">
<div className="flex-1 flex items-center justify-center text-gray-400">
{loading ? 'Loading...' : 'Select a file to edit'}
</div>
)}

View File

@ -1,7 +1,5 @@
import React, { memo } from 'react';
import { FileText, FileCode, FileImage, File, Trash2 } from 'lucide-react';
import { IconButton } from './ui/IconButton';
import { cn } from '../utils/cn';
interface FileInfo {
path: string;
@ -20,7 +18,7 @@ interface FileListProps {
const getFileIcon = (fileName: string) => {
const ext = fileName.split('.').pop()?.toLowerCase();
const iconClass = "w-4 h-4 text-text-tertiary";
const iconClass = "w-4 h-4 text-gray-600 dark:text-gray-400";
if (!ext) return <File className={iconClass} />;
@ -45,15 +43,15 @@ const getFileIcon = (fileName: string) => {
const getTypeColor = (type: FileInfo['type']) => {
switch (type) {
case 'added':
return 'text-status-success';
return 'text-green-600 dark:text-green-400';
case 'deleted':
return 'text-status-error';
return 'text-red-600 dark:text-red-400';
case 'modified':
return 'text-interactive';
return 'text-blue-600 dark:text-blue-400';
case 'renamed':
return 'text-interactive';
return 'text-purple-600 dark:text-purple-400';
default:
return 'text-text-tertiary';
return 'text-gray-600 dark:text-gray-400';
}
};
@ -75,7 +73,7 @@ const getTypeLabel = (type: FileInfo['type']) => {
export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onFileDelete, selectedFile }) => {
if (files.length === 0) {
return (
<div className="p-4 text-center text-text-tertiary text-sm">
<div className="p-4 text-center text-gray-500 dark:text-gray-400 text-sm">
No files changed
</div>
);
@ -83,8 +81,8 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
return (
<div className="flex flex-col h-full">
<div className="px-4 py-2 border-b border-border-secondary bg-bg-secondary">
<h3 className="text-sm font-semibold text-text-secondary">
<div className="px-4 py-2 border-b border-gray-200 dark:border-gray-700 bg-gray-100 dark:bg-gray-800">
<h3 className="text-sm font-semibold text-gray-700 dark:text-gray-300">
Files Changed ({files.length})
</h3>
</div>
@ -94,10 +92,9 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
{files.map((file, index) => (
<div
key={`${file.path}-${index}`}
className={cn(
'w-full px-4 py-2 hover:bg-bg-hover transition-colors flex items-center justify-between group',
selectedFile === file.path && 'bg-bg-accent'
)}
className={`w-full px-4 py-2 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center justify-between group ${
selectedFile === file.path ? 'bg-blue-50 dark:bg-blue-900/20' : ''
}`}
>
<button
onClick={() => onFileClick(file.path, index)}
@ -107,24 +104,24 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
{getTypeLabel(file.type)}
</span>
{getFileIcon(file.path)}
<span className="text-sm text-text-primary truncate">
<span className="text-sm text-gray-700 dark:text-gray-300 truncate">
{file.path}
</span>
</button>
<div className="flex items-center gap-2 ml-2 flex-shrink-0">
{file.additions > 0 && (
<span className="text-xs text-status-success">
<span className="text-xs text-green-600 dark:text-green-400">
+{file.additions}
</span>
)}
{file.deletions > 0 && (
<span className="text-xs text-status-error">
<span className="text-xs text-red-600 dark:text-red-400">
-{file.deletions}
</span>
)}
{onFileDelete && (
<IconButton
<button
onClick={(e) => {
e.stopPropagation();
if (file.type !== 'deleted' && window.confirm(`Are you sure you want to delete ${file.path}?`)) {
@ -132,16 +129,19 @@ export const FileList: React.FC<FileListProps> = memo(({ files, onFileClick, onF
}
}}
disabled={file.type === 'deleted'}
variant={file.type === 'deleted' ? 'ghost' : 'danger'}
size="sm"
className={cn(
'opacity-0 group-hover:opacity-100 transition-opacity',
file.type === 'deleted' && 'cursor-not-allowed !text-text-disabled'
)}
aria-label={file.type === 'deleted' ? 'File already deleted' : 'Delete file'}
className={`opacity-0 group-hover:opacity-100 p-1 rounded transition-all ${
file.type === 'deleted'
? 'cursor-not-allowed'
: 'hover:bg-red-100 dark:hover:bg-red-900/30'
}`}
title={file.type === 'deleted' ? 'File already deleted' : 'Delete file'}
icon={<Trash2 className="w-4 h-4" />}
/>
>
<Trash2 className={`w-4 h-4 ${
file.type === 'deleted'
? 'text-gray-400 dark:text-gray-600'
: 'text-red-600 dark:text-red-400'
}`} />
</button>
)}
</div>
</div>

View File

@ -1,5 +1,5 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { FileText, Folder, Zap } from 'lucide-react';
import { FileText, Folder } from 'lucide-react';
interface FileItem {
path: string;
@ -48,7 +48,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
const [showSuggestions, setShowSuggestions] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(0);
const [cursorPosition, setCursorPosition] = useState(0);
const [activePattern, setActivePattern] = useState<{ start: number; pattern: string; type: 'file' | 'slash' } | null>(null);
const [activePattern, setActivePattern] = useState<{ start: number; pattern: string } | null>(null);
const [dropdownPosition, setDropdownPosition] = useState<{
left?: number;
right?: number;
@ -69,20 +69,13 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
return inputRef.current;
};
// Detect @ pattern (file paths) or / pattern (slash commands) in the text
// Detect @ pattern in the text
const detectPattern = useCallback((text: string, cursorPos: number) => {
// Find the last @ or / before the cursor
let lastPatternIndex = -1;
let patternType: 'file' | 'slash' | null = null;
// Find the last @ before the cursor
let lastAtIndex = -1;
for (let i = cursorPos - 1; i >= 0; i--) {
if (text[i] === '@') {
lastPatternIndex = i;
patternType = 'file';
break;
} else if (text[i] === '/') {
lastPatternIndex = i;
patternType = 'slash';
lastAtIndex = i;
break;
}
// Stop if we hit whitespace or newline
@ -91,12 +84,12 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
}
}
if (lastPatternIndex !== -1 && patternType) {
// Extract the pattern from @ or / to cursor
const pattern = text.substring(lastPatternIndex + 1, cursorPos);
// Check if there's no whitespace after the trigger
if (lastAtIndex !== -1) {
// Extract the pattern from @ to cursor
const pattern = text.substring(lastAtIndex + 1, cursorPos);
// Check if there's no whitespace after the @
if (!pattern.includes(' ') && !pattern.includes('\n')) {
return { start: lastPatternIndex, pattern, type: patternType };
return { start: lastAtIndex, pattern };
}
}
return null;
@ -180,40 +173,6 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
});
}, []);
// Get available slash commands for the current session
const getSlashCommands = useCallback((): FileItem[] => {
if (!sessionId) return [];
try {
const slashCommandsKey = `slashCommands_${sessionId}`;
const stored = localStorage.getItem(slashCommandsKey);
if (stored) {
const commands: string[] = JSON.parse(stored);
console.log('[slash-debug] Retrieved slash commands from localStorage:', commands);
return commands.map(cmd => ({
path: cmd,
isDirectory: false,
name: cmd
}));
}
} catch (e) {
console.warn('[slash-debug] Failed to retrieve slash commands:', e);
}
return [];
}, [sessionId]);
// Search for slash commands
const searchSlashCommands = useCallback((pattern: string) => {
const commands = getSlashCommands();
const filtered = commands.filter(cmd =>
cmd.path.toLowerCase().includes(pattern.toLowerCase())
);
console.log('[slash-debug] Filtered slash commands:', filtered);
setSuggestions(filtered);
setSelectedIndex(0);
}, [getSlashCommands]);
// Search for files
const searchFiles = useCallback(async (pattern: string) => {
if (!sessionId && !projectId) return;
@ -240,54 +199,33 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const newValue = e.target.value;
const cursorPos = e.target.selectionStart || 0;
onChange(newValue);
setCursorPosition(cursorPos);
// Only check for pattern if value contains "@" or "/" - performance optimization
if (newValue.includes('@') || newValue.includes('/')) {
setCursorPosition(cursorPos);
// Check for @ pattern
const pattern = detectPattern(newValue, cursorPos);
setActivePattern(pattern);
// Check for @ pattern (file paths) or / pattern (slash commands)
const pattern = detectPattern(newValue, cursorPos);
setActivePattern(pattern);
if (pattern) {
// Clear existing timeout
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
// Debounce the search
searchTimeoutRef.current = setTimeout(() => {
if (pattern.type === 'slash') {
console.log('[slash-debug] Searching slash commands with pattern:', pattern.pattern);
searchSlashCommands(pattern.pattern);
} else {
searchFiles(pattern.pattern);
}
setShowSuggestions(true);
}, 200);
} else {
setShowSuggestions(false);
setSuggestions([]);
if (pattern) {
// Clear existing timeout
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
// Debounce the search
searchTimeoutRef.current = setTimeout(() => {
searchFiles(pattern.pattern);
setShowSuggestions(true);
}, 200);
} else {
// No @ or / in text, clear autocomplete state
if (showSuggestions) {
setShowSuggestions(false);
setSuggestions([]);
setActivePattern(null);
}
setShowSuggestions(false);
setSuggestions([]);
}
};
// Handle selection change (cursor movement)
const handleSelectionChange = (e: React.SyntheticEvent<HTMLInputElement | HTMLTextAreaElement>) => {
// Only process cursor movement if autocomplete is active - performance optimization
if (!showSuggestions && !value.includes('@') && !value.includes('/')) {
return;
}
const target = e.target as HTMLInputElement | HTMLTextAreaElement;
const cursorPos = target.selectionStart || 0;
setCursorPosition(cursorPos);
@ -305,12 +243,11 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
const selectSuggestion = (suggestion: FileItem) => {
if (!activePattern) return;
// Replace the pattern with the selected path
// Replace the pattern with the selected file path
const before = value.substring(0, activePattern.start);
const after = value.substring(cursorPosition);
const prefix = activePattern.type === 'slash' ? '/' : '@';
const newValue = before + prefix + suggestion.path + after;
const newValue = before + '@' + suggestion.path + after;
onChange(newValue);
setShowSuggestions(false);
setSuggestions([]);
@ -330,10 +267,6 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
if (onSelect) {
onSelect(suggestion.path);
}
if (activePattern.type === 'slash') {
console.log('[slash-debug] Selected slash command:', suggestion.path);
}
};
// Handle keyboard navigation
@ -385,9 +318,9 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && event.target && event.target instanceof Node && !dropdownRef.current.contains(event.target)) {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
const element = getInputElement();
if (element && event.target && event.target instanceof Node && !element.contains(event.target)) {
if (element && !element.contains(event.target as Node)) {
setShowSuggestions(false);
}
}
@ -421,7 +354,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
};
return (
<div className="relative h-full w-full">
<div className="relative">
{isTextarea ? (
<textarea
ref={textareaRef || internalTextareaRef}
@ -439,7 +372,7 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
{showSuggestions && suggestions.length > 0 && (
<div
ref={dropdownRef}
className="absolute z-50 max-h-60 overflow-auto rounded-md bg-surface-secondary py-1 shadow-lg ring-1 ring-black ring-opacity-5 border border-border-primary"
className="absolute z-50 max-h-60 overflow-auto rounded-md bg-gray-800 py-1 shadow-lg ring-1 ring-black ring-opacity-5"
style={{
minWidth: Math.min(300, dropdownPosition?.maxWidth || 300) + 'px',
maxWidth: dropdownPosition?.maxWidth || '800px',
@ -452,34 +385,25 @@ const FilePathAutocomplete: React.FC<FilePathAutocompleteProps> = ({
})
}}
>
{suggestions.map((suggestion, index) => {
// Check if this is a slash command (activePattern will be set)
const isSlashCommand = activePattern?.type === 'slash';
return (
<div
key={suggestion.path}
className={`flex items-center px-4 py-2.5 cursor-pointer min-w-0 transition-colors ${
index === selectedIndex
? 'bg-interactive text-on-interactive'
: 'text-text-secondary hover:bg-surface-hover'
}`}
onClick={() => selectSuggestion(suggestion)}
onMouseEnter={() => setSelectedIndex(index)}
>
{isSlashCommand ? (
<Zap className="w-4 h-4 mr-3 flex-shrink-0 text-purple-500" />
) : suggestion.isDirectory ? (
<Folder className="w-4 h-4 mr-3 flex-shrink-0" />
) : (
<FileText className="w-4 h-4 mr-3 flex-shrink-0" />
)}
<span className="text-sm truncate pr-2" title={suggestion.path}>
{isSlashCommand ? '/' : ''}{suggestion.path}
</span>
</div>
);
})}
{suggestions.map((suggestion, index) => (
<div
key={suggestion.path}
className={`flex items-center px-4 py-2.5 cursor-pointer min-w-0 ${
index === selectedIndex
? 'bg-blue-600 text-white'
: 'text-gray-300 hover:bg-gray-700'
}`}
onClick={() => selectSuggestion(suggestion)}
onMouseEnter={() => setSelectedIndex(index)}
>
{suggestion.isDirectory ? (
<Folder className="w-4 h-4 mr-3 flex-shrink-0" />
) : (
<FileText className="w-4 h-4 mr-3 flex-shrink-0" />
)}
<span className="text-sm truncate pr-2" title={suggestion.path}>{suggestion.path}</span>
</div>
))}
</div>
)}
</div>

View File

@ -1,353 +0,0 @@
import React from 'react';
import { Check, Edit, CircleArrowDown, AlertTriangle, HelpCircle, GitMerge, Loader2 } from 'lucide-react';
import type { GitStatus } from '../types/session';
interface GitStatusIndicatorProps {
gitStatus?: GitStatus;
size?: 'small' | 'medium' | 'large';
sessionId?: string;
onClick?: () => void;
isLoading?: boolean;
}
interface GitStatusConfig {
color: string;
bgColor: string;
icon: React.ReactNode;
label: string;
description: string;
}
/**
* Checks if the git status indicates the branch is fully synced with main
*/
function isGitStatusFullySynced(gitStatus: GitStatus): boolean {
return (!gitStatus.ahead || gitStatus.ahead === 0) &&
(!gitStatus.behind || gitStatus.behind === 0) &&
(!gitStatus.hasUncommittedChanges) &&
(!gitStatus.hasUntrackedFiles);
}
/**
* Builds the comprehensive tooltip content for the git status indicator
*/
function buildTooltipContent(gitStatus: GitStatus, config: GitStatusConfig): string {
let tooltipContent = '';
// Show total commits in branch if available
if (gitStatus.totalCommits && gitStatus.totalCommits > 0) {
tooltipContent = `${gitStatus.totalCommits} commit${gitStatus.totalCommits !== 1 ? 's' : ''} in branch`;
// Add ahead/behind info if relevant
if (gitStatus.ahead && gitStatus.ahead > 0) {
tooltipContent += ` (${gitStatus.ahead} ahead of main)`;
} else if (gitStatus.behind && gitStatus.behind > 0) {
tooltipContent += ` (${gitStatus.behind} behind main)`;
} else if (gitStatus.state === 'diverged') {
tooltipContent += ` (${gitStatus.ahead || 0} ahead, ${gitStatus.behind || 0} behind)`;
}
// Add file change statistics for commits
if (gitStatus.commitFilesChanged) {
tooltipContent += `\n${gitStatus.commitFilesChanged} files changed (+${gitStatus.commitAdditions || 0}/-${gitStatus.commitDeletions || 0})`;
}
} else if (gitStatus.ahead && gitStatus.ahead > 0) {
// Fallback to old behavior if totalCommits not available
tooltipContent = `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} ahead of main`;
if (gitStatus.commitFilesChanged) {
tooltipContent += `\n${gitStatus.commitFilesChanged} files changed (+${gitStatus.commitAdditions || 0}/-${gitStatus.commitDeletions || 0})`;
}
} else if (gitStatus.behind && gitStatus.behind > 0) {
tooltipContent = `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind main`;
} else if (gitStatus.state === 'diverged') {
tooltipContent = `${gitStatus.ahead || 0} ahead, ${gitStatus.behind || 0} behind main`;
}
// Add uncommitted changes info
if (gitStatus.hasUncommittedChanges && gitStatus.filesChanged) {
if (tooltipContent) tooltipContent += '\n\n';
tooltipContent += `Uncommitted changes:\n${gitStatus.filesChanged} file${gitStatus.filesChanged !== 1 ? 's' : ''} modified`;
if (gitStatus.additions || gitStatus.deletions) {
tooltipContent += ` (+${gitStatus.additions || 0}/-${gitStatus.deletions || 0})`;
}
}
// If still no content (e.g., clean state with no commits ahead), be more descriptive
if (!tooltipContent) {
if (gitStatus.state === 'clean') {
tooltipContent = 'Branch is up to date with main\nNo uncommitted changes';
} else if (gitStatus.state === 'modified' && gitStatus.filesChanged) {
tooltipContent = `${gitStatus.filesChanged} uncommitted file${gitStatus.filesChanged !== 1 ? 's' : ''}`;
if (gitStatus.additions || gitStatus.deletions) {
tooltipContent += ` (+${gitStatus.additions || 0}/-${gitStatus.deletions || 0})`;
}
} else {
tooltipContent = config.description;
}
}
// Add untracked files note
if (gitStatus.hasUntrackedFiles) {
tooltipContent += '\n+ untracked files';
}
// Add actionable information based on new simplified scheme
let actionableInfo = '';
// Check sync status
const isFullySynced = isGitStatusFullySynced(gitStatus);
const hasCommitsToMerge = gitStatus.ahead && gitStatus.ahead > 0 && !gitStatus.hasUncommittedChanges && !gitStatus.hasUntrackedFiles && (!gitStatus.behind || gitStatus.behind === 0);
const hasConflictRisk = gitStatus.ahead && gitStatus.ahead > 0 && gitStatus.behind && gitStatus.behind > 0;
const isMostlyBehind = hasConflictRisk && gitStatus.behind && gitStatus.ahead && gitStatus.behind >= 5 * gitStatus.ahead && gitStatus.ahead <= 2;
if (hasCommitsToMerge || gitStatus.isReadyToMerge) {
actionableInfo = '🔀 Ready to merge - no conflicts expected';
} else if (isMostlyBehind) {
actionableInfo = '📊 Mostly behind main - minimal unique changes, consider rebasing or removing';
} else if (hasConflictRisk) {
actionableInfo = '⚠️ Rebase from main before merging to avoid conflicts';
} else if (gitStatus.state === 'conflict') {
actionableInfo = '🚫 Resolve merge conflicts before continuing';
} else if (gitStatus.hasUncommittedChanges || gitStatus.hasUntrackedFiles) {
actionableInfo = '📝 Commit changes before merging';
} else if (gitStatus.behind && gitStatus.behind > 0 && (!gitStatus.ahead || gitStatus.ahead === 0)) {
actionableInfo = '⬇️ Consider updating or removing - no unique changes';
} else if (isFullySynced) {
actionableInfo = '✅ Safe to remove - no unique changes';
}
if (actionableInfo) {
tooltipContent += '\n\n' + actionableInfo;
}
// Add click hint
tooltipContent += '\n\nClick to view diff details';
return tooltipContent;
}
function getGitStatusConfig(gitStatus: GitStatus): GitStatusConfig {
const iconProps = { size: 14, strokeWidth: 2 };
// HIGH PRIORITY: Branches with changes that matter
// 1. Ready to Merge (HIGH PRIORITY) - Has commits to merge, clean working directory, not behind
if (gitStatus.isReadyToMerge ||
(gitStatus.ahead && gitStatus.ahead > 0 && !gitStatus.hasUncommittedChanges && !gitStatus.hasUntrackedFiles && (!gitStatus.behind || gitStatus.behind === 0))) {
const commitCount = gitStatus.totalCommits || gitStatus.ahead || 0;
return {
color: 'text-green-600 dark:text-green-400',
bgColor: 'bg-green-100 dark:bg-green-900/30',
icon: <GitMerge {...iconProps} />,
label: 'Ready to Merge',
description: `${commitCount} commit${commitCount !== 1 ? 's' : ''} ready to merge`
};
}
// 2. Conflict Risk (HIGH PRIORITY) - Has commits but also behind main
// Special case: If significantly behind with minimal ahead, treat as "Mostly Behind" instead of conflict risk
if (gitStatus.ahead && gitStatus.ahead > 0 && gitStatus.behind && gitStatus.behind > 0) {
// If the branch is significantly more behind than ahead (5:1 ratio), and has few commits ahead (<=2),
// treat it more like a "behind" branch than a conflict risk
const mostlyBehind = gitStatus.behind >= 5 * gitStatus.ahead && gitStatus.ahead <= 2;
if (mostlyBehind) {
// Show as "Mostly Behind" with gray color like other low-priority statuses
return {
color: 'text-gray-500 dark:text-gray-400',
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
icon: <CircleArrowDown {...iconProps} />,
label: 'Mostly Behind',
description: `${gitStatus.behind} behind, ${gitStatus.ahead} ahead - consider rebasing`
};
}
// Normal conflict risk for branches with significant divergence
return {
color: 'text-amber-600 dark:text-amber-400',
bgColor: 'bg-amber-100 dark:bg-amber-900/30',
icon: <AlertTriangle {...iconProps} />,
label: 'Conflict Risk',
description: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind - potential conflicts`
};
}
// SPECIAL CASES: Keep these distinct
// Active merge conflicts
if (gitStatus.state === 'conflict') {
return {
color: 'text-red-600 dark:text-red-400',
bgColor: 'bg-red-100 dark:bg-red-900/30',
icon: <AlertTriangle {...iconProps} />,
label: 'Conflicts',
description: 'Has merge conflicts - resolve before continuing'
};
}
// Uncommitted changes (includes both modified and untracked)
if (gitStatus.hasUncommittedChanges || gitStatus.hasUntrackedFiles || gitStatus.state === 'modified' || gitStatus.state === 'untracked') {
const ahead = gitStatus.ahead || 0;
const filesChanged = gitStatus.filesChanged || 0;
const hasFiles = filesChanged > 0 || gitStatus.hasUntrackedFiles;
let description = '';
if (ahead > 0 && hasFiles) {
description = `${ahead} commit${ahead !== 1 ? 's' : ''} + uncommitted changes`;
} else if (hasFiles) {
description = gitStatus.hasUntrackedFiles ? 'Untracked files' : `${filesChanged} uncommitted file${filesChanged !== 1 ? 's' : ''}`;
} else {
description = 'Uncommitted changes';
}
return {
color: 'text-blue-600 dark:text-blue-400',
bgColor: 'bg-blue-100 dark:bg-blue-900/30',
icon: <Edit {...iconProps} />,
label: 'Uncommitted',
description: description
};
}
// LOW PRIORITY: Branches you care little about
// Behind only (no commits ahead)
if (gitStatus.behind && gitStatus.behind > 0 && (!gitStatus.ahead || gitStatus.ahead === 0)) {
return {
color: 'text-gray-500 dark:text-gray-400',
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
icon: <CircleArrowDown {...iconProps} />,
label: 'Behind Only',
description: `${gitStatus.behind} commit${gitStatus.behind !== 1 ? 's' : ''} behind main`
};
}
// Up to date (fully synced)
const isFullySynced = isGitStatusFullySynced(gitStatus);
if (isFullySynced) {
return {
color: 'text-gray-500 dark:text-gray-400',
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
icon: <Check {...iconProps} />,
label: 'Up to Date',
description: 'No changes - safe to remove'
};
}
// Fallback for unknown states
return {
color: 'text-gray-500 dark:text-gray-400',
bgColor: 'bg-gray-100 dark:bg-gray-800/30',
icon: <HelpCircle {...iconProps} />,
label: 'Unknown',
description: 'Unable to determine git status'
};
}
const GitStatusIndicator: React.FC<GitStatusIndicatorProps> = React.memo(({ gitStatus, size = 'small', sessionId, onClick, isLoading }) => {
// Size configurations
const sizeConfig = {
small: {
dot: 'w-2 h-2',
text: 'text-xs',
padding: 'px-1.5 py-0.5',
gap: 'gap-0.5',
loader: 'w-3 h-3'
},
medium: {
dot: 'w-3 h-3',
text: 'text-sm',
padding: 'px-2 py-1',
gap: 'gap-1',
loader: 'w-4 h-4'
},
large: {
dot: 'w-4 h-4',
text: 'text-base',
padding: 'px-3 py-1.5',
gap: 'gap-1.5',
loader: 'w-5 h-5'
}
}[size];
// Show loading state
if (isLoading === true) {
return (
<span
className={`inline-flex items-center justify-center w-[5.5ch] ${sizeConfig.padding} ${sizeConfig.text} rounded-md border bg-gray-100 dark:bg-gray-900/30 text-gray-500 dark:text-gray-400 border-gray-300 dark:border-gray-600`}
title="Checking git status..."
data-testid={sessionId ? `session-${sessionId}-git-status` : 'git-status'}
data-git-loading="true"
>
<Loader2 className={`${sizeConfig.loader} animate-spin`} />
</span>
);
}
// No git status and not loading
if (!gitStatus) {
return null;
}
const config = getGitStatusConfig(gitStatus);
// Build comprehensive tooltip content using helper function
const tooltipContent = buildTooltipContent(gitStatus, config);
const handleClick = (e: React.MouseEvent) => {
e.stopPropagation();
if (onClick) {
onClick();
} else if (sessionId) {
// Dispatch event to select session and switch to View Diff tab
const selectEvent = new CustomEvent('select-session-and-view-diff', {
detail: { sessionId }
});
window.dispatchEvent(selectEvent);
}
};
// Determine the primary count to display
let primaryCount = 0;
let ariaLabel = config.label;
if (gitStatus.totalCommits && gitStatus.totalCommits > 0) {
primaryCount = gitStatus.totalCommits;
ariaLabel = `${primaryCount} commit${primaryCount !== 1 ? 's' : ''} in branch`;
} else if (gitStatus.filesChanged && gitStatus.filesChanged > 0) {
primaryCount = gitStatus.filesChanged;
ariaLabel = `${primaryCount} file${primaryCount !== 1 ? 's' : ''} changed`;
} else if (gitStatus.ahead && gitStatus.ahead > 0) {
primaryCount = gitStatus.ahead;
ariaLabel = `Ahead by ${primaryCount} commit${primaryCount !== 1 ? 's' : ''}`;
} else if (gitStatus.behind && gitStatus.behind > 0) {
primaryCount = gitStatus.behind;
ariaLabel = `Behind by ${primaryCount} commit${primaryCount !== 1 ? 's' : ''}`;
}
return (
<span
className={`inline-flex items-center ${primaryCount > 0 ? 'justify-center gap-0.5' : 'justify-center'} w-[5.5ch] ${sizeConfig.padding} ${sizeConfig.text} rounded-md border ${config.bgColor} ${config.color} border-gray-300 dark:border-gray-600 ${(onClick || sessionId) ? 'cursor-pointer hover:opacity-80 transition-opacity' : ''}`}
title={tooltipContent}
onClick={handleClick}
aria-label={ariaLabel}
data-testid={sessionId ? `session-${sessionId}-git-status` : 'git-status'}
data-git-state={gitStatus.state}
data-git-ahead={gitStatus.ahead}
data-git-behind={gitStatus.behind}
>
<span className="flex-shrink-0">
{config.icon}
</span>
{primaryCount > 0 && (
<span className="font-bold">
{primaryCount > 9 ? '★' : primaryCount}
</span>
)}
</span>
);
});
GitStatusIndicator.displayName = 'GitStatusIndicator';
export { GitStatusIndicator };

View File

@ -1,5 +1,4 @@
import { GitBranch, Terminal, Folder, Zap, MessageSquare, Settings, Bell, History } from 'lucide-react';
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
import { X, GitBranch, Terminal, Folder, Zap, MessageSquare, Settings, Bell, History } from 'lucide-react';
interface HelpProps {
isOpen: boolean;
@ -7,24 +6,36 @@ interface HelpProps {
}
export default function Help({ isOpen, onClose }: HelpProps) {
if (!isOpen) return null;
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl" showCloseButton={false}>
<ModalHeader>Crystal Help</ModalHeader>
<ModalBody>
<div className="space-y-8">
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4 overflow-y-auto">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-2xl font-bold text-gray-900 dark:text-white">Crystal Help</h2>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-500 dark:hover:text-gray-300"
>
<X className="h-6 w-6" />
</button>
</div>
<div className="flex-1 overflow-y-auto p-6">
<div className="space-y-8">
{/* Quick Start */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<Zap className="h-5 w-5 mr-2" />
Quick Start
</h3>
<div className="space-y-3 text-text-secondary">
<div className="bg-interactive/10 border border-interactive/30 rounded-lg p-3">
<p className="font-medium text-interactive mb-2">Prerequisites</p>
<div className="space-y-3 text-gray-700 dark:text-gray-300">
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-3">
<p className="font-medium text-blue-900 dark:text-blue-200 mb-2">Prerequisites</p>
<ul className="list-disc list-inside space-y-1 text-sm">
<li>Claude Code must be installed with credentials configured</li>
<li>We recommend using a MAX plan for best performance</li>
<li>Crystal runs Claude Code with <code className="bg-surface-tertiary px-1 rounded">--dangerously-ignore-permissions</code></li>
<li>Crystal runs Claude Code with <code className="bg-gray-200 dark:bg-gray-700 px-1 rounded">--dangerously-ignore-permissions</code></li>
</ul>
</div>
@ -46,7 +57,7 @@ export default function Help({ isOpen, onClose }: HelpProps) {
</li>
<li><strong>Work with results:</strong>
<ul className="list-disc list-inside ml-4 mt-1 text-sm">
<li>View changes in the Diff panel</li>
<li>View changes in the View Diff tab</li>
<li>Continue conversations to refine the solution</li>
<li>Rebase back to your main branch when done</li>
</ul>
@ -58,14 +69,14 @@ export default function Help({ isOpen, onClose }: HelpProps) {
{/* Session Management */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<Terminal className="h-5 w-5 mr-2" />
Session Management
</h3>
<div className="space-y-3">
<div>
<h4 className="font-medium text-text-primary">Creating Sessions</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<h4 className="font-medium text-gray-800 dark:text-gray-200">Creating Sessions</h4>
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li>Enter a prompt describing what you want Claude to do</li>
<li>Optionally specify a worktree name template</li>
<li>Create multiple sessions at once with the count field</li>
@ -73,20 +84,20 @@ export default function Help({ isOpen, onClose }: HelpProps) {
</ul>
</div>
<div>
<h4 className="font-medium text-text-primary">Session States</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<li><span className="text-status-warning">Initializing</span> - Setting up git worktree</li>
<li><span className="text-interactive">Running</span> - Claude is processing</li>
<li><span className="text-status-success">Waiting</span> - Waiting for your input</li>
<li><span className="text-text-tertiary">Stopped</span> - Session completed or stopped</li>
<li><span className="text-status-error">Error</span> - Something went wrong</li>
<h4 className="font-medium text-gray-800 dark:text-gray-200">Session States</h4>
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li><span className="text-yellow-600 dark:text-yellow-500">Initializing</span> - Setting up git worktree</li>
<li><span className="text-blue-600 dark:text-blue-500">Running</span> - Claude is processing</li>
<li><span className="text-green-600 dark:text-green-500">Waiting</span> - Waiting for your input</li>
<li><span className="text-gray-600 dark:text-gray-400">Stopped</span> - Session completed or stopped</li>
<li><span className="text-red-600 dark:text-red-500">Error</span> - Something went wrong</li>
</ul>
</div>
<div>
<h4 className="font-medium text-text-primary">Continuing Conversations</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<h4 className="font-medium text-gray-800 dark:text-gray-200">Continuing Conversations</h4>
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li>Click on a stopped session to resume it</li>
<li>Use <kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Enter</kbd> to send input</li>
<li>Use <kbd className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">Cmd/Ctrl + Enter</kbd> to send input</li>
<li>Full conversation history is preserved</li>
</ul>
</div>
@ -95,17 +106,17 @@ export default function Help({ isOpen, onClose }: HelpProps) {
{/* Git Integration */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<GitBranch className="h-5 w-5 mr-2" />
Git Worktree Integration
</h3>
<div className="space-y-3">
<p className="text-text-secondary">
<p className="text-gray-700 dark:text-gray-300">
Each session operates in its own git worktree, allowing parallel development without conflicts.
</p>
<div>
<h4 className="font-medium text-text-primary">Git Operations</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<h4 className="font-medium text-gray-800 dark:text-gray-200">Git Operations</h4>
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li><strong>Rebase from main</strong> - Pull latest changes from main branch</li>
<li><strong>Squash and rebase to main</strong> - Combine commits and rebase onto main</li>
<li>View diffs in the View Diff tab</li>
@ -117,40 +128,40 @@ export default function Help({ isOpen, onClose }: HelpProps) {
{/* View Tabs */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<MessageSquare className="h-5 w-5 mr-2" />
View Tabs
</h3>
<div className="space-y-2">
<div>
<h4 className="font-medium text-text-primary">Output</h4>
<p className="text-text-secondary">Formatted terminal output with syntax highlighting</p>
<h4 className="font-medium text-gray-800 dark:text-gray-200">Output</h4>
<p className="text-gray-700 dark:text-gray-300">Formatted terminal output with syntax highlighting</p>
</div>
<div>
<h4 className="font-medium text-text-primary">Messages</h4>
<p className="text-text-secondary">Raw JSON messages for debugging</p>
<h4 className="font-medium text-gray-800 dark:text-gray-200">Messages</h4>
<p className="text-gray-700 dark:text-gray-300">Raw JSON messages for debugging</p>
</div>
<div>
<h4 className="font-medium text-text-primary">View Diff</h4>
<p className="text-text-secondary">Git diffs showing all file changes</p>
<h4 className="font-medium text-gray-800 dark:text-gray-200">View Diff</h4>
<p className="text-gray-700 dark:text-gray-300">Git diffs showing all file changes</p>
</div>
<div>
<h4 className="font-medium text-text-primary">Terminal</h4>
<p className="text-text-secondary">Run project scripts (tests, builds, etc.)</p>
<h4 className="font-medium text-gray-800 dark:text-gray-200">Terminal</h4>
<p className="text-gray-700 dark:text-gray-300">Run project scripts (tests, builds, etc.)</p>
</div>
</div>
</section>
{/* Project Management */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<Folder className="h-5 w-5 mr-2" />
Project Management
</h3>
<div className="space-y-3">
<div>
<h4 className="font-medium text-text-primary">Project Settings</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<h4 className="font-medium text-gray-800 dark:text-gray-200">Project Settings</h4>
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li>Custom system prompts per project</li>
<li>Run scripts for testing/building</li>
<li>Main branch configuration</li>
@ -162,11 +173,11 @@ export default function Help({ isOpen, onClose }: HelpProps) {
{/* Prompts Tab */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<History className="h-5 w-5 mr-2" />
Prompts History
</h3>
<div className="space-y-2 text-text-secondary">
<div className="space-y-2 text-gray-700 dark:text-gray-300">
<p>Access all prompts from the Prompts tab in the sidebar:</p>
<ul className="list-disc list-inside mt-1 space-y-1">
<li>Search through all prompts and session names</li>
@ -179,14 +190,14 @@ export default function Help({ isOpen, onClose }: HelpProps) {
{/* Settings */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3 flex items-center">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<Settings className="h-5 w-5 mr-2" />
Settings
</h3>
<div className="space-y-3">
<div>
<h4 className="font-medium text-text-primary">Global Settings</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<h4 className="font-medium text-gray-800 dark:text-gray-200">Global Settings</h4>
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li>Verbose logging for debugging</li>
<li>Anthropic API key for AI features</li>
<li>Global system prompt additions</li>
@ -194,11 +205,11 @@ export default function Help({ isOpen, onClose }: HelpProps) {
</ul>
</div>
<div>
<h4 className="font-medium text-text-primary flex items-center">
<h4 className="font-medium text-gray-800 dark:text-gray-200 flex items-center">
<Bell className="h-4 w-4 mr-1" />
Notifications
</h4>
<ul className="list-disc list-inside text-text-secondary mt-1 space-y-1">
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 mt-1 space-y-1">
<li>Desktop notifications for status changes</li>
<li>Sound alerts when sessions need input</li>
<li>Customizable notification triggers</li>
@ -209,39 +220,27 @@ export default function Help({ isOpen, onClose }: HelpProps) {
{/* Keyboard Shortcuts */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">
Keyboard Shortcuts
</h3>
<div className="space-y-2">
<div className="flex justify-between items-center">
<span className="text-text-secondary">Send Input / Continue Conversation</span>
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Enter</kbd>
<span className="text-gray-700 dark:text-gray-300">Send Input / Continue Conversation</span>
<kbd className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">Cmd/Ctrl + Enter</kbd>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Quick Create Session (untitled)</span>
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Shift + N</kbd>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Open Prompt History</span>
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + P</kbd>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Navigate Back in Session History</span>
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Option/Alt + ←</kbd>
</div>
<div className="flex justify-between items-center">
<span className="text-text-secondary">Navigate Forward in Session History</span>
<kbd className="px-2 py-1 bg-surface-tertiary rounded text-sm">Cmd/Ctrl + Option/Alt + →</kbd>
<span className="text-gray-700 dark:text-gray-300">Open Prompt History</span>
<kbd className="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded text-sm">Cmd/Ctrl + P</kbd>
</div>
</div>
</section>
{/* Tips */}
<section>
<h3 className="text-lg font-semibold text-text-primary mb-3">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-3">
Tips & Tricks
</h3>
<ul className="list-disc list-inside text-text-secondary space-y-2">
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 space-y-2">
<li>Run multiple sessions with different approaches to compare results</li>
<li>Use descriptive worktree names to organize your experiments</li>
<li>Check the View Diff tab to review what Claude modified</li>
@ -252,11 +251,12 @@ export default function Help({ isOpen, onClose }: HelpProps) {
</ul>
</section>
</div>
</ModalBody>
<div className="p-4 border-t border-border-primary text-center text-sm text-text-muted">
Crystal - Manage multiple Claude Code instances with git worktrees
</div>
<div className="p-4 border-t border-gray-200 dark:border-gray-700 text-center text-sm text-gray-600 dark:text-gray-400">
Crystal - Manage multiple Claude Code instances with git worktrees
</div>
</div>
</Modal>
</div>
);
}

View File

@ -0,0 +1,143 @@
import { useState } from 'react';
interface JsonMessage {
type: string;
subtype?: string;
content?: string;
data?: any;
timestamp: string;
[key: string]: any;
}
interface JsonMessageItemProps {
message: JsonMessage;
index: number;
}
function JsonMessageItem({ message }: JsonMessageItemProps) {
const [isCollapsed, setIsCollapsed] = useState(true);
const getMessageTypeColor = (type: string, subtype?: string) => {
if (type === 'system') {
return subtype === 'init' ? 'bg-blue-900/20 border-blue-700' : 'bg-gray-800 border-gray-700';
}
if (type === 'user') return 'bg-green-900/20 border-green-700';
if (type === 'assistant') return 'bg-purple-900/20 border-purple-700';
return 'bg-gray-800 border-gray-700';
};
const getMessageTypeIcon = (type: string, subtype?: string) => {
if (type === 'system') {
return subtype === 'init' ? '🚀' : '⚙️';
}
if (type === 'user') return '👤';
if (type === 'assistant') return '🤖';
return '📄';
};
const formatTimestamp = (timestamp: string) => {
return new Date(timestamp).toLocaleTimeString();
};
const getMessageTitle = (message: JsonMessage) => {
if (message.type === 'system' && message.subtype === 'init') {
return 'Session Started';
}
if (message.type === 'system' && message.subtype === 'result') {
return `Result (${message.cost_usd ? `$${message.cost_usd}` : 'No cost'})`;
}
if (message.type === 'user') {
return 'User Input';
}
if (message.type === 'assistant') {
return 'Assistant Response';
}
return `${message.type} ${message.subtype || ''}`.trim();
};
const getMessagePreview = (message: JsonMessage) => {
if (message.content) {
return message.content.length > 100
? message.content.substring(0, 100) + '...'
: message.content;
}
if (message.type === 'system' && message.subtype === 'result') {
return `Duration: ${message.duration_ms}ms, Turns: ${message.num_turns}`;
}
return '';
};
return (
<div className={`border rounded-lg mb-2 ${getMessageTypeColor(message.type, message.subtype)}`}>
<div
className="p-3 cursor-pointer flex items-center justify-between hover:bg-opacity-80"
onClick={() => setIsCollapsed(!isCollapsed)}
>
<div className="flex items-center space-x-3">
<span className="text-lg">{getMessageTypeIcon(message.type, message.subtype)}</span>
<div>
<h4 className="font-medium text-gray-200">{getMessageTitle(message)}</h4>
{isCollapsed && (
<p className="text-sm text-gray-400 mt-1">{getMessagePreview(message)}</p>
)}
</div>
</div>
<div className="flex items-center space-x-2">
<span className="text-xs text-gray-400">{formatTimestamp(message.timestamp)}</span>
<span className={`transform transition-transform ${isCollapsed ? 'rotate-0' : 'rotate-180'}`}>
▼
</span>
</div>
</div>
{!isCollapsed && (
<div className="border-t bg-gray-900/50 p-4">
{message.content && (
<div className="mb-4">
<h5 className="font-medium text-gray-300 mb-2">Content:</h5>
<div className="bg-gray-800 rounded p-3 text-sm font-mono whitespace-pre-wrap border border-gray-700 text-gray-200">
{message.content}
</div>
</div>
)}
<details>
<summary className="cursor-pointer font-medium text-gray-300 mb-2">Raw JSON Data</summary>
<pre className="bg-gray-800 rounded p-3 text-xs overflow-auto max-h-64 border border-gray-700 text-gray-200">
{JSON.stringify(message, null, 2)}
</pre>
</details>
</div>
)}
</div>
);
}
interface JsonMessageViewProps {
messages: JsonMessage[];
}
export function JsonMessageView({ messages }: JsonMessageViewProps) {
if (messages.length === 0) {
return (
<div className="flex items-center justify-center h-32 text-gray-400">
No messages yet
</div>
);
}
return (
<div className="h-full flex flex-col bg-gray-900 overflow-hidden">
<div className="flex-1 overflow-auto p-4">
<div className="max-w-4xl mx-auto">
<h3 className="text-lg font-semibold text-gray-200 mb-4">
Claude Code Messages ({messages.length})
</h3>
{messages.map((message, index) => (
<JsonMessageItem key={index} message={message} index={index} />
))}
</div>
</div>
</div>
);
}

View File

@ -1,5 +1,4 @@
import { Loader2 } from 'lucide-react';
import { cn } from '../utils/cn';
interface LoadingSpinnerProps {
text?: string;
@ -7,7 +6,7 @@ interface LoadingSpinnerProps {
className?: string;
}
export function LoadingSpinner({ text = 'Loading...', size = 'medium', className }: LoadingSpinnerProps) {
export function LoadingSpinner({ text = 'Loading...', size = 'medium', className = '' }: LoadingSpinnerProps) {
const sizeClasses = {
small: 'w-4 h-4',
medium: 'w-6 h-6',
@ -21,9 +20,9 @@ export function LoadingSpinner({ text = 'Loading...', size = 'medium', className
};
return (
<div className={cn('flex items-center justify-center gap-3', className)}>
<Loader2 className={cn(sizeClasses[size], 'animate-spin text-interactive')} />
<span className={cn('text-text-tertiary', textSizeClasses[size])}>{text}</span>
<div className={`flex items-center justify-center gap-3 ${className}`}>
<Loader2 className={`${sizeClasses[size]} animate-spin text-blue-500`} />
<span className={`text-gray-600 dark:text-gray-400 ${textSizeClasses[size]}`}>{text}</span>
</div>
);
}

View File

@ -1,6 +1,4 @@
import { Plus } from 'lucide-react';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
interface MainBranchWarningDialogProps {
isOpen: boolean;
@ -19,6 +17,8 @@ export function MainBranchWarningDialog({
projectId,
mainBranch
}: MainBranchWarningDialogProps) {
if (!isOpen) return null;
const handleDontShowAgain = () => {
const warningKey = `mainBranchWarning_${projectId}`;
localStorage.setItem(warningKey, 'true');
@ -26,70 +26,78 @@ export function MainBranchWarningDialog({
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="lg" showCloseButton={false}>
<ModalHeader title={`Working in the ${mainBranch} branch`} onClose={onClose} />
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-lg relative shadow-xl border border-gray-200 dark:border-gray-700">
<button
onClick={onClose}
className="absolute top-4 right-4 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
title="Close"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<ModalBody className="space-y-4">
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100 mb-4">
Working in the {mainBranch} branch
</h2>
<div className="space-y-4">
<div className="flex items-start gap-3">
<span className="text-interactive text-2xl mt-1">💡</span>
<span className="text-blue-600 dark:text-blue-400 text-2xl mt-1">💡</span>
<div className="flex-1">
<p className="text-text-secondary mb-3">
You're about to create a session in the <span className="font-mono bg-surface-secondary px-1 rounded">{mainBranch}</span> branch
<p className="text-gray-700 dark:text-gray-300 mb-3">
You're about to create a session in the <span className="font-mono bg-gray-100 dark:bg-gray-700 px-1 rounded">{mainBranch}</span> branch
of <span className="font-medium">{projectName}</span>.
</p>
<p className="text-text-secondary mb-3">
<p className="text-gray-700 dark:text-gray-300 mb-3">
For better workflow management, it's recommended to create worktrees instead. This allows you to:
</p>
<ul className="list-disc list-inside text-text-secondary space-y-1 mb-4">
<ul className="list-disc list-inside text-gray-700 dark:text-gray-300 space-y-1 mb-4">
<li>Run multiple sessions in parallel without conflicts</li>
<li>Keep your main branch clean</li>
<li>Easily manage and compare different approaches</li>
<li>Avoid creating more commits than intended in your main branch</li>
</ul>
<div className="bg-status-warning/10 border border-status-warning/30 rounded-md p-3 mb-3">
<p className="text-sm text-status-warning">
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-md p-3 mb-3">
<p className="text-sm text-amber-800 dark:text-amber-300">
<span className="font-medium">⚠️ Note:</span> Working directly in the {mainBranch} branch may result in
multiple intermediate commits as Claude makes changes. Using worktrees allows you to squash
these into a single clean commit before merging.
</p>
</div>
<div className="bg-interactive/10 border border-interactive/30 rounded-md p-3">
<p className="text-sm text-interactive">
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-md p-3">
<p className="text-sm text-blue-800 dark:text-blue-300">
<span className="font-medium">Tip:</span> Click the <Plus className="w-4 h-4 inline mx-1" /> button
next to the project name to create a new worktree session.
</p>
</div>
</div>
</div>
</ModalBody>
<ModalFooter>
<div className="w-full space-y-2">
<div className="flex gap-3">
<Button
onClick={onContinue}
variant="secondary"
fullWidth
>
Continue to {mainBranch} branch
</Button>
<Button
onClick={handleDontShowAgain}
variant="primary"
fullWidth
>
Continue and don't ask again
</Button>
</div>
<Button
onClick={onClose}
variant="ghost"
fullWidth
>
Cancel
</Button>
</div>
</ModalFooter>
</Modal>
<div className="flex gap-3 mt-6">
<button
onClick={onContinue}
className="flex-1 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 font-medium py-2 px-4 rounded-md transition-colors"
>
Continue to {mainBranch} branch
</button>
<button
onClick={handleDontShowAgain}
className="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded-md transition-colors"
>
Continue and don't ask again
</button>
</div>
<button
onClick={onClose}
className="w-full mt-2 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 text-sm py-2"
>
Cancel
</button>
</div>
</div>
);
}

View File

@ -1,14 +1,9 @@
import React, { useEffect, useState } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { useTheme } from '../contexts/ThemeContext';
import { MermaidRenderer } from './MermaidRenderer';
interface CodeComponentProps extends React.HTMLAttributes<HTMLElement> {
node?: unknown;
className?: string;
children?: React.ReactNode;
}
interface MarkdownPreviewProps {
content: string;
className?: string;
@ -16,6 +11,8 @@ interface MarkdownPreviewProps {
}
export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, className = '' }) => {
const { theme } = useTheme();
const isDarkMode = theme === 'dark';
const [mermaidKey, setMermaidKey] = useState(0);
// Force re-render of mermaid diagrams when content changes
@ -24,11 +21,11 @@ export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, class
}, [content]);
return (
<div className={`markdown-preview ${className}`}>
<div className={`markdown-preview ${isDarkMode ? 'markdown-dark' : 'markdown-light'} ${className}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
code({ node, className, children, ...props }: CodeComponentProps) {
code({ node, className, children, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
const language = match ? match[1] : '';
const codeString = String(children).replace(/\n$/, '');
@ -53,42 +50,42 @@ export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, class
);
},
// Style other markdown elements
h1: ({ children }) => <h1 className="text-3xl font-bold mt-6 mb-4 text-text-primary">{children}</h1>,
h2: ({ children }) => <h2 className="text-2xl font-bold mt-5 mb-3 text-text-primary">{children}</h2>,
h3: ({ children }) => <h3 className="text-xl font-bold mt-4 mb-2 text-text-primary">{children}</h3>,
h4: ({ children }) => <h4 className="text-lg font-bold mt-3 mb-2 text-text-primary">{children}</h4>,
p: ({ children }) => <p className="mb-4 text-text-primary">{children}</p>,
ul: ({ children }) => <ul className="list-disc mb-4 ml-6 text-text-primary">{children}</ul>,
ol: ({ children }) => <ol className="list-decimal mb-4 ml-6 text-text-primary">{children}</ol>,
li: ({ children }) => <li className="mb-2 text-text-primary">{children}</li>,
h1: ({ children }) => <h1 className="text-3xl font-bold mt-6 mb-4">{children}</h1>,
h2: ({ children }) => <h2 className="text-2xl font-bold mt-5 mb-3">{children}</h2>,
h3: ({ children }) => <h3 className="text-xl font-bold mt-4 mb-2">{children}</h3>,
h4: ({ children }) => <h4 className="text-lg font-bold mt-3 mb-2">{children}</h4>,
p: ({ children }) => <p className="mb-4">{children}</p>,
ul: ({ children }) => <ul className="list-disc list-inside mb-4 ml-4">{children}</ul>,
ol: ({ children }) => <ol className="list-decimal list-inside mb-4 ml-4">{children}</ol>,
li: ({ children }) => <li className="mb-1">{children}</li>,
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-border-secondary pl-4 italic my-4 text-text-tertiary">
<blockquote className="border-l-4 border-gray-300 dark:border-gray-600 pl-4 italic my-4">
{children}
</blockquote>
),
table: ({ children }) => (
<div className="overflow-x-auto mb-4">
<table className="min-w-full border-collapse border border-border-primary">
<table className="min-w-full border-collapse border border-gray-300 dark:border-gray-600">
{children}
</table>
</div>
),
th: ({ children }) => (
<th className="border border-border-primary px-4 py-2 bg-surface-secondary font-semibold text-left text-text-primary">
<th className="border border-gray-300 dark:border-gray-600 px-4 py-2 bg-gray-100 dark:bg-gray-800 font-semibold text-left">
{children}
</th>
),
td: ({ children }) => (
<td className="border border-border-primary px-4 py-2 text-text-primary">
<td className="border border-gray-300 dark:border-gray-600 px-4 py-2">
{children}
</td>
),
a: ({ href, children }) => (
<a href={href} className="text-interactive-on-dark" target="_blank" rel="noopener noreferrer">
<a href={href} className="text-blue-600 dark:text-blue-400 hover:underline" target="_blank" rel="noopener noreferrer">
{children}
</a>
),
hr: () => <hr className="my-6 border-border-primary" />,
hr: () => <hr className="my-6 border-gray-300 dark:border-gray-600" />,
}}
>
{content}

View File

@ -15,15 +15,12 @@ export const MermaidRenderer: React.FC<MermaidRendererProps> = ({ chart, id }) =
const renderChart = async () => {
if (!elementRef.current || !chart) return;
// Create a unique ID for this render (define it outside try block)
const graphId = `mermaid-${id}-${Date.now()}`;
try {
// Clear any previous content
elementRef.current.innerHTML = '';
setHasError(false);
// Configure mermaid
// Configure mermaid if needed
mermaid.initialize({
startOnLoad: false,
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'default',
@ -31,36 +28,21 @@ export const MermaidRenderer: React.FC<MermaidRendererProps> = ({ chart, id }) =
fontFamily: 'monospace',
});
// Create a unique ID for this render
const graphId = `mermaid-${id}-${Date.now()}`;
// Render the chart
const { svg } = await mermaid.render(graphId, chart);
// Insert the SVG
if (elementRef.current) {
elementRef.current.innerHTML = svg;
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Mermaid rendering error:', error);
setHasError(true);
// Extract meaningful error message
let message = 'Failed to render diagram';
if (error instanceof Error) {
// Clean up the error message - remove version info and extra details
message = error.message
.replace(/mermaid version [\d.]+/gi, '')
.replace(/\s+/g, ' ')
.trim();
}
setErrorMessage(message);
// Clean up any error SVGs that mermaid may have inserted
const errorElements = document.querySelectorAll(`#${graphId}, [id^="mermaid-"]`);
errorElements.forEach(el => {
if (el.parentNode) {
el.parentNode.removeChild(el);
}
});
setErrorMessage(error?.message || 'Failed to render diagram');
// Try to clean up mermaid's internal state
try {
// @ts-expect-error - Mermaid API types don't include reset method
@ -81,11 +63,9 @@ export const MermaidRenderer: React.FC<MermaidRendererProps> = ({ chart, id }) =
if (hasError) {
return (
<div className="border border-status-error/30 rounded p-2 bg-status-error/5 text-sm">
<p className="text-status-error">
<span className="font-semibold">⚠ Diagram error:</span>{' '}
<span className="text-status-error/90">{errorMessage}</span>
</p>
<div className="border border-red-300 dark:border-red-700 rounded p-4 bg-red-50 dark:bg-red-900/20">
<p className="text-red-600 dark:text-red-400 font-semibold">Failed to render diagram</p>
<pre className="text-xs text-red-500 dark:text-red-300 mt-2">{errorMessage}</pre>
</div>
);
}

View File

@ -1,15 +1,11 @@
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
import { DiffEditor, type DiffEditorProps, type MonacoDiffEditor } from '@monaco-editor/react';
import * as monaco from 'monaco-editor';
import { AlertCircle, FileText, Check, Loader2, Eye, Code } from 'lucide-react';
import type { FileDiff } from '../../../types/diff';
import { debounce, type DebouncedFunction } from '../../../utils/debounce';
import { MonacoErrorBoundary } from '../../MonacoErrorBoundary';
import { MarkdownPreview } from '../../MarkdownPreview';
import type * as monaco from 'monaco-editor';
interface IDisposable {
dispose(): void;
}
import type { FileDiff } from '../types/diff';
import { debounce } from '../utils/debounce';
import { MonacoErrorBoundary } from './MonacoErrorBoundary';
import { MarkdownPreview } from './MarkdownPreview';
interface MonacoDiffViewerProps {
file: FileDiff;
@ -41,7 +37,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
const [isFullContentLoaded, setIsFullContentLoaded] = useState(false);
const [editorHeight, setEditorHeight] = useState<number>(400); // Default height
const containerRef = useRef<HTMLDivElement>(null);
const debouncedSaveRef = useRef<DebouncedFunction<(content: string) => Promise<void>> | null>(null);
const debouncedSaveRef = useRef<any>(null);
const [viewMode, setViewMode] = useState<'diff' | 'preview' | 'split'>('diff');
const [previewHeight, setPreviewHeight] = useState<number>(600); // Default preview height
const previewRef = useRef<HTMLDivElement>(null);
@ -52,10 +48,6 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
return ext === 'md' || ext === 'markdown';
}, [file.path]);
// Debug logging
console.log('MonacoDiffViewer - isDarkMode:', isDarkMode);
console.log('MonacoDiffViewer - theme:', isDarkMode ? 'vs-dark' : 'vs');
// Delay mounting editor to ensure stability
useEffect(() => {
// Reset states when important props change
@ -247,7 +239,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
const originalModel = originalEditor.getModel();
const modifiedModel = modifiedEditor.getModel();
const lineHeight = 19; // Default line height for Monaco editor
const lineHeight = originalEditor.getOption(monaco.editor.EditorOption.lineHeight);
const originalLines = originalModel ? originalModel.getLineCount() : 0;
const modifiedLines = modifiedModel ? modifiedModel.getLineCount() : 0;
@ -260,47 +252,11 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
setEditorHeight(calculatedHeight);
} catch (error) {
// Error calculating editor height - debug logging removed
console.debug('Error calculating editor height:', error);
}
}, []);
const handleBeforeMount = useCallback((_monaco: typeof monaco) => {
// Temporarily commented out to test built-in themes
// // Define custom themes before the editor mounts
// monaco.editor.defineTheme('crystal-dark', {
// base: 'vs-dark',
// inherit: true,
// rules: [],
// colors: {
// 'editor.background': '#111827',
// 'editor.foreground': '#f3f4f6',
// 'editorWidget.background': '#111827',
// 'editorWidget.foreground': '#f3f4f6',
// 'diffEditor.insertedTextBackground': '#10b98120',
// 'diffEditor.removedTextBackground': '#ef444420',
// 'diffEditor.insertedLineBackground': '#10b98115',
// 'diffEditor.removedLineBackground': '#ef444415',
// }
// });
// monaco.editor.defineTheme('crystal-light', {
// base: 'vs',
// inherit: true,
// rules: [],
// colors: {
// 'editor.background': '#ffffff',
// 'editor.foreground': '#1e2026',
// 'editorWidget.background': '#ffffff',
// 'editorWidget.foreground': '#1e2026',
// 'diffEditor.insertedTextBackground': '#16a34a15',
// 'diffEditor.removedTextBackground': '#dc262615',
// 'diffEditor.insertedLineBackground': '#16a34a10',
// 'diffEditor.removedLineBackground': '#dc262610',
// }
// });
}, []);
const handleEditorDidMount: DiffEditorProps['onMount'] = useCallback((editor: MonacoDiffEditor, monacoInstance: typeof monaco) => {
const handleEditorDidMount: DiffEditorProps['onMount'] = useCallback((editor: MonacoDiffEditor) => {
try {
editorRef.current = editor;
@ -308,7 +264,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
const modifiedEditor = editor.getModifiedEditor();
// Store disposables for cleanup
const disposables: IDisposable[] = [];
const disposables: monaco.IDisposable[] = [];
// Mark editor as ready
setIsEditorReady(true);
@ -360,7 +316,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
// Add save keyboard shortcut for immediate save
const commandDisposable = modifiedEditor.addCommand(
monacoInstance.KeyMod.CtrlCmd | monacoInstance.KeyCode.KeyS,
monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS,
() => {
// Check if editor and model still exist
if (!editorRef.current || !modifiedEditor.getModel()) {
@ -383,7 +339,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
}
// Store disposables for cleanup
(editor as MonacoDiffEditor & { __disposables?: IDisposable[] }).__disposables = disposables;
(editor as any).__disposables = disposables;
} catch (error) {
console.error('Error mounting Monaco editor:', error);
setIsEditorReady(false);
@ -393,7 +349,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
setTimeout(() => setCanMountEditor(true), 100);
}, 100);
}
}, [isReadOnly, debouncedSave, performSave, file.newValue, isFullContentLoaded, calculateEditorHeight, isDarkMode]);
}, [isReadOnly, debouncedSave, performSave, file.newValue, isFullContentLoaded, calculateEditorHeight]);
// Refresh content when file changes
useEffect(() => {
@ -447,16 +403,6 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
}
}, [isReadOnly, isEditorReady]);
// Update theme when isDarkMode changes
// useEffect(() => {
// if (editorRef.current && isEditorReady) {
// // The monaco instance from @monaco-editor/react is available via the loader
// import('monaco-editor').then((monacoModule) => {
// monacoModule.editor.setTheme(isDarkMode ? 'crystal-dark' : 'crystal-light');
// });
// }
// }, [isDarkMode, isEditorReady]);
// Calculate preview height when content or view mode changes
useEffect(() => {
if (!isMarkdownFile || viewMode === 'diff') return;
@ -484,25 +430,11 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
};
}, [currentContent, viewMode, isMarkdownFile]);
// Also flush pending saves when switching sessions
useEffect(() => {
const handleSessionSwitch = () => {
if (debouncedSaveRef.current?.flush) {
debouncedSaveRef.current.flush(); // Save before switching sessions
}
};
window.addEventListener('session-switched', handleSessionSwitch);
return () => {
window.removeEventListener('session-switched', handleSessionSwitch);
};
}, []); // Empty deps - only create once
// Cleanup on unmount or when key props change
useEffect(() => {
return () => {
// Flush any pending saves before unmount
debouncedSaveRef.current?.flush();
// Cancel any pending saves
debouncedSaveRef.current?.cancel?.();
// Clear timeout
if (savedTimeoutRef.current) {
@ -513,9 +445,9 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
if (editorRef.current) {
try {
// Dispose event handlers first
const editor = editorRef.current as MonacoDiffEditor & { __disposables?: IDisposable[] };
const editor = editorRef.current as any;
if (editor.__disposables) {
editor.__disposables.forEach((d: IDisposable) => {
editor.__disposables.forEach((d: monaco.IDisposable) => {
try {
d.dispose();
} catch (error) {
@ -547,18 +479,18 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
};
}, [file.path]); // Only cleanup when file path changes
const options = {
const options: monaco.editor.IStandaloneDiffEditorConstructionOptions = {
readOnly: isReadOnly,
renderSideBySide: viewType === 'split',
minimap: { enabled: false },
scrollBeyondLastLine: false,
fontSize: 13,
lineNumbers: 'on' as const,
renderWhitespace: 'selection' as const,
lineNumbers: 'on',
renderWhitespace: 'selection',
automaticLayout: true,
scrollbar: {
vertical: 'hidden' as const,
horizontal: 'hidden' as const,
vertical: 'hidden',
horizontal: 'hidden',
handleMouseWheel: false,
alwaysConsumeMouseWheel: false,
},
@ -596,23 +528,23 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
switch (saveStatus) {
case 'saving':
case 'pending':
return 'text-status-warning';
return 'text-yellow-600 dark:text-yellow-400';
case 'saved':
return 'text-status-success';
return 'text-green-600 dark:text-green-400';
case 'error':
return 'text-status-error';
return 'text-red-600 dark:text-red-400';
default:
return 'text-text-tertiary';
return 'text-gray-500';
}
};
return (
<div className="flex flex-col">
{/* Header */}
<div className="flex items-center justify-between px-4 py-2 bg-surface-secondary border-b border-border-primary">
<div className="flex items-center justify-between px-4 py-2 bg-gray-100 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-text-tertiary" />
<span className="text-sm font-medium text-text-primary">
<FileText className="w-4 h-4 text-gray-500" />
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">
{file.path}
</span>
</div>
@ -620,13 +552,13 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
<div className="flex items-center gap-2">
{/* Preview Toggle for Markdown Files */}
{isMarkdownFile && (
<div className="flex items-center rounded-lg border border-border-primary bg-surface-primary">
<div className="flex items-center rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700">
<button
onClick={() => setViewMode('diff')}
className={`px-2 py-1 text-xs font-medium rounded-l-lg transition-colors flex items-center gap-1 ${
viewMode === 'diff'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
title="Show diff view"
>
@ -637,8 +569,8 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
onClick={() => setViewMode('split')}
className={`px-2 py-1 text-xs font-medium transition-colors flex items-center gap-1 ${
viewMode === 'split'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
title="Show split view"
>
@ -651,8 +583,8 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
onClick={() => setViewMode('preview')}
className={`px-2 py-1 text-xs font-medium rounded-r-lg transition-colors flex items-center gap-1 ${
viewMode === 'preview'
? 'bg-interactive text-white'
: 'text-text-secondary hover:bg-surface-hover'
? 'bg-blue-500 text-white'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-600'
}`}
title="Show markdown preview"
>
@ -664,7 +596,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
{/* Save Status or Read-only indicator */}
{isReadOnly ? (
<div className="flex items-center gap-1 text-xs text-text-tertiary">
<div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400">
<AlertCircle className="w-3 h-3" />
<span>Read-only (select all commits to edit)</span>
</div>
@ -689,10 +621,10 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
) : viewMode === 'split' && isMarkdownFile ? (
<div className="flex" style={{ height: `${Math.max(editorHeight, previewHeight)}px` }}>
{/* Diff Editor */}
<div className="w-1/2 border-r border-border-primary" ref={containerRef} style={{ overflow: 'hidden' }}>
<div className="w-1/2 border-r border-gray-200 dark:border-gray-700" ref={containerRef} style={{ overflow: 'hidden' }}>
{(!isEditorReady || !canMountEditor) && (
<div className="absolute inset-0 flex items-center justify-center bg-bg-primary z-10">
<div className="flex items-center gap-2 text-text-secondary">
<div className="absolute inset-0 flex items-center justify-center bg-white dark:bg-gray-900 z-10">
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<Loader2 className="w-5 h-5 animate-spin" />
<span>Loading editor...</span>
</div>
@ -724,8 +656,8 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
) : (
<div className="relative" ref={containerRef} style={{ height: `${editorHeight}px`, overflow: 'hidden' }}>
{(!isEditorReady || !canMountEditor) && (
<div className="absolute inset-0 flex items-center justify-center bg-bg-primary z-10">
<div className="flex items-center gap-2 text-text-secondary">
<div className="absolute inset-0 flex items-center justify-center bg-white dark:bg-gray-900 z-10">
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<Loader2 className="w-5 h-5 animate-spin" />
<span>Loading editor...</span>
</div>
@ -740,7 +672,6 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
modified={currentContent}
theme={isDarkMode ? 'vs-dark' : 'vs'}
options={options}
beforeMount={handleBeforeMount}
onMount={handleEditorDidMount}
/>
</MonacoErrorBoundary>

View File

@ -51,7 +51,7 @@ export class MonacoErrorBoundary extends Component<MonacoErrorBoundaryProps, Mon
// Show a brief loading state while auto-recovering
return (
<div className="flex items-center justify-center h-full p-8">
<div className="flex items-center gap-2 text-text-tertiary">
<div className="flex items-center gap-2 text-gray-600 dark:text-gray-400">
<RefreshCw className="w-5 h-5 animate-spin" />
<span>Reloading editor...</span>
</div>

View File

@ -1,112 +0,0 @@
import { useEffect } from 'react';
import { X, ExternalLink, Download } from 'lucide-react';
import { NimbalystIcon } from './icons/NimbalystIcon';
import { AnalyticsService } from '../services/analyticsService';
interface NimbalystInstallDialogProps {
isOpen: boolean;
onClose: () => void;
}
export function NimbalystInstallDialog({ isOpen, onClose }: NimbalystInstallDialogProps) {
// Handle keyboard events
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
onClose();
} else if (event.key === 'Enter') {
event.preventDefault();
handleDownload();
}
};
if (isOpen) {
document.addEventListener('keydown', handleKeyDown);
return () => document.removeEventListener('keydown', handleKeyDown);
}
}, [isOpen, onClose]);
if (!isOpen) return null;
const handleDownload = async () => {
// Track download button click
await AnalyticsService.trackNimbalystDownloadClicked({});
window.electronAPI.invoke('openExternal', 'https://nimbalyst.com/');
onClose();
};
return (
<div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
<div className="bg-gradient-to-br from-white to-gray-50 dark:from-gray-800 dark:to-gray-900 rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden border border-gray-200/50 dark:border-gray-700/50">
{/* Header with gradient background */}
<div className="relative bg-gradient-to-r from-blue-500 to-blue-600 dark:from-blue-600 dark:to-blue-700 p-6 pb-8">
<button
onClick={onClose}
className="absolute top-4 right-4 text-white/80 hover:text-white transition-colors p-1 rounded-lg hover:bg-white/10"
>
<X className="w-5 h-5" />
</button>
<div className="flex items-center space-x-4">
<div className="flex-shrink-0 bg-white dark:bg-gray-800 p-3 rounded-xl shadow-lg">
<NimbalystIcon size={40} />
</div>
<div>
<h3 className="text-2xl font-bold text-white mb-1">
Nimbalyst
</h3>
<p className="text-blue-100 dark:text-blue-200 text-sm font-medium">
Integrated Markdown Environment
</p>
</div>
</div>
</div>
{/* Content */}
<div className="p-6 space-y-4">
<div className="flex items-start space-x-3">
<div className="flex-shrink-0 mt-1">
<div className="w-8 h-8 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center">
<Download className="w-4 h-4 text-blue-600 dark:text-blue-400" />
</div>
</div>
<div className="flex-1">
<h4 className="text-base font-semibold text-gray-900 dark:text-white mb-2">
Installation Required
</h4>
<p className="text-gray-600 dark:text-gray-300 text-sm leading-relaxed">
Nimbalyst is not installed on your system. To open worktrees in Nimbalyst, please download and install it first.
</p>
</div>
</div>
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800/30 rounded-lg p-4">
<p className="text-gray-700 dark:text-gray-300 text-sm leading-relaxed">
<span className="font-semibold text-blue-700 dark:text-blue-400">Nimbalyst</span> is an integrated markdown environment for Claude Code from the team that brought you Crystal.
</p>
</div>
</div>
{/* Footer with actions */}
<div className="bg-gray-50 dark:bg-gray-800/50 px-6 py-4 flex justify-end space-x-3 border-t border-gray-200/50 dark:border-gray-700/50">
<button
onClick={onClose}
className="px-5 py-2.5 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 rounded-lg transition-all border border-gray-300 dark:border-gray-600 shadow-sm hover:shadow"
>
Cancel
</button>
<button
onClick={handleDownload}
className="px-5 py-2.5 text-sm font-semibold text-white bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 rounded-lg transition-all flex items-center gap-2 shadow-lg shadow-blue-500/25 hover:shadow-xl hover:shadow-blue-500/40 hover:scale-[1.02]"
autoFocus
>
Download Nimbalyst
<ExternalLink className="w-4 h-4" />
</button>
</div>
</div>
</div>
);
}

View File

@ -1,9 +1,4 @@
import { useState, useEffect } from 'react';
import { Button } from './ui/Button';
import { ToggleField } from './ui/Toggle';
import { CollapsibleCard } from './ui/CollapsibleCard';
import { SettingsSection } from './ui/SettingsSection';
import { Bell, BellOff, Volume2, VolumeX, Zap, Shield } from 'lucide-react';
interface NotificationSettings {
enabled: boolean;
@ -48,142 +43,142 @@ export function NotificationSettings({ settings, onUpdateSettings }: Notificatio
}
};
const getPermissionIcon = () => {
switch (permissionStatus) {
case 'granted': return <Bell className="w-4 h-4 text-status-success" />;
case 'denied': return <BellOff className="w-4 h-4 text-status-error" />;
default: return <Shield className="w-4 h-4 text-status-warning" />;
}
const handleToggle = (key: keyof NotificationSettings) => {
onUpdateSettings({ [key]: !settings[key] });
};
const getPermissionStatus = () => {
switch (permissionStatus) {
case 'granted': return { text: 'Enabled', color: 'text-status-success' };
case 'denied': return { text: 'Denied', color: 'text-status-error' };
default: return { text: 'Not requested', color: 'text-status-warning' };
}
};
const status = getPermissionStatus();
return (
<div className="space-y-6">
{/* Browser Permissions */}
<CollapsibleCard
title="Browser Permissions"
subtitle="Allow Crystal to show desktop notifications"
icon={getPermissionIcon()}
defaultExpanded={true}
>
<SettingsSection
title="Notification Access"
description="Crystal needs browser permission to show notifications when your sessions update"
icon={getPermissionIcon()}
>
<div className="flex items-center justify-between p-4 bg-surface-secondary rounded-lg border border-border-secondary">
<div className="flex items-center gap-3">
{getPermissionIcon()}
<div>
<span className="text-sm font-medium text-text-primary">Permission Status</span>
<p className={`text-sm ${status.color} font-medium`}>
{status.text}
</p>
</div>
</div>
<div className="flex gap-2">
{permissionStatus !== 'granted' && (
<Button
onClick={requestPermission}
size="sm"
variant="primary"
>
Enable Notifications
</Button>
)}
{permissionStatus === 'granted' && (
<Button
onClick={testNotification}
size="sm"
variant="secondary"
>
Test Notification
</Button>
)}
</div>
</div>
{permissionStatus === 'denied' && (
<div className="mt-3 p-3 bg-status-error/10 border border-status-error/20 rounded-lg">
<p className="text-xs text-status-error">
Notifications are blocked. Please enable them in your browser settings and refresh Crystal.
<div>
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-4">Notification Settings</h3>
{/* Permission Status */}
<div className="mb-6 p-4 border border-gray-300 dark:border-gray-700 rounded-lg">
<div className="flex items-center justify-between">
<div>
<h4 className="font-medium text-gray-700 dark:text-gray-300">Browser Permissions</h4>
<p className="text-sm text-gray-600 dark:text-gray-400">
Status: {permissionStatus === 'granted' ? '✅ Enabled' :
permissionStatus === 'denied' ? '❌ Denied' : '⚠️ Not requested'}
</p>
</div>
)}
</SettingsSection>
</CollapsibleCard>
{/* Notification Preferences */}
<CollapsibleCard
title="Notification Preferences"
subtitle="Customize when and how you receive notifications"
icon={settings.enabled ? <Bell className="w-5 h-5" /> : <BellOff className="w-5 h-5" />}
defaultExpanded={true}
>
<SettingsSection
title="Master Control"
description="Turn all notifications on or off"
icon={settings.enabled ? <Bell className="w-4 h-4" /> : <BellOff className="w-4 h-4" />}
>
<ToggleField
label="Enable Notifications"
description="Show browser notifications for session events"
checked={settings.enabled}
onChange={(checked) => onUpdateSettings({ enabled: checked })}
/>
</SettingsSection>
<SettingsSection
title="Sound & Audio"
description="Control notification sounds"
icon={settings.playSound ? <Volume2 className="w-4 h-4" /> : <VolumeX className="w-4 h-4" />}
>
<ToggleField
label="Play notification sounds"
description="Play a subtle sound when notifications appear"
checked={settings.playSound}
onChange={(checked) => onUpdateSettings({ playSound: checked })}
/>
</SettingsSection>
<SettingsSection
title="Event Triggers"
description="Choose which session events should trigger notifications"
icon={<Zap className="w-4 h-4" />}
spacing="sm"
>
<div className="space-y-3">
<ToggleField
label="Status changes"
description="When sessions start, stop, or change state"
checked={settings.notifyOnStatusChange}
onChange={(checked) => onUpdateSettings({ notifyOnStatusChange: checked })}
/>
<ToggleField
label="Input required"
description="When Claude is waiting for your response"
checked={settings.notifyOnWaiting}
onChange={(checked) => onUpdateSettings({ notifyOnWaiting: checked })}
/>
<ToggleField
label="Task completion"
description="When sessions finish successfully"
checked={settings.notifyOnComplete}
onChange={(checked) => onUpdateSettings({ notifyOnComplete: checked })}
/>
{permissionStatus !== 'granted' && (
<button
onClick={requestPermission}
className="px-3 py-1 bg-blue-600 text-white text-sm rounded hover:bg-blue-700"
>
Enable Notifications
</button>
)}
</div>
</SettingsSection>
</CollapsibleCard>
{permissionStatus === 'granted' && (
<button
onClick={testNotification}
className="mt-2 px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700"
>
Test Notification
</button>
)}
</div>
{/* Settings */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<label className="font-medium text-gray-700 dark:text-gray-300">Enable Notifications</label>
<p className="text-sm text-gray-600 dark:text-gray-400">Show browser notifications for session events</p>
</div>
<button
onClick={() => handleToggle('enabled')}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
settings.enabled ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
settings.enabled ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between">
<div>
<label className="font-medium text-gray-700 dark:text-gray-300">Play Sound</label>
<p className="text-sm text-gray-600 dark:text-gray-400">Play a sound when notifications appear</p>
</div>
<button
onClick={() => handleToggle('playSound')}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
settings.playSound ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
settings.playSound ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between">
<div>
<label className="font-medium text-gray-700 dark:text-gray-300">Status Changes</label>
<p className="text-sm text-gray-600 dark:text-gray-400">Notify when session status changes</p>
</div>
<button
onClick={() => handleToggle('notifyOnStatusChange')}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
settings.notifyOnStatusChange ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
settings.notifyOnStatusChange ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between">
<div>
<label className="font-medium text-gray-700 dark:text-gray-300">Input Required</label>
<p className="text-sm text-gray-600 dark:text-gray-400">Notify when sessions are waiting for input</p>
</div>
<button
onClick={() => handleToggle('notifyOnWaiting')}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
settings.notifyOnWaiting ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
settings.notifyOnWaiting ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
<div className="flex items-center justify-between">
<div>
<label className="font-medium text-gray-700 dark:text-gray-300">Session Complete</label>
<p className="text-sm text-gray-600 dark:text-gray-400">Notify when sessions finish successfully</p>
</div>
<button
onClick={() => handleToggle('notifyOnComplete')}
className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
settings.notifyOnComplete ? 'bg-blue-600' : 'bg-gray-300 dark:bg-gray-600'
}`}
>
<span
className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
settings.notifyOnComplete ? 'translate-x-6' : 'translate-x-1'
}`}
/>
</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,20 +1,17 @@
import React, { useState, useEffect } from 'react';
import { Check, X, Shield, AlertTriangle, Code, Edit } from 'lucide-react';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
import { Textarea } from './ui/Textarea';
interface PermissionRequest {
id: string;
sessionId: string;
toolName: string;
input: Record<string, unknown>;
input: any;
timestamp: number;
}
interface PermissionDialogProps {
request: PermissionRequest | null;
onRespond: (requestId: string, behavior: 'allow' | 'deny', updatedInput?: Record<string, unknown>, message?: string) => void;
onRespond: (requestId: string, behavior: 'allow' | 'deny', updatedInput?: any, message?: string) => void;
session?: { name: string };
}
@ -86,24 +83,15 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
const renderInputPreview = () => {
const { input, toolName } = request;
// Helper to safely get string value
const getStringValue = (obj: Record<string, unknown>, key: string): string | undefined => {
const value = obj[key];
return typeof value === 'string' ? value : undefined;
};
if (toolName.includes('Bash')) {
const command = getStringValue(input, 'command');
const description = getStringValue(input, 'description');
return (
<div className="bg-surface-secondary p-3 rounded font-mono text-sm border border-border-primary">
<div className="text-text-tertiary text-xs mb-1">Command:</div>
<div className="text-text-primary">{command || 'No command specified'}</div>
{description && (
<div className="bg-gray-100 dark:bg-gray-900 p-3 rounded font-mono text-sm border border-gray-200 dark:border-gray-700">
<div className="text-gray-600 dark:text-gray-400 text-xs mb-1">Command:</div>
<div className="text-gray-900 dark:text-white">{input.command || 'No command specified'}</div>
{input.description && (
<>
<div className="text-text-tertiary text-xs mt-2 mb-1">Description:</div>
<div className="text-text-secondary">{description}</div>
<div className="text-gray-600 dark:text-gray-400 text-xs mt-2 mb-1">Description:</div>
<div className="text-gray-700 dark:text-gray-300">{input.description}</div>
</>
)}
</div>
@ -111,18 +99,15 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
}
if (toolName.includes('Write') || toolName.includes('Edit')) {
const filePath = getStringValue(input, 'file_path') || getStringValue(input, 'path');
const content = getStringValue(input, 'content');
return (
<div className="bg-surface-secondary p-3 rounded font-mono text-sm border border-border-primary">
<div className="text-text-tertiary text-xs mb-1">File Path:</div>
<div className="text-text-primary">{filePath || 'No path specified'}</div>
{content && (
<div className="bg-gray-100 dark:bg-gray-900 p-3 rounded font-mono text-sm border border-gray-200 dark:border-gray-700">
<div className="text-gray-600 dark:text-gray-400 text-xs mb-1">File Path:</div>
<div className="text-gray-900 dark:text-white">{input.file_path || input.path || 'No path specified'}</div>
{input.content && (
<>
<div className="text-text-tertiary text-xs mt-2 mb-1">Content Preview:</div>
<div className="text-text-secondary max-h-32 overflow-y-auto whitespace-pre-wrap">
{content.length > 500 ? content.substring(0, 500) + '...' : content}
<div className="text-gray-600 dark:text-gray-400 text-xs mt-2 mb-1">Content Preview:</div>
<div className="text-gray-700 dark:text-gray-300 max-h-32 overflow-y-auto whitespace-pre-wrap">
{input.content.length > 500 ? input.content.substring(0, 500) + '...' : input.content}
</div>
</>
)}
@ -132,44 +117,45 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
// Default JSON view
return (
<div className="bg-surface-secondary p-3 rounded font-mono text-sm border border-border-primary">
<pre className="text-text-primary overflow-x-auto">{JSON.stringify(input, null, 2)}</pre>
<div className="bg-gray-900 p-3 rounded font-mono text-sm">
<pre className="text-gray-900 dark:text-white overflow-x-auto">{JSON.stringify(input, null, 2)}</pre>
</div>
);
};
return (
<Modal isOpen={true} onClose={() => handleDeny()} size="lg" showCloseButton={false}>
<ModalHeader onClose={() => handleDeny()}>
<div className="flex items-center gap-3">
<Shield className={`w-6 h-6 ${isHighRisk(request.toolName) ? 'text-status-error' : 'text-status-warning'}`} />
<div className="flex-1">
<h2 className="text-xl font-semibold text-text-primary">Permission Required</h2>
<p className="text-sm text-text-secondary mt-1">
Claude wants to {getToolDescription(request.toolName)} in session: {session?.name || request.sessionId}
</p>
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden border border-gray-200 dark:border-gray-700">
<div className="p-6 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-3">
<Shield className={`w-6 h-6 ${isHighRisk(request.toolName) ? 'text-red-400' : 'text-yellow-400'}`} />
<div className="flex-1">
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">Permission Required</h2>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Claude wants to {getToolDescription(request.toolName)} in session: {session?.name || request.sessionId}
</p>
</div>
</div>
</div>
</ModalHeader>
<ModalBody className="space-y-6">
<div>
<div className="p-6 overflow-y-auto max-h-[60vh]">
<div className="mb-4">
<div className="flex items-center gap-2 mb-2">
<Code className="w-4 h-4 text-text-tertiary" />
<h3 className="text-sm font-medium text-text-secondary">Tool</h3>
<Code className="w-4 h-4 text-gray-400" />
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Tool</h3>
{isHighRisk(request.toolName) && (
<span className="text-xs bg-status-error/20 text-status-error px-2 py-0.5 rounded">High Risk</span>
<span className="text-xs bg-red-500/20 text-red-400 px-2 py-0.5 rounded">High Risk</span>
)}
</div>
<p className="text-text-primary font-mono">{formatToolName(request.toolName)}</p>
<p className="text-gray-900 dark:text-white font-mono">{formatToolName(request.toolName)}</p>
</div>
<div>
<div className="mb-4">
<div className="flex items-center justify-between mb-2">
<h3 className="text-sm font-medium text-text-secondary">Input Parameters</h3>
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Input Parameters</h3>
<button
onClick={() => setEditMode(!editMode)}
className="flex items-center gap-1 text-xs text-interactive hover:text-interactive-hover transition-colors"
className="flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300"
>
<Edit className="w-3 h-3" />
{editMode ? 'Preview' : 'Edit'}
@ -177,10 +163,10 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
</div>
{editMode ? (
<Textarea
<textarea
value={editedInput}
onChange={(e) => setEditedInput(e.target.value)}
className="font-mono text-sm h-48"
className="w-full h-48 bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-white p-3 rounded font-mono text-sm resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 border border-gray-300 dark:border-gray-700"
spellCheck={false}
/>
) : (
@ -189,34 +175,35 @@ export const PermissionDialog: React.FC<PermissionDialogProps> = ({ request, onR
</div>
{isHighRisk(request.toolName) && (
<div className="bg-status-error/10 border border-status-error/30 rounded p-3">
<div className="flex items-center gap-2 text-status-error">
<div className="bg-red-100 dark:bg-red-500/10 border border-red-300 dark:border-red-500/30 rounded p-3">
<div className="flex items-center gap-2 text-red-400">
<AlertTriangle className="w-4 h-4" />
<span className="text-sm font-medium">High Risk Action</span>
</div>
<p className="text-xs text-text-tertiary mt-1">
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1">
This action could modify your system or files. Review carefully before approving.
</p>
</div>
)}
</ModalBody>
</div>
<ModalFooter>
<Button
onClick={handleDeny}
variant="secondary"
icon={<X className="w-4 h-4" />}
>
Deny
</Button>
<Button
onClick={handleAllow}
variant="primary"
icon={<Check className="w-4 h-4" />}
>
Allow
</Button>
</ModalFooter>
</Modal>
<div className="p-6 border-t border-gray-200 dark:border-gray-700 flex justify-end gap-3">
<button
onClick={handleDeny}
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-white rounded hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors flex items-center gap-2"
>
<X className="w-4 h-4" />
Deny
</button>
<button
onClick={handleAllow}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-500 transition-colors flex items-center gap-2"
>
<Check className="w-4 h-4" />
Allow
</button>
</div>
</div>
</div>
);
};

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { RefreshCw, GitBranch, AlertCircle, CheckCircle, GitPullRequest, Loader2, XCircle, Filter } from 'lucide-react';
import { API } from '../utils/api';
import type { ProjectDashboardData, SessionBranchInfo } from '../types/projectDashboard';
@ -10,8 +10,6 @@ import { useSessionStore } from '../stores/sessionStore';
import { useNavigationStore } from '../stores/navigationStore';
import { MultiOriginStatus } from './dashboard/MultiOriginStatus';
import { StatusSummaryCards } from './dashboard/StatusSummaryCards';
import { Card } from './ui/Card';
import { Button } from './ui/Button';
interface ProjectDashboardProps {
projectId: number;
@ -25,40 +23,8 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
const [error, setError] = useState<string | null>(null);
const [lastRefreshTime, setLastRefreshTime] = useState<Date | null>(null);
const [filterType, setFilterType] = useState<'all' | 'stale' | 'changes' | 'pr'>('all');
const [isProgressive] = useState(true); // Use progressive loading by default
const pendingSessionUpdatesRef = useRef<Map<string, SessionBranchInfo>>(new Map());
// Debounced function to apply pending session updates
const applyPendingSessionUpdates = useMemo(
() => debounce(() => {
const updates = Array.from(pendingSessionUpdatesRef.current.values());
if (updates.length === 0) return;
setDashboardData(prevData => {
if (!prevData) return null;
const sessionMap = new Map(
prevData.sessionBranches.map(s => [s.sessionId, s])
);
// Apply all pending updates
updates.forEach(update => {
sessionMap.set(update.sessionId, update);
});
// Clear pending updates
pendingSessionUpdatesRef.current.clear();
return {
...prevData,
sessionBranches: Array.from(sessionMap.values())
};
});
}, 100), // 100ms debounce for smooth updates
[]
);
const fetchDashboardData = useCallback(async (useCache: boolean = true, useProgressive: boolean = true) => {
const fetchDashboardData = useCallback(async (useCache: boolean = true) => {
// Check cache first if not forcing refresh
if (useCache) {
const cachedData = dashboardCache.get(projectId);
@ -74,30 +40,15 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
setError(null);
try {
if (useProgressive && isProgressive) {
// Use progressive loading
const response = await API.dashboard.getProjectStatusProgressive(projectId);
if (response.success && response.data) {
setDashboardData(response.data);
setLastRefreshTime(new Date());
// Cache the data
dashboardCache.set(projectId, response.data);
} else {
setError(response.error || 'Failed to fetch project status');
}
const response = await API.dashboard.getProjectStatus(projectId);
if (response.success && response.data) {
setDashboardData(response.data);
setLastRefreshTime(new Date());
// Cache the data
dashboardCache.set(projectId, response.data);
} else {
// Use traditional loading
const response = await API.dashboard.getProjectStatus(projectId);
if (response.success && response.data) {
setDashboardData(response.data);
setLastRefreshTime(new Date());
// Cache the data
dashboardCache.set(projectId, response.data);
} else {
setError(response.error || 'Failed to fetch project status');
}
setError(response.error || 'Failed to fetch project status');
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error occurred');
@ -105,72 +56,17 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
setIsLoading(false);
setIsRefreshing(false);
}
}, [projectId, dashboardData, isProgressive]);
}, [projectId, dashboardData]);
// Debounced refresh function
const debouncedRefresh = useMemo(
() => debounce(() => {
dashboardCache.invalidate(projectId);
fetchDashboardData(false, true);
fetchDashboardData(false);
}, 500),
[projectId, fetchDashboardData]
);
// Set up progressive loading event listeners
useEffect(() => {
if (!isProgressive) return;
const cleanupFns: Array<() => void> = [];
// Handle dashboard updates
const unsubscribeUpdate = API.dashboard.onUpdate((event) => {
if (event.projectId === projectId) {
setDashboardData(prevData => {
if (!prevData && event.data) {
// Initial data
return event.data as ProjectDashboardData;
} else if (prevData && event.data && event.isPartial) {
// Merge partial update
return { ...prevData, ...event.data };
} else if (event.data) {
// Full update
const data = event.data as ProjectDashboardData;
if (data.projectId && data.projectName && data.sessionBranches) {
dashboardCache.set(projectId, data);
}
return data;
}
return prevData;
});
if (!event.isPartial) {
setIsLoading(false);
setIsRefreshing(false);
}
}
});
cleanupFns.push(unsubscribeUpdate);
// Handle individual session updates with debouncing
const unsubscribeSession = API.dashboard.onSessionUpdate((event) => {
if (event.projectId === projectId && event.data && event.sessionId) {
// Cast to SessionBranchInfo since we know this is the expected shape from dashboard updates
const sessionData = event.data as SessionBranchInfo;
// Add to pending updates
pendingSessionUpdatesRef.current.set(event.sessionId, sessionData);
// Trigger debounced update
applyPendingSessionUpdates();
}
});
cleanupFns.push(unsubscribeSession);
return () => {
cleanupFns.forEach(fn => fn());
// Cancel any pending updates
applyPendingSessionUpdates.cancel();
};
}, [projectId, isProgressive, applyPendingSessionUpdates]);
useEffect(() => {
// Clear previous data when switching projects to show skeleton
setDashboardData(null);
@ -195,7 +91,7 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
// }, [dashboardData?.sessionBranches]);
const renderSessionRow = useCallback((session: SessionBranchInfo) => {
const staleClass = session.isStale ? 'bg-status-warning/10' : '';
const staleClass = session.isStale ? 'bg-yellow-50 dark:bg-yellow-900/20' : '';
const handleSessionClick = async () => {
console.log('[ProjectDashboard] Session clicked:', session.sessionId, session.sessionName);
@ -210,52 +106,52 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
};
return (
<tr key={session.sessionId} className={`hover:bg-surface-hover ${staleClass} cursor-pointer`} onClick={handleSessionClick}>
<tr key={session.sessionId} className={`hover:bg-gray-50 dark:hover:bg-gray-800 ${staleClass} cursor-pointer`} onClick={handleSessionClick}>
<td className="px-4 py-3 text-sm">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4 text-text-tertiary" />
<GitBranch className="w-4 h-4 text-gray-400" />
<div>
<div className="font-medium text-text-primary">{session.sessionName}</div>
<div className="text-text-tertiary text-xs">{session.branchName}</div>
<div className="font-medium text-gray-900 dark:text-gray-100">{session.sessionName}</div>
<div className="text-gray-500 dark:text-gray-400 text-xs">{session.branchName}</div>
</div>
</div>
</td>
<td className="px-4 py-3 text-sm text-text-secondary">
<code className="text-xs bg-surface-secondary px-1 py-0.5 rounded">
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">
<code className="text-xs bg-gray-100 dark:bg-gray-800 px-1 py-0.5 rounded">
{session.baseBranch}
</code>
</td>
<td className="px-4 py-3 text-sm">
{session.isStale ? (
<div className="flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-status-warning" />
<span className="text-status-warning">
<AlertCircle className="w-4 h-4 text-yellow-600" />
<span className="text-yellow-700 dark:text-yellow-400">
Stale {session.staleSince && `since ${formatDistanceToNow(session.staleSince)}`}
</span>
</div>
) : (
<div className="flex items-center gap-2">
<CheckCircle className="w-4 h-4 text-status-success" />
<span className="text-status-success">Current</span>
<CheckCircle className="w-4 h-4 text-green-500" />
<span className="text-green-700 dark:text-green-400">Current</span>
</div>
)}
</td>
<td className="px-4 py-3 text-sm text-text-secondary">
<td className="px-4 py-3 text-sm text-gray-700 dark:text-gray-300">
<div className="flex gap-3 text-xs">
{session.commitsAhead > 0 && (
<span className="text-interactive">+{session.commitsAhead}</span>
<span className="text-blue-600 dark:text-blue-400">+{session.commitsAhead}</span>
)}
{session.commitsBehind > 0 && (
<span className="text-status-warning">-{session.commitsBehind}</span>
<span className="text-orange-600 dark:text-orange-400">-{session.commitsBehind}</span>
)}
{session.commitsAhead === 0 && session.commitsBehind === 0 && (
<span className="text-text-tertiary">—</span>
<span className="text-gray-400">—</span>
)}
</div>
</td>
<td className="px-4 py-3 text-sm">
{session.hasUncommittedChanges && (
<span className="inline-flex items-center gap-1 text-status-warning">
<span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-400">
<AlertCircle className="w-3 h-3" />
<span className="text-xs">Uncommitted</span>
</span>
@ -267,23 +163,23 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
href={session.pullRequest.url}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-interactive hover:text-interactive-hover"
className="inline-flex items-center gap-1 text-blue-600 hover:text-blue-800 dark:text-blue-400"
onClick={(e) => e.stopPropagation()}
>
<GitPullRequest className="w-4 h-4" />
<span>#{session.pullRequest.number}</span>
{session.pullRequest.state === 'open' && (
<span className="inline-block w-2 h-2 bg-status-success rounded-full"></span>
<span className="inline-block w-2 h-2 bg-green-500 rounded-full"></span>
)}
{session.pullRequest.state === 'closed' && (
<XCircle className="w-3 h-3 text-status-error" />
<XCircle className="w-3 h-3 text-red-500" />
)}
{session.pullRequest.state === 'merged' && (
<CheckCircle className="w-3 h-3 text-interactive" />
<CheckCircle className="w-3 h-3 text-purple-500" />
)}
</a>
) : (
<span className="text-text-tertiary">—</span>
<span className="text-gray-400">—</span>
)}
</td>
</tr>
@ -308,15 +204,15 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
if (error) {
return (
<div className="p-6 bg-status-error/10 rounded-lg">
<div className="flex items-center gap-2 text-status-error">
<div className="p-6 bg-red-50 dark:bg-red-900/20 rounded-lg">
<div className="flex items-center gap-2 text-red-700 dark:text-red-400">
<AlertCircle className="w-5 h-5" />
<span className="font-medium">Error loading dashboard</span>
</div>
<p className="mt-1 text-sm text-status-error/80">{error}</p>
<p className="mt-1 text-sm text-red-600 dark:text-red-300">{error}</p>
<button
onClick={() => fetchDashboardData(false)}
className="mt-3 px-3 py-1 text-sm bg-status-error text-white rounded hover:bg-status-error-hover"
className="mt-3 px-3 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700"
>
Try Again
</button>
@ -329,32 +225,37 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
}
return (
<Card className="flex flex-col h-full">
<div className="px-6 py-4 border-b border-border-primary">
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 flex flex-col h-full">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<div>
<h2 className="text-lg font-semibold text-text-primary">
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
Project Dashboard
</h2>
<p className="text-sm text-text-secondary">
<p className="text-sm text-gray-500 dark:text-gray-400">
Git status for {dashboardData?.projectName || projectName}
</p>
</div>
<div className="flex items-center gap-4">
{lastRefreshTime && (
<span className="text-xs text-text-tertiary">
<span className="text-xs text-gray-500 dark:text-gray-400">
Updated {formatDistanceToNow(lastRefreshTime)}
</span>
)}
<Button
<button
onClick={debouncedRefresh}
disabled={isLoading || isRefreshing}
variant="secondary"
size="sm"
icon={(isLoading || isRefreshing) ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
className="inline-flex items-center gap-2 px-3 py-1.5 text-sm bg-gray-100 dark:bg-gray-800
text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700
disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
{(isLoading || isRefreshing) ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4" />
)}
Refresh
</Button>
</button>
</div>
</div>
</div>
@ -362,14 +263,12 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
{dashboardData ? (
<div className="p-6 flex-1 flex flex-col overflow-hidden">
{/* Multi-Origin Status */}
{dashboardData.mainBranchStatus && (
<MultiOriginStatus
mainBranch={dashboardData.mainBranch}
mainBranchStatus={dashboardData.mainBranchStatus}
remotes={dashboardData.remotes}
onReviewUpdates={() => console.log('Review updates clicked')}
/>
)}
<MultiOriginStatus
mainBranch={dashboardData.mainBranch}
mainBranchStatus={dashboardData.mainBranchStatus}
remotes={dashboardData.remotes}
onReviewUpdates={() => console.log('Review updates clicked')}
/>
{/* Status Summary Cards */}
<StatusSummaryCards sessions={dashboardData.sessionBranches} />
@ -378,15 +277,15 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
{dashboardData.sessionBranches.length > 0 ? (
<div className="flex-1 flex flex-col overflow-hidden">
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-medium text-text-primary">
<h3 className="text-sm font-medium text-gray-900 dark:text-gray-100">
Session Branches ({filteredSessions.length} of {dashboardData.sessionBranches.length})
</h3>
<div className="flex items-center gap-2">
<Filter className="w-4 h-4 text-text-tertiary" />
<Filter className="w-4 h-4 text-gray-400" />
<select
value={filterType}
onChange={(e) => setFilterType(e.target.value as typeof filterType)}
className="text-sm border border-border-primary rounded px-2 py-1 bg-surface-primary text-text-primary focus:outline-none focus:ring-2 focus:ring-interactive focus:border-interactive"
className="text-sm border border-gray-300 dark:border-gray-600 rounded px-2 py-1 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300"
>
<option value="all">All Sessions</option>
<option value="stale">Stale Only</option>
@ -395,44 +294,44 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
</select>
</div>
</div>
<div className="flex-1 overflow-x-auto overflow-y-auto border border-border-primary rounded-lg">
<table className="min-w-full divide-y divide-border-primary">
<thead className="bg-surface-secondary">
<div className="flex-1 overflow-x-auto overflow-y-auto border border-gray-200 dark:border-gray-700 rounded-lg">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-800">
<tr>
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Session
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Base Branch
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Status
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Commits
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Changes
</th>
<th className="px-4 py-3 text-left text-xs font-medium text-text-tertiary uppercase tracking-wider">
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Pull Request
</th>
</tr>
</thead>
<tbody className="bg-bg-primary divide-y divide-border-primary">
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
{filteredSessions.map(renderSessionRow)}
</tbody>
</table>
</div>
</div>
) : (
<div className="text-center py-8 text-text-tertiary">
<GitBranch className="w-12 h-12 mx-auto mb-3 text-text-tertiary/50" />
<div className="text-center py-8 text-gray-500 dark:text-gray-400">
<GitBranch className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
<p>No active session branches</p>
</div>
)}
</div>
) : null}
</Card>
</div>
);
});

View File

@ -1,32 +1,31 @@
import React from 'react';
import { Card } from './ui/Card';
export const ProjectDashboardSkeleton: React.FC = () => {
return (
<Card className="animate-pulse">
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 animate-pulse">
{/* Header Skeleton */}
<div className="px-6 py-4 border-b border-border-primary">
<div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<div>
<div className="h-6 w-48 bg-surface-tertiary rounded mb-2"></div>
<div className="h-4 w-32 bg-surface-tertiary rounded"></div>
<div className="h-6 w-48 bg-gray-200 dark:bg-gray-700 rounded mb-2"></div>
<div className="h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded"></div>
</div>
<div className="flex items-center gap-4">
<div className="h-4 w-24 bg-surface-tertiary rounded"></div>
<div className="h-8 w-20 bg-surface-tertiary rounded"></div>
<div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
<div className="h-8 w-20 bg-gray-200 dark:bg-gray-700 rounded"></div>
</div>
</div>
</div>
<div className="p-6">
{/* Main Branch Status Skeleton */}
<div className="mb-6 p-4 bg-surface-secondary rounded-lg">
<div className="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="w-5 h-5 bg-border-primary rounded"></div>
<div className="w-5 h-5 bg-gray-300 dark:bg-gray-600 rounded"></div>
<div>
<div className="h-5 w-36 bg-surface-tertiary rounded mb-2"></div>
<div className="h-4 w-48 bg-surface-tertiary rounded"></div>
<div className="h-5 w-36 bg-gray-200 dark:bg-gray-700 rounded mb-2"></div>
<div className="h-4 w-48 bg-gray-200 dark:bg-gray-700 rounded"></div>
</div>
</div>
</div>
@ -34,47 +33,47 @@ export const ProjectDashboardSkeleton: React.FC = () => {
{/* Table Header Skeleton */}
<div className="mb-3">
<div className="h-4 w-40 bg-surface-tertiary rounded"></div>
<div className="h-4 w-40 bg-gray-200 dark:bg-gray-700 rounded"></div>
</div>
{/* Table Skeleton */}
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-border-primary">
<thead className="bg-surface-secondary">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-800">
<tr>
{[1, 2, 3, 4, 5, 6].map((i) => (
<th key={i} className="px-4 py-3">
<div className="h-3 w-16 bg-border-primary rounded"></div>
<div className="h-3 w-16 bg-gray-300 dark:bg-gray-600 rounded"></div>
</th>
))}
</tr>
</thead>
<tbody className="bg-surface-primary divide-y divide-border-primary">
<tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
{[1, 2, 3].map((row) => (
<tr key={row}>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
<div className="w-4 h-4 bg-surface-tertiary rounded"></div>
<div className="w-4 h-4 bg-gray-200 dark:bg-gray-700 rounded"></div>
<div>
<div className="h-4 w-32 bg-surface-tertiary rounded mb-1"></div>
<div className="h-3 w-24 bg-surface-tertiary rounded"></div>
<div className="h-4 w-32 bg-gray-200 dark:bg-gray-700 rounded mb-1"></div>
<div className="h-3 w-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
</div>
</div>
</td>
<td className="px-4 py-3">
<div className="h-4 w-16 bg-surface-tertiary rounded"></div>
<div className="h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded"></div>
</td>
<td className="px-4 py-3">
<div className="h-4 w-20 bg-surface-tertiary rounded"></div>
<div className="h-4 w-20 bg-gray-200 dark:bg-gray-700 rounded"></div>
</td>
<td className="px-4 py-3">
<div className="h-4 w-12 bg-surface-tertiary rounded"></div>
<div className="h-4 w-12 bg-gray-200 dark:bg-gray-700 rounded"></div>
</td>
<td className="px-4 py-3">
<div className="h-4 w-24 bg-surface-tertiary rounded"></div>
<div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded"></div>
</td>
<td className="px-4 py-3">
<div className="h-4 w-16 bg-surface-tertiary rounded"></div>
<div className="h-4 w-16 bg-gray-200 dark:bg-gray-700 rounded"></div>
</td>
</tr>
))}
@ -82,6 +81,6 @@ export const ProjectDashboardSkeleton: React.FC = () => {
</table>
</div>
</div>
</Card>
</div>
);
};

View File

@ -1,15 +1,9 @@
import { useState, useEffect } from 'react';
import { ChevronDown, Plus, Check, Settings } from 'lucide-react';
import { API } from '../utils/api';
import type { Project, CreateProjectRequest } from '../types/project';
import type { Project } from '../types/project';
import ProjectSettings from './ProjectSettings';
import { useErrorStore } from '../stores/errorStore';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Button, IconButton } from './ui/Button';
import { EnhancedInput } from './ui/EnhancedInput';
import { FieldWithTooltip } from './ui/FieldWithTooltip';
import { Card } from './ui/Card';
import { Folder, GitBranch, Hammer, Play } from 'lucide-react';
interface ProjectSelectorProps {
onProjectChange?: (project: Project) => void;
@ -20,8 +14,7 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
const [activeProject, setActiveProject] = useState<Project | null>(null);
const [isOpen, setIsOpen] = useState(false);
const [showAddDialog, setShowAddDialog] = useState(false);
const [newProject, setNewProject] = useState<CreateProjectRequest>({ name: '', path: '', buildScript: '', runScript: '' });
const [showValidationErrors, setShowValidationErrors] = useState(false);
const [newProject, setNewProject] = useState({ name: '', path: '', buildScript: '', runScript: '' });
const [detectedBranch, setDetectedBranch] = useState<string | null>(null);
const [showSettings, setShowSettings] = useState(false);
const [settingsProject, setSettingsProject] = useState<Project | null>(null);
@ -90,7 +83,7 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
if (!newProject.name || !newProject.path) return;
try {
const response = await API.projects.create({ ...newProject, active: false });
const response = await API.projects.create(newProject);
if (!response.success) {
showError({
@ -115,14 +108,12 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
} else {
fetchProjects();
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to create project:', error);
const errorMessage = error instanceof Error ? error.message : 'An error occurred while creating the project.';
const errorDetails = error instanceof Error ? error.stack : String(error);
showError({
title: 'Failed to Create Project',
error: errorMessage,
details: errorDetails || ''
error: error.message || 'An error occurred while creating the project.',
details: error.stack || error.toString()
});
}
};
@ -153,259 +144,210 @@ export default function ProjectSelector({ onProjectChange }: ProjectSelectorProp
<>
<div className="relative">
<div className="flex items-center space-x-2">
<Button
<button
onClick={() => setIsOpen(!isOpen)}
variant="secondary"
size="md"
className="flex-1 justify-between"
className="flex-1 flex items-center space-x-2 px-3 py-2 bg-gray-800 hover:bg-gray-700 rounded-md text-sm transition-colors"
>
<span>
<span className="text-gray-300">
{activeProject ? activeProject.name : 'Select Project'}
</span>
<ChevronDown className={`w-4 h-4 ml-2 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</Button>
<ChevronDown className={`w-4 h-4 text-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
</button>
{activeProject && (
<IconButton
<button
onClick={() => handleSettingsClick(activeProject)}
aria-label="Project Settings"
size="md"
icon={<Settings className="w-4 h-4" />}
/>
className="p-2 bg-gray-800 hover:bg-gray-700 rounded-md transition-colors"
title="Project Settings"
>
<Settings className="w-4 h-4 text-gray-400" />
</button>
)}
</div>
{isOpen && (
<Card
variant="elevated"
className="absolute top-full left-0 mt-1 w-64 z-50"
padding="none"
>
<div className="p-1">
<div className="absolute top-full left-0 mt-1 w-64 bg-gray-800 rounded-md shadow-lg border border-gray-700 z-50">
<div className="p-2">
{projects.map(project => (
<div
key={project.id}
className="flex items-center hover:bg-bg-hover rounded-md group"
className="flex items-center hover:bg-gray-700 rounded group"
>
<button
onClick={() => handleSelectProject(project)}
className="flex-1 text-left px-3 py-2 flex items-center justify-between"
>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-text-primary">{project.name}</div>
<div className="text-xs text-text-tertiary truncate">{project.path}</div>
<div className="text-sm font-medium text-gray-200">{project.name}</div>
<div className="text-xs text-gray-500 truncate">{project.path}</div>
</div>
{project.active && (
<Check className="w-4 h-4 text-status-success ml-2 flex-shrink-0" />
<Check className="w-4 h-4 text-green-500 ml-2 flex-shrink-0" />
)}
</button>
<IconButton
<button
onClick={(e) => {
e.stopPropagation();
handleSettingsClick(project);
}}
size="sm"
className="opacity-0 group-hover:opacity-100 transition-opacity"
aria-label="Project Settings"
icon={<Settings className="w-4 h-4" />}
/>
className="p-2 opacity-0 group-hover:opacity-100 transition-opacity"
title="Project Settings"
>
<Settings className="w-4 h-4 text-gray-400 hover:text-gray-200" />
</button>
</div>
))}
<div className="border-t border-border-primary mt-2 pt-2">
<Button
<div className="border-t border-gray-700 mt-2 pt-2">
<button
onClick={() => {
setIsOpen(false);
setShowAddDialog(true);
}}
variant="ghost"
size="sm"
className="w-full justify-start"
className="w-full text-left px-3 py-2 rounded hover:bg-gray-700 flex items-center space-x-2 text-sm"
>
<Plus className="w-4 h-4 mr-2" />
Add Project
</Button>
<Plus className="w-4 h-4 text-gray-400" />
<span className="text-gray-300">Add Project</span>
</button>
</div>
</div>
</Card>
</div>
)}
</div>
{/* Add Project Dialog */}
<Modal
isOpen={showAddDialog}
onClose={() => {
setShowAddDialog(false);
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
setDetectedBranch(null);
setShowValidationErrors(false);
}}
size="lg"
>
<ModalHeader title="Add New Project" icon={<Plus className="w-5 h-5" />} />
<ModalBody>
<div className="space-y-8">
{/* Project Info Section */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-2 border-b border-border-primary">
<Folder className="w-5 h-5 text-interactive" />
<h3 className="text-heading-3 font-semibold text-text-primary">Project Information</h3>
</div>
<FieldWithTooltip
label="Project Name"
tooltip="A descriptive name for your project that will appear in the project selector."
required
>
<EnhancedInput
{showAddDialog && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-gray-800 rounded-lg p-6 w-96 relative">
<button
onClick={() => {
setShowAddDialog(false);
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
setDetectedBranch(null);
}}
className="absolute top-4 right-4 text-gray-400 hover:text-gray-200 transition-colors"
title="Close"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<h3 className="text-lg font-semibold text-gray-200 mb-4 pr-8">Add New Project</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-300 mb-1">
Project Name
</label>
<input
type="text"
value={newProject.name}
onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="My Project"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-300 mb-1">
Repository Path
</label>
<div className="flex gap-2">
<input
type="text"
value={newProject.name}
value={newProject.path}
onChange={(e) => {
setNewProject({ ...newProject, name: e.target.value });
if (showValidationErrors) setShowValidationErrors(false);
setNewProject({ ...newProject, path: e.target.value });
detectCurrentBranch(e.target.value);
}}
placeholder="Enter project name"
size="lg"
fullWidth
required
showRequiredIndicator={showValidationErrors}
className="flex-1 px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="/path/to/repository"
/>
</FieldWithTooltip>
<FieldWithTooltip
label="Repository Path"
tooltip="Path to your git repository. This is where Crystal will create worktrees for parallel development."
required
>
<div className="space-y-3">
<EnhancedInput
type="text"
value={newProject.path}
onChange={(e) => {
setNewProject({ ...newProject, path: e.target.value });
detectCurrentBranch(e.target.value);
if (showValidationErrors) setShowValidationErrors(false);
}}
placeholder="/path/to/your/repository"
size="lg"
fullWidth
required
showRequiredIndicator={showValidationErrors}
/>
<div className="flex justify-end">
<Button
type="button"
onClick={async () => {
const result = await API.dialog.openDirectory({
title: 'Select Repository Directory',
buttonLabel: 'Select',
});
if (result.success && result.data) {
setNewProject({ ...newProject, path: result.data });
detectCurrentBranch(result.data);
}
}}
variant="secondary"
size="sm"
>
Browse
</Button>
</div>
</div>
</FieldWithTooltip>
<button
type="button"
onClick={async () => {
const result = await API.dialog.openDirectory({
title: 'Select Repository Directory',
buttonLabel: 'Select',
});
if (result.success && result.data) {
setNewProject({ ...newProject, path: result.data });
detectCurrentBranch(result.data);
}
}}
className="px-4 py-2 text-sm font-medium text-gray-300 bg-gray-700 border border-gray-600 rounded-md hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Browse
</button>
</div>
</div>
{/* Git Info Section */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-2 border-b border-border-primary">
<GitBranch className="w-5 h-5 text-interactive" />
<h3 className="text-heading-3 font-semibold text-text-primary">Git Information</h3>
<div>
<label className="block text-sm font-medium text-gray-300 mb-1">
Current Branch <span className="text-gray-500">(Auto-detected)</span>
</label>
<div className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200">
{detectedBranch || (newProject.path ? 'Detecting...' : 'Select a repository path first')}
</div>
<FieldWithTooltip
label="Main Branch"
tooltip="The main branch of your repository. Crystal will automatically detect this from your git configuration."
>
<Card variant="bordered" padding="md" className="text-text-secondary bg-surface-secondary">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4" />
<span className="font-mono">
{detectedBranch || (newProject.path ? 'Detecting...' : 'Select a repository path first')}
</span>
</div>
</Card>
</FieldWithTooltip>
<p className="text-xs text-gray-500 mt-1">
The main branch is automatically detected from the repository. This will be used for git operations.
</p>
</div>
{/* Optional Scripts Section */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-2 border-b border-border-primary">
<Play className="w-5 h-5 text-interactive" />
<h3 className="text-heading-3 font-semibold text-text-primary">Optional Scripts</h3>
</div>
<FieldWithTooltip
label="Build Script"
tooltip="Command to build your project. This runs automatically before each Claude Code session starts."
>
<EnhancedInput
type="text"
value={newProject.buildScript}
onChange={(e) => setNewProject({ ...newProject, buildScript: e.target.value })}
placeholder="pnpm build"
size="lg"
fullWidth
icon={<Hammer className="w-4 h-4" />}
/>
</FieldWithTooltip>
<div>
<label className="block text-sm font-medium text-gray-300 mb-1">
Build Script <span className="text-gray-500">(optional)</span>
</label>
<input
type="text"
value={newProject.buildScript}
onChange={(e) => setNewProject({ ...newProject, buildScript: e.target.value })}
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="e.g., pnpm build or npm run build"
/>
<p className="text-xs text-gray-500 mt-1">
This script will run automatically before each Claude Code session starts.
</p>
</div>
<FieldWithTooltip
label="Run Script"
tooltip="Command to start your development server. You can run this manually from the Terminal view during sessions."
>
<EnhancedInput
type="text"
value={newProject.runScript}
onChange={(e) => setNewProject({ ...newProject, runScript: e.target.value })}
placeholder="pnpm dev"
size="lg"
fullWidth
icon={<Play className="w-4 h-4" />}
/>
</FieldWithTooltip>
<div>
<label className="block text-sm font-medium text-gray-300 mb-1">
Run Script <span className="text-gray-500">(optional)</span>
</label>
<input
type="text"
value={newProject.runScript}
onChange={(e) => setNewProject({ ...newProject, runScript: e.target.value })}
className="w-full px-3 py-2 bg-gray-900 border border-gray-700 rounded-md text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="e.g., pnpm dev or npm start"
/>
<p className="text-xs text-gray-500 mt-1">
This script can be run manually from the Terminal view during sessions.
</p>
</div>
</div>
</ModalBody>
<ModalFooter>
<Button
onClick={() => {
setShowAddDialog(false);
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
setDetectedBranch(null);
setShowValidationErrors(false);
}}
variant="ghost"
size="md"
>
Cancel
</Button>
<Button
onClick={() => {
if (!newProject.name || !newProject.path) {
setShowValidationErrors(true);
return;
}
handleCreateProject();
}}
disabled={!newProject.name || !newProject.path}
variant="primary"
size="md"
className={(!newProject.name || !newProject.path) ? 'border-status-error border-2' : ''}
>
Create Project
</Button>
</ModalFooter>
</Modal>
<div className="mt-6 flex justify-end space-x-3">
<button
onClick={() => {
setShowAddDialog(false);
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
setDetectedBranch(null);
}}
className="px-4 py-2 text-gray-300 hover:text-gray-100 transition-colors"
>
Cancel
</button>
<button
onClick={handleCreateProject}
disabled={!newProject.name || !newProject.path}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Add Project
</button>
</div>
</div>
</div>
)}
{/* Project Settings Dialog */}
{settingsProject && (

View File

@ -1,13 +1,7 @@
import { useState, useEffect } from 'react';
import { Save, Trash2, FolderIcon, GitBranch, Settings, Code2, BrainCircuit } from 'lucide-react';
import { X, Save, Trash2 } from 'lucide-react';
import { API } from '../utils/api';
import type { Project } from '../types/project';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Input, Textarea } from './ui/Input';
import { Button } from './ui/Button';
import { EnhancedInput } from './ui/EnhancedInput';
import { FieldWithTooltip } from './ui/FieldWithTooltip';
import { Card } from './ui/Card';
interface ProjectSettingsProps {
project: Project;
@ -56,7 +50,7 @@ export default function ProjectSettings({ project, isOpen, onClose, onUpdate, on
setError(null);
try {
const updates: Partial<Project> = {
const response = await API.projects.update(project.id.toString(), {
name,
path,
system_prompt: systemPrompt || null,
@ -64,9 +58,7 @@ export default function ProjectSettings({ project, isOpen, onClose, onUpdate, on
build_script: buildScript || null,
open_ide_command: openIdeCommand || null,
worktree_folder: worktreeFolder || null
};
const response = await API.projects.update(project.id.toString(), updates);
});
if (!response.success) {
throw new Error(response.error || 'Failed to update project');
@ -97,340 +89,273 @@ export default function ProjectSettings({ project, isOpen, onClose, onUpdate, on
}
};
if (!isOpen) return null;
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl">
<ModalHeader
title="Project Settings"
icon={<Settings className="w-5 h-5" />}
onClose={onClose}
>
<div className="flex items-center gap-2">
<Button
onClick={handleSave}
disabled={isSaving || !name || !path}
variant="primary"
size="sm"
icon={<Save className="w-4 h-4" />}
loading={isSaving}
loadingText="Saving..."
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg w-full max-w-3xl max-h-[90vh] overflow-hidden flex flex-col border border-gray-200 dark:border-gray-700">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-xl font-semibold text-gray-900 dark:text-gray-200">Project Settings</h2>
<button
onClick={onClose}
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors"
>
Save Changes
</Button>
<X className="w-5 h-5" />
</button>
</div>
</ModalHeader>
<ModalBody>
{error && (
<div className="mb-6 p-4 bg-status-error/10 border border-status-error/30 rounded-lg text-status-error">
{error}
</div>
)}
<div className="space-y-8">
{/* Project Overview */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
<FolderIcon className="w-5 h-5 text-interactive" />
<div>
<h3 className="text-heading-3 font-semibold text-text-primary">Project Overview</h3>
<p className="text-sm text-text-tertiary">Basic project information and repository details</p>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{error && (
<div className="mb-4 p-3 bg-red-100 dark:bg-red-900 dark:bg-opacity-50 border border-red-300 dark:border-red-700 rounded-md text-red-700 dark:text-red-200">
{error}
</div>
<FieldWithTooltip
label="Project Name"
tooltip="Display name for this project in Crystal's interface."
>
<EnhancedInput
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="My Project"
size="lg"
fullWidth
/>
</FieldWithTooltip>
)}
<FieldWithTooltip
label="Repository Path"
tooltip="Local path to the git repository where Crystal will manage worktrees."
>
<div className="space-y-3">
<EnhancedInput
type="text"
value={path}
onChange={(e) => setPath(e.target.value)}
placeholder="/path/to/your/repository"
size="lg"
fullWidth
/>
<div className="flex justify-end">
<Button
type="button"
variant="secondary"
size="sm"
onClick={async () => {
const result = await API.dialog.openDirectory({
title: 'Select Repository Directory',
buttonLabel: 'Select',
});
if (result.success && result.data) {
setPath(result.data);
}
}}
>
Browse
</Button>
</div>
</div>
</FieldWithTooltip>
<FieldWithTooltip
label="Current Branch"
tooltip="The currently checked out branch in your repository. This is auto-detected."
>
<Card variant="bordered" padding="md" className="bg-surface-secondary">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4 text-text-tertiary" />
<span className="font-mono text-text-primary">
{currentBranch || 'Detecting...'}
</span>
<span className="ml-auto px-2 py-1 text-xs bg-surface-tertiary text-text-tertiary rounded">
Auto-detected
</span>
</div>
</Card>
</FieldWithTooltip>
</div>
{/* Worktree Configuration */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
<GitBranch className="w-5 h-5 text-interactive" />
<div>
<h3 className="text-heading-3 font-semibold text-text-primary">Worktree Configuration</h3>
<p className="text-sm text-text-tertiary">Settings for git worktree creation and management</p>
</div>
</div>
{/* Basic Information */}
<div>
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">Basic Information</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Project Name
</label>
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="My Project"
/>
</div>
<FieldWithTooltip
label="Worktree Folder"
tooltip="Directory where git worktrees will be created. Can be relative to the project or an absolute path."
>
<div className="space-y-3">
<EnhancedInput
type="text"
value={worktreeFolder}
onChange={(e) => setWorktreeFolder(e.target.value)}
placeholder="worktrees"
size="lg"
fullWidth
/>
<div className="flex justify-between items-center">
<div className="flex items-center gap-2">
<span className="px-2 py-1 text-xs bg-surface-tertiary text-text-tertiary rounded">
Default: worktrees/
</span>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Repository Path
</label>
<div className="flex gap-2">
<input
type="text"
value={path}
onChange={(e) => setPath(e.target.value)}
className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="/path/to/repository"
/>
<button
type="button"
onClick={async () => {
const result = await API.dialog.openDirectory({
title: 'Select Repository Directory',
buttonLabel: 'Select',
});
if (result.success && result.data) {
setPath(result.data);
}
}}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Browse
</button>
</div>
<Button
type="button"
variant="secondary"
size="sm"
onClick={async () => {
const result = await API.dialog.openDirectory({
title: 'Select Worktree Directory',
buttonLabel: 'Select',
});
if (result.success && result.data) {
setWorktreeFolder(result.data);
}
}}
>
Browse
</Button>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
The local path to the git repository for this project
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Current Branch (Auto-detected)
</label>
<div className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200">
{currentBranch || 'Detecting...'}
</div>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
This is the currently checked out branch in the project directory
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Worktree Folder
</label>
<div className="flex items-center gap-2">
<input
type="text"
value={worktreeFolder}
onChange={(e) => setWorktreeFolder(e.target.value)}
className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500"
placeholder="worktrees (default)"
/>
<button
type="button"
onClick={async () => {
const result = await API.dialog.openDirectory({
title: 'Select Worktree Directory',
buttonLabel: 'Select',
});
if (result.success && result.data) {
setWorktreeFolder(result.data);
}
}}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Browse
</button>
</div>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
The folder where git worktrees will be created. Can be a relative path (e.g., "worktrees") or an absolute path.
Leave empty to use the default "worktrees" folder inside the project directory.
</p>
</div>
</div>
</FieldWithTooltip>
</div>
</div>
{/* Session Behavior */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
<Code2 className="w-5 h-5 text-interactive" />
<div>
<h3 className="text-heading-3 font-semibold text-text-primary">Session Behavior</h3>
<p className="text-sm text-text-tertiary">Commands and scripts that run during Claude sessions</p>
{/* Project-Specific Settings */}
<div>
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-200 mb-4">Project-Specific Settings</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Project System Prompt
</label>
<textarea
value={systemPrompt}
onChange={(e) => setSystemPrompt(e.target.value)}
rows={6}
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
placeholder="Enter project-specific instructions for Claude..."
/>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
This prompt will be appended to the global system prompt for all sessions in this project
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Build Script
</label>
<textarea
value={buildScript}
onChange={(e) => setBuildScript(e.target.value)}
rows={3}
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
placeholder="npm install&#10;npm run build"
/>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
Commands to run once when creating a new worktree (e.g., install dependencies, build assets).
One command per line. These run in the worktree directory before Claude starts.
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Run Commands
</label>
<textarea
value={runScript}
onChange={(e) => setRunScript(e.target.value)}
rows={4}
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
placeholder="npm run dev&#10;npm test --watch"
/>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
Commands to run continuously while Claude is working (e.g., dev server, test watcher).
One command per line. Commands run sequentially - each must complete successfully before the next starts.
All commands are automatically stopped when the session ends. Output appears in the Terminal tab.
<br />
<span className="text-gray-700 dark:text-gray-600">Tip: To run multiple servers together, use a process manager like concurrently:</span>
<br />
<span className="font-mono text-gray-700 dark:text-gray-600">• npx concurrently "npm:server" "npm:client"</span>
<br />
<span className="font-mono text-gray-700 dark:text-gray-600">• npm run dev (if your package.json uses concurrently)</span>
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Open IDE Command
</label>
<input
type="text"
value={openIdeCommand}
onChange={(e) => setOpenIdeCommand(e.target.value)}
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 font-mono text-sm"
placeholder='open -na "PyCharm.app" --args "`pwd`"'
/>
<p className="mt-1 text-xs text-gray-600 dark:text-gray-500">
Command to open the worktree in your IDE. Use `pwd` to reference the worktree directory.
<br />
<span className="text-gray-700 dark:text-gray-600">Examples:</span>
<br />
<span className="font-mono text-gray-700 dark:text-gray-600">• code . (VS Code)</span>
<br />
<span className="font-mono text-gray-700 dark:text-gray-600">• cursor . (Cursor)</span>
<br />
<span className="text-gray-700 dark:text-gray-600 italic">Note: You may need to install the shell command separately for VS Code and Cursor</span>
<br />
<span className="font-mono text-gray-700 dark:text-gray-600">• open -na "PyCharm.app" --args "`pwd`" (PyCharm on macOS)</span>
</p>
</div>
</div>
</div>
<FieldWithTooltip
label="Open IDE Command"
tooltip="Command to open the worktree in your IDE. The command will be executed in the worktree directory."
>
<Input
value={openIdeCommand}
onChange={(e) => setOpenIdeCommand(e.target.value)}
placeholder='code .'
className="font-mono text-sm"
/>
<p className="mt-1 text-xs text-text-tertiary">
<span className="text-text-secondary font-semibold">Common Examples:</span>
<br />
<span className="font-mono text-text-secondary">• code . </span><span className="text-text-tertiary">(VS Code)</span>
<br />
<span className="font-mono text-text-secondary">• cursor . </span><span className="text-text-tertiary">(Cursor)</span>
<br />
<span className="font-mono text-text-secondary">• subl . </span><span className="text-text-tertiary">(Sublime Text)</span>
<br />
<span className="font-mono text-text-secondary">• idea . </span><span className="text-text-tertiary">(IntelliJ IDEA)</span>
<br />
<span className="font-mono text-text-secondary">• open -a "PyCharm" . </span><span className="text-text-tertiary">(PyCharm on macOS)</span>
<br />
<br />
<span className="text-text-secondary font-semibold">Troubleshooting:</span>
<br />
<span className="text-text-tertiary">• If the command is not found, use the full path (e.g., </span><span className="font-mono text-text-secondary">/usr/local/bin/code .</span><span className="text-text-tertiary">)</span>
<br />
<span className="text-text-tertiary">• For VS Code and Cursor, install the shell command from the Command Palette:</span>
<br />
<span className="text-text-tertiary ml-2">→ VS Code: "Shell Command: Install 'code' command in PATH"</span>
<br />
<span className="text-text-tertiary ml-2">→ Cursor: "Shell Command: Install 'cursor' command in PATH"</span>
<br />
<span className="text-text-tertiary">• The command runs with your shell's environment, inheriting your PATH</span>
</p>
</FieldWithTooltip>
<FieldWithTooltip
label="Build Script"
tooltip="Commands that run once when creating a new worktree. Use for setup tasks like installing dependencies."
>
<Card variant="bordered" padding="sm" className="bg-surface-secondary/50">
<Textarea
value={buildScript}
onChange={(e) => setBuildScript(e.target.value)}
rows={4}
placeholder="npm install"
className="font-mono text-sm bg-transparent border-0 p-3 focus:ring-0 resize-none"
fullWidth
/>
</Card>
</FieldWithTooltip>
<FieldWithTooltip
label="Run Commands"
tooltip="Commands that run continuously during sessions. Perfect for development servers and test watchers."
>
<Card variant="bordered" padding="sm" className="bg-surface-secondary/50">
<Textarea
value={runScript}
onChange={(e) => setRunScript(e.target.value)}
rows={4}
placeholder="npm run dev"
className="font-mono text-sm bg-transparent border-0 p-3 focus:ring-0 resize-none"
fullWidth
/>
</Card>
</FieldWithTooltip>
</div>
{/* AI Prompt Customization */}
<div className="space-y-6">
<div className="flex items-center gap-2 pb-3 border-b border-border-primary">
<BrainCircuit className="w-5 h-5 text-interactive" />
<div>
<h3 className="text-heading-3 font-semibold text-text-primary">AI Prompt Customization</h3>
<p className="text-sm text-text-tertiary">Project-specific instructions that enhance Claude's understanding</p>
</div>
</div>
<FieldWithTooltip
label="Project System Prompt"
tooltip="Custom instructions that will be added to every Claude session for this project. Use this to provide context about your codebase, coding standards, or preferred approaches."
>
<Card variant="bordered" padding="sm" className="bg-surface-secondary/50">
<Textarea
value={systemPrompt}
onChange={(e) => setSystemPrompt(e.target.value)}
rows={6}
placeholder="This project uses TypeScript and follows strict ESLint rules..."
className="font-mono text-sm bg-transparent border-0 p-3 focus:ring-0 resize-none"
fullWidth
/>
</Card>
</FieldWithTooltip>
</div>
{/* Danger Zone */}
<div className="border-t border-status-error/20 pt-6">
<div className="flex items-center gap-2 pb-3 border-b border-status-error/20">
<Trash2 className="w-5 h-5 text-status-error" />
<div>
<h3 className="text-heading-3 font-semibold text-status-error">Danger Zone</h3>
<p className="text-sm text-text-tertiary">Irreversible actions for this project</p>
</div>
</div>
<div className="mt-4">
{/* Danger Zone */}
<div className="border-t border-gray-200 dark:border-gray-700 pt-6">
<h3 className="text-lg font-medium text-red-600 dark:text-red-400 mb-4">Danger Zone</h3>
{!showDeleteConfirm ? (
<Button
<button
onClick={() => setShowDeleteConfirm(true)}
variant="danger"
icon={<Trash2 className="w-4 h-4" />}
className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors flex items-center space-x-2"
>
Delete Project
</Button>
<Trash2 className="w-4 h-4" />
<span>Delete Project</span>
</button>
) : (
<div className="space-y-4">
<Card variant="bordered" padding="md" className="bg-status-error/5 border-status-error/20">
<p className="text-sm text-text-secondary mb-3">
Are you sure you want to delete this project? This action cannot be undone and will remove all project data from Crystal.
</p>
<div className="flex space-x-3">
<Button
onClick={handleDelete}
variant="danger"
size="sm"
>
Yes, Delete Project
</Button>
<Button
onClick={() => setShowDeleteConfirm(false)}
variant="secondary"
size="sm"
>
Cancel
</Button>
</div>
</Card>
<div className="space-y-3">
<p className="text-sm text-gray-700 dark:text-gray-300">
Are you sure you want to delete this project? This action cannot be undone.
</p>
<div className="flex space-x-3">
<button
onClick={handleDelete}
className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors"
>
Yes, Delete Project
</button>
<button
onClick={() => setShowDeleteConfirm(false)}
className="px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-md transition-colors"
>
Cancel
</button>
</div>
</div>
)}
</div>
</div>
</div>
</ModalBody>
<ModalFooter>
<Button
onClick={onClose}
variant="ghost"
size="md"
>
Cancel
</Button>
<Button
onClick={handleSave}
disabled={isSaving || !name || !path}
variant="primary"
size="md"
icon={<Save className="w-4 h-4" />}
loading={isSaving}
loadingText="Saving..."
>
Save Changes
</Button>
</ModalFooter>
</Modal>
{/* Footer */}
<div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700">
<button
onClick={onClose}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
>
Cancel
</button>
<button
onClick={handleSave}
disabled={isSaving || !name || !path}
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center space-x-2"
>
<Save className="w-4 h-4" />
<span>{isSaving ? 'Saving...' : 'Save Changes'}</span>
</button>
</div>
</div>
</div>
);
}

View File

@ -10,7 +10,7 @@ import { EmptyState } from './EmptyState';
import { LoadingSpinner } from './LoadingSpinner';
import { API } from '../utils/api';
import type { Session } from '../types/session';
import type { Project, CreateProjectRequest } from '../types/project';
import type { Project } from '../types/project';
interface ProjectWithSessions extends Project {
sessions: Session[];
@ -26,7 +26,7 @@ export function ProjectTreeView() {
const [showProjectSettings, setShowProjectSettings] = useState(false);
const [selectedProjectForSettings, setSelectedProjectForSettings] = useState<Project | null>(null);
const [showAddProjectDialog, setShowAddProjectDialog] = useState(false);
const [newProject, setNewProject] = useState<CreateProjectRequest>({ name: '', path: '', buildScript: '', runScript: '' });
const [newProject, setNewProject] = useState({ name: '', path: '', buildScript: '', runScript: '' });
const [hasPendingUpdates, setHasPendingUpdates] = useState(false);
const activeSessionId = useSessionStore((state) => state.activeSessionId);
const [showMainBranchWarning, setShowMainBranchWarning] = useState(false);
@ -251,11 +251,11 @@ export function ProjectTreeView() {
error: response.error || 'Unknown error occurred'
});
}
} catch (error: unknown) {
} catch (error: any) {
console.error('Error handling project click:', error);
showError({
title: 'Failed to open main repository session',
error: error instanceof Error ? error.message : 'Unknown error occurred'
error: error.message || 'Unknown error occurred'
});
}
};
@ -284,7 +284,7 @@ export function ProjectTreeView() {
if (!newProject.name || !newProject.path) return;
try {
const response = await API.projects.create({ ...newProject, active: false });
const response = await API.projects.create(newProject);
if (!response.success) {
showError({
@ -301,12 +301,12 @@ export function ProjectTreeView() {
// Just reload the projects list
loadProjectsWithSessions();
} catch (error: unknown) {
} catch (error: any) {
console.error('Failed to create project:', error);
showError({
title: 'Failed to Create Project',
error: error instanceof Error ? error.message : 'An error occurred while creating the project.',
details: error instanceof Error && error.stack ? error.stack : String(error)
error: error.message || 'An error occurred while creating the project.',
details: error.stack || error.toString()
});
}
};
@ -342,21 +342,21 @@ export function ProjectTreeView() {
return (
<div key={project.id}>
<div
className="group flex items-center space-x-1 px-2 py-1.5 rounded cursor-pointer transition-colors hover:bg-surface-hover"
className="group flex items-center space-x-1 px-2 py-1.5 rounded cursor-pointer transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
>
<button
onClick={(e) => {
e.stopPropagation();
toggleProject(project.id);
}}
className="p-0.5 hover:bg-surface-hover rounded transition-colors"
className="p-0.5 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
disabled={sessionCount === 0}
>
{sessionCount > 0 ? (
isExpanded ? (
<ChevronDown className="w-3 h-3 text-text-tertiary" />
<ChevronDown className="w-3 h-3 text-gray-600 dark:text-gray-400" />
) : (
<ChevronRight className="w-3 h-3 text-text-tertiary" />
<ChevronRight className="w-3 h-3 text-gray-600 dark:text-gray-400" />
)
) : (
<div className="w-3 h-3" />
@ -368,11 +368,11 @@ export function ProjectTreeView() {
onClick={() => handleProjectClick(project)}
>
{isExpanded ? (
<FolderOpen className="w-4 h-4 text-interactive flex-shrink-0" />
<FolderOpen className="w-4 h-4 text-blue-600 dark:text-blue-400 flex-shrink-0" />
) : (
<Folder className="w-4 h-4 text-text-tertiary flex-shrink-0" />
<Folder className="w-4 h-4 text-gray-600 dark:text-gray-400 flex-shrink-0" />
)}
<span className="text-sm font-medium text-text-primary truncate text-left">
<span className="text-sm font-medium text-gray-800 dark:text-gray-200 truncate text-left">
{project.name}
</span>
</div>
@ -382,14 +382,14 @@ export function ProjectTreeView() {
e.stopPropagation();
handleCreateSession(project);
}}
className={`relative p-1 hover:bg-surface-hover rounded transition-colors group/tooltip ${
className={`relative p-1 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors group/tooltip ${
sessionCount === 0 ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
}`}
>
<Plus className="w-4 h-4 text-text-tertiary hover:text-text-primary" />
<span className="absolute left-1/2 -translate-x-1/2 bottom-full mb-2 px-2 py-1 text-xs text-white bg-surface-tertiary rounded whitespace-nowrap opacity-0 invisible group-hover/tooltip:opacity-100 group-hover/tooltip:visible transition-all duration-200 pointer-events-none z-50">
<Plus className="w-4 h-4 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200" />
<span className="absolute left-1/2 -translate-x-1/2 bottom-full mb-2 px-2 py-1 text-xs text-white bg-gray-800 dark:bg-gray-700 rounded whitespace-nowrap opacity-0 invisible group-hover/tooltip:opacity-100 group-hover/tooltip:visible transition-all duration-200 pointer-events-none z-50">
Create new session
<span className="absolute left-1/2 -translate-x-1/2 top-full w-0 h-0 border-4 border-transparent border-t-surface-tertiary"></span>
<span className="absolute left-1/2 -translate-x-1/2 top-full w-0 h-0 border-4 border-transparent border-t-gray-800 dark:border-t-gray-700"></span>
</span>
</button>
@ -399,10 +399,10 @@ export function ProjectTreeView() {
setSelectedProjectForSettings(project);
setShowProjectSettings(true);
}}
className="p-1 hover:bg-surface-hover rounded transition-colors opacity-0 group-hover:opacity-100"
className="p-1 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors opacity-0 group-hover:opacity-100"
title="Project settings"
>
<Settings className="w-3 h-3 text-text-tertiary hover:text-text-primary" />
<Settings className="w-3 h-3 text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200" />
</button>
</div>
@ -423,7 +423,7 @@ export function ProjectTreeView() {
<button
onClick={() => setShowAddProjectDialog(true)}
className="w-full mt-2 px-2 py-1.5 text-sm text-text-secondary hover:text-text-primary hover:bg-surface-hover rounded transition-colors flex items-center justify-center space-x-2"
className="w-full mt-2 px-2 py-1.5 text-sm text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors flex items-center justify-center space-x-2"
>
<Plus className="w-4 h-4" />
<span>New Project</span>
@ -469,26 +469,26 @@ export function ProjectTreeView() {
{/* Add Project Dialog */}
{showAddProjectDialog && (
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50">
<div className="bg-surface-primary rounded-lg p-6 w-96 shadow-xl border border-border-primary">
<h3 className="text-lg font-semibold text-text-primary mb-4">Add New Project</h3>
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 w-96 shadow-xl border border-gray-200 dark:border-gray-700">
<h3 className="text-lg font-semibold text-gray-900 dark:text-gray-200 mb-4">Add New Project</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Project Name
</label>
<input
type="text"
value={newProject.name}
onChange={(e) => setNewProject({ ...newProject, name: e.target.value })}
className="w-full px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
placeholder="My Project"
/>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Repository Path
</label>
<div className="flex gap-2">
@ -499,7 +499,7 @@ export function ProjectTreeView() {
setNewProject({ ...newProject, path: e.target.value });
detectCurrentBranch(e.target.value);
}}
className="flex-1 px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
className="flex-1 px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
placeholder="/path/to/repository"
/>
<button
@ -514,7 +514,7 @@ export function ProjectTreeView() {
detectCurrentBranch(result.data);
}
}}
className="px-4 py-2 text-sm font-medium text-text-secondary bg-surface-tertiary border border-border-primary rounded-md hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-interactive"
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
Browse
</button>
@ -522,45 +522,45 @@ export function ProjectTreeView() {
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
Current Branch <span className="text-text-tertiary">(Auto-detected)</span>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Current Branch <span className="text-gray-500">(Auto-detected)</span>
</label>
<div className="w-full px-3 py-2 bg-surface-tertiary border border-border-primary rounded-md text-text-secondary">
<div className="w-full px-3 py-2 bg-gray-100 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200">
{detectedBranchForNewProject || (newProject.path ? 'Detecting...' : 'Select a repository path first')}
</div>
<p className="text-xs text-text-tertiary mt-1">
<p className="text-xs text-gray-500 mt-1">
The main branch is automatically detected from the repository. This will be used for git operations.
</p>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
Build Script <span className="text-text-tertiary">(optional)</span>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Build Script <span className="text-gray-500 dark:text-gray-500">(optional)</span>
</label>
<input
type="text"
value={newProject.buildScript}
onChange={(e) => setNewProject({ ...newProject, buildScript: e.target.value })}
className="w-full px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
placeholder="e.g., pnpm build or npm run build"
/>
<p className="text-xs text-text-tertiary mt-1">
<p className="text-xs text-gray-500 mt-1">
This script will run automatically before each Claude Code session starts.
</p>
</div>
<div>
<label className="block text-sm font-medium text-text-secondary mb-1">
Run Script <span className="text-text-tertiary">(optional)</span>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Run Script <span className="text-gray-500 dark:text-gray-500">(optional)</span>
</label>
<input
type="text"
value={newProject.runScript}
onChange={(e) => setNewProject({ ...newProject, runScript: e.target.value })}
className="w-full px-3 py-2 bg-surface-secondary border border-border-primary rounded-md text-text-primary focus:outline-none focus:border-interactive focus:ring-1 focus:ring-interactive placeholder-text-tertiary"
className="w-full px-3 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-md text-gray-900 dark:text-gray-200 focus:outline-none focus:border-blue-500 placeholder-gray-500 dark:placeholder-gray-400"
placeholder="e.g., pnpm dev or npm start"
/>
<p className="text-xs text-text-tertiary mt-1">
<p className="text-xs text-gray-500 mt-1">
This script can be run manually from the Terminal view during sessions.
</p>
</div>
@ -572,14 +572,14 @@ export function ProjectTreeView() {
setShowAddProjectDialog(false);
setNewProject({ name: '', path: '', buildScript: '', runScript: '' });
}}
className="px-4 py-2 text-text-secondary hover:text-text-primary transition-colors"
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
>
Cancel
</button>
<button
onClick={handleCreateProject}
disabled={!newProject.name || !newProject.path}
className="px-4 py-2 bg-interactive hover:bg-interactive-hover text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
Add Project
</button>

View File

@ -1,388 +0,0 @@
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { API } from '../utils/api';
import { useSessionStore } from '../stores/sessionStore';
import { Session } from '../types/session';
import { PanelTabBar } from './panels/PanelTabBar';
import { PanelContainer } from './panels/PanelContainer';
import { usePanelStore } from '../stores/panelStore';
import { panelApi } from '../services/panelApi';
import { ToolPanel, ToolPanelType } from '../../../shared/types/panels';
import { SessionProvider } from '../contexts/SessionContext';
interface ProjectViewProps {
projectId: number;
projectName: string;
onGitPull: () => void;
onGitPush: () => void;
isMerging: boolean;
}
export const ProjectView: React.FC<ProjectViewProps> = ({
projectId,
projectName,
onGitPull,
onGitPush,
isMerging
}) => {
const [mainRepoSessionId, setMainRepoSessionId] = useState<string | null>(null);
const [mainRepoSession, setMainRepoSession] = useState<Session | null>(null);
const [isLoadingSession, setIsLoadingSession] = useState(false);
// Panel store state and actions
const {
panels,
activePanels,
setPanels,
setActivePanel: setActivePanelInStore,
addPanel,
removePanel
} = usePanelStore();
// Load panels when main repo session changes and ensure dashboard panel exists
useEffect(() => {
if (mainRepoSessionId) {
console.log('[ProjectView] Loading panels for project session:', mainRepoSessionId);
panelApi.loadPanelsForSession(mainRepoSessionId).then(async (loadedPanels) => {
console.log('[ProjectView] Loaded panels:', loadedPanels);
// Check if dashboard panel exists, create if not
const dashboardPanel = loadedPanels.find(p => p.type === 'dashboard');
const setupTasksPanel = loadedPanels.find(p => p.type === 'setup-tasks');
let panelsCreated = false;
if (!dashboardPanel) {
console.log('[ProjectView] Creating dashboard panel for project');
await panelApi.createPanel({
sessionId: mainRepoSessionId,
type: 'dashboard',
title: 'Dashboard',
metadata: { permanent: true }
});
panelsCreated = true;
}
if (!setupTasksPanel) {
console.log('[ProjectView] Creating setup-tasks panel for project');
await panelApi.createPanel({
sessionId: mainRepoSessionId,
type: 'setup-tasks',
title: 'Setup',
metadata: { permanent: true }
});
panelsCreated = true;
}
// Reload panels if any were created
const finalPanels = panelsCreated
? await panelApi.loadPanelsForSession(mainRepoSessionId)
: loadedPanels;
setPanels(mainRepoSessionId, finalPanels);
// Determine which panel should be active
const activePanel = await panelApi.getActivePanel(mainRepoSessionId);
const setupPanel = finalPanels.find(p => p.type === 'setup-tasks');
const dashPanel = finalPanels.find(p => p.type === 'dashboard');
if (!activePanel) {
// No active panel - prioritize setup-tasks if it exists, otherwise dashboard
const panelToActivate = setupPanel || dashPanel;
if (panelToActivate) {
setActivePanelInStore(mainRepoSessionId, panelToActivate.id);
await panelApi.setActivePanel(mainRepoSessionId, panelToActivate.id);
}
} else {
// There's already an active panel, use it
setActivePanelInStore(mainRepoSessionId, activePanel.id);
}
});
}
}, [mainRepoSessionId, setPanels, setActivePanelInStore]);
// Get panels for current main repo session
const sessionPanels = useMemo(
() => panels[mainRepoSessionId || ''] || [],
[panels, mainRepoSessionId]
);
const currentActivePanel = useMemo(
() => sessionPanels.find(p => p.id === activePanels[mainRepoSessionId || '']),
[sessionPanels, activePanels, mainRepoSessionId]
);
// Panel event handlers
const handlePanelSelect = useCallback(
async (panel: ToolPanel) => {
if (!mainRepoSessionId) return;
setActivePanelInStore(mainRepoSessionId, panel.id);
await panelApi.setActivePanel(mainRepoSessionId, panel.id);
},
[mainRepoSessionId, setActivePanelInStore]
);
const handlePanelClose = useCallback(
async (panel: ToolPanel) => {
if (!mainRepoSessionId) return;
// Don't allow closing dashboard or setup-tasks panels
if (panel.type === 'dashboard' || panel.type === 'setup-tasks') {
console.log('[ProjectView] Cannot close permanent panel:', panel.type);
return;
}
// Find next panel to activate
const panelIndex = sessionPanels.findIndex(p => p.id === panel.id);
let nextPanel = sessionPanels[panelIndex + 1] || sessionPanels[panelIndex - 1];
// If no other panel or the next panel is the same, fall back to dashboard
if (!nextPanel || nextPanel.id === panel.id) {
nextPanel = sessionPanels.find(p => p.type === 'dashboard') || sessionPanels[0];
}
// Remove from store first for immediate UI update
removePanel(mainRepoSessionId, panel.id);
// Set next active panel (should always have dashboard)
if (nextPanel) {
setActivePanelInStore(mainRepoSessionId, nextPanel.id);
await panelApi.setActivePanel(mainRepoSessionId, nextPanel.id);
}
// Delete on backend
await panelApi.deletePanel(panel.id);
},
[mainRepoSessionId, sessionPanels, removePanel, setActivePanelInStore]
);
const handlePanelCreate = useCallback(
async (type: ToolPanelType) => {
if (!mainRepoSessionId) return;
const newPanel = await panelApi.createPanel({
sessionId: mainRepoSessionId,
type
});
// Immediately add the panel and set it as active
// The panel:created event will also fire, but addPanel checks for duplicates
addPanel(newPanel);
setActivePanelInStore(mainRepoSessionId, newPanel.id);
},
[mainRepoSessionId, addPanel, setActivePanelInStore]
);
// Wrapped git operations
const handleGitPull = useCallback(() => {
// Find or create a Claude panel
const claudePanel = sessionPanels.find(p => p.type === 'claude');
if (claudePanel) {
handlePanelSelect(claudePanel);
} else {
handlePanelCreate('claude');
}
onGitPull();
}, [onGitPull, sessionPanels, handlePanelSelect, handlePanelCreate]);
const handleGitPush = useCallback(() => {
// Find or create a Claude panel
const claudePanel = sessionPanels.find(p => p.type === 'claude');
if (claudePanel) {
handlePanelSelect(claudePanel);
} else {
handlePanelCreate('claude');
}
onGitPush();
}, [onGitPush, sessionPanels, handlePanelSelect, handlePanelCreate]);
// We don't need terminal handling or the hook for now, as panels handle their own terminals
// Debug logging
useEffect(() => {
console.log('[ProjectView] Session state:', {
mainRepoSessionId,
mainRepoSession: mainRepoSession?.id,
activePanelType: currentActivePanel?.type,
activeSessionInStore: useSessionStore.getState().activeSessionId
});
}, [mainRepoSessionId, mainRepoSession, currentActivePanel]);
// Get or create main repo session when panels are needed
useEffect(() => {
// Create main repo session when component mounts to support panels
const getMainRepoSession = async () => {
setIsLoadingSession(true);
try {
const response = await API.sessions.getOrCreateMainRepoSession(projectId);
if (response.success && response.data) {
setMainRepoSessionId(response.data.id);
setMainRepoSession(response.data);
// Subscribe to session updates
const sessions = useSessionStore.getState().sessions;
const mainSession = sessions.find(s => s.id === response.data.id);
if (mainSession) {
setMainRepoSession(mainSession);
}
// Set as active session
useSessionStore.getState().setActiveSession(response.data.id);
}
} catch (error) {
console.error('Failed to get main repo session:', error);
} finally {
setIsLoadingSession(false);
}
};
getMainRepoSession();
}, [projectId]);
// Subscribe to session updates - optimized to check for actual changes
useEffect(() => {
if (!mainRepoSessionId) return;
let previousSession = useSessionStore.getState().sessions.find(s => s.id === mainRepoSessionId);
const unsubscribe = useSessionStore.subscribe((state) => {
const session = state.sessions.find(s => s.id === mainRepoSessionId);
// Only update if session actually changed
if (session && session !== previousSession) {
previousSession = session;
setMainRepoSession(session);
}
});
return unsubscribe;
}, [mainRepoSessionId]);
// Listen for panel updates from the backend
useEffect(() => {
if (!mainRepoSessionId) return;
// Handle panel creation events (for auto-created panels like logs)
const handlePanelCreated = (panel: ToolPanel) => {
console.log('[ProjectView] Received panel:created event:', panel);
// Only add if it's for the current session
if (panel.sessionId === mainRepoSessionId) {
// The store's addPanel now checks for duplicates, so we can safely call it
addPanel(panel);
}
};
// Listen for panel events
const unsubscribeCreated = window.electronAPI?.events?.onPanelCreated?.(handlePanelCreated);
// Cleanup
return () => {
unsubscribeCreated?.();
};
}, [mainRepoSessionId, addPanel]);
// We don't need Stravu connection status here anymore as it's handled in panels
return (
<div className="flex-1 flex flex-col overflow-hidden bg-bg-primary">
{/* Project Header */}
<div className="bg-surface-primary border-b border-border-primary px-4 py-3 flex-shrink-0">
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0 relative">
<h2 className="font-bold text-xl text-text-primary truncate">
{projectName}
</h2>
{/* Git Actions for Main Project */}
<div className="flex flex-wrap items-center gap-2 mt-2">
<div className="flex flex-wrap items-center gap-2 relative z-20">
<div className="group relative">
<button
onClick={handleGitPull}
disabled={isMerging}
className={`px-3 py-1.5 rounded-full border transition-all flex items-center space-x-2 ${
isMerging
? 'bg-surface-secondary border-border-secondary text-text-disabled cursor-not-allowed'
: 'bg-surface-secondary border-status-info text-status-info hover:bg-status-info/10 hover:border-status-info/70'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 17l-4 4m0 0l-4-4m4 4V3" />
</svg>
<span className="text-sm font-medium">{isMerging ? 'Pulling...' : 'Pull'}</span>
</button>
</div>
<div className="group relative">
<button
onClick={handleGitPush}
disabled={isMerging}
className={`px-3 py-1.5 rounded-full border transition-all flex items-center space-x-2 ${
isMerging
? 'bg-surface-secondary border-border-secondary text-text-disabled cursor-not-allowed'
: 'bg-surface-secondary border-status-success text-status-success hover:bg-status-success/10 hover:border-status-success/70'
}`}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7l4-4m0 0l4 4m-4-4v18" />
</svg>
<span className="text-sm font-medium">{isMerging ? 'Pushing...' : 'Push'}</span>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Tool Panel Bar (Dashboard is now part of the panel system) */}
{mainRepoSessionId && (
<SessionProvider session={mainRepoSession} projectName={projectName}>
<PanelTabBar
panels={sessionPanels}
activePanel={currentActivePanel}
onPanelSelect={handlePanelSelect}
onPanelClose={handlePanelClose}
onPanelCreate={handlePanelCreate}
context="project"
/>
</SessionProvider>
)}
{/* Content Area */}
<div className="flex-1 flex relative min-h-0">
<div className="flex-1 relative">
{isLoadingSession || !mainRepoSessionId ? (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-interactive mx-auto mb-4"></div>
<p className="text-text-secondary">Loading panels...</p>
</div>
</div>
) : sessionPanels.length > 0 && currentActivePanel ? (
<SessionProvider session={mainRepoSession} projectName={projectName}>
{sessionPanels.map(panel => (
<div
key={panel.id}
className="absolute inset-0"
style={{ display: panel.id === currentActivePanel.id ? 'block' : 'none' }}
>
<PanelContainer
panel={panel}
isActive={panel.id === currentActivePanel.id}
isMainRepo={!!mainRepoSession?.isMainRepo}
/>
</div>
))}
</SessionProvider>
) : (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<p className="text-text-secondary mb-4">Loading dashboard...</p>
<p className="text-text-tertiary text-sm">Setting up project panels</p>
</div>
</div>
)}
</div>
</div>
</div>
);
};

View File

@ -1,14 +1,11 @@
import { Copy, Check } from 'lucide-react';
import { X, Copy, Check } from 'lucide-react';
import { useState } from 'react';
import { formatDistanceToNow } from '../utils/formatters';
import { formatDuration, getTimeDifference, isValidTimestamp, parseTimestamp } from '../utils/timestampUtils';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { IconButton } from './ui/IconButton';
interface PromptMarker {
id: number;
session_id?: string;
panel_id?: string;
session_id: string;
prompt_text: string;
output_index: number;
output_line?: number;
@ -56,44 +53,72 @@ export function PromptDetailModal({ prompt, promptIndex, onClose }: PromptDetail
}
};
// No need for manual escape handling - Modal component handles it
// Close on escape key
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Escape') {
onClose();
}
};
return (
<Modal isOpen={true} onClose={onClose} size="lg" showCloseButton={false}>
<ModalHeader onClose={onClose}>
<div className="flex items-center justify-between flex-1 pr-2">
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
onClick={onClose}
onKeyDown={handleKeyDown}
>
<div
className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[80vh] flex flex-col"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
<div className="flex items-center space-x-3">
<h2 className="text-lg font-semibold text-text-primary">
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
Prompt #{promptIndex + 1}
</h2>
<div className="flex items-center space-x-2 text-sm text-text-tertiary">
<div className="flex items-center space-x-2 text-sm text-gray-500 dark:text-gray-400">
<span>{formatDistanceToNow(parseTimestamp(prompt.timestamp))} ago</span>
<span className="text-text-tertiary">•</span>
<span className="text-gray-400">•</span>
<span className="font-medium">{calculateDuration()}</span>
</div>
</div>
<IconButton
onClick={handleCopy}
variant="ghost"
size="sm"
aria-label="Copy prompt"
icon={copied ? <Check className="h-4 w-4 text-status-success" /> : <Copy className="h-4 w-4" />}
/>
<div className="flex items-center space-x-2">
<button
onClick={handleCopy}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
title="Copy prompt"
>
{copied ? (
<Check className="h-4 w-4 text-green-500" />
) : (
<Copy className="h-4 w-4 text-gray-500 dark:text-gray-400" />
)}
</button>
<button
onClick={onClose}
className="p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-md transition-colors"
title="Close"
>
<X className="h-4 w-4 text-gray-500 dark:text-gray-400" />
</button>
</div>
</div>
</ModalHeader>
<ModalBody>
<pre className="whitespace-pre-wrap font-mono text-sm text-text-primary bg-surface-primary p-4 rounded-md border border-border-secondary">
{prompt.prompt_text}
</pre>
</ModalBody>
<ModalFooter>
<div className="flex items-center justify-between w-full text-sm text-text-tertiary">
<span>Press ESC to close</span>
<span>Double-click any prompt to view details</span>
{/* Content */}
<div className="flex-1 overflow-y-auto p-4">
<pre className="whitespace-pre-wrap font-mono text-sm text-gray-800 dark:text-gray-200 bg-gray-50 dark:bg-gray-900 p-4 rounded-md">
{prompt.prompt_text}
</pre>
</div>
</ModalFooter>
</Modal>
{/* Footer */}
<div className="p-4 border-t border-gray-200 dark:border-gray-700 text-sm text-gray-500 dark:text-gray-400">
<div className="flex items-center justify-between">
<span>Press ESC to close</span>
<span>Double-click any prompt to view details</span>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,10 +1,6 @@
import { useEffect, useState } from 'react';
import { useSessionStore } from '../stores/sessionStore';
import { API } from '../utils/api';
import { Button } from './ui/Button';
import { Input } from './ui/Input';
import { Card } from './ui/Card';
import { Search, Copy } from 'lucide-react';
interface PromptHistoryItem {
id: string;
@ -100,15 +96,15 @@ export function PromptHistory() {
switch (status) {
case 'completed':
case 'stopped':
return 'text-status-success bg-status-success/10';
return 'text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/20';
case 'error':
return 'text-status-error bg-status-error/10';
return 'text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20';
case 'running':
return 'text-interactive bg-interactive/10';
return 'text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20';
case 'waiting':
return 'text-status-warning bg-status-warning/10';
return 'text-yellow-600 dark:text-yellow-400 bg-yellow-100 dark:bg-yellow-900/20';
default:
return 'text-text-tertiary bg-surface-tertiary';
return 'text-gray-600 dark:text-gray-400 bg-gray-200 dark:bg-gray-700';
}
};
@ -117,20 +113,31 @@ export function PromptHistory() {
};
return (
<div className="h-full flex flex-col bg-bg-primary overflow-hidden">
<div className="h-full flex flex-col bg-white dark:bg-gray-900 overflow-hidden">
{/* Header */}
<div className="border-b border-border-primary p-6 flex-shrink-0">
<h1 className="text-2xl font-bold text-text-primary mb-4">Prompt History</h1>
<div className="border-b border-gray-200 dark:border-gray-700 p-6 flex-shrink-0">
<h1 className="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-4">Prompt History</h1>
<div className="relative">
<Input
<input
type="text"
placeholder="Search prompts or session names..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
fullWidth
className="pl-10"
className="w-full px-4 py-2 pl-10 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
/>
<Search className="absolute left-3 top-2.5 h-5 w-5 text-text-tertiary pointer-events-none" />
<svg
className="absolute left-3 top-2.5 h-5 w-5 text-gray-500 dark:text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</div>
</div>
@ -138,15 +145,15 @@ export function PromptHistory() {
<div className="flex-1 overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center h-32">
<div className="text-text-secondary">Loading prompt history...</div>
<div className="text-gray-600 dark:text-gray-400">Loading prompt history...</div>
</div>
) : filteredPrompts.length === 0 ? (
<div className="flex items-center justify-center h-32">
<div className="text-center text-text-secondary">
<div className="text-center text-gray-600 dark:text-gray-400">
<div className="text-lg mb-2">
{searchTerm ? 'No prompts found' : 'No prompt history yet'}
</div>
<div className="text-sm text-text-tertiary">
<div className="text-sm">
{searchTerm
? 'Try adjusting your search terms'
: 'Create a session to start building your prompt history'
@ -157,20 +164,19 @@ export function PromptHistory() {
) : (
<div className="p-6 space-y-4">
{filteredPrompts.map((promptItem) => (
<Card
<div
key={promptItem.id}
variant={selectedPromptId === promptItem.id ? 'interactive' : 'bordered'}
className={`cursor-pointer transition-all ${
className={`border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer ${
selectedPromptId === promptItem.id
? 'border-interactive bg-interactive/10'
: ''
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800'
}`}
onClick={() => handlePromptClick(promptItem)}
>
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-3 mb-2">
<h3 className="text-lg font-medium text-text-primary truncate">
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 truncate">
{promptItem.sessionName}
</h3>
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(promptItem.status)}`}>
@ -178,11 +184,11 @@ export function PromptHistory() {
</span>
</div>
<p className="text-text-secondary mb-3 leading-relaxed">
<p className="text-gray-700 dark:text-gray-300 mb-3 leading-relaxed">
{truncatePrompt(promptItem.prompt, 200)}
</p>
<div className="flex items-center justify-between text-sm text-text-tertiary">
<div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-400">
<span>
Created {new Date(promptItem.createdAt).toLocaleDateString()} at{' '}
{new Date(promptItem.createdAt).toLocaleTimeString()}
@ -191,40 +197,32 @@ export function PromptHistory() {
</div>
<div className="flex flex-col space-y-2 ml-4">
<Button
onClick={(e) => {
e.stopPropagation();
handleReusePrompt(promptItem);
}}
size="sm"
<button
onClick={() => handleReusePrompt(promptItem)}
className="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
>
Reuse
</Button>
<Button
onClick={(e) => {
e.stopPropagation();
navigator.clipboard.writeText(promptItem.prompt);
}}
variant="secondary"
size="sm"
</button>
<button
onClick={() => navigator.clipboard.writeText(promptItem.prompt)}
className="px-3 py-1 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 text-sm rounded-md hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
>
<Copy className="w-3 h-3 mr-1" />
Copy
</Button>
</button>
</div>
</div>
{promptItem.prompt.length > 200 && (
<details className="mt-3">
<summary className="cursor-pointer text-interactive-on-dark text-sm transition-colors">
<summary className="cursor-pointer text-blue-600 dark:text-blue-400 text-sm hover:text-blue-700 dark:hover:text-blue-300">
Show full prompt
</summary>
<p className="mt-2 text-text-secondary whitespace-pre-wrap">
<p className="mt-2 text-gray-700 dark:text-gray-300 whitespace-pre-wrap">
{promptItem.prompt}
</p>
</details>
)}
</Card>
</div>
))}
</div>
)}

View File

@ -1,11 +1,7 @@
import { useEffect, useState } from 'react';
import { useSessionStore } from '../stores/sessionStore';
import { API } from '../utils/api';
import { Search } from 'lucide-react';
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
import { Button } from './ui/Button';
import { Input } from './ui/Input';
import { Badge } from './ui/Badge';
import { X } from 'lucide-react';
interface PromptHistoryItem {
id: string;
@ -36,7 +32,18 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
}
}, [isOpen]);
// Modal component handles escape key automatically
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) {
onClose();
}
};
if (isOpen) {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}
}, [isOpen, onClose]);
const fetchPromptHistory = async () => {
try {
@ -118,19 +125,19 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
navigator.clipboard.writeText(prompt);
};
const getStatusVariant = (status: string): 'success' | 'error' | 'warning' | 'info' | 'default' => {
const getStatusColor = (status: string) => {
switch (status) {
case 'completed':
case 'stopped':
return 'success';
return 'text-green-600 dark:text-green-400 bg-green-100 dark:bg-green-900/20';
case 'error':
return 'error';
return 'text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20';
case 'running':
return 'info';
return 'text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20';
case 'waiting':
return 'warning';
return 'text-yellow-600 dark:text-yellow-400 bg-yellow-100 dark:bg-yellow-900/20';
default:
return 'default';
return 'text-gray-600 dark:text-gray-400 bg-gray-200 dark:bg-gray-700';
}
};
@ -138,37 +145,62 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
return prompt.length > maxLength ? prompt.substring(0, maxLength) + '...' : prompt;
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl" showCloseButton={false}>
<ModalHeader title="Prompt History" onClose={onClose} />
<div className="p-6 border-b border-border-primary">
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Search className="w-5 h-5 text-text-muted" />
</div>
<Input
type="text"
placeholder="Search prompts or session names..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="pl-10"
/>
</div>
</div>
if (!isOpen) return null;
<ModalBody className="p-6">
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={onClose}>
<div
className="bg-white dark:bg-gray-900 rounded-lg shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col m-4"
onClick={(e) => e.stopPropagation()}
>
{/* Header */}
<div className="border-b border-gray-200 dark:border-gray-700 p-6 flex-shrink-0">
<div className="flex items-center justify-between mb-4">
<h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">Prompt History</h2>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
>
<X className="w-6 h-6" />
</button>
</div>
<div className="relative">
<input
type="text"
placeholder="Search prompts or session names..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full px-4 py-2 pl-10 bg-gray-50 dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 placeholder-gray-500 dark:placeholder-gray-400"
/>
<svg
className="absolute left-3 top-2.5 h-5 w-5 text-gray-500 dark:text-gray-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
/>
</svg>
</div>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{loading ? (
<div className="flex items-center justify-center h-32">
<div className="text-text-secondary">Loading prompt history...</div>
<div className="text-gray-600 dark:text-gray-400">Loading prompt history...</div>
</div>
) : filteredPrompts.length === 0 ? (
<div className="flex items-center justify-center h-32">
<div className="text-center text-text-secondary">
<div className="text-center text-gray-600 dark:text-gray-400">
<div className="text-lg mb-2">
{searchTerm ? 'No prompts found' : 'No prompt history yet'}
</div>
<div className="text-sm text-text-tertiary">
<div className="text-sm">
{searchTerm
? 'Try adjusting your search terms'
: 'Create a session to start building your prompt history'
@ -181,29 +213,29 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
{filteredPrompts.map((promptItem) => (
<div
key={promptItem.id}
className={`border rounded-lg p-4 hover:shadow-md transition-all cursor-pointer ${
className={`border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer ${
selectedPromptId === promptItem.id
? 'border-interactive bg-interactive/10'
: 'border-border-primary bg-surface-secondary hover:bg-surface-tertiary'
? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
: 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800'
}`}
onClick={() => handlePromptClick(promptItem)}
>
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-3 mb-2">
<h3 className="text-lg font-medium text-text-primary truncate">
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 truncate">
{promptItem.sessionName}
</h3>
<Badge variant={getStatusVariant(promptItem.status)} size="sm">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(promptItem.status)}`}>
{promptItem.status}
</Badge>
</span>
</div>
<p className="text-text-secondary mb-3 leading-relaxed">
<p className="text-gray-700 dark:text-gray-300 mb-3 leading-relaxed">
{truncatePrompt(promptItem.prompt, 200)}
</p>
<div className="flex items-center justify-between text-sm text-text-tertiary">
<div className="flex items-center justify-between text-sm text-gray-600 dark:text-gray-400">
<span>
Created {new Date(promptItem.createdAt).toLocaleDateString()} at{' '}
{new Date(promptItem.createdAt).toLocaleTimeString()}
@ -212,29 +244,27 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
</div>
<div className="flex flex-col space-y-2 ml-4">
<Button
<button
onClick={(e) => handleReusePrompt(promptItem, e)}
variant="primary"
size="sm"
className="px-3 py-1 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 transition-colors"
>
Reuse
</Button>
<Button
</button>
<button
onClick={(e) => handleCopyPrompt(promptItem.prompt, e)}
variant="secondary"
size="sm"
className="px-3 py-1 bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200 text-sm rounded-md hover:bg-gray-300 dark:hover:bg-gray-600 transition-colors"
>
Copy
</Button>
</button>
</div>
</div>
{promptItem.prompt.length > 200 && (
<details className="mt-3">
<summary className="cursor-pointer text-interactive text-sm hover:text-interactive-hover">
<summary className="cursor-pointer text-blue-600 dark:text-blue-400 text-sm hover:text-blue-700 dark:hover:text-blue-300">
Show full prompt
</summary>
<p className="mt-2 text-text-secondary whitespace-pre-wrap">
<p className="mt-2 text-gray-700 dark:text-gray-300 whitespace-pre-wrap">
{promptItem.prompt}
</p>
</details>
@ -243,7 +273,8 @@ export function PromptHistoryModal({ isOpen, onClose }: PromptHistoryModalProps)
))}
</div>
)}
</ModalBody>
</Modal>
</div>
</div>
</div>
);
}

View File

@ -0,0 +1,258 @@
import { useEffect, useState } from 'react';
import { formatDistanceToNow } from '../utils/formatters';
import { formatDuration, getTimeDifference, isValidTimestamp, parseTimestamp } from '../utils/timestampUtils';
import { API } from '../utils/api';
import { useSessionStore } from '../stores/sessionStore';
import { PromptDetailModal } from './PromptDetailModal';
interface PromptMarker {
id: number;
session_id: string;
prompt_text: string;
output_index: number;
output_line?: number;
timestamp: string;
completion_timestamp?: string;
}
interface PromptNavigationProps {
sessionId: string;
onNavigateToPrompt: (marker: PromptMarker) => void;
}
export function PromptNavigation({ sessionId, onNavigateToPrompt }: PromptNavigationProps) {
const [prompts, setPrompts] = useState<PromptMarker[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [selectedPromptId, setSelectedPromptId] = useState<number | null>(null);
const [modalPrompt, setModalPrompt] = useState<{ prompt: PromptMarker; index: number } | null>(null);
const activeSession = useSessionStore((state) => state.sessions.find(s => s.id === sessionId));
const calculateDuration = (currentPrompt: PromptMarker, currentIndex: number): string => {
try {
const isLast = currentIndex === prompts.length - 1;
console.log('calculateDuration for prompt:', {
index: currentIndex,
isLast,
prompt_id: currentPrompt.id,
raw_timestamp: currentPrompt.timestamp,
completion_timestamp: currentPrompt.completion_timestamp,
session_status: activeSession?.status,
prompt_text_preview: currentPrompt.prompt_text.substring(0, 30) + '...'
});
// Validate the current prompt's timestamp
if (!isValidTimestamp(currentPrompt.timestamp)) {
console.warn('Invalid timestamp for prompt:', currentPrompt.timestamp);
return 'Unknown duration';
}
// If we have a completion_timestamp, use it to calculate the actual execution duration
if (currentPrompt.completion_timestamp && isValidTimestamp(currentPrompt.completion_timestamp)) {
const durationMs = getTimeDifference(currentPrompt.timestamp, currentPrompt.completion_timestamp);
console.log('Using completion timestamp:', {
start: currentPrompt.timestamp,
end: currentPrompt.completion_timestamp,
duration_ms: durationMs
});
// Check for negative duration
if (durationMs < 0) {
console.warn('Negative duration detected with completion timestamp');
return 'Invalid duration';
}
return formatDuration(durationMs);
}
// If no completion timestamp, check if prompt is still running
if (isLast && activeSession && (activeSession.status === 'running' || activeSession.status === 'waiting')) {
// For ongoing prompts, calculate duration from the UTC timestamp to current UTC time
const startTime = parseTimestamp(currentPrompt.timestamp);
const now = new Date();
const durationMs = now.getTime() - startTime.getTime();
console.log('Calculating ongoing duration:', {
raw_timestamp: currentPrompt.timestamp,
parsed_start: startTime.toISOString(),
now_utc: now.toISOString(),
duration_ms: durationMs
});
// Check for negative duration
if (durationMs < 0) {
console.error('NEGATIVE DURATION DETECTED:', {
raw_timestamp: currentPrompt.timestamp,
parsed_as_utc: startTime.toISOString(),
current_time_utc: now.toISOString(),
difference_ms: durationMs,
difference_hours: durationMs / (1000 * 60 * 60)
});
// Instead of showing negative, show the absolute value with a warning
return `${formatDuration(Math.abs(durationMs))} (!)`;
}
return formatDuration(durationMs) + ' (ongoing)';
}
// For prompts without completion_timestamp that are not actively running
// Try to estimate using the next prompt's timestamp
if (!isLast && currentIndex < prompts.length - 1) {
const nextPrompt = prompts[currentIndex + 1];
if (nextPrompt && isValidTimestamp(nextPrompt.timestamp)) {
const durationMs = getTimeDifference(currentPrompt.timestamp, nextPrompt.timestamp);
console.log('Estimating duration from next prompt:', {
current_timestamp: currentPrompt.timestamp,
next_timestamp: nextPrompt.timestamp,
duration_ms: durationMs
});
if (durationMs >= 0) {
return formatDuration(durationMs);
}
}
}
// Fallback for completed prompts without any way to calculate duration
return 'Completed';
} catch (error) {
console.error('Error calculating duration:', error);
return 'Unknown duration';
}
};
useEffect(() => {
if (!sessionId) return;
const fetchPrompts = async () => {
setIsLoading(true);
try {
const response = await API.sessions.getPrompts(sessionId);
if (response.success) {
// Log the timestamps to debug format issues
console.log('Fetched prompts with timestamps:', response.data.map((p: PromptMarker) => ({
id: p.id,
raw_timestamp: p.timestamp,
parsed_timestamp: parseTimestamp(p.timestamp).toISOString(),
completion_timestamp: p.completion_timestamp,
parsed_completion: p.completion_timestamp ? parseTimestamp(p.completion_timestamp).toISOString() : null,
prompt_text: p.prompt_text.substring(0, 50) + '...'
})));
setPrompts(response.data);
}
} catch (error) {
console.error('Error fetching prompt markers:', error);
} finally {
setIsLoading(false);
}
};
fetchPrompts();
// Only refresh prompts when session status changes, not on a timer
// This reduces unnecessary API calls from every 5 seconds to only when needed
}, [sessionId, activeSession?.status]);
// Use requestAnimationFrame for smooth UI updates instead of setInterval
useEffect(() => {
if (!activeSession || (activeSession.status !== 'running' && activeSession.status !== 'waiting')) {
return;
}
let animationId: number;
let lastUpdate = 0;
const UPDATE_INTERVAL = 5000; // Update every 5 seconds instead of every second
const updateOngoingDuration = (timestamp: number) => {
if (timestamp - lastUpdate >= UPDATE_INTERVAL) {
setPrompts(prev => [...prev]); // Force re-render for duration updates
lastUpdate = timestamp;
}
animationId = requestAnimationFrame(updateOngoingDuration);
};
animationId = requestAnimationFrame(updateOngoingDuration);
return () => cancelAnimationFrame(animationId);
}, [activeSession?.status]);
const handlePromptClick = (marker: PromptMarker) => {
setSelectedPromptId(marker.id);
onNavigateToPrompt(marker);
};
const handlePromptDoubleClick = (marker: PromptMarker, index: number) => {
setModalPrompt({ prompt: marker, index });
};
if (isLoading && prompts.length === 0) {
return (
<div className="w-64 bg-gray-800 border-l border-gray-700 p-4">
<h3 className="font-semibold text-gray-700 dark:text-gray-300 mb-4">Prompt History</h3>
<div className="text-gray-500 dark:text-gray-400 text-sm">Loading prompts...</div>
</div>
);
}
return (
<>
<div className="w-64 bg-gray-800 border-l border-gray-700 flex flex-col h-full">
<div className="p-4 border-b border-gray-700">
<h3 className="font-semibold text-gray-700 dark:text-gray-300">Prompt History</h3>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Click to navigate • Double-click for details</p>
</div>
<div className="flex-1 overflow-y-auto">
{prompts.length === 0 ? (
<div className="p-4 text-gray-500 dark:text-gray-400 text-sm">
No prompts yet. Start by entering a prompt below.
</div>
) : (
<div className="space-y-1 p-2">
{prompts.map((marker, index) => (
<button
key={marker.id}
onClick={() => handlePromptClick(marker)}
onDoubleClick={() => handlePromptDoubleClick(marker, index)}
className={`w-full text-left p-3 rounded-lg transition-colors ${
selectedPromptId === marker.id
? 'bg-blue-900/30 border-blue-700 border'
: 'hover:bg-gray-700 border border-transparent'
}`}
>
<div className="flex items-start space-x-2">
<span className="text-blue-500 dark:text-blue-400 font-mono text-sm mt-0.5">
#{index + 1}
</span>
<div className="flex-1 min-w-0">
<div className="text-sm text-gray-800 dark:text-gray-200 line-clamp-2">
{marker.prompt_text}
</div>
<div className="flex items-center space-x-2 text-xs text-gray-500 dark:text-gray-400 mt-1">
<span>{formatDistanceToNow(parseTimestamp(marker.timestamp))} ago</span>
<span className="text-gray-400">•</span>
<span className="font-medium text-gray-600 dark:text-gray-400">
{calculateDuration(marker, index)}
</span>
</div>
</div>
</div>
</button>
))}
</div>
)}
</div>
</div>
{modalPrompt && (
<PromptDetailModal
prompt={modalPrompt.prompt}
promptIndex={modalPrompt.index}
onClose={() => setModalPrompt(null)}
/>
)}
</>
);
}

View File

@ -1,114 +0,0 @@
import React, { useState, useCallback, useEffect, useRef } from 'react';
import { GripHorizontal } from 'lucide-react';
interface ResizablePanelProps {
children: React.ReactNode;
defaultHeight?: number;
minHeight?: number;
maxHeight?: number;
storageKey: string;
className?: string;
}
export const ResizablePanel: React.FC<ResizablePanelProps> = ({
children,
defaultHeight = 300,
minHeight = 200,
maxHeight = 600,
storageKey,
className = '',
}) => {
// Load height from localStorage or use default
const [height, setHeight] = useState<number>(() => {
const saved = localStorage.getItem(storageKey);
return saved ? parseInt(saved, 10) : defaultHeight;
});
const [isResizing, setIsResizing] = useState(false);
const startYRef = useRef<number>(0);
const startHeightRef = useRef<number>(0);
// Save height to localStorage when it changes
useEffect(() => {
localStorage.setItem(storageKey, height.toString());
}, [height, storageKey]);
const handleMouseDown = useCallback((e: React.MouseEvent) => {
e.preventDefault();
setIsResizing(true);
startYRef.current = e.clientY;
startHeightRef.current = height;
}, [height]);
const handleMouseMove = useCallback((e: MouseEvent) => {
if (!isResizing) return;
// Calculate the new height based on mouse movement
// Since we're dragging from the top, moving up should increase height
const deltaY = startYRef.current - e.clientY;
const newHeight = startHeightRef.current + deltaY;
// Clamp height between min and max
const clampedHeight = Math.max(minHeight, Math.min(maxHeight, newHeight));
setHeight(clampedHeight);
}, [isResizing, minHeight, maxHeight]);
const handleMouseUp = useCallback(() => {
setIsResizing(false);
}, []);
// Add global mouse event listeners when resizing
useEffect(() => {
if (isResizing) {
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mouseup', handleMouseUp);
// Prevent text selection while dragging
document.body.style.userSelect = 'none';
document.body.style.cursor = 'ns-resize';
return () => {
document.removeEventListener('mousemove', handleMouseMove);
document.removeEventListener('mouseup', handleMouseUp);
document.body.style.userSelect = '';
document.body.style.cursor = '';
};
}
}, [isResizing, handleMouseMove, handleMouseUp]);
return (
<div
className={`flex flex-col ${className}`}
style={{ height: `${height}px` }}
>
{/* Resize Handle */}
<div
className={`
flex items-center justify-center
h-2 cursor-ns-resize
border-t border-border-primary
bg-surface-secondary
hover:bg-surface-hover
transition-colors
group
${isResizing ? 'bg-interactive/10' : ''}
`}
onMouseDown={handleMouseDown}
title="Drag to resize"
>
<GripHorizontal
className={`
w-5 h-5 text-text-tertiary
group-hover:text-text-secondary
transition-colors
${isResizing ? 'text-interactive' : ''}
`}
/>
</div>
{/* Content */}
<div className="flex-1 overflow-visible">
{children}
</div>
</div>
);
};

View File

@ -1,103 +0,0 @@
import { Settings, X, Play, AlertCircle } from 'lucide-react';
interface RunScriptConfigDialogProps {
isOpen: boolean;
onClose: () => void;
onOpenSettings?: () => void;
}
export function RunScriptConfigDialog({
isOpen,
onClose,
onOpenSettings
}: RunScriptConfigDialogProps) {
if (!isOpen) return null;
const handleOpenSettings = () => {
onClose();
if (onOpenSettings) {
onOpenSettings();
}
};
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full mx-4 p-6">
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-3">
<div className="flex-shrink-0">
<Play className="w-6 h-6 text-blue-500" />
</div>
<h3 className="text-lg font-medium text-gray-900 dark:text-white">
Configure Run Script
</h3>
</div>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<X className="w-5 h-5" />
</button>
</div>
<div className="mb-6 space-y-4">
<div className="bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-4">
<div className="flex items-start space-x-2">
<AlertCircle className="w-5 h-5 text-yellow-600 dark:text-yellow-500 flex-shrink-0 mt-0.5" />
<div className="text-sm text-yellow-800 dark:text-yellow-300">
<p className="font-semibold mb-1">No run script configured</p>
<p>A run script is required to test changes in your application.</p>
</div>
</div>
</div>
<div className="text-gray-700 dark:text-gray-300 space-y-3">
<p>
<strong>What is a run script?</strong><br />
A run script contains the commands needed to start your application for testing changes made by Claude Code sessions.
</p>
<p>
<strong>How to configure:</strong>
</p>
<ol className="list-decimal list-inside space-y-2 ml-4">
<li>Click the settings icon (⚙️) next to your project name in the sidebar (visible on hover)</li>
<li>In the "Run Script" field, enter the command(s) to start your application</li>
<li>Optionally add a "Build Script" that runs when creating new worktrees</li>
</ol>
<div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 mt-4">
<p className="text-sm text-blue-800 dark:text-blue-300">
<strong>💡 Recommendation:</strong> Include commands to kill any existing instances of your application to prevent port conflicts when switching between sessions.
</p>
<div className="mt-2 font-mono text-xs bg-white dark:bg-gray-900 p-2 rounded border border-blue-200 dark:border-blue-700">
<div className="text-gray-600 dark:text-gray-400"># Example for a Node.js app on port 3000:</div>
<div>pkill -f "node.*port=3000" || true</div>
<div>npm run dev</div>
</div>
</div>
</div>
</div>
<div className="flex justify-end space-x-3">
<button
onClick={onClose}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
>
Close
</button>
{onOpenSettings && (
<button
onClick={handleOpenSettings}
className="px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 rounded-md transition-colors flex items-center space-x-2"
autoFocus
>
<Settings className="w-4 h-4" />
<span>Open Project Settings</span>
</button>
)}
</div>
</div>
</div>
);
}

View File

@ -1,27 +1,17 @@
import { useState, useEffect, memo, useCallback } from 'react';
import { useState, useEffect } from 'react';
import { useSessionStore } from '../stores/sessionStore';
import { useNavigationStore } from '../stores/navigationStore';
import { StatusIndicator } from './StatusIndicator';
import { GitStatusIndicator } from './GitStatusIndicator';
import { ConfirmDialog } from './ConfirmDialog';
import { RunScriptConfigDialog } from './RunScriptConfigDialog';
import { NimbalystInstallDialog } from './NimbalystInstallDialog';
import { API } from '../utils/api';
import { Star, Archive } from 'lucide-react';
import { NimbalystIcon } from './icons/NimbalystIcon';
import type { Session, GitStatus } from '../types/session';
import { useContextMenu } from '../contexts/ContextMenuContext';
import { IconButton } from './ui/IconButton';
import { cn } from '../utils/cn';
import { AnalyticsService } from '../services/analyticsService';
import type { Session } from '../types/session';
interface SessionListItemProps {
session: Session;
isNested?: boolean;
}
// Memoized component to prevent unnecessary re-renders
export const SessionListItem = memo(function SessionListItem({ session, isNested = false }: SessionListItemProps) {
export function SessionListItem({ session, isNested = false }: SessionListItemProps) {
const { activeSessionId, setActiveSession, deletingSessionIds, addDeletingSessionId, removeDeletingSessionId } = useSessionStore();
const { navigateToSessions } = useNavigationStore();
const isActive = activeSessionId === session.id;
@ -31,23 +21,36 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
const [isClosing, setIsClosing] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [editName, setEditName] = useState(session.name);
const [gitStatus, setGitStatus] = useState<GitStatus | undefined>(session.gitStatus);
const { menuState, openMenu, closeMenu, isMenuOpen } = useContextMenu();
const [showArchiveConfirm, setShowArchiveConfirm] = useState(false);
const [showRunScriptConfig, setShowRunScriptConfig] = useState(false);
const [showNimbalystInstall, setShowNimbalystInstall] = useState(false);
const [gitStatusLoading, setGitStatusLoading] = useState(false);
const [showContextMenu, setShowContextMenu] = useState(false);
const [contextMenuPosition, setContextMenuPosition] = useState({ x: 0, y: 0 });
// Performance optimization: Remove unnecessary subscription
// The component already receives the session as a prop, which will cause re-render when it changes
// No need for an additional store subscription that runs for every session item on every store change
// Sync git status loading state from store
// Force re-render when session status changes
const [, forceUpdate] = useState({});
useEffect(() => {
const loading = useSessionStore.getState().isGitStatusLoading(session.id);
setGitStatusLoading(loading);
}, [session.id]);
// Subscribe to session updates to ensure UI updates when this session's status changes
const unsubscribe = useSessionStore.subscribe((state) => {
const updatedSession = state.sessions.find(s => s.id === session.id) ||
(state.activeMainRepoSession?.id === session.id ? state.activeMainRepoSession : null);
if (updatedSession && updatedSession.status !== session.status) {
forceUpdate({});
}
});
// Also listen for custom session status change events
const handleStatusChange = (event: CustomEvent) => {
if (event.detail.sessionId === session.id) {
forceUpdate({});
}
};
window.addEventListener('session-status-changed', handleStatusChange as EventListener);
return () => {
unsubscribe();
window.removeEventListener('session-status-changed', handleStatusChange as EventListener);
};
}, [session.id, session.status]);
useEffect(() => {
// Check if this session's project has a run script
@ -63,25 +66,26 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
checkRunScript();
// Listen for custom project update events from the global useIPCEvents hook
const handleProjectUpdate = (event: CustomEvent) => {
const project = event.detail;
// Check if this session belongs to the updated project
if (session.projectId === project.id) {
// Re-check if the run script exists for this session
checkRunScript();
}
};
// Listen for project updates
let unsubscribe: (() => void) | undefined;
window.addEventListener('project-updated', handleProjectUpdate as EventListener);
if (window.electronAPI?.events?.onProjectUpdated) {
unsubscribe = window.electronAPI.events.onProjectUpdated((project) => {
// Check if this session belongs to the updated project
if (session.projectId === project.id) {
// Re-check if the run script exists for this session
checkRunScript();
}
});
}
return () => {
window.removeEventListener('project-updated', handleProjectUpdate as EventListener);
if (unsubscribe) {
unsubscribe();
}
};
// Only re-run when the actual session ID changes to prevent memory leaks
}, [session.id]);
}, [session.id, session.projectId]);
// Combine script-related effects
useEffect(() => {
// Check if this session is currently running
API.sessions.getRunningSession()
@ -91,85 +95,37 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
}
})
.catch(console.error);
}, [session.id]);
useEffect(() => {
// Listen for script session changes
const handleScriptSessionChange = (event: CustomEvent) => {
setIsRunning(event.detail === session.id);
};
window.addEventListener('script-session-changed', handleScriptSessionChange as EventListener);
return () => {
window.removeEventListener('script-session-changed', handleScriptSessionChange as EventListener);
};
}, [session.id]);
useEffect(() => {
// Listen for script closing state
const handleScriptClosing = (event: CustomEvent) => {
setIsClosing(event.detail === session.id);
};
window.addEventListener('script-session-changed', handleScriptSessionChange as EventListener);
window.addEventListener('script-closing', handleScriptClosing as EventListener);
return () => {
window.removeEventListener('script-session-changed', handleScriptSessionChange as EventListener);
window.removeEventListener('script-closing', handleScriptClosing as EventListener);
};
}, [session.id]);
useEffect(() => {
// Optimized git status fetching - rely on centralized smart polling instead of individual fetches
const fetchGitStatusIfNeeded = async () => {
// Only fetch if we don't have git status yet and session is active/viable
if (!session.archived && session.status !== 'error' && !gitStatus && !session.gitStatus) {
try {
setGitStatusLoading(true);
// Use queue-based initial load to prevent overwhelming the system
const response = await window.electronAPI.invoke('sessions:get-git-status', session.id, false, true);
if (response.success && response.gitStatus) {
setGitStatus(response.gitStatus);
}
setGitStatusLoading(false);
} catch (error) {
console.warn('Error fetching initial git status:', error);
setGitStatusLoading(false);
}
}
};
// Use session.gitStatus if available, or fetch only once if needed
if (session.gitStatus) {
setGitStatus(session.gitStatus);
} else {
fetchGitStatusIfNeeded();
}
// Listen for custom git status events from the global useIPCEvents hook
const handleGitStatusUpdate = (event: CustomEvent) => {
const { sessionId, gitStatus } = event.detail;
if (sessionId === session.id) {
setGitStatus(gitStatus);
setGitStatusLoading(false);
}
};
// Listen for git status loading events to show immediate feedback
const handleGitStatusLoading = (event: CustomEvent) => {
const { sessionId } = event.detail;
if (sessionId === session.id) {
setGitStatusLoading(true);
}
};
window.addEventListener('git-status-updated', handleGitStatusUpdate as EventListener);
window.addEventListener('git-status-loading', handleGitStatusLoading as EventListener);
return () => {
window.removeEventListener('git-status-updated', handleGitStatusUpdate as EventListener);
window.removeEventListener('git-status-loading', handleGitStatusLoading as EventListener);
};
// Reduced dependency array to prevent excessive re-runs
}, [session.id, session.archived, session.status, session.gitStatus]);
const handleRunScript = useCallback(async (e: React.MouseEvent) => {
const handleRunScript = async (e: React.MouseEvent) => {
e.stopPropagation();
if (!hasRunScript) {
setShowRunScriptConfig(true);
alert('No run script configured for this project.\n\nRun scripts are the commands needed to run your application so you can easily test changes.\n\nTo configure a run script:\n1. Click the settings icon (⚙️) next to your project (only shows on hover)\n\n2. Enter your \'Build Script\' to run at worktree creation (Optional)\n\n3. Enter your run script command(s) to run your application for testing');
return;
}
@ -188,8 +144,8 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
// Clear closing state after stop completes
window.dispatchEvent(new CustomEvent('script-closing', { detail: null }));
// Note: Script output now goes to logs, not terminal
// No need to clear terminal output here
// Clear any previous script output for this session
useSessionStore.getState().clearScriptOutput(session.id);
// Then run the script for this session
const response = await API.sessions.runScript(session.id);
@ -206,20 +162,22 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
window.dispatchEvent(new CustomEvent('script-closing', { detail: null }));
alert('Failed to run script');
}
}, [hasRunScript, session.id]);
};
const handleStopScript = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
console.log('Stopping script...');
// Set closing state for this session
setIsClosing(true);
const response = await API.sessions.stopScript(session.id);
const response = await API.sessions.stopScript();
if (!response.success) {
throw new Error(response.error || 'Failed to stop script');
}
console.log('Script stop request successful');
// Clear closing state
setIsClosing(false);
// Update running state for all sessions
@ -234,17 +192,20 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
}
};
const handleDelete = useCallback(async (e: React.MouseEvent) => {
const handleDelete = async (e: React.MouseEvent) => {
e.stopPropagation(); // Prevent selecting the session
// Prevent deletion if already being deleted
if (isDeleting) return;
// Show the confirmation dialog
setShowArchiveConfirm(true);
}, [isDeleting]);
const handleConfirmArchive = useCallback(async () => {
const confirmMessage = `Archive session "${session.name}"? This will:\n` +
`• Move the session to the archived sessions list\n` +
`• Preserve all session history and outputs\n` +
(session.isMainRepo ? `• Close the active Claude Code connection` : `• Remove the git worktree (${session.worktreePath?.split('/').pop() || 'worktree'})`);
const confirmed = window.confirm(confirmMessage);
if (!confirmed) return;
addDeletingSessionId(session.id);
try {
const response = await API.sessions.delete(session.id);
@ -263,7 +224,7 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
} finally {
removeDeletingSessionId(session.id);
}
}, [isDeleting, session.name, session.id, session.isMainRepo, session.worktreePath, isActive, addDeletingSessionId, removeDeletingSessionId, setActiveSession]);
};
const handleSaveEdit = async () => {
if (editName.trim() === '') {
@ -308,101 +269,72 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
const handleContextMenu = (e: React.MouseEvent) => {
e.preventDefault();
e.stopPropagation();
openMenu('session', session, { x: e.clientX, y: e.clientY });
setContextMenuPosition({ x: e.clientX, y: e.clientY });
setShowContextMenu(true);
};
const closeContextMenu = () => {
setShowContextMenu(false);
};
// Close context menu when clicking outside
useEffect(() => {
if (showContextMenu) {
const handleClick = () => closeContextMenu();
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
}
}, [showContextMenu]);
const handleRename = () => {
closeMenu();
closeContextMenu();
setEditName(session.name);
setIsEditing(true);
};
const handleDeleteFromMenu = () => {
closeMenu();
closeContextMenu();
handleDelete({ stopPropagation: () => {} } as React.MouseEvent);
};
const handleToggleFavorite = async (e: React.MouseEvent) => {
e.stopPropagation();
console.log('[SessionListItem] Toggling favorite for session:', session.id, 'Current status:', session.isFavorite);
try {
const response = await API.sessions.toggleFavorite(session.id);
console.log('[SessionListItem] Toggle favorite response:', response);
if (!response.success) {
throw new Error(response.error || 'Failed to toggle favorite status');
}
console.log('[SessionListItem] Successfully toggled favorite status to:', response.data?.isFavorite);
} catch (error) {
console.error('Error toggling favorite status:', error);
alert('Failed to toggle favorite status');
}
};
const handleOpenInNimbalyst = async (e: React.MouseEvent) => {
e.stopPropagation();
try {
// Track button click
const sessionIdHash = await AnalyticsService.hashSessionId(session.id);
await AnalyticsService.trackNimbalystButtonClicked({
session_id_hash: sessionIdHash
});
// Check if Nimbalyst is installed
const checkResponse = await window.electronAPI.nimbalyst.checkInstalled();
if (!checkResponse.success) {
throw new Error(checkResponse.error || 'Failed to check Nimbalyst installation');
}
if (!checkResponse.data) {
// Track install dialog shown
await AnalyticsService.trackNimbalystInstallDialogShown({
session_id_hash: sessionIdHash
});
// Show install dialog if not installed
setShowNimbalystInstall(true);
return;
}
// Open the worktree in Nimbalyst
const openResponse = await window.electronAPI.nimbalyst.openWorktree(session.worktreePath);
if (!openResponse.success) {
throw new Error(openResponse.error || 'Failed to open worktree in Nimbalyst');
}
// Track successful open
await AnalyticsService.trackNimbalystOpened({
session_id_hash: sessionIdHash
});
} catch (error) {
console.error('Error opening in Nimbalyst:', error);
alert('Failed to open in Nimbalyst');
}
};
return (
<>
<div
className={cn(
'w-full text-left rounded-md flex items-center space-x-2 transition-all group',
isNested ? 'px-2 py-1.5 text-sm' : 'px-3 py-2',
className={`w-full text-left ${isNested ? 'px-2 py-1.5' : 'px-3 py-2'} rounded-md flex items-center space-x-2 transition-all group ${
isActive
? 'bg-interactive/20 text-text-primary shadow-sm ring-1 ring-interactive/20 dark:ring-interactive/30'
: 'hover:bg-surface-hover text-text-secondary hover:shadow-sm'
)}
? 'bg-blue-100 dark:bg-blue-600/20 text-gray-900 dark:text-white shadow-sm ring-1 ring-blue-200 dark:ring-blue-600/30'
: 'hover:bg-gray-100 dark:hover:bg-gray-700/50 text-gray-700 dark:text-gray-300 hover:shadow-sm'
} ${isNested ? 'text-sm' : ''}`}
onContextMenu={handleContextMenu}
>
<button
onClick={() => {
console.log('[SessionListItem] Clicking session:', session.id, session.name);
setActiveSession(session.id);
navigateToSessions();
}}
className="flex items-center justify-start space-x-3 flex-1 min-w-0"
>
<StatusIndicator session={session} size="small" />
{isEditing ? (
<input
type="text"
@ -411,30 +343,19 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
onKeyDown={handleKeyDown}
onBlur={handleSaveEdit}
onClick={(e) => e.stopPropagation()}
className="flex-1 text-sm bg-surface-primary text-text-primary px-2 py-1 rounded border border-border-primary focus:border-interactive focus:outline-none focus:ring-2 focus:ring-interactive/20"
className="flex-1 text-sm bg-white dark:bg-gray-800 text-gray-900 dark:text-white px-2 py-1 rounded border border-gray-300 dark:border-gray-600 focus:border-blue-500 focus:outline-none"
autoFocus
/>
) : (
<span className={cn(
'flex-1 truncate text-sm text-left flex items-center gap-2',
(isActive || session.status === 'completed_unviewed') && 'font-semibold',
session.status === 'completed_unviewed' && 'text-interactive'
)} title={session.name}>
{(gitStatus || gitStatusLoading) && !session.archived && (
<GitStatusIndicator gitStatus={gitStatus} size="small" sessionId={session.id} isLoading={gitStatusLoading} />
)}
<StatusIndicator session={session} size="small" />
<span className="ml-1">{session.name}</span>
<span className={`flex-1 truncate text-sm text-left ${isActive || session.status === 'completed_unviewed' ? 'font-semibold' : ''} ${session.status === 'completed_unviewed' ? 'text-blue-700 dark:text-blue-300' : ''}`} title={session.name}>
{session.name}
{!!session.isMainRepo && (
<span className="ml-1 text-xs text-interactive">(main)</span>
<span className="ml-1 text-xs text-blue-600 dark:text-blue-400">(main)</span>
)}
</span>
)}
{!isEditing && (isRunning || isClosing) && (
<span className={cn(
'text-xs',
isClosing ? 'text-status-warning' : 'text-status-success'
)}>
<span className={isClosing ? "text-amber-600 dark:text-amber-400 text-xs" : "text-green-600 dark:text-green-400 text-xs"}>
{isClosing ? '⏸️ Closing' : '▶️ Running'}
</span>
)}
@ -443,49 +364,34 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
{!isEditing && (
<>
{!session.archived && (
<IconButton
<button
onClick={handleToggleFavorite}
variant="ghost"
size="sm"
className={cn(
'transition-all',
session.isFavorite
? 'text-status-warning hover:text-status-warning-hover'
: 'text-text-tertiary opacity-0 group-hover:opacity-100'
)}
aria-label={session.isFavorite ? 'Remove from favorites' : 'Add to favorites'}
icon={
<Star
className="w-4 h-4"
fill={session.isFavorite ? 'currentColor' : 'none'}
strokeWidth={session.isFavorite ? 0 : 2}
/>
}
/>
)}
{!session.archived && (
<IconButton
onClick={handleOpenInNimbalyst}
variant="ghost"
size="sm"
className="text-text-tertiary opacity-0 group-hover:opacity-100 transition-opacity hover:text-blue-500"
aria-label="Open in Nimbalyst"
icon={<NimbalystIcon size={18} className="text-current" />}
/>
className={`p-1 rounded transition-all ${
session.isFavorite
? 'text-yellow-500 hover:text-yellow-600 dark:text-yellow-400 dark:hover:text-yellow-300'
: 'text-gray-400 hover:text-gray-600 dark:text-gray-600 dark:hover:text-gray-400 opacity-0 group-hover:opacity-100'
} hover:bg-gray-100 dark:hover:bg-gray-700/50`}
title={session.isFavorite ? 'Remove from favorites' : 'Add to favorites'}
>
<Star
className="w-4 h-4"
fill={session.isFavorite ? 'currentColor' : 'none'}
strokeWidth={session.isFavorite ? 0 : 2}
/>
</button>
)}
{!session.archived && (
<button
onClick={isRunning ? handleStopScript : handleRunScript}
className={cn(
'opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded',
className={`opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded ${
isClosing
? 'cursor-wait text-status-warning'
? 'cursor-wait text-amber-600 dark:text-amber-400'
: isRunning
? 'hover:bg-status-error/10 text-status-error hover:text-status-error'
? 'hover:bg-red-100 dark:hover:bg-red-600/20 text-red-600 dark:text-red-400 hover:text-red-700 dark:hover:text-red-300'
: hasRunScript
? 'hover:bg-status-success/10 text-status-success hover:text-status-success'
: 'hover:bg-surface-hover text-text-tertiary hover:text-text-secondary'
)}
? 'hover:bg-green-100 dark:hover:bg-green-600/20 text-green-600 dark:text-green-400 hover:text-green-700 dark:hover:text-green-300'
: 'hover:bg-gray-100 dark:hover:bg-gray-600/20 text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400'
}`}
title={isClosing ? 'Closing script...' : isRunning ? 'Stop script' : (hasRunScript ? 'Run script' : 'No run script configured - Click to configure')}
disabled={isClosing}
>
@ -493,25 +399,20 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
</button>
)}
{!session.archived && (
<IconButton
<button
onClick={handleDelete}
disabled={isDeleting}
variant="ghost"
size="sm"
className={cn(
'opacity-0 group-hover:opacity-100 transition-opacity',
'hover:bg-status-warning/10',
isDeleting && 'cursor-not-allowed'
className={`opacity-0 group-hover:opacity-100 transition-opacity p-1 rounded hover:bg-amber-100 dark:hover:bg-amber-600/20 ${
isDeleting ? 'cursor-not-allowed' : ''
}`}
title="Archive session"
>
{isDeleting ? (
<span className="text-gray-600 dark:text-gray-400">⏳</span>
) : (
<Archive className="w-4 h-4 text-amber-600 dark:text-amber-400 hover:text-amber-700 dark:hover:text-amber-300" />
)}
aria-label="Archive session"
icon={
isDeleting ? (
<span className="text-text-tertiary">⏳</span>
) : (
<Archive className="w-4 h-4 text-status-warning hover:text-status-warning" />
)
}
/>
</button>
)}
</>
)}
@ -519,21 +420,21 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
</div>
{/* Context Menu */}
{isMenuOpen('session', session.id) && menuState.position && (
{showContextMenu && (
<div
className="context-menu fixed bg-surface-primary border border-border-primary rounded-md shadow-lg py-1 z-50 min-w-[150px]"
style={{ top: menuState.position.y, left: menuState.position.x }}
className="fixed bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg py-1 z-50 min-w-[150px]"
style={{ top: contextMenuPosition.y, left: contextMenuPosition.x }}
onClick={(e) => e.stopPropagation()}
>
<button
onClick={handleRename}
className="w-full text-left px-4 py-2 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary"
className="w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white"
>
Rename
</button>
<button
onClick={() => {
closeMenu();
closeContextMenu();
if (isRunning) {
handleStopScript({ stopPropagation: () => {} } as React.MouseEvent);
} else {
@ -541,62 +442,23 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
}
}}
disabled={isClosing}
className={cn(
'w-full text-left px-4 py-2 text-sm',
isClosing
? 'text-text-tertiary cursor-wait'
: 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'
)}
className={`w-full text-left px-4 py-2 text-sm ${
isClosing
? 'text-gray-400 dark:text-gray-600 cursor-wait'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-gray-900 dark:hover:text-white'
}`}
>
{isClosing ? 'Closing Script...' : isRunning ? 'Stop Script' : 'Run Script'}
</button>
<div className="border-t border-border-primary my-1" />
<button
onClick={() => {
closeMenu();
// Dispatch the discard-and-retry event with session data
// The session will be archived only after the new session is created
window.dispatchEvent(new CustomEvent('discard-and-retry', {
detail: {
session,
projectId: session.projectId,
folderId: session.folderId
}
}));
}}
className="w-full text-left px-4 py-2 text-sm text-text-secondary hover:bg-surface-hover hover:text-text-primary"
>
Discard and Retry
</button>
<div className="border-t border-gray-200 dark:border-gray-700 my-1" />
<button
onClick={handleDeleteFromMenu}
className="w-full text-left px-4 py-2 text-sm text-status-error hover:bg-surface-hover hover:text-status-error"
className="w-full text-left px-4 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-gray-100 dark:hover:bg-gray-700 hover:text-red-700 dark:hover:text-red-300"
>
Archive
{session.isMainRepo ? 'Archive' : 'Delete'}
</button>
</div>
)}
<ConfirmDialog
isOpen={showArchiveConfirm}
onClose={() => setShowArchiveConfirm(false)}
onConfirm={handleConfirmArchive}
title={`Archive Session`}
message={`Archive session "${session.name}"? This will:\n\n• Move the session to the archived sessions list\n• Preserve all session history and outputs\n${session.isMainRepo ? '• Close the active Claude Code connection' : `• Remove the git worktree locally (${session.worktreePath?.split('/').pop() || 'worktree'})`}`}
confirmText="Archive"
confirmButtonClass="bg-amber-600 hover:bg-amber-700 text-white"
icon={<Archive className="w-6 h-6 text-amber-500 flex-shrink-0" />}
/>
<RunScriptConfigDialog
isOpen={showRunScriptConfig}
onClose={() => setShowRunScriptConfig(false)}
/>
<NimbalystInstallDialog
isOpen={showNimbalystInstall}
onClose={() => setShowNimbalystInstall(false)}
/>
</>
);
});
}

View File

@ -1,467 +1,68 @@
import { useRef, useEffect, useState, memo, useMemo, useCallback } from 'react';
import { useRef, useEffect, useState, memo, useMemo } from 'react';
import { useSessionStore } from '../stores/sessionStore';
import { useNavigationStore } from '../stores/navigationStore';
import { useSessionHistoryStore } from '../stores/sessionHistoryStore';
import { JsonMessageView } from './JsonMessageView';
import { EmptyState } from './EmptyState';
// import CombinedDiffView from './panels/diff/CombinedDiffView'; // Removed - now in panels
import CombinedDiffView from './CombinedDiffView';
import { StravuFileSearch } from './StravuFileSearch';
import { Inbox } from 'lucide-react';
import '@xterm/xterm/css/xterm.css';
import { useSessionView } from '../hooks/useSessionView';
import { SessionHeader } from './session/SessionHeader';
// import { SessionInputWithImages } from './panels/claude/ClaudeInputWithImages'; // Removed - now in panels
import { SessionInputWithImages } from './session/SessionInputWithImages';
import { GitErrorDialog } from './session/GitErrorDialog';
import { CommitMessageDialog } from './session/CommitMessageDialog';
import { FolderArchiveDialog } from './session/FolderArchiveDialog';
// import { FileEditor } from './panels/editor/FileEditor'; // Removed - now in panels
import { ProjectView } from './ProjectView';
import { API } from '../utils/api';
// import { RichOutputWithSidebar } from './panels/claude/RichOutputWithSidebar'; // Removed - now in panels
// import { RichOutputSettings } from './panels/claude/RichOutputView'; // Removed - not needed
// import { LogsView } from './panels/logPanel/LogsView'; // Removed - now in panels
// import { MessagesView } from './panels/claude/MessagesView'; // Removed - now in panels
import { usePanelStore } from '../stores/panelStore';
import { panelApi } from '../services/panelApi';
import { PanelTabBar } from './panels/PanelTabBar';
import { PanelContainer } from './panels/PanelContainer';
import { SessionProvider } from '../contexts/SessionContext';
import { ToolPanel, ToolPanelType } from '../../../shared/types/panels';
import { Download, Upload, GitMerge, Code2 } from 'lucide-react';
import type { Project } from '../types/project';
import { devLog, renderLog } from '../utils/console';
import { PromptNavigation } from './PromptNavigation';
import { isDocumentVisible } from '../utils/performanceUtils';
import { FileEditor } from './FileEditor';
import { ProjectDashboard } from './ProjectDashboard';
export const SessionView = memo(() => {
const activeSessionId = useSessionStore((state) => state.activeSessionId);
const sessions = useSessionStore((state) => state.sessions);
const activeMainRepoSession = useSessionStore((state) => state.activeMainRepoSession);
const { activeView, activeProjectId } = useNavigationStore();
const [projectData, setProjectData] = useState<Project | null>(null);
const [isProjectLoading, setIsProjectLoading] = useState(false);
const [isMergingProject, setIsMergingProject] = useState(false);
const [sessionProject, setSessionProject] = useState<Project | null>(null);
const [animationsEnabled, setAnimationsEnabled] = useState(isDocumentVisible());
// Get active session by subscribing directly to store state
// This ensures the component re-renders when git status or other session properties update
const activeSession = useSessionStore((state) => {
if (!state.activeSessionId) return undefined;
// Check main repo session first
if (state.activeMainRepoSession && state.activeMainRepoSession.id === state.activeSessionId) {
return state.activeMainRepoSession;
}
// Otherwise look in regular sessions
return state.sessions.find(session => session.id === state.activeSessionId);
});
const setActiveSession = useSessionStore(state => state.setActiveSession);
// Panel store state and actions
const {
panels,
activePanels,
setPanels,
setActivePanel: setActivePanelInStore,
addPanel,
removePanel,
updatePanelState,
} = usePanelStore();
// History store for navigation
const { addToHistory, navigateBack, navigateForward } = useSessionHistoryStore();
// Load panels when session changes
useEffect(() => {
if (activeSession?.id) {
devLog.debug('[SessionView] Loading panels for session:', activeSession.id);
// Always reload panels from database when switching sessions
// to ensure we get the latest saved state
panelApi.loadPanelsForSession(activeSession.id).then(loadedPanels => {
devLog.debug('[SessionView] Loaded panels:', loadedPanels);
setPanels(activeSession.id, loadedPanels);
});
panelApi.getActivePanel(activeSession.id).then(activePanel => {
console.log('[SessionView] Active panel from backend:', activePanel);
if (activePanel) {
setActivePanelInStore(activeSession.id, activePanel.id);
}
});
}
}, [activeSession?.id, setPanels, setActivePanelInStore]); // Remove panels from deps to avoid skipping reload
// Listen for panel updates from the backend
useEffect(() => {
if (!activeSession?.id) return;
// Handle panel creation events (for logs panel auto-creation)
const handlePanelCreated = (panel: ToolPanel) => {
console.log('[SessionView] Received panel:created event:', panel);
// Only add if it's for the current session
if (panel.sessionId === activeSession.id) {
// Check if panel already exists to prevent duplicates
const existingPanels = panels[activeSession.id] || [];
const panelExists = existingPanels.some(p => p.id === panel.id);
if (!panelExists) {
console.log('[SessionView] Adding new panel to store:', panel);
addPanel(panel);
} else {
console.log('[SessionView] Panel already exists, not adding duplicate:', panel.id);
}
}
const handleVisibilityChange = () => {
setAnimationsEnabled(isDocumentVisible());
};
const handlePanelUpdated = (updatedPanel: ToolPanel) => {
console.log('[SessionView] Received panel:updated event:', updatedPanel);
// Only update if it's for the current session
if (updatedPanel.sessionId === activeSession.id) {
console.log('[SessionView] Updating panel in store:', updatedPanel);
updatePanelState(updatedPanel);
}
};
// Listen for panel events
const unsubscribeCreated = window.electronAPI?.events?.onPanelCreated?.(handlePanelCreated);
const unsubscribeUpdated = window.electronAPI?.events?.onPanelUpdated?.(handlePanelUpdated);
// Cleanup
return () => {
unsubscribeCreated?.();
unsubscribeUpdated?.();
};
}, [activeSession?.id, addPanel, updatePanelState, panels]);
// Get panels for current session with memoization
const sessionPanels = useMemo(
() => panels[activeSession?.id || ''] || [],
[panels, activeSession?.id]
);
const currentActivePanel = useMemo(
() => sessionPanels.find(p => p.id === activePanels[activeSession?.id || '']),
[sessionPanels, activePanels, activeSession?.id]
);
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
}, []);
// Check if session has Claude panels
const hasClaudePanels = useMemo(
() => sessionPanels.some(panel => panel.type === 'claude'),
[sessionPanels]
);
// Track current session/panel in history when they change
useEffect(() => {
if (activeSession?.id && currentActivePanel?.id) {
addToHistory(activeSession.id, currentActivePanel.id);
}
}, [activeSession?.id, currentActivePanel?.id, addToHistory]);
// Keyboard shortcuts for navigating history
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Cmd/Ctrl + Option/Alt + Left/Right arrows for navigation
if ((e.metaKey || e.ctrlKey) && e.altKey) {
if (e.key === 'ArrowLeft') {
e.preventDefault();
const previousEntry = navigateBack();
if (previousEntry) {
// Navigate to the previous session/panel
setActiveSession(previousEntry.sessionId);
// Small delay to ensure session is set before panel
setTimeout(() => {
setActivePanelInStore(previousEntry.sessionId, previousEntry.panelId);
panelApi.setActivePanel(previousEntry.sessionId, previousEntry.panelId);
}, 50);
}
} else if (e.key === 'ArrowRight') {
e.preventDefault();
const nextEntry = navigateForward();
if (nextEntry) {
// Navigate to the next session/panel
setActiveSession(nextEntry.sessionId);
// Small delay to ensure session is set before panel
setTimeout(() => {
setActivePanelInStore(nextEntry.sessionId, nextEntry.panelId);
panelApi.setActivePanel(nextEntry.sessionId, nextEntry.panelId);
}, 50);
}
}
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [navigateBack, navigateForward, setActiveSession, setActivePanelInStore]);
// Debug logging - only in development with verbose enabled
renderLog('[SessionView] Session panels:', sessionPanels);
renderLog('[SessionView] Active panel ID:', activePanels[activeSession?.id || '']);
renderLog('[SessionView] Current active panel:', currentActivePanel);
renderLog('[SessionView] Has Claude panels:', hasClaudePanels);
// FIX: Memoize all callbacks to prevent re-renders
const handlePanelSelect = useCallback(
async (panel: ToolPanel) => {
if (!activeSession) return;
// Add to history when panel is selected
addToHistory(activeSession.id, panel.id);
setActivePanelInStore(activeSession.id, panel.id);
await panelApi.setActivePanel(activeSession.id, panel.id);
// Clear unviewed content flag when panel is viewed (for AI panels)
if (panel.type === 'claude' || panel.type === 'codex') {
const customState = panel.state?.customState as { hasUnviewedContent?: boolean; panelStatus?: string } | undefined;
if (customState?.hasUnviewedContent || customState?.panelStatus === 'completed_unviewed') {
try {
await panelApi.clearPanelUnviewedContent(panel.id);
} catch (err) {
console.error('[SessionView] Failed to clear unviewed content:', err);
}
}
}
},
[activeSession, setActivePanelInStore, addToHistory]
);
const handlePanelClose = useCallback(
async (panel: ToolPanel) => {
if (!activeSession) return;
// Find next panel to activate
const panelIndex = sessionPanels.findIndex(p => p.id === panel.id);
const nextPanel = sessionPanels[panelIndex + 1] || sessionPanels[panelIndex - 1];
// Remove from store first for immediate UI update
removePanel(activeSession.id, panel.id);
// Set next active panel if available
if (nextPanel) {
setActivePanelInStore(activeSession.id, nextPanel.id);
await panelApi.setActivePanel(activeSession.id, nextPanel.id);
}
// Delete on backend
await panelApi.deletePanel(panel.id);
},
[activeSession, sessionPanels, removePanel, setActivePanelInStore]
);
const handlePanelCreate = useCallback(
async (type: ToolPanelType) => {
if (!activeSession) return;
// For Codex panels, include the last selected model and thinking level in initial state
let initialState: { customState?: unknown } | undefined = undefined;
if (type === 'codex') {
const savedModel = localStorage.getItem('codex.lastSelectedModel');
const savedThinkingLevel = localStorage.getItem('codex.lastSelectedThinkingLevel');
initialState = {
customState: {
codexConfig: {
model: savedModel || 'auto',
modelProvider: 'openai',
thinkingLevel: savedThinkingLevel || 'medium',
sandboxMode: 'workspace-write',
webSearch: false
}
}
};
}
const newPanel = await panelApi.createPanel({
sessionId: activeSession.id,
type,
initialState
});
// Immediately add the panel and set it as active
// The panel:created event will also fire, but addPanel checks for duplicates
addPanel(newPanel);
setActivePanelInStore(activeSession.id, newPanel.id);
},
[activeSession, addPanel, setActivePanelInStore]
);
// Load project data for active session
useEffect(() => {
const loadSessionProject = async () => {
if (activeSession?.projectId) {
try {
const response = await API.projects.getAll();
if (response.success && response.data) {
const project = response.data.find((p: Project) => p.id === activeSession.projectId);
if (project) {
setSessionProject(project);
}
}
} catch (error) {
console.error('Failed to load session project:', error);
}
} else {
setSessionProject(null);
}
};
loadSessionProject();
}, [activeSession?.projectId]);
// Load project data when activeProjectId changes
useEffect(() => {
if (activeView === 'project' && activeProjectId) {
const loadProjectData = async () => {
setIsProjectLoading(true);
try {
// Get all projects and find the one we need
const response = await API.projects.getAll();
if (response.success && response.data) {
const project = response.data.find((p: Project) => p.id === activeProjectId);
if (project) {
setProjectData(project);
}
}
} catch (error) {
console.error('Failed to load project data:', error);
} finally {
setIsProjectLoading(false);
}
};
loadProjectData();
} else {
setProjectData(null);
}
}, [activeView, activeProjectId]);
const handleProjectGitPull = async () => {
if (!activeProjectId || !projectData) return;
setIsMergingProject(true);
try {
// Get or create main repo session for this project
const sessionResponse = await API.sessions.getOrCreateMainRepoSession(activeProjectId);
if (sessionResponse.success && sessionResponse.data) {
const response = await API.sessions.gitPull(sessionResponse.data.id);
if (!response.success) {
console.error('Git pull failed:', response.error);
}
}
} catch (error) {
console.error('Failed to perform git pull:', error);
} finally {
setIsMergingProject(false);
}
};
const handleProjectGitPush = async () => {
if (!activeProjectId || !projectData) return;
setIsMergingProject(true);
try {
// Get or create main repo session for this project
const sessionResponse = await API.sessions.getOrCreateMainRepoSession(activeProjectId);
if (sessionResponse.success && sessionResponse.data) {
const response = await API.sessions.gitPush(sessionResponse.data.id);
if (!response.success) {
console.error('Git push failed:', response.error);
}
}
} catch (error) {
console.error('Failed to perform git push:', error);
} finally {
setIsMergingProject(false);
}
};
const activeSession = activeSessionId
? (activeMainRepoSession && activeMainRepoSession.id === activeSessionId
? activeMainRepoSession
: sessions.find(s => s.id === activeSessionId))
: undefined;
const terminalRef = useRef<HTMLDivElement>(null);
// scriptTerminalRef removed - terminals now handled by panels
const scriptTerminalRef = useRef<HTMLDivElement>(null);
const hook = useSessionView(activeSession, terminalRef);
const hook = useSessionView(activeSession, terminalRef, scriptTerminalRef);
// Create branch actions for the panel bar
const branchActions = useMemo(() => {
if (!activeSession) return [];
return activeSession.isMainRepo ? [
{
id: 'pull',
label: 'Pull from Remote',
icon: Download,
onClick: hook.handleGitPull,
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing',
variant: 'default' as const,
description: hook.gitCommands?.getPullCommand ? `git ${hook.gitCommands.getPullCommand()}` : 'git pull'
},
{
id: 'push',
label: 'Push to Remote',
icon: Upload,
onClick: hook.handleGitPush,
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing',
variant: 'success' as const,
description: hook.gitCommands?.getPushCommand ? `git ${hook.gitCommands.getPushCommand()}` : 'git push'
}
] : [
{
id: 'rebase-from-main',
label: `Rebase from ${hook.gitCommands?.mainBranch || 'main'}`,
icon: GitMerge,
onClick: hook.handleRebaseMainIntoWorktree,
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing' || !hook.hasChangesToRebase,
variant: 'default' as const,
description: hook.gitCommands?.getRebaseFromMainCommand ? hook.gitCommands.getRebaseFromMainCommand() : `Pulls latest changes from ${hook.gitCommands?.mainBranch || 'main'}`
},
{
id: 'rebase-to-main',
label: `Merge to ${hook.gitCommands?.mainBranch || 'main'}`,
icon: GitMerge,
onClick: hook.handleSquashAndRebaseToMain,
disabled: hook.isMerging || activeSession.status === 'running' || activeSession.status === 'initializing' ||
(!activeSession.gitStatus?.totalCommits || activeSession.gitStatus?.totalCommits === 0 || activeSession.gitStatus?.ahead === 0),
variant: 'success' as const,
description: (!activeSession.gitStatus?.totalCommits || activeSession.gitStatus?.totalCommits === 0 || activeSession.gitStatus?.ahead === 0) ?
'No commits to merge' :
(hook.gitCommands?.getSquashAndRebaseToMainCommand ? hook.gitCommands.getSquashAndRebaseToMainCommand() : `Merges all commits to ${hook.gitCommands?.mainBranch || 'main'} (with safety checks)`)
},
{
id: 'open-ide',
label: hook.isOpeningIDE ? 'Opening...' : 'Open in IDE',
icon: Code2,
onClick: hook.handleOpenIDE,
disabled: activeSession.status === 'initializing' || hook.isOpeningIDE || !sessionProject?.open_ide_command,
variant: 'default' as const,
description: sessionProject?.open_ide_command ? 'Open the worktree in your default IDE' : 'No IDE command configured'
}
];
}, [activeSession, hook.isMerging, hook.gitCommands, hook.hasChangesToRebase, hook.handleGitPull, hook.handleGitPush, hook.handleRebaseMainIntoWorktree, hook.handleSquashAndRebaseToMain, hook.handleOpenIDE, hook.isOpeningIDE, sessionProject?.open_ide_command, activeSession?.gitStatus]);
// Removed unused variables - now handled by panels
// Show project view if navigation is set to project
if (activeView === 'project' && activeProjectId) {
if (isProjectLoading || !projectData) {
return (
<div className="flex-1 flex flex-col overflow-hidden bg-surface-secondary p-6">
<div className="flex items-center justify-center h-full">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-interactive mx-auto mb-4"></div>
<p className="text-text-secondary">Loading project...</p>
</div>
</div>
</div>
);
}
// Memoize props to prevent unnecessary re-renders
const emptySelectedExecutions = useMemo(() => [], []);
const isMainRepo = useMemo(() => activeSession?.isMainRepo || false, [activeSession?.isMainRepo]);
// Show project dashboard if navigation is set to dashboard
if (activeView === 'dashboard' && activeProjectId) {
return (
<ProjectView
projectId={activeProjectId}
projectName={projectData.name || 'Project'}
onGitPull={handleProjectGitPull}
onGitPush={handleProjectGitPush}
isMerging={isMergingProject}
/>
<div className="flex-1 flex flex-col overflow-hidden bg-gray-50 dark:bg-gray-900 p-6">
<ProjectDashboard
projectId={activeProjectId}
projectName="" // Will be fetched by ProjectDashboard
/>
</div>
);
}
if (!activeSession) {
return (
<div className="flex-1 flex flex-col overflow-hidden bg-bg-primary">
<div className="flex-1 flex flex-col overflow-hidden bg-gray-50 dark:bg-gray-950">
<EmptyState
icon={Inbox}
title="No Session Selected"
@ -473,7 +74,7 @@ export const SessionView = memo(() => {
}
return (
<div className="flex-1 flex flex-col overflow-hidden bg-bg-primary">
<div className="flex-1 flex flex-col overflow-hidden bg-gray-50 dark:bg-gray-900">
<SessionHeader
activeSession={activeSession}
isEditingName={hook.isEditingName}
@ -482,68 +83,153 @@ export const SessionView = memo(() => {
handleNameKeyDown={hook.handleNameKeyDown}
handleSaveEditName={hook.handleSaveEditName}
handleStartEditName={hook.handleStartEditName}
isMerging={hook.isMerging}
handleGitPull={hook.handleGitPull}
handleGitPush={hook.handleGitPush}
handleRebaseMainIntoWorktree={hook.handleRebaseMainIntoWorktree}
hasChangesToRebase={hook.hasChangesToRebase}
gitCommands={hook.gitCommands}
handleSquashAndRebaseToMain={hook.handleSquashAndRebaseToMain}
handleOpenIDE={hook.handleOpenIDE}
mergeError={hook.mergeError}
viewMode={hook.viewMode}
setViewMode={hook.setViewMode}
unreadActivity={hook.unreadActivity}
setUnreadActivity={hook.setUnreadActivity}
/>
{/* Tool Panel Bar - ALWAYS VISIBLE */}
<SessionProvider session={activeSession} gitBranchActions={branchActions} isMerging={hook.isMerging}>
<PanelTabBar
panels={sessionPanels}
activePanel={currentActivePanel}
onPanelSelect={handlePanelSelect}
onPanelClose={handlePanelClose}
onPanelCreate={handlePanelCreate}
/>
</SessionProvider>
<div className="flex-1 flex relative min-h-0">
<div className="flex-1 relative">
{/* Render panels with smart visibility - keeps critical processes alive */}
{sessionPanels.length > 0 && currentActivePanel ? (
<SessionProvider session={activeSession} gitBranchActions={branchActions} isMerging={hook.isMerging}>
{sessionPanels.map(panel => {
const isActive = panel.id === currentActivePanel.id;
const shouldKeepAlive = ['terminal', 'claude', 'codex'].includes(panel.type);
// Only render if active OR if it's a panel type that needs to stay alive
if (!isActive && !shouldKeepAlive) {
return null;
}
return (
<div
key={panel.id}
className="absolute inset-0"
style={{
display: isActive ? 'block' : 'none',
pointerEvents: isActive ? 'auto' : 'none'
}}
>
<PanelContainer
panel={panel}
isActive={isActive}
isMainRepo={!!activeSession.isMainRepo}
/>
</div>
);
})}
</SessionProvider>
) : (
<div className="flex-1 flex items-center justify-center text-text-secondary">
<div className="text-center p-8">
<div className="text-4xl mb-4">⚡</div>
<h2 className="text-xl font-semibold mb-2">No Active Panel</h2>
<p className="text-sm">Add a tool panel to get started</p>
</div>
</div>
{hook.isLoadingOutput && (
<div className="absolute top-4 left-4 text-gray-600 dark:text-gray-400 z-10">Loading output...</div>
)}
<div className={`bg-gray-50 dark:bg-black h-full ${hook.viewMode === 'output' ? 'flex flex-col' : 'hidden'} relative`}>
<div
ref={terminalRef}
className="flex-1 min-h-0"
/>
{(activeSession.status === 'running' || activeSession.status === 'initializing') && (
<div className="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 px-4 py-2 flex-shrink-0">
<div className="flex items-center justify-between text-gray-700 dark:text-gray-300">
<div className="flex items-center space-x-3">
<div className="flex space-x-1">
<div className={`w-2 h-2 bg-blue-400 rounded-full ${animationsEnabled ? 'animate-typing-dot' : ''}`}></div>
<div className={`w-2 h-2 bg-blue-400 rounded-full ${animationsEnabled ? 'animate-typing-dot' : ''}`} style={{ animationDelay: '0.2s' }}></div>
<div className={`w-2 h-2 bg-blue-400 rounded-full ${animationsEnabled ? 'animate-typing-dot' : ''}`} style={{ animationDelay: '0.4s' }}></div>
</div>
<span className="text-sm font-medium">
{activeSession.status === 'initializing' ? 'Starting Claude Code...' : 'Claude is working...'}
</span>
</div>
<div className="flex items-center space-x-3">
<div className="text-xs text-gray-600 dark:text-gray-400 font-mono">
{activeSession.status === 'initializing' ? '⚡' : hook.formatElapsedTime(hook.elapsedTime)}
</div>
<button onClick={hook.handleStopSession} className="px-3 py-1 text-xs bg-red-600 hover:bg-red-700 text-white rounded-md">
Cancel
</button>
</div>
</div>
</div>
)}
{hook.loadError && hook.viewMode === 'output' && (
<div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-center">
<div className="bg-white dark:bg-gray-800 rounded-lg p-6 border border-gray-200 dark:border-gray-700 shadow-lg">
<p className="text-gray-700 dark:text-gray-300 mb-2">Failed to load output content</p>
<p className="text-gray-600 dark:text-gray-500 text-sm mb-4">{hook.loadError}</p>
<button onClick={() => hook.loadOutputContent(activeSession.id)} className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
Reload Output
</button>
</div>
</div>
)}
</div>
<div className={`h-full ${hook.viewMode === 'messages' ? 'block' : 'hidden'}`}>
<JsonMessageView messages={activeSession.jsonMessages || []} />
</div>
<div className={`h-full ${hook.viewMode === 'changes' ? 'block' : 'hidden'} overflow-hidden`}>
<CombinedDiffView
sessionId={activeSession.id}
selectedExecutions={emptySelectedExecutions}
isGitOperationRunning={hook.isMerging}
isMainRepo={isMainRepo}
isVisible={hook.viewMode === 'changes'}
/>
</div>
<div className={`h-full ${hook.viewMode === 'terminal' ? 'flex flex-col' : 'hidden'} bg-gray-50 dark:bg-black`}>
<div className="flex items-center justify-between px-4 py-2 bg-gray-100 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700">
<div className="text-sm text-gray-600 dark:text-gray-400">
Terminal
</div>
{!activeSession.archived && (
<button
onClick={hook.handleClearTerminal}
className="p-1.5 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 hover:bg-gray-200 dark:hover:bg-gray-700 rounded transition-colors"
title="Clear terminal"
>
<svg
className="w-4 h-4"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
/>
</svg>
</button>
)}
</div>
{activeSession.archived ? (
<div className="flex-1 flex items-center justify-center p-8">
<div className="text-center max-w-md">
<div className="mb-4">
<svg className="w-16 h-16 mx-auto text-gray-400 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4" />
</svg>
</div>
<h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
No Terminal History Available
</h3>
<p className="text-sm text-gray-600 dark:text-gray-400">
This session has been archived. Terminal history is not preserved for archived sessions to save resources.
</p>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-2">
The session outputs and conversation history are still available in the Output and Messages views.
</p>
</div>
</div>
) : (
<>
<div ref={scriptTerminalRef} className="flex-1" />
<div className="h-2" />
</>
)}
</div>
<div className={`h-full ${hook.viewMode === 'editor' ? 'block' : 'hidden'}`}>
<FileEditor sessionId={activeSession.id} />
</div>
<div className={`h-full ${hook.viewMode === 'dashboard' ? 'flex flex-col p-6' : 'hidden'}`}>
{activeSession.projectId && (
<ProjectDashboard
projectId={activeSession.projectId}
projectName={activeSession.name.split(' - ')[0] || 'Project'}
/>
)}
</div>
</div>
{hook.viewMode === 'output' && (
<PromptNavigation
sessionId={activeSession.id}
onNavigateToPrompt={hook.handleNavigateToPrompt}
/>
)}
</div>
{/* Legacy session-level prompt bar removed - now handled by panels */}
{/* Legacy session-level prompt bar - COMMENTED OUT for Claude panel integration
{hook.viewMode !== 'terminal' && !currentActivePanel && (
{hook.viewMode !== 'terminal' && (
<SessionInputWithImages
activeSession={activeSession}
viewMode={hook.viewMode}
@ -557,14 +243,10 @@ export const SessionView = memo(() => {
setShowStravuSearch={hook.setShowStravuSearch}
ultrathink={hook.ultrathink}
setUltrathink={hook.setUltrathink}
handleToggleAutoCommit={hook.handleToggleAutoCommit}
gitCommands={hook.gitCommands}
handleCompactContext={hook.handleCompactContext}
hasConversationHistory={hook.hasConversationHistory}
contextCompacted={hook.contextCompacted}
handleCancelRequest={hook.handleStopSession}
/>
)}
*/}
<CommitMessageDialog
isOpen={hook.showCommitMessageDialog}
@ -576,9 +258,7 @@ export const SessionView = memo(() => {
shouldSquash={hook.shouldSquash}
setShouldSquash={hook.setShouldSquash}
onConfirm={hook.performSquashWithCommitMessage}
onMergeAndArchive={hook.performSquashWithCommitMessageAndArchive}
isMerging={hook.isMerging}
isMergingAndArchiving={hook.isMergingAndArchiving}
/>
<GitErrorDialog
@ -594,17 +274,8 @@ export const SessionView = memo(() => {
onClose={() => hook.setShowStravuSearch(false)}
onFileSelect={hook.handleStravuFileSelect}
/>
<FolderArchiveDialog
isOpen={hook.showFolderArchiveDialog}
sessionCount={hook.folderSessionCount}
onArchiveSessionOnly={hook.handleArchiveSessionOnly}
onArchiveEntireFolder={hook.handleArchiveEntireFolder}
onCancel={hook.handleCancelFolderArchive}
/>
</div>
);
});
SessionView.displayName = 'SessionView';
SessionView.displayName = 'SessionView';

View File

@ -4,26 +4,7 @@ import { StravuConnection } from './StravuConnection';
import { useNotifications } from '../hooks/useNotifications';
import { API } from '../utils/api';
import type { AppConfig } from '../types/config';
import { useConfigStore } from '../stores/configStore';
import {
Shield,
ShieldOff,
Sun,
Moon,
Settings as SettingsIcon,
Palette,
Zap,
RefreshCw,
FileText,
Eye,
BarChart3
} from 'lucide-react';
import { Input, Textarea, Checkbox } from './ui/Input';
import { Button } from './ui/Button';
import { useTheme } from '../contexts/ThemeContext';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { CollapsibleCard } from './ui/CollapsibleCard';
import { SettingsSection } from './ui/SettingsSection';
import { Shield, ShieldOff } from 'lucide-react';
interface SettingsProps {
isOpen: boolean;
@ -38,10 +19,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
const [claudeExecutablePath, setClaudeExecutablePath] = useState('');
const [defaultPermissionMode, setDefaultPermissionMode] = useState<'approve' | 'ignore'>('ignore');
const [autoCheckUpdates, setAutoCheckUpdates] = useState(true);
const [devMode, setDevMode] = useState(false);
const [additionalPathsText, setAdditionalPathsText] = useState('');
const [platform, setPlatform] = useState<string>('darwin');
const [enableCrystalFooter, setEnableCrystalFooter] = useState(true);
const [notificationSettings, setNotificationSettings] = useState({
enabled: true,
playSound: true,
@ -51,18 +28,12 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
});
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [activeTab, setActiveTab] = useState<'general' | 'notifications' | 'analytics' | 'stravu'>('general');
const [analyticsEnabled, setAnalyticsEnabled] = useState(true);
const [previousAnalyticsEnabled, setPreviousAnalyticsEnabled] = useState(true);
const [activeTab, setActiveTab] = useState<'general' | 'notifications' | 'stravu'>('general');
const { updateSettings } = useNotifications();
const { theme, toggleTheme } = useTheme();
const { fetchConfig: refreshConfigStore } = useConfigStore();
useEffect(() => {
if (isOpen) {
fetchConfig();
// Get platform for PATH help text
window.electronAPI.getPlatform().then(setPlatform);
}
}, [isOpen]);
@ -78,12 +49,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
setClaudeExecutablePath(data.claudeExecutablePath || '');
setDefaultPermissionMode(data.defaultPermissionMode || 'ignore');
setAutoCheckUpdates(data.autoCheckUpdates !== false); // Default to true
setDevMode(data.devMode || false);
setEnableCrystalFooter(data.enableCrystalFooter !== false); // Default to true
// Load additional paths
const paths = data.additionalPaths || [];
setAdditionalPathsText(paths.join('\n'));
// Load notification settings
if (data.notifications) {
@ -91,13 +56,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
// Update the useNotifications hook with loaded settings
updateSettings(data.notifications);
}
// Load analytics settings
if (data.analytics) {
const enabled = data.analytics.enabled !== false; // Default to true
setAnalyticsEnabled(enabled);
setPreviousAnalyticsEnabled(enabled);
}
} catch (err) {
setError('Failed to load configuration');
}
@ -109,43 +67,14 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
setError(null);
try {
// Parse the additional paths text into an array
const parsedPaths = additionalPathsText
.split('\n')
.map(p => p.trim())
.filter(p => p.length > 0);
// Track analytics opt-in/opt-out events if the preference changed
if (previousAnalyticsEnabled !== analyticsEnabled) {
if (analyticsEnabled) {
// User opted back in
await window.electronAPI.analytics.trackUIEvent({
event: 'analytics_opted_in',
properties: {}
});
} else {
// User opted out - send final event before disabling
await window.electronAPI.analytics.trackUIEvent({
event: 'analytics_opted_out',
properties: {}
});
}
}
const response = await API.config.update({
verbose,
anthropicApiKey,
systemPromptAppend: globalSystemPrompt,
const response = await API.config.update({
verbose,
anthropicApiKey,
systemPromptAppend: globalSystemPrompt,
claudeExecutablePath,
defaultPermissionMode,
autoCheckUpdates,
devMode,
enableCrystalFooter,
additionalPaths: parsedPaths,
notifications: notificationSettings,
analytics: {
enabled: analyticsEnabled
}
notifications: notificationSettings
});
if (!response.success) {
@ -157,10 +86,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
// Refresh config from server
await fetchConfig();
// Also refresh the global config store
await refreshConfigStore();
onClose();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update configuration');
@ -169,53 +94,54 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
}
};
return (
<Modal isOpen={isOpen} onClose={onClose} size="xl" showCloseButton={false}>
<ModalHeader
title="Crystal Settings"
icon={<SettingsIcon className="w-5 h-5" />}
onClose={onClose}
/>
if (!isOpen) return null;
<ModalBody>
{/* Tabs */}
<div className="flex border-b border-border-primary mb-8">
return (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white dark:bg-gray-800 rounded-lg w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col border border-gray-200 dark:border-gray-700">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
<h2 className="text-xl font-bold text-gray-900 dark:text-white">Settings</h2>
<button
onClick={onClose}
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300"
>
<svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
{/* Content */}
<div className="flex-1 overflow-y-auto p-6">
{/* Tabs */}
<div className="flex border-b border-gray-200 dark:border-gray-700 mb-6">
<button
onClick={() => setActiveTab('general')}
className={`px-4 py-3 text-sm font-medium transition-colors ${
className={`px-4 py-2 text-sm font-medium ${
activeTab === 'general'
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300'
}`}
>
General
</button>
<button
onClick={() => setActiveTab('notifications')}
className={`px-4 py-3 text-sm font-medium transition-colors ${
className={`px-4 py-2 text-sm font-medium ${
activeTab === 'notifications'
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300'
}`}
>
Notifications
</button>
<button
onClick={() => setActiveTab('analytics')}
className={`px-4 py-3 text-sm font-medium transition-colors ${
activeTab === 'analytics'
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
}`}
>
Analytics
</button>
<button
onClick={() => setActiveTab('stravu')}
className={`px-4 py-3 text-sm font-medium transition-colors ${
className={`px-4 py-2 text-sm font-medium ${
activeTab === 'stravu'
? 'text-interactive border-b-2 border-interactive bg-interactive/5'
: 'text-text-tertiary hover:text-text-primary hover:bg-surface-hover'
? 'text-blue-600 dark:text-blue-400 border-b-2 border-blue-500'
: 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300'
}`}
>
Stravu Integration
@ -223,301 +149,207 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
</div>
{activeTab === 'general' && (
<form id="settings-form" onSubmit={handleSubmit} className="space-y-6">
{/* Appearance */}
<CollapsibleCard
title="Appearance & Theme"
subtitle="Customize how Crystal looks and feels"
icon={<Palette className="w-5 h-5" />}
defaultExpanded={true}
>
<SettingsSection
title="Theme Mode"
description="Choose between light and dark theme"
icon={theme === 'light' ? <Sun className="w-4 h-4" /> : <Moon className="w-4 h-4" />}
>
<button
type="button"
onClick={toggleTheme}
className="flex items-center gap-3 px-4 py-3 bg-surface-secondary hover:bg-surface-hover rounded-lg transition-colors border border-border-secondary w-full"
>
{theme === 'light' ? (
<>
<Sun className="w-5 h-5 text-status-warning" />
<span className="text-text-primary font-medium">Light Mode</span>
<span className="ml-auto text-xs text-text-tertiary">Currently active</span>
</>
) : (
<>
<Moon className="w-5 h-5 text-interactive" />
<span className="text-text-primary font-medium">Dark Mode</span>
<span className="ml-auto text-xs text-text-tertiary">Currently active</span>
</>
)}
</button>
</SettingsSection>
</CollapsibleCard>
<form id="settings-form" onSubmit={handleSubmit} className="space-y-4">
{/* AI Integration */}
<CollapsibleCard
title="AI Integration"
subtitle="Configure Claude integration and smart features"
icon={<Zap className="w-5 h-5" />}
defaultExpanded={true}
<div>
<label className="flex items-center space-x-2">
<input
type="checkbox"
checked={verbose}
onChange={(e) => setVerbose(e.target.checked)}
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">Enable verbose logging</span>
</label>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Shows detailed logs for debugging session creation and Claude Code execution
</p>
</div>
{/* Theme toggle disabled - dark mode only */}
{/* <div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
Theme
</label>
<button
type="button"
onClick={toggleTheme}
className="flex items-center space-x-3 px-4 py-2 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 rounded-md transition-colors"
>
<SettingsSection
title="Smart Session Names"
description="Let Claude automatically generate meaningful names for your sessions"
icon={<FileText className="w-4 h-4" />}
>
<Input
label="Anthropic API Key"
type="password"
value={anthropicApiKey}
onChange={(e) => setAnthropicApiKey(e.target.value)}
placeholder="sk-ant-..."
fullWidth
helperText="Optional: Used only for generating session names. Your main Claude Code API key is separate."
{theme === 'light' ? (
<>
<Sun className="w-5 h-5 text-yellow-400" />
<span className="text-gray-700 dark:text-gray-100">Light Mode</span>
</>
) : (
<>
<Moon className="w-5 h-5 text-blue-400" />
<span className="text-gray-700 dark:text-gray-100">Dark Mode</span>
</>
)}
</button>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Toggle between light and dark theme
</p>
</div> */}
<div>
<label htmlFor="anthropicApiKey" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Anthropic API Key (Optional)
</label>
<input
id="anthropicApiKey"
type="password"
value={anthropicApiKey}
onChange={(e) => setAnthropicApiKey(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700"
placeholder="sk-ant-..."
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Used for auto-generating session names with AI (NOT for Claude Code itself). If not provided, fallback names will be used.
</p>
</div>
<div>
<label htmlFor="globalSystemPrompt" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Global System Prompt (Optional)
</label>
<textarea
id="globalSystemPrompt"
value={globalSystemPrompt}
onChange={(e) => setGlobalSystemPrompt(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 dark:text-gray-100 bg-white dark:bg-gray-700"
placeholder="Additional instructions to append to every prompt..."
rows={3}
/>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
This text will be automatically appended to every initial prompt sent to Claude Code across ALL projects. For project-specific prompts, use the project settings.
</p>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Default Permission Mode
</label>
<div className="space-y-2">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="defaultPermissionMode"
value="ignore"
checked={defaultPermissionMode === 'ignore'}
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
className="text-blue-600"
/>
</SettingsSection>
<SettingsSection
title="Default Security Mode"
description="How Claude should handle potentially risky operations"
icon={defaultPermissionMode === 'approve' ? <Shield className="w-4 h-4" /> : <ShieldOff className="w-4 h-4" />}
>
<div className="space-y-3">
<label className="flex items-start gap-3 cursor-pointer p-3 rounded-lg hover:bg-surface-hover transition-colors border border-border-secondary">
<input
type="radio"
name="defaultPermissionMode"
value="ignore"
checked={defaultPermissionMode === 'ignore'}
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
className="text-interactive mt-1"
/>
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<ShieldOff className="w-4 h-4 text-text-tertiary" />
<span className="text-sm font-medium text-text-primary">Fast & Flexible</span>
<span className="ml-auto px-2 py-0.5 text-xs bg-status-warning/20 text-status-warning rounded-full">Default</span>
</div>
<p className="text-xs text-text-tertiary leading-relaxed">
Claude executes commands quickly without asking permission. Great for development workflows.
</p>
</div>
</label>
<label className="flex items-start gap-3 cursor-pointer p-3 rounded-lg hover:bg-surface-hover transition-colors border border-border-secondary">
<input
type="radio"
name="defaultPermissionMode"
value="approve"
checked={defaultPermissionMode === 'approve'}
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
className="text-interactive mt-1"
/>
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<Shield className="w-4 h-4 text-status-success" />
<span className="text-sm font-medium text-text-primary">Secure & Controlled</span>
</div>
<p className="text-xs text-text-tertiary leading-relaxed">
Claude asks for your approval before running potentially risky commands. Safer for production code.
</p>
</div>
</label>
<div className="flex items-center gap-2">
<ShieldOff className="w-4 h-4 text-gray-500 dark:text-gray-400" />
<span className="text-sm text-gray-700 dark:text-gray-200">Skip Permissions (Default)</span>
<span className="text-xs text-gray-500 dark:text-gray-400">(faster, less secure)</span>
</div>
</SettingsSection>
<SettingsSection
title="Global Instructions"
description="Add custom instructions that apply to all your projects"
icon={<FileText className="w-4 h-4" />}
>
<Textarea
label="Global System Prompt"
value={globalSystemPrompt}
onChange={(e) => setGlobalSystemPrompt(e.target.value)}
placeholder="Always use TypeScript... Follow our team's coding standards..."
rows={3}
fullWidth
helperText="These instructions will be added to every Claude session across all projects."
</label>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="radio"
name="defaultPermissionMode"
value="approve"
checked={defaultPermissionMode === 'approve'}
onChange={(e) => setDefaultPermissionMode(e.target.value as 'ignore' | 'approve')}
className="text-blue-600"
/>
</SettingsSection>
<SettingsSection
title="Crystal Attribution"
description="Add Crystal branding to commit messages"
icon={<FileText className="w-4 h-4" />}
>
<Checkbox
label="Include Crystal footer in commits"
checked={enableCrystalFooter}
onChange={(e) => setEnableCrystalFooter(e.target.checked)}
/>
<p className="text-xs text-text-tertiary mt-1">
When enabled, commits made through Crystal will include a footer crediting Crystal. This helps others know you're using Crystal for AI-powered development.
</p>
</SettingsSection>
</CollapsibleCard>
{/* System Updates */}
<CollapsibleCard
title="Updates & Maintenance"
subtitle="Keep Crystal up to date with the latest features"
icon={<RefreshCw className="w-5 h-5" />}
defaultExpanded={false}
>
<SettingsSection
title="Automatic Updates"
description="Stay current with new features and bug fixes"
icon={<RefreshCw className="w-4 h-4" />}
>
<div className="flex items-center justify-between p-3 bg-surface-secondary rounded-lg border border-border-secondary">
<div className="flex items-center gap-3">
<Checkbox
label="Check for updates automatically"
checked={autoCheckUpdates}
onChange={(e) => setAutoCheckUpdates(e.target.checked)}
/>
</div>
<Button
type="button"
variant="secondary"
size="sm"
onClick={async () => {
try {
const response = await API.checkForUpdates();
if (response.success && response.data) {
if (response.data.hasUpdate) {
// Update will be shown via the version update event
} else {
alert('You are running the latest version of Crystal!');
}
}
} catch (error) {
console.error('Failed to check for updates:', error);
alert('Failed to check for updates. Please try again later.');
}
}}
>
Check Now
</Button>
<div className="flex items-center gap-2">
<Shield className="w-4 h-4 text-green-500" />
<span className="text-sm text-gray-700 dark:text-gray-200">Approve Actions</span>
<span className="text-xs text-gray-500 dark:text-gray-400">(safer, interactive)</span>
</div>
<p className="text-xs text-text-tertiary mt-2">
We check GitHub for new releases every 24 hours. Updates require manual installation.
</p>
</SettingsSection>
</CollapsibleCard>
</label>
</div>
<p className="text-xs text-gray-600 dark:text-gray-500 mt-2">
When enabled, Claude will ask for permission before performing potentially dangerous actions. This sets the default for new sessions.
</p>
</div>
{/* Advanced Options */}
<CollapsibleCard
title="Advanced Options"
subtitle="Technical settings for power users"
icon={<Eye className="w-5 h-5" />}
defaultExpanded={false}
variant="subtle"
>
<SettingsSection
title="Debugging"
description="Enable detailed logging for troubleshooting"
icon={<FileText className="w-4 h-4" />}
>
<Checkbox
label="Enable verbose logging"
checked={verbose}
onChange={(e) => setVerbose(e.target.checked)}
/>
<p className="text-xs text-text-tertiary mt-1">
Shows detailed logs for session creation and Claude Code execution. Useful for debugging issues.
</p>
<div className="mt-4">
<Checkbox
label="Enable dev mode"
checked={devMode}
onChange={(e) => setDevMode(e.target.checked)}
/>
<p className="text-xs text-text-tertiary mt-1">
Adds a "Messages" tab to each session showing raw JSON responses from Claude Code. Useful for debugging and development.
</p>
</div>
</SettingsSection>
<SettingsSection
title="Additional PATH Directories"
description="Add custom directories to the PATH environment variable"
icon={<FileText className="w-4 h-4" />}
>
<Textarea
label=""
value={additionalPathsText}
onChange={(e) => setAdditionalPathsText(e.target.value)}
placeholder={
platform === 'win32'
? "C:\\tools\\bin\nC:\\Program Files\\MyApp\n%USERPROFILE%\\bin"
: platform === 'darwin'
? "/opt/homebrew/bin\n/usr/local/bin\n~/bin\n~/.cargo/bin"
: "/usr/local/bin\n/opt/bin\n~/bin\n~/.local/bin"
<div>
<label htmlFor="claudeExecutablePath" className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
Claude Executable Path (Optional)
</label>
<div className="flex gap-2">
<input
id="claudeExecutablePath"
type="text"
value={claudeExecutablePath}
onChange={(e) => setClaudeExecutablePath(e.target.value)}
className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-900 bg-white"
placeholder="/usr/local/bin/claude"
/>
<button
type="button"
onClick={async () => {
const result = await API.dialog.openFile({
title: 'Select Claude Executable',
buttonLabel: 'Select',
properties: ['openFile'],
filters: [
{ name: 'Executables', extensions: ['*'] }
]
});
if (result.success && result.data) {
setClaudeExecutablePath(result.data);
}
rows={4}
fullWidth
helperText={
`Enter one directory path per line. These will be added to PATH for all tools.\n${
platform === 'win32'
? "Windows: Use backslashes (C:\\path) or forward slashes (C:/path). Environment variables like %USERPROFILE% are supported."
: "Unix/macOS: Use forward slashes (/path). The tilde (~) expands to your home directory."
}\nNote: Changes require restarting Crystal to take full effect.`
}
/>
</SettingsSection>
<SettingsSection
title="Custom Claude Installation"
description="Override the default Claude executable path"
icon={<FileText className="w-4 h-4" />}
}}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
>
<div className="flex gap-2">
Browse
</button>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Full path to the claude executable. Leave empty to use the claude command from PATH. This is useful if Claude is installed in a non-standard location.
</p>
</div>
<div>
<div className="flex items-start justify-between">
<div className="flex-1">
<label className="flex items-center space-x-2">
<input
id="claudeExecutablePath"
type="text"
value={claudeExecutablePath}
onChange={(e) => setClaudeExecutablePath(e.target.value)}
className="flex-1 px-3 py-2 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-secondary"
placeholder="/usr/local/bin/claude"
type="checkbox"
checked={autoCheckUpdates}
onChange={(e) => setAutoCheckUpdates(e.target.checked)}
className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
/>
<Button
type="button"
variant="secondary"
size="sm"
onClick={async () => {
const result = await API.dialog.openFile({
title: 'Select Claude Executable',
buttonLabel: 'Select',
properties: ['openFile'],
filters: [
{ name: 'Executables', extensions: ['*'] }
]
});
if (result.success && result.data) {
setClaudeExecutablePath(result.data);
}
}}
>
Browse
</Button>
</div>
<p className="text-xs text-text-tertiary mt-1">
Leave empty to use the 'claude' command from your system PATH.
<span className="text-sm font-medium text-gray-700 dark:text-gray-300">Check for updates automatically</span>
</label>
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
Automatically check for new Crystal releases on GitHub every 24 hours. You'll be notified when updates are available.
</p>
</SettingsSection>
</CollapsibleCard>
{error && (
<div className="text-status-error text-sm bg-status-error/10 border border-status-error/30 rounded-lg p-4">
{error}
</div>
)}
<button
type="button"
onClick={async () => {
try {
const response = await API.checkForUpdates();
if (response.success && response.data) {
if (response.data.hasUpdate) {
// Update will be shown via the version update event
} else {
alert('You are running the latest version of Crystal!');
}
}
} catch (error) {
console.error('Failed to check for updates:', error);
alert('Failed to check for updates. Please try again later.');
}
}}
className="ml-4 px-3 py-1 text-sm font-medium text-blue-600 dark:text-blue-500 hover:text-blue-700 dark:hover:text-blue-400 focus:outline-none"
>
Check Now
</button>
</div>
</div>
{error && (
<div className="text-red-600 text-sm">{error}</div>
)}
</form>
)}
@ -529,185 +361,65 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
}}
/>
)}
{activeTab === 'analytics' && (
<form id="analytics-form" onSubmit={handleSubmit} className="space-y-6">
{/* Analytics Overview */}
<CollapsibleCard
title="About Analytics"
subtitle="Help improve Crystal by sharing anonymous usage data"
icon={<BarChart3 className="w-5 h-5" />}
defaultExpanded={true}
variant="subtle"
>
<div className="space-y-4">
<p className="text-sm text-text-secondary leading-relaxed">
Crystal collects anonymous usage analytics to understand how the application is used and to help prioritize improvements. All data is completely anonymous and privacy-focused.
</p>
<div className="bg-surface-tertiary rounded-lg p-4 border border-border-secondary">
<h4 className="font-medium text-text-primary mb-3 text-sm">✅ What we track:</h4>
<ul className="space-y-1 text-xs text-text-secondary">
<li>• Feature usage patterns (which features are used)</li>
<li>• Session counts and statuses</li>
<li>• Git operation types (rebase, squash, etc.)</li>
<li>• UI interactions (view switches, button clicks)</li>
<li>• Error types (generic categories only)</li>
<li>• Performance metrics (categorized durations)</li>
</ul>
</div>
<div className="bg-status-error/10 rounded-lg p-4 border border-status-error/30">
<h4 className="font-medium text-text-primary mb-3 text-sm">❌ What we NEVER track:</h4>
<ul className="space-y-1 text-xs text-text-secondary">
<li>• Your prompts or AI responses</li>
<li>• File paths, names, or directory structures</li>
<li>• Project names or descriptions</li>
<li>• Git commit messages or code diffs</li>
<li>• Terminal output or commands</li>
<li>• Personal identifiers (emails, usernames, API keys)</li>
</ul>
</div>
<p className="text-xs text-text-tertiary italic">
You can opt-out at any time. When disabled, no analytics data will be collected or sent.
</p>
</div>
</CollapsibleCard>
{/* Analytics Settings */}
<CollapsibleCard
title="Analytics Settings"
subtitle="Configure anonymous usage tracking"
icon={<BarChart3 className="w-5 h-5" />}
defaultExpanded={true}
>
<SettingsSection
title="Enable Analytics"
description="Allow Crystal to collect anonymous usage data to improve the product"
icon={<BarChart3 className="w-4 h-4" />}
>
<Checkbox
label="Enable anonymous analytics tracking"
checked={analyticsEnabled}
onChange={(e) => setAnalyticsEnabled(e.target.checked)}
/>
{!analyticsEnabled && (
<p className="text-xs text-status-warning mt-2">
Analytics is disabled. No data will be collected or sent.
</p>
)}
{analyticsEnabled && (
<p className="text-xs text-status-success mt-2">
Analytics is enabled. Thank you for helping improve Crystal!
</p>
)}
</SettingsSection>
</CollapsibleCard>
{error && (
<div className="text-status-error text-sm bg-status-error/10 border border-status-error/30 rounded-lg p-4">
{error}
</div>
)}
</form>
)}
{activeTab === 'stravu' && (
<div className="space-y-6">
{/* Stravu Introduction */}
<CollapsibleCard
title="About Stravu Integration"
subtitle="Connect your team's knowledge to your AI workflow"
icon={
<img
src="./stravu-logo.png"
alt="Stravu Logo"
className="w-5 h-5 object-contain"
/>
}
defaultExpanded={true}
variant="subtle"
>
<div className="space-y-4">
<p className="text-sm text-text-secondary leading-relaxed">
Stravu is the knowledge platform for AI-first teams. Connect Crystal to your Stravu workspace to give Claude access to your team's documentation, best practices, and institutional knowledge.
<div className="flex items-start gap-4">
<img
src="./stravu-logo.png"
alt="Stravu Logo"
className="w-16 h-16 object-contain flex-shrink-0"
/>
<div className="flex-1">
<h2 className="text-lg font-semibold text-gray-900 dark:text-gray-100 mb-2">
Stravu - The way AI-first teams collaborate
</h2>
<p className="text-sm text-gray-600 dark:text-gray-400 mb-3">
Connect Crystal to your Stravu workspace to seamlessly integrate your team's knowledge and documentation into your AI-powered development workflow.
</p>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
<div className="p-3 bg-surface-tertiary rounded-lg">
<h4 className="font-medium text-text-primary mb-1">🚀 Smart Context</h4>
<p className="text-text-tertiary">Claude automatically pulls relevant docs and standards</p>
</div>
<div className="p-3 bg-surface-tertiary rounded-lg">
<h4 className="font-medium text-text-primary mb-1">👥 Team Alignment</h4>
<p className="text-text-tertiary">Ensure AI follows your team's patterns and conventions</p>
</div>
<div className="p-3 bg-surface-tertiary rounded-lg">
<h4 className="font-medium text-text-primary mb-1">📚 Knowledge Base</h4>
<p className="text-text-tertiary">Surface relevant documentation during development</p>
</div>
<div className="p-3 bg-surface-tertiary rounded-lg">
<h4 className="font-medium text-text-primary mb-1">🔄 Always Current</h4>
<p className="text-text-tertiary">Real-time sync with your latest team knowledge</p>
</div>
</div>
<div className="flex items-center justify-between pt-2 border-t border-border-secondary">
<a
href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1"
target="_blank"
rel="noopener noreferrer"
className="text-interactive hover:text-interactive-hover text-sm inline-flex items-center gap-2 font-medium transition-colors"
>
Learn more about Stravu
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
<span className="text-xs text-text-tertiary">
Made by the Crystal team
</span>
</div>
<a
href="https://stravu.com/?utm_source=Crystal&utm_medium=OS&utm_campaign=Crystal&utm_id=1"
target="_blank"
rel="noopener noreferrer"
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 text-sm font-medium inline-flex items-center gap-1"
>
Learn more about Stravu
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
</div>
</CollapsibleCard>
{/* Connection Management */}
<CollapsibleCard
title="Connection Management"
subtitle="Connect and manage your Stravu workspace integration"
icon={<Zap className="w-5 h-5" />}
defaultExpanded={true}
>
</div>
<div className="border-t border-gray-700 pt-6">
<StravuConnection />
</CollapsibleCard>
</div>
</div>
)}
</ModalBody>
</div>
{/* Footer */}
{(activeTab === 'general' || activeTab === 'notifications' || activeTab === 'analytics') && (
<ModalFooter>
<Button
type="button"
variant="ghost"
onClick={onClose}
disabled={isSubmitting}
>
Cancel
</Button>
<Button
type={activeTab === 'general' ? 'submit' : 'button'}
form={activeTab === 'general' ? 'settings-form' : undefined}
onClick={activeTab === 'notifications' ? (e) => handleSubmit(e as React.FormEvent) : undefined}
disabled={isSubmitting}
loading={isSubmitting}
variant="primary"
>
Save Changes
</Button>
</ModalFooter>
)}
</Modal>
{/* Footer */}
{(activeTab === 'general' || activeTab === 'notifications') && (
<div className="flex justify-end space-x-3 p-6 border-t border-gray-200 dark:border-gray-700">
<button
type="button"
onClick={onClose}
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
disabled={isSubmitting}
>
Cancel
</button>
<button
type={activeTab === 'general' ? 'submit' : 'button'}
form={activeTab === 'general' ? 'settings-form' : undefined}
onClick={activeTab === 'notifications' ? (e) => handleSubmit(e as any) : undefined}
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 transition-colors"
disabled={isSubmitting}
>
{isSubmitting ? 'Saving...' : 'Save'}
</button>
</div>
)}
</div>
</div>
);
}

View File

@ -1,11 +1,8 @@
import { useState, useEffect } from 'react';
import { Settings } from './Settings';
import { DraggableProjectTreeView } from './DraggableProjectTreeView';
import { ArchiveProgress } from './ArchiveProgress';
import { Info, Clock, Check, Edit, CircleArrowDown, AlertTriangle, GitMerge, ArrowUpDown } from 'lucide-react';
import { Info, Clock } from 'lucide-react';
import crystalLogo from '../assets/crystal-logo.svg';
import { IconButton } from './ui/Button';
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
interface SidebarProps {
onHelpClick: () => void;
@ -20,70 +17,33 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
const [showStatusGuide, setShowStatusGuide] = useState(false);
const [version, setVersion] = useState<string>('');
const [gitCommit, setGitCommit] = useState<string>('');
const [worktreeName, setWorktreeName] = useState<string>('');
const [sessionSortAscending, setSessionSortAscending] = useState<boolean>(false); // Default to descending (newest first)
useEffect(() => {
// Fetch version info and UI state on component mount
// Fetch version info on component mount
const fetchVersion = async () => {
try {
console.log('[Sidebar Debug] Fetching version info...');
const result = await window.electronAPI.getVersionInfo();
console.log('[Sidebar Debug] Version info result:', result);
if (result.success && result.data) {
console.log('[Sidebar Debug] Version data:', result.data);
if (result.data.current) {
setVersion(result.data.current);
console.log('[Sidebar Debug] Set version:', result.data.current);
}
if (result.data.gitCommit) {
setGitCommit(result.data.gitCommit);
console.log('[Sidebar Debug] Set gitCommit:', result.data.gitCommit);
}
if (result.data.worktreeName) {
setWorktreeName(result.data.worktreeName);
console.log('[Sidebar Debug] Set worktreeName:', result.data.worktreeName);
} else {
console.log('[Sidebar Debug] No worktreeName in response');
}
}
} catch (error) {
console.error('Failed to fetch version:', error);
}
};
const loadUIState = async () => {
try {
const result = await window.electronAPI.uiState.getExpanded();
if (result.success && result.data) {
setSessionSortAscending(result.data.sessionSortAscending ?? false);
}
} catch (error) {
console.error('Failed to load UI state:', error);
}
};
fetchVersion();
loadUIState();
}, []);
const toggleSessionSortOrder = async () => {
const newValue = !sessionSortAscending;
setSessionSortAscending(newValue);
// Save to database via electronAPI
try {
await window.electronAPI.uiState.saveSessionSortAscending(newValue);
} catch (error) {
console.error('Failed to save session sort order:', error);
}
};
return (
<>
<div
data-testid="sidebar"
className="bg-surface-primary text-text-primary h-full flex flex-col pt-4 relative flex-shrink-0 border-r border-border-primary"
className="bg-white dark:bg-gray-800 text-gray-900 dark:text-white h-full flex flex-col pt-4 relative flex-shrink-0 border-r border-gray-200 dark:border-gray-700"
style={{ width: `${width}px` }}
>
{/* Resize handle */}
@ -92,263 +52,178 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
onMouseDown={onResize}
>
{/* Visual indicator */}
<div className="absolute inset-0 bg-border-secondary group-hover:bg-interactive transition-colors" />
<div className="absolute inset-0 bg-gray-300 dark:bg-gray-700 group-hover:bg-blue-500 transition-colors" />
{/* Larger grab area */}
<div className="absolute -left-2 -right-2 top-0 bottom-0" />
{/* Drag indicator dots */}
<div className="absolute top-1/2 -translate-y-1/2 right-0 transform translate-x-1/2 opacity-0 group-hover:opacity-100 transition-opacity">
<div className="flex flex-col gap-1">
<div className="w-1 h-1 bg-interactive rounded-full" />
<div className="w-1 h-1 bg-interactive rounded-full" />
<div className="w-1 h-1 bg-interactive rounded-full" />
<div className="w-1 h-1 bg-blue-400 rounded-full" />
<div className="w-1 h-1 bg-blue-400 rounded-full" />
<div className="w-1 h-1 bg-blue-400 rounded-full" />
</div>
</div>
</div>
<div className="p-4 border-b border-border-primary flex items-center justify-between overflow-hidden">
<div className="p-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between overflow-hidden">
<div className="flex items-center space-x-2 min-w-0">
<img src={crystalLogo} alt="Crystal" className="h-6 w-6 flex-shrink-0" />
<h1 className="text-xl font-bold truncate">Crystal</h1>
</div>
<div className="flex items-center space-x-2 flex-shrink-0">
<IconButton
<button
onClick={onHelpClick}
aria-label="Help"
size="md"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
}
/>
<IconButton
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
title="Help"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
<button
onClick={() => setIsSettingsOpen(true)}
aria-label="Settings"
data-testid="settings-button"
size="md"
icon={
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
}
/>
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors"
title="Settings"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
</button>
</div>
</div>
<div className="flex-1 overflow-y-auto overflow-x-hidden min-h-0">
<div className="px-4 py-2 text-sm uppercase flex items-center justify-between overflow-hidden">
<span className="truncate text-text-tertiary">Projects & Sessions</span>
<span className="truncate text-gray-700 dark:text-gray-400">Projects & Sessions</span>
<div className="flex items-center space-x-1">
<IconButton
aria-label={sessionSortAscending ? "Sort sessions: Oldest first (click to reverse)" : "Sort sessions: Newest first (click to reverse)"}
size="sm"
onClick={toggleSessionSortOrder}
icon={<ArrowUpDown className="w-4 h-4" />}
/>
<IconButton
aria-label="View Prompt History (Cmd/Ctrl + P)"
size="sm"
<button
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
title="View Prompt History (Cmd/Ctrl + P)"
onClick={onPromptHistoryClick}
icon={<Clock className="w-4 h-4" />}
/>
<IconButton
aria-label="View status legend"
size="sm"
>
<Clock className="w-4 h-4" />
</button>
<button
className="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200 transition-colors p-1 rounded hover:bg-gray-200 dark:hover:bg-gray-700"
title="View status legend"
onClick={() => setShowStatusGuide(true)}
icon={<Info className="w-4 h-4" />}
/>
>
<Info className="w-4 h-4" />
</button>
</div>
</div>
<DraggableProjectTreeView sessionSortAscending={sessionSortAscending} />
<DraggableProjectTreeView />
</div>
{/* Bottom section - always visible */}
<div className="flex-shrink-0">
{/* Archive progress indicator above version */}
<ArchiveProgress />
{/* Version display at bottom */}
{version && (
<div className="px-4 py-2 border-t border-border-primary">
<div
className="text-xs text-text-tertiary text-center cursor-pointer hover:text-text-secondary transition-colors truncate"
onClick={onAboutClick}
title="Click to view version details"
>
v{version}{worktreeName && ` • ${worktreeName}`}{gitCommit && ` • ${gitCommit}`}
</div>
{/* Version display at bottom */}
{version && (
<div className="px-4 py-2 border-t border-gray-200 dark:border-gray-700">
<div
className="text-xs text-gray-500 dark:text-gray-500 text-center cursor-pointer hover:text-gray-700 dark:hover:text-gray-400 transition-colors"
onClick={onAboutClick}
title="Click to view version details"
>
v{version}{gitCommit && ` • ${gitCommit}`}
</div>
)}
</div>
</div>
)}
</div>
<Settings isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
{/* Status Guide Modal */}
<Modal
isOpen={showStatusGuide}
onClose={() => setShowStatusGuide(false)}
size="lg"
>
<ModalHeader>Status Indicators Guide</ModalHeader>
<ModalBody>
{showStatusGuide && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" onClick={() => setShowStatusGuide(false)}>
<div className="bg-white dark:bg-gray-900 rounded-lg shadow-xl p-6 max-w-md w-full mx-4" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center justify-between mb-4">
<h3 className="text-lg font-semibold text-gray-900 dark:text-white">Status Indicators Guide</h3>
<button
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
onClick={() => setShowStatusGuide(false)}
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div className="space-y-4">
{/* Project Indicators */}
<div className="pb-3 border-b border-border-primary">
<h4 className="text-sm font-medium text-text-primary mb-2">Project Indicators</h4>
<div className="pb-3 border-b border-gray-200 dark:border-gray-700">
<h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Project Indicators</h4>
<div className="flex items-center gap-3">
<div className="relative">
<svg className="w-4 h-4 text-interactive" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
<svg className="w-4 h-4 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth="2">
<path d="M6 3v12M6 3a9 9 0 0 0 9 9m-9-9a9 9 0 0 1 9 9m0-9h12" />
</svg>
<div className="absolute -bottom-0.5 -right-0.5 w-2 h-2 bg-status-success rounded-full"></div>
<div className="absolute -bottom-0.5 -right-0.5 w-2 h-2 bg-green-500 rounded-full"></div>
</div>
<div>
<span className="text-text-secondary font-medium">Git Project</span>
<p className="text-text-tertiary text-sm">Project connected to a git repository</p>
<span className="text-gray-700 dark:text-gray-200 font-medium">Git Project</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Project connected to a git repository</p>
</div>
</div>
</div>
{/* Session Status Indicators */}
<div className="pb-3 border-b border-border-primary">
<h4 className="text-sm font-medium text-text-primary mb-2">Session Status</h4>
<div>
<h4 className="text-sm font-medium text-gray-900 dark:text-white mb-2">Session Status</h4>
<div className="space-y-3">
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-status-success rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-text-secondary font-medium">Initializing</span>
<p className="text-text-tertiary text-sm">Setting up git worktree and environment</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-status-success rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-text-secondary font-medium">Running</span>
<p className="text-text-tertiary text-sm">Claude is actively processing your request</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-status-warning rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-text-secondary font-medium">Waiting</span>
<p className="text-text-tertiary text-sm">Claude needs your input to continue</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-status-neutral rounded-full flex-shrink-0"></div>
<div>
<span className="text-text-secondary font-medium">Completed</span>
<p className="text-text-tertiary text-sm">Task finished successfully</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-status-info rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-text-secondary font-medium">New Activity</span>
<p className="text-text-tertiary text-sm">Session has new unviewed results</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-status-error rounded-full flex-shrink-0"></div>
<div>
<span className="text-text-secondary font-medium">Error</span>
<p className="text-text-tertiary text-sm">Something went wrong with the session</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-green-500 rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-gray-700 dark:text-gray-200 font-medium">Initializing</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Setting up git worktree and environment</p>
</div>
</div>
{/* Git Status Indicators */}
<div>
<h4 className="text-sm font-medium text-text-primary mb-2">Git Status Indicators</h4>
<p className="text-text-tertiary text-sm mb-3">Click any indicator to view detailed changes in the Diff panel</p>
{/* HIGH PRIORITY */}
<div className="mb-3">
<p className="text-xs font-medium text-text-tertiary mb-2">HIGH PRIORITY</p>
<div className="space-y-2">
<div className="flex items-center gap-3 p-2 rounded">
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-success/10 text-status-success border-border-primary">
<GitMerge className="w-3.5 h-3.5" strokeWidth={2} />
<span className="font-bold">3</span>
</span>
<span className="text-xs text-text-secondary"><strong>Ready to Merge</strong> - Changes ready to merge cleanly</span>
</div>
<div className="flex items-center gap-3 p-2 rounded">
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-warning/10 text-status-warning border-border-primary">
<AlertTriangle className="w-3.5 h-3.5" strokeWidth={2} />
<span className="font-bold">2</span>
</span>
<span className="text-xs text-text-secondary"><strong>Conflict Risk</strong> - Behind main, potential conflicts</span>
</div>
</div>
</div>
{/* SPECIAL CASES */}
<div className="mb-3">
<p className="text-xs font-medium text-text-tertiary mb-2">SPECIAL CASES</p>
<div className="space-y-2">
<div className="flex items-center gap-3 p-2 rounded">
<span className="inline-flex items-center justify-center w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-error/10 text-status-error border-border-primary">
<AlertTriangle className="w-3.5 h-3.5" strokeWidth={2} />
</span>
<span className="text-xs text-text-secondary"><strong>Conflicts</strong> - Active merge conflicts need resolution</span>
</div>
<div className="flex items-center gap-3 p-2 rounded">
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-status-info/10 text-status-info border-border-primary">
<Edit className="w-3.5 h-3.5" strokeWidth={2} />
<span className="font-bold">2</span>
</span>
<span className="text-xs text-text-secondary"><strong>Uncommitted</strong> - Work in progress</span>
</div>
</div>
</div>
{/* LOW PRIORITY */}
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-green-500 rounded-full animate-pulse flex-shrink-0"></div>
<div>
<p className="text-xs font-medium text-text-tertiary mb-2">LOW PRIORITY</p>
<div className="space-y-2">
<div className="flex items-center gap-3 p-2 rounded">
<span className="inline-flex items-center justify-center gap-0.5 w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-bg-tertiary text-text-tertiary border-border-primary">
<CircleArrowDown className="w-3.5 h-3.5" strokeWidth={2} />
<span className="font-bold">2</span>
</span>
<span className="text-xs text-text-secondary"><strong>Behind Only</strong> - No unique changes</span>
</div>
<div className="flex items-center gap-3 p-2 rounded">
<span className="inline-flex items-center justify-center w-[5.5ch] px-1.5 py-0.5 text-xs rounded-md border bg-bg-tertiary text-text-tertiary border-border-primary">
<Check className="w-3.5 h-3.5" strokeWidth={2} />
</span>
<span className="text-xs text-text-secondary"><strong>Up to Date</strong> - Safe to remove</span>
</div>
</div>
<span className="text-gray-700 dark:text-gray-200 font-medium">Running</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Claude is actively processing your request</p>
</div>
<div className="mt-4 p-3 bg-status-info/10 border border-status-info/20 rounded-lg">
<p className="font-medium text-status-info text-xs mb-2">Tips</p>
<ul className="list-disc list-inside space-y-1 text-xs text-text-secondary">
<li>Focus on <strong>High Priority</strong> branches first</li>
<li>Numbers show commit count or file changes</li>
<li>Star (★) indicates counts above 9</li>
<li>Gray indicators are low priority - often safe to remove</li>
<li>Click any indicator to view detailed diff</li>
</ul>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-amber-500 rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-gray-700 dark:text-gray-200 font-medium">Waiting</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Claude needs your input to continue</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-gray-400 rounded-full flex-shrink-0"></div>
<div>
<span className="text-gray-700 dark:text-gray-200 font-medium">Completed</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Task finished successfully</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-blue-500 rounded-full animate-pulse flex-shrink-0"></div>
<div>
<span className="text-gray-700 dark:text-gray-200 font-medium">New Activity</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Session has new unviewed results</p>
</div>
</div>
<div className="flex items-center gap-3">
<div className="w-3 h-3 bg-red-500 rounded-full flex-shrink-0"></div>
<div>
<span className="text-gray-700 dark:text-gray-200 font-medium">Error</span>
<p className="text-gray-500 dark:text-gray-400 text-sm">Something went wrong with the session</p>
</div>
</div>
</div>
</div>
</div>
</ModalBody>
</Modal>
</div>
</div>
)}
</>
);
}

View File

@ -1,10 +1,7 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useRef, useState } from 'react';
import { Session } from '../types/session';
import { AlertCircle, CheckCircle, Loader2, PauseCircle, Bell } from 'lucide-react';
import { isDocumentVisible } from '../utils/performanceUtils';
import { Badge } from './ui/Badge';
import { StatusDot } from './ui/StatusDot';
import { cn } from '../utils/cn';
interface StatusIndicatorProps {
session: Session;
@ -20,9 +17,7 @@ export const StatusIndicator = React.memo(({
showProgress = false
}: StatusIndicatorProps) => {
const [animationsEnabled, setAnimationsEnabled] = useState(isDocumentVisible());
// Use the session status from the prop - parent component manages the session state
const currentStatus = session.status;
const elementRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleVisibilityChange = () => {
@ -32,159 +27,205 @@ export const StatusIndicator = React.memo(({
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
}, []);
const getStatusConfig = (status: Session['status'], statusMessage?: string) => {
const getStatusConfig = (status: Session['status']) => {
switch (status) {
case 'initializing':
return {
variant: 'success' as const,
badgeVariant: 'success' as const,
dotStatus: 'running' as const,
status: 'initializing',
color: 'bg-green-500',
textColor: 'text-green-400',
bgColor: 'bg-green-900/20',
borderColor: 'border-green-800',
icon: Loader2,
text: statusMessage || 'Initializing',
tooltip: statusMessage || 'Setting up git worktree and environment',
text: 'Initializing',
tooltip: 'Setting up git worktree and environment',
animated: true,
spin: true,
animated: true
};
case 'running':
return {
variant: 'success' as const,
badgeVariant: 'success' as const,
dotStatus: 'running' as const,
status: 'running',
color: 'bg-green-500',
textColor: 'text-green-400',
bgColor: 'bg-green-900/20',
borderColor: 'border-green-800',
icon: Loader2,
text: 'Running',
tooltip: 'Claude is actively processing your request',
animated: true,
spin: true,
animated: true
};
case 'waiting':
return {
variant: 'warning' as const,
badgeVariant: 'warning' as const,
dotStatus: 'waiting' as const,
status: 'waiting',
color: 'bg-amber-500',
textColor: 'text-amber-400',
bgColor: 'bg-amber-900/20',
borderColor: 'border-amber-800',
icon: PauseCircle,
text: 'Waiting for input',
tooltip: 'Claude needs your input to continue',
animated: true,
pulse: true,
animated: true
};
case 'stopped':
return {
variant: 'default' as const,
badgeVariant: 'default' as const,
dotStatus: 'default' as const,
status: 'stopped',
color: 'bg-gray-400',
textColor: 'text-gray-400',
bgColor: 'bg-gray-800',
borderColor: 'border-gray-700',
icon: CheckCircle,
text: 'Completed',
tooltip: 'Task finished successfully',
animated: false
animated: false,
};
case 'completed_unviewed':
return {
variant: 'info' as const,
badgeVariant: 'info' as const,
dotStatus: 'info' as const,
status: 'completed_unviewed',
color: 'bg-blue-500',
textColor: 'text-blue-400',
bgColor: 'bg-blue-900/20',
borderColor: 'border-blue-800',
icon: Bell,
text: 'New activity',
tooltip: 'Session has new unviewed results',
animated: true,
pulse: true,
animated: true
};
case 'error':
return {
variant: 'error' as const,
badgeVariant: 'error' as const,
dotStatus: 'error' as const,
status: 'error',
color: 'bg-red-500',
textColor: 'text-red-400',
bgColor: 'bg-red-900/20',
borderColor: 'border-red-800',
icon: AlertCircle,
text: 'Error',
tooltip: 'Something went wrong with the session',
animated: false
animated: false,
};
default:
return {
variant: 'default' as const,
badgeVariant: 'default' as const,
dotStatus: 'default' as const,
status: 'unknown',
color: 'bg-gray-400',
textColor: 'text-gray-400',
bgColor: 'bg-gray-800',
borderColor: 'border-gray-700',
icon: AlertCircle,
text: 'Unknown',
tooltip: 'Unknown status',
animated: false
animated: false,
};
}
};
const getBadgeSize = (size: string) => {
const getSizeClasses = (size: string) => {
switch (size) {
case 'small':
return 'sm' as const;
return {
dot: 'w-2 h-2',
container: 'w-3 h-3',
text: 'text-xs',
spacing: 'space-x-1',
};
case 'large':
return 'lg' as const;
default:
return 'md' as const;
return {
dot: 'w-4 h-4',
container: 'w-5 h-5',
text: 'text-sm',
spacing: 'space-x-3',
};
default: // medium
return {
dot: 'w-3 h-3',
container: 'w-4 h-4',
text: 'text-sm',
spacing: 'space-x-2',
};
}
};
const getDotSize = (size: string) => {
switch (size) {
case 'small':
return 'sm' as const;
case 'large':
return 'lg' as const;
default:
return 'md' as const;
}
};
const config = getStatusConfig(currentStatus, session.statusMessage);
const badgeSize = getBadgeSize(size);
const dotSize = getDotSize(size);
const config = getStatusConfig(session.status);
const sizeClasses = getSizeClasses(size);
// Disable animations when not visible or for non-active states
const shouldAnimate = animationsEnabled && config.animated;
const shouldAnimate = animationsEnabled && config.animated &&
['running', 'initializing', 'waiting', 'completed_unviewed'].includes(session.status);
const estimateProgress = (): number => {
if (currentStatus === 'stopped') return 100;
if (currentStatus === 'error') return 0;
if (currentStatus === 'waiting') return 75;
if (currentStatus === 'running') return 50;
if (currentStatus === 'initializing') return 25;
if (session.status === 'stopped') return 100;
if (session.status === 'error') return 0;
if (session.status === 'waiting') return 75;
if (session.status === 'running') return 50;
if (session.status === 'initializing') return 25;
return 0;
};
// When showText is true, render as a badge
// When showText is true, render as a chip
if (showText) {
return (
<div className="flex items-center gap-2">
<Badge
variant={config.badgeVariant}
size={badgeSize}
animated={shouldAnimate}
pulse={config.pulse}
icon={React.createElement(config.icon, {
className: cn(
'w-4 h-4',
config.spin && shouldAnimate && 'animate-spin'
)
})}
className={config.tooltip ? `cursor-help` : undefined}
<div className={`flex items-center ${sizeClasses.spacing}`}>
{/* Status Chip */}
<div
className={`
inline-flex items-center gap-2
px-3 py-1.5
rounded-full
${config.bgColor}
border
${config.borderColor}
${shouldAnimate ? 'relative overflow-hidden' : ''}
transition-all duration-200
`}
title={config.tooltip}
>
{config.text}
</Badge>
{/* Animated background effect for active states */}
{shouldAnimate && (
<div className="absolute inset-0 -z-10">
<div
className={`
absolute inset-0
${config.color}
opacity-20
${animationsEnabled ? 'animate-pulse' : ''}
`}
/>
{(config.status === 'running' || config.status === 'initializing') && (
<div
className="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full animate-[shimmer_2s_infinite]"
style={{
animation: 'shimmer 2s infinite',
}}
/>
)}
</div>
)}
{/* Status icon and text */}
{React.createElement(config.icon, {
className: `w-4 h-4 ${config.textColor} ${config.spin && animationsEnabled ? 'animate-spin' : ''}`
})}
<span className={`${sizeClasses.text} font-medium ${config.textColor}`}>
{config.text}
</span>
{/* Pulsing dot for waiting/new activity status */}
{config.pulse && shouldAnimate && (
<div className="relative flex h-2 w-2">
<span className={`${animationsEnabled ? 'animate-ping' : ''} absolute inline-flex h-full w-full rounded-full ${config.color} opacity-75`}></span>
<span className={`relative inline-flex rounded-full h-2 w-2 ${config.color}`}></span>
</div>
)}
</div>
{/* Progress Bar */}
{showProgress && (
<div className="flex-1 ml-2">
<div className="w-full bg-surface-tertiary rounded-full h-1.5">
<div className="w-full bg-gray-700 rounded-full h-1.5">
<div
className={cn(
'h-1.5 rounded-full transition-all duration-1000 ease-out',
config.dotStatus === 'running' && 'bg-status-success',
config.dotStatus === 'waiting' && 'bg-status-warning',
config.dotStatus === 'error' && 'bg-status-error',
config.dotStatus === 'info' && 'bg-status-info',
config.dotStatus === 'default' && 'bg-text-tertiary'
)}
className={`${config.color} h-1.5 rounded-full transition-all duration-1000 ease-out`}
style={{ width: `${estimateProgress()}%` }}
/>
</div>
@ -194,16 +235,33 @@ export const StatusIndicator = React.memo(({
);
}
// Simple dot indicator for when showText is false
// Original dot indicator for when showText is false
return (
<StatusDot
status={config.dotStatus}
size={dotSize}
animated={shouldAnimate && !config.pulse}
pulse={config.pulse && shouldAnimate}
className={config.tooltip ? 'cursor-help' : undefined}
title={config.tooltip}
/>
<div className={`flex items-center ${sizeClasses.spacing}`} title={config.tooltip}>
{/* Status Indicator Dot */}
<div className={`relative ${sizeClasses.container} flex items-center justify-center`} ref={elementRef}>
<div
className={`
${sizeClasses.dot}
${config.color}
rounded-full
${shouldAnimate && config.animated && animationsEnabled ? 'animate-pulse' : ''}
${shouldAnimate && config.pulse && animationsEnabled ? 'animate-ping' : ''}
`}
/>
{config.pulse && shouldAnimate && (
<div
className={`
absolute inset-0
${sizeClasses.dot}
${config.color}
rounded-full
opacity-75
`}
/>
)}
</div>
</div>
);
});

View File

@ -131,15 +131,15 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
const getStatusIndicator = () => {
switch (connectionState.status) {
case 'connected':
return <div className="w-3 h-3 bg-status-success rounded-full animate-pulse" />;
return <div className="w-3 h-3 bg-green-500 rounded-full animate-pulse" />;
case 'connecting':
return <div className="w-3 h-3 bg-status-warning rounded-full animate-pulse" />;
return <div className="w-3 h-3 bg-yellow-500 rounded-full animate-pulse" />;
case 'expired':
return <div className="w-3 h-3 bg-status-warning rounded-full" />;
return <div className="w-3 h-3 bg-orange-500 rounded-full" />;
case 'error':
return <div className="w-3 h-3 bg-status-error rounded-full" />;
return <div className="w-3 h-3 bg-red-500 rounded-full" />;
default:
return <div className="w-3 h-3 bg-text-tertiary rounded-full" />;
return <div className="w-3 h-3 bg-gray-400 dark:bg-gray-500 rounded-full" />;
}
};
@ -164,10 +164,10 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
<div className="flex items-center space-x-3">
{getStatusIndicator()}
<div>
<div className="text-sm font-medium text-text-primary">
<div className="text-sm font-medium text-gray-900 dark:text-gray-100">
Stravu Integration
</div>
<div className="text-xs text-text-tertiary">
<div className="text-xs text-gray-600 dark:text-gray-400">
{getStatusText()}
</div>
</div>
@ -178,7 +178,7 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
<button
onClick={handleConnect}
disabled={false}
className="px-3 py-1.5 text-sm font-medium text-interactive bg-interactive/10 border border-interactive/30 rounded-md hover:bg-interactive/20 focus:outline-none focus:ring-2 focus:ring-interactive disabled:opacity-50 disabled:cursor-not-allowed"
className="px-3 py-1.5 text-sm font-medium text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20 border border-blue-300 dark:border-blue-800 rounded-md hover:bg-blue-200 dark:hover:bg-blue-900/30 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
>
{connectionState.status === 'expired' ? 'Reconnect' : 'Connect'}
</button>
@ -186,7 +186,7 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
<>
<button
onClick={checkConnectionStatus}
className="p-1.5 text-text-tertiary hover:text-text-primary rounded-md hover:bg-surface-hover"
className="p-1.5 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-300 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700"
title="Refresh connection status"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@ -195,7 +195,7 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
</button>
<button
onClick={handleDisconnect}
className="px-3 py-1.5 text-sm font-medium text-status-error bg-status-error/10 border border-status-error/30 rounded-md hover:bg-status-error/20 focus:outline-none focus:ring-2 focus:ring-status-error"
className="px-3 py-1.5 text-sm font-medium text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded-md hover:bg-red-200 dark:hover:bg-red-900/30 focus:outline-none focus:ring-2 focus:ring-red-500"
>
Disconnect
</button>
@ -205,13 +205,13 @@ export function StravuConnection({ className = '' }: StravuConnectionProps) {
</div>
{connectionState.error && (
<div className="mt-2 text-xs text-status-error bg-status-error/10 border border-status-error/30 rounded-md p-2">
<div className="mt-2 text-xs text-red-600 dark:text-red-400 bg-red-100 dark:bg-red-900/20 border border-red-300 dark:border-red-800 rounded-md p-2">
{connectionState.error}
</div>
)}
{connectionState.status === 'connecting' && (
<div className="mt-2 text-xs text-interactive bg-interactive/10 border border-interactive/30 rounded-md p-2">
<div className="mt-2 text-xs text-blue-600 dark:text-blue-400 bg-blue-100 dark:bg-blue-900/20 border border-blue-300 dark:border-blue-800 rounded-md p-2">
Please complete authentication in your browser. This may take a few moments...
</div>
)}

View File

@ -178,14 +178,14 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
if (!isOpen) return null;
return (
<div className="fixed inset-0 bg-modal-overlay flex items-center justify-center z-50">
<div className="bg-surface-secondary rounded-lg w-full max-w-4xl mx-4 max-h-[80vh] overflow-hidden flex flex-col">
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-gray-800 rounded-lg w-full max-w-4xl mx-4 max-h-[80vh] overflow-hidden flex flex-col">
{/* Header */}
<div className="flex items-center justify-between p-6 border-b border-border-primary">
<div className="flex items-center justify-between p-6 border-b border-gray-700">
<h2 className="text-lg font-semibold text-white">Search Stravu Notebooks</h2>
<button
onClick={onClose}
className="text-text-tertiary hover:text-text-secondary transition-colors"
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"
>
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
@ -200,24 +200,24 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
{isConnecting ? (
<div className="space-y-4">
<div className="flex justify-center">
<svg className="w-8 h-8 animate-spin text-interactive" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg className="w-8 h-8 animate-spin text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</div>
<p className="text-text-secondary">Connecting to Stravu...</p>
<p className="text-gray-600 dark:text-gray-400">Connecting to Stravu...</p>
</div>
) : (
<div className="space-y-4">
<div className="flex justify-center">
<svg className="w-12 h-12 text-text-tertiary" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
</svg>
</div>
<p className="text-text-secondary">Not connected to Stravu</p>
<p className="text-sm text-text-tertiary">Please authenticate with Stravu to access your notebooks.</p>
<p className="text-gray-600 dark:text-gray-400">Not connected to Stravu</p>
<p className="text-sm text-gray-500 dark:text-gray-400">Please authenticate with Stravu to access your notebooks.</p>
<button
onClick={connectToStravu}
className="px-4 py-2 bg-interactive text-white rounded-md hover:bg-interactive-hover transition-colors"
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
>
Connect to Stravu
</button>
@ -234,12 +234,12 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Search for notebooks (AI-powered semantic search)..."
className="flex-1 px-3 py-2 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-primary placeholder-text-tertiary"
className="flex-1 px-3 py-2 border border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-gray-100 bg-gray-700 placeholder-gray-400"
/>
<button
onClick={handleSearch}
disabled={isSearching || !searchQuery.trim()}
className="px-4 py-2 bg-interactive text-white rounded-md hover:bg-interactive-hover disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed flex items-center space-x-2"
>
{isSearching ? (
<>
@ -261,15 +261,15 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
{/* Error Display */}
{error && (
<div className="bg-status-error/10 border border-status-error/30 rounded-md p-3">
<p className="text-status-error text-sm">{error}</p>
<div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md p-3">
<p className="text-red-800 dark:text-red-200 text-sm">{error}</p>
</div>
)}
{/* Search Results */}
{searchResults.length > 0 && (
<div className="space-y-2">
<h3 className="text-sm font-medium text-text-secondary">
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">
Search Results ({searchResults.length})
</h3>
<div className="grid gap-2">
@ -277,44 +277,44 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
<div
key={notebook.id}
onClick={() => handleNotebookClick(notebook)}
className={`p-3 border border-border-primary rounded-md hover:bg-surface-hover cursor-pointer transition-colors ${
selectedNotebook?.id === notebook.id && isLoadingContent ? 'bg-interactive/20 border-interactive' : ''
className={`p-3 border border-gray-700 rounded-md hover:bg-gray-700 cursor-pointer transition-colors ${
selectedNotebook?.id === notebook.id && isLoadingContent ? 'bg-blue-900/20 border-blue-700' : ''
}`}
>
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<div className="flex items-center space-x-2">
<svg className="w-4 h-4 text-text-tertiary flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg className="w-4 h-4 text-gray-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
</svg>
<h4 className="text-sm font-medium text-text-primary truncate">{notebook.title}</h4>
<h4 className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate">{notebook.title}</h4>
{selectedNotebook?.id === notebook.id && isLoadingContent && (
<svg className="w-4 h-4 animate-spin text-interactive" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg className="w-4 h-4 animate-spin text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
)}
{notebook.similarity && (
<span className="text-xs bg-interactive/30 text-interactive px-2 py-1 rounded">
<span className="text-xs bg-blue-900/30 text-blue-200 px-2 py-1 rounded">
{Math.round(notebook.similarity * 100)}% match
</span>
)}
</div>
{notebook.excerpt && (
<p className="text-xs text-text-secondary mt-1">{notebook.excerpt}</p>
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1">{notebook.excerpt}</p>
)}
<div className="flex items-center space-x-4 mt-2 text-xs text-text-tertiary">
<div className="flex items-center space-x-4 mt-2 text-xs text-gray-500">
<span>{formatWordCount(notebook.wordCount)}</span>
<span>{formatDate(notebook.lastModified)}</span>
{notebook.tags.length > 0 && (
<div className="flex items-center space-x-1">
<span>Tags:</span>
{notebook.tags.slice(0, 3).map((tag) => (
<span key={tag} className="bg-surface-tertiary text-text-secondary px-1 rounded text-xs">
<span key={tag} className="bg-gray-700 text-gray-400 px-1 rounded text-xs">
{tag}
</span>
))}
{notebook.tags.length > 3 && (
<span className="text-text-tertiary">+{notebook.tags.length - 3}</span>
<span className="text-gray-400">+{notebook.tags.length - 3}</span>
)}
</div>
)}
@ -329,22 +329,22 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
{searchQuery && !isSearching && searchResults.length === 0 && !error && (
<div className="text-center py-8">
<svg className="w-12 h-12 text-text-tertiary mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg className="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.746 0 3.332.477 4.5 1.253v13C19.832 18.477 18.246 18 16.5 18c-1.746 0-3.332.477-4.5 1.253" />
</svg>
<p className="text-text-secondary">No notebooks found for "{searchQuery}"</p>
<p className="text-sm text-text-tertiary mt-1">Try a different search term or concept</p>
<p className="text-gray-600 dark:text-gray-400">No notebooks found for "{searchQuery}"</p>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Try a different search term or concept</p>
</div>
)}
{!searchQuery && (
<div className="text-center py-8">
<svg className="w-12 h-12 text-text-tertiary mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<svg className="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
<p className="text-text-secondary">Search for Stravu notebooks</p>
<p className="text-sm text-text-tertiary mt-1">Use AI-powered semantic search to find notebooks by concept</p>
<p className="text-xs text-text-tertiary mt-2">💡 Try searching for "machine learning examples" or "API documentation"</p>
<p className="text-gray-600 dark:text-gray-400">Search for Stravu notebooks</p>
<p className="text-sm text-gray-500 dark:text-gray-400 mt-1">Use AI-powered semantic search to find notebooks by concept</p>
<p className="text-xs text-gray-400 mt-2">💡 Try searching for "machine learning examples" or "API documentation"</p>
</div>
)}
</div>
@ -352,10 +352,10 @@ export function StravuFileSearch({ isOpen, onClose, onFileSelect }: StravuFileSe
</div>
{/* Footer */}
<div className="flex justify-end space-x-3 p-6 border-t border-border-primary">
<div className="flex justify-end space-x-3 p-6 border-t border-gray-700">
<button
onClick={onClose}
className="px-4 py-2 text-text-secondary hover:text-text-primary transition-colors"
className="px-4 py-2 text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-gray-100 transition-colors"
>
Cancel
</button>

View File

@ -123,15 +123,15 @@ export function StravuStatusIndicator() {
const getStatusColor = () => {
switch (connectionState.status) {
case 'connected':
return 'text-status-success';
return 'text-green-600 dark:text-green-400';
case 'connecting':
return 'text-interactive';
return 'text-blue-600 dark:text-blue-400';
case 'expired':
return 'text-status-warning';
return 'text-yellow-600 dark:text-yellow-400';
case 'error':
return 'text-status-error';
return 'text-red-600 dark:text-red-400';
default:
return 'text-text-tertiary';
return 'text-gray-400 dark:text-gray-500';
}
};
@ -182,7 +182,7 @@ export function StravuStatusIndicator() {
onClick={handleConnect}
onMouseEnter={() => setShowTooltip(true)}
onMouseLeave={() => setShowTooltip(false)}
className={`p-2 rounded-lg hover:bg-surface-hover transition-colors ${getStatusColor()}`}
className={`p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors ${getStatusColor()}`}
disabled={connectionState.status === 'connecting'}
>
{renderIcon()}
@ -190,30 +190,30 @@ export function StravuStatusIndicator() {
{/* Tooltip */}
{showTooltip && (
<div className="absolute right-0 top-full mt-2 w-64 bg-surface-tertiary text-text-primary text-sm rounded-lg p-3 z-50">
<div className="absolute right-0 top-full mt-2 w-64 bg-gray-900 text-white text-sm rounded-lg p-3 z-50">
<div className="font-medium mb-1">Stravu Integration</div>
<div className="text-text-secondary">{getStatusText()}</div>
<div className="text-gray-300">{getStatusText()}</div>
{connectionState.status === 'connected' && connectionState.memberInfo && (
<div className="mt-2 pt-2 border-t border-border-secondary">
<div className="text-xs text-text-tertiary">
<div className="mt-2 pt-2 border-t border-gray-700">
<div className="text-xs text-gray-400">
Member: {connectionState.memberInfo.memberId}
</div>
<div className="text-xs text-text-tertiary">
<div className="text-xs text-gray-400">
Scopes: {connectionState.memberInfo.scopes.join(', ')}
</div>
</div>
)}
{(connectionState.status === 'disconnected' || connectionState.status === 'error') && (
<div className="mt-2 text-xs text-text-tertiary">
<div className="mt-2 text-xs text-gray-400">
Click to connect to Stravu
</div>
)}
{/* Arrow pointing up */}
<div className="absolute top-0 right-4 transform -translate-y-1">
<div className="w-0 h-0 border-l-4 border-r-4 border-b-4 border-transparent border-b-surface-tertiary"></div>
<div className="w-0 h-0 border-l-4 border-r-4 border-b-4 border-transparent border-b-gray-900"></div>
</div>
</div>
)}

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,5 @@
import { useState, useEffect } from 'react';
import { Download, AlertCircle, CheckCircle, Loader2 } from 'lucide-react';
import { Modal, ModalHeader, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { X, Download, AlertCircle, CheckCircle, Loader2 } from 'lucide-react';
interface UpdateDialogProps {
isOpen: boolean;
@ -105,8 +101,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
try {
setError(null);
await window.electronAPI.updater.checkAndDownload();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Failed to check for updates');
} catch (err: any) {
setError(err.message || 'Failed to check for updates');
setUpdateState('error');
}
};
@ -119,8 +115,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
try {
setError(null);
await window.electronAPI.updater.downloadUpdate();
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Failed to download update');
} catch (err: any) {
setError(err.message || 'Failed to download update');
setUpdateState('error');
}
};
@ -133,8 +129,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
try {
await window.electronAPI.updater.installUpdate();
// App will restart, so no need to handle response
} catch (err: unknown) {
setError(err instanceof Error ? err.message : 'Failed to install update');
} catch (err: any) {
setError(err.message || 'Failed to install update');
setUpdateState('error');
}
};
@ -154,23 +150,31 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
if (!isOpen) return null;
return (
<Modal isOpen={isOpen} onClose={onClose} size="lg" showCloseButton={false}>
<ModalHeader onClose={updateState === 'downloading' ? undefined : onClose}>
<div className="flex items-center gap-3">
<Download className="w-6 h-6 text-interactive" />
<h2 className="text-xl font-semibold text-text-primary">Software Update</h2>
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
<div className="bg-gray-800 rounded-lg w-full max-w-2xl max-h-[90vh] flex flex-col">
<div className="flex items-center justify-between p-6 border-b border-gray-700">
<div className="flex items-center gap-3">
<Download className="w-6 h-6 text-blue-400" />
<h2 className="text-xl font-semibold text-gray-100">Software Update</h2>
</div>
<button
onClick={onClose}
className="text-gray-400 hover:text-gray-200 transition-colors"
disabled={updateState === 'downloading'}
>
<X className="w-5 h-5" />
</button>
</div>
</ModalHeader>
<ModalBody className="space-y-6">
<div className="flex-1 overflow-y-auto p-6">
{versionInfo && (
<div>
<div className="text-text-secondary mb-2">
Current version: <span className="font-mono text-text-primary">{versionInfo.current}</span>
<div className="mb-6">
<div className="text-gray-300 mb-2">
Current version: <span className="font-mono text-gray-100">{versionInfo.current}</span>
</div>
{versionInfo.hasUpdate && (
<div className="text-text-secondary">
Latest version: <span className="font-mono text-status-success">{versionInfo.latest}</span>
<div className="text-gray-300">
Latest version: <span className="font-mono text-green-400">{versionInfo.latest}</span>
</div>
)}
</div>
@ -179,76 +183,76 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
{/* Update State UI */}
<div className="space-y-4">
{updateState === 'idle' && versionInfo?.hasUpdate && (
<div className="bg-surface-secondary rounded-lg p-4">
<h3 className="text-lg font-medium text-text-primary mb-2">Update Available</h3>
<p className="text-text-secondary mb-4">
<div className="bg-gray-700 rounded-lg p-4">
<h3 className="text-lg font-medium text-gray-100 mb-2">Update Available</h3>
<p className="text-gray-300 mb-4">
A new version of Crystal is available.
{isPackaged ? ' Click below to download and install the update.' : ' Auto-update is only available in the packaged app.'}
</p>
{isPackaged ? (
<Button
<button
onClick={handleCheckForUpdates}
variant="primary"
icon={<Download className="w-4 h-4" />}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
>
Download Update
</Button>
</button>
) : (
<Button
onClick={() => versionInfo.releaseUrl && window.electronAPI.openExternal(versionInfo.releaseUrl)}
variant="primary"
>
View Release
</Button>
<div className="flex gap-3">
<button
onClick={() => versionInfo.releaseUrl && window.electronAPI.openExternal(versionInfo.releaseUrl)}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
>
View Release
</button>
</div>
)}
</div>
)}
{updateState === 'checking' && (
<div className="flex items-center gap-3 text-text-secondary">
<div className="flex items-center gap-3 text-gray-300">
<Loader2 className="w-5 h-5 animate-spin" />
<span>Checking for updates...</span>
</div>
)}
{updateState === 'available' && (
<div className="bg-surface-secondary rounded-lg p-4">
<h3 className="text-lg font-medium text-text-primary mb-2">Ready to Download</h3>
<p className="text-text-secondary mb-4">
<div className="bg-gray-700 rounded-lg p-4">
<h3 className="text-lg font-medium text-gray-100 mb-2">Ready to Download</h3>
<p className="text-gray-300 mb-4">
The update is ready to download. This may take a few minutes depending on your connection.
</p>
<Button
<button
onClick={handleDownloadUpdate}
variant="primary"
icon={<Download className="w-4 h-4" />}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
>
Start Download
</Button>
</button>
</div>
)}
{updateState === 'downloading' && downloadProgress && (
<div className="space-y-3">
<div className="flex items-center gap-3 text-text-secondary">
<div className="flex items-center gap-3 text-gray-300">
<Loader2 className="w-5 h-5 animate-spin" />
<span>Downloading update...</span>
</div>
<div className="bg-surface-secondary rounded-lg p-4 space-y-3">
<div className="flex justify-between text-sm text-text-tertiary">
<div className="bg-gray-700 rounded-lg p-4 space-y-3">
<div className="flex justify-between text-sm text-gray-400">
<span>{formatBytes(downloadProgress.transferred)} / {formatBytes(downloadProgress.total)}</span>
<span>{formatSpeed(downloadProgress.bytesPerSecond)}</span>
</div>
<div className="w-full bg-surface-tertiary rounded-full h-2">
<div className="w-full bg-gray-600 rounded-full h-2">
<div
className="bg-interactive h-2 rounded-full transition-all duration-300"
className="bg-blue-500 h-2 rounded-full transition-all duration-300"
style={{ width: `${downloadProgress.percent}%` }}
/>
</div>
<div className="text-center text-sm text-text-tertiary">
<div className="text-center text-sm text-gray-400">
{Math.round(downloadProgress.percent)}%
</div>
</div>
@ -256,21 +260,20 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
)}
{updateState === 'downloaded' && (
<div className="bg-status-success/10 border border-status-success/30 rounded-lg p-4">
<div className="bg-green-900/30 border border-green-700 rounded-lg p-4">
<div className="flex items-start gap-3">
<CheckCircle className="w-5 h-5 text-status-success mt-0.5" />
<CheckCircle className="w-5 h-5 text-green-400 mt-0.5" />
<div className="flex-1">
<h3 className="text-lg font-medium text-status-success mb-2">Update Downloaded</h3>
<p className="text-text-secondary mb-4">
<h3 className="text-lg font-medium text-green-400 mb-2">Update Downloaded</h3>
<p className="text-gray-300 mb-4">
The update has been downloaded successfully. Crystal will restart to apply the update.
</p>
<Button
<button
onClick={handleInstallUpdate}
variant="primary"
className="bg-status-success hover:bg-status-success/90"
className="px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
>
Restart and Install
</Button>
</button>
</div>
</div>
</div>
@ -280,37 +283,37 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
<div className="space-y-4">
{/* Manual Download Box */}
{versionInfo?.releaseUrl && (
<div className="bg-interactive/10 border border-interactive/30 rounded-lg p-4">
<div className="bg-blue-900/30 border border-blue-700 rounded-lg p-4">
<div className="flex items-center justify-between">
<div>
<h3 className="text-lg font-medium text-interactive mb-1">Manual Update Available</h3>
<p className="text-sm text-text-secondary">
<h3 className="text-lg font-medium text-blue-400 mb-1">Manual Update Available</h3>
<p className="text-sm text-gray-300">
Automatic update failed, but you can download the latest version manually.
</p>
</div>
<Button
<button
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
variant="primary"
icon={<Download className="w-4 h-4" />}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors flex items-center gap-2"
>
<Download className="w-4 h-4" />
Download from GitHub
</Button>
</button>
</div>
</div>
)}
{/* Error Details */}
<div className="bg-status-error/10 border border-status-error/30 rounded-lg p-4">
<div className="bg-red-900/30 border border-red-700 rounded-lg p-4">
<div className="flex items-start gap-3">
<AlertCircle className="w-5 h-5 text-status-error mt-0.5" />
<AlertCircle className="w-5 h-5 text-red-400 mt-0.5" />
<div className="flex-1">
<h3 className="text-lg font-medium text-status-error mb-2">Update Error</h3>
<p className="text-text-secondary mb-2">{error}</p>
<h3 className="text-lg font-medium text-red-400 mb-2">Update Error</h3>
<p className="text-gray-300 mb-2">{error}</p>
<div className="space-y-3">
<p className="text-sm text-text-tertiary">
<p className="text-sm text-gray-400">
To update manually:
</p>
<ol className="text-sm text-text-secondary list-decimal list-inside ml-2 space-y-2">
<ol className="text-sm text-gray-300 list-decimal list-inside ml-2 space-y-2">
<li>Click "Download from GitHub" above</li>
<li>Download the .dmg file from the release page</li>
<li>Close Crystal</li>
@ -318,11 +321,11 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
<li>Drag Crystal to your Applications folder</li>
<li>Launch the new version of Crystal</li>
</ol>
<p className="text-sm text-text-tertiary mt-3">
<p className="text-sm text-gray-400 mt-3">
Your settings and sessions will be preserved during the update.
</p>
{(error.includes('404') || error.includes('latest-mac.yml')) && (
<div className="mt-3 p-2 bg-surface-primary rounded text-xs text-text-tertiary">
<div className="mt-3 p-2 bg-gray-800 rounded text-xs text-gray-500">
<p className="font-semibold mb-1">Technical Details:</p>
<p>The release may be missing required update metadata files, or you may be testing with a development version.</p>
</div>
@ -331,7 +334,7 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
{versionInfo?.releaseUrl && (
<button
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
className="mt-3 text-sm text-interactive hover:text-interactive-hover underline"
className="mt-3 text-sm text-blue-400 hover:text-blue-300 underline"
>
View Release on GitHub
</button>
@ -344,8 +347,8 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
{!versionInfo?.hasUpdate && updateState === 'idle' && (
<div className="text-center py-8">
<CheckCircle className="w-12 h-12 text-status-success mx-auto mb-3" />
<p className="text-text-secondary">You're running the latest version of Crystal!</p>
<CheckCircle className="w-12 h-12 text-green-400 mx-auto mb-3" />
<p className="text-gray-300">You're running the latest version of Crystal!</p>
</div>
)}
</div>
@ -353,67 +356,38 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
{/* Release Notes */}
{versionInfo?.releaseNotes && (
<div className="mt-6">
<h3 className="text-lg font-medium text-text-primary mb-3">Release Notes</h3>
<div className="bg-surface-secondary rounded-lg p-4 max-h-64 overflow-y-auto">
<div className="text-sm">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
h1: ({ children }) => <h1 className="text-2xl font-bold mt-4 mb-3 text-text-primary">{children}</h1>,
h2: ({ children }) => <h2 className="text-xl font-bold mt-3 mb-2 text-text-primary">{children}</h2>,
h3: ({ children }) => <h3 className="text-lg font-bold mt-2 mb-2 text-text-primary">{children}</h3>,
h4: ({ children }) => <h4 className="text-base font-bold mt-2 mb-1 text-text-primary">{children}</h4>,
p: ({ children }) => <p className="mb-3 text-text-primary">{children}</p>,
ul: ({ children }) => <ul className="list-disc mb-3 ml-6 text-text-primary">{children}</ul>,
ol: ({ children }) => <ol className="list-decimal mb-3 ml-6 text-text-primary">{children}</ol>,
li: ({ children }) => <li className="mb-1 text-text-primary">{children}</li>,
blockquote: ({ children }) => (
<blockquote className="border-l-4 border-border-secondary pl-4 italic my-3 text-text-tertiary">
{children}
</blockquote>
),
a: ({ href, children }) => (
<a href={href} className="text-interactive hover:text-interactive-hover underline" target="_blank" rel="noopener noreferrer">
{children}
</a>
),
code: ({ children }) => (
<code className="bg-surface-tertiary px-1 py-0.5 rounded text-text-primary font-mono text-xs">
{children}
</code>
),
hr: () => <hr className="my-4 border-border-primary" />,
}}
>
{versionInfo.releaseNotes}
</ReactMarkdown>
</div>
<h3 className="text-lg font-medium text-gray-100 mb-3">Release Notes</h3>
<div className="bg-gray-700 rounded-lg p-4 max-h-64 overflow-y-auto">
<pre className="text-sm text-gray-300 whitespace-pre-wrap font-sans">
{versionInfo.releaseNotes}
</pre>
</div>
</div>
)}
</ModalBody>
<ModalFooter>
<div className="flex justify-between items-center w-full">
<div className="text-sm text-text-tertiary">
{versionInfo?.releaseUrl && (
<button
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
className="hover:text-text-secondary underline transition-colors"
>
View on GitHub
</button>
)}
</div>
<Button
onClick={onClose}
variant="secondary"
disabled={updateState === 'downloading'}
>
Close
</Button>
</div>
</ModalFooter>
</Modal>
<div className="p-6 border-t border-gray-700">
<div className="flex justify-between items-center">
<div className="text-sm text-gray-400">
{versionInfo?.releaseUrl && (
<button
onClick={() => window.electronAPI.openExternal(versionInfo.releaseUrl!)}
className="hover:text-gray-200 underline transition-colors"
>
View on GitHub
</button>
)}
</div>
<button
onClick={onClose}
className="px-4 py-2 bg-gray-700 text-gray-300 rounded hover:bg-gray-600 transition-colors"
disabled={updateState === 'downloading'}
>
Close
</button>
</div>
</div>
</div>
</div>
);
}

View File

@ -1,8 +1,6 @@
import React from 'react';
import { Zap, CheckCircle, GitBranch } from 'lucide-react';
import crystalLogo from '../assets/crystal-logo.svg';
import { Modal, ModalBody, ModalFooter } from './ui/Modal';
import { Button } from './ui/Button';
interface WelcomeProps {
isOpen: boolean;
@ -42,36 +40,37 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
if (!isOpen) return null;
return (
<Modal isOpen={isOpen} onClose={onClose} size="lg">
{/* Header with gradient */}
<div className="bg-gradient-to-r from-interactive to-interactive-active p-6 text-on-interactive rounded-t-lg">
<div className="flex items-center justify-between">
<div className="flex items-center">
<img src={crystalLogo} alt="Crystal" className="h-10 w-10 mr-3" />
<div>
<h1 className="text-2xl font-bold">Welcome to Crystal</h1>
<p className="text-interactive-text/80">Multi-Session Claude Code Manager</p>
<div className="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
<div className="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden flex flex-col">
{/* Header with gradient */}
<div className="bg-gradient-to-r from-blue-600 to-purple-600 p-6 text-white">
<div className="flex items-center justify-between">
<div className="flex items-center">
<img src={crystalLogo} alt="Crystal" className="h-10 w-10 mr-3" />
<div>
<h1 className="text-2xl font-bold">Welcome to Crystal</h1>
<p className="text-blue-50">Multi-Session Claude Code Manager</p>
</div>
</div>
</div>
</div>
</div>
<ModalBody className="max-h-96 overflow-y-auto">
<div className="flex-1 overflow-y-auto p-6">
<div className="space-y-6">
{/* Quick Start Guide */}
<section>
<h2 className="text-xl font-semibold text-text-primary mb-4 flex items-center">
<Zap className="h-6 w-6 mr-2 text-status-warning" />
<h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4 flex items-center">
<Zap className="h-6 w-6 mr-2 text-yellow-500" />
Quick Start Guide
</h2>
{/* Prerequisites */}
<div className="bg-status-warning/10 border border-status-warning/30 rounded-lg p-4 mb-4">
<h3 className="font-semibold text-status-warning mb-2 flex items-center">
<div className="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 mb-4">
<h3 className="font-semibold text-amber-900 dark:text-amber-200 mb-2 flex items-center">
<CheckCircle className="h-5 w-5 mr-2" />
Before You Begin
</h3>
<ul className="space-y-2 text-status-warning/80">
<ul className="space-y-2 text-amber-800 dark:text-amber-300">
<li className="flex items-start">
<span className="mr-2">•</span>
<span>Claude Code must be installed with credentials configured</span>
@ -82,7 +81,7 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
</li>
<li className="flex items-start">
<span className="mr-2">•</span>
<span>Crystal runs Claude Code with <code className="bg-status-warning/20 px-1 rounded text-sm">--dangerously-ignore-permissions</code></span>
<span>Crystal runs Claude Code with <code className="bg-amber-200 dark:bg-amber-800 px-1 rounded text-sm">--dangerously-ignore-permissions</code></span>
</li>
</ul>
</div>
@ -90,12 +89,12 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
{/* Steps */}
<div className="space-y-4">
<div className="flex items-start">
<div className="flex-shrink-0 w-8 h-8 bg-interactive rounded-full flex items-center justify-center text-on-interactive font-semibold">
<div className="flex-shrink-0 w-8 h-8 bg-blue-600 dark:bg-blue-900 rounded-full flex items-center justify-center text-white dark:text-blue-300 font-semibold">
1
</div>
<div className="ml-4 flex-1">
<h4 className="font-semibold text-text-primary mb-1">Create or Select a Project</h4>
<ul className="text-text-secondary space-y-1 text-sm">
<h4 className="font-semibold text-gray-900 dark:text-white mb-1">Create or Select a Project</h4>
<ul className="text-gray-600 dark:text-gray-400 space-y-1 text-sm">
<li>• Point to a <strong>new directory</strong> - Crystal will create it and initialize git</li>
<li>• Or select an <strong>existing git repository</strong></li>
</ul>
@ -103,12 +102,12 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-8 h-8 bg-interactive rounded-full flex items-center justify-center text-on-interactive font-semibold">
<div className="flex-shrink-0 w-8 h-8 bg-blue-600 dark:bg-blue-900 rounded-full flex items-center justify-center text-white dark:text-blue-300 font-semibold">
2
</div>
<div className="ml-4 flex-1">
<h4 className="font-semibold text-text-primary mb-1">Create Sessions</h4>
<ul className="text-text-secondary space-y-1 text-sm">
<h4 className="font-semibold text-gray-900 dark:text-white mb-1">Create Sessions</h4>
<ul className="text-gray-600 dark:text-gray-400 space-y-1 text-sm">
<li>• Enter a prompt describing what you want Claude to do</li>
<li>• <strong>Create multiple sessions</strong> with different prompts to explore various approaches</li>
<li>• Or <strong>run the same prompt multiple times</strong> to choose the best result</li>
@ -117,13 +116,13 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
</div>
<div className="flex items-start">
<div className="flex-shrink-0 w-8 h-8 bg-interactive rounded-full flex items-center justify-center text-on-interactive font-semibold">
<div className="flex-shrink-0 w-8 h-8 bg-blue-600 dark:bg-blue-900 rounded-full flex items-center justify-center text-white dark:text-blue-300 font-semibold">
3
</div>
<div className="ml-4 flex-1">
<h4 className="font-semibold text-text-primary mb-1">Work with Results</h4>
<ul className="text-text-secondary space-y-1 text-sm">
<li>• View changes in the <strong>Diff panel</strong></li>
<h4 className="font-semibold text-gray-900 dark:text-white mb-1">Work with Results</h4>
<ul className="text-gray-600 dark:text-gray-400 space-y-1 text-sm">
<li>• View changes in the <strong>View Diff tab</strong></li>
<li>• <strong>Continue conversations</strong> to refine the solution</li>
<li>• <strong>Rebase back to main</strong> when you're done</li>
</ul>
@ -134,67 +133,71 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
{/* Key Features */}
<section className="border-t pt-6">
<h3 className="font-semibold text-text-primary mb-3 flex items-center">
<h3 className="font-semibold text-gray-900 dark:text-white mb-3 flex items-center">
<GitBranch className="h-5 w-5 mr-2" />
Key Features
</h3>
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="flex items-center text-text-secondary">
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
<div className="flex items-center text-gray-600 dark:text-gray-400">
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
<span>Parallel sessions with git worktrees</span>
</div>
<div className="flex items-center text-text-secondary">
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
<div className="flex items-center text-gray-600 dark:text-gray-400">
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
<span>Real-time status updates</span>
</div>
<div className="flex items-center text-text-secondary">
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
<div className="flex items-center text-gray-600 dark:text-gray-400">
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
<span>Session persistence</span>
</div>
<div className="flex items-center text-text-secondary">
<CheckCircle className="h-4 w-4 mr-2 text-status-success flex-shrink-0" />
<div className="flex items-center text-gray-600 dark:text-gray-400">
<CheckCircle className="h-4 w-4 mr-2 text-green-500 flex-shrink-0" />
<span>Git integration</span>
</div>
</div>
</section>
</div>
</ModalBody>
</div>
<ModalFooter className="flex justify-between items-center">
<Button
onClick={async () => {
const newValue = !dontShowAgain;
console.log('[Welcome Debug] Don\'t show again clicked:', newValue);
setDontShowAgain(newValue);
if (window.electron?.invoke) {
try {
const result = await window.electron.invoke('preferences:set', 'hide_welcome', newValue ? 'true' : 'false');
if (result?.success) {
console.log('[Welcome Debug] Successfully set hide_welcome preference to', newValue);
} else {
console.error('[Welcome Debug] Failed to set preference:', result?.error);
<div className="p-4 border-t border-gray-200 dark:border-gray-700 flex justify-between items-center">
<button
onClick={async () => {
const newValue = !dontShowAgain;
console.log('[Welcome Debug] Don\'t show again clicked:', newValue);
setDontShowAgain(newValue);
if (window.electron?.invoke) {
try {
const result = await window.electron.invoke('preferences:set', 'hide_welcome', newValue ? 'true' : 'false');
if (result?.success) {
console.log('[Welcome Debug] Successfully set hide_welcome preference to', newValue);
} else {
console.error('[Welcome Debug] Failed to set preference:', result?.error);
}
} catch (error) {
console.error('[Welcome Debug] Error setting preference:', error);
}
} catch (error) {
console.error('[Welcome Debug] Error setting preference:', error);
}
}
// Close the popup when don't show again is clicked and set to true
if (newValue) {
onClose();
}
}}
variant={dontShowAgain ? "secondary" : "ghost"}
size="sm"
>
{dontShowAgain ? "Will hide on next launch" : "Don't show this again"}
</Button>
<Button
onClick={onClose}
variant="primary"
>
Get Started
</Button>
</ModalFooter>
</Modal>
// Close the popup when don't show again is clicked and set to true
if (newValue) {
onClose();
}
}}
className={`px-4 py-2 text-sm font-medium rounded-lg transition-colors ${
dontShowAgain
? 'bg-gray-200 dark:bg-gray-700 text-gray-900 dark:text-gray-100 hover:bg-gray-300 dark:hover:bg-gray-600'
: 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-700'
}`}
>
{dontShowAgain ? "Will hide on next launch" : "Don't show this again"}
</button>
<button
onClick={onClose}
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
>
Get Started
</button>
</div>
</div>
</div>
);
}

View File

@ -4,7 +4,7 @@ import type { RemoteStatus, MainBranchStatus } from '../../types/projectDashboar
interface MultiOriginStatusProps {
mainBranch: string;
mainBranchStatus?: MainBranchStatus;
mainBranchStatus: MainBranchStatus;
remotes?: RemoteStatus[];
onReviewUpdates?: () => void;
}
@ -15,11 +15,6 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
remotes = [],
onReviewUpdates
}) => {
// Handle progressive loading - mainBranchStatus might not be available yet
if (!mainBranchStatus) {
return null;
}
// Find upstream and origin remotes
const upstream = remotes.find(r => r.isUpstream || r.name === 'upstream');
const origin = remotes.find(r => !r.isUpstream && r.name === 'origin');
@ -34,13 +29,13 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
const getStatusIcon = (status: string) => {
switch (status) {
case 'up-to-date':
return <CheckCircle className="w-4 h-4 text-status-success" />;
return <CheckCircle className="w-4 h-4 text-green-500" />;
case 'behind':
return <AlertCircle className="w-4 h-4 text-status-warning" />;
return <AlertCircle className="w-4 h-4 text-yellow-500" />;
case 'ahead':
return <Clock className="w-4 h-4 text-interactive" />;
return <Clock className="w-4 h-4 text-blue-500" />;
case 'diverged':
return <AlertCircle className="w-4 h-4 text-status-error" />;
return <AlertCircle className="w-4 h-4 text-red-500" />;
default:
return null;
}
@ -80,15 +75,15 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
if (!hasMultipleRemotes) {
// Single remote view (original view)
return (
<div className="mb-6 p-4 bg-surface-secondary rounded-lg">
<div className="mb-6 p-4 bg-gray-50 dark:bg-gray-800 rounded-lg">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<GitBranch className="w-5 h-5 text-text-tertiary" />
<GitBranch className="w-5 h-5 text-gray-600 dark:text-gray-400" />
<div>
<h3 className="font-medium text-text-primary">
<h3 className="font-medium text-gray-900 dark:text-gray-100">
Main Branch ({mainBranch})
</h3>
<p className="text-sm text-text-tertiary flex items-center gap-2 mt-1">
<p className="text-sm text-gray-600 dark:text-gray-400 flex items-center gap-2 mt-1">
{getStatusIcon(mainBranchStatus.status)}
{getLocalStatusText()}
</p>
@ -103,9 +98,9 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
return (
<div className="mb-6 space-y-3">
{/* Multi-Origin Status Flow */}
<div className="bg-surface-primary border border-border-primary rounded-lg overflow-hidden">
<div className="bg-surface-secondary px-4 py-2 border-b border-border-primary">
<h3 className="text-sm font-medium text-text-secondary">Git Remote Status</h3>
<div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg overflow-hidden">
<div className="bg-gray-50 dark:bg-gray-800 px-4 py-2 border-b border-gray-200 dark:border-gray-700">
<h3 className="text-sm font-medium text-gray-700 dark:text-gray-300">Git Remote Status</h3>
</div>
<div className="p-4">
@ -114,20 +109,20 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
{/* Upstream Status */}
{upstream && (
<>
<div className="flex-1 bg-interactive/10 rounded-lg p-3 border border-interactive/30">
<div className="flex-1 bg-purple-50 dark:bg-purple-900/20 rounded-lg p-3 border border-purple-200 dark:border-purple-800">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2 mb-1">
<GitBranch className="w-4 h-4 text-interactive" />
<span className="text-sm font-semibold text-text-primary">
<GitBranch className="w-4 h-4 text-purple-600 dark:text-purple-400" />
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
{upstream.name}/{upstream.branch}
</span>
</div>
<div className="text-xs text-text-tertiary">Source repository</div>
<div className="text-xs text-gray-600 dark:text-gray-400">Source repository</div>
</div>
<div className="flex items-center gap-2">
{upstream.status !== 'up-to-date' && (
<span className="text-xs font-medium text-interactive">
<span className="text-xs font-medium text-purple-700 dark:text-purple-300">
{getStatusText(upstream)}
</span>
)}
@ -136,33 +131,33 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
</div>
</div>
<ArrowRight className="w-5 h-5 text-text-tertiary flex-shrink-0" />
<ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
</>
)}
{/* Origin/Fork Status */}
{origin && (
<>
<div className="flex-1 bg-interactive/10 rounded-lg p-3 border border-interactive/30">
<div className="flex-1 bg-blue-50 dark:bg-blue-900/20 rounded-lg p-3 border border-blue-200 dark:border-blue-800">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2 mb-1">
<GitBranch className="w-4 h-4 text-interactive" />
<span className="text-sm font-semibold text-text-primary">
<GitBranch className="w-4 h-4 text-blue-600 dark:text-blue-400" />
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
{origin.name}/{origin.branch}
</span>
{origin.isFork && (
<span className="inline-flex items-center gap-1 text-xs bg-interactive/20 text-interactive px-1.5 py-0.5 rounded">
<span className="inline-flex items-center gap-1 text-xs bg-blue-100 dark:bg-blue-800 text-blue-700 dark:text-blue-300 px-1.5 py-0.5 rounded">
<GitFork className="w-3 h-3" />
<span>fork</span>
</span>
)}
</div>
<div className="text-xs text-text-tertiary">Your remote</div>
<div className="text-xs text-gray-600 dark:text-gray-400">Your remote</div>
</div>
<div className="flex items-center gap-2">
{origin.status !== 'up-to-date' && (
<span className="text-xs font-medium text-interactive">
<span className="text-xs font-medium text-blue-700 dark:text-blue-300">
{getStatusText(origin)}
</span>
)}
@ -171,28 +166,28 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
</div>
</div>
<ArrowRight className="w-5 h-5 text-text-tertiary flex-shrink-0" />
<ArrowRight className="w-5 h-5 text-gray-400 flex-shrink-0" />
</>
)}
{/* Local Main Status */}
<div className="flex-1 bg-surface-secondary rounded-lg p-3 border border-border-primary">
<div className="flex-1 bg-gray-50 dark:bg-gray-800 rounded-lg p-3 border border-gray-200 dark:border-gray-700">
<div className="flex items-center justify-between">
<div>
<div className="flex items-center gap-2 mb-1">
<GitBranch className="w-4 h-4 text-text-tertiary" />
<span className="text-sm font-semibold text-text-primary">
<GitBranch className="w-4 h-4 text-gray-600 dark:text-gray-400" />
<span className="text-sm font-semibold text-gray-900 dark:text-gray-100">
{mainBranch}
</span>
<span className="text-xs bg-surface-tertiary text-text-secondary px-1.5 py-0.5 rounded">
<span className="text-xs bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-1.5 py-0.5 rounded">
local
</span>
</div>
<div className="text-xs text-text-tertiary">Base for sessions</div>
<div className="text-xs text-gray-600 dark:text-gray-400">Base for sessions</div>
</div>
<div className="flex items-center gap-2">
{mainBranchStatus.status !== 'up-to-date' && (
<span className="text-xs font-medium text-text-secondary">
<span className="text-xs font-medium text-gray-700 dark:text-gray-300">
{getLocalStatusText()}
</span>
)}
@ -205,18 +200,18 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
{/* Action Bar - Shows when updates are needed */}
{hasUpdatesNeeded && (
<div className="bg-status-warning/10 border-t border-status-warning/30 px-4 py-3">
<div className="bg-amber-50 dark:bg-amber-900/20 border-t border-amber-200 dark:border-amber-800 px-4 py-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-status-warning" />
<span className="text-sm font-medium text-status-warning">
<AlertCircle className="w-4 h-4 text-amber-600 dark:text-amber-400" />
<span className="text-sm font-medium text-amber-800 dark:text-amber-200">
Updates available in the cascade
</span>
</div>
{onReviewUpdates && (
<button
onClick={onReviewUpdates}
className="text-sm bg-status-warning hover:bg-status-warning-hover text-white px-3 py-1.5 rounded font-medium transition-colors"
className="text-sm bg-amber-600 hover:bg-amber-700 text-white px-3 py-1.5 rounded font-medium transition-colors"
>
Review Updates →
</button>
@ -226,22 +221,22 @@ export const MultiOriginStatus: React.FC<MultiOriginStatusProps> = ({
)}
{/* Flow Legend */}
<div className="bg-surface-secondary px-4 py-2 border-t border-border-primary">
<div className="flex items-center gap-6 text-xs text-text-tertiary">
<div className="bg-gray-50 dark:bg-gray-800 px-4 py-2 border-t border-gray-200 dark:border-gray-700">
<div className="flex items-center gap-6 text-xs text-gray-600 dark:text-gray-400">
<div className="flex items-center gap-2">
<CheckCircle className="w-3 h-3 text-status-success" />
<CheckCircle className="w-3 h-3 text-green-500" />
<span>Synced</span>
</div>
<div className="flex items-center gap-2">
<AlertCircle className="w-3 h-3 text-status-warning" />
<AlertCircle className="w-3 h-3 text-yellow-500" />
<span>Behind</span>
</div>
<div className="flex items-center gap-2">
<Clock className="w-3 h-3 text-interactive" />
<Clock className="w-3 h-3 text-blue-500" />
<span>Ahead</span>
</div>
<div className="flex items-center gap-2">
<AlertCircle className="w-3 h-3 text-status-error" />
<AlertCircle className="w-3 h-3 text-red-500" />
<span>Diverged</span>
</div>
</div>

View File

@ -1,6 +1,5 @@
import React from 'react';
import type { SessionBranchInfo } from '../../types/projectDashboard';
import { Card } from '../ui/Card';
interface StatusSummaryCardsProps {
sessions: SessionBranchInfo[];
@ -13,40 +12,40 @@ export const StatusSummaryCards: React.FC<StatusSummaryCardsProps> = ({ sessions
return (
<div className="grid grid-cols-3 gap-3 mb-6">
<Card className="p-4">
<div className="bg-white dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
<div className="space-y-1">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">Up to date</span>
<div className="w-2 h-2 bg-status-success rounded-full"></div>
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Up to date</span>
<div className="w-2 h-2 bg-green-500 rounded-full"></div>
</div>
<div className="text-2xl font-bold text-text-primary">
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
{upToDateCount}
<span className="text-sm font-normal text-text-tertiary">/{sessions.length}</span>
<span className="text-sm font-normal text-gray-500 dark:text-gray-400">/{sessions.length}</span>
</div>
</div>
</Card>
<Card className="p-4">
</div>
<div className="bg-white dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
<div className="space-y-1">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">Stale</span>
<div className="w-2 h-2 bg-status-warning rounded-full"></div>
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Stale</span>
<div className="w-2 h-2 bg-yellow-500 rounded-full"></div>
</div>
<div className="text-2xl font-bold text-text-primary">
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
{staleCount}
</div>
</div>
</Card>
<Card className="p-4">
</div>
<div className="bg-white dark:bg-gray-900 p-4 rounded-lg border border-gray-200 dark:border-gray-700 shadow-sm">
<div className="space-y-1">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">Changes</span>
<div className="w-2 h-2 bg-status-warning rounded-full"></div>
<span className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">Changes</span>
<div className="w-2 h-2 bg-orange-500 rounded-full"></div>
</div>
<div className="text-2xl font-bold text-text-primary">
<div className="text-2xl font-bold text-gray-900 dark:text-gray-100">
{needsAttentionCount}
</div>
</div>
</Card>
</div>
</div>
);
};

View File

@ -1,220 +0,0 @@
import React, { useState } from 'react';
import { Cpu, Brain, Zap } from 'lucide-react';
import { TogglePill } from '../ui/Pill';
import { TogglePillImproved } from '../ui/TogglePillImproved';
import { Switch } from '../ui/Switch';
import { Card } from '../ui/Card';
export const ExtendedThinkingDemo: React.FC = () => {
const [currentPill, setCurrentPill] = useState(false);
const [improvedPill, setImprovedPill] = useState(false);
const [switchState, setSwitchState] = useState(false);
return (
<div className="p-8 space-y-8 bg-bg-primary">
<h1 className="text-2xl font-bold text-text-primary mb-8">
Extended Thinking Toggle - Dark Mode UX Study
</h1>
{/* Current Implementation */}
<Card variant="bordered" className="p-6">
<h2 className="text-lg font-semibold text-text-primary mb-4">
Current Implementation
</h2>
<div className="flex items-center gap-4 mb-4">
<TogglePill
checked={currentPill}
onCheckedChange={setCurrentPill}
icon={<Cpu className="w-2 h-2" />}
>
Extended Thinking
</TogglePill>
<span className="text-sm text-text-tertiary">
Current TogglePill component
</span>
</div>
<div className="text-sm text-text-secondary space-y-1">
<p>Issues in dark mode:</p>
<ul className="list-disc list-inside text-text-tertiary">
<li>Poor idle state affordance (looks like static text)</li>
<li>Weak hover state (barely visible)</li>
<li>Focus ring shows on mouse clicks</li>
<li>Small indicator (14px)</li>
</ul>
</div>
</Card>
{/* Improved Pill Implementation */}
<Card variant="bordered" className="p-6">
<h2 className="text-lg font-semibold text-text-primary mb-4">
Improved Pill Design
</h2>
<div className="flex items-center gap-4 mb-4">
<TogglePillImproved
checked={improvedPill}
onCheckedChange={setImprovedPill}
icon={<Cpu className="w-3 h-3" />}
>
Extended Thinking
</TogglePillImproved>
<span className="text-sm text-text-tertiary">
Improved TogglePill with better affordance
</span>
</div>
<div className="text-sm text-text-secondary space-y-1">
<p>Improvements:</p>
<ul className="list-disc list-inside text-text-tertiary">
<li>Clear interactive surface in idle state</li>
<li>Visible hover with elevation and color change</li>
<li>:focus-visible for keyboard-only focus</li>
<li>Larger indicator (16px) with rounded square shape</li>
<li>Smooth transitions on all states</li>
</ul>
</div>
</Card>
{/* Recommended Switch Implementation */}
<Card variant="bordered" className="p-6 bg-interactive-surface/10">
<h2 className="text-lg font-semibold text-text-primary mb-4 flex items-center gap-2">
<span className="text-interactive-on-dark">✨</span>
Recommended: Switch Component
</h2>
<div className="space-y-4">
<div className="flex items-center gap-4">
<Switch
checked={switchState}
onCheckedChange={setSwitchState}
label="Extended Thinking"
icon={<Cpu />}
size="md"
/>
<span className="text-sm text-text-tertiary">
Industry-standard switch pattern
</span>
</div>
<div className="text-sm text-text-secondary space-y-1">
<p>Benefits:</p>
<ul className="list-disc list-inside text-text-tertiary">
<li>Immediately recognizable as toggleable</li>
<li>Clear on/off state with position</li>
<li>Better accessibility (native switch semantics)</li>
<li>Larger click target with label</li>
<li>Smooth transitions and micro-interactions</li>
</ul>
</div>
{/* Size variations */}
<div className="mt-6 space-y-3 pt-4 border-t border-border-primary">
<h3 className="text-sm font-medium text-text-primary">Size Variations:</h3>
<div className="space-y-2">
<Switch
checked={switchState}
onCheckedChange={setSwitchState}
label="Small"
icon={<Zap />}
size="sm"
/>
<Switch
checked={switchState}
onCheckedChange={setSwitchState}
label="Medium (default)"
icon={<Cpu />}
size="md"
/>
<Switch
checked={switchState}
onCheckedChange={setSwitchState}
label="Large"
icon={<Brain />}
size="lg"
/>
</div>
</div>
</div>
</Card>
{/* Side-by-side comparison */}
<Card variant="bordered" className="p-6">
<h2 className="text-lg font-semibold text-text-primary mb-4">
Side-by-Side Comparison
</h2>
<div className="grid grid-cols-3 gap-6">
<div>
<h3 className="text-sm font-medium text-text-secondary mb-3">Current</h3>
<TogglePill
checked={currentPill}
onCheckedChange={setCurrentPill}
icon={<Cpu className="w-2 h-2" />}
>
Extended Thinking
</TogglePill>
</div>
<div>
<h3 className="text-sm font-medium text-text-secondary mb-3">Improved Pill</h3>
<TogglePillImproved
checked={improvedPill}
onCheckedChange={setImprovedPill}
icon={<Cpu className="w-3 h-3" />}
>
Extended Thinking
</TogglePillImproved>
</div>
<div>
<h3 className="text-sm font-medium text-text-secondary mb-3">Switch (Recommended)</h3>
<Switch
checked={switchState}
onCheckedChange={setSwitchState}
label="Extended Thinking"
icon={<Cpu />}
size="md"
/>
</div>
</div>
</Card>
{/* Interaction states preview */}
<Card variant="bordered" className="p-6">
<h2 className="text-lg font-semibold text-text-primary mb-4">
Interaction States (Improved Pill)
</h2>
<div className="grid grid-cols-2 gap-4">
<div>
<h3 className="text-sm font-medium text-text-secondary mb-3">Off States</h3>
<div className="space-y-2">
<div className="flex items-center gap-3">
<TogglePillImproved checked={false} onCheckedChange={() => {}}>
Idle
</TogglePillImproved>
<span className="text-xs text-text-tertiary">Default off state</span>
</div>
<div className="flex items-center gap-3">
<TogglePillImproved checked={false} onCheckedChange={() => {}} disabled>
Disabled
</TogglePillImproved>
<span className="text-xs text-text-tertiary">Disabled state</span>
</div>
</div>
</div>
<div>
<h3 className="text-sm font-medium text-text-secondary mb-3">On States</h3>
<div className="space-y-2">
<div className="flex items-center gap-3">
<TogglePillImproved checked={true} onCheckedChange={() => {}} icon={<Cpu className="w-3 h-3" />}>
Active
</TogglePillImproved>
<span className="text-xs text-text-tertiary">Active on state</span>
</div>
<div className="flex items-center gap-3">
<TogglePillImproved checked={true} onCheckedChange={() => {}} disabled icon={<Cpu className="w-3 h-3" />}>
Disabled
</TogglePillImproved>
<span className="text-xs text-text-tertiary">Disabled on state</span>
</div>
</div>
</div>
</div>
</Card>
</div>
);
};

View File

@ -1,34 +0,0 @@
import React from 'react';
import { Card } from '../ui/Card';
import { Sparkles } from 'lucide-react';
import type { AttachedImage, AttachedText } from '../../types/session';
export interface BaseAIToolConfig {
prompt?: string;
model?: string;
attachedImages?: AttachedImage[];
attachedTexts?: AttachedText[];
ultrathink?: boolean;
}
export interface BaseAIToolConfigProps {
config: BaseAIToolConfig;
onChange: (config: BaseAIToolConfig) => void;
disabled?: boolean;
children?: React.ReactNode;
}
export const BaseAIToolConfigComponent: React.FC<BaseAIToolConfigProps> = ({
children
}) => {
return (
<Card variant="bordered" className="p-4 space-y-4">
<div className="flex items-center gap-2 mb-2">
<Sparkles className="w-4 h-4 text-interactive" />
<span className="text-sm font-medium text-text-secondary">AI Tool Configuration</span>
</div>
{children}
</Card>
);
};

View File

@ -1,334 +0,0 @@
import React, { useRef } from 'react';
import { Card } from '../ui/Card';
import { Checkbox } from '../ui/Input';
import { Shield, ShieldOff, Sparkles, Brain, Target, Zap, Paperclip, X, FileText } from 'lucide-react';
import FilePathAutocomplete from '../FilePathAutocomplete';
import type { AttachedImage, AttachedText } from '../../types/session';
export interface ClaudeCodeConfig {
prompt?: string;
model: 'auto' | 'sonnet' | 'opus' | 'haiku';
permissionMode: 'ignore' | 'approve';
ultrathink?: boolean;
attachedImages?: AttachedImage[];
attachedTexts?: AttachedText[];
}
interface ClaudeCodeConfigProps {
config: ClaudeCodeConfig;
onChange: (config: ClaudeCodeConfig) => void;
projectId?: string;
disabled?: boolean;
onPaste?: (e: React.ClipboardEvent) => void;
onRemoveImage?: (id: string) => void;
onRemoveText?: (id: string) => void;
}
export const ClaudeCodeConfigComponent: React.FC<ClaudeCodeConfigProps> = ({
config,
onChange,
projectId,
disabled = false,
onPaste,
onRemoveImage,
onRemoveText
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const processFile = async (file: File): Promise<AttachedImage | null> => {
const generateImageId = () => `img_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
if (!file.type.startsWith('image/')) {
console.warn('File is not an image:', file.name);
return null;
}
// Limit file size to 10MB
if (file.size > 10 * 1024 * 1024) {
console.warn('Image file too large (max 10MB):', file.name);
return null;
}
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
if (e.target?.result) {
resolve({
id: generateImageId(),
name: file.name,
dataUrl: e.target.result as string,
size: file.size,
type: file.type,
});
} else {
resolve(null);
}
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(file);
});
};
return (
<div className="space-y-4">
{/* Prompt Field - Hidden since it's now at the top level */}
<div className="hidden">
<label htmlFor="claude-prompt" className="block text-sm font-medium text-text-secondary mb-2">
Initial Prompt
</label>
{(config.attachedImages?.length ?? 0) > 0 || (config.attachedTexts?.length ?? 0) > 0 ? (
<div className="mb-3 flex flex-wrap gap-2">
{config.attachedTexts?.map(text => (
<div key={text.id} className="relative group">
<div className="h-12 px-3 flex items-center gap-2 bg-surface-secondary rounded border border-border-primary">
<FileText className="w-4 h-4 text-text-secondary" />
<span className="text-xs text-text-secondary max-w-[150px] truncate">
{text.name}
</span>
</div>
<button
type="button"
onClick={() => {
if (disabled) return;
if (onRemoveText) {
onRemoveText(text.id);
} else {
onChange({
...config,
attachedTexts: (config.attachedTexts || []).filter(item => item.id !== text.id)
});
}
}}
className="absolute -top-1 -right-1 bg-surface-primary border border-border-primary rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
aria-label={`Remove ${text.name}`}
>
<X className="w-2.5 h-2.5 text-text-secondary" />
</button>
</div>
))}
{config.attachedImages?.map(image => (
<div key={image.id} className="relative group">
<img
src={image.dataUrl}
alt={image.name}
className="h-12 w-12 object-cover rounded border border-border-primary"
/>
<button
type="button"
onClick={() => {
if (disabled) return;
if (onRemoveImage) {
onRemoveImage(image.id);
} else {
onChange({
...config,
attachedImages: (config.attachedImages || []).filter(item => item.id !== image.id)
});
}
}}
className="absolute -top-1 -right-1 bg-surface-primary border border-border-primary rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity shadow-sm"
aria-label={`Remove ${image.name}`}
>
<X className="w-2.5 h-2.5 text-text-secondary" />
</button>
</div>
))}
</div>
) : null}
<div className="relative">
<FilePathAutocomplete
value={config.prompt || ''}
onChange={(value) => onChange({ ...config, prompt: value })}
projectId={projectId}
placeholder="Describe your task... (use @ to reference files)"
className="w-full px-3 py-2 pr-10 border border-border-primary rounded-md focus:outline-none focus:ring-2 focus:ring-interactive text-text-primary bg-surface-secondary placeholder-text-tertiary"
isTextarea={true}
rows={3}
onPaste={onPaste}
disabled={disabled}
/>
{/* Attachment button */}
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="absolute bottom-2 right-2 p-1.5 rounded hover:bg-surface-hover transition-colors"
title="Attach images"
disabled={disabled}
>
<Paperclip className="w-4 h-4 text-text-tertiary hover:text-text-secondary" />
</button>
</div>
{/* Hidden file input */}
<input
ref={fileInputRef}
type="file"
accept="image/*"
multiple
className="hidden"
disabled={disabled}
onChange={async (e) => {
const files = Array.from(e.target.files || []);
for (const file of files) {
const image = await processFile(file);
if (image) {
onChange({
...config,
attachedImages: [...(config.attachedImages || []), image]
});
}
}
e.target.value = ''; // Reset input
}}
/>
</div>
{/* Model Selection */}
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Model
</label>
<div className="grid grid-cols-4 gap-2">
<Card
variant={config.model === 'auto' ? 'interactive' : 'bordered'}
padding="sm"
className={`relative cursor-pointer transition-all ${
config.model === 'auto'
? 'border-interactive bg-interactive/10'
: ''
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => !disabled && onChange({ ...config, model: 'auto' })}
>
<div className="flex flex-col items-center gap-1 py-2">
<Sparkles className={`w-5 h-5 ${config.model === 'auto' ? 'text-interactive' : ''}`} />
<span className={`text-sm font-medium ${config.model === 'auto' ? 'text-interactive' : ''}`}>Auto</span>
<span className="text-xs opacity-75">Default</span>
</div>
{config.model === 'auto' && (
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
)}
</Card>
<Card
variant={config.model === 'sonnet' ? 'interactive' : 'bordered'}
padding="sm"
className={`relative cursor-pointer transition-all ${
config.model === 'sonnet'
? 'border-interactive bg-interactive/10'
: ''
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => !disabled && onChange({ ...config, model: 'sonnet' })}
>
<div className="flex flex-col items-center gap-1 py-2">
<Target className={`w-5 h-5 ${config.model === 'sonnet' ? 'text-interactive' : ''}`} />
<span className={`text-sm font-medium ${config.model === 'sonnet' ? 'text-interactive' : ''}`}>Sonnet</span>
<span className="text-xs opacity-75">Balanced</span>
</div>
{config.model === 'sonnet' && (
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
)}
</Card>
<Card
variant={config.model === 'opus' ? 'interactive' : 'bordered'}
padding="sm"
className={`relative cursor-pointer transition-all ${
config.model === 'opus'
? 'border-interactive bg-interactive/10'
: ''
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => !disabled && onChange({ ...config, model: 'opus' })}
>
<div className="flex flex-col items-center gap-1 py-2">
<Brain className={`w-5 h-5 ${config.model === 'opus' ? 'text-interactive' : ''}`} />
<span className={`text-sm font-medium ${config.model === 'opus' ? 'text-interactive' : ''}`}>Opus</span>
<span className="text-xs opacity-75">Maximum</span>
</div>
{config.model === 'opus' && (
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
)}
</Card>
<Card
variant={config.model === 'haiku' ? 'interactive' : 'bordered'}
padding="sm"
className={`relative cursor-pointer transition-all ${
config.model === 'haiku'
? 'border-status-success bg-status-success/10'
: ''
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => !disabled && onChange({ ...config, model: 'haiku' })}
>
<div className="flex flex-col items-center gap-1 py-2">
<Zap className={`w-5 h-5 ${config.model === 'haiku' ? 'text-status-success' : ''}`} />
<span className={`text-sm font-medium ${config.model === 'haiku' ? 'text-status-success' : ''}`}>Haiku</span>
<span className="text-xs opacity-75">Fast</span>
</div>
{config.model === 'haiku' && (
<div className="absolute top-1 right-1 w-2 h-2 bg-status-success rounded-full" />
)}
</Card>
</div>
</div>
{/* Additional Options */}
<div className="space-y-3">
{/* Ultrathink Mode */}
<Checkbox
id="claude-ultrathink"
label="Enable ultrathink mode"
checked={config.ultrathink || false}
onChange={(e) => onChange({ ...config, ultrathink: e.target.checked })}
disabled={disabled}
/>
{/* Permission Mode */}
<div>
<label className="block text-sm font-medium text-text-secondary mb-2">
Permission Mode
</label>
<div className="grid grid-cols-2 gap-2">
<Card
variant={config.permissionMode === 'ignore' ? 'interactive' : 'bordered'}
padding="sm"
className={`relative cursor-pointer transition-all ${
config.permissionMode === 'ignore'
? 'border-interactive bg-interactive/10'
: ''
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => !disabled && onChange({ ...config, permissionMode: 'ignore' })}
>
<div className="flex flex-col items-center gap-1 py-2">
<ShieldOff className={`w-5 h-5 ${config.permissionMode === 'ignore' ? 'text-interactive' : 'text-text-tertiary'}`} />
<span className={`text-sm font-medium ${config.permissionMode === 'ignore' ? 'text-interactive' : ''}`}>Skip</span>
<span className="text-xs opacity-75">Default</span>
</div>
{config.permissionMode === 'ignore' && (
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
)}
</Card>
<Card
variant={config.permissionMode === 'approve' ? 'interactive' : 'bordered'}
padding="sm"
className={`relative cursor-pointer transition-all ${
config.permissionMode === 'approve'
? 'border-status-success bg-status-success/10'
: ''
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
onClick={() => !disabled && onChange({ ...config, permissionMode: 'approve' })}
>
<div className="flex flex-col items-center gap-1 py-2">
<Shield className={`w-5 h-5 ${config.permissionMode === 'approve' ? 'text-status-success' : ''}`} />
<span className={`text-sm font-medium ${config.permissionMode === 'approve' ? 'text-status-success' : ''}`}>Manual</span>
<span className="text-xs opacity-75">Approve</span>
</div>
{config.permissionMode === 'approve' && (
<div className="absolute top-1 right-1 w-2 h-2 bg-status-success rounded-full" />
)}
</Card>
</div>
</div>
</div>
</div>
);
};

Some files were not shown because too many files have changed in this diff Show More