Compare commits
1 Commits
main
...
jordan-BAI
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
292c103191 |
52
.github/workflows/build.yml
vendored
@ -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:
|
||||
@ -15,24 +15,20 @@ jobs:
|
||||
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
|
||||
artifact_name: crystal-macos
|
||||
artifact_path: dist-electron/*.dmg
|
||||
- os: ubuntu-latest
|
||||
build_cmd: canary:linux
|
||||
artifact_name: crystal-linux-canary
|
||||
build_cmd: build:linux:ci
|
||||
artifact_name: crystal-linux
|
||||
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 || '' }}
|
||||
@ -130,5 +146,5 @@ jobs:
|
||||
name: ${{ matrix.artifact_name }}
|
||||
path: ${{ matrix.artifact_path }}
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
retention-days: 7
|
||||
|
||||
|
||||
5
.github/workflows/release.yml
vendored
@ -12,7 +12,7 @@ jobs:
|
||||
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 +55,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:
|
||||
|
||||
42
AGENTS.md
@ -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.
|
||||
160
CHANGELOG.md
@ -1,166 +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
|
||||
|
||||
606
CLAUDE.md
@ -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.
|
||||
|
||||
519
NOTICES
@ -13,8 +13,8 @@ The following packages are licensed under the MIT license:
|
||||
|
||||
- @alloc/quick-lru (5.2.0) - Sindre Sorhus
|
||||
- @antfu/install-pkg (1.1.0) - Anthony Fu <anthonyfu117@hotmail.com>
|
||||
- @antfu/utils (9.2.0) - Anthony Fu <anthonyfu117@hotmail.com>
|
||||
- @anthropic-ai/sdk (0.60.0) - Anthropic <support@anthropic.com>
|
||||
- @antfu/utils (8.1.1) - Anthony Fu <anthonyfu117@hotmail.com>
|
||||
- @anthropic-ai/sdk (0.53.0) - Anthropic <support@anthropic.com>
|
||||
- @babel/code-frame (7.27.1) - The Babel Team (https://babel.dev/team)
|
||||
- @babel/compat-data (7.28.0) - The Babel Team (https://babel.dev/team)
|
||||
- @babel/core (7.28.0) - The Babel Team (https://babel.dev/team)
|
||||
@ -32,17 +32,13 @@ The following packages are licensed under the MIT license:
|
||||
- @babel/template (7.27.2) - The Babel Team (https://babel.dev/team)
|
||||
- @babel/traverse (7.28.0) - The Babel Team (https://babel.dev/team)
|
||||
- @babel/types (7.28.1) - The Babel Team (https://babel.dev/team)
|
||||
- @bcoe/v8-coverage (0.2.3) - Charles Samborski <demurgos@demurgos.net> (https://demurgos.net)
|
||||
- @braintree/sanitize-url (7.1.1)
|
||||
- @develar/schema-utils (2.6.5) - webpack Contrib (https://github.com/webpack-contrib)
|
||||
- @electron/asar (3.4.1)
|
||||
- @electron/fuses (1.8.0) - Electron Community
|
||||
- @electron/get (2.0.3) - Samuel Attard
|
||||
- @electron/node-gyp (10.2.0-electron.1) - Nathan Rajlich <nathan@tootallnate.net> (http://tootallnate.net)
|
||||
- @electron/notarize (2.5.0) - Samuel Attard
|
||||
- @electron/rebuild (3.7.2)
|
||||
- @electron/rebuild (4.0.1)
|
||||
- @electron/universal (2.0.3) - Samuel Attard
|
||||
- @electron/rebuild (3.6.1) - Paul Betts <paul@paulbetts.org>
|
||||
- @electron/universal (2.0.1) - Samuel Attard
|
||||
- @emotion/babel-plugin (11.13.5) - Kye Hohenberger
|
||||
- @emotion/cache (11.14.0)
|
||||
- @emotion/css (11.13.5) - Kye Hohenberger
|
||||
@ -53,7 +49,6 @@ The following packages are licensed under the MIT license:
|
||||
- @emotion/unitless (0.10.0)
|
||||
- @emotion/utils (1.4.2)
|
||||
- @emotion/weak-memoize (0.4.0)
|
||||
- @esbuild/darwin-arm64 (0.21.5)
|
||||
- @esbuild/darwin-arm64 (0.25.7)
|
||||
- @eslint-community/regexpp (4.12.1) - Toru Nagashima
|
||||
- @floating-ui/core (1.7.2) - atomiks
|
||||
@ -62,11 +57,10 @@ The following packages are licensed under the MIT license:
|
||||
- @gar/promisify (1.1.3) - Gar <gar+npm@danger.computer>
|
||||
- @homebridge/node-pty-prebuilt-multiarch (0.12.0) - Microsoft Corporation
|
||||
- @iconify/types (2.0.0) - Vjacheslav Trushkin
|
||||
- @iconify/utils (3.0.2) - Vjacheslav Trushkin
|
||||
- @iconify/utils (2.3.0) - Vjacheslav Trushkin
|
||||
- @ioredis/commands (1.2.0) - Zihua Li <i@zihua.li> (http://zihua.li)
|
||||
- @isaacs/balanced-match (4.0.1)
|
||||
- @isaacs/brace-expansion (5.0.0)
|
||||
- @istanbuljs/schema (0.1.3) - Corey Farrell
|
||||
- @jridgewell/gen-mapping (0.3.12) - Justin Ridgewell <justin@ridgewell.name>
|
||||
- @jridgewell/resolve-uri (3.1.2) - Justin Ridgewell <justin@ridgewell.name>
|
||||
- @jridgewell/sourcemap-codec (1.5.4) - Justin Ridgewell <justin@ridgewell.name>
|
||||
@ -81,22 +75,14 @@ The following packages are licensed under the MIT license:
|
||||
- @nodelib/fs.walk (1.2.8)
|
||||
- @npmcli/move-file (2.0.1) - GitHub Inc.
|
||||
- @pkgjs/parseargs (0.11.0)
|
||||
- @posthog/core (1.5.2)
|
||||
- @radix-ui/number (1.1.1)
|
||||
- @radix-ui/primitive (1.1.2)
|
||||
- @radix-ui/rect (1.1.1)
|
||||
- @rolldown/pluginutils (1.0.0-beta.27)
|
||||
- @rollup/rollup-darwin-arm64 (4.45.1) - Lukas Taegert-Atkinson
|
||||
- @sindresorhus/is (4.6.0) - Sindre Sorhus
|
||||
- @standard-schema/spec (1.0.0) - Colin McDonnell
|
||||
- @szmarczak/http-timer (4.0.6) - Szymon Marczak
|
||||
- @tootallnate/once (2.0.0) - Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)
|
||||
- @vitest/expect (2.1.9)
|
||||
- @vitest/pretty-format (2.1.9)
|
||||
- @vitest/runner (2.1.9)
|
||||
- @vitest/snapshot (2.1.9)
|
||||
- @vitest/spy (2.1.9)
|
||||
- @vitest/utils (2.1.9)
|
||||
- @xmldom/xmldom (0.8.10)
|
||||
- @xterm/xterm (5.5.0)
|
||||
- 7zip-bin (5.2.0)
|
||||
@ -115,19 +101,20 @@ The following packages are licensed under the MIT license:
|
||||
- ansi-regex (6.1.0) - Sindre Sorhus
|
||||
- ansi-styles (4.3.0) - Sindre Sorhus
|
||||
- ansi-styles (6.2.1) - Sindre Sorhus
|
||||
- ansi-to-html (0.7.2) - Rob Burns
|
||||
- any-promise (1.3.0) - Kevin Beaty
|
||||
- app-builder-bin (5.0.0-alpha.12)
|
||||
- app-builder-lib (26.0.20) - Vladimir Krivosheev
|
||||
- app-builder-bin (5.0.0-alpha.10)
|
||||
- app-builder-lib (25.1.8) - Vladimir Krivosheev
|
||||
- archiver (5.3.2) - Chris Talkington
|
||||
- archiver-utils (2.1.0) - Chris Talkington
|
||||
- archiver-utils (3.0.4) - Chris Talkington
|
||||
- arg (5.0.2) - Josh Junon <junon@wavetilt.com>
|
||||
- aria-hidden (1.2.6) - Anton Korzunov <thekashey@gmail.com>
|
||||
- assert-plus (1.0.0) - Mark Cavage <mcavage@gmail.com>
|
||||
- assertion-error (2.0.1) - Jake Luer <jake@qualiancy.com> (http://qualiancy.com)
|
||||
- astral-regex (2.0.0) - Kevin Mårtensson
|
||||
- async (3.2.6) - Caolan McMahon
|
||||
- async-exit-hook (2.0.1) - Tapani Moilanen
|
||||
- asynckit (0.4.0) - Alex Indigo <iam@alexindigo.com>
|
||||
- axios (1.12.2) - Matt Zabriskie
|
||||
- axios (1.10.0) - Matt Zabriskie
|
||||
- babel-plugin-macros (3.1.0) - Kent C. Dodds <me@kentcdodds.com> (https://kentcdodds.com)
|
||||
- bail (2.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- balanced-match (1.0.2) - Julian Gruber
|
||||
@ -136,6 +123,8 @@ The following packages are licensed under the MIT license:
|
||||
- binary-extensions (2.3.0) - Sindre Sorhus
|
||||
- bindings (1.5.0) - Nathan Rajlich <nathan@tootallnate.net> (http://tootallnate.net)
|
||||
- bl (4.1.0)
|
||||
- bluebird (3.7.2) - Petka Antonov
|
||||
- bluebird-lst (1.0.9) - Vladimir Krivosheev
|
||||
- body-parser (2.2.0)
|
||||
- boolean (3.2.0)
|
||||
- brace-expansion (1.1.12) - Julian Gruber
|
||||
@ -145,11 +134,11 @@ The following packages are licensed under the MIT license:
|
||||
- buffer (5.7.1) - Feross Aboukhadijeh
|
||||
- buffer-crc32 (0.2.13) - Brian J. Brennan <brianloveswords@gmail.com>
|
||||
- buffer-from (1.1.2)
|
||||
- builder-util (26.0.20) - Vladimir Krivosheev
|
||||
- builder-util-runtime (9.4.0) - Vladimir Krivosheev
|
||||
- builder-util (25.1.7) - Vladimir Krivosheev
|
||||
- builder-util-runtime (9.2.10) - Vladimir Krivosheev
|
||||
- builder-util-runtime (9.3.1) - Vladimir Krivosheev
|
||||
- bull (4.16.5) - OptimalBits
|
||||
- bytes (3.1.2) - TJ Holowaychuk <tj@vision-media.ca> (http://tjholowaychuk.com)
|
||||
- cac (6.7.14) - egoist <0x142857@gmail.com>
|
||||
- cacheable-lookup (5.0.4) - Szymon Marczak
|
||||
- cacheable-request (7.0.4) - Luke Childs <lukechilds123@gmail.com> (http://lukechilds.co.uk)
|
||||
- call-bind-apply-helpers (1.0.2) - Jordan Harband <ljharb@gmail.com>
|
||||
@ -157,17 +146,15 @@ The following packages are licensed under the MIT license:
|
||||
- callsites (3.1.0) - Sindre Sorhus
|
||||
- camelcase-css (2.0.1) - Steven Vachon <contact@svachon.com> (https://www.svachon.com/)
|
||||
- ccount (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- chai (5.2.1) - Jake Luer <jake@alogicalparadox.com>
|
||||
- chalk (4.1.2)
|
||||
- character-entities (2.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- character-entities-html4 (2.1.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- character-entities-legacy (3.0.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- character-reference-invalid (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- check-error (2.1.1) - Jake Luer <jake@alogicalparadox.com> (http://alogicalparadox.com)
|
||||
- chevrotain-allstar (0.3.1) - TypeFox
|
||||
- chokidar (3.6.0) - Paul Miller (https://paulmillr.com)
|
||||
- chromium-pickle-js (0.2.0)
|
||||
- ci-info (4.3.0) - Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)
|
||||
- ci-info (3.9.0) - Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)
|
||||
- classnames (2.5.1) - Jed Watson
|
||||
- clean-stack (2.2.0) - Sindre Sorhus
|
||||
- cli-cursor (3.1.0) - Sindre Sorhus
|
||||
@ -185,10 +172,12 @@ The following packages are licensed under the MIT license:
|
||||
- commander (7.2.0) - TJ Holowaychuk <tj@vision-media.ca>
|
||||
- commander (8.3.0) - TJ Holowaychuk <tj@vision-media.ca>
|
||||
- compare-version (0.1.2) - Kevin Mårtensson
|
||||
- compress-commons (4.1.2) - Chris Talkington
|
||||
- concat-map (0.0.1) - James Halliday
|
||||
- conf (15.0.0) - Sindre Sorhus
|
||||
- conf (14.0.0) - Sindre Sorhus
|
||||
- confbox (0.1.8)
|
||||
- confbox (0.2.2)
|
||||
- config-file-ts (0.2.8-rc1) - lee mighdoll
|
||||
- content-disposition (1.0.0) - Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
- content-type (1.0.5) - Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
- convert-source-map (1.9.0) - Thorsten Lorenz
|
||||
@ -196,11 +185,13 @@ The following packages are licensed under the MIT license:
|
||||
- cookie (0.7.2) - Roman Shtylman <shtylman@gmail.com>
|
||||
- cookie-signature (1.2.2) - TJ Holowaychuk <tj@learnboost.com>
|
||||
- core-util-is (1.0.2) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- core-util-is (1.0.3) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- cors (2.8.5) - Troy Goode <troygoode@gmail.com> (https://github.com/troygoode/)
|
||||
- cose-base (1.0.3)
|
||||
- cose-base (2.2.0)
|
||||
- cosmiconfig (7.1.0) - David Clark <david.dave.clark@gmail.com>
|
||||
- crc (3.8.0) - Alex Gorbatchev
|
||||
- crc32-stream (4.0.3) - Chris Talkington
|
||||
- cron-parser (4.9.0) - Harri Siirak
|
||||
- cross-spawn (7.0.6) - André Cruz <andre@moxy.studio>
|
||||
- cssesc (3.0.0) - Mathias Bynens
|
||||
@ -215,7 +206,6 @@ The following packages are licensed under the MIT license:
|
||||
- debug (4.4.1) - Josh Junon (https://github.com/qix-)
|
||||
- decode-named-character-reference (1.2.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- decompress-response (6.0.0) - Sindre Sorhus
|
||||
- deep-eql (5.0.2) - Jake Luer <jake@alogicalparadox.com>
|
||||
- deep-extend (0.6.0) - Viacheslav Lotsmanov <lotsmanov89@gmail.com>
|
||||
- deep-is (0.1.4) - Thorsten Lorenz
|
||||
- defaults (1.0.4) - Elijah Insua <tmpvar@gmail.com>
|
||||
@ -223,6 +213,7 @@ The following packages are licensed under the MIT license:
|
||||
- define-data-property (1.1.4) - Jordan Harband <ljharb@gmail.com>
|
||||
- define-properties (1.2.1) - Jordan Harband <ljharb@gmail.com>
|
||||
- delayed-stream (1.0.0) - Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)
|
||||
- delegates (1.0.0)
|
||||
- depd (2.0.0) - Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
- dequal (2.0.3) - Luke Edwards
|
||||
- detect-node (2.1.0) - Ilya Kantor
|
||||
@ -230,16 +221,16 @@ The following packages are licensed under the MIT license:
|
||||
- devlop (1.1.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- dir-compare (4.2.0) - Liviu Grigorescu
|
||||
- dlv (1.1.3) - Jason Miller <jason@developit.ca> (http://jasonformat.com)
|
||||
- dmg-builder (26.0.20) - Vladimir Krivosheev
|
||||
- dmg-builder (25.1.8) - Vladimir Krivosheev
|
||||
- dmg-license (1.0.11) - argvminusone
|
||||
- dot-prop (10.0.0) - Sindre Sorhus
|
||||
- dot-prop (9.0.0) - Sindre Sorhus
|
||||
- dunder-proto (1.0.1) - Jordan Harband <ljharb@gmail.com>
|
||||
- eastasianwidth (0.2.0) - Masaki Komagata
|
||||
- ee-first (1.1.1) - Jonathan Ong
|
||||
- electron (37.6.0) - Electron Community
|
||||
- electron-publish (26.0.20) - Vladimir Krivosheev
|
||||
- electron-store (11.0.0) - Sindre Sorhus
|
||||
- electron-updater (6.6.8) - Vladimir Krivosheev
|
||||
- electron (36.7.1) - Electron Community
|
||||
- electron-publish (25.1.7) - Vladimir Krivosheev
|
||||
- electron-store (10.1.0) - Sindre Sorhus
|
||||
- electron-updater (6.6.2) - Vladimir Krivosheev
|
||||
- emoji-regex (8.0.0) - Mathias Bynens
|
||||
- emoji-regex (9.2.2) - Mathias Bynens
|
||||
- encodeurl (2.0.0)
|
||||
@ -251,18 +242,15 @@ The following packages are licensed under the MIT license:
|
||||
- error-ex (1.3.2)
|
||||
- es-define-property (1.0.1) - Jordan Harband <ljharb@gmail.com>
|
||||
- es-errors (1.3.0) - Jordan Harband <ljharb@gmail.com>
|
||||
- es-module-lexer (1.7.0) - Guy Bedford
|
||||
- es-object-atoms (1.1.1) - Jordan Harband <ljharb@gmail.com>
|
||||
- es-set-tostringtag (2.1.0) - Jordan Harband <ljharb@gmail.com>
|
||||
- es6-error (4.1.1) - Ben Youngblood
|
||||
- esbuild (0.21.5)
|
||||
- esbuild (0.25.7)
|
||||
- escalade (3.2.0) - Luke Edwards
|
||||
- escape-html (1.0.3)
|
||||
- escape-string-regexp (4.0.0) - Sindre Sorhus
|
||||
- escape-string-regexp (5.0.0) - Sindre Sorhus
|
||||
- estree-util-is-identifier-name (3.0.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- estree-walker (3.0.3) - Rich Harris
|
||||
- etag (1.8.1)
|
||||
- eventsource (3.0.7) - Espen Hovlandsdal <espen@hovlandsdal.com>
|
||||
- eventsource-parser (3.0.3) - Espen Hovlandsdal <espen@hovlandsdal.com>
|
||||
@ -316,7 +304,6 @@ The following packages are licensed under the MIT license:
|
||||
- hasown (2.0.2) - Jordan Harband <ljharb@gmail.com>
|
||||
- hast-util-to-jsx-runtime (2.3.6) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- hast-util-whitespace (3.0.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- html-escaper (2.0.2) - Andrea Giammarchi
|
||||
- html-url-attributes (3.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- http-errors (2.0.0) - Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)
|
||||
- http-proxy-agent (5.0.0) - Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)
|
||||
@ -329,7 +316,6 @@ The following packages are licensed under the MIT license:
|
||||
- iconv-lite (0.6.3) - Alexander Shtuchkin <ashtuchkin@gmail.com>
|
||||
- ignore (5.3.2) - kael
|
||||
- ignore (7.0.5) - kael
|
||||
- immer (10.1.3) - Michel Weststrate <info@michel.codes>
|
||||
- import-fresh (3.3.1) - Sindre Sorhus
|
||||
- imurmurhash (0.1.4) - Jens Taylor
|
||||
- indent-string (4.0.0) - Sindre Sorhus
|
||||
@ -341,6 +327,7 @@ The following packages are licensed under the MIT license:
|
||||
- is-alphanumerical (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- is-arrayish (0.2.1) - Qix (http://github.com/qix-)
|
||||
- is-binary-path (2.1.0) - Sindre Sorhus
|
||||
- is-ci (3.0.1) - Thomas Watson Steen <w@tson.dk> (https://twitter.com/wa7son)
|
||||
- is-core-module (2.16.1) - Jordan Harband <ljharb@gmail.com>
|
||||
- is-decimal (2.0.1) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- is-extglob (2.1.1) - Jon Schlinkert (https://github.com/jonschlinkert)
|
||||
@ -353,10 +340,10 @@ The following packages are licensed under the MIT license:
|
||||
- is-plain-obj (4.1.0) - Sindre Sorhus
|
||||
- is-promise (4.0.0) - ForbesLindesay
|
||||
- is-unicode-supported (0.1.0) - Sindre Sorhus
|
||||
- isarray (1.0.0) - Julian Gruber
|
||||
- isbinaryfile (4.0.10)
|
||||
- isbinaryfile (5.0.4)
|
||||
- jiti (1.21.7)
|
||||
- jiti (2.6.0)
|
||||
- js-tokens (4.0.0) - Simon Lydell
|
||||
- js-yaml (4.1.0) - Vladimir Zapparov <dervus.grim@gmail.com>
|
||||
- jsbn (1.1.0) - Tom Wu
|
||||
@ -376,6 +363,7 @@ The following packages are licensed under the MIT license:
|
||||
- layout-base (1.0.2)
|
||||
- layout-base (2.0.1)
|
||||
- lazy-val (1.0.5) - Vladimir Krivosheev
|
||||
- lazystream (1.0.1) - Jonas Pommerening
|
||||
- levn (0.4.1) - George Zahariev <z@georgezahariev.com>
|
||||
- lilconfig (3.1.3) - antonk52
|
||||
- lines-and-columns (1.2.4) - Brian Donovan <brian@donovans.cc>
|
||||
@ -384,21 +372,22 @@ The following packages are licensed under the MIT license:
|
||||
- lodash (4.17.21) - John-David Dalton <john.david.dalton@gmail.com>
|
||||
- lodash-es (4.17.21) - John-David Dalton <john.david.dalton@gmail.com>
|
||||
- lodash.defaults (4.2.0) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.difference (4.5.0) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.escaperegexp (4.1.2) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.flatten (4.4.0) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.isarguments (3.1.0) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.isequal (4.5.0) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.isplainobject (4.0.6) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- lodash.merge (4.6.2) - John-David Dalton <john.david.dalton@gmail.com>
|
||||
- lodash.union (4.6.0) - John-David Dalton <john.david.dalton@gmail.com> (http://allyoucanleet.com/)
|
||||
- log-symbols (4.1.0) - Sindre Sorhus
|
||||
- longest-streak (3.1.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- loose-envify (1.4.0) - Andres Suarez <zertosh@gmail.com>
|
||||
- loupe (3.1.4) - Veselin Todorov <hi@vesln.com>
|
||||
- lowercase-keys (2.0.0) - Sindre Sorhus
|
||||
- luxon (3.7.1) - Isaac Cambron
|
||||
- magic-string (0.30.17) - Rich Harris
|
||||
- magicast (0.3.5)
|
||||
- make-dir (4.0.0) - Sindre Sorhus
|
||||
- lzma-native (8.0.6) - Anna Henningsen
|
||||
- markdown-table (3.0.4) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- marked (15.0.12) - Christopher Jeffrey
|
||||
- marked (16.1.1) - Christopher Jeffrey
|
||||
- matcher (3.0.0) - Sindre Sorhus
|
||||
- math-intrinsics (1.1.0) - Jordan Harband <ljharb@gmail.com>
|
||||
- mdast-util-find-and-replace (3.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
@ -420,7 +409,7 @@ The following packages are licensed under the MIT license:
|
||||
- memoize-one (6.0.0) - Alex Reardon <alexreardon@gmail.com>
|
||||
- merge-descriptors (2.0.0)
|
||||
- merge2 (1.4.1)
|
||||
- mermaid (11.11.0) - Knut Sveidqvist
|
||||
- mermaid (11.9.0) - Knut Sveidqvist
|
||||
- micromark (4.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- micromark-core-commonmark (2.0.3) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- micromark-extension-gfm (3.0.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
@ -461,9 +450,7 @@ The following packages are licensed under the MIT license:
|
||||
- mimic-response (3.1.0) - Sindre Sorhus
|
||||
- minimist (1.2.8) - James Halliday
|
||||
- minipass-fetch (2.1.2) - GitHub Inc.
|
||||
- minipass-fetch (4.0.1) - GitHub Inc.
|
||||
- minizlib (2.1.2) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- minizlib (3.1.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- mlly (1.7.4)
|
||||
- monaco-editor (0.52.2) - Microsoft Corporation
|
||||
- ms (2.1.3)
|
||||
@ -475,12 +462,14 @@ The following packages are licensed under the MIT license:
|
||||
- natural-compare (1.4.0) - Lauri Rooden (https://github.com/litejs/natural-compare-lite)
|
||||
- negotiator (0.6.4)
|
||||
- negotiator (1.0.0)
|
||||
- node-abi (3.77.0) - Lukas Geiger
|
||||
- node-abi (4.14.0) - Lukas Geiger
|
||||
- node-abi (3.75.0) - Lukas Geiger
|
||||
- node-addon-api (1.7.2)
|
||||
- node-addon-api (3.2.1)
|
||||
- node-addon-api (7.1.1)
|
||||
- node-api-version (0.1.4) - Tim Fish <tim@timfish.uk>
|
||||
- node-api-version (0.2.1) - Tim Fish <tim@timfish.uk>
|
||||
- node-gyp (11.4.2) - Nathan Rajlich <nathan@tootallnate.net> (http://tootallnate.net)
|
||||
- node-gyp (9.4.1) - Nathan Rajlich <nathan@tootallnate.net> (http://tootallnate.net)
|
||||
- node-gyp-build (4.8.4) - Mathias Buus (@mafintosh)
|
||||
- node-gyp-build-optional-packages (5.2.2) - Mathias Buus (@mafintosh)
|
||||
- node-releases (2.0.19) - Sergey Rubanov <chi187@gmail.com>
|
||||
- normalize-path (3.0.0) - Jon Schlinkert (https://github.com/jonschlinkert)
|
||||
@ -498,7 +487,6 @@ The following packages are licensed under the MIT license:
|
||||
- p-limit (3.1.0) - Sindre Sorhus
|
||||
- p-locate (5.0.0) - Sindre Sorhus
|
||||
- p-map (4.0.0) - Sindre Sorhus
|
||||
- p-map (7.0.3) - Sindre Sorhus
|
||||
- package-manager-detector (1.3.0) - Anthony Fu <anthonyfu117@hotmail.com>
|
||||
- parent-module (1.0.1) - Sindre Sorhus
|
||||
- parse-entities (4.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
@ -511,9 +499,7 @@ The following packages are licensed under the MIT license:
|
||||
- path-parse (1.0.7) - Javier Blanco <http://jbgutierrez.info>
|
||||
- path-to-regexp (8.2.0)
|
||||
- path-type (4.0.0) - Sindre Sorhus
|
||||
- pathe (1.1.2)
|
||||
- pathe (2.0.3)
|
||||
- pathval (2.0.1) - Veselin Todorov <hi@vesln.com>
|
||||
- pe-library (0.4.1) - jet
|
||||
- pend (1.2.0) - Andrew Kelley <superjoe30@gmail.com>
|
||||
- picomatch (2.3.1) - Jon Schlinkert (https://github.com/jonschlinkert)
|
||||
@ -526,9 +512,9 @@ The following packages are licensed under the MIT license:
|
||||
- plist (3.1.0) - Nathan Rajlich <nathan@tootallnate.net>
|
||||
- points-on-curve (0.2.0) - Preet Shihn
|
||||
- points-on-path (0.2.1) - Preet Shihn
|
||||
- posthog-node (5.11.2) - PostHog
|
||||
- prebuild-install (7.1.3) - Mathias Buus (@mafintosh)
|
||||
- prelude-ls (1.2.1) - George Zahariev <z@georgezahariev.com>
|
||||
- process-nextick-args (2.0.1)
|
||||
- progress (2.0.3) - TJ Holowaychuk <tj@vision-media.ca>
|
||||
- promise-retry (2.0.1) - IndigoUnited <hello@indigounited.com> (http://indigounited.com)
|
||||
- prop-types (15.8.1)
|
||||
@ -545,12 +531,12 @@ The following packages are licensed under the MIT license:
|
||||
- react (19.1.0)
|
||||
- react-diff-viewer-continued (3.4.0)
|
||||
- react-dom (19.1.0)
|
||||
- react-error-boundary (6.0.0) - Brian Vaughn <brian.david.vaughn@gmail.com>
|
||||
- react-is (16.13.1)
|
||||
- react-json-view-lite (1.5.0) - AnyRoad
|
||||
- react-refresh (0.17.0)
|
||||
- read-binary-file-arch (1.0.6) - Samuel Maddock
|
||||
- read-cache (1.0.0) - Bogdan Chadkin <trysound@yandex.ru>
|
||||
- readable-stream (2.3.8)
|
||||
- readable-stream (3.6.2)
|
||||
- readdirp (3.6.0) - Thorsten Lorenz <thlorenz@gmx.de> (thlorenz.com)
|
||||
- redis-errors (1.2.0) - Ruben Bridgewater
|
||||
@ -573,6 +559,7 @@ The following packages are licensed under the MIT license:
|
||||
- roughjs (4.6.6) - Preet Shihn <preetshihn@gmail.com>
|
||||
- router (2.2.0) - Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
- run-parallel (1.2.0) - Feross Aboukhadijeh
|
||||
- safe-buffer (5.1.2) - Feross Aboukhadijeh
|
||||
- safe-buffer (5.2.1) - Feross Aboukhadijeh
|
||||
- safer-buffer (2.1.2) - Nikita Skovoroda
|
||||
- scheduler (0.26.0)
|
||||
@ -594,16 +581,14 @@ The following packages are licensed under the MIT license:
|
||||
- smart-buffer (4.2.0) - Josh Glazebrook
|
||||
- socks (2.8.6) - Josh Glazebrook
|
||||
- socks-proxy-agent (7.0.0) - Nathan Rajlich
|
||||
- socks-proxy-agent (8.0.5) - Nathan Rajlich
|
||||
- source-map-support (0.5.21)
|
||||
- space-separated-tokens (2.0.2) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- stackback (0.0.2) - Roman Shtylman <shtylman@gmail.com>
|
||||
- standard-as-callback (2.1.0) - luin <i@zihua.li>
|
||||
- stat-mode (1.0.0) - Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)
|
||||
- state-local (1.0.7) - Suren Atoyan <contact@surenatoyan.com>
|
||||
- statuses (2.0.1)
|
||||
- statuses (2.0.2)
|
||||
- std-env (3.9.0)
|
||||
- string_decoder (1.1.1)
|
||||
- string_decoder (1.3.0)
|
||||
- string-width (4.2.3) - Sindre Sorhus
|
||||
- string-width (5.1.2) - Sindre Sorhus
|
||||
@ -620,22 +605,15 @@ The following packages are licensed under the MIT license:
|
||||
- supports-color (7.2.0) - Sindre Sorhus
|
||||
- supports-color (8.1.1) - Sindre Sorhus
|
||||
- supports-preserve-symlinks-flag (1.0.0) - Jordan Harband <ljharb@gmail.com>
|
||||
- tagged-tag (1.0.0) - Sindre Sorhus
|
||||
- tailwind-merge (2.6.0) - Dany Castillo
|
||||
- tar-fs (2.1.3) - Mathias Buus
|
||||
- tar-stream (2.2.0) - Mathias Buus <mathiasbuus@gmail.com>
|
||||
- temp-file (3.4.0) - Vladimir Krivosheev
|
||||
- thenify (3.3.1) - Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)
|
||||
- thenify-all (1.6.0) - Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)
|
||||
- tiny-async-pool (1.3.0) - Rafael Xavier de Souza
|
||||
- tiny-typed-emitter (2.1.0) - Zurab Benashvili <zura.benashvili@gmail.com>
|
||||
- tinybench (2.9.0)
|
||||
- tinyexec (0.3.2) - James Garbutt (https://github.com/43081j)
|
||||
- tinyexec (1.0.1) - James Garbutt (https://github.com/43081j)
|
||||
- tinyglobby (0.2.14) - Superchupu
|
||||
- tinypool (1.1.1)
|
||||
- tinyrainbow (1.2.0)
|
||||
- tinyspy (3.0.2)
|
||||
- tmp (0.2.3) - KARASZI István <github@spam.raszi.hu> (http://raszi.hu/)
|
||||
- tmp-promise (3.0.3) - Benjamin Gruenbaum and Collaborators.
|
||||
- to-regex-range (5.0.1) - Jon Schlinkert (https://github.com/jonschlinkert)
|
||||
@ -648,7 +626,7 @@ The following packages are licensed under the MIT license:
|
||||
- type-check (0.4.0) - George Zahariev <z@georgezahariev.com>
|
||||
- type-is (2.0.1)
|
||||
- ufo (1.6.1)
|
||||
- uint8array-extras (1.5.0) - Sindre Sorhus
|
||||
- uint8array-extras (1.4.0) - Sindre Sorhus
|
||||
- undici-types (6.21.0)
|
||||
- unified (11.0.5) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
- unist-util-is (6.0.0) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
@ -662,7 +640,6 @@ The following packages are licensed under the MIT license:
|
||||
- update-browserslist-db (1.1.3) - Andrey Sitnik <andrey@sitnik.ru>
|
||||
- util-deprecate (1.0.2) - Nathan Rajlich <nathan@tootallnate.net> (http://n8.io/)
|
||||
- uuid (11.1.0)
|
||||
- uuid (13.0.0)
|
||||
- uuid (8.3.2)
|
||||
- vary (1.1.2) - Douglas Christopher Wilson <doug@somethingdoug.com>
|
||||
- verror (1.10.1)
|
||||
@ -675,9 +652,7 @@ The following packages are licensed under the MIT license:
|
||||
- vscode-languageserver-types (3.17.5) - Microsoft Corporation
|
||||
- vscode-uri (3.0.8) - Microsoft
|
||||
- wcwidth (1.0.1) - Tim Oxley
|
||||
- web-streams-polyfill (3.3.3) - Mattias Buelens <mattias@buelens.com>
|
||||
- when-exit (2.1.4)
|
||||
- why-is-node-running (2.3.0) - Mathias Buus (@mafintosh)
|
||||
- word-wrap (1.2.5) - Jon Schlinkert (https://github.com/jonschlinkert)
|
||||
- wrap-ansi (7.0.0) - Sindre Sorhus
|
||||
- wrap-ansi (8.1.0) - Sindre Sorhus
|
||||
@ -685,6 +660,7 @@ The following packages are licensed under the MIT license:
|
||||
- yargs (17.7.2)
|
||||
- yauzl (2.10.0) - Josh Wolfe <thejoshwolfe@gmail.com>
|
||||
- yocto-queue (0.1.0) - Sindre Sorhus
|
||||
- zip-stream (4.1.1) - Chris Talkington
|
||||
- zod (3.25.76) - Colin McDonnell <zod@colinhacks.com>
|
||||
- zwitch (2.0.4) - Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)
|
||||
|
||||
@ -705,20 +681,19 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
|
||||
The following packages are licensed under the ISC license:
|
||||
|
||||
- @isaacs/cliui (8.0.2) - Ben Coe <ben@npmjs.com>
|
||||
- @isaacs/fs-minipass (4.0.1) - Isaac Z. Schlueter
|
||||
- @npmcli/agent (3.0.0) - GitHub Inc.
|
||||
- @npmcli/fs (2.1.2) - GitHub Inc.
|
||||
- @npmcli/fs (4.0.0) - GitHub Inc.
|
||||
- @ungap/structured-clone (1.3.0) - Andrea Giammarchi
|
||||
- abbrev (1.1.1) - Isaac Z. Schlueter <i@izs.me>
|
||||
- abbrev (3.0.1) - GitHub Inc.
|
||||
- anymatch (3.1.3) - Elan Shanker
|
||||
- aproba (2.1.0) - Rebecca Turner <me@re-becca.org>
|
||||
- are-we-there-yet (3.0.1) - GitHub Inc.
|
||||
- at-least-node (1.0.0) - Ryan Zimmerman <opensrc@ryanzim.com>
|
||||
- cacache (16.1.3) - GitHub Inc.
|
||||
- cacache (19.0.1) - GitHub Inc.
|
||||
- chownr (1.1.4) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- chownr (2.0.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- cliui (8.0.1) - Ben Coe <ben@npmjs.com>
|
||||
- color-support (1.1.3) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- console-control-strings (1.1.0) - Rebecca Turner <me@re-becca.org> (http://re-becca.org/)
|
||||
- d3 (7.9.0) - Mike Bostock
|
||||
- d3-array (3.2.4) - Mike Bostock
|
||||
- d3-axis (3.0.0) - Mike Bostock
|
||||
@ -755,8 +730,8 @@ The following packages are licensed under the ISC license:
|
||||
- flatted (3.3.3) - Andrea Giammarchi
|
||||
- foreground-child (3.3.1) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- fs-minipass (2.1.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- fs-minipass (3.0.3) - GitHub Inc.
|
||||
- fs.realpath (1.0.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- gauge (4.0.4) - GitHub Inc.
|
||||
- get-caller-file (2.0.5) - Stefan Penner
|
||||
- glob (10.4.5) - Isaac Z. Schlueter <i@izs.me> (https://blog.izs.me/)
|
||||
- glob (11.0.3) - Isaac Z. Schlueter <i@izs.me> (https://blog.izs.me/)
|
||||
@ -765,6 +740,7 @@ The following packages are licensed under the ISC license:
|
||||
- glob-parent (5.1.2) - Gulp Team <team@gulpjs.com> (https://gulpjs.com/)
|
||||
- glob-parent (6.0.2) - Gulp Team <team@gulpjs.com> (https://gulpjs.com/)
|
||||
- graceful-fs (4.2.11)
|
||||
- has-unicode (2.0.1) - Rebecca Turner <me@re-becca.org>
|
||||
- hosted-git-info (4.1.0) - Rebecca Turner <me@re-becca.org> (http://re-becca.org)
|
||||
- infer-owner (1.0.4) - Isaac Z. Schlueter <i@izs.me> (https://izs.me)
|
||||
- inflight (1.0.6) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
@ -773,7 +749,6 @@ The following packages are licensed under the ISC license:
|
||||
- internmap (1.0.1) - Mike Bostock
|
||||
- internmap (2.0.3) - Mike Bostock
|
||||
- isexe (2.0.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- isexe (3.1.1) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- json-stringify-safe (5.0.1) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)
|
||||
- lru-cache (10.4.3) - Isaac Z. Schlueter <i@izs.me>
|
||||
- lru-cache (11.1.0) - Isaac Z. Schlueter <i@izs.me>
|
||||
@ -782,7 +757,6 @@ The following packages are licensed under the ISC license:
|
||||
- lru-cache (7.18.3) - Isaac Z. Schlueter <i@izs.me>
|
||||
- lucide-react (0.468.0) - Eric Fennis
|
||||
- make-fetch-happen (10.2.1) - GitHub Inc.
|
||||
- make-fetch-happen (14.0.3) - GitHub Inc.
|
||||
- minimatch (10.0.3) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)
|
||||
- minimatch (3.1.2) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)
|
||||
- minimatch (5.1.6) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)
|
||||
@ -791,36 +765,27 @@ The following packages are licensed under the ISC license:
|
||||
- minipass (5.0.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- minipass (7.1.2) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- minipass-collect (1.0.2) - Isaac Z. Schlueter <i@izs.me> (https://izs.me)
|
||||
- minipass-collect (2.0.1) - Isaac Z. Schlueter <i@izs.me> (https://izs.me)
|
||||
- minipass-flush (1.0.5) - Isaac Z. Schlueter <i@izs.me> (https://izs.me)
|
||||
- minipass-pipeline (1.2.4) - Isaac Z. Schlueter <i@izs.me> (https://izs.me)
|
||||
- minipass-sized (1.0.3) - Isaac Z. Schlueter <i@izs.me> (https://izs.me)
|
||||
- nopt (6.0.0) - GitHub Inc.
|
||||
- nopt (8.1.0) - GitHub Inc.
|
||||
- npmlog (6.0.2) - GitHub Inc.
|
||||
- once (1.4.0) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- picocolors (1.1.1) - Alexey Raspopov
|
||||
- proc-log (2.0.1) - GitHub Inc.
|
||||
- proc-log (5.0.0) - GitHub Inc.
|
||||
- promise-inflight (1.0.1) - Rebecca Turner <me@re-becca.org> (http://re-becca.org/)
|
||||
- sax (1.4.1) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- semver (5.7.2) - GitHub Inc.
|
||||
- semver (6.3.1) - GitHub Inc.
|
||||
- semver (7.7.2) - GitHub Inc.
|
||||
- set-blocking (2.0.0) - Ben Coe <ben@npmjs.com>
|
||||
- setprototypeof (1.2.0) - Wes Todd
|
||||
- siginfo (2.0.0) - Emil Bay <github@tixz.dk>
|
||||
- signal-exit (3.0.7) - Ben Coe <ben@npmjs.com>
|
||||
- signal-exit (4.1.0) - Ben Coe <ben@npmjs.com>
|
||||
- ssri (12.0.0) - GitHub Inc.
|
||||
- ssri (9.0.1) - GitHub Inc.
|
||||
- tar (6.2.1) - GitHub Inc.
|
||||
- tar (7.5.1) - Isaac Z. Schlueter
|
||||
- test-exclude (7.0.1) - Ben Coe <ben@npmjs.com>
|
||||
- unique-filename (2.0.1) - GitHub Inc.
|
||||
- unique-filename (4.0.0) - GitHub Inc.
|
||||
- unique-slug (3.0.0) - GitHub Inc.
|
||||
- unique-slug (5.0.0) - GitHub Inc.
|
||||
- which (2.0.2) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)
|
||||
- which (5.0.0) - GitHub Inc.
|
||||
- wide-align (1.1.5) - Rebecca Turner <me@re-becca.org> (http://re-becca.org/)
|
||||
- wrappy (1.0.2) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
- y18n (5.0.8) - Ben Coe <bencoe@gmail.com>
|
||||
- yallist (3.1.1) - Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
@ -867,15 +832,16 @@ The following packages are licensed under the Apache-2.0 license:
|
||||
- chevrotain (11.0.3) - Shahar Soel
|
||||
- class-variance-authority (0.7.1) - Joe Bell (https://joebell.co.uk)
|
||||
- cluster-key-slot (1.1.2) - Mike Diarmid
|
||||
- crc-32 (1.2.2) - sheetjs
|
||||
- denque (2.1.0) - Invertase
|
||||
- detect-libc (2.0.4) - Lovell Fuller <npm@lovell.info>
|
||||
- didyoumean (1.2.2) - Dave Porter
|
||||
- ejs (3.1.10) - Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)
|
||||
- expect-type (1.2.2)
|
||||
- exponential-backoff (3.1.2) - Sami Sayegh
|
||||
- filelist (1.0.4) - Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)
|
||||
- jake (10.9.2) - Matthew Eernisse <mde@fleegix.org> (http://fleegix.org)
|
||||
- openai (5.10.1) - OpenAI <support@openai.com>
|
||||
- readdir-glob (1.1.3) - Yann Armelin
|
||||
- rxjs (7.8.2) - Ben Lesh <ben@benlesh.com>
|
||||
- sumchecker (3.0.1) - Mark Lee
|
||||
- ts-interface-checker (0.1.13) - Dmitry S, Grist Labs
|
||||
@ -1087,45 +1053,12 @@ Apache License
|
||||
## BSD-3-Clause LICENSE
|
||||
================================================================================
|
||||
|
||||
Package: @hapi/address
|
||||
Version: 5.1.1
|
||||
Repository: git://github.com/hapijs/address
|
||||
|
||||
Copyright (c) 2019-2022, Sideway, Inc. and Project contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* The names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: @hapi/formula
|
||||
Version: 3.0.2
|
||||
Repository: git://github.com/hapijs/formula
|
||||
|
||||
Copyright (c) 2019-2020, Sideway. Inc, and project contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* The names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: @hapi/hoek
|
||||
Version: 11.0.7
|
||||
Version: 9.3.0
|
||||
Repository: git://github.com/hapijs/hoek
|
||||
|
||||
Copyright (c) 2011-2022, Project contributors
|
||||
Copyright (c) 2011-2020, Sideway Inc
|
||||
Copyright (c) 2011-2014, Walmart
|
||||
Copyright (c) 2011-2020, Sideway Inc, and project contributors
|
||||
Copyright (c) 2011-2014, Walmart
|
||||
Copyright (c) 2011, Yahoo Inc.
|
||||
|
||||
All rights reserved.
|
||||
@ -1139,12 +1072,12 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: @hapi/pinpoint
|
||||
Version: 2.0.1
|
||||
Repository: git://github.com/hapijs/pinpoint
|
||||
|
||||
Copyright (c) 2019-2020, Sideway. Inc, and project contributors
|
||||
Package: @hapi/topo
|
||||
Version: 5.1.0
|
||||
Repository: git://github.com/hapijs/topo
|
||||
|
||||
Copyright (c) 2012-2020, Sideway Inc, and project contributors
|
||||
Copyright (c) 2012-2014, Walmart.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
@ -1156,11 +1089,11 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: @hapi/tlds
|
||||
Version: 1.1.3
|
||||
Repository: git://github.com/hapijs/tlds
|
||||
Package: @sideway/address
|
||||
Version: 4.1.5
|
||||
Repository: git://github.com/sideway/address
|
||||
|
||||
Copyright (c) 2019-2022, Sideway, Inc. and Project contributors
|
||||
Copyright (c) 2019-2020, Sideway, Inc. and Project contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
@ -1172,13 +1105,28 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: @hapi/topo
|
||||
Version: 6.0.2
|
||||
Repository: git://github.com/hapijs/topo
|
||||
Package: @sideway/formula
|
||||
Version: 3.0.1
|
||||
Repository: git://github.com/sideway/formula
|
||||
|
||||
Copyright (c) 2019-2020, Sideway. Inc, and project contributors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* The names of any contributors may not be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: @sideway/pinpoint
|
||||
Version: 2.0.0
|
||||
Repository: git://github.com/sideway/pinpoint
|
||||
|
||||
Copyright (c) 2019-2020, Sideway. Inc, and project contributors
|
||||
|
||||
Copyright (c) 2012-2022, Project contributors
|
||||
Copyright (c) 2012-2020, Sideway Inc
|
||||
Copyright (c) 2012-2014, Walmart.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
@ -1523,136 +1471,8 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: istanbul-lib-coverage
|
||||
Version: 3.2.2
|
||||
Author: Krishnan Anantheswaran <kananthmail-github@yahoo.com>
|
||||
Homepage: https://istanbul.js.org/
|
||||
|
||||
Copyright 2012-2015 Yahoo! Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the Yahoo! Inc. nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: istanbul-lib-report
|
||||
Version: 3.0.1
|
||||
Author: Krishnan Anantheswaran <kananthmail-github@yahoo.com>
|
||||
Homepage: https://istanbul.js.org/
|
||||
|
||||
Copyright 2012-2015 Yahoo! Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the Yahoo! Inc. nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: istanbul-lib-source-maps
|
||||
Version: 5.0.6
|
||||
Author: Krishnan Anantheswaran <kananthmail-github@yahoo.com>
|
||||
Homepage: https://istanbul.js.org/
|
||||
|
||||
Copyright 2015 Yahoo! Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the Yahoo! Inc. nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: istanbul-reports
|
||||
Version: 3.1.7
|
||||
Author: Krishnan Anantheswaran <kananthmail-github@yahoo.com>
|
||||
Homepage: https://istanbul.js.org/
|
||||
|
||||
Copyright 2012-2015 Yahoo! Inc.
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the Yahoo! Inc. nor the
|
||||
names of its contributors may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL YAHOO! INC. BE LIABLE FOR ANY
|
||||
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
|
||||
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: joi
|
||||
Version: 18.0.1
|
||||
Version: 17.13.3
|
||||
Repository: git://github.com/hapijs/joi
|
||||
|
||||
Copyright (c) 2012-2022, Project contributors.
|
||||
@ -1914,10 +1734,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
The following packages are licensed under the BSD-2-Clause license:
|
||||
|
||||
- @electron/osx-sign (1.3.3) - electron
|
||||
- @electron/osx-sign (1.3.1) - electron
|
||||
- dotenv (16.6.1)
|
||||
- dotenv-expand (11.0.7) - motdotla
|
||||
- entities (2.2.0) - Felix Boehm <me@feedic.com>
|
||||
- espree (10.4.0) - Nicholas C. Zakas <nicholas+npm@nczconsulting.com>
|
||||
- esrecurse (4.3.0)
|
||||
- estraverse (5.3.0)
|
||||
@ -1956,77 +1775,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
## BlueOak-1.0.0 LICENSE
|
||||
================================================================================
|
||||
|
||||
Package: chownr
|
||||
Version: 3.0.0
|
||||
Author: Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
Repository: git://github.com/isaacs/chownr.git
|
||||
|
||||
All packages under `src/` are licensed according to the terms in
|
||||
their respective `LICENSE` or `LICENSE.md` files.
|
||||
|
||||
The remainder of this project is licensed under the Blue Oak
|
||||
Model License, as follows:
|
||||
|
||||
-----
|
||||
|
||||
# Blue Oak Model License
|
||||
|
||||
Version 1.0.0
|
||||
|
||||
## Purpose
|
||||
|
||||
This license gives everyone as much permission to work with
|
||||
this software as possible, while protecting contributors
|
||||
from liability.
|
||||
|
||||
## Acceptance
|
||||
|
||||
In order to receive this license, you must agree to its
|
||||
rules. The rules of this license are both obligations
|
||||
under that agreement and conditions to your license.
|
||||
You must not do anything with this software that triggers
|
||||
a rule that you cannot or will not follow.
|
||||
|
||||
## Copyright
|
||||
|
||||
Each contributor licenses you to do everything with this
|
||||
software that would otherwise infringe that contributor's
|
||||
copyright in it.
|
||||
|
||||
## Notices
|
||||
|
||||
You must ensure that everyone who gets a copy of
|
||||
any part of this software from you, with or without
|
||||
changes, also gets the text of this license or a link to
|
||||
<https://blueoakcouncil.org/license/1.0.0>.
|
||||
|
||||
## Excuse
|
||||
|
||||
If anyone notifies you in writing that you have not
|
||||
complied with [Notices](#notices), you can keep your
|
||||
license by taking all practical steps to comply within 30
|
||||
days after the notice. If you do not do so, your license
|
||||
ends immediately.
|
||||
|
||||
## Patent
|
||||
|
||||
Each contributor licenses you to do everything with this
|
||||
software that would otherwise infringe any patent claims
|
||||
they can license or become able to license.
|
||||
|
||||
## Reliability
|
||||
|
||||
No contributor can revoke this license.
|
||||
|
||||
## No Liability
|
||||
|
||||
***As far as the law allows, this software comes as is,
|
||||
without any warranty or condition, and no contributor
|
||||
will be liable to anyone for any damages related to this
|
||||
software or this license, under any kind of legal claim.***
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: jackspeak
|
||||
Version: 3.4.3
|
||||
Author: Isaac Z. Schlueter <i@izs.me>
|
||||
@ -2350,77 +2098,6 @@ software or this license, under any kind of legal claim.***
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Package: yallist
|
||||
Version: 5.0.0
|
||||
Author: Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me/)
|
||||
Repository: git+https://github.com/isaacs/yallist.git
|
||||
|
||||
All packages under `src/` are licensed according to the terms in
|
||||
their respective `LICENSE` or `LICENSE.md` files.
|
||||
|
||||
The remainder of this project is licensed under the Blue Oak
|
||||
Model License, as follows:
|
||||
|
||||
-----
|
||||
|
||||
# Blue Oak Model License
|
||||
|
||||
Version 1.0.0
|
||||
|
||||
## Purpose
|
||||
|
||||
This license gives everyone as much permission to work with
|
||||
this software as possible, while protecting contributors
|
||||
from liability.
|
||||
|
||||
## Acceptance
|
||||
|
||||
In order to receive this license, you must agree to its
|
||||
rules. The rules of this license are both obligations
|
||||
under that agreement and conditions to your license.
|
||||
You must not do anything with this software that triggers
|
||||
a rule that you cannot or will not follow.
|
||||
|
||||
## Copyright
|
||||
|
||||
Each contributor licenses you to do everything with this
|
||||
software that would otherwise infringe that contributor's
|
||||
copyright in it.
|
||||
|
||||
## Notices
|
||||
|
||||
You must ensure that everyone who gets a copy of
|
||||
any part of this software from you, with or without
|
||||
changes, also gets the text of this license or a link to
|
||||
<https://blueoakcouncil.org/license/1.0.0>.
|
||||
|
||||
## Excuse
|
||||
|
||||
If anyone notifies you in writing that you have not
|
||||
complied with [Notices](#notices), you can keep your
|
||||
license by taking all practical steps to comply within 30
|
||||
days after the notice. If you do not do so, your license
|
||||
ends immediately.
|
||||
|
||||
## Patent
|
||||
|
||||
Each contributor licenses you to do everything with this
|
||||
software that would otherwise infringe any patent claims
|
||||
they can license or become able to license.
|
||||
|
||||
## Reliability
|
||||
|
||||
No contributor can revoke this license.
|
||||
|
||||
## No Liability
|
||||
|
||||
***As far as the law allows, this software comes as is,
|
||||
without any warranty or condition, and no contributor
|
||||
will be liable to anyone for any damages related to this
|
||||
software or this license, under any kind of legal claim.***
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
================================================================================
|
||||
## Unknown LICENSE
|
||||
================================================================================
|
||||
@ -3814,7 +3491,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
================================================================================
|
||||
|
||||
Package: @anthropic-ai/claude-code
|
||||
Version: 2.0.0
|
||||
Version: 1.0.56
|
||||
Author: Anthropic <support@anthropic.com>
|
||||
Homepage: https://github.com/anthropics/claude-code
|
||||
|
||||
@ -3863,7 +3540,7 @@ For more information, please refer to <http://unlicense.org>
|
||||
================================================================================
|
||||
|
||||
Package: Crystal
|
||||
Version: 0.3.3
|
||||
Version: 0.1.16
|
||||
Author: [object Object]
|
||||
License: MIT
|
||||
|
||||
|
||||
212
README.md
@ -1,56 +1,172 @@
|
||||
# Crystal - Agent Management Platform for Claude Code
|
||||
|
||||
<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>
|
||||
|
||||
[](https://github.com/stravu/crystal/actions/workflows/build.yml)
|
||||
[](https://github.com/stravu/crystal/actions/workflows/quality.yml)
|
||||
[](https://discord.gg/XrVa6q7DPY)
|
||||
|
||||
</div>
|
||||
|
||||
Crystal is a 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/c1181542-c5d2-439e-a2d7-17edaef61366
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
## Using with Third-Party Deployments
|
||||
|
||||
To use Crystal with cloud providers or via corporate infrastructure, you should create a [settings](https://docs.anthropic.com/en/docs/claude-code/settings) file with `ENV` values to correctly connect to the provider.
|
||||
|
||||
For example, here is a minimal configuration to use Amazon Bedrock via an AWS Profile:
|
||||
|
||||
```json5
|
||||
{
|
||||
"env": {
|
||||
"CLAUDE_CODE_USE_BEDROCK": "1",
|
||||
"AWS_REGION": "us-east-2", // Replace with your AWS region
|
||||
"AWS_PROFILE": "my-aws-profile" // Replace with your profile
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Check the [deployment documentation](https://docs.anthropic.com/en/docs/claude-code/third-party-integrations) for more information on getting setup with your particular deployment.
|
||||
|
||||
## 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/**.
|
||||
|
||||
@ -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
|
||||
@ -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.
|
||||
@ -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 |
|
||||
@ -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/)
|
||||
@ -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.
|
||||
@ -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
|
||||
@ -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
|
||||
@ -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.
|
||||
@ -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.
|
||||
@ -36,40 +36,4 @@ brew install python-setuptools
|
||||
|
||||
### 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.
|
||||
- Fix npm permissions: `npm config set prefix ~/.npm-global`
|
||||
@ -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
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.3.5",
|
||||
"version": "0.2.0",
|
||||
"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": {
|
||||
|
||||
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 6.3 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 1.9 MiB |
@ -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 |
@ -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,35 +15,24 @@ 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);
|
||||
@ -52,7 +40,6 @@ function App() {
|
||||
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
|
||||
@ -63,81 +50,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 +68,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 +112,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 +136,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 +183,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 +209,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'
|
||||
);
|
||||
};
|
||||
|
||||
@ -317,11 +246,12 @@ function App() {
|
||||
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) {
|
||||
@ -348,16 +278,12 @@ function App() {
|
||||
/>
|
||||
<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}
|
||||
versionInfo={updateVersionInfo}
|
||||
/>
|
||||
<ErrorDialog
|
||||
isOpen={!!currentError}
|
||||
|
||||
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 1.9 MiB |
@ -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 |
@ -10,7 +10,6 @@ interface VersionInfo {
|
||||
releaseNotes?: string;
|
||||
publishedAt?: string;
|
||||
workingDirectory?: string;
|
||||
crystalDirectory?: string;
|
||||
buildDate?: string;
|
||||
gitCommit?: string;
|
||||
buildTimestamp?: number;
|
||||
@ -44,7 +43,6 @@ 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,
|
||||
@ -170,17 +168,6 @@ export function AboutDialog({ isOpen, onClose }: AboutDialogProps) {
|
||||
</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">
|
||||
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -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 [];
|
||||
@ -558,18 +480,7 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
|
||||
<div className={`combined-diff-view flex flex-col ${isFullscreen ? 'fixed inset-0 z-50 bg-bg-primary' : '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>
|
||||
<h2 className="text-xl font-semibold text-text-primary">File Changes</h2>
|
||||
<div className="flex items-center space-x-4">
|
||||
{isGitOperationRunning && (
|
||||
<div className="flex items-center space-x-2 text-sm text-interactive">
|
||||
@ -612,48 +523,32 @@ 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-border-primary bg-surface-secondary 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-border-primary 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 */}
|
||||
@ -708,21 +603,11 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
|
||||
})()}
|
||||
mainBranch={mainBranch}
|
||||
/>
|
||||
) : executions.length === 0 ? (
|
||||
) : isMainRepo ? (
|
||||
<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>
|
||||
)}
|
||||
<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>
|
||||
) : (
|
||||
@ -757,4 +642,4 @@ const CombinedDiffView: React.FC<CombinedDiffViewProps> = memo(({
|
||||
|
||||
CombinedDiffView.displayName = 'CombinedDiffView';
|
||||
|
||||
export default CombinedDiffView;
|
||||
export default CombinedDiffView;
|
||||
@ -47,7 +47,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 +63,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 {
|
||||
|
||||
@ -24,7 +24,7 @@ interface CommitModePillProps {
|
||||
autoCommit?: boolean;
|
||||
projectId?: number;
|
||||
onModeChange?: (mode: CommitMode, settings: CommitModeSettings) => void;
|
||||
isAutoCommitEnabled?: boolean; // Made optional since it's no longer used
|
||||
isAutoCommitEnabled: boolean;
|
||||
}
|
||||
|
||||
interface AutoCommitSwitchProps {
|
||||
@ -43,6 +43,7 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
|
||||
autoCommit,
|
||||
projectId,
|
||||
onModeChange,
|
||||
isAutoCommitEnabled,
|
||||
}) => {
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
@ -58,10 +59,12 @@ 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;
|
||||
// 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 getModeConfig = (mode: CommitMode) => {
|
||||
const getModeConfig = (mode: 'structured' | 'checkpoint') => {
|
||||
switch (mode) {
|
||||
case 'structured':
|
||||
return {
|
||||
@ -73,15 +76,10 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
|
||||
icon: RotateCcw,
|
||||
label: 'Checkpoint',
|
||||
};
|
||||
case 'disabled':
|
||||
return {
|
||||
icon: GitCommit,
|
||||
label: 'Disabled',
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const handleCommitModeChange = async (newMode: CommitMode) => {
|
||||
const handleCommitModeChange = async (newMode: 'structured' | 'checkpoint') => {
|
||||
const newSettings: CommitModeSettings = {
|
||||
...parsedSettings,
|
||||
mode: newMode,
|
||||
@ -134,15 +132,6 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
|
||||
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);
|
||||
@ -151,18 +140,22 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
|
||||
const modeSelectorPill = (
|
||||
<Pill
|
||||
variant="default"
|
||||
isActive={activeCommitMode !== 'disabled'} // Show active styling when commits are enabled
|
||||
isActive={isAutoCommitEnabled} // Show active styling when enabled
|
||||
icon={<Icon className={cn(
|
||||
'w-3.5 h-3.5',
|
||||
activeCommitMode !== 'disabled' ? 'text-text-on-interactive' : 'text-text-secondary'
|
||||
isAutoCommitEnabled ? 'text-text-on-interactive' : 'text-text-secondary'
|
||||
)} />}
|
||||
className="transition-all duration-200 shadow-sm"
|
||||
className={cn(
|
||||
'transition-all duration-200 shadow-sm',
|
||||
!isAutoCommitEnabled && 'opacity-50 cursor-default'
|
||||
)}
|
||||
disabled={!isAutoCommitEnabled}
|
||||
>
|
||||
{config.label}
|
||||
<ChevronDown className={cn(
|
||||
'w-3 h-3 transition-transform',
|
||||
showDropdown ? 'rotate-180' : '',
|
||||
activeCommitMode !== 'disabled' ? 'text-text-on-interactive' : 'text-text-secondary'
|
||||
isAutoCommitEnabled ? 'text-text-on-interactive' : 'text-text-secondary'
|
||||
)} />
|
||||
</Pill>
|
||||
);
|
||||
@ -181,14 +174,18 @@ export const CommitModePill: React.FC<CommitModePillProps> = ({
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dropdown
|
||||
trigger={modeSelectorPill}
|
||||
items={dropdownItems}
|
||||
selectedId={activeCommitMode}
|
||||
footer={dropdownFooter}
|
||||
position="auto"
|
||||
onOpenChange={setShowDropdown}
|
||||
/>
|
||||
{isAutoCommitEnabled ? (
|
||||
<Dropdown
|
||||
trigger={modeSelectorPill}
|
||||
items={dropdownItems}
|
||||
selectedId={activeCommitMode}
|
||||
footer={dropdownFooter}
|
||||
position="auto"
|
||||
onOpenChange={setShowDropdown}
|
||||
/>
|
||||
) : (
|
||||
modeSelectorPill
|
||||
)}
|
||||
|
||||
{/* Settings Dialog */}
|
||||
{showSettings && (
|
||||
@ -221,25 +218,6 @@ 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,
|
||||
|
||||
179
frontend/src/components/CommitsPanel.tsx
Normal file
@ -0,0 +1,179 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { GitCommit, ChevronDown, ChevronRight, FileText, Plus, Minus } from 'lucide-react';
|
||||
import { API } from '../utils/api';
|
||||
import { parseTimestamp, formatDistanceToNow } from '../utils/timestampUtils';
|
||||
import { cn } from '../utils/cn';
|
||||
|
||||
interface ExecutionDiff {
|
||||
id: number;
|
||||
session_id: string;
|
||||
execution_sequence: number;
|
||||
after_commit_hash?: string;
|
||||
commit_message?: string;
|
||||
stats_additions: number;
|
||||
stats_deletions: number;
|
||||
stats_files_changed: number;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
interface CommitsPanelProps {
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
export function CommitsPanel({ sessionId }: CommitsPanelProps) {
|
||||
const [commits, setCommits] = useState<ExecutionDiff[]>([]);
|
||||
const [expandedCommits, setExpandedCommits] = useState<Set<number>>(new Set());
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
loadCommits();
|
||||
}, [sessionId]);
|
||||
|
||||
const loadCommits = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await API.sessions.getExecutions(sessionId);
|
||||
if (response.success && response.data) {
|
||||
// Show all execution diffs, including failed commits
|
||||
setCommits(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load commits:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleCommit = (commitId: number) => {
|
||||
setExpandedCommits(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(commitId)) {
|
||||
next.delete(commitId);
|
||||
} else {
|
||||
next.add(commitId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="h-full flex items-center justify-center p-4 text-sm text-text-tertiary">
|
||||
Loading commits...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (commits.length === 0) {
|
||||
return (
|
||||
<div className="h-full flex items-center justify-center p-4 text-sm text-text-tertiary text-center">
|
||||
No commits yet
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full overflow-y-auto">
|
||||
{commits.map((commit) => {
|
||||
const isExpanded = expandedCommits.has(commit.id);
|
||||
const timeAgo = formatDistanceToNow(parseTimestamp(commit.timestamp));
|
||||
const isFailedCommit = !commit.after_commit_hash || commit.after_commit_hash === 'UNCOMMITTED';
|
||||
const hasChanges = commit.stats_files_changed > 0;
|
||||
|
||||
// Skip executions with no changes and no commit
|
||||
if (!hasChanges && isFailedCommit) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={commit.id}
|
||||
className="border-b border-border-primary last:border-b-0"
|
||||
>
|
||||
<button
|
||||
onClick={() => toggleCommit(commit.id)}
|
||||
className={cn(
|
||||
"w-full px-4 py-3 flex items-start gap-3 hover:bg-surface-hover transition-colors text-left",
|
||||
isExpanded && "bg-surface-secondary"
|
||||
)}
|
||||
>
|
||||
<div className="mt-0.5">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="w-4 h-4 text-text-tertiary" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-text-tertiary" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<GitCommit className={cn(
|
||||
"w-4 h-4 mt-0.5 flex-shrink-0",
|
||||
isFailedCommit ? "text-status-error" : "text-status-success"
|
||||
)} />
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium text-text-primary truncate">
|
||||
{isFailedCommit ? (
|
||||
<span className="text-status-error">Uncommitted changes</span>
|
||||
) : (
|
||||
commit.commit_message || 'Autocommit'
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-1 text-xs text-text-secondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<FileText className="w-3 h-3" />
|
||||
{commit.stats_files_changed}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-status-success">
|
||||
<Plus className="w-3 h-3" />
|
||||
{commit.stats_additions}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-status-error">
|
||||
<Minus className="w-3 h-3" />
|
||||
{commit.stats_deletions}
|
||||
</span>
|
||||
<span className="text-text-tertiary">•</span>
|
||||
<span>{timeAgo} ago</span>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="px-4 pl-14 pb-3 bg-surface-secondary">
|
||||
<div className="space-y-2 text-sm">
|
||||
{isFailedCommit ? (
|
||||
<div className="text-status-error text-sm">
|
||||
<p className="font-medium">⚠️ Changes were not committed</p>
|
||||
<p className="text-xs mt-1 text-text-secondary">
|
||||
Check the Terminal tab for error details. You may need to commit manually.
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-text-tertiary">Hash:</span>
|
||||
<code className="font-mono text-xs text-text-primary">
|
||||
{commit.after_commit_hash?.substring(0, 7)}
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-text-tertiary">Execution:</span>
|
||||
<span className="text-text-primary">#{commit.execution_sequence}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-text-secondary">
|
||||
<span>{commit.stats_files_changed} file{commit.stats_files_changed !== 1 ? 's' : ''} changed</span>
|
||||
<span className="text-status-success">
|
||||
{commit.stats_additions} addition{commit.stats_additions !== 1 ? 's' : ''}
|
||||
</span>
|
||||
<span className="text-status-error">
|
||||
{commit.stats_deletions} deletion{commit.stats_deletions !== 1 ? 's' : ''}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -2,12 +2,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 +24,19 @@ 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"
|
||||
variant="primary"
|
||||
fullWidth
|
||||
>
|
||||
New Session
|
||||
</Button>
|
||||
|
||||
<CreateSessionDialog isOpen={isOpen} onClose={() => setIsOpen(false)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,9 +1,9 @@
|
||||
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';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
|
||||
// Parse unified diff format to extract individual file diffs
|
||||
const parseUnifiedDiff = (diff: string): FileDiff[] => {
|
||||
@ -1,13 +1,6 @@
|
||||
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;
|
||||
}
|
||||
|
||||
interface DiscordPopupProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
@ -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);
|
||||
}
|
||||
@ -152,7 +145,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 {
|
||||
|
||||
@ -25,17 +25,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 +37,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-status-error mx-auto mb-4" />
|
||||
<h2 className="text-lg font-semibold text-text-primary 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-text-secondary mb-4">
|
||||
The editor encountered an error. Please try refreshing the page.
|
||||
</p>
|
||||
<Button
|
||||
onClick={() => window.location.reload()}
|
||||
variant="primary"
|
||||
>
|
||||
Refresh Page
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -10,12 +10,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) {
|
||||
@ -133,7 +130,7 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
{isUncommitted ? (
|
||||
<span className="text-status-warning">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 && (
|
||||
@ -209,13 +206,6 @@ 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 */}
|
||||
@ -238,4 +228,4 @@ const ExecutionList: React.FC<ExecutionListProps> = memo(({
|
||||
|
||||
ExecutionList.displayName = 'ExecutionList';
|
||||
|
||||
export default ExecutionList;
|
||||
export default ExecutionList;
|
||||
@ -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;
|
||||
@ -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) => {
|
||||
@ -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,53 +609,7 @@ 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">
|
||||
@ -863,10 +621,6 @@ export function FileEditor({
|
||||
sessionId={sessionId}
|
||||
onFileSelect={loadFile}
|
||||
selectedPath={selectedFile?.path || null}
|
||||
initialExpandedDirs={initialState?.expandedDirs}
|
||||
initialSearchQuery={initialState?.searchQuery}
|
||||
initialShowSearch={initialState?.showSearch}
|
||||
onTreeStateChange={handleTreeStateChange}
|
||||
/>
|
||||
|
||||
{/* Resize handle */}
|
||||
@ -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}
|
||||
@ -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 transition-colors ${
|
||||
index === selectedIndex
|
||||
? 'bg-interactive text-on-interactive'
|
||||
: 'text-text-secondary hover:bg-surface-hover'
|
||||
}`}
|
||||
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>
|
||||
|
||||
@ -98,12 +98,9 @@ function buildTooltipContent(gitStatus: GitStatus, config: GitStatusConfig): str
|
||||
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') {
|
||||
@ -145,24 +142,7 @@ function getGitStatusConfig(gitStatus: GitStatus): GitStatusConfig {
|
||||
}
|
||||
|
||||
// 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',
|
||||
|
||||
@ -46,7 +46,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>
|
||||
@ -217,22 +217,10 @@ export default function Help({ isOpen, onClose }: HelpProps) {
|
||||
<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>
|
||||
</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>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@ -3,12 +3,6 @@ import ReactMarkdown from 'react-markdown';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import { MermaidRenderer } from './MermaidRenderer';
|
||||
|
||||
interface CodeComponentProps extends React.HTMLAttributes<HTMLElement> {
|
||||
node?: unknown;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
interface MarkdownPreviewProps {
|
||||
content: string;
|
||||
className?: string;
|
||||
@ -28,7 +22,7 @@ export const MarkdownPreview: React.FC<MarkdownPreviewProps> = ({ content, class
|
||||
<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$/, '');
|
||||
|
||||
@ -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-status-error/30 rounded p-4 bg-status-error/10">
|
||||
<p className="text-status-error font-semibold">Failed to render diagram</p>
|
||||
<pre className="text-xs text-status-error/80 mt-2">{errorMessage}</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -1,15 +1,10 @@
|
||||
import React, { useEffect, useRef, useState, useCallback, useMemo } from 'react';
|
||||
import { DiffEditor, type DiffEditorProps, type MonacoDiffEditor } from '@monaco-editor/react';
|
||||
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 +36,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);
|
||||
@ -260,11 +255,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) => {
|
||||
const handleBeforeMount = useCallback((_monaco: any) => {
|
||||
// Temporarily commented out to test built-in themes
|
||||
// // Define custom themes before the editor mounts
|
||||
// monaco.editor.defineTheme('crystal-dark', {
|
||||
@ -300,7 +295,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
|
||||
// });
|
||||
}, []);
|
||||
|
||||
const handleEditorDidMount: DiffEditorProps['onMount'] = useCallback((editor: MonacoDiffEditor, monacoInstance: typeof monaco) => {
|
||||
const handleEditorDidMount: DiffEditorProps['onMount'] = useCallback((editor: MonacoDiffEditor, monaco: any) => {
|
||||
try {
|
||||
editorRef.current = editor;
|
||||
|
||||
@ -308,7 +303,7 @@ export const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
|
||||
const modifiedEditor = editor.getModifiedEditor();
|
||||
|
||||
// Store disposables for cleanup
|
||||
const disposables: IDisposable[] = [];
|
||||
const disposables: any[] = [];
|
||||
|
||||
// Mark editor as ready
|
||||
setIsEditorReady(true);
|
||||
@ -360,7 +355,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 +378,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);
|
||||
@ -484,25 +479,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 +494,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: any) => {
|
||||
try {
|
||||
d.dispose();
|
||||
} catch (error) {
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -8,13 +8,13 @@ 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 +86,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="text-text-primary">{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-text-secondary">{input.description}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@ -111,18 +102,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="text-text-primary">{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}
|
||||
{input.content.length > 500 ? input.content.substring(0, 500) + '...' : input.content}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
@ -134,11 +134,8 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
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;
|
||||
dashboardCache.set(projectId, event.data);
|
||||
return event.data as ProjectDashboardData;
|
||||
}
|
||||
return prevData;
|
||||
});
|
||||
@ -153,11 +150,9 @@ export const ProjectDashboard: React.FC<ProjectDashboardProps> = React.memo(({ p
|
||||
|
||||
// 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;
|
||||
if (event.projectId === projectId && event.session) {
|
||||
// Add to pending updates
|
||||
pendingSessionUpdatesRef.current.set(event.sessionId, sessionData);
|
||||
pendingSessionUpdatesRef.current.set(event.session.sessionId, event.session);
|
||||
// Trigger debounced update
|
||||
applyPendingSessionUpdates();
|
||||
}
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
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';
|
||||
@ -20,7 +20,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 [newProject, setNewProject] = useState({ name: '', path: '', buildScript: '', runScript: '' });
|
||||
const [showValidationErrors, setShowValidationErrors] = useState(false);
|
||||
const [detectedBranch, setDetectedBranch] = useState<string | null>(null);
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
@ -90,7 +90,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 +115,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()
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@ -56,7 +56,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 +64,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');
|
||||
|
||||
@ -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()
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,13 +1,21 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||
import React, { useState, useRef, useEffect, useCallback } from 'react';
|
||||
import { ProjectDashboard } from './ProjectDashboard';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { SessionInputWithImages } from './session/SessionInputWithImages';
|
||||
import { RichOutputWithSidebar } from './session/RichOutputWithSidebar';
|
||||
import { RichOutputSettings } from './session/RichOutputView';
|
||||
import { API } from '../utils/api';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { useTheme } from '../contexts/ThemeContext';
|
||||
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';
|
||||
import { useSessionView } from '../hooks/useSessionView';
|
||||
import { cn } from '../utils/cn';
|
||||
import { BarChart3, Eye, FolderTree, Terminal as TerminalIcon } from 'lucide-react';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
|
||||
export type ProjectViewMode = 'dashboard' | 'output' | 'files' | 'terminal';
|
||||
|
||||
interface ProjectViewProps {
|
||||
projectId: number;
|
||||
@ -15,201 +23,226 @@ interface ProjectViewProps {
|
||||
onGitPull: () => void;
|
||||
onGitPush: () => void;
|
||||
isMerging: boolean;
|
||||
onViewModeChange?: (mode: ProjectViewMode) => void;
|
||||
}
|
||||
|
||||
interface ProjectViewTabsProps {
|
||||
viewMode: ProjectViewMode;
|
||||
setViewMode: (mode: ProjectViewMode) => void;
|
||||
}
|
||||
|
||||
const ProjectViewTabs: React.FC<ProjectViewTabsProps> = ({ viewMode, setViewMode }) => {
|
||||
const tabs: {
|
||||
mode: ProjectViewMode;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
}[] = [
|
||||
{
|
||||
mode: 'dashboard',
|
||||
label: 'Dashboard',
|
||||
icon: <BarChart3 className="w-4 h-4" />
|
||||
},
|
||||
{
|
||||
mode: 'output',
|
||||
label: 'Output',
|
||||
icon: <Eye className="w-4 h-4" />
|
||||
},
|
||||
{
|
||||
mode: 'files',
|
||||
label: 'Files',
|
||||
icon: <FolderTree className="w-4 h-4" />
|
||||
},
|
||||
{
|
||||
mode: 'terminal',
|
||||
label: 'Terminal',
|
||||
icon: <TerminalIcon className="w-4 h-4" />
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="flex items-center bg-surface-secondary" role="tablist">
|
||||
{tabs.map(({ mode, label, icon }) => (
|
||||
<button
|
||||
key={mode}
|
||||
role="tab"
|
||||
aria-selected={viewMode === mode}
|
||||
onClick={() => setViewMode(mode)}
|
||||
className={cn(
|
||||
"relative flex items-center gap-2 px-4 py-3 text-sm font-medium transition-all",
|
||||
"border-b-2 hover:text-text-primary",
|
||||
viewMode === mode ? [
|
||||
"text-text-primary border-interactive",
|
||||
"bg-gradient-to-t from-interactive/5 to-transparent"
|
||||
] : [
|
||||
"text-text-secondary border-transparent",
|
||||
"hover:border-border-secondary hover:bg-surface-hover/50"
|
||||
]
|
||||
)}
|
||||
>
|
||||
{/* Icon */}
|
||||
<span className={cn(
|
||||
"transition-colors",
|
||||
viewMode === mode ? "text-interactive" : "text-text-tertiary"
|
||||
)}>
|
||||
{icon}
|
||||
</span>
|
||||
|
||||
{/* Label */}
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export const ProjectView: React.FC<ProjectViewProps> = ({
|
||||
projectId,
|
||||
projectName,
|
||||
onGitPull,
|
||||
onGitPush,
|
||||
isMerging
|
||||
isMerging,
|
||||
onViewModeChange
|
||||
}) => {
|
||||
const { theme } = useTheme();
|
||||
const [viewMode, setViewMode] = useState<ProjectViewMode>('dashboard');
|
||||
const [mainRepoSessionId, setMainRepoSessionId] = useState<string | null>(null);
|
||||
const [mainRepoSession, setMainRepoSession] = useState<Session | null>(null);
|
||||
const [isLoadingSession, setIsLoadingSession] = useState(false);
|
||||
const [isStravuConnected, setIsStravuConnected] = useState(false);
|
||||
|
||||
// Panel store state and actions
|
||||
const {
|
||||
panels,
|
||||
activePanels,
|
||||
setPanels,
|
||||
setActivePanel: setActivePanelInStore,
|
||||
addPanel,
|
||||
removePanel
|
||||
} = usePanelStore();
|
||||
// Rich Output settings state (similar to SessionView)
|
||||
const [richOutputSettings, setRichOutputSettings] = useState<RichOutputSettings>(() => {
|
||||
const saved = localStorage.getItem('richOutputSettings');
|
||||
return saved ? JSON.parse(saved) : {
|
||||
showToolCalls: true,
|
||||
compactMode: false,
|
||||
collapseTools: false,
|
||||
showThinking: true,
|
||||
showSessionInit: false,
|
||||
};
|
||||
});
|
||||
|
||||
// Load panels when main repo session changes and ensure dashboard panel exists
|
||||
const handleRichOutputSettingsChange = (newSettings: RichOutputSettings) => {
|
||||
setRichOutputSettings(newSettings);
|
||||
localStorage.setItem('richOutputSettings', JSON.stringify(newSettings));
|
||||
};
|
||||
|
||||
// Notify parent component when view mode changes
|
||||
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);
|
||||
}
|
||||
});
|
||||
if (onViewModeChange) {
|
||||
onViewModeChange(viewMode);
|
||||
}
|
||||
}, [mainRepoSessionId, setPanels, setActivePanelInStore]);
|
||||
}, [viewMode, onViewModeChange]);
|
||||
|
||||
// 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]
|
||||
);
|
||||
// Set main repo session as active when output tab is selected
|
||||
useEffect(() => {
|
||||
if (viewMode === 'output' && mainRepoSession) {
|
||||
useSessionStore.getState().setActiveSession(mainRepoSession.id);
|
||||
}
|
||||
}, [viewMode, mainRepoSession]);
|
||||
|
||||
// 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
|
||||
// Wrapped git operations that switch to output tab
|
||||
const handleGitPull = useCallback(() => {
|
||||
// Find or create a Claude panel
|
||||
const claudePanel = sessionPanels.find(p => p.type === 'claude');
|
||||
if (claudePanel) {
|
||||
handlePanelSelect(claudePanel);
|
||||
} else {
|
||||
handlePanelCreate('claude');
|
||||
}
|
||||
setViewMode('output');
|
||||
onGitPull();
|
||||
}, [onGitPull, sessionPanels, handlePanelSelect, handlePanelCreate]);
|
||||
}, [onGitPull]);
|
||||
|
||||
const handleGitPush = useCallback(() => {
|
||||
// Find or create a Claude panel
|
||||
const claudePanel = sessionPanels.find(p => p.type === 'claude');
|
||||
if (claudePanel) {
|
||||
handlePanelSelect(claudePanel);
|
||||
} else {
|
||||
handlePanelCreate('claude');
|
||||
}
|
||||
setViewMode('output');
|
||||
onGitPush();
|
||||
}, [onGitPush, sessionPanels, handlePanelSelect, handlePanelCreate]);
|
||||
}, [onGitPush]);
|
||||
|
||||
// We don't need terminal handling or the hook for now, as panels handle their own terminals
|
||||
// Handle terminal command
|
||||
const handleTerminalCommand = useCallback(() => {
|
||||
if (!mainRepoSessionId) return;
|
||||
setViewMode('terminal');
|
||||
}, [mainRepoSessionId]);
|
||||
const terminalRef = useRef<HTMLDivElement>(null);
|
||||
const scriptTerminalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
// Terminal state
|
||||
const terminalInstance = useRef<Terminal | null>(null);
|
||||
const fitAddon = useRef<FitAddon | null>(null);
|
||||
const [scriptOutput, setScriptOutput] = useState<string[]>([]);
|
||||
const lastProcessedOutputLength = useRef(0);
|
||||
|
||||
// Use the same hook as SessionView for output handling
|
||||
const hook = useSessionView(mainRepoSession || undefined, undefined, scriptTerminalRef);
|
||||
|
||||
// Debug logging
|
||||
useEffect(() => {
|
||||
console.log('[ProjectView] Session state:', {
|
||||
mainRepoSessionId,
|
||||
mainRepoSession: mainRepoSession?.id,
|
||||
activePanelType: currentActivePanel?.type,
|
||||
viewMode,
|
||||
activeSessionInStore: useSessionStore.getState().activeSessionId
|
||||
});
|
||||
}, [mainRepoSessionId, mainRepoSession, currentActivePanel]);
|
||||
}, [mainRepoSessionId, mainRepoSession, viewMode]);
|
||||
|
||||
// Get or create main repo session when panels are needed
|
||||
// Terminal initialization function
|
||||
const initTerminal = useCallback(() => {
|
||||
if (!terminalRef.current || terminalInstance.current || !mainRepoSessionId) return;
|
||||
|
||||
const term = new Terminal({
|
||||
cursorBlink: true,
|
||||
convertEol: true,
|
||||
rows: 30,
|
||||
cols: 80,
|
||||
scrollback: 100000,
|
||||
fastScrollModifier: 'ctrl',
|
||||
theme: theme === 'dark' ? {
|
||||
background: '#1a1a1a',
|
||||
foreground: '#ffffff',
|
||||
cursor: '#ffffff',
|
||||
} : {
|
||||
background: '#ffffff',
|
||||
foreground: '#000000',
|
||||
cursor: '#000000',
|
||||
}
|
||||
});
|
||||
|
||||
const addon = new FitAddon();
|
||||
term.loadAddon(addon);
|
||||
term.open(terminalRef.current);
|
||||
addon.fit();
|
||||
|
||||
terminalInstance.current = term;
|
||||
fitAddon.current = addon;
|
||||
|
||||
// Handle terminal input
|
||||
term.onData((data) => {
|
||||
if (mainRepoSessionId) {
|
||||
API.sessions.sendTerminalInput(mainRepoSessionId, data).catch(error => {
|
||||
console.error('Failed to send terminal input:', error);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Handle window resize
|
||||
const handleResize = () => {
|
||||
if (fitAddon.current && terminalInstance.current) {
|
||||
fitAddon.current.fit();
|
||||
if (mainRepoSessionId) {
|
||||
API.sessions.resizeTerminal(
|
||||
mainRepoSessionId,
|
||||
terminalInstance.current.cols,
|
||||
terminalInstance.current.rows
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('resize', handleResize);
|
||||
};
|
||||
}, [terminalRef, mainRepoSessionId, theme]);
|
||||
|
||||
// Remove output terminal initialization - now handled by useSessionView
|
||||
|
||||
// Get or create main repo session for file operations
|
||||
useEffect(() => {
|
||||
// Create main repo session when component mounts to support panels
|
||||
const getMainRepoSession = async () => {
|
||||
setIsLoadingSession(true);
|
||||
try {
|
||||
@ -225,8 +258,10 @@ export const ProjectView: React.FC<ProjectViewProps> = ({
|
||||
setMainRepoSession(mainSession);
|
||||
}
|
||||
|
||||
// Set as active session
|
||||
useSessionStore.getState().setActiveSession(response.data.id);
|
||||
// Set as active session if currently on output tab
|
||||
if (viewMode === 'output') {
|
||||
useSessionStore.getState().setActiveSession(response.data.id);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to get main repo session:', error);
|
||||
@ -236,18 +271,15 @@ export const ProjectView: React.FC<ProjectViewProps> = ({
|
||||
};
|
||||
|
||||
getMainRepoSession();
|
||||
}, [projectId]);
|
||||
}, [projectId, viewMode]);
|
||||
|
||||
// Subscribe to session updates - optimized to check for actual changes
|
||||
// Subscribe to session updates
|
||||
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;
|
||||
if (session) {
|
||||
setMainRepoSession(session);
|
||||
}
|
||||
});
|
||||
@ -255,31 +287,92 @@ export const ProjectView: React.FC<ProjectViewProps> = ({
|
||||
return unsubscribe;
|
||||
}, [mainRepoSessionId]);
|
||||
|
||||
// Listen for panel updates from the backend
|
||||
// Initialize terminal when switching to terminal view
|
||||
useEffect(() => {
|
||||
if (viewMode === 'terminal' && mainRepoSessionId) {
|
||||
initTerminal();
|
||||
|
||||
// Pre-create the backend PTY session
|
||||
API.sessions.preCreateTerminal(mainRepoSessionId).then(response => {
|
||||
if (response.success) {
|
||||
console.log('[ProjectView Terminal] Backend PTY pre-created for session', mainRepoSessionId);
|
||||
}
|
||||
}).catch(error => {
|
||||
console.error('[ProjectView Terminal] Failed to pre-create backend PTY:', error);
|
||||
});
|
||||
}
|
||||
}, [viewMode, mainRepoSessionId, initTerminal]);
|
||||
|
||||
// Output loading is now handled by useSessionView hook
|
||||
|
||||
// Subscribe to script output for this session
|
||||
useEffect(() => {
|
||||
if (!mainRepoSessionId) return;
|
||||
|
||||
const unsubscribe = useSessionStore.subscribe((state) => {
|
||||
const sessionOutput = state.scriptOutput[mainRepoSessionId] || [];
|
||||
setScriptOutput(sessionOutput);
|
||||
});
|
||||
|
||||
// Get initial state
|
||||
const initialOutput = useSessionStore.getState().scriptOutput[mainRepoSessionId] || [];
|
||||
setScriptOutput(initialOutput);
|
||||
|
||||
return unsubscribe;
|
||||
}, [mainRepoSessionId]);
|
||||
|
||||
// Session output updates are now handled by useSessionView hook
|
||||
|
||||
// Write script output to terminal
|
||||
useEffect(() => {
|
||||
if (!terminalInstance.current || !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);
|
||||
const fullScriptOutput = scriptOutput.join('');
|
||||
|
||||
// Handle case where output was cleared
|
||||
if (fullScriptOutput.length === 0 && lastProcessedOutputLength.current > 0) {
|
||||
terminalInstance.current.reset();
|
||||
lastProcessedOutputLength.current = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// Write new output
|
||||
if (fullScriptOutput.length > lastProcessedOutputLength.current) {
|
||||
const newOutput = fullScriptOutput.substring(lastProcessedOutputLength.current);
|
||||
terminalInstance.current.write(newOutput);
|
||||
lastProcessedOutputLength.current = fullScriptOutput.length;
|
||||
}
|
||||
}, [scriptOutput, mainRepoSessionId]);
|
||||
|
||||
// Output terminal updates are now handled by useSessionView hook
|
||||
|
||||
// Elapsed time tracking is now handled by useSessionView hook
|
||||
|
||||
// Check Stravu connection status
|
||||
useEffect(() => {
|
||||
const checkStravuConnection = async () => {
|
||||
try {
|
||||
const response = await API.stravu.getConnectionStatus();
|
||||
setIsStravuConnected(response.success && response.data.status === 'connected');
|
||||
} catch (err) {
|
||||
setIsStravuConnected(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for panel events
|
||||
const unsubscribeCreated = window.electronAPI?.events?.onPanelCreated?.(handlePanelCreated);
|
||||
|
||||
// Cleanup
|
||||
return () => {
|
||||
unsubscribeCreated?.();
|
||||
};
|
||||
}, [mainRepoSessionId, addPanel]);
|
||||
checkStravuConnection();
|
||||
const interval = setInterval(checkStravuConnection, 30000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// We don't need Stravu connection status here anymore as it's handled in panels
|
||||
// formatElapsedTime is now provided by useSessionView hook
|
||||
|
||||
// Add clear terminal function
|
||||
const handleClearTerminal = useCallback(() => {
|
||||
if (terminalInstance.current) {
|
||||
terminalInstance.current.reset();
|
||||
lastProcessedOutputLength.current = 0;
|
||||
setScriptOutput([]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
|
||||
return (
|
||||
@ -333,56 +426,115 @@ export const ProjectView: React.FC<ProjectViewProps> = ({
|
||||
</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>
|
||||
)}
|
||||
{/* View Tabs */}
|
||||
<ProjectViewTabs viewMode={viewMode} setViewMode={setViewMode} />
|
||||
|
||||
{/* Content Area */}
|
||||
{/* Project Content */}
|
||||
<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}
|
||||
/>
|
||||
{/* Dashboard View */}
|
||||
<div className={`h-full ${viewMode === 'dashboard' ? 'flex flex-col p-6' : 'hidden'}`}>
|
||||
<ProjectDashboard
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* File Tree View */}
|
||||
<div className={`h-full ${viewMode === 'files' ? 'block' : 'hidden'}`}>
|
||||
{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 file tree...</p>
|
||||
</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>
|
||||
) : (
|
||||
<FileEditor sessionId={mainRepoSessionId} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Terminal View */}
|
||||
<div className={`h-full ${viewMode === 'terminal' ? 'flex flex-col' : 'hidden'} bg-surface-primary`}>
|
||||
<div className="flex items-center justify-between px-4 py-2 bg-surface-secondary border-b border-border-primary">
|
||||
<div className="text-sm text-text-secondary">
|
||||
Terminal - {projectName}
|
||||
</div>
|
||||
{mainRepoSessionId && (
|
||||
<button
|
||||
onClick={handleClearTerminal}
|
||||
className="p-1.5 text-text-secondary hover:text-text-primary hover:bg-surface-hover 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>
|
||||
)}
|
||||
{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 terminal...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div ref={terminalRef} className="flex-1" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Output View */}
|
||||
<div className={`h-full ${viewMode === 'output' ? 'block' : 'hidden'}`}>
|
||||
{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 output...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<RichOutputWithSidebar
|
||||
sessionId={mainRepoSessionId}
|
||||
sessionStatus={mainRepoSession?.status}
|
||||
settings={richOutputSettings}
|
||||
onSettingsChange={handleRichOutputSettingsChange}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{viewMode === 'output' && mainRepoSession && (
|
||||
<SessionInputWithImages
|
||||
activeSession={mainRepoSession}
|
||||
viewMode="richOutput"
|
||||
input={hook.input}
|
||||
setInput={hook.setInput}
|
||||
textareaRef={hook.textareaRef}
|
||||
handleTerminalCommand={handleTerminalCommand}
|
||||
handleSendInput={hook.handleSendInput}
|
||||
handleContinueConversation={hook.handleContinueConversation}
|
||||
isStravuConnected={isStravuConnected}
|
||||
setShowStravuSearch={hook.setShowStravuSearch}
|
||||
ultrathink={hook.ultrathink}
|
||||
setUltrathink={hook.setUltrathink}
|
||||
gitCommands={hook.gitCommands}
|
||||
handleCompactContext={hook.handleCompactContext}
|
||||
hasConversationHistory={hook.hasConversationHistory}
|
||||
contextCompacted={hook.contextCompacted}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
};
|
||||
@ -7,8 +7,7 @@ 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;
|
||||
|
||||
258
frontend/src/components/PromptNavigation.tsx
Normal 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-surface-secondary border-l border-border-primary p-4">
|
||||
<h3 className="font-semibold text-text-primary mb-4">Prompt History</h3>
|
||||
<div className="text-text-tertiary text-sm">Loading prompts...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-64 bg-surface-secondary border-l border-border-primary flex flex-col h-full">
|
||||
<div className="p-4 border-b border-border-primary">
|
||||
<h3 className="font-semibold text-text-primary">Prompt History</h3>
|
||||
<p className="text-xs text-text-tertiary 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-text-tertiary 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-interactive/20 border-interactive border'
|
||||
: 'hover:bg-bg-hover border border-transparent'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start space-x-2">
|
||||
<span className="text-interactive font-mono text-sm mt-0.5">
|
||||
#{index + 1}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm text-text-primary line-clamp-2">
|
||||
{marker.prompt_text}
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 text-xs text-text-tertiary mt-1">
|
||||
<span>{formatDistanceToNow(parseTimestamp(marker.timestamp))} ago</span>
|
||||
<span className="text-text-tertiary">•</span>
|
||||
<span className="font-medium text-text-secondary">
|
||||
{calculateDuration(marker, index)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{modalPrompt && (
|
||||
<PromptDetailModal
|
||||
prompt={modalPrompt.prompt}
|
||||
promptIndex={modalPrompt.index}
|
||||
onClose={() => setModalPrompt(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -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>
|
||||
);
|
||||
};
|
||||
@ -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>
|
||||
);
|
||||
}
|
||||
@ -4,16 +4,12 @@ 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';
|
||||
|
||||
interface SessionListItemProps {
|
||||
session: Session;
|
||||
@ -34,20 +30,31 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
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);
|
||||
|
||||
// Selective subscription for git status loading state
|
||||
const gitStatusLoading = useSessionStore((state) => state.gitStatusLoading.has(session.id));
|
||||
|
||||
|
||||
// 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
|
||||
// Subscribe to session status updates specifically for this session
|
||||
useEffect(() => {
|
||||
const loading = useSessionStore.getState().isGitStatusLoading(session.id);
|
||||
setGitStatusLoading(loading);
|
||||
}, [session.id]);
|
||||
const unsubscribe = useSessionStore.subscribe((state, prevState) => {
|
||||
// Check if this session's status changed
|
||||
const currentSession = state.sessions.find(s => s.id === session.id) ||
|
||||
(state.activeMainRepoSession?.id === session.id ? state.activeMainRepoSession : null);
|
||||
|
||||
const previousSession = prevState.sessions.find(s => s.id === session.id) ||
|
||||
(prevState.activeMainRepoSession?.id === session.id ? prevState.activeMainRepoSession : null);
|
||||
|
||||
// Compare store status with prop status
|
||||
|
||||
// Force component update if status changed
|
||||
if (currentSession && previousSession && currentSession.status !== previousSession.status) {
|
||||
// Status changed - component will re-render due to prop change
|
||||
}
|
||||
});
|
||||
|
||||
return unsubscribe;
|
||||
}, [session.id, session.status]);
|
||||
|
||||
useEffect(() => {
|
||||
// Check if this session's project has a run script
|
||||
@ -63,23 +70,25 @@ 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(() => {
|
||||
@ -112,64 +121,47 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
}, [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);
|
||||
// Fetch Git status for this session
|
||||
const fetchGitStatus = async () => {
|
||||
try {
|
||||
// Don't set loading state here anymore - it's handled by backend events
|
||||
const response = await window.electronAPI.invoke('sessions:get-git-status', session.id);
|
||||
if (response.success && response.gitStatus) {
|
||||
setGitStatus(response.gitStatus);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching git status:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Use session.gitStatus if available, or fetch only once if needed
|
||||
if (session.gitStatus) {
|
||||
setGitStatus(session.gitStatus);
|
||||
} else {
|
||||
fetchGitStatusIfNeeded();
|
||||
// Initial fetch only if we don't already have git status
|
||||
if (!session.archived && session.status !== 'error' && !gitStatus) {
|
||||
fetchGitStatus();
|
||||
}
|
||||
|
||||
// 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 updates
|
||||
let unsubscribeGitStatus: (() => void) | undefined;
|
||||
|
||||
// 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);
|
||||
if (window.electronAPI?.events?.onGitStatusUpdated) {
|
||||
unsubscribeGitStatus = window.electronAPI.events.onGitStatusUpdated((data) => {
|
||||
if (data.sessionId === session.id) {
|
||||
setGitStatus(data.gitStatus);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('git-status-updated', handleGitStatusUpdate as EventListener);
|
||||
window.removeEventListener('git-status-loading', handleGitStatusLoading as EventListener);
|
||||
if (unsubscribeGitStatus) {
|
||||
unsubscribeGitStatus();
|
||||
}
|
||||
};
|
||||
// Reduced dependency array to prevent excessive re-runs
|
||||
}, [session.id, session.archived, session.status, session.gitStatus]);
|
||||
}, [session.id, session.archived, session.status, gitStatus]);
|
||||
|
||||
const handleRunScript = useCallback(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 +180,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);
|
||||
@ -214,7 +206,7 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
try {
|
||||
// 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');
|
||||
@ -324,65 +316,19 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
|
||||
const handleToggleFavorite = async (e: React.MouseEvent) => {
|
||||
e.stopPropagation();
|
||||
|
||||
|
||||
try {
|
||||
const response = await API.sessions.toggleFavorite(session.id);
|
||||
|
||||
|
||||
if (!response.success) {
|
||||
throw new Error(response.error || 'Failed to toggle favorite status');
|
||||
}
|
||||
|
||||
|
||||
} 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 (
|
||||
<>
|
||||
@ -449,30 +395,20 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
size="sm"
|
||||
className={cn(
|
||||
'transition-all',
|
||||
session.isFavorite
|
||||
? 'text-status-warning hover:text-status-warning-hover'
|
||||
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"
|
||||
<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" />}
|
||||
/>
|
||||
)}
|
||||
{!session.archived && (
|
||||
<button
|
||||
onClick={isRunning ? handleStopScript : handleRunScript}
|
||||
@ -521,7 +457,7 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
{/* Context Menu */}
|
||||
{isMenuOpen('session', session.id) && menuState.position && (
|
||||
<div
|
||||
className="context-menu fixed bg-surface-primary border border-border-primary rounded-md shadow-lg py-1 z-50 min-w-[150px]"
|
||||
className="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 }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
@ -543,31 +479,14 @@ 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'
|
||||
isClosing
|
||||
? 'text-text-tertiary cursor-wait'
|
||||
: 'text-text-secondary hover:bg-surface-hover hover:text-text-primary'
|
||||
)}
|
||||
>
|
||||
{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>
|
||||
<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"
|
||||
@ -587,16 +506,6 @@ export const SessionListItem = memo(function SessionListItem({ session, isNested
|
||||
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)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@ -1,287 +1,40 @@
|
||||
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 { 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 { FileEditor } from './FileEditor';
|
||||
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 { RichOutputWithSidebar } from './session/RichOutputWithSidebar';
|
||||
import { RichOutputSettings } from './session/RichOutputView';
|
||||
import { RichOutputSettingsPanel } from './session/RichOutputSettingsPanel';
|
||||
|
||||
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 [projectData, setProjectData] = useState<any>(null);
|
||||
const [isProjectLoading, setIsProjectLoading] = useState(false);
|
||||
const [isMergingProject, setIsMergingProject] = useState(false);
|
||||
const [sessionProject, setSessionProject] = useState<Project | null>(null);
|
||||
const [sessionProject, setSessionProject] = useState<any>(null);
|
||||
|
||||
// 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);
|
||||
// Define activeSession early so it can be used in effects
|
||||
const activeSession = activeSessionId
|
||||
? (activeMainRepoSession && activeMainRepoSession.id === activeSessionId
|
||||
? activeMainRepoSession
|
||||
: sessions.find(s => s.id === activeSessionId))
|
||||
: undefined;
|
||||
|
||||
// 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 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]
|
||||
);
|
||||
|
||||
// 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(() => {
|
||||
@ -290,7 +43,7 @@ export const SessionView = memo(() => {
|
||||
try {
|
||||
const response = await API.projects.getAll();
|
||||
if (response.success && response.data) {
|
||||
const project = response.data.find((p: Project) => p.id === activeSession.projectId);
|
||||
const project = response.data.find((p: any) => p.id === activeSession.projectId);
|
||||
if (project) {
|
||||
setSessionProject(project);
|
||||
}
|
||||
@ -314,7 +67,7 @@ export const SessionView = memo(() => {
|
||||
// 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);
|
||||
const project = response.data.find((p: any) => p.id === activeProjectId);
|
||||
if (project) {
|
||||
setProjectData(project);
|
||||
}
|
||||
@ -370,68 +123,32 @@ export const SessionView = memo(() => {
|
||||
};
|
||||
|
||||
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]);
|
||||
// Settings state for Rich Output view
|
||||
const [showRichOutputSettings, setShowRichOutputSettings] = useState(false);
|
||||
const [richOutputSettings, setRichOutputSettings] = useState<RichOutputSettings>(() => {
|
||||
const saved = localStorage.getItem('richOutputSettings');
|
||||
return saved ? JSON.parse(saved) : {
|
||||
showToolCalls: true,
|
||||
compactMode: false,
|
||||
collapseTools: false,
|
||||
showThinking: true,
|
||||
showSessionInit: false,
|
||||
};
|
||||
});
|
||||
|
||||
// Removed unused variables - now handled by panels
|
||||
const handleRichOutputSettingsChange = (newSettings: RichOutputSettings) => {
|
||||
setRichOutputSettings(newSettings);
|
||||
localStorage.setItem('richOutputSettings', JSON.stringify(newSettings));
|
||||
};
|
||||
|
||||
|
||||
// Memoize props to prevent unnecessary re-renders
|
||||
const emptySelectedExecutions = useMemo(() => [], []);
|
||||
const isMainRepo = useMemo(() => activeSession?.isMainRepo || false, [activeSession?.isMainRepo]);
|
||||
|
||||
// Show project view if navigation is set to project
|
||||
if (activeView === 'project' && activeProjectId) {
|
||||
@ -482,68 +199,106 @@ 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}
|
||||
isOpeningIDE={hook.isOpeningIDE}
|
||||
hasIdeCommand={!!sessionProject?.open_ide_command}
|
||||
mergeError={hook.mergeError}
|
||||
viewMode={hook.viewMode}
|
||||
setViewMode={hook.setViewMode}
|
||||
unreadActivity={hook.unreadActivity}
|
||||
setUnreadActivity={hook.setUnreadActivity}
|
||||
onSettingsClick={() => setShowRichOutputSettings(!showRichOutputSettings)}
|
||||
showSettings={showRichOutputSettings}
|
||||
/>
|
||||
|
||||
{/* 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 && hook.viewMode !== 'richOutput' && (
|
||||
<div className="absolute top-4 left-4 text-text-secondary z-10">Loading output...</div>
|
||||
)}
|
||||
<div className={`h-full ${hook.viewMode === 'richOutput' ? 'block' : 'hidden'}`}>
|
||||
<RichOutputWithSidebar
|
||||
sessionId={activeSession.id}
|
||||
settings={richOutputSettings}
|
||||
onSettingsChange={handleRichOutputSettingsChange}
|
||||
/>
|
||||
</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-bg-primary`}>
|
||||
<div className="flex items-center justify-between px-4 py-2 bg-surface-secondary border-b border-border-primary">
|
||||
<div className="text-sm text-text-secondary">
|
||||
Terminal
|
||||
</div>
|
||||
{!activeSession.archived && (
|
||||
<button
|
||||
onClick={hook.handleClearTerminal}
|
||||
className="p-1.5 text-text-secondary hover:text-text-primary hover:bg-surface-hover 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-text-tertiary" 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-text-primary mb-2">
|
||||
No Terminal History Available
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
This session has been archived. Terminal history is not preserved for archived sessions to save resources.
|
||||
</p>
|
||||
<p className="text-sm text-text-secondary 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>
|
||||
</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}
|
||||
@ -564,7 +319,6 @@ export const SessionView = memo(() => {
|
||||
handleCancelRequest={hook.handleStopSession}
|
||||
/>
|
||||
)}
|
||||
*/}
|
||||
|
||||
<CommitMessageDialog
|
||||
isOpen={hook.showCommitMessageDialog}
|
||||
@ -576,9 +330,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 +346,18 @@ 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}
|
||||
/>
|
||||
|
||||
{/* Rich Output Settings Panel */}
|
||||
{hook.viewMode === 'richOutput' && showRichOutputSettings && (
|
||||
<RichOutputSettingsPanel
|
||||
settings={richOutputSettings}
|
||||
onSettingsChange={handleRichOutputSettingsChange}
|
||||
onClose={() => setShowRichOutputSettings(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
SessionView.displayName = 'SessionView';
|
||||
SessionView.displayName = 'SessionView';
|
||||
@ -4,19 +4,17 @@ 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,
|
||||
import {
|
||||
Shield,
|
||||
ShieldOff,
|
||||
Sun,
|
||||
Moon,
|
||||
Settings as SettingsIcon,
|
||||
Palette,
|
||||
Zap,
|
||||
RefreshCw,
|
||||
FileText,
|
||||
Eye,
|
||||
BarChart3
|
||||
Eye
|
||||
} from 'lucide-react';
|
||||
import { Input, Textarea, Checkbox } from './ui/Input';
|
||||
import { Button } from './ui/Button';
|
||||
@ -38,10 +36,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 +45,13 @@ 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 +67,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 +74,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 +85,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 +104,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');
|
||||
@ -200,16 +143,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
>
|
||||
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 ${
|
||||
@ -344,21 +277,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
helperText="These instructions will be added to every Claude session across all projects."
|
||||
/>
|
||||
</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 */}
|
||||
@ -431,45 +349,6 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
<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"
|
||||
}
|
||||
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
|
||||
@ -529,90 +408,7 @@ 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 */}
|
||||
@ -686,7 +482,7 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
</ModalBody>
|
||||
|
||||
{/* Footer */}
|
||||
{(activeTab === 'general' || activeTab === 'notifications' || activeTab === 'analytics') && (
|
||||
{(activeTab === 'general' || activeTab === 'notifications') && (
|
||||
<ModalFooter>
|
||||
<Button
|
||||
type="button"
|
||||
@ -699,7 +495,7 @@ export function Settings({ isOpen, onClose }: SettingsProps) {
|
||||
<Button
|
||||
type={activeTab === 'general' ? 'submit' : 'button'}
|
||||
form={activeTab === 'general' ? 'settings-form' : undefined}
|
||||
onClick={activeTab === 'notifications' ? (e) => handleSubmit(e as React.FormEvent) : undefined}
|
||||
onClick={activeTab === 'notifications' ? (e) => handleSubmit(e as any) : undefined}
|
||||
disabled={isSubmitting}
|
||||
loading={isSubmitting}
|
||||
variant="primary"
|
||||
|
||||
@ -1,8 +1,7 @@
|
||||
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, Check, Edit, CircleArrowDown, AlertTriangle, GitMerge } from 'lucide-react';
|
||||
import crystalLogo from '../assets/crystal-logo.svg';
|
||||
import { IconButton } from './ui/Button';
|
||||
import { Modal, ModalHeader, ModalBody } from './ui/Modal';
|
||||
@ -21,10 +20,9 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
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...');
|
||||
@ -51,34 +49,10 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
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
|
||||
@ -140,12 +114,6 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
<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>
|
||||
<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"
|
||||
@ -160,27 +128,21 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
/>
|
||||
</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-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>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Settings isOpen={isSettingsOpen} onClose={() => setIsSettingsOpen(false)} />
|
||||
@ -269,7 +231,7 @@ export function Sidebar({ onHelpClick, onAboutClick, onPromptHistoryClick, width
|
||||
{/* 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>
|
||||
<p className="text-text-tertiary text-sm mb-3">Click any indicator to view detailed changes in the View Diff tab</p>
|
||||
|
||||
{/* HIGH PRIORITY */}
|
||||
<div className="mb-3">
|
||||
|
||||
@ -5,6 +5,7 @@ import { isDocumentVisible } from '../utils/performanceUtils';
|
||||
import { Badge } from './ui/Badge';
|
||||
import { StatusDot } from './ui/StatusDot';
|
||||
import { cn } from '../utils/cn';
|
||||
import { useSessionStore } from '../stores/sessionStore';
|
||||
|
||||
interface StatusIndicatorProps {
|
||||
session: Session;
|
||||
@ -21,8 +22,14 @@ export const StatusIndicator = React.memo(({
|
||||
}: StatusIndicatorProps) => {
|
||||
const [animationsEnabled, setAnimationsEnabled] = useState(isDocumentVisible());
|
||||
|
||||
// Use the session status from the prop - parent component manages the session state
|
||||
const currentStatus = session.status;
|
||||
// Get the current session status from the store - this is the source of truth
|
||||
const storeSession = useSessionStore((state) =>
|
||||
state.sessions.find(s => s.id === session.id) ||
|
||||
(state.activeMainRepoSession?.id === session.id ? state.activeMainRepoSession : null)
|
||||
);
|
||||
|
||||
// Use store session status if available, otherwise fall back to prop
|
||||
const currentStatus = storeSession?.status || session.status;
|
||||
|
||||
useEffect(() => {
|
||||
const handleVisibilityChange = () => {
|
||||
@ -32,7 +39,7 @@ 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 {
|
||||
@ -40,8 +47,8 @@ export const StatusIndicator = React.memo(({
|
||||
badgeVariant: 'success' as const,
|
||||
dotStatus: 'running' as const,
|
||||
icon: Loader2,
|
||||
text: statusMessage || 'Initializing',
|
||||
tooltip: statusMessage || 'Setting up git worktree and environment',
|
||||
text: 'Initializing',
|
||||
tooltip: 'Setting up git worktree and environment',
|
||||
spin: true,
|
||||
animated: true
|
||||
};
|
||||
@ -133,7 +140,7 @@ export const StatusIndicator = React.memo(({
|
||||
}
|
||||
};
|
||||
|
||||
const config = getStatusConfig(currentStatus, session.statusMessage);
|
||||
const config = getStatusConfig(currentStatus);
|
||||
const badgeSize = getBadgeSize(size);
|
||||
const dotSize = getDotSize(size);
|
||||
|
||||
|
||||
@ -2,8 +2,6 @@ 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';
|
||||
|
||||
interface UpdateDialogProps {
|
||||
isOpen: boolean;
|
||||
@ -105,8 +103,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 +117,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 +131,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');
|
||||
}
|
||||
};
|
||||
@ -355,39 +353,9 @@ export function UpdateDialog({ isOpen, onClose, versionInfo }: UpdateDialogProps
|
||||
<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>
|
||||
<pre className="text-sm text-text-secondary whitespace-pre-wrap font-sans">
|
||||
{versionInfo.releaseNotes}
|
||||
</pre>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
@ -123,7 +123,7 @@ export default function Welcome({ isOpen, onClose }: WelcomeProps) {
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@ -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>
|
||||
);
|
||||
};
|
||||
@ -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>
|
||||
);
|
||||
};
|
||||
@ -1,344 +0,0 @@
|
||||
import React, { useRef } from 'react';
|
||||
import { Card } from '../ui/Card';
|
||||
import { Cpu, Paperclip, X, FileText, Brain, Gauge, Zap } from 'lucide-react';
|
||||
import FilePathAutocomplete from '../FilePathAutocomplete';
|
||||
import { CODEX_MODELS, type OpenAICodexModel } from '../../../../shared/types/models';
|
||||
import type { AttachedImage, AttachedText } from '../../types/session';
|
||||
|
||||
export interface CodexConfig {
|
||||
prompt?: string;
|
||||
model?: OpenAICodexModel;
|
||||
modelProvider?: string;
|
||||
approvalPolicy?: 'auto' | 'manual';
|
||||
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
webSearch?: boolean;
|
||||
thinkingLevel?: 'low' | 'medium' | 'high';
|
||||
attachedImages?: AttachedImage[];
|
||||
attachedTexts?: AttachedText[];
|
||||
}
|
||||
|
||||
interface CodexConfigProps {
|
||||
config: CodexConfig;
|
||||
onChange: (config: CodexConfig) => void;
|
||||
projectId?: string;
|
||||
disabled?: boolean;
|
||||
onPaste?: (e: React.ClipboardEvent) => void;
|
||||
onRemoveImage?: (id: string) => void;
|
||||
onRemoveText?: (id: string) => void;
|
||||
}
|
||||
|
||||
export const CodexConfigComponent: React.FC<CodexConfigProps> = ({
|
||||
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="codex-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-3 gap-2">
|
||||
{Object.values(CODEX_MODELS).filter(m => m.id !== 'auto').map(modelCfg => (
|
||||
<Card
|
||||
key={modelCfg.id}
|
||||
variant={config.model === modelCfg.id ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
config.model === modelCfg.id ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, model: modelCfg.id as OpenAICodexModel, modelProvider: 'openai' })}
|
||||
title={modelCfg.description}
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Cpu className={`w-5 h-5 ${config.model === modelCfg.id ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${config.model === modelCfg.id ? 'text-interactive' : ''}`}>{modelCfg.label}</span>
|
||||
<span className="text-xs opacity-75">OpenAI</span>
|
||||
</div>
|
||||
{config.model === modelCfg.id && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Thinking Level */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Thinking Level
|
||||
</label>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<Card
|
||||
variant={(config.thinkingLevel || 'medium') === 'low' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
(config.thinkingLevel || 'medium') === 'low' ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, thinkingLevel: 'low' })}
|
||||
title="Low thinking - Faster responses with less reasoning"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Gauge className={`w-5 h-5 ${(config.thinkingLevel || 'medium') === 'low' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${(config.thinkingLevel || 'medium') === 'low' ? 'text-interactive' : ''}`}>Low</span>
|
||||
<span className="text-xs opacity-75">Fast</span>
|
||||
</div>
|
||||
{(config.thinkingLevel || 'medium') === 'low' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
<Card
|
||||
variant={(config.thinkingLevel || 'medium') === 'medium' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
(config.thinkingLevel || 'medium') === 'medium' ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, thinkingLevel: 'medium' })}
|
||||
title="Medium thinking - Balanced speed and reasoning (default)"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Brain className={`w-5 h-5 ${(config.thinkingLevel || 'medium') === 'medium' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${(config.thinkingLevel || 'medium') === 'medium' ? 'text-interactive' : ''}`}>Medium</span>
|
||||
<span className="text-xs opacity-75">Balanced</span>
|
||||
</div>
|
||||
{(config.thinkingLevel || 'medium') === 'medium' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
<Card
|
||||
variant={(config.thinkingLevel || 'medium') === 'high' ? 'interactive' : 'bordered'}
|
||||
padding="sm"
|
||||
className={`relative cursor-pointer transition-all ${
|
||||
(config.thinkingLevel || 'medium') === 'high' ? 'border-interactive bg-interactive/10' : ''
|
||||
} ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
|
||||
onClick={() => !disabled && onChange({ ...config, thinkingLevel: 'high' })}
|
||||
title="High thinking - Slower but more thorough reasoning"
|
||||
>
|
||||
<div className="flex flex-col items-center gap-1 py-2">
|
||||
<Zap className={`w-5 h-5 ${(config.thinkingLevel || 'medium') === 'high' ? 'text-interactive' : ''}`} />
|
||||
<span className={`text-sm font-medium ${(config.thinkingLevel || 'medium') === 'high' ? 'text-interactive' : ''}`}>High</span>
|
||||
<span className="text-xs opacity-75">Thorough</span>
|
||||
</div>
|
||||
{(config.thinkingLevel || 'medium') === 'high' && (
|
||||
<div className="absolute top-1 right-1 w-2 h-2 bg-interactive rounded-full" />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Additional Options */}
|
||||
<div className="space-y-3">
|
||||
{/* Web Search - Hidden for Codex as it doesn't work */}
|
||||
{/* <Checkbox
|
||||
id="codex-websearch"
|
||||
label="Enable web search"
|
||||
checked={config.webSearch || false}
|
||||
onChange={(e) => onChange({ ...config, webSearch: e.target.checked })}
|
||||
disabled={disabled}
|
||||
/> */}
|
||||
|
||||
{/* Approval Policy - Hidden as Crystal doesn't implement approval handling for Codex */}
|
||||
{/* Manual approval mode requires implementing exec_approval_request and patch_approval_request handlers */}
|
||||
{/* which Crystal currently doesn't support, so we default to 'auto' */}
|
||||
|
||||
{/* Sandbox Mode */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-text-secondary mb-2">
|
||||
Sandbox Mode
|
||||
</label>
|
||||
<div className="space-y-2">
|
||||
<label className={`flex items-center gap-2 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name="codex-sandbox"
|
||||
value="read-only"
|
||||
checked={config.sandboxMode === 'read-only'}
|
||||
onChange={(e) => onChange({ ...config, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="text-interactive"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="text-sm text-text-secondary">Read-only</span>
|
||||
</label>
|
||||
<label className={`flex items-center gap-2 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name="codex-sandbox"
|
||||
value="workspace-write"
|
||||
checked={config.sandboxMode === 'workspace-write'}
|
||||
onChange={(e) => onChange({ ...config, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="text-interactive"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="text-sm text-text-secondary">Workspace write</span>
|
||||
<span className="text-xs text-text-tertiary">(default)</span>
|
||||
</label>
|
||||
<label className={`flex items-center gap-2 cursor-pointer ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}>
|
||||
<input
|
||||
type="radio"
|
||||
name="codex-sandbox"
|
||||
value="danger-full-access"
|
||||
checked={config.sandboxMode === 'danger-full-access'}
|
||||
onChange={(e) => onChange({ ...config, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="text-interactive"
|
||||
disabled={disabled}
|
||||
/>
|
||||
<span className="text-sm text-status-error">Full access (dangerous)</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,35 +0,0 @@
|
||||
interface NimbalystIconProps {
|
||||
className?: string;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
export function NimbalystIcon({ className = '', size = 16 }: NimbalystIconProps) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 1024 1024"
|
||||
className={className}
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<path
|
||||
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"
|
||||
fill="#6395ff"
|
||||
transform="matrix(7.5995429,0,0,7.5995429,-560.09045,326.96861)"
|
||||
/>
|
||||
<text
|
||||
x="306.01437"
|
||||
y="668.91577"
|
||||
style={{
|
||||
fontWeight: 'bold',
|
||||
fontSize: '527.974px',
|
||||
fontFamily: 'Chalkboard SE',
|
||||
fill: '#ffffff',
|
||||
}}
|
||||
>
|
||||
#
|
||||
</text>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@ -1,45 +0,0 @@
|
||||
import React from 'react';
|
||||
import { ProjectDashboard } from '../ProjectDashboard';
|
||||
import { useSession } from '../../contexts/SessionContext';
|
||||
|
||||
interface DashboardPanelProps {
|
||||
panelId: string;
|
||||
sessionId: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
const DashboardPanel: React.FC<DashboardPanelProps> = () => {
|
||||
const sessionContext = useSession();
|
||||
|
||||
// Get project info from session context
|
||||
const projectIdStr = sessionContext?.projectId;
|
||||
const projectName = sessionContext?.projectName || 'Project';
|
||||
|
||||
if (!projectIdStr) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full bg-gray-900">
|
||||
<div className="text-gray-400">No project selected</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const projectId = parseInt(projectIdStr, 10);
|
||||
if (isNaN(projectId)) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full bg-gray-900">
|
||||
<div className="text-gray-400">Invalid project ID</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full bg-gray-900 overflow-auto">
|
||||
<ProjectDashboard
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DashboardPanel;
|
||||
@ -1,102 +0,0 @@
|
||||
import React, { Suspense, lazy, useMemo } from 'react';
|
||||
import { PanelContainerProps } from '../../types/panelComponents';
|
||||
import { ErrorBoundary } from 'react-error-boundary';
|
||||
import { CliPanelFactory } from './cli/CliPanelFactory';
|
||||
import { PanelLoadingFallback } from './PanelLoadingFallback';
|
||||
import { renderLog } from '../../utils/console';
|
||||
|
||||
// Lazy load panel components for better performance
|
||||
const TerminalPanel = lazy(() => import('./TerminalPanel'));
|
||||
const DiffPanel = lazy(() => import('./diff/DiffPanel'));
|
||||
const EditorPanel = lazy(() => import('./editor/EditorPanel'));
|
||||
const LogsPanel = lazy(() => import('./logPanel/LogsPanel'));
|
||||
const DashboardPanel = lazy(() => import('./DashboardPanel'));
|
||||
const SetupTasksPanel = lazy(() => import('./SetupTasksPanel'));
|
||||
|
||||
const PanelErrorFallback: React.FC<{ error: Error; resetErrorBoundary: () => void }> = ({
|
||||
error,
|
||||
resetErrorBoundary
|
||||
}) => (
|
||||
<div className="flex flex-col items-center justify-center h-full text-red-500 p-4">
|
||||
<p className="text-lg font-semibold mb-2">Panel Error</p>
|
||||
<p className="text-sm text-gray-400 mb-4">{error.message}</p>
|
||||
<button
|
||||
onClick={resetErrorBoundary}
|
||||
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
|
||||
>
|
||||
Retry
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
|
||||
export const PanelContainer: React.FC<PanelContainerProps> = React.memo(({
|
||||
panel,
|
||||
isActive,
|
||||
isMainRepo = false
|
||||
}) => {
|
||||
renderLog('[PanelContainer] Rendering panel:', panel.id, 'Type:', panel.type, 'Active:', isActive);
|
||||
|
||||
// FIX: Use stable panel rendering without forcing remounts
|
||||
// Each panel type maintains its own state internally
|
||||
// The isActive prop controls whether it should render its content
|
||||
|
||||
const panelComponent = useMemo(() => {
|
||||
renderLog('[PanelContainer] Creating component for panel type:', panel.type);
|
||||
|
||||
// CLI panel types (including Claude and Codex) use the CLI panel factory
|
||||
const cliPanelTypes = ['claude', 'codex', 'aider', 'continue', 'cursor', 'generic-cli'];
|
||||
if (cliPanelTypes.includes(panel.type)) {
|
||||
return <CliPanelFactory panel={panel} isActive={isActive} />;
|
||||
}
|
||||
|
||||
// Non-CLI panel types use direct components
|
||||
switch (panel.type) {
|
||||
case 'terminal':
|
||||
return <TerminalPanel panel={panel} isActive={isActive} />;
|
||||
case 'diff':
|
||||
return <DiffPanel panel={panel} isActive={isActive} sessionId={panel.sessionId} isMainRepo={isMainRepo} />;
|
||||
case 'editor':
|
||||
return <EditorPanel panel={panel} isActive={isActive} />;
|
||||
case 'logs':
|
||||
return <LogsPanel panel={panel} isActive={isActive} />;
|
||||
case 'dashboard':
|
||||
return <DashboardPanel panelId={panel.id} sessionId={panel.sessionId} isActive={isActive} />;
|
||||
case 'setup-tasks':
|
||||
return <SetupTasksPanel panelId={panel.id} sessionId={panel.sessionId} isActive={isActive} />;
|
||||
default:
|
||||
return (
|
||||
<div className="h-full w-full flex items-center justify-center p-8">
|
||||
<div className="text-center max-w-md">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
Unknown Panel Type
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
Panel type "{panel.type}" is not recognized.
|
||||
</p>
|
||||
<p className="text-xs text-text-tertiary mt-2">
|
||||
Panel ID: {panel.id}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}, [panel, isActive, isMainRepo]); // Include panel to catch state changes
|
||||
|
||||
return (
|
||||
<ErrorBoundary
|
||||
FallbackComponent={PanelErrorFallback}
|
||||
resetKeys={[panel.id]} // Only reset when panel changes
|
||||
>
|
||||
<Suspense fallback={
|
||||
<PanelLoadingFallback
|
||||
panelType={panel.type}
|
||||
message={`Loading ${panel.type} panel...`}
|
||||
/>
|
||||
}>
|
||||
{panelComponent}
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
});
|
||||
|
||||
PanelContainer.displayName = 'PanelContainer';
|
||||
@ -1,30 +0,0 @@
|
||||
import React from 'react';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
|
||||
interface PanelLoadingFallbackProps {
|
||||
panelType?: string;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimized loading fallback for lazy-loaded panels
|
||||
* Reduces unnecessary re-renders and provides better UX
|
||||
*/
|
||||
export const PanelLoadingFallback: React.FC<PanelLoadingFallbackProps> = React.memo(({
|
||||
panelType = 'panel',
|
||||
message
|
||||
}) => (
|
||||
<div className="flex items-center justify-center h-full bg-bg-primary">
|
||||
<div className="text-center">
|
||||
<RefreshCw
|
||||
className="w-8 h-8 text-text-secondary animate-spin mx-auto mb-3"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<p className="text-sm text-text-secondary">
|
||||
{message || `Loading ${panelType} panel...`}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
));
|
||||
|
||||
PanelLoadingFallback.displayName = 'PanelLoadingFallback';
|
||||
@ -1,347 +0,0 @@
|
||||
import React, { useCallback, memo, useState, useRef, useEffect } from 'react';
|
||||
import { Plus, X, Terminal, ChevronDown, MessageSquare, GitBranch, FileText, FileCode, MoreVertical, BarChart3, Code2, Edit2 } from 'lucide-react';
|
||||
import { cn } from '../../utils/cn';
|
||||
import { PanelTabBarProps } from '../../types/panelComponents';
|
||||
import { ToolPanel, ToolPanelType, PANEL_CAPABILITIES, LogsPanelState, BaseAIPanelState, PanelStatus } from '../../../../shared/types/panels';
|
||||
import { Button } from '../ui/Button';
|
||||
import { Dropdown } from '../ui/Dropdown';
|
||||
import { useSession } from '../../contexts/SessionContext';
|
||||
import { StatusDot } from '../ui/StatusDot';
|
||||
|
||||
export const PanelTabBar: React.FC<PanelTabBarProps> = memo(({
|
||||
panels,
|
||||
activePanel,
|
||||
onPanelSelect,
|
||||
onPanelClose,
|
||||
onPanelCreate,
|
||||
context = 'worktree' // Default to worktree for backward compatibility
|
||||
}) => {
|
||||
const sessionContext = useSession();
|
||||
const { gitBranchActions, isMerging } = sessionContext || {};
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
const [editingPanelId, setEditingPanelId] = useState<string | null>(null);
|
||||
const [editingTitle, setEditingTitle] = useState('');
|
||||
const editInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Memoize event handlers to prevent unnecessary re-renders
|
||||
const handlePanelClick = useCallback((panel: ToolPanel) => {
|
||||
onPanelSelect(panel);
|
||||
}, [onPanelSelect]);
|
||||
|
||||
const handlePanelClose = useCallback((e: React.MouseEvent, panel: ToolPanel) => {
|
||||
e.stopPropagation();
|
||||
|
||||
// Prevent closing logs panel while it's running
|
||||
if (panel.type === 'logs') {
|
||||
const logsState = panel.state?.customState as LogsPanelState;
|
||||
if (logsState?.isRunning) {
|
||||
alert('Cannot close logs panel while process is running. Please stop the process first.');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
onPanelClose(panel);
|
||||
}, [onPanelClose]);
|
||||
|
||||
const handleAddPanel = useCallback((type: ToolPanelType) => {
|
||||
onPanelCreate(type);
|
||||
setShowDropdown(false);
|
||||
}, [onPanelCreate]);
|
||||
|
||||
const handleStartRename = useCallback((e: React.MouseEvent, panel: ToolPanel) => {
|
||||
e.stopPropagation();
|
||||
if (panel.type === 'diff') {
|
||||
return;
|
||||
}
|
||||
setEditingPanelId(panel.id);
|
||||
setEditingTitle(panel.title);
|
||||
}, []);
|
||||
|
||||
const handleRenameSubmit = useCallback(async () => {
|
||||
if (editingPanelId && editingTitle.trim()) {
|
||||
try {
|
||||
// Update the panel title via IPC
|
||||
await window.electron?.invoke('panels:update', editingPanelId, {
|
||||
title: editingTitle.trim()
|
||||
});
|
||||
|
||||
// Update the local panel in the store
|
||||
const panel = panels.find(p => p.id === editingPanelId);
|
||||
if (panel) {
|
||||
panel.title = editingTitle.trim();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to rename panel:', error);
|
||||
}
|
||||
}
|
||||
setEditingPanelId(null);
|
||||
setEditingTitle('');
|
||||
}, [editingPanelId, editingTitle, panels]);
|
||||
|
||||
const handleRenameCancel = useCallback(() => {
|
||||
setEditingPanelId(null);
|
||||
setEditingTitle('');
|
||||
}, []);
|
||||
|
||||
const handleRenameKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleRenameSubmit();
|
||||
} else if (e.key === 'Escape') {
|
||||
handleRenameCancel();
|
||||
}
|
||||
}, [handleRenameSubmit, handleRenameCancel]);
|
||||
|
||||
// Close dropdown when clicking outside
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (dropdownRef.current && event.target && event.target instanceof Node && !dropdownRef.current.contains(event.target)) {
|
||||
setShowDropdown(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (showDropdown) {
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}
|
||||
}, [showDropdown]);
|
||||
|
||||
// Focus input when editing starts
|
||||
useEffect(() => {
|
||||
if (editingPanelId && editInputRef.current) {
|
||||
editInputRef.current.focus();
|
||||
editInputRef.current.select();
|
||||
}
|
||||
}, [editingPanelId]);
|
||||
|
||||
// Get available panel types (excluding permanent panels, logs, and enforcing singleton)
|
||||
const availablePanelTypes = (Object.keys(PANEL_CAPABILITIES) as ToolPanelType[])
|
||||
.filter(type => {
|
||||
const capabilities = PANEL_CAPABILITIES[type];
|
||||
|
||||
// Filter based on context
|
||||
if (context === 'project' && !capabilities.canAppearInProjects) return false;
|
||||
if (context === 'worktree' && !capabilities.canAppearInWorktrees) return false;
|
||||
|
||||
// Exclude permanent panels
|
||||
if (capabilities.permanent) return false;
|
||||
|
||||
// Exclude logs panel - it's only created automatically when running scripts
|
||||
if (type === 'logs') return false;
|
||||
|
||||
// Enforce singleton panels
|
||||
if (capabilities.singleton) {
|
||||
// Check if a panel of this type already exists
|
||||
return !panels.some(p => p.type === type);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
const getPanelIcon = (type: ToolPanelType) => {
|
||||
switch (type) {
|
||||
case 'terminal':
|
||||
return <Terminal className="w-4 h-4" />;
|
||||
case 'claude':
|
||||
return <MessageSquare className="w-4 h-4" />;
|
||||
case 'codex':
|
||||
return <Code2 className="w-4 h-4" />;
|
||||
case 'diff':
|
||||
return <GitBranch className="w-4 h-4" />;
|
||||
case 'editor':
|
||||
return <FileText className="w-4 h-4" />;
|
||||
case 'logs':
|
||||
return <FileCode className="w-4 h-4" />;
|
||||
case 'dashboard':
|
||||
return <BarChart3 className="w-4 h-4" />;
|
||||
// Add more icons as panel types are added
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
// Get panel status indicator config for AI panels (claude/codex)
|
||||
const getPanelStatusConfig = (panel: ToolPanel): { status: 'running' | 'waiting' | 'info' | 'error' | 'default'; animated: boolean; pulse: boolean } | null => {
|
||||
// Only show status for AI panels
|
||||
if (panel.type !== 'claude' && panel.type !== 'codex') {
|
||||
return null;
|
||||
}
|
||||
|
||||
const customState = panel.state?.customState as BaseAIPanelState | undefined;
|
||||
const panelStatus: PanelStatus | undefined = customState?.panelStatus;
|
||||
const hasUnviewedContent = customState?.hasUnviewedContent ?? false;
|
||||
const isActivePanel = activePanel?.id === panel.id;
|
||||
|
||||
// Don't show status indicator if panel is active and doesn't have unviewed content
|
||||
// (user is actively viewing it)
|
||||
if (isActivePanel && !hasUnviewedContent && panelStatus !== 'running' && panelStatus !== 'waiting') {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (panelStatus) {
|
||||
case 'running':
|
||||
return { status: 'running', animated: true, pulse: false };
|
||||
case 'waiting':
|
||||
return { status: 'waiting', animated: false, pulse: true };
|
||||
case 'error':
|
||||
return { status: 'error', animated: false, pulse: false };
|
||||
case 'completed_unviewed':
|
||||
// Show blue dot for completed with unviewed content
|
||||
return { status: 'info', animated: false, pulse: true };
|
||||
case 'stopped':
|
||||
case 'idle':
|
||||
default:
|
||||
// Only show if there's unviewed content and panel is not active
|
||||
if (hasUnviewedContent && !isActivePanel) {
|
||||
return { status: 'info', animated: false, pulse: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="panel-tab-bar bg-surface-secondary border-b border-border-primary dark:border-border-hover">
|
||||
{/* Flex container that wraps when needed */}
|
||||
<div
|
||||
className="flex flex-wrap items-center min-h-[2rem] px-2 gap-x-1"
|
||||
role="tablist"
|
||||
aria-label="Panel Tabs"
|
||||
>
|
||||
{/* Render panel tabs */}
|
||||
{panels.map((panel) => {
|
||||
const isPermanent = panel.metadata?.permanent === true;
|
||||
const isEditing = editingPanelId === panel.id;
|
||||
const isDiffPanel = panel.type === 'diff';
|
||||
const displayTitle = isDiffPanel ? 'Diff' : panel.title;
|
||||
const statusConfig = getPanelStatusConfig(panel);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={panel.id}
|
||||
className={cn(
|
||||
"group relative inline-flex items-center h-8 px-3 text-sm whitespace-nowrap cursor-pointer select-none",
|
||||
"rounded-t-md border border-border-primary dark:border-border-hover border-b-0 -mb-px",
|
||||
activePanel?.id === panel.id
|
||||
? "bg-surface-primary text-text-primary shadow-tactile"
|
||||
: "bg-surface-secondary text-text-secondary hover:bg-surface-hover hover:text-text-primary"
|
||||
)}
|
||||
onClick={() => !isEditing && handlePanelClick(panel)}
|
||||
title={isPermanent ? "This panel cannot be closed" : undefined}
|
||||
role="tab"
|
||||
aria-selected={activePanel?.id === panel.id}
|
||||
tabIndex={activePanel?.id === panel.id ? 0 : -1}
|
||||
onKeyDown={(e) => {
|
||||
if (isEditing) return;
|
||||
if (e.key === 'Enter' || e.key === ' ') {
|
||||
e.preventDefault();
|
||||
handlePanelClick(panel);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{/* Status indicator for AI panels */}
|
||||
{statusConfig && (
|
||||
<StatusDot
|
||||
status={statusConfig.status}
|
||||
size="sm"
|
||||
animated={statusConfig.animated}
|
||||
pulse={statusConfig.pulse}
|
||||
className="mr-1"
|
||||
/>
|
||||
)}
|
||||
{getPanelIcon(panel.type)}
|
||||
|
||||
{isEditing ? (
|
||||
<input
|
||||
ref={editInputRef}
|
||||
type="text"
|
||||
value={editingTitle}
|
||||
onChange={(e) => setEditingTitle(e.target.value)}
|
||||
onKeyDown={handleRenameKeyDown}
|
||||
onBlur={handleRenameSubmit}
|
||||
className="ml-2 px-1 text-sm bg-bg-primary border border-border-primary dark:border-border-hover rounded outline-none focus:border-border-focus focus:ring-1 focus:ring-border-focus text-text-primary"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{ width: `${Math.max(50, editingTitle.length * 8)}px` }}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<span className="ml-2 text-sm">{displayTitle}</span>
|
||||
{!isPermanent && !isDiffPanel && (
|
||||
<button
|
||||
className="ml-1 p-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity transition-colors text-text-muted hover:bg-surface-hover hover:text-text-primary focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring-subtle"
|
||||
onClick={(e) => handleStartRename(e, panel)}
|
||||
title="Rename panel"
|
||||
>
|
||||
<Edit2 className="w-3 h-3" />
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{!isPermanent && !isEditing && (
|
||||
<button
|
||||
className="ml-1 p-0.5 rounded transition-colors text-text-muted hover:bg-surface-hover hover:text-status-error focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring-subtle"
|
||||
onClick={(e) => handlePanelClose(e, panel)}
|
||||
>
|
||||
<X className="w-3 h-3" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* Add Panel dropdown button */}
|
||||
<div className="relative h-8 flex items-center ml-1" ref={dropdownRef}>
|
||||
<button
|
||||
className="inline-flex items-center h-8 px-3 text-sm rounded-t-md border border-border-primary dark:border-border-hover border-b-0 -mb-px bg-surface-secondary text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring-subtle"
|
||||
onClick={() => setShowDropdown(!showDropdown)}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={showDropdown}
|
||||
>
|
||||
<Plus className="w-4 h-4 mr-1" />
|
||||
Add Tool
|
||||
<ChevronDown className="w-3 h-3 ml-1" />
|
||||
</button>
|
||||
|
||||
{showDropdown && (
|
||||
<div className="absolute top-full left-0 mt-1 bg-surface-primary border border-border-primary dark:border-border-hover rounded shadow-dropdown z-10 animate-dropdown-enter">
|
||||
{availablePanelTypes.map((type) => (
|
||||
<button
|
||||
key={type}
|
||||
className="flex items-center w-full px-4 py-2 text-sm text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary text-left"
|
||||
onClick={() => handleAddPanel(type)}
|
||||
>
|
||||
{getPanelIcon(type)}
|
||||
<span className="ml-2 capitalize">{type}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Branch Actions button - moved from ViewTabs - only in worktree context */}
|
||||
{context === 'worktree' && gitBranchActions && gitBranchActions.length > 0 && (
|
||||
<div className="ml-auto flex items-center gap-2 pr-2 h-8">
|
||||
<Dropdown
|
||||
trigger={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="flex items-center gap-2 px-3 py-1 h-7"
|
||||
disabled={isMerging}
|
||||
>
|
||||
<GitBranch className="w-4 h-4" />
|
||||
<span className="text-sm">Git Branch Actions</span>
|
||||
<MoreVertical className="w-3 h-3" />
|
||||
</Button>
|
||||
}
|
||||
items={gitBranchActions}
|
||||
position="bottom-right"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
PanelTabBar.displayName = 'PanelTabBar';
|
||||
@ -1,466 +0,0 @@
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { CheckCircle2, Circle, ChevronRight, GitBranch, FileCode } from 'lucide-react';
|
||||
import { useSession } from '../../contexts/SessionContext';
|
||||
import { panelApi } from '../../services/panelApi';
|
||||
import { API } from '../../utils/api';
|
||||
import type { SetupTasksPanelState } from '../../../../shared/types/panels';
|
||||
import { CreateSessionDialog } from '../CreateSessionDialog';
|
||||
|
||||
interface SetupTask {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
icon: React.ReactNode;
|
||||
check: () => Promise<boolean>;
|
||||
action?: () => void;
|
||||
actionLabel?: string;
|
||||
}
|
||||
|
||||
interface SetupTasksPanelProps {
|
||||
panelId: string;
|
||||
sessionId: string;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
const SetupTasksPanel: React.FC<SetupTasksPanelProps> = ({ panelId, isActive }) => {
|
||||
const sessionContext = useSession();
|
||||
const [tasksStatus, setTasksStatus] = useState<Record<string, boolean>>({});
|
||||
const [isChecking, setIsChecking] = useState(false);
|
||||
const [expandedTask, setExpandedTask] = useState<string | null>(null);
|
||||
const [showSessionDialog, setShowSessionDialog] = useState(false);
|
||||
|
||||
// Get project info from session context
|
||||
const projectId = sessionContext?.projectId;
|
||||
|
||||
// Check if .gitignore contains worktrees directory
|
||||
const checkGitignore = useCallback(async (): Promise<boolean> => {
|
||||
if (!projectId) return false;
|
||||
|
||||
try {
|
||||
// Use the file API to read .gitignore from the project
|
||||
const response = await window.electronAPI.file.readProject(parseInt(projectId), '.gitignore');
|
||||
if (!response.success || !response.data) return false;
|
||||
|
||||
const content = response.data as string;
|
||||
// Check for common worktree patterns
|
||||
return content.includes('/worktrees/') ||
|
||||
content.includes('/worktree-*/') ||
|
||||
content.includes('worktrees/') ||
|
||||
content.includes('worktree-*/');
|
||||
} catch (error) {
|
||||
// If .gitignore doesn't exist, that's ok - it's not found
|
||||
return false;
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Check if project has run scripts configured
|
||||
const checkRunScript = useCallback(async (): Promise<boolean> => {
|
||||
if (!projectId) return false;
|
||||
|
||||
try {
|
||||
// Get project details to check run script
|
||||
const response = await API.projects.getAll();
|
||||
if (!response.success || !response.data) return false;
|
||||
|
||||
const projects = response.data as Array<{ id: number; run_script?: string }>;
|
||||
const project = projects.find(p => p.id === parseInt(projectId));
|
||||
return !!(project?.run_script && project.run_script.trim());
|
||||
} catch (error) {
|
||||
console.error('Error checking run script:', error);
|
||||
return false;
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Open project settings
|
||||
const openProjectSettings = useCallback(async () => {
|
||||
if (!projectId) return;
|
||||
|
||||
try {
|
||||
// First, update the project's run script to "./crystal-run.sh"
|
||||
const updateResponse = await API.projects.update(projectId, {
|
||||
run_script: './crystal-run.sh'
|
||||
});
|
||||
|
||||
if (!updateResponse.success) {
|
||||
console.error('Failed to update project run script:', updateResponse.error);
|
||||
alert(`Failed to update run script: ${updateResponse.error}`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[SetupTasksPanel] Successfully set run script to ./crystal-run.sh');
|
||||
|
||||
// Now open the session dialog with the specific prompt
|
||||
setShowSessionDialog(true);
|
||||
} catch (error) {
|
||||
console.error('Error updating project settings:', error);
|
||||
alert(`Error updating project settings: ${error}`);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Add worktrees to .gitignore
|
||||
const addToGitignore = useCallback(async () => {
|
||||
if (!projectId) return;
|
||||
|
||||
console.log('[SetupTasksPanel] Starting addToGitignore for project:', projectId);
|
||||
|
||||
// Show confirmation dialog
|
||||
const confirmed = window.confirm(
|
||||
'Crystal will add worktree patterns to .gitignore and create a new commit.\n\n' +
|
||||
'This will:\n' +
|
||||
'• Add /worktrees/ and /worktree-*/ patterns to .gitignore\n' +
|
||||
'• Create a commit with only these changes\n' +
|
||||
'• Leave any other uncommitted changes untouched\n\n' +
|
||||
'Proceed?'
|
||||
);
|
||||
|
||||
if (!confirmed) {
|
||||
console.log('[SetupTasksPanel] User cancelled .gitignore update');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Read current .gitignore or create empty if doesn't exist
|
||||
console.log('[SetupTasksPanel] Reading .gitignore...');
|
||||
const readResponse = await window.electronAPI.file.readProject(parseInt(projectId), '.gitignore');
|
||||
console.log('[SetupTasksPanel] Read response:', readResponse);
|
||||
|
||||
let content = '';
|
||||
|
||||
if (readResponse.success && readResponse.data) {
|
||||
content = readResponse.data as string;
|
||||
console.log('[SetupTasksPanel] Current .gitignore length:', content.length);
|
||||
} else if (readResponse.success && readResponse.data === null) {
|
||||
console.log('[SetupTasksPanel] .gitignore does not exist, will create it');
|
||||
} else {
|
||||
console.error('[SetupTasksPanel] Failed to read .gitignore:', readResponse.error);
|
||||
alert(`Failed to read .gitignore: ${readResponse.error}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add worktree patterns if not already present
|
||||
const patterns = [
|
||||
'\n# Git worktrees (Crystal)',
|
||||
'/worktrees/',
|
||||
'/worktree-*/'
|
||||
];
|
||||
|
||||
let needsUpdate = false;
|
||||
const linesToAdd: string[] = [];
|
||||
|
||||
for (const pattern of patterns) {
|
||||
if (!content.includes(pattern.replace('\n# ', '')) && !content.includes(pattern)) {
|
||||
linesToAdd.push(pattern);
|
||||
needsUpdate = true;
|
||||
console.log('[SetupTasksPanel] Will add pattern:', pattern);
|
||||
}
|
||||
}
|
||||
|
||||
if (needsUpdate) {
|
||||
console.log('[SetupTasksPanel] Updating .gitignore with patterns:', linesToAdd);
|
||||
|
||||
// Ensure file ends with newline
|
||||
if (content && !content.endsWith('\n')) {
|
||||
content += '\n';
|
||||
}
|
||||
|
||||
// Add the patterns
|
||||
content += linesToAdd.join('\n') + '\n';
|
||||
|
||||
console.log('[SetupTasksPanel] Writing updated content to .gitignore...');
|
||||
// Write back to file
|
||||
const writeResponse = await window.electronAPI.file.writeProject(parseInt(projectId), '.gitignore', content);
|
||||
console.log('[SetupTasksPanel] Write response:', writeResponse);
|
||||
|
||||
if (!writeResponse.success) {
|
||||
console.error('[SetupTasksPanel] Failed to write .gitignore:', writeResponse.error);
|
||||
alert(`Failed to update .gitignore: ${writeResponse.error}`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[SetupTasksPanel] Successfully updated .gitignore');
|
||||
|
||||
// Now create a git commit with just the .gitignore file
|
||||
console.log('[SetupTasksPanel] Creating git commit...');
|
||||
|
||||
// Stage the .gitignore file
|
||||
const gitAddResponse = await window.electronAPI.git.executeProject(
|
||||
parseInt(projectId),
|
||||
['add', '.gitignore']
|
||||
);
|
||||
|
||||
if (!gitAddResponse.success) {
|
||||
console.error('[SetupTasksPanel] Failed to stage .gitignore:', gitAddResponse.error);
|
||||
alert(`Failed to stage .gitignore: ${gitAddResponse.error}`);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[SetupTasksPanel] Staged .gitignore file');
|
||||
|
||||
// Create the commit
|
||||
const commitMessage = 'Add Crystal worktree patterns to .gitignore\n\n' +
|
||||
'Added patterns to ignore Crystal worktree directories:\n' +
|
||||
'- /worktrees/\n' +
|
||||
'- /worktree-*/\n\n' +
|
||||
'This prevents git from tracking temporary Crystal session directories.';
|
||||
|
||||
const gitCommitResponse = await window.electronAPI.git.executeProject(
|
||||
parseInt(projectId),
|
||||
['commit', '-m', commitMessage]
|
||||
);
|
||||
|
||||
if (!gitCommitResponse.success) {
|
||||
// Check if it's because there's nothing to commit (file unchanged)
|
||||
if (gitCommitResponse.error?.includes('nothing to commit') || gitCommitResponse.error?.includes('no changes added')) {
|
||||
console.log('[SetupTasksPanel] No changes to commit (file was already up to date)');
|
||||
alert('The .gitignore file was already up to date. No commit needed.');
|
||||
} else {
|
||||
console.error('[SetupTasksPanel] Failed to commit:', gitCommitResponse.error);
|
||||
alert(`Failed to create commit: ${gitCommitResponse.error}`);
|
||||
}
|
||||
// Still refresh the task status
|
||||
setTimeout(() => checkAllTasks(), 100);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[SetupTasksPanel] Successfully created commit');
|
||||
alert('Successfully added worktree patterns to .gitignore and created a commit!');
|
||||
|
||||
// Refresh the task status
|
||||
setTimeout(() => checkAllTasks(), 100);
|
||||
} else {
|
||||
console.log('[SetupTasksPanel] No update needed, patterns already exist');
|
||||
alert('Worktree patterns are already in .gitignore. No changes needed.');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[SetupTasksPanel] Error updating .gitignore:', error);
|
||||
alert(`Error updating .gitignore: ${error}`);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
// Check all tasks
|
||||
const checkAllTasks = useCallback(async () => {
|
||||
if (!isActive || !projectId) return;
|
||||
|
||||
setIsChecking(true);
|
||||
const newStatus: Record<string, boolean> = {};
|
||||
|
||||
// Check gitignore
|
||||
try {
|
||||
newStatus['gitignore'] = await checkGitignore();
|
||||
} catch (error) {
|
||||
console.error('Error checking gitignore:', error);
|
||||
newStatus['gitignore'] = false;
|
||||
}
|
||||
|
||||
// Check run script
|
||||
try {
|
||||
newStatus['runscript'] = await checkRunScript();
|
||||
} catch (error) {
|
||||
console.error('Error checking run script:', error);
|
||||
newStatus['runscript'] = false;
|
||||
}
|
||||
|
||||
setTasksStatus(newStatus);
|
||||
setIsChecking(false);
|
||||
|
||||
// Update panel state
|
||||
const panelState: SetupTasksPanelState = {
|
||||
lastCheck: new Date().toISOString(),
|
||||
tasksCompleted: newStatus
|
||||
};
|
||||
|
||||
await panelApi.updatePanel(panelId, {
|
||||
state: {
|
||||
isActive: true,
|
||||
customState: panelState
|
||||
}
|
||||
});
|
||||
}, [isActive, projectId, panelId, checkGitignore, checkRunScript]);
|
||||
|
||||
// Update addToGitignore to use checkAllTasks after it's defined
|
||||
const addToGitignoreWithRefresh = useCallback(async () => {
|
||||
await addToGitignore();
|
||||
await checkAllTasks();
|
||||
}, [addToGitignore, checkAllTasks]);
|
||||
|
||||
// Define setup tasks
|
||||
const setupTasks: SetupTask[] = [
|
||||
{
|
||||
id: 'gitignore',
|
||||
title: 'Add worktrees to .gitignore',
|
||||
description: 'Prevents git from tracking temporary worktree directories created by Crystal sessions. This keeps your repository clean and avoids committing session-specific files.',
|
||||
icon: <GitBranch className="w-5 h-5" />,
|
||||
check: checkGitignore,
|
||||
action: addToGitignoreWithRefresh,
|
||||
actionLabel: 'Add to .gitignore'
|
||||
},
|
||||
{
|
||||
id: 'runscript',
|
||||
title: 'Configure run script',
|
||||
description: 'Set up a command to run your project (e.g., npm run dev, python app.py). This allows you to quickly test changes made by Claude Code sessions.',
|
||||
icon: <FileCode className="w-5 h-5" />,
|
||||
check: checkRunScript,
|
||||
action: openProjectSettings,
|
||||
actionLabel: 'Create Run Script'
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
// Check tasks when panel becomes active
|
||||
useEffect(() => {
|
||||
if (isActive) {
|
||||
checkAllTasks();
|
||||
}
|
||||
}, [isActive, checkAllTasks]);
|
||||
|
||||
// Listen for file changes
|
||||
useEffect(() => {
|
||||
// File change listener could be implemented here if needed
|
||||
// For now, we'll rely on manual refresh
|
||||
}, [isActive, checkAllTasks]);
|
||||
|
||||
const allTasksComplete = Object.values(tasksStatus).every(status => status);
|
||||
const completedCount = Object.values(tasksStatus).filter(status => status).length;
|
||||
|
||||
if (!projectId) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full bg-bg-primary">
|
||||
<div className="text-text-secondary">No project selected</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full bg-bg-primary text-text-primary overflow-auto">
|
||||
<div className="p-6">
|
||||
<div className="mb-6">
|
||||
<h2 className="text-2xl font-bold text-text-primary mb-2">Setup Tasks</h2>
|
||||
<p className="text-text-secondary">Complete these tasks to get the best experience with Crystal</p>
|
||||
</div>
|
||||
|
||||
{/* Progress indicator */}
|
||||
<div className="mb-6 p-4 bg-surface-secondary border border-border-secondary rounded-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-sm text-text-secondary">Progress</span>
|
||||
<span className="text-sm text-text-secondary">{completedCount} of {setupTasks.length} completed</span>
|
||||
</div>
|
||||
<div className="w-full bg-border-secondary rounded-full h-2 overflow-hidden">
|
||||
<div
|
||||
className="bg-status-success h-full transition-all duration-300"
|
||||
style={{ width: `${(completedCount / setupTasks.length) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
{allTasksComplete && (
|
||||
<div className="mt-2 text-sm text-status-success flex items-center gap-1">
|
||||
<CheckCircle2 className="w-4 h-4" />
|
||||
All setup tasks complete!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Task list */}
|
||||
<div className="space-y-3">
|
||||
{setupTasks.map(task => {
|
||||
const isComplete = tasksStatus[task.id] || false;
|
||||
const isExpanded = expandedTask === task.id;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={task.id}
|
||||
className={`
|
||||
border rounded-lg transition-all
|
||||
${isComplete
|
||||
? 'border-status-success bg-surface-secondary'
|
||||
: 'border-border-secondary bg-surface-primary'
|
||||
}
|
||||
`}
|
||||
>
|
||||
<button
|
||||
onClick={() => setExpandedTask(isExpanded ? null : task.id)}
|
||||
className="w-full px-4 py-3 flex items-center gap-3 hover:bg-surface-hover transition-colors rounded-t-lg"
|
||||
>
|
||||
{/* Status icon */}
|
||||
<div className={`${isComplete ? 'text-status-success' : 'text-text-tertiary'}`}>
|
||||
{isChecking ? (
|
||||
<div className="w-5 h-5 border-2 border-current border-t-transparent rounded-full animate-spin" />
|
||||
) : isComplete ? (
|
||||
<CheckCircle2 className="w-5 h-5" />
|
||||
) : (
|
||||
<Circle className="w-5 h-5" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Task icon */}
|
||||
<div className={`${isComplete ? 'text-status-success' : 'text-text-secondary'}`}>
|
||||
{task.icon}
|
||||
</div>
|
||||
|
||||
{/* Task title */}
|
||||
<span className={`
|
||||
flex-1 text-left font-medium
|
||||
${isComplete ? 'text-status-success' : 'text-text-primary'}
|
||||
`}>
|
||||
{task.title}
|
||||
</span>
|
||||
|
||||
{/* Expand icon */}
|
||||
<ChevronRight
|
||||
className={`
|
||||
w-4 h-4 text-text-tertiary transition-transform
|
||||
${isExpanded ? 'rotate-90' : ''}
|
||||
`}
|
||||
/>
|
||||
</button>
|
||||
|
||||
{/* Expanded content */}
|
||||
{isExpanded && (
|
||||
<div className="px-4 pb-4 border-t border-border-secondary">
|
||||
<p className="mt-3 text-sm text-text-secondary">
|
||||
{task.description}
|
||||
</p>
|
||||
|
||||
{!isComplete && task.action && (
|
||||
<button
|
||||
onClick={task.action}
|
||||
className="mt-3 px-4 py-2 bg-interactive hover:bg-interactive-hover text-text-on-interactive text-sm font-medium rounded transition-colors"
|
||||
>
|
||||
{task.actionLabel}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Refresh button */}
|
||||
<div className="mt-6 flex justify-center">
|
||||
<button
|
||||
onClick={checkAllTasks}
|
||||
disabled={isChecking}
|
||||
className="px-4 py-2 text-sm font-medium rounded transition-colors bg-surface-secondary hover:bg-surface-hover text-text-primary disabled:bg-surface-secondary disabled:opacity-50"
|
||||
>
|
||||
{isChecking ? 'Checking...' : 'Refresh Status'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Create Session Dialog for run script */}
|
||||
<CreateSessionDialog
|
||||
isOpen={showSessionDialog}
|
||||
onClose={() => {
|
||||
setShowSessionDialog(false);
|
||||
// Refresh task status after dialog closes
|
||||
setTimeout(() => checkAllTasks(), 500);
|
||||
}}
|
||||
projectId={parseInt(projectId)}
|
||||
projectName={sessionContext?.projectName}
|
||||
initialPrompt="Create a new file crystal-run.sh that launches this project. Before launching, the script should safely kill any other running instances of the project."
|
||||
initialSessionName="build-run-script"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SetupTasksPanel;
|
||||
@ -1,281 +0,0 @@
|
||||
import React, { useRef, useEffect, useState } from 'react';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { useSession } from '../../contexts/SessionContext';
|
||||
import { useTheme } from '../../contexts/ThemeContext';
|
||||
import { TerminalPanelProps } from '../../types/panelComponents';
|
||||
import { renderLog, devLog } from '../../utils/console';
|
||||
import { getTerminalTheme } from '../../utils/terminalTheme';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
|
||||
// Type for terminal state restoration
|
||||
interface TerminalRestoreState {
|
||||
scrollbackBuffer: string | string[];
|
||||
cursorX?: number;
|
||||
cursorY?: number;
|
||||
}
|
||||
|
||||
export const TerminalPanel: React.FC<TerminalPanelProps> = React.memo(({ panel, isActive }) => {
|
||||
renderLog('[TerminalPanel] Component rendering, panel:', panel.id, 'isActive:', isActive);
|
||||
|
||||
// All hooks must be called at the top level, before any conditional returns
|
||||
const terminalRef = useRef<HTMLDivElement>(null);
|
||||
const xtermRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
const [initError, setInitError] = useState<string | null>(null);
|
||||
|
||||
// Get session data from context using the safe hook
|
||||
const sessionContext = useSession();
|
||||
const sessionId = sessionContext?.sessionId;
|
||||
const workingDirectory = sessionContext?.workingDirectory;
|
||||
const { theme } = useTheme();
|
||||
|
||||
if (sessionContext) {
|
||||
devLog.debug('[TerminalPanel] Session context:', sessionContext);
|
||||
} else {
|
||||
devLog.error('[TerminalPanel] No session context available');
|
||||
}
|
||||
|
||||
// Initialize terminal only once when component first mounts
|
||||
// Keep it alive even when switching sessions
|
||||
useEffect(() => {
|
||||
devLog.debug('[TerminalPanel] Initialization useEffect running, terminalRef:', terminalRef.current);
|
||||
|
||||
if (!terminalRef.current) {
|
||||
devLog.debug('[TerminalPanel] Missing terminal ref, skipping initialization');
|
||||
return;
|
||||
}
|
||||
|
||||
let terminal: Terminal | null = null;
|
||||
let fitAddon: FitAddon | null = null;
|
||||
let disposed = false;
|
||||
|
||||
const initializeTerminal = async () => {
|
||||
try {
|
||||
devLog.debug('[TerminalPanel] Starting initialization for panel:', panel.id);
|
||||
|
||||
// Check if already initialized on backend
|
||||
const initialized = await window.electronAPI.invoke('panels:checkInitialized', panel.id);
|
||||
console.log('[TerminalPanel] Panel already initialized?', initialized);
|
||||
|
||||
// Store terminal state for THIS panel only (not in global variable)
|
||||
let terminalStateForThisPanel: TerminalRestoreState | null = null;
|
||||
|
||||
if (!initialized) {
|
||||
// Initialize backend PTY process
|
||||
console.log('[TerminalPanel] Initializing backend PTY process...');
|
||||
// Use workingDirectory and sessionId if available, but don't require them
|
||||
await window.electronAPI.invoke('panels:initialize', panel.id, {
|
||||
cwd: workingDirectory || process.cwd(),
|
||||
sessionId: sessionId || panel.sessionId
|
||||
});
|
||||
console.log('[TerminalPanel] Backend PTY process initialized');
|
||||
} else {
|
||||
// Terminal is already initialized, get its state to restore scrollback
|
||||
console.log('[TerminalPanel] Restoring terminal state from backend...');
|
||||
const terminalState = await window.electronAPI.invoke('terminal:getState', panel.id);
|
||||
if (terminalState && terminalState.scrollbackBuffer) {
|
||||
// We'll restore this to the terminal after it's created
|
||||
console.log('[TerminalPanel] Found scrollback buffer with', terminalState.scrollbackBuffer.length, 'lines');
|
||||
// Store for restoration after terminal is created - LOCAL to this initialization
|
||||
terminalStateForThisPanel = terminalState;
|
||||
}
|
||||
}
|
||||
|
||||
// FIX: Check if component was unmounted during async operation
|
||||
if (disposed) return;
|
||||
|
||||
// Create XTerm instance
|
||||
console.log('[TerminalPanel] Creating XTerm instance...');
|
||||
terminal = new Terminal({
|
||||
fontSize: 14,
|
||||
fontFamily: 'Menlo, Monaco, "Courier New", monospace',
|
||||
theme: getTerminalTheme(),
|
||||
scrollback: 50000
|
||||
});
|
||||
console.log('[TerminalPanel] XTerm instance created:', !!terminal);
|
||||
|
||||
fitAddon = new FitAddon();
|
||||
terminal.loadAddon(fitAddon);
|
||||
console.log('[TerminalPanel] FitAddon loaded');
|
||||
|
||||
// FIX: Additional check before DOM manipulation
|
||||
if (terminalRef.current && !disposed) {
|
||||
console.log('[TerminalPanel] Opening terminal in DOM element:', terminalRef.current);
|
||||
terminal.open(terminalRef.current);
|
||||
console.log('[TerminalPanel] Terminal opened in DOM');
|
||||
fitAddon.fit();
|
||||
console.log('[TerminalPanel] FitAddon fitted');
|
||||
terminal.options.theme = getTerminalTheme();
|
||||
|
||||
xtermRef.current = terminal;
|
||||
fitAddonRef.current = fitAddon;
|
||||
|
||||
// Restore scrollback if we have saved state FOR THIS PANEL
|
||||
if (terminalStateForThisPanel && terminalStateForThisPanel.scrollbackBuffer) {
|
||||
// Handle both string and array formats
|
||||
let restoredContent: string;
|
||||
if (typeof terminalStateForThisPanel.scrollbackBuffer === 'string') {
|
||||
restoredContent = terminalStateForThisPanel.scrollbackBuffer;
|
||||
console.log('[TerminalPanel] Restoring', restoredContent.length, 'chars of scrollback');
|
||||
} else if (Array.isArray(terminalStateForThisPanel.scrollbackBuffer)) {
|
||||
restoredContent = terminalStateForThisPanel.scrollbackBuffer.join('\n');
|
||||
console.log('[TerminalPanel] Restoring', terminalStateForThisPanel.scrollbackBuffer.length, 'lines of scrollback');
|
||||
} else {
|
||||
restoredContent = '';
|
||||
}
|
||||
|
||||
if (restoredContent) {
|
||||
terminal.write(restoredContent);
|
||||
}
|
||||
}
|
||||
|
||||
setIsInitialized(true);
|
||||
console.log('[TerminalPanel] Terminal initialization complete, isInitialized set to true');
|
||||
|
||||
// Set up IPC communication for terminal I/O
|
||||
const outputHandler = (data: { panelId?: string; sessionId?: string; output?: string } | unknown) => {
|
||||
// Check if this is panel terminal output (has panelId) vs session terminal output (has sessionId)
|
||||
if (data && typeof data === 'object' && 'panelId' in data && data.panelId && 'output' in data) {
|
||||
const typedData = data as { panelId: string; output: string };
|
||||
console.log('[TerminalPanel] Received panel output for:', typedData.panelId, 'Current panel:', panel.id);
|
||||
if (typedData.panelId === panel.id && terminal && !disposed) {
|
||||
console.log('[TerminalPanel] Writing to terminal:', typedData.output.substring(0, 50) + '...');
|
||||
terminal.write(typedData.output);
|
||||
}
|
||||
}
|
||||
// Ignore session terminal output (has sessionId instead of panelId)
|
||||
};
|
||||
|
||||
const unsubscribeOutput = window.electronAPI.events.onTerminalOutput(outputHandler);
|
||||
console.log('[TerminalPanel] Subscribed to terminal output events for panel:', panel.id);
|
||||
|
||||
// Handle terminal input
|
||||
const inputDisposable = terminal.onData((data) => {
|
||||
window.electronAPI.invoke('terminal:input', panel.id, data);
|
||||
});
|
||||
|
||||
// Handle resize
|
||||
const resizeObserver = new ResizeObserver(() => {
|
||||
if (fitAddon && !disposed) {
|
||||
fitAddon.fit();
|
||||
const dimensions = fitAddon.proposeDimensions();
|
||||
if (dimensions) {
|
||||
window.electronAPI.invoke('terminal:resize', panel.id, dimensions.cols, dimensions.rows);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
resizeObserver.observe(terminalRef.current);
|
||||
|
||||
// FIX: Return comprehensive cleanup function
|
||||
return () => {
|
||||
disposed = true;
|
||||
resizeObserver.disconnect();
|
||||
unsubscribeOutput(); // Use the unsubscribe function
|
||||
inputDisposable.dispose();
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize terminal:', error);
|
||||
setInitError(error instanceof Error ? error.message : 'Unknown error');
|
||||
}
|
||||
};
|
||||
|
||||
const cleanupPromise = initializeTerminal();
|
||||
|
||||
// Only dispose when component is actually unmounting (panel deleted)
|
||||
// Not when just switching tabs
|
||||
return () => {
|
||||
disposed = true;
|
||||
|
||||
// Clean up async initialization
|
||||
cleanupPromise.then(cleanupFn => cleanupFn?.());
|
||||
|
||||
// Dispose XTerm instance only on final unmount
|
||||
if (xtermRef.current) {
|
||||
try {
|
||||
console.log('[TerminalPanel] Disposing terminal for panel:', panel.id);
|
||||
xtermRef.current.dispose();
|
||||
} catch (e) {
|
||||
console.warn('Error disposing terminal:', e);
|
||||
}
|
||||
xtermRef.current = null;
|
||||
}
|
||||
|
||||
if (fitAddonRef.current) {
|
||||
try {
|
||||
fitAddonRef.current.dispose();
|
||||
} catch (e) {
|
||||
console.warn('Error disposing fit addon:', e);
|
||||
}
|
||||
fitAddonRef.current = null;
|
||||
}
|
||||
|
||||
setIsInitialized(false);
|
||||
};
|
||||
}, [panel.id]); // Only depend on panel.id to prevent re-initialization on session switch
|
||||
|
||||
// Handle visibility changes (resize when becoming visible)
|
||||
useEffect(() => {
|
||||
if (isActive && fitAddonRef.current && xtermRef.current) {
|
||||
console.log('[TerminalPanel] Panel became active, fitting terminal');
|
||||
// Small delay to ensure DOM is ready
|
||||
setTimeout(() => {
|
||||
if (fitAddonRef.current) {
|
||||
fitAddonRef.current.fit();
|
||||
const dimensions = fitAddonRef.current.proposeDimensions();
|
||||
if (dimensions) {
|
||||
window.electronAPI.invoke('terminal:resize', panel.id, dimensions.cols, dimensions.rows);
|
||||
}
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
}, [isActive, panel.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!xtermRef.current) {
|
||||
return;
|
||||
}
|
||||
const newTheme = getTerminalTheme();
|
||||
xtermRef.current.options.theme = newTheme;
|
||||
const rows = xtermRef.current.rows;
|
||||
if (rows > 0) {
|
||||
xtermRef.current.refresh(0, rows - 1);
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
// Handle missing session context (show after all hooks have been called)
|
||||
if (!sessionContext) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full text-red-500">
|
||||
Session context not available
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (initError) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full text-red-500">
|
||||
Terminal initialization failed: {initError}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Always render the terminal div to keep XTerm instance alive
|
||||
return (
|
||||
<div className="h-full w-full relative">
|
||||
<div ref={terminalRef} className="h-full w-full" />
|
||||
{!isInitialized && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-surface-primary bg-opacity-80">
|
||||
<div className="text-text-secondary">Initializing terminal...</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
TerminalPanel.displayName = 'TerminalPanel';
|
||||
|
||||
export default TerminalPanel;
|
||||
@ -1,268 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Settings } from 'lucide-react';
|
||||
import { ToolPanel } from '../../../../../shared/types/panels';
|
||||
import { Session } from '../../../types/session';
|
||||
|
||||
/**
|
||||
* Common view modes for AI agent panels
|
||||
*/
|
||||
export type AIViewMode = 'richOutput' | 'messages' | 'stats' | 'debugState';
|
||||
|
||||
/**
|
||||
* Common settings for rich output display
|
||||
*/
|
||||
export interface RichOutputSettings {
|
||||
showToolCalls: boolean;
|
||||
compactMode: boolean;
|
||||
collapseTools: boolean;
|
||||
showThinking: boolean;
|
||||
showSessionInit: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Props for AI agent panels
|
||||
*/
|
||||
export interface AIPanelProps {
|
||||
panel: ToolPanel;
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* State for AI agent panels
|
||||
*/
|
||||
export interface AIPanelState {
|
||||
viewMode: AIViewMode;
|
||||
showSettings: boolean;
|
||||
richOutputSettings: RichOutputSettings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base component for AI agent panels
|
||||
* This provides the common structure and functionality that all AI panels share
|
||||
*/
|
||||
export abstract class AbstractAIPanel<T extends AIPanelProps = AIPanelProps> extends React.Component<T, AIPanelState> {
|
||||
|
||||
constructor(props: T) {
|
||||
super(props);
|
||||
|
||||
// Initialize state with defaults
|
||||
this.state = {
|
||||
viewMode: 'richOutput',
|
||||
showSettings: false,
|
||||
richOutputSettings: this.loadRichOutputSettings()
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the agent name for display and storage keys
|
||||
*/
|
||||
protected abstract getAgentName(): string;
|
||||
|
||||
/**
|
||||
* Get the active session for this panel
|
||||
*/
|
||||
protected abstract getActiveSession(): Session | null;
|
||||
|
||||
/**
|
||||
* Render the rich output view component
|
||||
*/
|
||||
protected abstract renderRichOutputView(): React.ReactNode;
|
||||
|
||||
/**
|
||||
* Render the messages view component
|
||||
*/
|
||||
protected abstract renderMessagesView(): React.ReactNode;
|
||||
|
||||
/**
|
||||
* Render the stats view component
|
||||
*/
|
||||
protected abstract renderStatsView(): React.ReactNode;
|
||||
|
||||
/**
|
||||
* Render the input component
|
||||
*/
|
||||
protected abstract renderInputComponent(): React.ReactNode;
|
||||
|
||||
/**
|
||||
* Render the settings panel (optional override)
|
||||
*/
|
||||
protected abstract renderSettingsPanel(): React.ReactNode;
|
||||
|
||||
/**
|
||||
* Get additional header elements (optional override)
|
||||
*/
|
||||
protected renderHeaderExtras(): React.ReactNode {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load rich output settings from localStorage
|
||||
*/
|
||||
protected loadRichOutputSettings(): RichOutputSettings {
|
||||
const key = `${this.getAgentName().toLowerCase()}RichOutputSettings`;
|
||||
const saved = localStorage.getItem(key);
|
||||
return saved ? JSON.parse(saved) : {
|
||||
showToolCalls: true,
|
||||
compactMode: false,
|
||||
collapseTools: true, // Collapse tools by default
|
||||
showThinking: true,
|
||||
showSessionInit: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Save rich output settings to localStorage
|
||||
*/
|
||||
protected handleRichOutputSettingsChange = (newSettings: RichOutputSettings) => {
|
||||
const key = `${this.getAgentName().toLowerCase()}RichOutputSettings`;
|
||||
this.setState({ richOutputSettings: newSettings });
|
||||
localStorage.setItem(key, JSON.stringify(newSettings));
|
||||
};
|
||||
|
||||
/**
|
||||
* Handle view mode change
|
||||
*/
|
||||
protected setViewMode = (viewMode: AIViewMode) => {
|
||||
this.setState({ viewMode });
|
||||
};
|
||||
|
||||
/**
|
||||
* Toggle settings panel visibility
|
||||
*/
|
||||
protected toggleSettings = () => {
|
||||
this.setState(prev => ({ showSettings: !prev.showSettings }));
|
||||
};
|
||||
|
||||
/**
|
||||
* Get view mode button class names
|
||||
*/
|
||||
protected getViewModeButtonClass(mode: AIViewMode): string {
|
||||
return `px-3 py-1 text-xs font-medium rounded-md transition-all ${
|
||||
this.state.viewMode === mode
|
||||
? 'bg-bg-primary text-text-primary shadow-sm'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the view mode display name
|
||||
*/
|
||||
protected getViewModeDisplayName(mode: AIViewMode): string {
|
||||
switch (mode) {
|
||||
case 'richOutput':
|
||||
return 'Output';
|
||||
case 'messages':
|
||||
return 'Messages';
|
||||
case 'stats':
|
||||
return 'Stats';
|
||||
default:
|
||||
return mode;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main render method - provides the common structure
|
||||
*/
|
||||
public render(): React.ReactNode {
|
||||
const activeSession = this.getActiveSession();
|
||||
|
||||
if (!activeSession) {
|
||||
return (
|
||||
<div className="h-full w-full flex items-center justify-center p-8">
|
||||
<div className="text-center max-w-md">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
No Session Found
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
This {this.getAgentName()} panel is not associated with an active session.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full w-full flex flex-col overflow-hidden bg-bg-primary">
|
||||
{/* Panel Header with Segmented Control */}
|
||||
<div className="flex items-center justify-between px-4 py-2 border-b border-border-primary bg-surface-primary">
|
||||
{/* Segmented Control for View Mode */}
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">View</span>
|
||||
<div className="inline-flex rounded-lg bg-surface-secondary p-0.5">
|
||||
{(['richOutput', 'messages', 'stats'] as AIViewMode[]).map((mode) => (
|
||||
<button
|
||||
key={mode}
|
||||
onClick={() => this.setViewMode(mode)}
|
||||
className={this.getViewModeButtonClass(mode)}
|
||||
>
|
||||
{this.getViewModeDisplayName(mode)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Settings button and header extras */}
|
||||
<div className="flex items-center gap-2">
|
||||
{this.renderHeaderExtras()}
|
||||
|
||||
{this.state.viewMode === 'richOutput' && (
|
||||
<button
|
||||
onClick={() => this.toggleSettings()}
|
||||
className={`px-2 py-1 rounded-md text-xs transition-all flex items-center gap-1.5 ${
|
||||
this.state.showSettings
|
||||
? 'bg-surface-hover text-text-primary'
|
||||
: 'text-text-secondary hover:text-text-primary hover:bg-surface-hover'
|
||||
}`}
|
||||
title="Configure display settings"
|
||||
>
|
||||
<Settings className="w-3.5 h-3.5" />
|
||||
<span>Settings</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 relative min-h-0 overflow-hidden">
|
||||
{this.state.viewMode === 'richOutput' && (
|
||||
<div className="h-full block w-full">
|
||||
{this.renderRichOutputView()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{this.state.viewMode === 'messages' && (
|
||||
<div className="h-full flex flex-col overflow-hidden w-full">
|
||||
{this.renderMessagesView()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{this.state.viewMode === 'stats' && (
|
||||
<div className="h-full flex flex-col overflow-hidden w-full">
|
||||
{this.renderStatsView()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Input Component - Always visible at bottom if not archived */}
|
||||
{!activeSession.archived && this.renderInputComponent()}
|
||||
|
||||
{/* Show archived message if session is archived */}
|
||||
{activeSession.archived && (
|
||||
<div className="border-t-2 border-border-primary flex-shrink-0 bg-surface-secondary p-4">
|
||||
<div className="text-center text-text-secondary">
|
||||
<svg className="w-8 h-8 mx-auto mb-2 text-text-tertiary" 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>
|
||||
<p className="text-sm">
|
||||
This session has been archived. You can view the conversation history but cannot send new messages.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Settings Panel */}
|
||||
{this.state.viewMode === 'richOutput' && this.state.showSettings && this.renderSettingsPanel()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,457 +0,0 @@
|
||||
import React, { KeyboardEvent } from 'react';
|
||||
import { Send, Settings2, X, Paperclip, FileText, Square } from 'lucide-react';
|
||||
import type { Session } from '../../../types/session';
|
||||
|
||||
export interface AttachedImage {
|
||||
id: string;
|
||||
name: string;
|
||||
dataUrl: string;
|
||||
size: number;
|
||||
type: string;
|
||||
}
|
||||
|
||||
export interface AttachedText {
|
||||
id: string;
|
||||
name: string;
|
||||
content: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface InputOptions {
|
||||
model?: string;
|
||||
modelProvider?: string;
|
||||
approvalPolicy?: 'manual' | 'auto';
|
||||
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
webSearch?: boolean;
|
||||
ultrathink?: boolean;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface AbstractInputPanelProps {
|
||||
session: Session;
|
||||
panelId: string;
|
||||
onSendMessage: (message: string, options?: InputOptions, attachedImages?: AttachedImage[], attachedTexts?: AttachedText[]) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
initialModel?: string;
|
||||
placeholder?: string;
|
||||
statusIndicator?: React.ReactNode;
|
||||
contextBar?: React.ReactNode;
|
||||
optionsPanel?: React.ReactNode;
|
||||
actionButtons?: React.ReactNode;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export interface AbstractInputPanelState {
|
||||
input: string;
|
||||
isSubmitting: boolean;
|
||||
attachedImages: AttachedImage[];
|
||||
attachedTexts: AttachedText[];
|
||||
isDragging: boolean;
|
||||
showOptions: boolean;
|
||||
textareaHeight: number;
|
||||
}
|
||||
|
||||
export abstract class AbstractInputPanel<
|
||||
P extends AbstractInputPanelProps = AbstractInputPanelProps,
|
||||
S extends AbstractInputPanelState = AbstractInputPanelState
|
||||
> extends React.Component<P, S> {
|
||||
protected inputRef = React.createRef<HTMLTextAreaElement>();
|
||||
protected fileInputRef = React.createRef<HTMLInputElement>();
|
||||
|
||||
constructor(props: P) {
|
||||
super(props);
|
||||
this.state = {
|
||||
input: '',
|
||||
isSubmitting: false,
|
||||
attachedImages: [],
|
||||
attachedTexts: [],
|
||||
isDragging: false,
|
||||
showOptions: false,
|
||||
textareaHeight: 52,
|
||||
...this.getInitialState?.(),
|
||||
} as S;
|
||||
}
|
||||
|
||||
// Optional method for subclasses to add their own initial state
|
||||
protected getInitialState?(): Partial<S>;
|
||||
|
||||
// Abstract methods that subclasses must implement
|
||||
abstract getDefaultOptions(): InputOptions;
|
||||
abstract renderOptionsPanel(): React.ReactNode;
|
||||
abstract renderActionButtons(): React.ReactNode;
|
||||
abstract getPlaceholder(): string;
|
||||
|
||||
// Optional methods that subclasses can override
|
||||
protected renderContextBar(): React.ReactNode {
|
||||
return null;
|
||||
}
|
||||
|
||||
protected renderStatusIndicator(): React.ReactNode {
|
||||
const { session } = this.props;
|
||||
|
||||
if (session.status === 'running') {
|
||||
return (
|
||||
<div className="px-4 pb-2">
|
||||
<div className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
<span>Processing...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
protected generateId(prefix: string): string {
|
||||
return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
||||
}
|
||||
|
||||
protected async processImageFile(file: File): Promise<AttachedImage | null> {
|
||||
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: this.generateId('img'),
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
protected handlePaste = async (e: React.ClipboardEvent) => {
|
||||
const items = e.clipboardData?.items;
|
||||
if (!items) return;
|
||||
|
||||
// Check for text content first
|
||||
const textData = e.clipboardData.getData('text/plain');
|
||||
const LARGE_TEXT_THRESHOLD = 5000;
|
||||
|
||||
if (textData && textData.length > LARGE_TEXT_THRESHOLD) {
|
||||
// Large text pasted - convert to attachment
|
||||
e.preventDefault();
|
||||
|
||||
const textAttachment: AttachedText = {
|
||||
id: this.generateId('txt'),
|
||||
name: `Pasted Text (${textData.length.toLocaleString()} chars)`,
|
||||
content: textData,
|
||||
size: textData.length,
|
||||
};
|
||||
|
||||
this.setState(prevState => ({
|
||||
attachedTexts: [...prevState.attachedTexts, textAttachment]
|
||||
}));
|
||||
console.log(`[Input] Automatically attached ${textData.length} characters from paste`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check for images
|
||||
const imageItems: DataTransferItem[] = [];
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
if (items[i].type.startsWith('image/')) {
|
||||
imageItems.push(items[i]);
|
||||
}
|
||||
}
|
||||
|
||||
if (imageItems.length === 0) return;
|
||||
|
||||
e.preventDefault();
|
||||
|
||||
for (const item of imageItems) {
|
||||
const file = item.getAsFile();
|
||||
if (file) {
|
||||
const image = await this.processImageFile(file);
|
||||
if (image) {
|
||||
this.setState(prevState => ({
|
||||
attachedImages: [...prevState.attachedImages, image]
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
protected handleDrop = async (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
this.setState({ isDragging: false });
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
for (const file of files) {
|
||||
const image = await this.processImageFile(file);
|
||||
if (image) {
|
||||
this.setState(prevState => ({
|
||||
attachedImages: [...prevState.attachedImages, image]
|
||||
}));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
protected handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
this.setState({ isDragging: true });
|
||||
};
|
||||
|
||||
protected handleDragLeave = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
this.setState({ isDragging: false });
|
||||
};
|
||||
|
||||
protected removeImage = (id: string) => {
|
||||
this.setState(prevState => ({
|
||||
attachedImages: prevState.attachedImages.filter(img => img.id !== id)
|
||||
}));
|
||||
};
|
||||
|
||||
protected removeText = (id: string) => {
|
||||
this.setState(prevState => ({
|
||||
attachedTexts: prevState.attachedTexts.filter(txt => txt.id !== id)
|
||||
}));
|
||||
};
|
||||
|
||||
protected handleKeyDown = async (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
const { session, onCancel } = this.props;
|
||||
|
||||
// Handle cancel on Escape
|
||||
if (e.key === 'Escape' && session.status === 'running' && onCancel) {
|
||||
e.preventDefault();
|
||||
onCancel();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle submit on Enter with modifier
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
await this.handleSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
protected handleSubmit = async () => {
|
||||
const { onSendMessage, disabled } = this.props;
|
||||
const { input, isSubmitting, attachedImages, attachedTexts } = this.state;
|
||||
|
||||
if (!input.trim() || isSubmitting || disabled) return;
|
||||
|
||||
const message = input.trim();
|
||||
this.setState({ input: '', isSubmitting: true });
|
||||
|
||||
try {
|
||||
const options = this.getDefaultOptions();
|
||||
await onSendMessage(message, options, attachedImages, attachedTexts);
|
||||
// Clear attachments on successful send
|
||||
this.setState({ attachedImages: [], attachedTexts: [] });
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
// Restore input on error
|
||||
this.setState({ input: message });
|
||||
} finally {
|
||||
this.setState({ isSubmitting: false });
|
||||
// Refocus textarea
|
||||
this.inputRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
protected adjustTextareaHeight = () => {
|
||||
const textarea = this.inputRef.current;
|
||||
if (textarea) {
|
||||
textarea.style.height = 'auto';
|
||||
const newHeight = Math.min(textarea.scrollHeight, 200);
|
||||
this.setState({ textareaHeight: newHeight });
|
||||
}
|
||||
};
|
||||
|
||||
protected handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files || []);
|
||||
for (const file of files) {
|
||||
const image = await this.processImageFile(file);
|
||||
if (image) {
|
||||
this.setState(prevState => ({
|
||||
attachedImages: [...prevState.attachedImages, image]
|
||||
}));
|
||||
}
|
||||
}
|
||||
e.target.value = ''; // Reset input
|
||||
};
|
||||
|
||||
componentDidUpdate(_prevProps: P, prevState: S) {
|
||||
// Auto-resize textarea when input changes
|
||||
if (prevState.input !== this.state.input) {
|
||||
this.adjustTextareaHeight();
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const { session, onCancel } = this.props;
|
||||
const {
|
||||
input,
|
||||
isSubmitting,
|
||||
attachedImages,
|
||||
attachedTexts,
|
||||
isDragging,
|
||||
showOptions,
|
||||
textareaHeight
|
||||
} = this.state;
|
||||
|
||||
return (
|
||||
<div className="border-t border-border-primary bg-surface-primary">
|
||||
{/* Context Bar */}
|
||||
{this.renderContextBar()}
|
||||
|
||||
{/* Options Panel */}
|
||||
{showOptions && (
|
||||
<div className="px-4 py-3 border-b border-border-primary bg-surface-secondary">
|
||||
{this.renderOptionsPanel()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input Area */}
|
||||
<div
|
||||
className="flex flex-col gap-2 p-3"
|
||||
onDrop={this.handleDrop}
|
||||
onDragOver={this.handleDragOver}
|
||||
onDragLeave={this.handleDragLeave}
|
||||
>
|
||||
{/* Attached items */}
|
||||
{(attachedImages.length > 0 || attachedTexts.length > 0) && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{/* Attached text files */}
|
||||
{attachedTexts.map((text: AttachedText) => (
|
||||
<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
|
||||
onClick={() => this.removeText(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"
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Attached images */}
|
||||
{attachedImages.map((image: AttachedImage) => (
|
||||
<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
|
||||
onClick={() => this.removeImage(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"
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main input row */}
|
||||
<div className="flex items-end gap-2">
|
||||
{/* Options button */}
|
||||
<button
|
||||
onClick={() => this.setState({ showOptions: !showOptions })}
|
||||
className="p-2 text-text-secondary hover:text-text-primary hover:bg-surface-hover rounded-md transition-colors"
|
||||
title="Options"
|
||||
>
|
||||
<Settings2 className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{/* Attach button */}
|
||||
<button
|
||||
onClick={() => this.fileInputRef.current?.click()}
|
||||
className="p-2 text-text-secondary hover:text-text-primary hover:bg-surface-hover rounded-md transition-colors"
|
||||
title="Attach images"
|
||||
>
|
||||
<Paperclip className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{/* Textarea */}
|
||||
<div className="flex-1 relative">
|
||||
<textarea
|
||||
ref={this.inputRef}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
this.setState({ input: e.target.value });
|
||||
}}
|
||||
onKeyDown={this.handleKeyDown}
|
||||
onPaste={this.handlePaste}
|
||||
placeholder={isDragging ? "Drop images here..." : this.getPlaceholder()}
|
||||
disabled={isSubmitting || this.props.disabled}
|
||||
className="w-full px-3 py-2 bg-bg-primary border border-border-primary rounded-lg
|
||||
text-text-primary placeholder-text-tertiary resize-none
|
||||
focus:outline-none focus:ring-1 focus:ring-accent-primary focus:border-accent-primary
|
||||
disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{
|
||||
minHeight: '40px',
|
||||
maxHeight: '200px',
|
||||
height: `${textareaHeight}px`
|
||||
}}
|
||||
rows={1}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Action buttons - Cancel or Send */}
|
||||
{session.status === 'running' && onCancel ? (
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className="p-2 text-red-500 hover:text-red-400 hover:bg-red-500/10 rounded-md transition-colors"
|
||||
title="Cancel (Esc)"
|
||||
>
|
||||
<Square className="w-4 h-4" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={this.handleSubmit}
|
||||
disabled={!input.trim() || isSubmitting || this.props.disabled}
|
||||
className="p-2 text-accent-primary hover:text-accent-hover hover:bg-accent-primary/10
|
||||
rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
title="Send message (Enter)"
|
||||
>
|
||||
<Send className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Additional action buttons */}
|
||||
{this.renderActionButtons()}
|
||||
|
||||
{/* Hidden file input */}
|
||||
<input
|
||||
ref={this.fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={this.handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Status Indicator */}
|
||||
{this.renderStatusIndicator()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1,492 +0,0 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { API } from '../../../utils/api';
|
||||
import { cn } from '../../../utils/cn';
|
||||
import { ChevronRight, ChevronDown, Copy, Check, Terminal, FileText } from 'lucide-react';
|
||||
import { SessionOutput } from '../../../types/session';
|
||||
|
||||
interface MessagesViewProps {
|
||||
panelId: string;
|
||||
agentType: 'claude' | 'codex' | 'generic-cli';
|
||||
outputEventName: string;
|
||||
getMessagesHandler?: string; // For IPC-based panels like Codex
|
||||
}
|
||||
|
||||
interface JSONMessage {
|
||||
type: 'json';
|
||||
data: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
interface SessionInfo {
|
||||
type: 'session_info';
|
||||
initial_prompt?: string;
|
||||
claude_command?: string;
|
||||
codex_command?: string;
|
||||
worktree_path?: string;
|
||||
model?: string;
|
||||
permission_mode?: string;
|
||||
approval_policy?: string;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export const MessagesView: React.FC<MessagesViewProps> = ({
|
||||
panelId,
|
||||
agentType,
|
||||
outputEventName,
|
||||
getMessagesHandler
|
||||
}) => {
|
||||
const [messages, setMessages] = useState<JSONMessage[]>([]);
|
||||
const [sessionInfo, setSessionInfo] = useState<SessionInfo | null>(null);
|
||||
const [expandedMessages, setExpandedMessages] = useState<Set<number>>(new Set());
|
||||
const [copiedIndex, setCopiedIndex] = useState<number | null>(null);
|
||||
const [showSessionInfo, setShowSessionInfo] = useState(true);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const autoScrollRef = useRef(true);
|
||||
|
||||
// Load messages for the session
|
||||
useEffect(() => {
|
||||
const loadMessages = async () => {
|
||||
try {
|
||||
let response: { success: boolean; data?: JSONMessage[] };
|
||||
|
||||
// Use appropriate method based on agent type
|
||||
if (getMessagesHandler && window.electron) {
|
||||
// For Codex and other IPC-based panels
|
||||
const outputs = await window.electron.invoke(getMessagesHandler, panelId);
|
||||
const jsonMessages = outputs
|
||||
.filter((output: SessionOutput) => output.type === 'json')
|
||||
.map((output: SessionOutput) => ({
|
||||
type: 'json' as const,
|
||||
data: typeof output.data === 'object' ? JSON.stringify(output.data) : output.data,
|
||||
timestamp: output.timestamp
|
||||
}));
|
||||
response = { success: true, data: jsonMessages };
|
||||
} else {
|
||||
// For Claude panels using API
|
||||
response = await API.panels.getJsonMessages(panelId);
|
||||
}
|
||||
|
||||
if (response.success && response.data) {
|
||||
// Filter out session_info messages and handle them separately
|
||||
const regularMessages: JSONMessage[] = [];
|
||||
let foundSessionInfo: SessionInfo | null = null;
|
||||
|
||||
response.data.forEach((msg: JSONMessage) => {
|
||||
try {
|
||||
// Try to parse the message data to check its type
|
||||
let msgData: unknown;
|
||||
if (typeof msg === 'string') {
|
||||
try {
|
||||
msgData = JSON.parse(msg);
|
||||
} catch {
|
||||
// If it's a string but not valid JSON, treat as regular message
|
||||
// This case shouldn't have timestamps - skip adding to avoid "just now" issue
|
||||
console.warn('Received raw string message without timestamp:', msg);
|
||||
return;
|
||||
}
|
||||
} else if (msg.data) {
|
||||
// Handle messages with data field (from IPC)
|
||||
msgData = typeof msg.data === 'string' ? JSON.parse(msg.data) : msg.data;
|
||||
} else {
|
||||
msgData = msg;
|
||||
}
|
||||
|
||||
// Check if this is a session_info message
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- External protocol message with dynamic structure
|
||||
if (msgData && typeof msgData === 'object' && 'type' in msgData && (msgData as any).type === 'session_info') {
|
||||
foundSessionInfo = msgData as SessionInfo;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Codex protocol messages have varying nested structures
|
||||
} else if (msgData && typeof msgData === 'object' && 'msg' in msgData && typeof (msgData as any).msg === 'object' && (msgData as any).msg !== null && 'type' in (msgData as any).msg && (msgData as any).msg.type === 'session_configured') {
|
||||
// Handle Codex session configuration
|
||||
foundSessionInfo = {
|
||||
type: 'session_info',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic Codex protocol field
|
||||
model: (msgData as any).msg.model || 'default',
|
||||
timestamp: msg.timestamp || ''
|
||||
};
|
||||
} else {
|
||||
// Regular JSON message
|
||||
regularMessages.push({
|
||||
type: 'json' as const,
|
||||
data: msg.data ? (typeof msg.data === 'string' ? msg.data : JSON.stringify(msg.data)) :
|
||||
(typeof msg === 'string' ? msg : JSON.stringify(msg)),
|
||||
timestamp: msg.timestamp || ''
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error processing message:', error, msg);
|
||||
// If there's any error, treat it as a regular message
|
||||
regularMessages.push({
|
||||
type: 'json' as const,
|
||||
data: msg.data ? (typeof msg.data === 'string' ? msg.data : JSON.stringify(msg.data)) :
|
||||
(typeof msg === 'string' ? msg : JSON.stringify(msg)),
|
||||
timestamp: msg.timestamp || ''
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
setSessionInfo(foundSessionInfo);
|
||||
// Sort messages by timestamp if available
|
||||
const sortedMessages = regularMessages.sort((a, b) => {
|
||||
if (!a.timestamp || !b.timestamp) return 0;
|
||||
return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
|
||||
});
|
||||
setMessages(sortedMessages);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load messages:', error);
|
||||
}
|
||||
};
|
||||
|
||||
loadMessages();
|
||||
}, [panelId, getMessagesHandler]);
|
||||
|
||||
// Subscribe to new messages
|
||||
useEffect(() => {
|
||||
const handleOutput = (data: CustomEvent<{ panelId?: string; sessionId?: string; type?: string; data?: unknown; timestamp?: string }> | { panelId?: string; sessionId?: string; type?: string; data?: unknown; timestamp?: string; detail?: { panelId?: string; sessionId?: string; type?: string; data?: unknown; timestamp?: string } }) => {
|
||||
const detail = 'detail' in data ? data.detail : data;
|
||||
if (!detail || (!detail.panelId && !detail.sessionId) || detail.type !== 'json') {
|
||||
return;
|
||||
}
|
||||
if ((detail.panelId === panelId || detail.sessionId === panelId)) {
|
||||
try {
|
||||
// Check if this is a session_info message
|
||||
let parsedData: unknown;
|
||||
if (typeof detail.data === 'string') {
|
||||
try {
|
||||
parsedData = JSON.parse(detail.data);
|
||||
} catch {
|
||||
// If it's not valid JSON, treat as regular message
|
||||
setMessages(prev => [...prev, {
|
||||
type: 'json',
|
||||
data: String(detail.data || ''),
|
||||
timestamp: detail.timestamp || ''
|
||||
}]);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
parsedData = detail.data;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- External protocol message with dynamic structure
|
||||
if (parsedData && typeof parsedData === 'object' && 'type' in parsedData && (parsedData as any).type === 'session_info') {
|
||||
setSessionInfo(parsedData as SessionInfo);
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Codex protocol messages have varying nested structures
|
||||
} else if (parsedData && typeof parsedData === 'object' && 'msg' in parsedData && typeof (parsedData as any).msg === 'object' && (parsedData as any).msg !== null && 'type' in (parsedData as any).msg && (parsedData as any).msg.type === 'session_configured') {
|
||||
// Handle Codex session configuration
|
||||
setSessionInfo({
|
||||
type: 'session_info',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Dynamic Codex protocol field
|
||||
model: (parsedData as any).msg.model || 'default',
|
||||
timestamp: detail.timestamp || ''
|
||||
});
|
||||
} else {
|
||||
setMessages(prev => [...prev, {
|
||||
type: 'json',
|
||||
data: typeof detail.data === 'string' ? detail.data : JSON.stringify(detail.data || {}),
|
||||
timestamp: detail.timestamp || ''
|
||||
}]);
|
||||
|
||||
// Auto-scroll to bottom if enabled
|
||||
if (autoScrollRef.current) {
|
||||
setTimeout(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error handling output:', error, data);
|
||||
// On error, just add as regular message
|
||||
setMessages(prev => [...prev, {
|
||||
type: 'json',
|
||||
data: typeof detail.data === 'string' ? detail.data : JSON.stringify(detail.data),
|
||||
timestamp: detail.timestamp || ''
|
||||
}]);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Listen for the appropriate event based on the agent type
|
||||
if (outputEventName.includes('codex')) {
|
||||
// Only register Electron IPC listener for Codex - not both IPC and window
|
||||
window.electron?.on(outputEventName, handleOutput);
|
||||
} else {
|
||||
window.electron?.on('session:output', handleOutput);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (outputEventName.includes('codex')) {
|
||||
window.electron?.off(outputEventName, handleOutput);
|
||||
} else {
|
||||
window.electron?.off('session:output', handleOutput);
|
||||
}
|
||||
};
|
||||
}, [panelId, outputEventName]);
|
||||
|
||||
// Handle scroll to detect if user is at bottom
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const handleScroll = () => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = container;
|
||||
// Consider "at bottom" only if within 50px of the bottom
|
||||
const isAtBottom = scrollHeight - scrollTop - clientHeight < 50;
|
||||
autoScrollRef.current = isAtBottom;
|
||||
};
|
||||
|
||||
container.addEventListener('scroll', handleScroll);
|
||||
return () => container.removeEventListener('scroll', handleScroll);
|
||||
}, []);
|
||||
|
||||
const toggleMessage = (index: number) => {
|
||||
setExpandedMessages(prev => {
|
||||
const newSet = new Set(prev);
|
||||
if (newSet.has(index)) {
|
||||
newSet.delete(index);
|
||||
} else {
|
||||
newSet.add(index);
|
||||
}
|
||||
return newSet;
|
||||
});
|
||||
};
|
||||
|
||||
const copyToClipboard = async (text: string, index: number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
setCopiedIndex(index);
|
||||
setTimeout(() => setCopiedIndex(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const formatJSON = (jsonString: string): string => {
|
||||
try {
|
||||
const parsed = JSON.parse(jsonString);
|
||||
return JSON.stringify(parsed, null, 2);
|
||||
} catch {
|
||||
return jsonString;
|
||||
}
|
||||
};
|
||||
|
||||
const getMessagePreview = (jsonString: string): string => {
|
||||
try {
|
||||
const parsed = JSON.parse(jsonString);
|
||||
|
||||
// Handle Codex protocol messages
|
||||
if (parsed.op) {
|
||||
return `Operation: ${parsed.op.type}`;
|
||||
}
|
||||
if (parsed.msg) {
|
||||
return `Message: ${parsed.msg.type}`;
|
||||
}
|
||||
|
||||
// Handle standard messages
|
||||
if (parsed.type) {
|
||||
return `${parsed.type}${parsed.role ? ` (${parsed.role})` : ''}`;
|
||||
}
|
||||
return 'JSON Message';
|
||||
} catch {
|
||||
return 'Invalid JSON';
|
||||
}
|
||||
};
|
||||
|
||||
const getAgentName = () => {
|
||||
switch (agentType) {
|
||||
case 'claude':
|
||||
return 'Claude Code';
|
||||
case 'codex':
|
||||
return 'Codex';
|
||||
default:
|
||||
return 'CLI Tool';
|
||||
}
|
||||
};
|
||||
|
||||
if (messages.length === 0 && !sessionInfo) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center p-8">
|
||||
<div className="text-center">
|
||||
<div className="text-text-tertiary mb-2">No JSON messages yet</div>
|
||||
<div className="text-sm text-text-quaternary">
|
||||
JSON messages from {getAgentName()} will appear here
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="h-full overflow-y-auto overflow-x-hidden bg-surface-primary p-4 font-mono text-sm scrollbar-thin scrollbar-thumb-border-secondary"
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{/* Session Info Card */}
|
||||
{sessionInfo && (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary mb-4">
|
||||
<div
|
||||
className="flex items-center justify-between p-3 cursor-pointer hover:bg-surface-hover transition-colors"
|
||||
onClick={() => setShowSessionInfo(!showSessionInfo)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<button className="text-text-tertiary hover:text-text-primary">
|
||||
{showSessionInfo ?
|
||||
<ChevronDown className="w-4 h-4" /> :
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
}
|
||||
</button>
|
||||
<span className="text-text-primary font-medium flex items-center gap-2">
|
||||
<Terminal className="w-4 h-4" />
|
||||
Session Information
|
||||
</span>
|
||||
{sessionInfo.timestamp && (
|
||||
<span className="text-text-quaternary text-xs">
|
||||
{new Date(sessionInfo.timestamp).toLocaleTimeString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
const infoText = sessionInfo.initial_prompt ?
|
||||
`You:\n${sessionInfo.initial_prompt}\n\nCommand:\n${sessionInfo.claude_command || sessionInfo.codex_command || ''}\n\nWorktree Path:\n${sessionInfo.worktree_path}\n\nModel: ${sessionInfo.model}` :
|
||||
`Model: ${sessionInfo.model || 'Unknown'}`;
|
||||
copyToClipboard(infoText, -1);
|
||||
}}
|
||||
className={cn(
|
||||
"p-1.5 rounded transition-colors",
|
||||
copiedIndex === -1
|
||||
? "text-status-success bg-status-success/10"
|
||||
: "text-text-tertiary hover:text-text-primary hover:bg-surface-hover"
|
||||
)}
|
||||
title={copiedIndex === -1 ? "Copied!" : "Copy Session Info"}
|
||||
>
|
||||
{copiedIndex === -1 ? (
|
||||
<Check className="w-4 h-4" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showSessionInfo && (
|
||||
<div className="border-t border-border-primary">
|
||||
<div className="p-4 space-y-3">
|
||||
{/* User Prompt (if available) */}
|
||||
{sessionInfo.initial_prompt && (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-text-secondary mb-1">
|
||||
<FileText className="w-3.5 h-3.5" />
|
||||
<span className="text-xs font-semibold tracking-wider">You</span>
|
||||
</div>
|
||||
<div className="bg-surface-primary rounded p-3 text-text-primary whitespace-pre-wrap break-words">
|
||||
{sessionInfo.initial_prompt}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Command (if available) */}
|
||||
{(sessionInfo.claude_command || sessionInfo.codex_command) && (
|
||||
<div>
|
||||
<div className="flex items-center gap-2 text-text-secondary mb-1">
|
||||
<Terminal className="w-3.5 h-3.5" />
|
||||
<span className="text-xs font-semibold uppercase tracking-wider">
|
||||
{agentType === 'claude' ? 'Claude' : 'Codex'} Command
|
||||
</span>
|
||||
</div>
|
||||
<div className="bg-surface-primary rounded p-3 text-text-primary font-mono text-xs overflow-x-auto">
|
||||
{sessionInfo.claude_command || sessionInfo.codex_command}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Additional Info */}
|
||||
<div className="grid grid-cols-2 gap-3 text-xs">
|
||||
{sessionInfo.worktree_path && (
|
||||
<div>
|
||||
<span className="text-text-quaternary">Worktree Path:</span>
|
||||
<div className="text-text-secondary mt-1 font-mono truncate" title={sessionInfo.worktree_path}>
|
||||
{sessionInfo.worktree_path}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<span className="text-text-quaternary">Model:</span>
|
||||
<div className="text-text-secondary mt-1">
|
||||
{sessionInfo.model || 'Unknown'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Regular Messages */}
|
||||
{messages.map((message, index) => {
|
||||
const isExpanded = expandedMessages.has(index);
|
||||
const preview = getMessagePreview(message.data);
|
||||
const formatted = formatJSON(message.data);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`message_${panelId}_${index}_${message.timestamp}`}
|
||||
className="bg-surface-secondary rounded-lg border border-border-primary"
|
||||
>
|
||||
<div
|
||||
className="flex items-center justify-between p-3 cursor-pointer hover:bg-surface-hover transition-colors"
|
||||
onClick={() => toggleMessage(index)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<button className="text-text-tertiary hover:text-text-primary">
|
||||
{isExpanded ?
|
||||
<ChevronDown className="w-4 h-4" /> :
|
||||
<ChevronRight className="w-4 h-4" />
|
||||
}
|
||||
</button>
|
||||
<span className="text-text-primary font-medium">{preview}</span>
|
||||
{message.timestamp && (
|
||||
<span className="text-text-quaternary text-xs">
|
||||
{new Date(message.timestamp).toLocaleTimeString()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyToClipboard(formatted, index);
|
||||
}}
|
||||
className={cn(
|
||||
"p-1.5 rounded transition-colors",
|
||||
copiedIndex === index
|
||||
? "text-status-success bg-status-success/10"
|
||||
: "text-text-tertiary hover:text-text-primary hover:bg-surface-hover"
|
||||
)}
|
||||
title={copiedIndex === index ? "Copied!" : "Copy JSON"}
|
||||
>
|
||||
{copiedIndex === index ? (
|
||||
<Check className="w-4 h-4" />
|
||||
) : (
|
||||
<Copy className="w-4 h-4" />
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{isExpanded && (
|
||||
<div className="border-t border-border-primary">
|
||||
<pre className="p-4 text-text-secondary overflow-x-auto max-h-96">
|
||||
<code>{formatted}</code>
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,172 +0,0 @@
|
||||
import React from 'react';
|
||||
import { MarkdownPreview } from '../../../MarkdownPreview';
|
||||
import { ToolCallView } from './ToolCallView';
|
||||
import { MessageSegment as MessageSegmentType } from '../transformers/MessageTransformer';
|
||||
|
||||
interface MessageSegmentProps {
|
||||
segment: MessageSegmentType;
|
||||
messageId: string; // Used for unique keys
|
||||
index: number; // Used for unique keys
|
||||
isUser: boolean;
|
||||
isCollapsed?: boolean;
|
||||
expandedTools: Set<string>;
|
||||
collapseTools: boolean;
|
||||
showToolCalls: boolean;
|
||||
showThinking: boolean;
|
||||
onToggleToolExpand: (toolId: string) => void;
|
||||
}
|
||||
|
||||
export const MessageSegment: React.FC<MessageSegmentProps> = ({
|
||||
segment,
|
||||
messageId: _messageId, // Prefix with _ to indicate intentionally unused
|
||||
index: _index, // Prefix with _ to indicate intentionally unused
|
||||
isUser,
|
||||
isCollapsed = false,
|
||||
expandedTools,
|
||||
collapseTools,
|
||||
showToolCalls,
|
||||
showThinking,
|
||||
onToggleToolExpand
|
||||
}) => {
|
||||
// State for diff expansion - declared at top level
|
||||
const [isDiffExpanded, setDiffExpanded] = React.useState(false);
|
||||
|
||||
switch (segment.type) {
|
||||
case 'text':
|
||||
if (!segment.content.trim()) return null;
|
||||
|
||||
return (
|
||||
<div className={`${isCollapsed ? 'max-h-20 overflow-hidden relative' : ''}`}>
|
||||
{isUser ? (
|
||||
<div className="text-text-primary whitespace-pre-wrap font-medium">{segment.content}</div>
|
||||
) : (
|
||||
<div className="rich-output-markdown">
|
||||
<MarkdownPreview content={segment.content} />
|
||||
</div>
|
||||
)}
|
||||
{isCollapsed && (
|
||||
<div className="absolute bottom-0 left-0 right-0 h-12 bg-gradient-to-t from-surface-secondary to-transparent pointer-events-none" />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'thinking':
|
||||
if (!showThinking || !segment.content.trim()) return null;
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="absolute -left-7 top-0 w-1 h-full bg-interactive/20 rounded-full" />
|
||||
<div className="pl-4 pr-2 py-2">
|
||||
<div className="text-sm thinking-content italic text-text-secondary">
|
||||
<MarkdownPreview content={segment.content} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'tool_call':
|
||||
if (!showToolCalls) return null;
|
||||
|
||||
return (
|
||||
<ToolCallView
|
||||
tool={segment.tool}
|
||||
isExpanded={collapseTools ? expandedTools.has(segment.tool.id) : true}
|
||||
collapseTools={collapseTools}
|
||||
onToggleExpand={onToggleToolExpand}
|
||||
expandedTools={expandedTools}
|
||||
/>
|
||||
);
|
||||
|
||||
case 'tool_result':
|
||||
if (!showToolCalls) return null;
|
||||
|
||||
return (
|
||||
<div className="px-4 py-2 bg-surface-hover/30">
|
||||
<div className="text-xs text-text-secondary mb-1">Tool Result</div>
|
||||
<pre className="text-xs text-text-tertiary font-mono overflow-x-auto max-h-32 overflow-y-auto">
|
||||
{typeof segment.result.content === 'string'
|
||||
? segment.result.content
|
||||
: JSON.stringify(segment.result.content, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'system_info':
|
||||
// System info segments are handled differently by parent component
|
||||
return null;
|
||||
|
||||
case 'error':
|
||||
if (!segment.error) return null;
|
||||
|
||||
return (
|
||||
<div className="my-2 p-3 bg-red-900/20 border border-red-700/50 rounded-lg">
|
||||
<div className="text-red-400 font-semibold text-sm mb-2">
|
||||
{segment.error.message || 'Error'}
|
||||
</div>
|
||||
{segment.error.details && (
|
||||
<div className="text-red-300 text-sm whitespace-pre-wrap font-mono">
|
||||
{segment.error.details}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
case 'diff': {
|
||||
if (!segment.diff || !segment.diff.trim()) return null;
|
||||
|
||||
// For diffs, show them in a collapsible code block
|
||||
const lines = segment.diff.split('\n');
|
||||
const fileCount = (segment.diff.match(/^diff --git/gm) || []).length;
|
||||
const addedLines = (segment.diff.match(/^\+[^+]/gm) || []).length;
|
||||
const removedLines = (segment.diff.match(/^-[^-]/gm) || []).length;
|
||||
|
||||
return (
|
||||
<div className="my-2">
|
||||
<button
|
||||
onClick={() => setDiffExpanded(!isDiffExpanded)}
|
||||
className="flex items-center gap-2 px-3 py-1.5 text-xs bg-surface-secondary hover:bg-surface-hover rounded transition-colors w-full text-left"
|
||||
>
|
||||
<span className="text-text-tertiary">
|
||||
{isDiffExpanded ? '▼' : '▶'}
|
||||
</span>
|
||||
<span className="text-text-secondary font-medium">
|
||||
Diff: {fileCount} file{fileCount !== 1 ? 's' : ''} changed
|
||||
</span>
|
||||
<span className="text-green-500">+{addedLines}</span>
|
||||
<span className="text-red-500">-{removedLines}</span>
|
||||
</button>
|
||||
|
||||
{isDiffExpanded && (
|
||||
<div className="mt-2 bg-black/20 rounded-lg p-3 overflow-hidden">
|
||||
<pre className="text-xs font-mono overflow-x-auto">
|
||||
{lines.map((line, i) => {
|
||||
let className = 'text-text-tertiary';
|
||||
if (line.startsWith('+++') || line.startsWith('---')) {
|
||||
className = 'text-text-secondary font-semibold';
|
||||
} else if (line.startsWith('@@')) {
|
||||
className = 'text-blue-400';
|
||||
} else if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
className = 'text-green-400 bg-green-900/20';
|
||||
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
className = 'text-red-400 bg-red-900/20';
|
||||
} else if (line.startsWith('diff --git')) {
|
||||
className = 'text-purple-400 font-semibold mt-2';
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={i} className={className}>
|
||||
{line || '\u00A0'}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@ -1,100 +0,0 @@
|
||||
import React from 'react';
|
||||
import { CheckCircle, Circle, ArrowRight, ListTodo } from 'lucide-react';
|
||||
|
||||
interface Todo {
|
||||
id: string;
|
||||
content: string;
|
||||
status: 'pending' | 'in_progress' | 'completed';
|
||||
}
|
||||
|
||||
interface TodoListDisplayProps {
|
||||
todos: Todo[];
|
||||
timestamp?: string;
|
||||
}
|
||||
|
||||
export const TodoListDisplay: React.FC<TodoListDisplayProps> = ({ todos }) => {
|
||||
const completedCount = todos.filter(t => t.status === 'completed').length;
|
||||
const inProgressCount = todos.filter(t => t.status === 'in_progress').length;
|
||||
const totalCount = todos.length;
|
||||
|
||||
// Calculate progress percentage
|
||||
const progressPercent = totalCount > 0 ? (completedCount / totalCount) * 100 : 0;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg bg-gradient-to-br from-interactive/10 to-interactive/5 border border-interactive/25 overflow-hidden">
|
||||
{/* Header */}
|
||||
<div className="px-4 py-2.5 bg-interactive/10 border-b border-interactive/20 flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<ListTodo className="w-4 h-4 text-interactive" />
|
||||
<span className="font-semibold text-text-primary text-sm">Task List</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Progress bar */}
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="w-24 h-1.5 bg-surface-secondary rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-interactive transition-all duration-500 ease-out"
|
||||
style={{ width: `${progressPercent}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-[11px] text-text-secondary font-mono">
|
||||
{completedCount}/{totalCount}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Status badges */}
|
||||
{inProgressCount > 0 && (
|
||||
<span className="text-[11px] px-2 py-0.5 bg-status-warning/20 text-status-warning rounded-full font-medium">
|
||||
{inProgressCount} active
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Todo list */}
|
||||
<div className="p-3 space-y-1.5 max-h-96 overflow-y-auto">
|
||||
{todos.length === 0 ? (
|
||||
<div className="text-center py-4 text-text-tertiary text-sm italic">
|
||||
No tasks defined yet
|
||||
</div>
|
||||
) : (
|
||||
todos.map((todo, idx) => {
|
||||
const Icon =
|
||||
todo.status === 'completed' ? CheckCircle :
|
||||
todo.status === 'in_progress' ? ArrowRight :
|
||||
Circle;
|
||||
|
||||
const statusColor =
|
||||
todo.status === 'completed' ? 'text-status-success' :
|
||||
todo.status === 'in_progress' ? 'text-status-warning animate-pulse' :
|
||||
'text-text-tertiary';
|
||||
|
||||
const textStyle =
|
||||
todo.status === 'completed' ? 'line-through text-text-tertiary' :
|
||||
todo.status === 'in_progress' ? 'text-text-primary font-medium' :
|
||||
'text-text-secondary';
|
||||
|
||||
return (
|
||||
<div
|
||||
key={todo.id || `todo-${idx}`}
|
||||
className={`flex items-start gap-2.5 px-2 py-1 rounded transition-all ${
|
||||
todo.status === 'in_progress' ? 'bg-status-warning/10 border-l-2 border-status-warning' : ''
|
||||
}`}
|
||||
>
|
||||
<Icon className={`w-3.5 h-3.5 mt-0.5 flex-shrink-0 ${statusColor}`} />
|
||||
<span className={`text-sm flex-1 ${textStyle}`}>
|
||||
{todo.content}
|
||||
</span>
|
||||
{todo.status === 'in_progress' && (
|
||||
<span className="text-[10px] text-status-warning bg-status-warning/20 px-1.5 py-0.5 rounded">
|
||||
ACTIVE
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,81 +0,0 @@
|
||||
import React from 'react';
|
||||
import { MessageSegment as MessageSegmentType } from '../transformers/MessageTransformer';
|
||||
import { ToolCallView } from './ToolCallView';
|
||||
|
||||
interface ToolCallGroupProps {
|
||||
tools: MessageSegmentType[]; // These are tool_call segments
|
||||
expandedTools: Set<string>;
|
||||
collapseTools: boolean;
|
||||
onToggleToolExpand: (toolId: string) => void;
|
||||
}
|
||||
|
||||
export const ToolCallGroup: React.FC<ToolCallGroupProps> = ({
|
||||
tools,
|
||||
expandedTools,
|
||||
collapseTools,
|
||||
onToggleToolExpand
|
||||
}) => {
|
||||
// Filter to only tool_call segments and extract the tools
|
||||
const toolCalls = tools
|
||||
.filter(seg => seg.type === 'tool_call')
|
||||
.map(seg => seg.type === 'tool_call' ? seg.tool : null)
|
||||
.filter(tool => tool !== null);
|
||||
|
||||
// If there's only one tool, render it directly
|
||||
if (toolCalls.length === 1) {
|
||||
const tool = toolCalls[0];
|
||||
return (
|
||||
<ToolCallView
|
||||
tool={tool}
|
||||
isExpanded={collapseTools ? expandedTools.has(tool.id) : true}
|
||||
collapseTools={collapseTools}
|
||||
onToggleExpand={onToggleToolExpand}
|
||||
expandedTools={expandedTools}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// For multiple tools, render them in a grouped container
|
||||
return (
|
||||
<div className="rounded-lg bg-surface-tertiary/20 border border-border-primary/30 overflow-hidden">
|
||||
<div className="px-2 py-1.5 bg-surface-tertiary/30 border-b border-border-primary/20">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[10px] text-text-tertiary uppercase tracking-wider font-medium">
|
||||
Tool Sequence ({toolCalls.length} tools)
|
||||
</span>
|
||||
<div className="flex items-center gap-1 ml-auto">
|
||||
{/* Status summary */}
|
||||
{toolCalls.filter(t => t.status === 'success').length > 0 && (
|
||||
<span className="text-[10px] text-status-success">
|
||||
{toolCalls.filter(t => t.status === 'success').length} ✓
|
||||
</span>
|
||||
)}
|
||||
{toolCalls.filter(t => t.status === 'error').length > 0 && (
|
||||
<span className="text-[10px] text-status-error">
|
||||
{toolCalls.filter(t => t.status === 'error').length} ✗
|
||||
</span>
|
||||
)}
|
||||
{toolCalls.filter(t => t.status === 'pending').length > 0 && (
|
||||
<span className="text-[10px] text-text-tertiary">
|
||||
{toolCalls.filter(t => t.status === 'pending').length} ⏳
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="divide-y divide-border-primary/20">
|
||||
{toolCalls.map((tool, idx) => (
|
||||
<div key={`tool-${tool.id}-${idx}`} className="first:border-t-0">
|
||||
<ToolCallView
|
||||
tool={tool}
|
||||
isExpanded={collapseTools ? expandedTools.has(tool.id) : true}
|
||||
collapseTools={collapseTools}
|
||||
onToggleExpand={onToggleToolExpand}
|
||||
expandedTools={expandedTools}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,618 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Wrench, CheckCircle, XCircle, Clock, ChevronDown, ChevronRight } from 'lucide-react';
|
||||
import { ToolCall } from '../transformers/MessageTransformer';
|
||||
import { MarkdownPreview } from '../../../MarkdownPreview';
|
||||
|
||||
interface ToolCallViewProps {
|
||||
tool: ToolCall;
|
||||
depth?: number;
|
||||
isExpanded: boolean;
|
||||
collapseTools: boolean;
|
||||
onToggleExpand: (toolId: string) => void;
|
||||
expandedTools?: Set<string>; // Add this to track expanded state for child tools
|
||||
}
|
||||
|
||||
// Type guards for tool input types
|
||||
interface ReadToolInput extends Record<string, unknown> {
|
||||
file_path: string;
|
||||
offset?: number;
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
interface EditToolInput extends Record<string, unknown> {
|
||||
file_path: string;
|
||||
old_string?: string;
|
||||
new_string?: string;
|
||||
}
|
||||
|
||||
interface MultiEditToolInput extends Record<string, unknown> {
|
||||
file_path: string;
|
||||
edits: Array<{ old_string: string; new_string: string }>;
|
||||
}
|
||||
|
||||
interface WriteToolInput extends Record<string, unknown> {
|
||||
file_path: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface BashToolInput extends Record<string, unknown> {
|
||||
command: string;
|
||||
}
|
||||
|
||||
interface GrepToolInput extends Record<string, unknown> {
|
||||
pattern: string;
|
||||
path?: string;
|
||||
glob?: string;
|
||||
}
|
||||
|
||||
interface GlobToolInput extends Record<string, unknown> {
|
||||
pattern: string;
|
||||
path?: string;
|
||||
}
|
||||
|
||||
interface WebFetchToolInput extends Record<string, unknown> {
|
||||
url: string;
|
||||
prompt: string;
|
||||
}
|
||||
|
||||
// Type guards
|
||||
const isReadInput = (input: Record<string, unknown>): input is ReadToolInput => {
|
||||
return typeof input.file_path === 'string';
|
||||
};
|
||||
|
||||
const isEditInput = (input: Record<string, unknown>): input is EditToolInput => {
|
||||
return typeof input.file_path === 'string';
|
||||
};
|
||||
|
||||
const isMultiEditInput = (input: Record<string, unknown>): input is MultiEditToolInput => {
|
||||
return typeof input.file_path === 'string' && Array.isArray(input.edits);
|
||||
};
|
||||
|
||||
const isWriteInput = (input: Record<string, unknown>): input is WriteToolInput => {
|
||||
return typeof input.file_path === 'string' && typeof input.content === 'string';
|
||||
};
|
||||
|
||||
const isBashInput = (input: Record<string, unknown>): input is BashToolInput => {
|
||||
return typeof input.command === 'string';
|
||||
};
|
||||
|
||||
const isGrepInput = (input: Record<string, unknown>): input is GrepToolInput => {
|
||||
return typeof input.pattern === 'string';
|
||||
};
|
||||
|
||||
const isGlobInput = (input: Record<string, unknown>): input is GlobToolInput => {
|
||||
return typeof input.pattern === 'string';
|
||||
};
|
||||
|
||||
const isWebFetchInput = (input: Record<string, unknown>): input is WebFetchToolInput => {
|
||||
return typeof input.url === 'string' && typeof input.prompt === 'string';
|
||||
};
|
||||
|
||||
interface TaskToolInput extends Record<string, unknown> {
|
||||
description?: string;
|
||||
subagent_type?: string;
|
||||
prompt?: string;
|
||||
}
|
||||
|
||||
interface TodoWriteToolInput extends Record<string, unknown> {
|
||||
todos: Array<{ status: string; content: string }>;
|
||||
}
|
||||
|
||||
interface WebSearchToolInput extends Record<string, unknown> {
|
||||
query: string;
|
||||
}
|
||||
|
||||
const isTaskInput = (input: Record<string, unknown>): input is TaskToolInput => {
|
||||
return typeof input.description === 'string' || typeof input.subagent_type === 'string';
|
||||
};
|
||||
|
||||
const isTodoWriteInput = (input: Record<string, unknown>): input is TodoWriteToolInput => {
|
||||
return Array.isArray(input.todos);
|
||||
};
|
||||
|
||||
const isWebSearchInput = (input: Record<string, unknown>): input is WebSearchToolInput => {
|
||||
return typeof input.query === 'string';
|
||||
};
|
||||
|
||||
interface LSToolInput extends Record<string, unknown> {
|
||||
path: string;
|
||||
}
|
||||
|
||||
interface NotebookEditToolInput extends Record<string, unknown> {
|
||||
notebook_path: string;
|
||||
edit_mode?: string;
|
||||
}
|
||||
|
||||
interface BashOutputToolInput extends Record<string, unknown> {
|
||||
bash_id: string;
|
||||
}
|
||||
|
||||
interface KillBashToolInput extends Record<string, unknown> {
|
||||
shell_id: string;
|
||||
}
|
||||
|
||||
const isLSInput = (input: Record<string, unknown>): input is LSToolInput => {
|
||||
return typeof input.path === 'string';
|
||||
};
|
||||
|
||||
const isNotebookEditInput = (input: Record<string, unknown>): input is NotebookEditToolInput => {
|
||||
return typeof input.notebook_path === 'string';
|
||||
};
|
||||
|
||||
const isBashOutputInput = (input: Record<string, unknown>): input is BashOutputToolInput => {
|
||||
return typeof input.bash_id === 'string';
|
||||
};
|
||||
|
||||
const isKillBashInput = (input: Record<string, unknown>): input is KillBashToolInput => {
|
||||
return typeof input.shell_id === 'string';
|
||||
};
|
||||
|
||||
// Get a compact summary for the tool call
|
||||
const getCompactToolSummary = (tool: ToolCall): string => {
|
||||
const input = tool.input;
|
||||
if (!input) return '';
|
||||
|
||||
switch (tool.name) {
|
||||
case 'Read':
|
||||
if (isReadInput(input)) {
|
||||
const filename = input.file_path.split('/').pop() || input.file_path;
|
||||
const lines = input.offset ? ` (lines ${input.offset}-${input.offset + (input.limit || 2000)})` : '';
|
||||
return filename + lines;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'Edit':
|
||||
if (isEditInput(input)) {
|
||||
const filename = input.file_path.split('/').pop() || input.file_path;
|
||||
return filename;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'MultiEdit':
|
||||
if (isMultiEditInput(input)) {
|
||||
const filename = input.file_path.split('/').pop() || input.file_path;
|
||||
const editsInfo = ` (${input.edits.length} changes)`;
|
||||
return filename + editsInfo;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'Write':
|
||||
if (isWriteInput(input)) {
|
||||
const filename = input.file_path.split('/').pop() || input.file_path;
|
||||
const lines = ` (${input.content.split('\n').length} lines)`;
|
||||
return filename + lines;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'Bash':
|
||||
if (isBashInput(input)) {
|
||||
// Truncate long commands
|
||||
const cmd = input.command.length > 50 ? input.command.substring(0, 50) + '...' : input.command;
|
||||
return cmd;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'Grep':
|
||||
if (isGrepInput(input)) {
|
||||
const pattern = input.pattern.length > 20 ? input.pattern.substring(0, 20) + '...' : input.pattern;
|
||||
const location = input.path ? ` in ${input.path.split('/').pop() || input.path}` : '';
|
||||
return `"${pattern}"${location}`;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'Glob':
|
||||
if (isGlobInput(input)) {
|
||||
const location = input.path ? ` in ${input.path.split('/').pop() || input.path}` : '';
|
||||
return `${input.pattern}${location}`;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'Task':
|
||||
if (isTaskInput(input)) {
|
||||
if (input.description) {
|
||||
return input.description.length > 40 ? input.description.substring(0, 40) + '...' : input.description;
|
||||
}
|
||||
return input.subagent_type || '';
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'TodoWrite':
|
||||
if (isTodoWriteInput(input)) {
|
||||
const total = input.todos.length;
|
||||
const completed = input.todos.filter(t => t.status === 'completed').length;
|
||||
return `${completed}/${total} tasks`;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'WebFetch':
|
||||
if (isWebFetchInput(input)) {
|
||||
try {
|
||||
const url = new URL(input.url);
|
||||
return url.hostname;
|
||||
} catch {
|
||||
return input.url.substring(0, 30) + '...';
|
||||
}
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'WebSearch':
|
||||
if (isWebSearchInput(input)) {
|
||||
return input.query.length > 30 ? input.query.substring(0, 30) + '...' : input.query;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'LS':
|
||||
if (isLSInput(input)) {
|
||||
return input.path.split('/').pop() || input.path;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'NotebookEdit':
|
||||
if (isNotebookEditInput(input)) {
|
||||
const filename = input.notebook_path.split('/').pop() || input.notebook_path;
|
||||
const mode = input.edit_mode || 'replace';
|
||||
return `${filename} (${mode})`;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'BashOutput':
|
||||
if (isBashOutputInput(input)) {
|
||||
return `shell: ${input.bash_id.substring(0, 8)}...`;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'KillBash':
|
||||
if (isKillBashInput(input)) {
|
||||
return `kill shell: ${input.shell_id.substring(0, 8)}...`;
|
||||
}
|
||||
return '';
|
||||
|
||||
case 'ExitPlanMode':
|
||||
return 'exit planning mode';
|
||||
|
||||
case 'TodoRead':
|
||||
return 'read task list';
|
||||
|
||||
default:
|
||||
// For unknown tools, try to show something meaningful using type checks
|
||||
if (typeof input.file_path === 'string') {
|
||||
return input.file_path.split('/').pop() || input.file_path;
|
||||
}
|
||||
if (typeof input.path === 'string') {
|
||||
return input.path.split('/').pop() || input.path;
|
||||
}
|
||||
if (typeof input.command === 'string') {
|
||||
return input.command.substring(0, 30) + '...';
|
||||
}
|
||||
if (typeof input.name === 'string') {
|
||||
return input.name;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
export const ToolCallView: React.FC<ToolCallViewProps> = ({
|
||||
tool,
|
||||
depth = 0,
|
||||
isExpanded,
|
||||
collapseTools,
|
||||
onToggleExpand,
|
||||
expandedTools
|
||||
}) => {
|
||||
const isTaskAgent = tool.isSubAgent && tool.name === 'Task';
|
||||
const hasChildTools = tool.childToolCalls && tool.childToolCalls.length > 0;
|
||||
|
||||
// Sub-agents (Task tools) should always be expanded by default
|
||||
const effectiveIsExpanded = isTaskAgent ? (expandedTools ? expandedTools.has(tool.id) : true) : isExpanded;
|
||||
|
||||
// Get compact summary for the tool
|
||||
const compactSummary = getCompactToolSummary(tool);
|
||||
|
||||
// Lighter, more subtle styling
|
||||
const bgColor = isTaskAgent
|
||||
? 'bg-interactive/5'
|
||||
: depth > 0
|
||||
? 'bg-surface-tertiary/10'
|
||||
: 'bg-surface-tertiary/15';
|
||||
|
||||
const borderColor = isTaskAgent
|
||||
? 'border-interactive/20'
|
||||
: 'border-border-primary/20';
|
||||
|
||||
return (
|
||||
<div className={`rounded-md ${bgColor} overflow-hidden border ${borderColor} ${depth > 0 ? 'ml-4' : ''}`}>
|
||||
<button
|
||||
onClick={() => onToggleExpand(tool.id)}
|
||||
className="w-full px-2 py-1 flex items-center gap-2 hover:bg-surface-tertiary/20 transition-colors text-left"
|
||||
>
|
||||
{/* Always show chevron for expandable tools */}
|
||||
{effectiveIsExpanded ? <ChevronDown className="w-3 h-3 text-text-tertiary flex-shrink-0" /> : <ChevronRight className="w-3 h-3 text-text-tertiary flex-shrink-0" />}
|
||||
|
||||
{/* Tool icon */}
|
||||
{isTaskAgent ? (
|
||||
<svg className="w-3 h-3 text-interactive flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
|
||||
</svg>
|
||||
) : (
|
||||
<Wrench className="w-3 h-3 text-interactive-on-dark flex-shrink-0" />
|
||||
)}
|
||||
|
||||
{/* Compact display: tool name + summary */}
|
||||
<span className="font-mono text-xs text-text-primary flex-1 truncate">
|
||||
<span className="font-semibold">{isTaskAgent ? 'Agent' : tool.name}</span>
|
||||
{isTaskAgent && tool.subAgentType && (
|
||||
<span className="ml-1 text-interactive">
|
||||
[{tool.subAgentType}]
|
||||
</span>
|
||||
)}
|
||||
{compactSummary && <span className="ml-2 text-text-secondary">{compactSummary}</span>}
|
||||
</span>
|
||||
|
||||
{/* Status icon */}
|
||||
{tool.status === 'success' && <CheckCircle className="w-3 h-3 text-status-success flex-shrink-0" />}
|
||||
{tool.status === 'error' && <XCircle className="w-3 h-3 text-status-error flex-shrink-0" />}
|
||||
{tool.status === 'pending' && <Clock className="w-3 h-3 text-text-tertiary flex-shrink-0 animate-pulse" />}
|
||||
</button>
|
||||
|
||||
{effectiveIsExpanded && (
|
||||
<div className="px-2 py-1.5 text-xs border-t border-border-primary/15">
|
||||
{/* Tool Parameters - more compact display */}
|
||||
{tool.input && Object.keys(tool.input).length > 0 && (
|
||||
<div className="mb-1.5">
|
||||
<div className="text-text-tertiary text-[10px] uppercase tracking-wider mb-0.5">Parameters</div>
|
||||
{formatToolInput(tool.name, tool.input)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Child tool calls for Task agents */}
|
||||
{hasChildTools && (
|
||||
<div className="mt-1.5">
|
||||
<div className="text-text-secondary text-[10px] uppercase tracking-wider mb-1">
|
||||
Sub-agent Actions ({tool.childToolCalls!.length})
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
{tool.childToolCalls!.map((childTool, idx) => (
|
||||
<ToolCallView
|
||||
key={`${tool.id}-child-${idx}`}
|
||||
tool={childTool}
|
||||
depth={depth + 1}
|
||||
isExpanded={expandedTools ? expandedTools.has(childTool.id) : false}
|
||||
collapseTools={collapseTools}
|
||||
onToggleExpand={onToggleExpand}
|
||||
expandedTools={expandedTools}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tool Result - render in markdown */}
|
||||
{tool.result && (
|
||||
<div className="mt-1.5">
|
||||
<div className="text-text-tertiary text-[10px] uppercase tracking-wider mb-0.5">
|
||||
{tool.result.isError ? 'Error' : 'Result'}
|
||||
</div>
|
||||
<div className={`${tool.result.isError ? 'text-status-error' : 'text-text-primary'} text-[11px]`}>
|
||||
{formatToolResultMarkdown(tool.name, tool.result.content, tool.result.isError || false)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pending state */}
|
||||
{tool.status === 'pending' && !hasChildTools && (
|
||||
<div className="text-text-tertiary italic text-[11px]">Waiting for result...</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Format tool input for display - compact version
|
||||
const formatToolInput = (toolName: string, input: Record<string, unknown>): React.ReactNode => {
|
||||
switch (toolName) {
|
||||
case 'Read':
|
||||
if (isReadInput(input)) {
|
||||
return (
|
||||
<div className="font-mono text-[11px] space-y-0.5 text-text-secondary">
|
||||
<div className="truncate">
|
||||
<span className="text-text-tertiary">file:</span> {input.file_path}
|
||||
</div>
|
||||
{input.offset && <div>lines: {input.offset}-{input.offset + (input.limit || 2000)}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Edit':
|
||||
if (isEditInput(input)) {
|
||||
return (
|
||||
<div className="font-mono text-[11px] space-y-0.5 text-text-secondary">
|
||||
<div className="truncate"><span className="text-text-tertiary">file:</span> {input.file_path}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'MultiEdit':
|
||||
if (isMultiEditInput(input)) {
|
||||
return (
|
||||
<div className="font-mono text-[11px] space-y-0.5 text-text-secondary">
|
||||
<div className="truncate"><span className="text-text-tertiary">file:</span> {input.file_path}</div>
|
||||
<div>{input.edits.length} change{input.edits.length !== 1 ? 's' : ''}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Write':
|
||||
if (isWriteInput(input)) {
|
||||
return (
|
||||
<div className="font-mono text-[11px] space-y-0.5 text-text-secondary">
|
||||
<div className="truncate"><span className="text-text-tertiary">file:</span> {input.file_path}</div>
|
||||
<div>{input.content.split('\n').length} lines</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Bash':
|
||||
if (isBashInput(input)) {
|
||||
return (
|
||||
<div className="font-mono text-[11px] bg-bg-tertiary/50 px-1.5 py-0.5 rounded">
|
||||
<span className="text-status-success">$</span> {input.command}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Grep':
|
||||
if (isGrepInput(input)) {
|
||||
return (
|
||||
<div className="font-mono text-[11px] space-y-0.5 text-text-secondary">
|
||||
<div><span className="text-text-tertiary">pattern:</span> <span className="text-status-warning">"{input.pattern}"</span></div>
|
||||
{input.path && <div className="truncate"><span className="text-text-tertiary">path:</span> {input.path}</div>}
|
||||
{input.glob && <div><span className="text-text-tertiary">files:</span> {input.glob}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'Task':
|
||||
if (isTaskInput(input)) {
|
||||
return (
|
||||
<div className="text-[11px] space-y-1">
|
||||
{input.description && (
|
||||
<div className="text-interactive">{input.description}</div>
|
||||
)}
|
||||
{input.subagent_type && (
|
||||
<div className="text-status-warning font-mono">agent: {input.subagent_type}</div>
|
||||
)}
|
||||
{input.prompt && (
|
||||
<details>
|
||||
<summary className="cursor-pointer text-text-tertiary hover:text-text-secondary text-[10px]">
|
||||
view prompt
|
||||
</summary>
|
||||
<div className="mt-0.5 p-1 bg-surface-secondary/50 rounded text-[10px] whitespace-pre-wrap max-h-24 overflow-y-auto">
|
||||
{input.prompt}
|
||||
</div>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'TodoWrite':
|
||||
if (isTodoWriteInput(input)) {
|
||||
return (
|
||||
<div className="text-[11px] space-y-0.5">
|
||||
{input.todos.map((todo: { status: string; content: string }, idx: number) => {
|
||||
const icon = todo.status === 'completed' ? '✓' :
|
||||
todo.status === 'in_progress' ? '→' : '○';
|
||||
const color = todo.status === 'completed' ? 'text-status-success' :
|
||||
todo.status === 'in_progress' ? 'text-status-warning' : 'text-text-tertiary';
|
||||
return (
|
||||
<div key={idx} className={`${color}`}>
|
||||
{icon} {todo.content}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
// Compact display for unknown tools
|
||||
return (
|
||||
<pre className="text-[10px] overflow-x-auto max-h-16 text-text-secondary">
|
||||
{JSON.stringify(input, null, 2)}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
// Format tool result in markdown - replaces the old formatToolResult
|
||||
const formatToolResultMarkdown = (toolName: string, result: string, isError: boolean): React.ReactNode => {
|
||||
if (!result) {
|
||||
return <div className="text-[10px] text-text-tertiary italic">No result</div>;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if result is JSON
|
||||
const parsed = JSON.parse(result);
|
||||
|
||||
// Handle Task tool results (array with text objects)
|
||||
if (toolName === 'Task' && Array.isArray(parsed)) {
|
||||
// Extract text content from Task results
|
||||
const textContent = parsed
|
||||
.filter(item => item.type === 'text' && item.text)
|
||||
.map(item => item.text)
|
||||
.join('\n\n');
|
||||
|
||||
if (textContent) {
|
||||
// Render task results as markdown
|
||||
return (
|
||||
<div className="rich-output-markdown tool-result-markdown">
|
||||
<MarkdownPreview content={textContent} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle image reads
|
||||
if (Array.isArray(parsed) && parsed[0]?.type === 'image') {
|
||||
return (
|
||||
<div className="text-[11px] text-text-secondary italic">
|
||||
[Image displayed]
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// For other JSON results, pretty-print them in a code block
|
||||
return (
|
||||
<details className="text-[10px]">
|
||||
<summary className="cursor-pointer text-text-tertiary hover:text-text-secondary">
|
||||
View JSON result
|
||||
</summary>
|
||||
<pre className="mt-0.5 overflow-x-auto max-h-24 bg-surface-tertiary/30 p-2 rounded">
|
||||
{JSON.stringify(parsed, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
);
|
||||
} catch {
|
||||
// Not JSON - render as markdown for text content
|
||||
|
||||
// For error messages, show them prominently
|
||||
if (isError) {
|
||||
return (
|
||||
<div className="text-status-error bg-status-error/10 p-2 rounded border border-status-error/30">
|
||||
<MarkdownPreview content={result} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// For short results, render inline markdown
|
||||
if (result.length < 200) {
|
||||
return (
|
||||
<div className="rich-output-markdown tool-result-markdown">
|
||||
<MarkdownPreview content={result} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// For longer results, make them expandable but still render as markdown
|
||||
return (
|
||||
<details className="text-[11px]">
|
||||
<summary className="cursor-pointer text-text-secondary hover:text-text-primary mb-1">
|
||||
View full result ({result.split('\n').length} lines)
|
||||
</summary>
|
||||
<div className="rich-output-markdown tool-result-markdown mt-1 max-h-48 overflow-y-auto">
|
||||
<MarkdownPreview content={result} />
|
||||
</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@ -1,464 +0,0 @@
|
||||
import { MessageTransformer, UnifiedMessage, MessageSegment, ToolCall, ToolResult } from './MessageTransformer';
|
||||
|
||||
// Content block types
|
||||
interface ContentBlock {
|
||||
type: 'text' | 'tool_use' | 'tool_result' | 'thinking';
|
||||
text?: string;
|
||||
thinking?: string;
|
||||
content?: string;
|
||||
id?: string;
|
||||
name?: string;
|
||||
input?: Record<string, unknown>;
|
||||
tool_use_id?: string;
|
||||
is_error?: boolean;
|
||||
}
|
||||
|
||||
// Tool definition types
|
||||
interface ToolDefinition {
|
||||
name: string;
|
||||
description?: string;
|
||||
input_schema?: Record<string, unknown>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// MCP server definition types
|
||||
interface McpServerDefinition {
|
||||
name: string;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
env?: Record<string, string>;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
// Claude-specific message format
|
||||
interface ClaudeRawMessage {
|
||||
id?: string;
|
||||
type: 'user' | 'assistant' | 'system' | 'tool_use' | 'tool_result' | 'result';
|
||||
role?: 'user' | 'assistant' | 'system';
|
||||
content?: string | object;
|
||||
message?: {
|
||||
content?: string | ContentBlock[];
|
||||
model?: string;
|
||||
duration?: number;
|
||||
usage?: {
|
||||
input_tokens?: number;
|
||||
output_tokens?: number;
|
||||
cost?: number;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
};
|
||||
timestamp: string;
|
||||
name?: string;
|
||||
input?: Record<string, unknown>;
|
||||
tool_use_id?: string;
|
||||
parent_tool_use_id?: string;
|
||||
session_id?: string;
|
||||
text?: string;
|
||||
subtype?: string;
|
||||
cwd?: string;
|
||||
model?: string;
|
||||
tools?: ToolDefinition[];
|
||||
mcp_servers?: McpServerDefinition[];
|
||||
permissionMode?: string;
|
||||
summary?: string;
|
||||
error?: string;
|
||||
details?: string;
|
||||
raw_output?: string;
|
||||
is_error?: boolean;
|
||||
result?: string;
|
||||
duration_ms?: number;
|
||||
total_cost_usd?: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export class ClaudeMessageTransformer implements MessageTransformer {
|
||||
private messageIdCounter = 0;
|
||||
|
||||
transform(rawMessages: ClaudeRawMessage[]): UnifiedMessage[] {
|
||||
const transformed: UnifiedMessage[] = [];
|
||||
|
||||
// First pass: Build tool result map and identify sub-agent relationships
|
||||
const toolResults = new Map<string, ToolResult>();
|
||||
const parentToolMap = new Map<string, string>();
|
||||
|
||||
for (let i = 0; i < rawMessages.length; i++) {
|
||||
const msg = rawMessages[i];
|
||||
|
||||
// Check for parent_tool_use_id to identify sub-agent tool calls
|
||||
if (msg.parent_tool_use_id && msg.message?.content && Array.isArray(msg.message.content)) {
|
||||
const content = msg.message.content;
|
||||
for (let j = 0; j < content.length; j++) {
|
||||
const block = content[j];
|
||||
if (block.type === 'tool_use' && block.id) {
|
||||
parentToolMap.set(block.id, msg.parent_tool_use_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Collect tool results
|
||||
if (msg.type === 'user' && msg.message?.content && Array.isArray(msg.message.content)) {
|
||||
const content = msg.message.content;
|
||||
for (let j = 0; j < content.length; j++) {
|
||||
const block = content[j];
|
||||
if (block.type === 'tool_result' && block.tool_use_id) {
|
||||
toolResults.set(block.tool_use_id, {
|
||||
content: typeof block.content === 'string' ? block.content : JSON.stringify(block.content),
|
||||
isError: block.is_error || false
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: Build all tool calls
|
||||
const allToolCalls = new Map<string, ToolCall>();
|
||||
for (let i = 0; i < rawMessages.length; i++) {
|
||||
const msg = rawMessages[i];
|
||||
if (msg.type === 'assistant' && msg.message?.content && Array.isArray(msg.message.content)) {
|
||||
const content = msg.message.content;
|
||||
for (let j = 0; j < content.length; j++) {
|
||||
const block = content[j];
|
||||
if (block.type === 'tool_use') {
|
||||
const isTaskAgent = block.name === 'Task';
|
||||
const toolCall: ToolCall = {
|
||||
id: block.id || '',
|
||||
name: block.name || '',
|
||||
input: block.input,
|
||||
status: toolResults.has(block.id || '') ? 'success' : 'pending',
|
||||
result: toolResults.get(block.id || ''),
|
||||
isSubAgent: isTaskAgent,
|
||||
subAgentType: isTaskAgent && block.input && typeof block.input === 'object' && 'subagent_type' in block.input ? String(block.input.subagent_type) : undefined,
|
||||
parentToolId: parentToolMap.get(block.id || ''),
|
||||
childToolCalls: []
|
||||
};
|
||||
allToolCalls.set(block.id || '', toolCall);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build parent-child relationships
|
||||
const toolCallsArray = Array.from(allToolCalls.values());
|
||||
for (let i = 0; i < toolCallsArray.length; i++) {
|
||||
const toolCall = toolCallsArray[i];
|
||||
if (toolCall.parentToolId) {
|
||||
const parentTool = allToolCalls.get(toolCall.parentToolId);
|
||||
if (parentTool && parentTool.childToolCalls) {
|
||||
parentTool.childToolCalls.push(toolCall);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Third pass: Build conversation messages
|
||||
for (let i = 0; i < rawMessages.length; i++) {
|
||||
const msg = rawMessages[i];
|
||||
const unifiedMsg = this.parseMessage(msg, allToolCalls, toolResults);
|
||||
if (unifiedMsg) {
|
||||
transformed.push(unifiedMsg);
|
||||
}
|
||||
}
|
||||
|
||||
return transformed;
|
||||
}
|
||||
|
||||
parseMessage(msg: ClaudeRawMessage, allToolCalls?: Map<string, ToolCall>, _toolResults?: Map<string, ToolResult>): UnifiedMessage | null {
|
||||
if (msg.type === 'user') {
|
||||
return this.parseUserMessage(msg);
|
||||
} else if (msg.type === 'assistant') {
|
||||
return this.parseAssistantMessage(msg, allToolCalls);
|
||||
} else if (msg.type === 'system') {
|
||||
return this.parseSystemMessage(msg);
|
||||
} else if (msg.type === 'result') {
|
||||
return this.parseResultMessage(msg);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseUserMessage(msg: ClaudeRawMessage): UnifiedMessage | null {
|
||||
// First, extract the text content to check for slash command results
|
||||
const textContent = this.extractTextContent(msg);
|
||||
|
||||
// Check if this is a slash command result (contains <local-command-stdout> tags)
|
||||
if (textContent && textContent.includes('<local-command-stdout>')) {
|
||||
// Extract content and remove tags
|
||||
const slashCommandContent = textContent
|
||||
.replace(/<local-command-stdout>/g, '')
|
||||
.replace(/<\/local-command-stdout>/g, '')
|
||||
.trim();
|
||||
|
||||
return {
|
||||
id: msg.id || `slash_result_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{ type: 'text', content: slashCommandContent }],
|
||||
metadata: {
|
||||
agent: 'claude',
|
||||
systemSubtype: 'slash_command_result'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Check if this is a tool result message
|
||||
let hasToolResult = false;
|
||||
let hasOnlyText = true;
|
||||
|
||||
if (msg.message?.content && Array.isArray(msg.message.content)) {
|
||||
const content = msg.message.content;
|
||||
for (let j = 0; j < content.length; j++) {
|
||||
if (content[j].type === 'tool_result') {
|
||||
hasToolResult = true;
|
||||
hasOnlyText = false;
|
||||
break;
|
||||
}
|
||||
if (content[j].type !== 'text') {
|
||||
hasOnlyText = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only show real user prompts (text-only messages without tool results)
|
||||
if (!hasToolResult && hasOnlyText) {
|
||||
if (textContent) {
|
||||
return {
|
||||
id: msg.id || `user_msg_${++this.messageIdCounter}`,
|
||||
role: 'user',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{ type: 'text', content: textContent }],
|
||||
metadata: { agent: 'claude' }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseAssistantMessage(msg: ClaudeRawMessage, allToolCalls?: Map<string, ToolCall>): UnifiedMessage | null {
|
||||
const segments: MessageSegment[] = [];
|
||||
|
||||
// Check for direct text field first
|
||||
if (msg.text && typeof msg.text === 'string') {
|
||||
segments.push({ type: 'text', content: msg.text.trim() });
|
||||
} else if (msg.message?.content && Array.isArray(msg.message.content)) {
|
||||
const content = msg.message.content;
|
||||
for (let j = 0; j < content.length; j++) {
|
||||
const block = content[j];
|
||||
if (block.type === 'text' && block.text?.trim()) {
|
||||
segments.push({ type: 'text', content: block.text.trim() });
|
||||
} else if (block.type === 'thinking') {
|
||||
const thinkingContent = block.thinking || block.content || block.text;
|
||||
if (thinkingContent && typeof thinkingContent === 'string' && thinkingContent.trim()) {
|
||||
segments.push({ type: 'thinking', content: thinkingContent.trim() });
|
||||
}
|
||||
} else if (block.type === 'tool_use' && allToolCalls) {
|
||||
const toolCall = allToolCalls.get(block.id || '');
|
||||
// Only add top-level tools (those without parents)
|
||||
if (toolCall && !toolCall.parentToolId) {
|
||||
segments.push({ type: 'tool_call', tool: toolCall });
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Fallback for other formats
|
||||
const textContent = this.extractTextContent(msg);
|
||||
if (textContent) {
|
||||
segments.push({ type: 'text', content: textContent });
|
||||
}
|
||||
}
|
||||
|
||||
// Only add message if it has content
|
||||
if (segments.length > 0) {
|
||||
// Check if this is a synthetic error message
|
||||
const isSyntheticError = msg.message?.model === '<synthetic>' &&
|
||||
segments.some(seg => seg.type === 'text' &&
|
||||
(seg.content.includes('Prompt is too long') ||
|
||||
seg.content.includes('API Error') ||
|
||||
seg.content.includes('error')));
|
||||
|
||||
return {
|
||||
id: msg.id || `assistant_msg_${++this.messageIdCounter}`,
|
||||
role: isSyntheticError ? 'system' : 'assistant',
|
||||
timestamp: msg.timestamp,
|
||||
segments,
|
||||
metadata: {
|
||||
agent: 'claude',
|
||||
model: msg.message?.model,
|
||||
duration: msg.message?.duration,
|
||||
tokens: msg.message?.usage ?
|
||||
(msg.message.usage.input_tokens || 0) + (msg.message.usage.output_tokens || 0) :
|
||||
undefined,
|
||||
cost: msg.message?.usage?.cost,
|
||||
systemSubtype: isSyntheticError ? 'error' : undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseSystemMessage(msg: ClaudeRawMessage): UnifiedMessage | null {
|
||||
if (msg.subtype === 'init') {
|
||||
// Extract slash commands if available
|
||||
if (msg.slash_commands && Array.isArray(msg.slash_commands)) {
|
||||
console.log('[slash-debug] Detected slash commands in init message:', msg.slash_commands);
|
||||
// Store slash commands in localStorage keyed by session_id
|
||||
// We'll update this to use panel context later
|
||||
if (msg.session_id) {
|
||||
try {
|
||||
const slashCommandsKey = `slashCommands_${msg.session_id}`;
|
||||
localStorage.setItem(slashCommandsKey, JSON.stringify(msg.slash_commands));
|
||||
console.log('[slash-debug] Stored slash commands for session:', msg.session_id);
|
||||
} catch (e) {
|
||||
console.warn('[slash-debug] Failed to store slash commands:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: msg.id || `system_init_msg_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{
|
||||
type: 'system_info',
|
||||
info: {
|
||||
cwd: msg.cwd,
|
||||
model: msg.model,
|
||||
tools: msg.tools,
|
||||
mcp_servers: msg.mcp_servers,
|
||||
permissionMode: msg.permissionMode,
|
||||
session_id: msg.session_id,
|
||||
slash_commands: msg.slash_commands
|
||||
}
|
||||
}],
|
||||
metadata: {
|
||||
systemSubtype: 'init',
|
||||
sessionInfo: msg
|
||||
}
|
||||
};
|
||||
} else if (msg.subtype === 'context_compacted') {
|
||||
return {
|
||||
id: msg.id || `context_compacted_msg_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [
|
||||
{ type: 'text', content: msg.summary || '' },
|
||||
{ type: 'system_info', info: { message: msg.message } }
|
||||
],
|
||||
metadata: {
|
||||
systemSubtype: 'context_compacted'
|
||||
}
|
||||
};
|
||||
} else if (msg.subtype === 'error') {
|
||||
return {
|
||||
id: msg.id || `error_msg_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{
|
||||
type: 'system_info',
|
||||
info: {
|
||||
error: msg.error,
|
||||
details: msg.details,
|
||||
message: msg.message
|
||||
}
|
||||
}],
|
||||
metadata: {
|
||||
systemSubtype: 'error'
|
||||
}
|
||||
};
|
||||
} else if (msg.subtype === 'git_operation') {
|
||||
return {
|
||||
id: msg.id || `git_operation_msg_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{
|
||||
type: 'text',
|
||||
content: (typeof msg.message === 'string' ? msg.message : '') || (typeof msg.raw_output === 'string' ? msg.raw_output : '') || ''
|
||||
}],
|
||||
metadata: {
|
||||
systemSubtype: 'git_operation'
|
||||
}
|
||||
};
|
||||
} else if (msg.subtype === 'git_error') {
|
||||
return {
|
||||
id: msg.id || `git_error_msg_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{
|
||||
type: 'text',
|
||||
content: (typeof msg.message === 'string' ? msg.message : '') || (typeof msg.raw_output === 'string' ? msg.raw_output : '') || ''
|
||||
}],
|
||||
metadata: {
|
||||
systemSubtype: 'git_error'
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private parseResultMessage(msg: ClaudeRawMessage): UnifiedMessage | null {
|
||||
// Handle execution result messages - especially errors
|
||||
if (msg.is_error && msg.result) {
|
||||
return {
|
||||
id: msg.id || `error_msg_${++this.messageIdCounter}`,
|
||||
role: 'system',
|
||||
timestamp: msg.timestamp,
|
||||
segments: [{
|
||||
type: 'text',
|
||||
content: `Error: ${msg.result}`
|
||||
}],
|
||||
metadata: {
|
||||
systemSubtype: 'error',
|
||||
duration: msg.duration_ms,
|
||||
cost: msg.total_cost_usd
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private extractTextContent(msg: ClaudeRawMessage): string {
|
||||
// Handle Claude format: message.content as array of content blocks
|
||||
if (msg.message?.content && Array.isArray(msg.message.content)) {
|
||||
return msg.message.content
|
||||
.filter((block: ContentBlock) => block.type === 'text')
|
||||
.map((block: ContentBlock) => block.text || '')
|
||||
.join('\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
// Handle direct string content
|
||||
if (typeof msg.message?.content === 'string') {
|
||||
return msg.message.content.trim();
|
||||
}
|
||||
|
||||
// Handle direct content field
|
||||
if (typeof msg.content === 'string') {
|
||||
return msg.content.trim();
|
||||
}
|
||||
|
||||
// Handle non-string content by converting to string
|
||||
if (msg.content && typeof msg.content === 'object') {
|
||||
return JSON.stringify(msg.content);
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
supportsStreaming(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
supportsThinking(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
supportsToolCalls(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
getAgentName(): string {
|
||||
return 'Claude';
|
||||
}
|
||||
}
|
||||
@ -1,89 +0,0 @@
|
||||
// Session information interface
|
||||
export interface SessionInfoData {
|
||||
type?: string; // Make type optional for flexibility
|
||||
initialPrompt?: string;
|
||||
codexCommand?: string;
|
||||
claudeCommand?: string;
|
||||
worktreePath?: string;
|
||||
model?: string;
|
||||
modelProvider?: string;
|
||||
approvalPolicy?: string;
|
||||
sandboxMode?: boolean | string;
|
||||
permissionMode?: string;
|
||||
resumeSessionId?: string;
|
||||
isResume?: boolean;
|
||||
timestamp?: string;
|
||||
[key: string]: unknown; // Allow any additional properties
|
||||
}
|
||||
|
||||
// Generic system info that can contain various types
|
||||
export type SystemInfoData = SessionInfoData | {
|
||||
type?: string;
|
||||
[key: string]: unknown; // Allow any additional properties
|
||||
};
|
||||
|
||||
// Unified message structure that all agents transform to
|
||||
export interface UnifiedMessage {
|
||||
id: string;
|
||||
role: 'user' | 'assistant' | 'system';
|
||||
timestamp: string;
|
||||
segments: MessageSegment[];
|
||||
metadata?: {
|
||||
agent?: string;
|
||||
model?: string;
|
||||
duration?: number;
|
||||
tokens?: number;
|
||||
cost?: number;
|
||||
systemSubtype?: string;
|
||||
sessionInfo?: SessionInfoData;
|
||||
[key: string]: unknown; // Allow any additional metadata
|
||||
};
|
||||
}
|
||||
|
||||
export type MessageSegment =
|
||||
| { type: 'text'; content: string }
|
||||
| { type: 'tool_call'; tool: ToolCall }
|
||||
| { type: 'tool_result'; result: ToolResult & { toolCallId: string } }
|
||||
| { type: 'system_info'; info: SystemInfoData }
|
||||
| { type: 'thinking'; content: string }
|
||||
| { type: 'diff'; diff: string }
|
||||
| { type: 'error'; error: { message: string; details?: string } };
|
||||
|
||||
export interface ToolCall {
|
||||
id: string;
|
||||
name: string;
|
||||
input?: Record<string, unknown>; // Tool inputs can have various shapes
|
||||
result?: ToolResult;
|
||||
status: 'pending' | 'success' | 'error';
|
||||
isSubAgent?: boolean;
|
||||
subAgentType?: string;
|
||||
parentToolId?: string;
|
||||
childToolCalls?: ToolCall[];
|
||||
}
|
||||
|
||||
export interface ToolResult {
|
||||
content: string;
|
||||
isError?: boolean;
|
||||
metadata?: {
|
||||
exitCode?: number;
|
||||
duration?: number;
|
||||
[key: string]: unknown; // Tool result metadata can have various shapes
|
||||
};
|
||||
}
|
||||
|
||||
// Message transformer interface for converting agent-specific formats to unified format
|
||||
export interface MessageTransformer {
|
||||
// Transform raw agent messages to unified format
|
||||
transform(rawMessages: unknown[]): UnifiedMessage[];
|
||||
|
||||
// Parse a single message
|
||||
parseMessage(raw: unknown): UnifiedMessage | null;
|
||||
|
||||
// Agent-specific capabilities
|
||||
supportsStreaming(): boolean;
|
||||
supportsThinking(): boolean;
|
||||
supportsToolCalls(): boolean;
|
||||
|
||||
// Get agent name for display
|
||||
getAgentName(): string;
|
||||
}
|
||||
@ -1,299 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { AIPanelProps, RichOutputSettings } from '../ai/AbstractAIPanel';
|
||||
import { RichOutputWithSidebar } from './RichOutputWithSidebar';
|
||||
import { MessagesView } from '../ai/MessagesView';
|
||||
import { SessionStats } from './SessionStats';
|
||||
import { ClaudeInputWithImages } from './ClaudeInputWithImages';
|
||||
import { useClaudePanel } from '../../../hooks/useClaudePanel';
|
||||
import { ClaudeSettingsPanel } from './ClaudeSettingsPanel';
|
||||
import { ClaudeMessageTransformer } from '../ai/transformers/ClaudeMessageTransformer';
|
||||
import { Settings } from 'lucide-react';
|
||||
import { useConfigStore } from '../../../stores/configStore';
|
||||
import type { ClaudePanelState } from '../../../../../shared/types/panels';
|
||||
import { ResizablePanel } from '../../ResizablePanel';
|
||||
|
||||
export const ClaudePanel: React.FC<AIPanelProps> = React.memo(({ panel, isActive }) => {
|
||||
const hook = useClaudePanel(panel.id, isActive);
|
||||
const [activeView, setActiveView] = useState<'richOutput' | 'messages' | 'stats'>('richOutput');
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
const [richOutputSettings, setRichOutputSettings] = useState(() => {
|
||||
const saved = localStorage.getItem('richOutputSettings');
|
||||
return saved ? JSON.parse(saved) : {
|
||||
showToolCalls: true,
|
||||
compactMode: false,
|
||||
collapseTools: true, // Changed to true for collapsed by default
|
||||
showThinking: true,
|
||||
showSessionInit: false,
|
||||
};
|
||||
});
|
||||
|
||||
// Create transformer once and memoize it
|
||||
const transformer = React.useMemo(() => new ClaudeMessageTransformer(), []);
|
||||
const activeSession = hook.activeSession;
|
||||
const devModeEnabled = useConfigStore((state) => state.config?.devMode ?? false);
|
||||
const showDebugTabs = devModeEnabled;
|
||||
|
||||
const claudePanelState = (panel.state.customState as ClaudePanelState | undefined) ?? {};
|
||||
const contextUsage = claudePanelState.contextUsage ?? null;
|
||||
const autoContextRunState = claudePanelState.autoContextRunState ?? 'idle';
|
||||
const isContextUpdating = autoContextRunState === 'running';
|
||||
const contextDisplay = contextUsage ?? '-- tokens (--%)';
|
||||
|
||||
// Extract and store slash commands when we get JSON messages with init
|
||||
useEffect(() => {
|
||||
if (!activeSession) return;
|
||||
|
||||
const handleSlashCommandsFromMessages = () => {
|
||||
const jsonMessages = activeSession.jsonMessages || [];
|
||||
|
||||
// Look for init message with slash_commands
|
||||
const initMessage = jsonMessages.find((msg: { type?: string; subtype?: string; slash_commands?: string[] }) =>
|
||||
msg.type === 'system' && msg.subtype === 'init' && msg.slash_commands
|
||||
);
|
||||
|
||||
if (initMessage && Array.isArray(initMessage.slash_commands)) {
|
||||
console.log('[slash-debug] Found init message with slash commands for Crystal session:', activeSession.id);
|
||||
console.log('[slash-debug] Commands:', initMessage.slash_commands);
|
||||
|
||||
try {
|
||||
const slashCommandsKey = `slashCommands_${activeSession.id}`;
|
||||
localStorage.setItem(slashCommandsKey, JSON.stringify(initMessage.slash_commands));
|
||||
console.log('[slash-debug] Stored slash commands for Crystal session:', activeSession.id);
|
||||
} catch (e) {
|
||||
console.warn('[slash-debug] Failed to store slash commands for Crystal session:', e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
handleSlashCommandsFromMessages();
|
||||
}, [activeSession?.jsonMessages, activeSession?.id]);
|
||||
|
||||
const handleRichOutputSettingsChange = (newSettings: RichOutputSettings) => {
|
||||
setRichOutputSettings(newSettings);
|
||||
localStorage.setItem('richOutputSettings', JSON.stringify(newSettings));
|
||||
};
|
||||
|
||||
const toggleSettings = () => {
|
||||
setShowSettings(!showSettings);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!devModeEnabled && activeView !== 'richOutput') {
|
||||
setActiveView('richOutput');
|
||||
}
|
||||
}, [devModeEnabled, activeView]);
|
||||
|
||||
if (!activeSession) {
|
||||
return (
|
||||
<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">Claude Panel</h2>
|
||||
<p className="text-sm">No active session</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full bg-background">
|
||||
{/* Header */}
|
||||
{showDebugTabs && (
|
||||
<div className="border-b border-border-primary bg-surface-primary shadow-sm">
|
||||
<div className="flex items-center justify-between px-4 h-12">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex">
|
||||
<button
|
||||
onClick={() => setActiveView('richOutput')}
|
||||
className={`px-4 py-2 text-sm font-medium transition-colors relative ${
|
||||
activeView === 'richOutput'
|
||||
? 'text-text-primary'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
Output
|
||||
{activeView === 'richOutput' && (
|
||||
<div className="absolute bottom-0 left-0 right-0 h-0.5 bg-interactive" />
|
||||
)}
|
||||
</button>
|
||||
{devModeEnabled && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => setActiveView('messages')}
|
||||
className={`px-4 py-2 text-sm font-medium transition-colors relative ${
|
||||
activeView === 'messages'
|
||||
? 'text-text-primary'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
Messages
|
||||
{activeView === 'messages' && (
|
||||
<div className="absolute bottom-0 left-0 right-0 h-0.5 bg-interactive" />
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveView('stats')}
|
||||
className={`px-4 py-2 text-sm font-medium transition-colors relative ${
|
||||
activeView === 'stats'
|
||||
? 'text-text-primary'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
Stats
|
||||
{activeView === 'stats' && (
|
||||
<div className="absolute bottom-0 left-0 right-0 h-0.5 bg-interactive" />
|
||||
)}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{activeView === 'richOutput' && (
|
||||
<button
|
||||
onClick={toggleSettings}
|
||||
className="p-1.5 rounded hover:bg-surface-hover transition-colors"
|
||||
title="Display settings"
|
||||
>
|
||||
<Settings className="w-4 h-4 text-text-secondary" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main content area */}
|
||||
<ClaudeMainContent
|
||||
panelId={panel.id}
|
||||
activeView={activeView}
|
||||
showDebugTabs={showDebugTabs}
|
||||
devModeEnabled={devModeEnabled}
|
||||
activeSession={activeSession}
|
||||
richOutputSettings={richOutputSettings}
|
||||
handleRichOutputSettingsChange={handleRichOutputSettingsChange}
|
||||
transformer={transformer}
|
||||
toggleSettings={toggleSettings}
|
||||
/>
|
||||
|
||||
{/* Settings Panel */}
|
||||
{showSettings && (
|
||||
<ClaudeSettingsPanel
|
||||
settings={richOutputSettings}
|
||||
onSettingsChange={handleRichOutputSettingsChange}
|
||||
onClose={() => setShowSettings(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Claude Input - Always visible at bottom if not archived */}
|
||||
{!activeSession.archived && (
|
||||
<ResizablePanel
|
||||
defaultHeight={200}
|
||||
minHeight={140}
|
||||
maxHeight={600}
|
||||
storageKey="claude-input-panel-height"
|
||||
>
|
||||
<ClaudeInputWithImages
|
||||
activeSession={activeSession}
|
||||
viewMode="richOutput"
|
||||
input={hook.input}
|
||||
setInput={hook.setInput}
|
||||
textareaRef={hook.textareaRef}
|
||||
handleTerminalCommand={hook.handleTerminalCommand}
|
||||
handleSendInput={hook.handleSendInput}
|
||||
handleContinueConversation={hook.handleContinueConversation}
|
||||
isStravuConnected={hook.isStravuConnected}
|
||||
setShowStravuSearch={hook.setShowStravuSearch}
|
||||
ultrathink={hook.ultrathink}
|
||||
setUltrathink={hook.setUltrathink}
|
||||
gitCommands={hook.gitCommands}
|
||||
handleCompactContext={hook.handleCompactContext}
|
||||
hasConversationHistory={hook.hasConversationHistory}
|
||||
contextCompacted={hook.contextCompacted}
|
||||
handleCancelRequest={hook.handleStopSession}
|
||||
contextUsageDisplay={contextDisplay}
|
||||
contextUpdating={isContextUpdating}
|
||||
panelId={panel.id}
|
||||
/>
|
||||
</ResizablePanel>
|
||||
)}
|
||||
|
||||
{/* Show archived message if session is archived */}
|
||||
{activeSession.archived && (
|
||||
<div className="bg-surface-secondary border-t border-border-primary px-4 py-3 text-center text-text-muted text-sm">
|
||||
This session is archived. Unarchive it to continue the conversation.
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
ClaudePanel.displayName = 'ClaudePanel';
|
||||
|
||||
// Memoized main content component to prevent unnecessary re-renders when input changes
|
||||
const ClaudeMainContent = React.memo<{
|
||||
panelId: string;
|
||||
activeView: string;
|
||||
showDebugTabs: boolean;
|
||||
devModeEnabled: boolean;
|
||||
activeSession: { id: string; status: string };
|
||||
richOutputSettings: RichOutputSettings;
|
||||
handleRichOutputSettingsChange: (settings: RichOutputSettings) => void;
|
||||
transformer: ClaudeMessageTransformer;
|
||||
toggleSettings: () => void;
|
||||
}>(({ panelId, activeView, showDebugTabs, devModeEnabled, activeSession, richOutputSettings, handleRichOutputSettingsChange, transformer, toggleSettings }) => {
|
||||
return (
|
||||
<div className="flex-1 overflow-hidden relative">
|
||||
{!showDebugTabs && (
|
||||
<div className="absolute top-3 right-3 z-10">
|
||||
<button
|
||||
onClick={toggleSettings}
|
||||
className="p-2 rounded border border-border-primary bg-surface-secondary shadow-sm hover:bg-surface-hover transition-colors"
|
||||
title="Display settings"
|
||||
aria-label="Open Claude settings"
|
||||
>
|
||||
<Settings className="w-4 h-4 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{activeView === 'richOutput' && (
|
||||
<RichOutputWithSidebar
|
||||
panelId={panelId}
|
||||
sessionStatus={activeSession.status}
|
||||
settings={richOutputSettings}
|
||||
onSettingsChange={handleRichOutputSettingsChange}
|
||||
transformer={transformer}
|
||||
/>
|
||||
)}
|
||||
{devModeEnabled && activeView === 'messages' && (
|
||||
<MessagesView
|
||||
panelId={panelId}
|
||||
agentType="claude"
|
||||
outputEventName="session:output"
|
||||
/>
|
||||
)}
|
||||
{devModeEnabled && activeView === 'stats' && (
|
||||
<SessionStats sessionId={activeSession.id} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}, (prevProps, nextProps) => {
|
||||
// Custom comparison function - only re-render if these specific props change
|
||||
return (
|
||||
prevProps.panelId === nextProps.panelId &&
|
||||
prevProps.activeView === nextProps.activeView &&
|
||||
prevProps.showDebugTabs === nextProps.showDebugTabs &&
|
||||
prevProps.devModeEnabled === nextProps.devModeEnabled &&
|
||||
prevProps.activeSession.id === nextProps.activeSession.id &&
|
||||
prevProps.activeSession.status === nextProps.activeSession.status &&
|
||||
prevProps.richOutputSettings === nextProps.richOutputSettings &&
|
||||
prevProps.transformer === nextProps.transformer
|
||||
);
|
||||
});
|
||||
|
||||
ClaudeMainContent.displayName = 'ClaudeMainContent';
|
||||
|
||||
// Default export for lazy loading
|
||||
export default ClaudePanel;
|
||||
@ -1,170 +0,0 @@
|
||||
import React from 'react';
|
||||
import { AbstractAIPanel, AIPanelProps } from '../ai/AbstractAIPanel';
|
||||
import { RichOutputWithSidebar } from './RichOutputWithSidebar';
|
||||
import { MessagesView } from '../ai/MessagesView';
|
||||
import { SessionStats } from './SessionStats';
|
||||
import { ClaudeInputWithImages } from './ClaudeInputWithImages';
|
||||
import { useClaudePanel } from '../../../hooks/useClaudePanel';
|
||||
import { ClaudeSettingsPanel } from './ClaudeSettingsPanel';
|
||||
import { Session } from '../../../types/session';
|
||||
import { MessageTransformer } from '../ai/transformers/MessageTransformer';
|
||||
import { ClaudeMessageTransformer } from '../ai/transformers/ClaudeMessageTransformer';
|
||||
|
||||
class ClaudePanelClass extends AbstractAIPanel<AIPanelProps> {
|
||||
private transformer: MessageTransformer;
|
||||
|
||||
constructor(props: AIPanelProps) {
|
||||
super(props);
|
||||
this.transformer = new ClaudeMessageTransformer();
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
// Initialize hook when component mounts
|
||||
this.updateHook();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: AIPanelProps) {
|
||||
if (prevProps.panel.id !== this.props.panel.id || prevProps.isActive !== this.props.isActive) {
|
||||
this.updateHook();
|
||||
}
|
||||
}
|
||||
|
||||
private updateHook() {
|
||||
// This is a workaround to use hooks in a class component
|
||||
// In a production environment, we'd handle this differently
|
||||
this.forceUpdate();
|
||||
}
|
||||
|
||||
protected getAgentName(): string {
|
||||
return 'Claude';
|
||||
}
|
||||
|
||||
protected getMessageTransformer(): MessageTransformer {
|
||||
return this.transformer;
|
||||
}
|
||||
|
||||
protected getActiveSession(): Session | null {
|
||||
// We need to get the hook value here
|
||||
// This will be set by the wrapper component
|
||||
return (this as any)._hook?.activeSession || null;
|
||||
}
|
||||
|
||||
protected renderRichOutputView(): React.ReactNode {
|
||||
const hook = (this as any)._hook;
|
||||
const activeSession = this.getActiveSession();
|
||||
|
||||
if (!hook || !activeSession) return null;
|
||||
|
||||
return (
|
||||
<RichOutputWithSidebar
|
||||
panelId={this.props.panel.id}
|
||||
sessionStatus={activeSession.status}
|
||||
settings={this.state.richOutputSettings}
|
||||
onSettingsChange={this.handleRichOutputSettingsChange}
|
||||
transformer={this.transformer}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
protected renderMessagesView(): React.ReactNode {
|
||||
return (
|
||||
<MessagesView
|
||||
panelId={this.props.panel.id}
|
||||
agentType="claude"
|
||||
outputEventName="session:output"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
protected renderStatsView(): React.ReactNode {
|
||||
const activeSession = this.getActiveSession();
|
||||
if (!activeSession) return null;
|
||||
|
||||
return <SessionStats sessionId={activeSession.id} />;
|
||||
}
|
||||
|
||||
protected renderInputComponent(): React.ReactNode {
|
||||
const hook = (this as any)._hook;
|
||||
const activeSession = this.getActiveSession();
|
||||
|
||||
if (!hook || !activeSession) return null;
|
||||
|
||||
return (
|
||||
<ClaudeInputWithImages
|
||||
activeSession={activeSession}
|
||||
viewMode="richOutput" // Claude panel always uses richOutput mode
|
||||
input={hook.input}
|
||||
setInput={hook.setInput}
|
||||
textareaRef={hook.textareaRef}
|
||||
handleTerminalCommand={hook.handleTerminalCommand}
|
||||
handleSendInput={hook.handleSendInput}
|
||||
handleContinueConversation={hook.handleContinueConversation}
|
||||
isStravuConnected={hook.isStravuConnected}
|
||||
setShowStravuSearch={hook.setShowStravuSearch}
|
||||
ultrathink={hook.ultrathink}
|
||||
setUltrathink={hook.setUltrathink}
|
||||
gitCommands={hook.gitCommands}
|
||||
handleCompactContext={hook.handleCompactContext}
|
||||
hasConversationHistory={hook.hasConversationHistory}
|
||||
contextCompacted={hook.contextCompacted}
|
||||
handleCancelRequest={hook.handleStopSession}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
protected renderSettingsPanel(): React.ReactNode {
|
||||
return (
|
||||
<ClaudeSettingsPanel
|
||||
settings={this.state.richOutputSettings}
|
||||
onSettingsChange={this.handleRichOutputSettingsChange}
|
||||
onClose={() => this.toggleSettings()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Override to ensure localStorage key remains 'richOutputSettings' for backwards compatibility
|
||||
protected loadRichOutputSettings() {
|
||||
const saved = localStorage.getItem('richOutputSettings');
|
||||
return saved ? JSON.parse(saved) : {
|
||||
showToolCalls: true,
|
||||
compactMode: false,
|
||||
collapseTools: false,
|
||||
showThinking: true,
|
||||
showSessionInit: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Override to ensure localStorage key remains 'richOutputSettings' for backwards compatibility
|
||||
protected handleRichOutputSettingsChange = (newSettings: any) => {
|
||||
this.setState({ richOutputSettings: newSettings });
|
||||
localStorage.setItem('richOutputSettings', JSON.stringify(newSettings));
|
||||
};
|
||||
}
|
||||
|
||||
// Functional wrapper to use hooks with class component
|
||||
export const ClaudePanel: React.FC<AIPanelProps> = (props) => {
|
||||
const hook = useClaudePanel(props.panel.id, props.isActive);
|
||||
|
||||
// Create a ref to store the class instance
|
||||
const classRef = React.useRef<ClaudePanelClass | null>(null);
|
||||
|
||||
// Always update the hook reference when it changes
|
||||
if (classRef.current) {
|
||||
(classRef.current as any)._hook = hook;
|
||||
}
|
||||
|
||||
return (
|
||||
<ClaudePanelClass
|
||||
{...props}
|
||||
ref={(ref) => {
|
||||
classRef.current = ref;
|
||||
if (ref) {
|
||||
(ref as any)._hook = hook;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Default export for lazy loading
|
||||
export default ClaudePanel;
|
||||
@ -1,115 +0,0 @@
|
||||
import React from 'react';
|
||||
import { Wrench, Brain, Terminal, Maximize2, Package } from 'lucide-react';
|
||||
import { SwitchSimple } from '../../ui/SwitchSimple';
|
||||
import { RichOutputSettings } from '../ai/AbstractAIPanel';
|
||||
|
||||
interface ClaudeSettingsPanelProps {
|
||||
settings: RichOutputSettings;
|
||||
onSettingsChange: (settings: RichOutputSettings) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
export const ClaudeSettingsPanel: React.FC<ClaudeSettingsPanelProps> = ({
|
||||
settings,
|
||||
onSettingsChange,
|
||||
onClose,
|
||||
}) => {
|
||||
const toggleSetting = (key: keyof RichOutputSettings) => {
|
||||
const newSettings = { ...settings, [key]: !settings[key] };
|
||||
onSettingsChange(newSettings);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop to close settings when clicking outside */}
|
||||
<div
|
||||
className="absolute inset-0 z-20"
|
||||
onClick={onClose}
|
||||
/>
|
||||
|
||||
{/* Settings Dropdown - positioned relative to the panel */}
|
||||
<div className="absolute top-10 right-4 w-80 z-30 bg-surface-primary border border-border-primary rounded-lg shadow-lg animate-in fade-in slide-in-from-top-1 duration-200">
|
||||
<div className="p-4">
|
||||
<div className="space-y-4">
|
||||
{/* Content Display Settings */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-text-tertiary uppercase tracking-wider mb-2">Content</h4>
|
||||
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between py-1.5 hover:bg-surface-hover rounded px-2 -mx-2 transition-colors">
|
||||
<div className="flex items-center gap-2">
|
||||
<Wrench className="w-3.5 h-3.5 text-text-tertiary" />
|
||||
<span className="text-sm text-text-primary">Tool Calls</span>
|
||||
</div>
|
||||
<SwitchSimple
|
||||
checked={settings.showToolCalls}
|
||||
onCheckedChange={() => toggleSetting('showToolCalls')}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-1.5 hover:bg-surface-hover rounded px-2 -mx-2 transition-colors">
|
||||
<div className="flex items-center gap-2">
|
||||
<Brain className="w-3.5 h-3.5 text-text-tertiary" />
|
||||
<span className="text-sm text-text-primary">Thinking Process</span>
|
||||
</div>
|
||||
<SwitchSimple
|
||||
checked={settings.showThinking}
|
||||
onCheckedChange={() => toggleSetting('showThinking')}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-1.5 hover:bg-surface-hover rounded px-2 -mx-2 transition-colors">
|
||||
<div className="flex items-center gap-2">
|
||||
<Terminal className="w-3.5 h-3.5 text-text-tertiary" />
|
||||
<span className="text-sm text-text-primary">Session Info</span>
|
||||
</div>
|
||||
<SwitchSimple
|
||||
checked={settings.showSessionInit}
|
||||
onCheckedChange={() => toggleSetting('showSessionInit')}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-border-primary"></div>
|
||||
|
||||
{/* Layout Settings */}
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-medium text-text-tertiary uppercase tracking-wider mb-2">Layout</h4>
|
||||
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-center justify-between py-1.5 hover:bg-surface-hover rounded px-2 -mx-2 transition-colors">
|
||||
<div className="flex items-center gap-2">
|
||||
<Maximize2 className="w-3.5 h-3.5 text-text-tertiary" />
|
||||
<span className="text-sm text-text-primary">Compact View</span>
|
||||
</div>
|
||||
<SwitchSimple
|
||||
checked={settings.compactMode}
|
||||
onCheckedChange={() => toggleSetting('compactMode')}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between py-1.5 hover:bg-surface-hover rounded px-2 -mx-2 transition-colors">
|
||||
<div className="flex items-center gap-2">
|
||||
<Package className="w-3.5 h-3.5 text-text-tertiary" />
|
||||
<span className="text-sm text-text-primary">Minimize Tools</span>
|
||||
</div>
|
||||
<SwitchSimple
|
||||
checked={settings.collapseTools}
|
||||
onCheckedChange={() => toggleSetting('collapseTools')}
|
||||
size="sm"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@ -1,243 +0,0 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { formatDistanceToNow } from '../../../utils/formatters';
|
||||
import { formatDuration, getTimeDifference, isValidTimestamp, parseTimestamp } from '../../../utils/timestampUtils';
|
||||
import { API } from '../../../utils/api';
|
||||
import { PromptDetailModal } from '../../PromptDetailModal';
|
||||
// import type { Session } from '../../../types/session';
|
||||
|
||||
interface PromptMarker {
|
||||
id: number;
|
||||
session_id?: string;
|
||||
panel_id?: string;
|
||||
prompt_text: string;
|
||||
output_index: number;
|
||||
output_line?: number;
|
||||
timestamp: string;
|
||||
completion_timestamp?: string;
|
||||
}
|
||||
|
||||
interface PromptNavigationProps {
|
||||
panelId: string;
|
||||
onNavigateToPrompt: (marker: PromptMarker, index: number) => void;
|
||||
}
|
||||
|
||||
export function PromptNavigation({ panelId, 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, setActiveSession] = useState<Session | undefined>(undefined);
|
||||
|
||||
const calculateDuration = (currentPrompt: PromptMarker, currentIndex: number): string => {
|
||||
try {
|
||||
const isLast = currentIndex === prompts.length - 1;
|
||||
|
||||
// Validate the current prompt's timestamp
|
||||
if (!isValidTimestamp(currentPrompt.timestamp)) {
|
||||
console.warn('Invalid timestamp for prompt:', currentPrompt.timestamp);
|
||||
return '';
|
||||
}
|
||||
|
||||
// If we have a completion_timestamp (assistant response time), use it
|
||||
if (currentPrompt.completion_timestamp && isValidTimestamp(currentPrompt.completion_timestamp)) {
|
||||
const durationMs = getTimeDifference(currentPrompt.timestamp, currentPrompt.completion_timestamp);
|
||||
|
||||
if (durationMs >= 0) {
|
||||
return formatDuration(durationMs);
|
||||
}
|
||||
}
|
||||
|
||||
// For the last prompt without completion, show elapsed time
|
||||
if (isLast && !currentPrompt.completion_timestamp) {
|
||||
const startTime = parseTimestamp(currentPrompt.timestamp);
|
||||
const now = new Date();
|
||||
const durationMs = now.getTime() - startTime.getTime();
|
||||
|
||||
if (durationMs >= 0) {
|
||||
// Show it's still waiting for response
|
||||
return formatDuration(durationMs) + ' (waiting)';
|
||||
}
|
||||
}
|
||||
|
||||
// If completed but no duration available
|
||||
if (currentPrompt.completion_timestamp) {
|
||||
return 'completed';
|
||||
}
|
||||
|
||||
return '';
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error calculating duration:', error);
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
const fetchPrompts = useCallback(async () => {
|
||||
if (!panelId) return;
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const response = await API.panels.getPrompts(panelId);
|
||||
if (response.success) {
|
||||
setPrompts(response.data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching prompt markers:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [panelId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!panelId) return;
|
||||
fetchPrompts();
|
||||
}, [panelId, fetchPrompts]);
|
||||
|
||||
// Listen for new prompts being added
|
||||
useEffect(() => {
|
||||
if (!panelId) return;
|
||||
|
||||
const unsubscribe = window.electronAPI?.events?.onPanelPromptAdded?.((data: { panelId: string; content: string }) => {
|
||||
if (data.panelId === panelId) {
|
||||
// Refresh the prompts list when a new prompt is added to this panel
|
||||
fetchPrompts();
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (unsubscribe) {
|
||||
unsubscribe();
|
||||
}
|
||||
};
|
||||
}, [panelId, fetchPrompts]);
|
||||
|
||||
// Listen for assistant responses to stop duration timers
|
||||
useEffect(() => {
|
||||
if (!panelId) return;
|
||||
|
||||
const unsubscribe = window.electronAPI?.events?.onPanelResponseAdded?.((data: { panelId: string; content: string }) => {
|
||||
console.log('[PromptNavigation] Received panel:response-added event for panel:', data.panelId, 'current panel:', panelId);
|
||||
if (data.panelId === panelId) {
|
||||
console.log('[PromptNavigation] Refreshing prompts after assistant response');
|
||||
// Refresh the prompts list when an assistant response is added
|
||||
// This will update completion_timestamps and stop the duration from incrementing
|
||||
fetchPrompts();
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (unsubscribe) {
|
||||
unsubscribe();
|
||||
}
|
||||
};
|
||||
}, [panelId, fetchPrompts]);
|
||||
|
||||
// Use requestAnimationFrame for smooth UI updates for ongoing durations
|
||||
useEffect(() => {
|
||||
// Only run the animation if there's a prompt without a completion timestamp
|
||||
const hasOngoingPrompt = prompts.length > 0 &&
|
||||
prompts[prompts.length - 1] &&
|
||||
!prompts[prompts.length - 1].completion_timestamp;
|
||||
|
||||
if (!hasOngoingPrompt) {
|
||||
return; // No need to animate if there's no ongoing prompt
|
||||
}
|
||||
|
||||
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);
|
||||
}, [prompts]);
|
||||
|
||||
const handlePromptClick = (marker: PromptMarker, index: number) => {
|
||||
setSelectedPromptId(marker.id);
|
||||
onNavigateToPrompt(marker, index);
|
||||
};
|
||||
|
||||
const handlePromptDoubleClick = (marker: PromptMarker, index: number) => {
|
||||
setModalPrompt({ prompt: marker, index });
|
||||
};
|
||||
|
||||
if (isLoading && prompts.length === 0) {
|
||||
return (
|
||||
<div className="w-64 bg-surface-secondary border-l border-border-primary p-4">
|
||||
<h3 className="font-semibold text-text-primary mb-4">Prompt History</h3>
|
||||
<div className="text-text-tertiary text-sm">Loading prompts...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="w-64 bg-surface-secondary border-l border-border-primary flex flex-col h-full">
|
||||
<div className="p-4 border-b border-border-primary">
|
||||
<h3 className="font-semibold text-text-primary">Prompt History</h3>
|
||||
<p className="text-xs text-text-tertiary 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-text-tertiary 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, index)}
|
||||
onDoubleClick={() => handlePromptDoubleClick(marker, index)}
|
||||
className={`w-full text-left p-3 rounded-lg transition-colors ${
|
||||
selectedPromptId === marker.id
|
||||
? 'bg-interactive/20 border-interactive border'
|
||||
: 'hover:bg-bg-hover border border-transparent'
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-start space-x-2">
|
||||
<span className="text-interactive font-mono text-sm mt-0.5">
|
||||
#{index + 1}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm text-text-primary line-clamp-2">
|
||||
{marker.prompt_text}
|
||||
</div>
|
||||
<div className="flex items-center space-x-2 text-xs text-text-tertiary mt-1">
|
||||
<span>{formatDistanceToNow(parseTimestamp(marker.timestamp))} ago</span>
|
||||
{calculateDuration(marker, index) && (
|
||||
<>
|
||||
<span className="text-text-tertiary">•</span>
|
||||
<span className="font-medium text-text-secondary">
|
||||
{calculateDuration(marker, index)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{modalPrompt && (
|
||||
<PromptDetailModal
|
||||
prompt={modalPrompt.prompt}
|
||||
promptIndex={modalPrompt.index}
|
||||
onClose={() => setModalPrompt(null)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@ -1,121 +0,0 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { ChevronLeft, ChevronRight, History } from 'lucide-react';
|
||||
import { RichOutputView } from '../ai/RichOutputView';
|
||||
import { PromptNavigation } from './PromptNavigation';
|
||||
import { cn } from '../../../utils/cn';
|
||||
import { RichOutputSettings } from '../ai/AbstractAIPanel';
|
||||
import { MessageTransformer } from '../ai/transformers/MessageTransformer';
|
||||
import { ClaudeMessageTransformer } from '../ai/transformers/ClaudeMessageTransformer';
|
||||
import { CodexMessageTransformer } from '../ai/transformers/CodexMessageTransformer';
|
||||
|
||||
interface RichOutputWithSidebarProps {
|
||||
panelId?: string;
|
||||
sessionId?: string; // Support both for backward compatibility
|
||||
sessionStatus?: string;
|
||||
model?: string;
|
||||
settings?: RichOutputSettings;
|
||||
onSettingsChange?: (settings: RichOutputSettings) => void;
|
||||
showSettings?: boolean;
|
||||
onSettingsClick?: () => void;
|
||||
transformer?: MessageTransformer;
|
||||
showSystemMessages?: boolean;
|
||||
}
|
||||
|
||||
export const RichOutputWithSidebar: React.FC<RichOutputWithSidebarProps> = React.memo(({
|
||||
panelId,
|
||||
sessionId,
|
||||
sessionStatus,
|
||||
settings,
|
||||
transformer,
|
||||
showSystemMessages = true,
|
||||
}) => {
|
||||
// Use panelId if available, otherwise fall back to sessionId for backward compatibility
|
||||
const id = panelId || sessionId;
|
||||
if (!id) {
|
||||
throw new Error('RichOutputWithSidebar requires either panelId or sessionId');
|
||||
}
|
||||
|
||||
// Create panel-specific localStorage keys
|
||||
const sidebarCollapsedKey = `crystal-sidebar-collapsed-${id}`;
|
||||
|
||||
// Load collapsed state from localStorage (keyed by panel ID)
|
||||
const [isCollapsed, setIsCollapsed] = useState(() => {
|
||||
const stored = localStorage.getItem(sidebarCollapsedKey);
|
||||
return stored === 'true';
|
||||
});
|
||||
|
||||
const richOutputRef = useRef<{ scrollToPrompt: (promptIndex: number) => void }>(null);
|
||||
|
||||
// Save collapsed state to localStorage when it changes (keyed by panel ID)
|
||||
useEffect(() => {
|
||||
localStorage.setItem(sidebarCollapsedKey, String(isCollapsed));
|
||||
}, [isCollapsed, sidebarCollapsedKey]);
|
||||
|
||||
// Override the navigation handler to scroll within rich output
|
||||
const handleNavigateToPrompt = useCallback((_marker: { id: number }, promptIndex: number) => {
|
||||
// Use the prompt index to scroll to the right message
|
||||
if (richOutputRef.current && promptIndex >= 0) {
|
||||
richOutputRef.current.scrollToPrompt(promptIndex);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Determine event names and handlers based on transformer type
|
||||
const isCodex = transformer instanceof CodexMessageTransformer;
|
||||
const outputEventName = isCodex ? "codexPanel:output" : "session-output-available";
|
||||
const getOutputsHandler = isCodex ? "codexPanel:getOutputs" : "panels:getJsonMessages";
|
||||
|
||||
return (
|
||||
<div className="flex h-full relative">
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
<RichOutputView
|
||||
ref={richOutputRef}
|
||||
panelId={id}
|
||||
sessionStatus={sessionStatus}
|
||||
settings={settings}
|
||||
messageTransformer={transformer || new ClaudeMessageTransformer()}
|
||||
outputEventName={outputEventName}
|
||||
getOutputsHandler={getOutputsHandler}
|
||||
showSystemMessages={showSystemMessages}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Toggle Button */}
|
||||
<button
|
||||
onClick={() => setIsCollapsed(!isCollapsed)}
|
||||
className={cn(
|
||||
'absolute top-4 z-10 bg-surface-secondary hover:bg-surface-hover',
|
||||
'border border-border-primary rounded-l-lg p-2',
|
||||
'transition-all duration-300 ease-in-out',
|
||||
'flex items-center gap-1 group',
|
||||
isCollapsed ? 'right-0 rounded-r-lg' : 'right-64 -mr-px'
|
||||
)}
|
||||
title={isCollapsed ? 'Show prompt history' : 'Hide prompt history'}
|
||||
>
|
||||
{isCollapsed ? (
|
||||
<>
|
||||
<History className="w-4 h-4 text-text-secondary group-hover:text-text-primary" />
|
||||
<ChevronLeft className="w-4 h-4 text-text-secondary group-hover:text-text-primary" />
|
||||
</>
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 text-text-secondary group-hover:text-text-primary" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Collapsible Sidebar */}
|
||||
<div
|
||||
className={cn(
|
||||
'flex transition-all duration-300 ease-in-out',
|
||||
isCollapsed ? 'w-0' : 'w-64'
|
||||
)}
|
||||
>
|
||||
{!isCollapsed && (
|
||||
<PromptNavigation
|
||||
panelId={id}
|
||||
onNavigateToPrompt={handleNavigateToPrompt}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@ -1,457 +0,0 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { API } from '../../../utils/api';
|
||||
import { Activity, FileText, Clock, Zap, GitBranch, Hash, MessageSquare, Code, TrendingUp, Server, Wrench } from 'lucide-react';
|
||||
|
||||
interface SessionStatsProps {
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
interface ToolUsageStats {
|
||||
name: string;
|
||||
count: number;
|
||||
totalDuration: number;
|
||||
avgDuration: number;
|
||||
totalInputTokens: number;
|
||||
totalOutputTokens: number;
|
||||
}
|
||||
|
||||
interface SessionStatistics {
|
||||
session: {
|
||||
id: string;
|
||||
name: string;
|
||||
status: string;
|
||||
model: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
duration: number;
|
||||
worktreePath: string;
|
||||
branch?: string;
|
||||
};
|
||||
tokens: {
|
||||
totalInputTokens: number;
|
||||
totalOutputTokens: number;
|
||||
totalCacheReadTokens: number;
|
||||
totalCacheCreationTokens: number;
|
||||
messageCount: number;
|
||||
};
|
||||
files: {
|
||||
totalFilesChanged: number;
|
||||
totalLinesAdded: number;
|
||||
totalLinesDeleted: number;
|
||||
filesModified: string[];
|
||||
executionCount: number;
|
||||
};
|
||||
activity: {
|
||||
promptCount: number;
|
||||
messageCount: number;
|
||||
outputCounts: {
|
||||
json: number;
|
||||
stdout: number;
|
||||
stderr: number;
|
||||
};
|
||||
lastActivity: string;
|
||||
};
|
||||
toolUsage?: {
|
||||
tools: ToolUsageStats[];
|
||||
totalToolCalls: number;
|
||||
};
|
||||
}
|
||||
|
||||
export const SessionStats: React.FC<SessionStatsProps> = ({ sessionId }) => {
|
||||
if (!sessionId) {
|
||||
throw new Error('SessionStats requires sessionId');
|
||||
}
|
||||
|
||||
const [statistics, setStatistics] = useState<SessionStatistics | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const loadStatistics = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const response = await API.sessions.getStatistics(sessionId);
|
||||
if (response.success && response.data) {
|
||||
setStatistics(response.data);
|
||||
} else {
|
||||
setError(response.error || 'Failed to load statistics');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load session statistics:', err);
|
||||
setError('Failed to load session statistics');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadStatistics();
|
||||
|
||||
// Refresh every 30 seconds if session is active
|
||||
const interval = setInterval(() => {
|
||||
if (statistics?.session.status === 'running' || statistics?.session.status === 'waiting') {
|
||||
loadStatistics();
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [sessionId, statistics?.session.status]);
|
||||
|
||||
const formatDuration = (ms: number): string => {
|
||||
const seconds = Math.floor(ms / 1000);
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const hours = Math.floor(minutes / 60);
|
||||
const days = Math.floor(hours / 24);
|
||||
|
||||
if (days > 0) {
|
||||
return `${days}d ${hours % 24}h ${minutes % 60}m`;
|
||||
} else if (hours > 0) {
|
||||
return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
|
||||
} else if (minutes > 0) {
|
||||
return `${minutes}m ${seconds % 60}s`;
|
||||
} else {
|
||||
return `${seconds}s`;
|
||||
}
|
||||
};
|
||||
|
||||
const formatNumber = (num: number): string => {
|
||||
if (num >= 1000000) {
|
||||
return `${(num / 1000000).toFixed(2)}M`;
|
||||
} else if (num >= 1000) {
|
||||
return `${(num / 1000).toFixed(1)}K`;
|
||||
}
|
||||
return num.toString();
|
||||
};
|
||||
|
||||
const calculateCost = (tokens: SessionStatistics['tokens']): string => {
|
||||
// Rough estimate based on Claude pricing (as of knowledge cutoff)
|
||||
// Sonnet: $3 per million input tokens, $15 per million output tokens
|
||||
const inputCost = (tokens.totalInputTokens / 1000000) * 3;
|
||||
const outputCost = (tokens.totalOutputTokens / 1000000) * 15;
|
||||
const totalCost = inputCost + outputCost;
|
||||
|
||||
if (totalCost < 0.01) {
|
||||
return '<$0.01';
|
||||
}
|
||||
return `$${totalCost.toFixed(2)}`;
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center p-8">
|
||||
<div className="text-center">
|
||||
<div className="text-text-tertiary mb-2">Loading statistics...</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex-1 flex items-center justify-center p-8">
|
||||
<div className="text-center">
|
||||
<div className="text-status-error mb-2">Failed to load statistics</div>
|
||||
<div className="text-sm text-text-quaternary">{error}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!statistics) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { session, tokens, files, activity } = statistics;
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto bg-surface-primary p-6">
|
||||
<div className="max-w-6xl mx-auto space-y-6">
|
||||
{/* Header */}
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-6">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold text-text-primary mb-2">{session.name}</h2>
|
||||
<div className="flex items-center gap-4 text-sm text-text-secondary">
|
||||
<span className="flex items-center gap-1">
|
||||
<Server className="w-4 h-4" />
|
||||
{session.model}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<GitBranch className="w-4 h-4" />
|
||||
{session.branch || 'main'}
|
||||
</span>
|
||||
<span className={`px-2 py-1 rounded text-xs font-medium ${
|
||||
session.status === 'running' ? 'bg-status-success/10 text-status-success' :
|
||||
session.status === 'waiting' ? 'bg-status-warning/10 text-status-warning' :
|
||||
session.status === 'error' ? 'bg-status-error/10 text-status-error' :
|
||||
'bg-surface-hover text-text-tertiary'
|
||||
}`}>
|
||||
{session.status.toUpperCase()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-2xl font-bold text-text-primary">{formatDuration(session.duration)}</div>
|
||||
<div className="text-sm text-text-quaternary">Session Duration</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Token Usage */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<Zap className="w-5 h-5 text-status-info" />
|
||||
<span className="text-xs text-text-quaternary">Input</span>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-text-primary mb-1">
|
||||
{formatNumber(tokens.totalInputTokens)}
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary">tokens</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<TrendingUp className="w-5 h-5 text-status-success" />
|
||||
<span className="text-xs text-text-quaternary">Output</span>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-text-primary mb-1">
|
||||
{formatNumber(tokens.totalOutputTokens)}
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary">tokens</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<Activity className="w-5 h-5 text-status-warning" />
|
||||
<span className="text-xs text-text-quaternary">Cache Hit</span>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-text-primary mb-1">
|
||||
{tokens.totalCacheReadTokens > 0
|
||||
? `${((tokens.totalCacheReadTokens / (tokens.totalInputTokens || 1)) * 100).toFixed(0)}%`
|
||||
: '0%'
|
||||
}
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary">
|
||||
{formatNumber(tokens.totalCacheReadTokens)} cached
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<Hash className="w-5 h-5 text-accent-primary" />
|
||||
<span className="text-xs text-text-quaternary">Est. Cost</span>
|
||||
</div>
|
||||
<div className="text-2xl font-bold text-text-primary mb-1">
|
||||
{calculateCost(tokens)}
|
||||
</div>
|
||||
<div className="text-xs text-text-tertiary">USD</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Activity Stats */}
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<MessageSquare className="w-5 h-5 text-text-tertiary" />
|
||||
<h3 className="text-sm font-semibold text-text-primary">Conversation</h3>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Prompts</span>
|
||||
<span className="text-sm font-medium text-text-primary">{activity.promptCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Messages</span>
|
||||
<span className="text-sm font-medium text-text-primary">{activity.messageCount}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">JSON Events</span>
|
||||
<span className="text-sm font-medium text-text-primary">{activity.outputCounts.json}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<FileText className="w-5 h-5 text-text-tertiary" />
|
||||
<h3 className="text-sm font-semibold text-text-primary">File Changes</h3>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Files Modified</span>
|
||||
<span className="text-sm font-medium text-text-primary">{files.totalFilesChanged}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Lines Added</span>
|
||||
<span className="text-sm font-medium text-status-success">+{files.totalLinesAdded}</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Lines Deleted</span>
|
||||
<span className="text-sm font-medium text-status-error">-{files.totalLinesDeleted}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Code className="w-5 h-5 text-text-tertiary" />
|
||||
<h3 className="text-sm font-semibold text-text-primary">Performance</h3>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Tokens/Prompt</span>
|
||||
<span className="text-sm font-medium text-text-primary">
|
||||
{activity.promptCount > 0
|
||||
? formatNumber(Math.round((tokens.totalInputTokens + tokens.totalOutputTokens) / activity.promptCount))
|
||||
: '0'
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Lines/Hour</span>
|
||||
<span className="text-sm font-medium text-text-primary">
|
||||
{session.duration > 3600000
|
||||
? Math.round((files.totalLinesAdded + files.totalLinesDeleted) / (session.duration / 3600000))
|
||||
: files.totalLinesAdded + files.totalLinesDeleted
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-text-secondary">Executions</span>
|
||||
<span className="text-sm font-medium text-text-primary">{files.executionCount}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tool Usage Breakdown */}
|
||||
{statistics.toolUsage && statistics.toolUsage.totalToolCalls > 0 && (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center gap-3 mb-4">
|
||||
<Wrench className="w-5 h-5 text-text-tertiary" />
|
||||
<h3 className="text-sm font-semibold text-text-primary">Tool Usage</h3>
|
||||
<span className="text-xs text-text-quaternary">({statistics.toolUsage.totalToolCalls} total calls)</span>
|
||||
</div>
|
||||
|
||||
{/* Tool usage table */}
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left border-b border-border-primary">
|
||||
<th className="pb-2 pr-4 text-text-secondary font-medium">Tool</th>
|
||||
<th className="pb-2 px-2 text-text-secondary font-medium text-right">Uses</th>
|
||||
<th className="pb-2 px-2 text-text-secondary font-medium text-right">Total Time</th>
|
||||
<th className="pb-2 px-2 text-text-secondary font-medium text-right">Avg Time</th>
|
||||
<th className="pb-2 pl-2 text-text-secondary font-medium text-right">% of Calls</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{statistics.toolUsage.tools.slice(0, 10).map((tool) => {
|
||||
const percentage = ((tool.count / statistics.toolUsage!.totalToolCalls) * 100).toFixed(1);
|
||||
return (
|
||||
<tr key={tool.name} className="border-b border-border-primary/50 hover:bg-surface-hover transition-colors">
|
||||
<td className="py-2 pr-4">
|
||||
<span className="font-mono text-text-primary">{tool.name}</span>
|
||||
</td>
|
||||
<td className="py-2 px-2 text-right text-text-primary font-medium">
|
||||
{tool.count}
|
||||
</td>
|
||||
<td className="py-2 px-2 text-right text-text-secondary">
|
||||
{formatDuration(tool.totalDuration)}
|
||||
</td>
|
||||
<td className="py-2 px-2 text-right text-text-secondary">
|
||||
{tool.avgDuration > 0 ? formatDuration(tool.avgDuration) : '-'}
|
||||
</td>
|
||||
<td className="py-2 pl-2 text-right">
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
<div className="w-16 bg-surface-primary rounded-full h-1.5 overflow-hidden">
|
||||
<div
|
||||
className="bg-status-info rounded-full h-1.5 transition-all"
|
||||
style={{ width: `${percentage}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-text-tertiary text-xs w-10 text-right">{percentage}%</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{statistics.toolUsage.tools.length > 10 && (
|
||||
<div className="mt-2 text-xs text-text-quaternary text-center">
|
||||
And {statistics.toolUsage.tools.length - 10} more tools...
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tool usage summary */}
|
||||
<div className="mt-4 pt-4 border-t border-border-primary grid grid-cols-3 gap-4 text-xs">
|
||||
<div>
|
||||
<span className="text-text-quaternary">Most Used</span>
|
||||
<div className="text-text-primary font-medium">
|
||||
{statistics.toolUsage.tools[0]?.name || 'N/A'} ({statistics.toolUsage.tools[0]?.count || 0}x)
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-quaternary">Total Time</span>
|
||||
<div className="text-text-primary font-medium">
|
||||
{formatDuration(statistics.toolUsage.tools.reduce((sum, t) => sum + t.totalDuration, 0))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-quaternary">Unique Tools</span>
|
||||
<div className="text-text-primary font-medium">
|
||||
{statistics.toolUsage.tools.length}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modified Files List */}
|
||||
{files.filesModified.length > 0 && (
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<FileText className="w-5 h-5 text-text-tertiary" />
|
||||
<h3 className="text-sm font-semibold text-text-primary">Modified Files</h3>
|
||||
<span className="text-xs text-text-quaternary">({files.filesModified.length})</span>
|
||||
</div>
|
||||
<div className="max-h-48 overflow-y-auto">
|
||||
<div className="space-y-1">
|
||||
{files.filesModified.map((file, index) => (
|
||||
<div key={index} className="text-sm text-text-secondary font-mono hover:text-text-primary transition-colors">
|
||||
{file}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Timeline */}
|
||||
<div className="bg-surface-secondary rounded-lg border border-border-primary p-4">
|
||||
<div className="flex items-center gap-3 mb-3">
|
||||
<Clock className="w-5 h-5 text-text-tertiary" />
|
||||
<h3 className="text-sm font-semibold text-text-primary">Timeline</h3>
|
||||
</div>
|
||||
<div className="space-y-2 text-sm">
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-text-secondary">Created</span>
|
||||
<span className="font-medium text-text-primary">
|
||||
{new Date(session.createdAt).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-text-secondary">Last Activity</span>
|
||||
<span className="font-medium text-text-primary">
|
||||
{new Date(activity.lastActivity).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,448 +0,0 @@
|
||||
import React, { useState, useCallback, useMemo } from 'react';
|
||||
import { Settings, HelpCircle, Download, RefreshCw, AlertCircle, CheckCircle, Clock, Zap } from 'lucide-react';
|
||||
// import { ToolPanel } from '../../../../../shared/types/panels';
|
||||
import {
|
||||
CliPanel,
|
||||
CliViewMode,
|
||||
CliPanelSettings,
|
||||
CliPanelConfig,
|
||||
getCliPanelConfig,
|
||||
CliProcessStatus
|
||||
} from '../../../../../shared/types/cliPanels';
|
||||
|
||||
/**
|
||||
* Props for the base CLI panel component
|
||||
*/
|
||||
export interface BaseCliPanelProps {
|
||||
/** The panel data */
|
||||
panel: CliPanel;
|
||||
|
||||
/** Whether this panel is currently active */
|
||||
isActive: boolean;
|
||||
|
||||
/** CLI tool ID (claude, aider, etc.) */
|
||||
cliToolId: string;
|
||||
|
||||
/** Current view mode */
|
||||
viewMode: CliViewMode;
|
||||
|
||||
/** View mode change handler */
|
||||
onViewModeChange: (mode: CliViewMode) => void;
|
||||
|
||||
/** Panel settings */
|
||||
settings: CliPanelSettings;
|
||||
|
||||
/** Settings change handler */
|
||||
onSettingsChange: (settings: CliPanelSettings) => void;
|
||||
|
||||
/** Children render function for tool-specific content */
|
||||
children: (props: BaseCliPanelChildProps) => React.ReactNode;
|
||||
|
||||
/** Optional custom header content */
|
||||
headerContent?: React.ReactNode;
|
||||
|
||||
/** Optional custom footer content */
|
||||
footerContent?: React.ReactNode;
|
||||
|
||||
/** Error state */
|
||||
error?: string | null;
|
||||
|
||||
/** Loading state */
|
||||
isLoading?: boolean;
|
||||
|
||||
/** Process status */
|
||||
processStatus?: CliProcessStatus;
|
||||
|
||||
/** Action handlers */
|
||||
onRefresh?: () => void;
|
||||
onExport?: () => void;
|
||||
onHelp?: () => void;
|
||||
onRestart?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Props passed to child components
|
||||
*/
|
||||
export interface BaseCliPanelChildProps {
|
||||
/** Panel ID */
|
||||
panelId: string;
|
||||
|
||||
/** CLI tool ID */
|
||||
cliToolId: string;
|
||||
|
||||
/** Current view mode */
|
||||
viewMode: CliViewMode;
|
||||
|
||||
/** Panel settings */
|
||||
settings: CliPanelSettings;
|
||||
|
||||
/** Whether panel is active */
|
||||
isActive: boolean;
|
||||
|
||||
/** Process status */
|
||||
processStatus?: CliProcessStatus;
|
||||
|
||||
/** CLI panel configuration */
|
||||
config: CliPanelConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Status indicator component
|
||||
*/
|
||||
const StatusIndicator: React.FC<{ status?: CliProcessStatus }> = ({ status }) => {
|
||||
const getStatusInfo = () => {
|
||||
switch (status) {
|
||||
case 'initializing':
|
||||
return { icon: RefreshCw, color: 'text-blue-500', label: 'Initializing...', spinning: true };
|
||||
case 'ready':
|
||||
return { icon: CheckCircle, color: 'text-green-500', label: 'Ready' };
|
||||
case 'processing':
|
||||
return { icon: Zap, color: 'text-yellow-500', label: 'Processing...', spinning: true };
|
||||
case 'waiting':
|
||||
return { icon: Clock, color: 'text-blue-500', label: 'Waiting for input' };
|
||||
case 'error':
|
||||
return { icon: AlertCircle, color: 'text-red-500', label: 'Error' };
|
||||
case 'stopped':
|
||||
return { icon: AlertCircle, color: 'text-gray-500', label: 'Stopped' };
|
||||
case 'restarting':
|
||||
return { icon: RefreshCw, color: 'text-orange-500', label: 'Restarting...', spinning: true };
|
||||
default:
|
||||
return { icon: AlertCircle, color: 'text-gray-400', label: 'Unknown' };
|
||||
}
|
||||
};
|
||||
|
||||
const { icon: Icon, color, label, spinning } = getStatusInfo();
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 text-xs">
|
||||
<Icon
|
||||
className={`w-3.5 h-3.5 ${color} ${spinning ? 'animate-spin' : ''}`}
|
||||
/>
|
||||
<span className={`${color} font-medium`}>{label}</span>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* View mode selector component
|
||||
*/
|
||||
const ViewModeSelector: React.FC<{
|
||||
currentMode: CliViewMode;
|
||||
availableModes: CliViewMode[];
|
||||
onChange: (mode: CliViewMode) => void;
|
||||
}> = ({ currentMode, availableModes, onChange }) => {
|
||||
const getModeLabel = (mode: CliViewMode) => {
|
||||
switch (mode) {
|
||||
case 'output': return 'Output';
|
||||
case 'messages': return 'Messages';
|
||||
case 'stats': return 'Stats';
|
||||
case 'settings': return 'Settings';
|
||||
case 'help': return 'Help';
|
||||
default: return mode;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-xs font-medium text-text-tertiary uppercase tracking-wider">
|
||||
View
|
||||
</span>
|
||||
<div className="inline-flex rounded-lg bg-surface-secondary p-0.5">
|
||||
{availableModes.map((mode) => (
|
||||
<button
|
||||
key={mode}
|
||||
onClick={() => onChange(mode)}
|
||||
className={`px-3 py-1 text-xs font-medium rounded-md transition-all ${
|
||||
currentMode === mode
|
||||
? 'bg-bg-primary text-text-primary shadow-sm'
|
||||
: 'text-text-secondary hover:text-text-primary'
|
||||
}`}
|
||||
>
|
||||
{getModeLabel(mode)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Action button component
|
||||
*/
|
||||
const ActionButton: React.FC<{
|
||||
icon: React.ComponentType<{ className?: string }>;
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
isActive?: boolean;
|
||||
disabled?: boolean;
|
||||
variant?: 'default' | 'primary' | 'danger';
|
||||
}> = ({ icon: Icon, label, onClick, isActive, disabled, variant = 'default' }) => {
|
||||
const getButtonClasses = () => {
|
||||
const base = 'px-2 py-1 rounded-md text-xs transition-all flex items-center gap-1.5';
|
||||
|
||||
if (disabled) {
|
||||
return `${base} text-text-disabled cursor-not-allowed opacity-50`;
|
||||
}
|
||||
|
||||
if (isActive) {
|
||||
return `${base} bg-surface-hover text-text-primary`;
|
||||
}
|
||||
|
||||
switch (variant) {
|
||||
case 'primary':
|
||||
return `${base} text-text-primary hover:bg-surface-hover bg-primary-subtle`;
|
||||
case 'danger':
|
||||
return `${base} text-red-500 hover:bg-red-50 hover:text-red-600`;
|
||||
default:
|
||||
return `${base} text-text-secondary hover:text-text-primary hover:bg-surface-hover`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
className={getButtonClasses()}
|
||||
title={label}
|
||||
>
|
||||
<Icon className="w-3.5 h-3.5" />
|
||||
<span>{label}</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Base CLI panel component providing common UI elements and functionality
|
||||
*
|
||||
* This component serves as the foundation for all CLI tool panels (Claude, Aider, etc.)
|
||||
* providing consistent header, view management, settings, and error handling.
|
||||
*/
|
||||
export const BaseCliPanel: React.FC<BaseCliPanelProps> = ({
|
||||
panel,
|
||||
isActive,
|
||||
cliToolId,
|
||||
viewMode,
|
||||
onViewModeChange,
|
||||
settings,
|
||||
onSettingsChange,
|
||||
children,
|
||||
headerContent,
|
||||
footerContent,
|
||||
error,
|
||||
isLoading,
|
||||
processStatus,
|
||||
onRefresh,
|
||||
onExport,
|
||||
onHelp
|
||||
}) => {
|
||||
const [showSettings, setShowSettings] = useState(false);
|
||||
|
||||
// Get CLI panel configuration
|
||||
const config = useMemo(() => getCliPanelConfig(cliToolId), [cliToolId]);
|
||||
|
||||
// Filter available view modes based on config and features
|
||||
const availableViewModes = useMemo(() => {
|
||||
let modes = config.display.availableViewModes || ['output'];
|
||||
|
||||
// Remove modes that aren't supported by the current configuration
|
||||
if (!config.features.settingsPanel) {
|
||||
modes = modes.filter(m => m !== 'settings');
|
||||
}
|
||||
if (!config.features.statsView) {
|
||||
modes = modes.filter(m => m !== 'stats');
|
||||
}
|
||||
if (!config.features.helpDocumentation) {
|
||||
modes = modes.filter(m => m !== 'help');
|
||||
}
|
||||
|
||||
return modes;
|
||||
}, [config]);
|
||||
|
||||
// Handle settings panel toggle
|
||||
const handleSettingsToggle = useCallback(() => {
|
||||
if (viewMode === 'settings') {
|
||||
// If settings view is active, go back to previous view
|
||||
onViewModeChange('output');
|
||||
} else {
|
||||
setShowSettings(!showSettings);
|
||||
}
|
||||
}, [viewMode, showSettings, onViewModeChange]);
|
||||
|
||||
// Handle error display
|
||||
const errorContent = error && (
|
||||
<div className="bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-lg p-3 mb-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-red-500 mt-0.5 flex-shrink-0" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium text-red-700 dark:text-red-300">
|
||||
{cliToolId.charAt(0).toUpperCase() + cliToolId.slice(1)} Error
|
||||
</p>
|
||||
<p className="text-sm text-red-600 dark:text-red-400 mt-1">
|
||||
{error}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
// Prepare child props
|
||||
const childProps: BaseCliPanelChildProps = {
|
||||
panelId: panel.id,
|
||||
cliToolId,
|
||||
viewMode,
|
||||
settings,
|
||||
isActive,
|
||||
processStatus,
|
||||
config
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full w-full flex flex-col overflow-hidden bg-bg-primary">
|
||||
{/* Panel Header */}
|
||||
<div className="flex items-center justify-between px-4 py-2 border-b border-border-primary bg-surface-primary">
|
||||
<div className="flex items-center gap-4">
|
||||
{/* View Mode Selector */}
|
||||
<ViewModeSelector
|
||||
currentMode={viewMode}
|
||||
availableModes={availableViewModes}
|
||||
onChange={onViewModeChange}
|
||||
/>
|
||||
|
||||
{/* Status Indicator */}
|
||||
<StatusIndicator status={processStatus} />
|
||||
|
||||
{/* Custom Header Content */}
|
||||
{headerContent}
|
||||
</div>
|
||||
|
||||
{/* Action Buttons */}
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Refresh Button */}
|
||||
{onRefresh && (
|
||||
<ActionButton
|
||||
icon={RefreshCw}
|
||||
label="Refresh"
|
||||
onClick={onRefresh}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Export Button */}
|
||||
{onExport && config.features.exportSupport && (
|
||||
<ActionButton
|
||||
icon={Download}
|
||||
label="Export"
|
||||
onClick={onExport}
|
||||
disabled={isLoading}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Help Button */}
|
||||
{onHelp && config.features.helpDocumentation && (
|
||||
<ActionButton
|
||||
icon={HelpCircle}
|
||||
label="Help"
|
||||
onClick={onHelp}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Settings Button */}
|
||||
{config.features.settingsPanel && (
|
||||
<ActionButton
|
||||
icon={Settings}
|
||||
label="Settings"
|
||||
onClick={handleSettingsToggle}
|
||||
isActive={showSettings || viewMode === 'settings'}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="px-4 py-2">
|
||||
{errorContent}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Loading Overlay */}
|
||||
{isLoading && (
|
||||
<div className="absolute inset-0 bg-bg-primary bg-opacity-75 flex items-center justify-center z-10">
|
||||
<div className="flex items-center gap-2 text-text-secondary">
|
||||
<RefreshCw className="w-4 h-4 animate-spin" />
|
||||
<span className="text-sm">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Content Area */}
|
||||
<div className="flex-1 relative min-h-0 overflow-hidden">
|
||||
{children(childProps)}
|
||||
</div>
|
||||
|
||||
{/* Settings Panel Overlay */}
|
||||
{showSettings && viewMode !== 'settings' && config.features.settingsPanel && (
|
||||
<div className="absolute bottom-0 left-0 right-0 bg-surface-primary border-t border-border-primary shadow-lg">
|
||||
<div className="p-4">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<h3 className="text-sm font-medium text-text-primary">
|
||||
{config.display.titleTemplate || 'CLI Panel'} Settings
|
||||
</h3>
|
||||
<button
|
||||
onClick={() => setShowSettings(false)}
|
||||
className="text-text-secondary hover:text-text-primary text-xs"
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Basic settings UI - can be extended by specific tools */}
|
||||
<div className="space-y-3">
|
||||
{/* Model Selector */}
|
||||
{config.display.showModelSelector && (
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-text-secondary mb-1">
|
||||
Model
|
||||
</label>
|
||||
<select
|
||||
value={settings.defaultModel || 'auto'}
|
||||
onChange={(e) => onSettingsChange({ ...settings, defaultModel: e.target.value })}
|
||||
className="w-full px-2 py-1 text-xs border border-border-primary rounded bg-bg-primary"
|
||||
>
|
||||
<option value="auto">Auto</option>
|
||||
{/* Tool-specific models would be populated here */}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Permission Controls */}
|
||||
{config.display.showPermissionControls && (
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-text-secondary mb-1">
|
||||
Permission Mode
|
||||
</label>
|
||||
<select
|
||||
value={settings.defaultPermissionMode || 'ignore'}
|
||||
onChange={(e) => onSettingsChange({
|
||||
...settings,
|
||||
defaultPermissionMode: e.target.value as 'approve' | 'ignore'
|
||||
})}
|
||||
className="w-full px-2 py-1 text-xs border border-border-primary rounded bg-bg-primary"
|
||||
>
|
||||
<option value="ignore">Skip permissions</option>
|
||||
<option value="approve">Approve permissions</option>
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Custom Footer Content */}
|
||||
{footerContent}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default BaseCliPanel;
|
||||
@ -1,157 +0,0 @@
|
||||
import React, { Suspense, lazy, useMemo } from 'react';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
import { ToolPanel } from '../../../../../shared/types/panels';
|
||||
import { CliPanel } from '../../../../../shared/types/cliPanels';
|
||||
import { PanelLoadingFallback } from '../PanelLoadingFallback';
|
||||
|
||||
/**
|
||||
* Props for the CLI panel factory
|
||||
*/
|
||||
export interface CliPanelFactoryProps {
|
||||
/** The panel to render */
|
||||
panel: ToolPanel;
|
||||
|
||||
/** Whether this panel is currently active */
|
||||
isActive: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error boundary component for CLI panels
|
||||
*/
|
||||
class CliPanelErrorBoundary extends React.Component<
|
||||
{ children: React.ReactNode; cliToolId: string },
|
||||
{ hasError: boolean; error: Error | null }
|
||||
> {
|
||||
constructor(props: { children: React.ReactNode; cliToolId: string }) {
|
||||
super(props);
|
||||
this.state = { hasError: false, error: null };
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: Error) {
|
||||
return { hasError: true, error };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
|
||||
console.error(`Error in CLI panel (${this.props.cliToolId}):`, error, errorInfo);
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.hasError) {
|
||||
return (
|
||||
<div className="h-full w-full flex items-center justify-center p-8">
|
||||
<div className="text-center max-w-md">
|
||||
<AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
Panel Error
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary mb-4">
|
||||
An error occurred in the {this.props.cliToolId} panel.
|
||||
</p>
|
||||
<p className="text-xs text-text-tertiary mb-4 font-mono">
|
||||
{this.state.error?.message}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => this.setState({ hasError: false, error: null })}
|
||||
className="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary-hover transition-colors"
|
||||
>
|
||||
Try Again
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loading fallback component - memoized for better performance
|
||||
*/
|
||||
const LoadingFallback: React.FC<{ cliToolId: string }> = React.memo(({ cliToolId }) => (
|
||||
<PanelLoadingFallback
|
||||
panelType={cliToolId}
|
||||
message={`Loading ${cliToolId} panel...`}
|
||||
/>
|
||||
));
|
||||
|
||||
LoadingFallback.displayName = 'CliLoadingFallback';
|
||||
|
||||
// Lazy-loaded CLI panel components
|
||||
const ClaudePanel = lazy(() => import('../claude/ClaudePanel'));
|
||||
const CodexPanel = lazy(() => import('../codex/CodexPanel'));
|
||||
|
||||
/**
|
||||
* Factory component that dynamically renders the appropriate CLI panel
|
||||
*
|
||||
* This component examines the panel type to determine which
|
||||
* specific CLI panel component to render. Currently only supports Claude.
|
||||
*/
|
||||
export const CliPanelFactory: React.FC<CliPanelFactoryProps> = React.memo(({ panel, isActive }) => {
|
||||
// Determine CLI tool ID from panel
|
||||
const cliToolId = useMemo(() => {
|
||||
if (panel.type === 'claude') return 'claude';
|
||||
if (panel.type === 'codex') return 'codex';
|
||||
|
||||
// For future CLI panels, extract from panel data
|
||||
const cliPanel = panel as CliPanel;
|
||||
return cliPanel.cliToolId || panel.type;
|
||||
}, [panel]);
|
||||
|
||||
// Determine which component to render
|
||||
const renderPanel = () => {
|
||||
switch (cliToolId) {
|
||||
case 'claude':
|
||||
return (
|
||||
<Suspense fallback={<LoadingFallback cliToolId={cliToolId} />}>
|
||||
<ClaudePanel panel={panel} isActive={isActive} />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
case 'codex':
|
||||
return (
|
||||
<Suspense fallback={<LoadingFallback cliToolId={cliToolId} />}>
|
||||
<CodexPanel panel={panel} isActive={isActive} />
|
||||
</Suspense>
|
||||
);
|
||||
|
||||
default:
|
||||
// For any unrecognized panel type, show unsupported message
|
||||
return (
|
||||
<div className="h-full w-full flex items-center justify-center p-8">
|
||||
<div className="text-center max-w-md">
|
||||
<AlertCircle className="w-12 h-12 text-yellow-500 mx-auto mb-4" />
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">
|
||||
Unsupported Panel Type
|
||||
</h3>
|
||||
<p className="text-sm text-text-secondary">
|
||||
The panel type "{cliToolId}" is not yet supported.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<CliPanelErrorBoundary cliToolId={cliToolId}>
|
||||
{renderPanel()}
|
||||
</CliPanelErrorBoundary>
|
||||
);
|
||||
});
|
||||
|
||||
CliPanelFactory.displayName = 'CliPanelFactory';
|
||||
|
||||
/**
|
||||
* Hook to determine if a CLI tool is supported
|
||||
*/
|
||||
export const useCliToolSupport = (cliToolId: string) => {
|
||||
return useMemo(() => {
|
||||
const supportedTools = ['claude', 'codex'];
|
||||
|
||||
return {
|
||||
isSupported: supportedTools.includes(cliToolId),
|
||||
supportLevel: supportedTools.includes(cliToolId) ? 'full' : 'unsupported'
|
||||
};
|
||||
}, [cliToolId]);
|
||||
};
|
||||
@ -1,337 +0,0 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { RefreshCw, Terminal, Clock, Hash, Cpu, Network, AlertCircle, CheckCircle, FileJson, Command } from 'lucide-react';
|
||||
|
||||
interface CodexDebugStateViewProps {
|
||||
sessionId: string;
|
||||
panelId: string;
|
||||
}
|
||||
|
||||
interface CodexDebugState {
|
||||
// Process information
|
||||
pid?: number;
|
||||
isConnected: boolean;
|
||||
|
||||
// Session information
|
||||
sessionId: string;
|
||||
panelId: string;
|
||||
worktreePath?: string;
|
||||
|
||||
// Interactive mode information (new)
|
||||
codexSessionId?: string; // Codex's internal session ID for resume
|
||||
executionMode: 'interactive' | 'unknown';
|
||||
|
||||
// Message statistics (simplified for interactive mode)
|
||||
totalMessagesReceived: number;
|
||||
|
||||
// Process state
|
||||
processState: 'not_started' | 'initializing' | 'running' | 'stopped' | 'error';
|
||||
lastError?: string;
|
||||
|
||||
// Model information
|
||||
model?: string;
|
||||
modelProvider?: string;
|
||||
}
|
||||
|
||||
export const CodexDebugStateView: React.FC<CodexDebugStateViewProps> = ({ sessionId, panelId }) => {
|
||||
const [debugState, setDebugState] = useState<CodexDebugState | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [lastRefreshTime, setLastRefreshTime] = useState<Date>(new Date());
|
||||
|
||||
const loadDebugState = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
|
||||
// Get debug state from backend using proper electron IPC
|
||||
const state = await window.electron?.invoke('codexPanel:getDebugState', { panelId });
|
||||
|
||||
if (state) {
|
||||
// Transform the backend state to our frontend format
|
||||
setDebugState({
|
||||
...state,
|
||||
executionMode: 'interactive', // We're always in interactive mode now
|
||||
codexSessionId: state.codexSessionId || undefined
|
||||
});
|
||||
} else {
|
||||
// No state returned, set default
|
||||
setDebugState({
|
||||
isConnected: false,
|
||||
sessionId,
|
||||
panelId,
|
||||
processState: 'not_started',
|
||||
totalMessagesReceived: 0,
|
||||
executionMode: 'interactive'
|
||||
});
|
||||
}
|
||||
setLastRefreshTime(new Date());
|
||||
} catch (error) {
|
||||
console.error('[CodexDebugStateView] Failed to load debug state:', error);
|
||||
setDebugState({
|
||||
isConnected: false,
|
||||
sessionId,
|
||||
panelId,
|
||||
processState: 'error',
|
||||
lastError: String(error),
|
||||
totalMessagesReceived: 0,
|
||||
executionMode: 'interactive'
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
// Load initial state
|
||||
loadDebugState();
|
||||
}, [sessionId, panelId]);
|
||||
|
||||
|
||||
const getStatusIcon = (state: string) => {
|
||||
switch (state) {
|
||||
case 'running':
|
||||
return <CheckCircle className="w-5 h-5 text-green-400" />;
|
||||
case 'error':
|
||||
return <AlertCircle className="w-5 h-5 text-red-400" />;
|
||||
case 'stopped':
|
||||
return <Terminal className="w-5 h-5 text-gray-400" />;
|
||||
default:
|
||||
return <Clock className="w-5 h-5 text-yellow-400" />;
|
||||
}
|
||||
};
|
||||
|
||||
if (!debugState && !loading) {
|
||||
return (
|
||||
<div className="h-full flex items-center justify-center p-8">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-medium text-text-primary mb-2">No Debug State Available</h3>
|
||||
<button
|
||||
onClick={loadDebugState}
|
||||
className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Load Debug State
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="h-full overflow-y-auto p-6">
|
||||
<div className="max-w-4xl mx-auto">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h3 className="text-lg font-medium text-text-primary">Codex Process Debug State</h3>
|
||||
<div className="flex items-center gap-4">
|
||||
<span className="text-xs text-text-secondary">
|
||||
Last refresh: {lastRefreshTime.toLocaleTimeString()}
|
||||
</span>
|
||||
<button
|
||||
onClick={loadDebugState}
|
||||
disabled={loading}
|
||||
className={`flex items-center gap-2 px-3 py-1.5 rounded-md transition-colors ${
|
||||
loading
|
||||
? 'bg-surface-secondary text-text-secondary cursor-not-allowed'
|
||||
: 'bg-blue-600 text-white hover:bg-blue-700'
|
||||
}`}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
|
||||
<span className="text-sm font-medium">Refresh</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{debugState && (
|
||||
<div className="space-y-6">
|
||||
{/* Process Information */}
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-3 flex items-center gap-2">
|
||||
<Cpu className="w-4 h-4" />
|
||||
Process Information
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-text-secondary">Process ID (PID):</span>
|
||||
<div className="text-text-primary font-mono mt-1">
|
||||
{debugState.pid || 'Not started'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Process State:</span>
|
||||
<div className="text-text-primary font-medium mt-1 flex items-center gap-2">
|
||||
{getStatusIcon(debugState.processState)}
|
||||
<span className="capitalize">{debugState.processState}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Connection Status:</span>
|
||||
<div className="text-text-primary font-medium mt-1 flex items-center gap-2">
|
||||
<Network className={`w-4 h-4 ${debugState.isConnected ? 'text-green-400' : 'text-red-400'}`} />
|
||||
{debugState.isConnected ? 'Connected' : 'Disconnected'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Execution Mode:</span>
|
||||
<div className="text-text-primary font-medium mt-1 flex items-center gap-2">
|
||||
<Command className="w-4 h-4 text-blue-400" />
|
||||
Interactive (--json)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Session Information */}
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-3 flex items-center gap-2">
|
||||
<Hash className="w-4 h-4" />
|
||||
Session Information
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-text-secondary">Crystal Session ID:</span>
|
||||
<div className="text-text-primary font-mono mt-1 text-xs break-all">
|
||||
{debugState.sessionId}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Panel ID:</span>
|
||||
<div className="text-text-primary font-mono mt-1 text-xs break-all">
|
||||
{debugState.panelId}
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-span-2">
|
||||
<span className="text-text-secondary">Codex Session ID (for resume):</span>
|
||||
<div className="text-text-primary font-mono mt-1 text-xs break-all">
|
||||
{debugState.codexSessionId ? (
|
||||
<>
|
||||
{debugState.codexSessionId}
|
||||
<span className="text-green-400 ml-2 text-xs">✓ Can resume</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-yellow-400">Not yet captured - will be set after first response</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{debugState.worktreePath && (
|
||||
<div className="col-span-2">
|
||||
<span className="text-text-secondary">Worktree Path:</span>
|
||||
<div className="text-text-primary font-mono mt-1 text-xs break-all">
|
||||
{debugState.worktreePath}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Interactive Mode Information */}
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-3 flex items-center gap-2">
|
||||
<FileJson className="w-4 h-4" />
|
||||
Interactive Mode Status
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-text-secondary">Command Mode:</span>
|
||||
<div className="text-text-primary font-medium mt-1">
|
||||
codex exec --json
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Resume Support:</span>
|
||||
<div className="text-text-primary font-medium mt-1">
|
||||
{debugState.codexSessionId ? '✅ Available' : '⚠️ Not available (no session ID)'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Input Method:</span>
|
||||
<div className="text-text-primary mt-1">
|
||||
PTY stdin (direct)
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Output Format:</span>
|
||||
<div className="text-text-primary mt-1">
|
||||
JSON Lines (JSONL)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{debugState.codexSessionId && (
|
||||
<div className="mt-4 p-3 bg-green-900/20 border border-green-600/30 rounded-md">
|
||||
<div className="text-xs text-green-400 font-medium mb-1">Resume Command:</div>
|
||||
<code className="text-xs text-green-300 font-mono">
|
||||
codex exec resume {debugState.codexSessionId} --json
|
||||
</code>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Message Statistics (Simplified) */}
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-3 flex items-center gap-2">
|
||||
<Terminal className="w-4 h-4" />
|
||||
Communication Statistics
|
||||
</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-text-secondary">JSON Messages Received:</span>
|
||||
<div className="text-text-primary font-semibold text-lg mt-1">
|
||||
{debugState.totalMessagesReceived}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Communication Type:</span>
|
||||
<div className="text-text-primary font-medium mt-1">
|
||||
Bidirectional PTY
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Model Information */}
|
||||
{(debugState.model || debugState.modelProvider) && (
|
||||
<div className="bg-surface-secondary rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-text-primary mb-3">Model Configuration</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-text-secondary">Model:</span>
|
||||
<div className="text-text-primary font-medium mt-1">
|
||||
{debugState.model || 'Auto (GPT-5)'}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-text-secondary">Provider:</span>
|
||||
<div className="text-text-primary font-medium mt-1">
|
||||
{debugState.modelProvider || 'OpenAI'}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Information */}
|
||||
{debugState.lastError && (
|
||||
<div className="bg-red-900/20 border border-red-600/30 rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-red-400 mb-2 flex items-center gap-2">
|
||||
<AlertCircle className="w-4 h-4" />
|
||||
Last Error
|
||||
</h4>
|
||||
<div className="text-sm text-red-300 font-mono">
|
||||
{debugState.lastError}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tips for Interactive Mode */}
|
||||
<div className="bg-blue-900/20 border border-blue-600/30 rounded-lg p-4">
|
||||
<h4 className="text-sm font-medium text-blue-400 mb-2">Interactive Mode Tips</h4>
|
||||
<ul className="text-sm text-blue-300 space-y-1">
|
||||
<li>• Input is sent directly through PTY stdin</li>
|
||||
<li>• Use Ctrl+C (sent as \x03) to interrupt execution</li>
|
||||
<li>• Session IDs are captured from JSON output for resume capability</li>
|
||||
<li>• All output is streamed as JSON Lines (one JSON object per line)</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,223 +0,0 @@
|
||||
import React, { useState, useRef, KeyboardEvent, useEffect } from 'react';
|
||||
import { Send, Settings2, StopCircle } from 'lucide-react';
|
||||
import type { Session } from '../../../types/session';
|
||||
import { CODEX_MODELS, DEFAULT_CODEX_MODEL, type OpenAICodexModel, type CodexInputOptions } from '../../../../../shared/types/models';
|
||||
import { CommitModePill } from '../../CommitModeToggle';
|
||||
|
||||
const LAST_CODEX_MODEL_KEY = 'codex.lastSelectedModel';
|
||||
|
||||
interface CodexInputPanelProps {
|
||||
session: Session;
|
||||
panelId: string;
|
||||
onSendMessage: (message: string, options?: CodexInputOptions) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
initialModel?: string;
|
||||
}
|
||||
|
||||
export const CodexInputPanel: React.FC<CodexInputPanelProps> = ({
|
||||
session,
|
||||
onSendMessage,
|
||||
disabled = false,
|
||||
initialModel
|
||||
}) => {
|
||||
const [input, setInput] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [showOptions, setShowOptions] = useState(false);
|
||||
|
||||
// Initialize with initial model prop, then last selected model from localStorage
|
||||
const getInitialModel = (): OpenAICodexModel => {
|
||||
// First priority: initialModel prop (from panel state)
|
||||
if (initialModel && initialModel in CODEX_MODELS) {
|
||||
return initialModel as OpenAICodexModel;
|
||||
}
|
||||
// Second priority: saved model from localStorage
|
||||
const saved = localStorage.getItem(LAST_CODEX_MODEL_KEY);
|
||||
if (saved && saved in CODEX_MODELS) {
|
||||
return saved as OpenAICodexModel;
|
||||
}
|
||||
// Default fallback
|
||||
return DEFAULT_CODEX_MODEL;
|
||||
};
|
||||
|
||||
const [options, setOptions] = useState({
|
||||
model: getInitialModel(),
|
||||
modelProvider: 'openai' as const,
|
||||
sandboxMode: 'workspace-write' as 'read-only' | 'workspace-write' | 'danger-full-access',
|
||||
webSearch: false
|
||||
});
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// Calculate auto-commit enabled state
|
||||
const effectiveMode = session.commitMode || (session.autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
const isAutoCommitEnabled = effectiveMode !== 'disabled';
|
||||
|
||||
// Save model selection to localStorage whenever it changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem(LAST_CODEX_MODEL_KEY, options.model);
|
||||
}, [options.model]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!input.trim() || isSubmitting || disabled) return;
|
||||
|
||||
const message = input.trim();
|
||||
setInput('');
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await onSendMessage(message, options);
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
// Restore input on error
|
||||
setInput(message);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
// Refocus textarea
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
const adjustTextareaHeight = () => {
|
||||
const textarea = textareaRef.current;
|
||||
if (textarea) {
|
||||
textarea.style.height = 'auto';
|
||||
const newHeight = Math.min(textarea.scrollHeight, 200);
|
||||
textarea.style.height = `${newHeight}px`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-t border-border-primary bg-surface-primary">
|
||||
{/* Options Panel */}
|
||||
{showOptions && (
|
||||
<div className="px-4 py-3 border-b border-border-primary bg-surface-secondary">
|
||||
<div className="flex flex-wrap gap-4 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-text-secondary">Model:</label>
|
||||
<select
|
||||
value={options.model}
|
||||
onChange={(e) => setOptions({ ...options, model: e.target.value as OpenAICodexModel })}
|
||||
className="px-2 py-1 bg-bg-primary border border-border-primary rounded text-text-primary font-medium"
|
||||
title={CODEX_MODELS[options.model as OpenAICodexModel]?.description || 'Select model'}
|
||||
>
|
||||
{Object.values(CODEX_MODELS).map(model => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-text-secondary">Sandbox:</label>
|
||||
<select
|
||||
value={options.sandboxMode}
|
||||
onChange={(e) => setOptions({ ...options, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' })}
|
||||
className="px-2 py-1 bg-bg-primary border border-border-primary rounded text-text-primary"
|
||||
>
|
||||
<option value="read-only">Read Only</option>
|
||||
<option value="workspace-write">Workspace Write</option>
|
||||
<option value="danger-full-access">Full Access</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Commit Mode Controls */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Auto-Commit Toggle - Hidden: Now handled by CommitMode system */}
|
||||
{/* <label className="text-text-secondary">Auto-Commit:</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<AutoCommitSwitch
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
/>
|
||||
<CommitModePill */}
|
||||
<CommitModePill
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
projectId={session.projectId}
|
||||
isAutoCommitEnabled={isAutoCommitEnabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Web Search toggle hidden for Codex as it doesn't work */}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input Area */}
|
||||
<div className="flex items-end gap-2 p-3">
|
||||
<button
|
||||
onClick={() => setShowOptions(!showOptions)}
|
||||
className="p-2 text-text-secondary hover:text-text-primary hover:bg-surface-hover rounded-md transition-colors"
|
||||
title="Codex Options"
|
||||
>
|
||||
<Settings2 className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div className="flex-1 relative">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
adjustTextareaHeight();
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={
|
||||
session.status === 'waiting'
|
||||
? "Enter your response..."
|
||||
: "Ask Codex anything..."
|
||||
}
|
||||
disabled={isSubmitting || disabled}
|
||||
className="w-full px-3 py-2 bg-bg-primary border border-border-primary rounded-lg
|
||||
text-text-primary placeholder-text-tertiary resize-none
|
||||
focus:outline-none focus:ring-1 focus:ring-accent-primary focus:border-accent-primary
|
||||
disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{ minHeight: '40px', maxHeight: '200px' }}
|
||||
rows={1}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{session.status === 'running' ? (
|
||||
<button
|
||||
onClick={() => {/* TODO: Implement interrupt */}}
|
||||
className="p-2 text-red-500 hover:text-red-400 hover:bg-red-500/10 rounded-md transition-colors"
|
||||
title="Stop Codex"
|
||||
>
|
||||
<StopCircle className="w-4 h-4" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!input.trim() || isSubmitting || disabled}
|
||||
className="p-2 text-accent-primary hover:text-accent-hover hover:bg-accent-primary/10
|
||||
rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
title="Send message (Enter)"
|
||||
>
|
||||
<Send className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Indicator */}
|
||||
{session.status === 'running' && (
|
||||
<div className="px-4 pb-2">
|
||||
<div className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
<span>Codex is thinking...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,233 +0,0 @@
|
||||
import React, { useState, useRef, KeyboardEvent, useEffect } from 'react';
|
||||
import { Send, Settings2, StopCircle } from 'lucide-react';
|
||||
import type { Session } from '../../../types/session';
|
||||
import { CODEX_MODELS, DEFAULT_CODEX_MODEL, type OpenAICodexModel } from '../../../../../shared/types/models';
|
||||
import { CommitModePill, AutoCommitSwitch } from '../../CommitModeToggle';
|
||||
|
||||
const LAST_CODEX_MODEL_KEY = 'codex.lastSelectedModel';
|
||||
|
||||
interface CodexInputPanelProps {
|
||||
session: Session;
|
||||
panelId: string;
|
||||
onSendMessage: (message: string, options?: any) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
initialModel?: string;
|
||||
}
|
||||
|
||||
export const CodexInputPanel: React.FC<CodexInputPanelProps> = ({
|
||||
session,
|
||||
onSendMessage,
|
||||
disabled = false,
|
||||
initialModel
|
||||
}) => {
|
||||
const [input, setInput] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [showOptions, setShowOptions] = useState(false);
|
||||
|
||||
// Initialize with initial model prop, then last selected model from localStorage
|
||||
const getInitialModel = (): OpenAICodexModel => {
|
||||
// First priority: initialModel prop (from panel state)
|
||||
if (initialModel && initialModel in CODEX_MODELS) {
|
||||
return initialModel as OpenAICodexModel;
|
||||
}
|
||||
// Second priority: saved model from localStorage
|
||||
const saved = localStorage.getItem(LAST_CODEX_MODEL_KEY);
|
||||
if (saved && saved in CODEX_MODELS) {
|
||||
return saved as OpenAICodexModel;
|
||||
}
|
||||
// Default fallback
|
||||
return DEFAULT_CODEX_MODEL;
|
||||
};
|
||||
|
||||
const [options, setOptions] = useState({
|
||||
model: getInitialModel(),
|
||||
modelProvider: 'openai',
|
||||
sandboxMode: 'workspace-write' as 'read-only' | 'workspace-write' | 'danger-full-access',
|
||||
webSearch: false
|
||||
});
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
// Calculate auto-commit enabled state
|
||||
const effectiveMode = session.commitMode || (session.autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
const isAutoCommitEnabled = effectiveMode !== 'disabled';
|
||||
|
||||
// Save model selection to localStorage whenever it changes
|
||||
useEffect(() => {
|
||||
localStorage.setItem(LAST_CODEX_MODEL_KEY, options.model);
|
||||
}, [options.model]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!input.trim() || isSubmitting || disabled) return;
|
||||
|
||||
const message = input.trim();
|
||||
setInput('');
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
await onSendMessage(message, options);
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
// Restore input on error
|
||||
setInput(message);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
// Refocus textarea
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
const adjustTextareaHeight = () => {
|
||||
const textarea = textareaRef.current;
|
||||
if (textarea) {
|
||||
textarea.style.height = 'auto';
|
||||
const newHeight = Math.min(textarea.scrollHeight, 200);
|
||||
textarea.style.height = `${newHeight}px`;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="border-t border-border-primary bg-surface-primary">
|
||||
{/* Options Panel */}
|
||||
{showOptions && (
|
||||
<div className="px-4 py-3 border-b border-border-primary bg-surface-secondary">
|
||||
<div className="flex flex-wrap gap-4 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-text-secondary">Model:</label>
|
||||
<select
|
||||
value={options.model}
|
||||
onChange={(e) => setOptions({ ...options, model: e.target.value as OpenAICodexModel })}
|
||||
className="px-2 py-1 bg-bg-primary border border-border-primary rounded text-text-primary font-medium"
|
||||
title={CODEX_MODELS[options.model as OpenAICodexModel]?.description || 'Select model'}
|
||||
>
|
||||
{Object.values(CODEX_MODELS).map(model => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-text-secondary">Sandbox:</label>
|
||||
<select
|
||||
value={options.sandboxMode}
|
||||
onChange={(e) => setOptions({ ...options, sandboxMode: e.target.value as any })}
|
||||
className="px-2 py-1 bg-bg-primary border border-border-primary rounded text-text-primary"
|
||||
>
|
||||
<option value="read-only">Read Only</option>
|
||||
<option value="workspace-write">Workspace Write</option>
|
||||
<option value="danger-full-access">Full Access</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Commit Mode Controls */}
|
||||
<div className="flex items-center gap-3">
|
||||
<label className="text-text-secondary">Auto-Commit:</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<AutoCommitSwitch
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
/>
|
||||
<CommitModePill
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
projectId={session.projectId}
|
||||
isAutoCommitEnabled={isAutoCommitEnabled}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Web Search toggle hidden for Codex as it doesn't work */}
|
||||
{/* <div className="flex items-center gap-2">
|
||||
<label className="flex items-center gap-1 text-text-secondary cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={options.webSearch}
|
||||
onChange={(e) => setOptions({ ...options, webSearch: e.target.checked })}
|
||||
className="rounded border-border-primary"
|
||||
/>
|
||||
Web Search
|
||||
</label>
|
||||
</div> */
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Input Area */}
|
||||
<div className="flex items-end gap-2 p-3">
|
||||
<button
|
||||
onClick={() => setShowOptions(!showOptions)}
|
||||
className="p-2 text-text-secondary hover:text-text-primary hover:bg-surface-hover rounded-md transition-colors"
|
||||
title="Codex Options"
|
||||
>
|
||||
<Settings2 className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
<div className="flex-1 relative">
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
adjustTextareaHeight();
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={
|
||||
session.status === 'waiting'
|
||||
? "Enter your response..."
|
||||
: "Ask Codex anything..."
|
||||
}
|
||||
disabled={isSubmitting || disabled}
|
||||
className="w-full px-3 py-2 bg-bg-primary border border-border-primary rounded-lg
|
||||
text-text-primary placeholder-text-tertiary resize-none
|
||||
focus:outline-none focus:ring-1 focus:ring-accent-primary focus:border-accent-primary
|
||||
disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
style={{ minHeight: '40px', maxHeight: '200px' }}
|
||||
rows={1}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{session.status === 'running' ? (
|
||||
<button
|
||||
onClick={() => {/* TODO: Implement interrupt */}}
|
||||
className="p-2 text-red-500 hover:text-red-400 hover:bg-red-500/10 rounded-md transition-colors"
|
||||
title="Stop Codex"
|
||||
>
|
||||
<StopCircle className="w-4 h-4" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={!input.trim() || isSubmitting || disabled}
|
||||
className="p-2 text-accent-primary hover:text-accent-hover hover:bg-accent-primary/10
|
||||
rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
title="Send message (Enter)"
|
||||
>
|
||||
<Send className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Indicator */}
|
||||
{session.status === 'running' && (
|
||||
<div className="px-4 pb-2">
|
||||
<div className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
<span>Codex is thinking...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -1,212 +0,0 @@
|
||||
import React from 'react';
|
||||
import { AbstractInputPanel, AbstractInputPanelState, InputOptions, AbstractInputPanelProps } from '../ai/AbstractInputPanel';
|
||||
import { CODEX_MODELS, DEFAULT_CODEX_MODEL, type OpenAICodexModel, type CodexInputOptions } from '../../../../../shared/types/models';
|
||||
import { CommitModePill } from '../../CommitModeToggle';
|
||||
|
||||
const LAST_CODEX_MODEL_KEY = 'codex.lastSelectedModel';
|
||||
|
||||
interface CodexInputPanelProps extends AbstractInputPanelProps {
|
||||
disabled?: boolean;
|
||||
initialModel?: string;
|
||||
}
|
||||
|
||||
// Using shared CodexInputOptions interface from models.ts
|
||||
|
||||
interface CodexInputPanelState extends AbstractInputPanelState {
|
||||
options: CodexInputOptions;
|
||||
}
|
||||
|
||||
class CodexInputPanelClass extends AbstractInputPanel<CodexInputPanelProps, CodexInputPanelState> {
|
||||
protected getInitialState(): Partial<CodexInputPanelState> {
|
||||
return {
|
||||
options: this.initializeOptions(),
|
||||
};
|
||||
}
|
||||
|
||||
private initializeOptions(): CodexInputOptions {
|
||||
const { initialModel } = this.props;
|
||||
|
||||
// First priority: initialModel prop (from panel state)
|
||||
if (initialModel && initialModel in CODEX_MODELS) {
|
||||
return {
|
||||
model: initialModel as OpenAICodexModel,
|
||||
modelProvider: 'openai' as const,
|
||||
sandboxMode: 'workspace-write',
|
||||
webSearch: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Second priority: saved model from localStorage
|
||||
const saved = localStorage.getItem(LAST_CODEX_MODEL_KEY);
|
||||
if (saved && saved in CODEX_MODELS) {
|
||||
return {
|
||||
model: saved as OpenAICodexModel,
|
||||
modelProvider: 'openai' as const,
|
||||
sandboxMode: 'workspace-write',
|
||||
webSearch: false,
|
||||
};
|
||||
}
|
||||
|
||||
// Default fallback
|
||||
return {
|
||||
model: DEFAULT_CODEX_MODEL,
|
||||
modelProvider: 'openai',
|
||||
sandboxMode: 'workspace-write',
|
||||
webSearch: false,
|
||||
};
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps: CodexInputPanelProps, prevState: CodexInputPanelState) {
|
||||
super.componentDidUpdate(prevProps, prevState);
|
||||
|
||||
// Save model selection to localStorage whenever it changes
|
||||
if (prevState.options?.model !== this.state.options.model) {
|
||||
localStorage.setItem(LAST_CODEX_MODEL_KEY, this.state.options.model);
|
||||
}
|
||||
}
|
||||
|
||||
getDefaultOptions(): InputOptions {
|
||||
return this.state.options;
|
||||
}
|
||||
|
||||
getPlaceholder(): string {
|
||||
const { session } = this.props;
|
||||
return session.status === 'waiting'
|
||||
? "Enter your response..."
|
||||
: "Ask Codex anything...";
|
||||
}
|
||||
|
||||
protected handleSubmit = async () => {
|
||||
const { onSendMessage, disabled } = this.props;
|
||||
const { input, isSubmitting, options } = this.state;
|
||||
|
||||
if (!input.trim() || isSubmitting || disabled) return;
|
||||
|
||||
const message = input.trim();
|
||||
this.setState({ input: '', isSubmitting: true });
|
||||
|
||||
try {
|
||||
// Codex sends options differently - as direct parameters
|
||||
await onSendMessage(message, options);
|
||||
// Clear attachments on successful send
|
||||
this.setState({ attachedImages: [], attachedTexts: [] });
|
||||
} catch (error) {
|
||||
console.error('Failed to send message:', error);
|
||||
// Restore input on error
|
||||
this.setState({ input: message });
|
||||
} finally {
|
||||
this.setState({ isSubmitting: false });
|
||||
// Refocus textarea
|
||||
this.inputRef.current?.focus();
|
||||
}
|
||||
};
|
||||
|
||||
renderOptionsPanel(): React.ReactNode {
|
||||
const { options } = this.state;
|
||||
const { session } = this.props;
|
||||
|
||||
// Calculate auto-commit enabled state
|
||||
const effectiveMode = session.commitMode || (session.autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
const isAutoCommitEnabled = effectiveMode !== 'disabled';
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-4 text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-text-secondary">Model:</label>
|
||||
<select
|
||||
value={options.model}
|
||||
onChange={(e) => this.setState({
|
||||
options: { ...options, model: e.target.value as OpenAICodexModel }
|
||||
})}
|
||||
className="px-2 py-1 bg-bg-primary border border-border-primary rounded text-text-primary font-medium"
|
||||
title={CODEX_MODELS[options.model as OpenAICodexModel]?.description || 'Select model'}
|
||||
>
|
||||
{Object.values(CODEX_MODELS).map(model => (
|
||||
<option key={model.id} value={model.id}>
|
||||
{model.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="text-text-secondary">Sandbox:</label>
|
||||
<select
|
||||
value={options.sandboxMode}
|
||||
onChange={(e) => this.setState({
|
||||
options: { ...options, sandboxMode: e.target.value as 'read-only' | 'workspace-write' | 'danger-full-access' }
|
||||
})}
|
||||
className="px-2 py-1 bg-bg-primary border border-border-primary rounded text-text-primary"
|
||||
>
|
||||
<option value="read-only">Read Only</option>
|
||||
<option value="workspace-write">Workspace Write</option>
|
||||
<option value="danger-full-access">Full Access</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Commit Mode Controls */}
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Auto-Commit Toggle - Hidden: Now handled by CommitMode system */}
|
||||
{/* <label className="text-text-secondary">Auto-Commit:</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<AutoCommitSwitch
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
/>
|
||||
<CommitModePill */}
|
||||
<CommitModePill
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
projectId={session.projectId}
|
||||
isAutoCommitEnabled={isAutoCommitEnabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Web Search toggle hidden for Codex as it doesn't work */}
|
||||
{/* <div className="flex items-center gap-2">
|
||||
<label className="flex items-center gap-1 text-text-secondary cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={options.webSearch}
|
||||
onChange={(e) => this.setState({
|
||||
options: { ...options, webSearch: e.target.checked }
|
||||
})}
|
||||
className="rounded border-border-primary"
|
||||
/>
|
||||
Web Search
|
||||
</label>
|
||||
</div> */}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
renderActionButtons(): React.ReactNode {
|
||||
// Codex doesn't have additional action buttons like Claude
|
||||
return null;
|
||||
}
|
||||
|
||||
protected renderStatusIndicator(): React.ReactNode {
|
||||
const { session } = this.props;
|
||||
|
||||
if (session.status === 'running') {
|
||||
return (
|
||||
<div className="px-4 pb-2">
|
||||
<div className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
<span>Codex is thinking...</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Create a functional component wrapper for easier use
|
||||
export const CodexInputPanelRefactored: React.FC<CodexInputPanelProps> = (props) => {
|
||||
return <CodexInputPanelClass {...props} />;
|
||||
};
|
||||
@ -1,740 +0,0 @@
|
||||
import React, { useState, KeyboardEvent, useEffect, useCallback, memo } from 'react';
|
||||
import { Send, X, Paperclip, FileText, Square, ChevronRight, Zap, Target, Brain, CheckCircle, Gauge } from 'lucide-react';
|
||||
import type { Session, GitCommands } from '../../../types/session';
|
||||
import type { ToolPanel } from '../../../../../shared/types/panels';
|
||||
import { CODEX_MODELS, DEFAULT_CODEX_MODEL, type OpenAICodexModel, type CodexInputOptions } from '../../../../../shared/types/models';
|
||||
import { useAIInputPanel } from '../../../hooks/useAIInputPanel';
|
||||
import FilePathAutocomplete from '../../FilePathAutocomplete';
|
||||
import { Dropdown, type DropdownItem } from '../../ui/Dropdown';
|
||||
import { Pill } from '../../ui/Pill';
|
||||
import { CommitModePill } from '../../CommitModeToggle';
|
||||
import { API } from '../../../utils/api';
|
||||
|
||||
// Settings are now stored in database, no longer using localStorage
|
||||
|
||||
interface CodexInputPanelStyledProps {
|
||||
session: Session;
|
||||
panelId: string;
|
||||
panel?: ToolPanel;
|
||||
onSendMessage: (message: string, options?: CodexInputOptions) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
initialModel?: string;
|
||||
onCancel?: () => void;
|
||||
gitCommands?: GitCommands | null;
|
||||
}
|
||||
|
||||
export const CodexInputPanelStyled: React.FC<CodexInputPanelStyledProps> = memo(({
|
||||
session,
|
||||
panelId,
|
||||
onSendMessage,
|
||||
disabled = false,
|
||||
onCancel,
|
||||
gitCommands,
|
||||
panel
|
||||
}) => {
|
||||
// Initialize model
|
||||
// Initialize state with defaults, will be updated from database
|
||||
const [selectedModel, setSelectedModel] = useState<OpenAICodexModel>(DEFAULT_CODEX_MODEL);
|
||||
const [sandboxMode, setSandboxMode] = useState<'read-only' | 'workspace-write' | 'danger-full-access'>('workspace-write');
|
||||
const [webSearch, setWebSearch] = useState(false);
|
||||
const [thinkingLevel, setThinkingLevel] = useState<'low' | 'medium' | 'high'>('medium');
|
||||
const [settingsLoaded, setSettingsLoaded] = useState(false);
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
const [isToolbarActive, setIsToolbarActive] = useState(false);
|
||||
|
||||
// Use the shared hook for common functionality
|
||||
const {
|
||||
input,
|
||||
setInput,
|
||||
isSubmitting,
|
||||
attachedImages,
|
||||
attachedTexts,
|
||||
isDragging,
|
||||
textareaRef,
|
||||
fileInputRef,
|
||||
handlePaste,
|
||||
handleDrop,
|
||||
handleDragOver,
|
||||
handleDragLeave,
|
||||
removeImage,
|
||||
removeText,
|
||||
handleFileSelect,
|
||||
handleSubmit: hookHandleSubmit,
|
||||
} = useAIInputPanel({
|
||||
onSendMessage: async (message, _additionalOptions, images, texts) => {
|
||||
// Pass the message and attachments to the handler
|
||||
// The hook (useCodexPanel) will handle saving attachments and formatting
|
||||
const options = {
|
||||
model: selectedModel,
|
||||
modelProvider: 'openai' as const,
|
||||
sandboxMode,
|
||||
webSearch,
|
||||
thinkingLevel,
|
||||
attachedImages: images,
|
||||
attachedTexts: texts
|
||||
};
|
||||
await onSendMessage(message, options);
|
||||
},
|
||||
onCancel,
|
||||
disabled
|
||||
});
|
||||
|
||||
// Load settings from database on mount
|
||||
useEffect(() => {
|
||||
const loadSettings = async () => {
|
||||
try {
|
||||
const result = await API.codexPanels.getSettings(panelId);
|
||||
if (result.success && result.data) {
|
||||
const settings = result.data;
|
||||
if (settings.model && settings.model in CODEX_MODELS) {
|
||||
setSelectedModel(settings.model as OpenAICodexModel);
|
||||
}
|
||||
if (settings.sandboxMode) {
|
||||
setSandboxMode(settings.sandboxMode);
|
||||
}
|
||||
if (settings.webSearch !== undefined) {
|
||||
setWebSearch(settings.webSearch);
|
||||
}
|
||||
if (settings.thinkingLevel) {
|
||||
setThinkingLevel(settings.thinkingLevel);
|
||||
}
|
||||
setSettingsLoaded(true);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load Codex panel settings:', error);
|
||||
setSettingsLoaded(true); // Mark as loaded even on error to prevent blocking
|
||||
}
|
||||
};
|
||||
|
||||
loadSettings();
|
||||
}, [panelId]);
|
||||
|
||||
// Save settings to database when they change
|
||||
useEffect(() => {
|
||||
if (!settingsLoaded) return; // Don't save until initial load is complete
|
||||
|
||||
const saveSettings = async () => {
|
||||
try {
|
||||
await API.codexPanels.setSettings(panelId, {
|
||||
model: selectedModel,
|
||||
sandboxMode,
|
||||
webSearch,
|
||||
thinkingLevel
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to save Codex panel settings:', error);
|
||||
}
|
||||
};
|
||||
|
||||
saveSettings();
|
||||
}, [selectedModel, sandboxMode, webSearch, thinkingLevel, settingsLoaded, panelId]);
|
||||
|
||||
// Update model and thinking level when panel changes (e.g., when switching sessions)
|
||||
useEffect(() => {
|
||||
const customState = panel?.state?.customState as {
|
||||
codexConfig?: {
|
||||
model?: string;
|
||||
thinkingLevel?: 'low' | 'medium' | 'high';
|
||||
sandboxMode?: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
webSearch?: boolean;
|
||||
};
|
||||
} | undefined;
|
||||
|
||||
// Update model
|
||||
if (customState?.codexConfig?.model) {
|
||||
const storedModel = customState.codexConfig.model;
|
||||
if (storedModel in CODEX_MODELS) {
|
||||
setSelectedModel(storedModel as OpenAICodexModel);
|
||||
}
|
||||
}
|
||||
|
||||
// Update thinking level
|
||||
if (customState?.codexConfig?.thinkingLevel) {
|
||||
const storedLevel = customState.codexConfig.thinkingLevel;
|
||||
if (storedLevel === 'low' || storedLevel === 'medium' || storedLevel === 'high') {
|
||||
setThinkingLevel(storedLevel);
|
||||
}
|
||||
}
|
||||
|
||||
// Update sandbox mode
|
||||
if (customState?.codexConfig?.sandboxMode) {
|
||||
const storedMode = customState.codexConfig.sandboxMode;
|
||||
if (storedMode === 'read-only' || storedMode === 'workspace-write' || storedMode === 'danger-full-access') {
|
||||
setSandboxMode(storedMode);
|
||||
}
|
||||
}
|
||||
|
||||
// Update web search
|
||||
if (customState?.codexConfig?.webSearch !== undefined) {
|
||||
setWebSearch(customState.codexConfig.webSearch);
|
||||
}
|
||||
}, [panel?.state?.customState]);
|
||||
|
||||
const handleSubmit = async () => {
|
||||
// Use the hook's handleSubmit which includes attachments
|
||||
await hookHandleSubmit({
|
||||
model: selectedModel,
|
||||
modelProvider: 'openai',
|
||||
sandboxMode,
|
||||
webSearch,
|
||||
thinkingLevel
|
||||
});
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement | HTMLInputElement>) => {
|
||||
const shouldCancel = e.key === 'Escape' && session.status === 'running' && onCancel;
|
||||
|
||||
if (shouldCancel) {
|
||||
e.preventDefault();
|
||||
onCancel();
|
||||
} else if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
setIsToolbarActive(true);
|
||||
}, []);
|
||||
|
||||
const handleBlur = useCallback((e: React.FocusEvent) => {
|
||||
const toolbar = e.currentTarget?.closest?.('[data-toolbar-container]');
|
||||
const relatedTarget = e.relatedTarget;
|
||||
|
||||
if (!toolbar || !relatedTarget || !(toolbar instanceof Element) || !toolbar.contains(relatedTarget as Node)) {
|
||||
setIsFocused(false);
|
||||
setIsToolbarActive(false);
|
||||
} else {
|
||||
setIsFocused(false);
|
||||
setIsToolbarActive(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Get session status
|
||||
const getSessionStatus = () => {
|
||||
switch (session.status) {
|
||||
case 'initializing':
|
||||
return { color: 'bg-status-warning', pulse: true };
|
||||
case 'ready':
|
||||
return { color: 'bg-status-success', pulse: false };
|
||||
case 'running':
|
||||
return { color: 'bg-interactive', pulse: true };
|
||||
case 'waiting':
|
||||
return { color: 'bg-status-warning', pulse: true };
|
||||
case 'stopped':
|
||||
return { color: 'bg-text-tertiary', pulse: false };
|
||||
case 'completed_unviewed':
|
||||
return { color: 'bg-status-success', pulse: true };
|
||||
case 'error':
|
||||
return { color: 'bg-status-error', pulse: false };
|
||||
default:
|
||||
return { color: 'bg-text-tertiary', pulse: false };
|
||||
}
|
||||
};
|
||||
|
||||
const sessionStatus = getSessionStatus();
|
||||
const placeholder = session.status === 'waiting'
|
||||
? "Enter your response..."
|
||||
: "Ask Codex anything...";
|
||||
|
||||
// Calculate auto-commit enabled state
|
||||
const effectiveMode = session.commitMode || (session.autoCommit === false ? 'disabled' : 'checkpoint');
|
||||
const isAutoCommitEnabled = effectiveMode !== 'disabled';
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col shadow-[0_-4px_20px_rgba(0,0,0,0.1)]">
|
||||
<div className="bg-surface-secondary flex flex-col flex-1 min-h-0">
|
||||
{/* Context Bar */}
|
||||
<div className="px-4 py-2 border-b border-border-primary bg-surface-primary flex-shrink-0">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Session status indicator */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<div className={`w-2 h-2 rounded-full ${sessionStatus.color} ${sessionStatus.pulse ? 'animate-pulse' : ''}`} />
|
||||
</div>
|
||||
|
||||
{/* Project Badge */}
|
||||
<div className="px-2.5 py-1 rounded-full text-xs font-medium
|
||||
bg-interactive/10 text-interactive
|
||||
border border-interactive/30
|
||||
flex items-center gap-1.5">
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
|
||||
</svg>
|
||||
<span className="leading-none">
|
||||
{session.worktreePath.split('/').slice(-3, -2)[0] || 'Project'}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Branch Badge */}
|
||||
{gitCommands?.currentBranch && (
|
||||
<div className="px-2.5 py-1 rounded-full text-xs font-medium
|
||||
bg-status-success/10 text-status-success
|
||||
border border-status-success/30
|
||||
flex items-center gap-1.5">
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 3v12a3 3 0 003 3h6m-6-6l3-3-3-3m6 0a3 3 0 100 6 3 3 0 000-6z" />
|
||||
</svg>
|
||||
<span className="leading-none font-mono">
|
||||
{gitCommands.currentBranch}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Codex Indicator */}
|
||||
<div className="flex items-center gap-1 text-text-secondary">
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
|
||||
</svg>
|
||||
<span>Codex AI</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Command Input Area */}
|
||||
<div
|
||||
className="p-4 bg-surface-primary flex-1 flex flex-col min-h-0"
|
||||
data-toolbar-container
|
||||
onDrop={handleDrop}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
>
|
||||
{/* Attached items */}
|
||||
{(attachedImages.length > 0 || attachedTexts.length > 0) && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{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
|
||||
onClick={() => removeText(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"
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{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
|
||||
onClick={() => removeImage(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"
|
||||
>
|
||||
<X className="w-2.5 h-2.5 text-text-secondary" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Clean Input Container */}
|
||||
<div className={`
|
||||
relative z-10 flex-1 flex flex-col min-h-0
|
||||
bg-surface-primary
|
||||
rounded-lg border border-border-primary
|
||||
shadow-[0_4px_20px_rgba(0,0,0,0.1)] hover:shadow-[0_8px_30px_rgba(0,0,0,0.15)]
|
||||
transition-all duration-200 backdrop-blur-sm
|
||||
${(isFocused || isToolbarActive) ? 'command-bar-focus' : ''}
|
||||
`}>
|
||||
{/* Command prompt field */}
|
||||
<div className="relative flex-1 min-h-0 flex">
|
||||
<div className="absolute left-4 top-4 text-text-secondary select-none pointer-events-none font-mono text-sm z-10">
|
||||
>
|
||||
</div>
|
||||
<FilePathAutocomplete
|
||||
value={input}
|
||||
onChange={setInput}
|
||||
sessionId={session.id}
|
||||
placeholder={isDragging ? "Drop images here..." : placeholder}
|
||||
className={`
|
||||
w-full h-full pl-10 pr-4 py-4
|
||||
bg-transparent
|
||||
border-0 focus:outline-none
|
||||
resize-none font-mono text-sm
|
||||
text-text-primary
|
||||
placeholder-text-tertiary
|
||||
transition-colors
|
||||
`}
|
||||
textareaRef={textareaRef}
|
||||
isTextarea={true}
|
||||
rows={1}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={handleFocus}
|
||||
onBlur={() => handleBlur({} as React.FocusEvent)}
|
||||
style={{
|
||||
minHeight: '52px'
|
||||
}}
|
||||
/>
|
||||
{/* Hidden file input */}
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Unified Action Bar */}
|
||||
<div className="flex items-center justify-between mt-3 gap-4 flex-shrink-0">
|
||||
{/* Left Section - Tools and Settings */}
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Attach Button */}
|
||||
<Pill
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
icon={<Paperclip className="w-3.5 h-3.5" />}
|
||||
title="Attach images or paste large text blocks"
|
||||
>
|
||||
Attach
|
||||
</Pill>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-6 w-px bg-border-primary mx-1" />
|
||||
|
||||
{/* Model Selector */}
|
||||
<ModelSelector
|
||||
selectedModel={selectedModel}
|
||||
setSelectedModel={setSelectedModel}
|
||||
/>
|
||||
|
||||
{/* Thinking Level Selector */}
|
||||
<ThinkingLevelSelector
|
||||
thinkingLevel={thinkingLevel}
|
||||
setThinkingLevel={setThinkingLevel}
|
||||
/>
|
||||
|
||||
{/* Auto-Commit Mode Pill - always visible */}
|
||||
<CommitModePill
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
projectId={session.projectId}
|
||||
isAutoCommitEnabled={isAutoCommitEnabled}
|
||||
/>
|
||||
|
||||
{/* Toggle Group - subtle visual grouping */}
|
||||
<div className="flex items-center gap-2 ml-1 pl-2 border-l border-border-primary/20">
|
||||
{/* Auto-Commit Toggle - Hidden: Now handled by CommitMode system */}
|
||||
{/* <AutoCommitSwitch
|
||||
sessionId={session.id}
|
||||
currentMode={session.commitMode}
|
||||
currentSettings={session.commitModeSettings}
|
||||
autoCommit={session.autoCommit}
|
||||
/> */}
|
||||
|
||||
{/* Options Pills */}
|
||||
<div className="flex items-center gap-2">
|
||||
{/* Sandbox Mode */}
|
||||
<SandboxSelector
|
||||
sandboxMode={sandboxMode}
|
||||
setSandboxMode={setSandboxMode}
|
||||
/>
|
||||
|
||||
{/* Web Search Toggle - Hidden for Codex as it doesn't work */}
|
||||
{/* <div title="Allow AI to search the web for up-to-date information">
|
||||
<Switch
|
||||
checked={webSearch}
|
||||
onCheckedChange={setWebSearch}
|
||||
label="Web Search"
|
||||
size="sm"
|
||||
/>
|
||||
</div> */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Section - Send/Cancel Button */}
|
||||
<div className="flex items-center gap-2">
|
||||
{session.status === 'running' && onCancel ? (
|
||||
<button
|
||||
onClick={onCancel}
|
||||
className={`
|
||||
px-4 py-2 font-medium group
|
||||
flex items-center gap-2 transition-all duration-200
|
||||
rounded-lg border
|
||||
active:scale-[0.98]
|
||||
focus:outline-none focus:ring-2 focus:ring-inset focus:ring-offset-0
|
||||
bg-surface-secondary hover:bg-surface-hover
|
||||
text-status-error hover:text-status-error/90
|
||||
border-status-error/30 hover:border-status-error/50
|
||||
focus:ring-status-error/50
|
||||
hover:shadow-[0_2px_8px_rgba(0,0,0,0.1)]
|
||||
`}
|
||||
>
|
||||
<Square className="w-4 h-4 fill-current" />
|
||||
<span className="font-semibold">Cancel</span>
|
||||
<span className="ml-2 text-xs font-mono bg-surface-tertiary px-1.5 py-0.5 rounded opacity-80 group-hover:opacity-100 transition-opacity">
|
||||
ESC
|
||||
</span>
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
onClick={handleSubmit}
|
||||
disabled={isSubmitting || !input.trim()}
|
||||
className={`
|
||||
px-4 py-2 font-medium group
|
||||
flex items-center gap-2 transition-all duration-200
|
||||
rounded-lg border
|
||||
active:scale-[0.98]
|
||||
focus:outline-none focus:ring-2 focus:ring-inset focus:ring-offset-0
|
||||
${isSubmitting || !input.trim()
|
||||
? 'bg-gray-500 text-gray-300 border-gray-500 cursor-not-allowed opacity-60'
|
||||
: session.status === 'waiting'
|
||||
? 'bg-surface-secondary hover:bg-surface-hover text-interactive hover:text-interactive-hover border-border-primary focus:ring-interactive'
|
||||
: 'bg-gradient-to-r from-interactive to-interactive-hover hover:from-interactive-hover hover:to-interactive text-white border-interactive shadow-[inset_0_1px_0_rgba(255,255,255,0.1)] focus:ring-interactive hover:shadow-[0_4px_12px_rgba(59,130,246,0.3)]'
|
||||
}
|
||||
`}
|
||||
>
|
||||
{session.status === 'waiting' ? (
|
||||
<Send className="w-4 h-4" />
|
||||
) : (
|
||||
<ChevronRight className="w-4 h-4 transition-transform duration-200 group-hover:translate-x-0.5" />
|
||||
)}
|
||||
<span className="font-semibold">
|
||||
{isSubmitting ? 'Processing...' : session.status === 'waiting' ? 'Send' : 'Continue'}
|
||||
</span>
|
||||
<span className="ml-2 text-xs font-mono bg-white/10 px-1.5 py-0.5 rounded opacity-80 group-hover:opacity-100 transition-opacity">
|
||||
⌘⏎
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Status Indicator */}
|
||||
{session.status === 'running' && (
|
||||
<div className="bg-surface-primary border-t border-border-primary px-4 py-3">
|
||||
<div className="flex items-center gap-2 text-xs text-text-secondary">
|
||||
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
|
||||
<span>Codex is processing your request...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
CodexInputPanelStyled.displayName = 'CodexInputPanelStyled';
|
||||
|
||||
// Model Selector Component
|
||||
interface ModelSelectorProps {
|
||||
selectedModel: OpenAICodexModel;
|
||||
setSelectedModel: (model: OpenAICodexModel) => void;
|
||||
}
|
||||
|
||||
const ModelSelector: React.FC<ModelSelectorProps> = ({
|
||||
selectedModel,
|
||||
setSelectedModel,
|
||||
}) => {
|
||||
// Model configurations with icons - matching actual CODEX_MODELS
|
||||
const modelConfigs = {
|
||||
'auto': {
|
||||
label: 'Auto',
|
||||
icon: CheckCircle,
|
||||
iconColor: 'text-interactive',
|
||||
description: 'Auto-select',
|
||||
},
|
||||
'gpt-5': {
|
||||
label: 'GPT-5',
|
||||
icon: Brain,
|
||||
iconColor: 'text-interactive',
|
||||
description: 'Standard',
|
||||
},
|
||||
'gpt-5-codex': {
|
||||
label: 'GPT-5 Codex',
|
||||
icon: Zap,
|
||||
iconColor: 'text-status-success',
|
||||
description: 'Optimized for coding',
|
||||
},
|
||||
};
|
||||
|
||||
const currentConfig = modelConfigs[selectedModel as keyof typeof modelConfigs] || modelConfigs['gpt-5'];
|
||||
const Icon = currentConfig.icon;
|
||||
|
||||
// Create dropdown items
|
||||
const dropdownItems: DropdownItem[] = Object.entries(CODEX_MODELS).map(([modelId, model]) => {
|
||||
const config = modelConfigs[modelId as keyof typeof modelConfigs];
|
||||
return {
|
||||
id: modelId,
|
||||
label: model.label,
|
||||
description: model.description,
|
||||
icon: config?.icon || Target,
|
||||
iconColor: config?.iconColor || 'text-interactive',
|
||||
onClick: () => setSelectedModel(modelId as OpenAICodexModel),
|
||||
};
|
||||
});
|
||||
|
||||
// Create trigger button
|
||||
const triggerButton = (
|
||||
<Pill
|
||||
icon={<Icon className={`w-3.5 h-3.5 ${currentConfig.iconColor}`} />}
|
||||
title={`Model: ${currentConfig.description}. Click to change.`}
|
||||
>
|
||||
{currentConfig.label}
|
||||
<svg className="w-3.5 h-3.5 text-text-tertiary"
|
||||
fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</Pill>
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown
|
||||
trigger={triggerButton}
|
||||
items={dropdownItems}
|
||||
selectedId={selectedModel}
|
||||
position="auto"
|
||||
width="sm"
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Sandbox Mode Selector Component
|
||||
interface SandboxSelectorProps {
|
||||
sandboxMode: 'read-only' | 'workspace-write' | 'danger-full-access';
|
||||
setSandboxMode: (mode: 'read-only' | 'workspace-write' | 'danger-full-access') => void;
|
||||
}
|
||||
|
||||
const SandboxSelector: React.FC<SandboxSelectorProps> = ({
|
||||
sandboxMode,
|
||||
setSandboxMode,
|
||||
}) => {
|
||||
const modeConfigs = {
|
||||
'read-only': {
|
||||
label: 'Read Only',
|
||||
color: 'text-text-secondary',
|
||||
description: 'AI can only read files, cannot make any changes'
|
||||
},
|
||||
'workspace-write': {
|
||||
label: 'Workspace',
|
||||
color: 'text-interactive',
|
||||
description: 'AI can read and write files within the workspace'
|
||||
},
|
||||
'danger-full-access': {
|
||||
label: 'Full Access',
|
||||
color: 'text-status-warning',
|
||||
description: 'AI has full system access (use with caution)'
|
||||
},
|
||||
};
|
||||
|
||||
const currentConfig = modeConfigs[sandboxMode];
|
||||
|
||||
const dropdownItems: DropdownItem[] = Object.entries(modeConfigs).map(([mode, config]) => ({
|
||||
id: mode,
|
||||
label: config.label,
|
||||
description: config.description,
|
||||
onClick: () => setSandboxMode(mode as 'read-only' | 'workspace-write' | 'danger-full-access'),
|
||||
}));
|
||||
|
||||
const getTooltipText = () => {
|
||||
return `Sandbox Mode: ${currentConfig.description}`;
|
||||
};
|
||||
|
||||
const triggerButton = (
|
||||
<Pill title={getTooltipText()}>
|
||||
<span className={currentConfig.color}>{currentConfig.label}</span>
|
||||
<svg className="w-3.5 h-3.5 text-text-tertiary"
|
||||
fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</Pill>
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown
|
||||
trigger={triggerButton}
|
||||
items={dropdownItems}
|
||||
selectedId={sandboxMode}
|
||||
position="auto"
|
||||
width="sm"
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
// Thinking Level Selector Component
|
||||
interface ThinkingLevelSelectorProps {
|
||||
thinkingLevel: 'low' | 'medium' | 'high';
|
||||
setThinkingLevel: (level: 'low' | 'medium' | 'high') => void;
|
||||
}
|
||||
|
||||
const ThinkingLevelSelector: React.FC<ThinkingLevelSelectorProps> = ({
|
||||
thinkingLevel,
|
||||
setThinkingLevel,
|
||||
}) => {
|
||||
const levelConfigs = {
|
||||
'low': {
|
||||
label: 'Low',
|
||||
icon: Gauge,
|
||||
iconColor: 'text-interactive',
|
||||
description: 'Faster responses with less reasoning'
|
||||
},
|
||||
'medium': {
|
||||
label: 'Medium',
|
||||
icon: Brain,
|
||||
iconColor: 'text-interactive',
|
||||
description: 'Balanced speed and reasoning'
|
||||
},
|
||||
'high': {
|
||||
label: 'High',
|
||||
icon: Zap,
|
||||
iconColor: 'text-status-success',
|
||||
description: 'Slower but more thorough reasoning'
|
||||
}
|
||||
};
|
||||
|
||||
const currentConfig = levelConfigs[thinkingLevel];
|
||||
const Icon = currentConfig.icon;
|
||||
|
||||
const dropdownItems: DropdownItem[] = Object.entries(levelConfigs).map(([level, config]) => ({
|
||||
id: level,
|
||||
label: config.label,
|
||||
description: config.description,
|
||||
icon: config.icon,
|
||||
iconColor: config.iconColor,
|
||||
onClick: () => setThinkingLevel(level as 'low' | 'medium' | 'high'),
|
||||
}));
|
||||
|
||||
const triggerButton = (
|
||||
<Pill
|
||||
icon={<Icon className={`w-3.5 h-3.5 ${currentConfig.iconColor}`} />}
|
||||
title={`Thinking Level: ${currentConfig.description}. Click to change.`}
|
||||
>
|
||||
{currentConfig.label}
|
||||
<svg className="w-3.5 h-3.5 text-text-tertiary"
|
||||
fill="none" stroke="currentColor" strokeWidth={2} viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</Pill>
|
||||
);
|
||||
|
||||
return (
|
||||
<Dropdown
|
||||
trigger={triggerButton}
|
||||
items={dropdownItems}
|
||||
selectedId={thinkingLevel}
|
||||
position="auto"
|
||||
width="sm"
|
||||
onOpenChange={() => {}}
|
||||
/>
|
||||
);
|
||||
};
|
||||