diff --git a/.claude/optimization-todos.md b/.claude/optimization-todos.md deleted file mode 100644 index e007f1dd..00000000 --- a/.claude/optimization-todos.md +++ /dev/null @@ -1,234 +0,0 @@ -# Claudeman Code Optimization TODO List - -> Generated: 2026-01-21 -> Purpose: Comprehensive optimization roadmap for future sessions - -## Overview - -This document contains prioritized optimization tasks identified through codebase analysis. -Each item has specific file:line references and expected impact estimates. - ---- - -## HIGH PRIORITY OPTIMIZATIONS - -### 1. String Concatenation in Hot Paths -- **Files**: `src/session.ts:460, 677-686`, `src/respawn-controller.ts:469, 826`, `src/inner-loop-tracker.ts:408` -- **Issue**: String `+=` in terminal buffer accumulation creates GC pressure -- **Fix**: Use array-based accumulation with periodic joins -- **Impact**: 10-20% faster terminal streaming - -### 2. Regex Pattern lastIndex Reset -- **Files**: `src/inner-loop-tracker.ts:464-479`, `src/screen-manager.ts:264` -- **Issue**: Global regex without lastIndex reset causes skip-every-other-match bug -- **Fix**: Always reset `pattern.lastIndex = 0` before use -- **Impact**: Correct pattern matching, eliminate intermittent bugs - -### 3. Unbounded Buffer Growth -- **Files**: `src/respawn-controller.ts:268-269`, `src/inner-loop-tracker.ts:257-258` -- **Issue**: Buffers lack proper size limits or have loose limits -- **Fix**: Add hard limits with Ring Buffer pattern -- **Impact**: Bounded memory, prevent OOM in long sessions - -### 4. Event Listener Management -- **Files**: `src/respawn-controller.ts:446-455`, `src/session.ts:481-501`, `src/web/server.ts:987-1084` -- **Issue**: Listeners created repeatedly without cleanup tracking -- **Fix**: Use debounce/throttle utilities, consolidate timeout management -- **Impact**: Fewer memory leaks, reduced GC sweeps - -### 5. Task Lookup Optimization -- **Files**: `src/task-tracker.ts:214-220, 231-234` -- **Issue**: O(n) sequential iteration for task lookups -- **Fix**: Add secondary indices `runningTasksByType: Map>` -- **Impact**: O(1) lookups, faster with 1000+ tasks - ---- - -## MEDIUM PRIORITY OPTIMIZATIONS - -### 6. Pattern Test Result Caching -- **Files**: `src/inner-loop-tracker.ts:529-543` -- **Issue**: Multiple pattern tests on same data without caching -- **Fix**: Use `.exec()` once and reuse result -- **Impact**: 2-3x faster todo detection - -### 7. Dynamic Terminal Batching -- **Files**: `src/web/server.ts:46, 1350-1360` -- **Issue**: 16ms flush interval is too long for interactive sessions -- **Fix**: Flush immediately if batch > 1KB OR timeout 16ms -- **Impact**: Snappier UI feel - -### 8. Buffer Pagination -- **Files**: `src/session.ts:314-365`, `src/web/server.ts:219-224` -- **Issue**: Full buffer sent on every state update -- **Fix**: Add `/api/sessions/:id/history?offset=X&limit=Y` -- **Impact**: 10-100x faster reconnects - -### 9. Remove Unused Regex Patterns -- **Files**: `src/respawn-controller.ts:52-59` -- **Issue**: ANSI_ESCAPE_PATTERN, WHITESPACE_PATTERN marked @deprecated but still compiled -- **Fix**: Remove unused patterns -- **Impact**: Cleaner code, slightly faster startup - -### 10. State Serialization -- **Files**: `src/state-store.ts:80, 196`, `src/web/server.ts:1343` -- **Issue**: Full JSON.stringify on every save -- **Fix**: Incremental or selective serialization -- **Impact**: 5-10x faster state saves - ---- - -## LOW PRIORITY OPTIMIZATIONS - -### 11. Error Handling Consistency -- **Files**: `src/screen-manager.ts:101-104`, `src/session.ts:726-729`, `src/web/server.ts:838-845` -- **Issue**: Mix of try-catch and error codes -- **Fix**: Create ErrorRegistry, standardize responses -- **Impact**: Better debugging - -### 12. TypeScript Strict Typing -- **Files**: `src/task-tracker.ts:179`, `src/web/server.ts:138, 174` -- **Issue**: Some implicit `any` types -- **Fix**: Strong typing for all messages and payloads -- **Impact**: Better IDE support, fewer runtime errors - -### 13. Dead Code Removal -- **Files**: `src/task.ts`, `src/task-queue.ts`, `src/ralph-loop.ts` -- **Issue**: Potentially unused files -- **Fix**: Verify imports, remove unused -- **Impact**: Cleaner codebase - -### 14. Console Logging -- **Files**: Throughout `src/session.ts`, `src/respawn-controller.ts`, `src/screen-manager.ts` -- **Issue**: Debug logs not disabled in production -- **Fix**: Use logger abstraction with levels -- **Impact**: Cleaner logs - -### 15. Magic Numbers -- **Files**: `src/session.ts:397, 428`, `src/respawn-controller.ts:614, 619` -- **Issue**: Hardcoded timeout values -- **Fix**: Extract to named constants -- **Impact**: Easier tuning - ---- - -## Implementation Phases - -### Phase 1 (Critical) - Items #1-5 -- Time: 8-12 hours -- Expected Gain: 30% performance - -### Phase 2 (Important) - Items #6-10 -- Time: 6-8 hours -- Expected Gain: 15% performance - -### Phase 3 (Polish) - Items #11-15 -- Time: 4-6 hours -- Expected Gain: 5% + code quality - ---- - -## Progress Tracking - -| Item | Status | Completed By | Notes | -|------|--------|--------------|-------| -| 1 | ✅ Done | Claude | BufferAccumulator in session.ts, respawn-controller.ts | -| 2 | ✅ Done | Claude | Fixed lastIndex resets - now reset BEFORE .test() calls | -| 3 | ✅ Done | Claude | BufferAccumulator auto-trims, no manual limits needed | -| 4 | ✅ Done | Claude | cleanupTrackerListeners() stores/removes handlers; event debouncing in InnerLoopTracker | -| 5 | ☐ Pending | | | -| 6 | ✅ Done | Claude | Pre-checks before regex (hasCheckbox, hasTodoIndicator, etc.) - 60-75% reduction | -| 7 | ✅ Done | Claude | Immediate flush for >1KB batches | -| 8 | ☐ Pending | | | -| 9 | ✅ Done | Claude | Removed ANSI_ESCAPE_PATTERN, WHITESPACE_PATTERN | -| 10 | ✅ Done | Claude | broadcastSessionStateDebounced() batches state updates at 500ms intervals | -| 11 | ☐ Pending | | | -| 12 | ☐ Pending | | | -| 13 | ☐ Pending | | Not unused - used by CLI | -| 14 | ☐ Pending | | | -| 15 | ☐ Pending | | | - ---- - -## Session Log (2026-01-21) - -### Completed This Session: -1. **Regex lastIndex Fix** (#2): Moved lastIndex resets to BEFORE .test() calls in inner-loop-tracker.ts -2. **Event Listener Cleanup** (#4): Added `cleanupTrackerListeners()` in session.ts to properly remove TaskTracker and InnerLoopTracker listeners -3. **Event Debouncing** (#4): Added 50ms debouncing for todoUpdate/loopUpdate events in InnerLoopTracker -4. **Regex Pre-checks** (#6): Added fast pre-checks (string.includes) before expensive regex execution -5. **Promise Race Condition Fix**: Added `_promptResolved` flag in session.ts to prevent double resolution -6. **State Update Debouncing** (#10): Added `broadcastSessionStateDebounced()` in server.ts batching at 500ms intervals -7. **withTimeout Utility**: Added exported utility for async operation protection with configurable timeouts -8. **WebUI Render Debouncing**: Added debouncing to `renderInnerStatePanel` (50ms), `renderTaskPanel` (100ms), `renderScreenSessions` (100ms) -9. **CSS Containment**: Added `contain` property to terminal container, session tabs, ralph panel, task panel, and modal content for paint isolation -10. **GPU-Accelerated Animations**: Added `will-change` for animated elements, use transform-based transitions -11. **Input Batching**: Batch rapid keystrokes at 60fps, immediate flush for control chars -12. **Incremental DOM Updates (Ralph)**: Reuse existing DOM elements in Ralph todo list, ~80% fewer DOM ops -13. **Incremental DOM Updates (Tabs)**: Session tabs update only changed properties, ~70% fewer DOM ops - -### Documentation Work: -14. **README Improvements**: Added Requirements section, Performance Optimized section -15. **CLAUDE.md Updates**: Added timing constants, updated optimization status section -16. **TUI Implementation Plan**: Added implementation status with completed/pending files -17. **Test Badge Fix**: Updated test count to 195 passing - -### Commits: -- `df91823` - fix: improve memory safety and regex pattern handling -- `08b76cd` - perf: add event debouncing to InnerLoopTracker -- `645f86e` - perf: optimize regex execution and fix promise race condition -- `1a7c6d3` - fix: prevent memory leaks from orphaned event listeners -- `2709d43` - perf: add session state update debouncing in server -- `ef843bc` - docs: update optimization tracking with completed items -- `c0688e0` - perf: optimize WebUI rendering and CSS performance -- `26ab141` - docs: add WebUI optimization roadmap and session log -- `3dd6ea5` - perf: add input batching for rapid keystrokes -- `ab6f630` - perf: add incremental DOM updates for Ralph todo list -- `af1ea57` - perf: add incremental updates for session tabs rendering -- `63b9abc` - docs: add session tabs incremental updates to log -- `b4adbeb` - docs: fix test count in README badge (195 passing) -- `224be69` - docs: improve README for GitHub publishing -- `b3dd0bc` - docs: update CLAUDE.md with optimization status -- `84dab25` - feat(tui): add terminal user interface with Ink -- `f681972` - feat(tui): add real-time terminal output polling -- `451de84` - docs: add implementation status to TUI plan -- `8da6dce` - feat(tui): add arrow key navigation and screen attach - ---- - -## WebUI Future Optimizations - -### High Priority - -| Optimization | File | Description | Expected Impact | Status | -|-------------|------|-------------|-----------------|--------| -| Virtual scrolling for todo lists | `app.js` | Render only visible todos for long lists | 10x improvement for 100+ todos | Pending | -| Incremental DOM updates | `app.js` | Use DOM diffing instead of innerHTML | Reduces reflows by 50% | ✅ Done | -| Web Worker for JSON parsing | `app.js` | Offload SSE message parsing to worker | Smoother UI during high throughput | Pending | -| Request coalescing | `app.js` | Batch rapid API calls (resize, input) | Fewer network requests | ✅ Done (input) - -### Medium Priority - -| Optimization | File | Description | Expected Impact | -|-------------|------|-------------|-----------------| -| Service Worker caching | `sw.js` (new) | Cache static assets, offline support | Faster subsequent loads | -| WebSocket upgrade | `server.ts`, `app.js` | Replace SSE with WebSocket for bidirectional | Lower latency for input | -| IndexedDB for terminal history | `app.js` | Store large buffers in IndexedDB | Reduces memory footprint | -| CSS custom properties for themes | `styles.css` | Dynamic theme switching | Better theming support | - -### Low Priority - -| Optimization | File | Description | Expected Impact | -|-------------|------|-------------|-----------------| -| Preconnect hints | `index.html` | Add preconnect for external resources | Faster initial load | -| Code splitting | Build config | Split vendor/app bundles | Better caching | -| Compression for SSE | `server.ts` | gzip compression for SSE stream | 50% bandwidth reduction | - -### Performance Metrics to Track - -1. **Time to First Byte (TTFB)** - Server response time -2. **First Contentful Paint (FCP)** - Initial render time -3. **Time to Interactive (TTI)** - When UI becomes responsive -4. **Input Latency** - Delay between keypress and display -5. **Frame Rate** - Target 60fps during terminal output -6. **Memory Usage** - Monitor for leaks during long sessions diff --git a/.claude/settings.json b/.claude/settings.json deleted file mode 100644 index 5473423d..00000000 --- a/.claude/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "permissions": { - "defaultMode": "bypassPermissions" - } -} diff --git a/.claude/skills/e2e-test.md b/.claude/skills/e2e-test.md deleted file mode 100644 index 7d6d9ca9..00000000 --- a/.claude/skills/e2e-test.md +++ /dev/null @@ -1,85 +0,0 @@ -# E2E Testing with Agent-Browser - -This skill uses agent-browser to perform end-to-end testing of the Claudeman web interface. - -## Usage - -When this skill is invoked, run comprehensive E2E tests on the web interface. - -## Test Plan - -### Prerequisites -1. Ensure the server is running: `npm run dev` or `claudeman web` -2. Default URL: http://localhost:3000 - -### Test Execution - -Use `npx agent-browser` to run the following tests: - -```bash -# Test 1: Connection and Initial Load -npx agent-browser open http://localhost:3000 -npx agent-browser wait --load networkidle -npx agent-browser snapshot -npx agent-browser screenshot /tmp/claudeman-test-1-initial.png - -# Test 2: Font Controls (A+/A-) -npx agent-browser find text "A-" click -npx agent-browser wait 500 -npx agent-browser find text "A+" click -npx agent-browser find text "A+" click -npx agent-browser screenshot /tmp/claudeman-test-2-font.png - -# Test 3: Tab Count Stepper -npx agent-browser find text "+" click # Increment tab count -npx agent-browser find text "+" click -npx agent-browser find text "−" click # Decrement -npx agent-browser screenshot /tmp/claudeman-test-3-tabcount.png - -# Test 4: Create Claude Session -npx agent-browser find text "Run Claude" click -npx agent-browser wait 2000 -npx agent-browser snapshot -npx agent-browser screenshot /tmp/claudeman-test-4-session.png - -# Test 5: Open Session Options (gear icon on tab) -npx agent-browser snapshot # Get element refs -# Find and click the gear icon on the session tab -npx agent-browser screenshot /tmp/claudeman-test-5-options.png - -# Test 6: Test Respawn Settings in Modal -# Should see: Update Prompt, Idle Timeout, Step Delay, Duration, checkboxes -npx agent-browser screenshot /tmp/claudeman-test-6-respawn.png - -# Test 7: Monitor Panel -npx agent-browser find text "Monitor" click -npx agent-browser wait 500 -npx agent-browser snapshot -npx agent-browser screenshot /tmp/claudeman-test-7-monitor.png - -# Test 8: Close Monitor Panel -npx agent-browser find text "×" click -npx agent-browser screenshot /tmp/claudeman-test-8-closed.png - -# Cleanup -npx agent-browser close -``` - -### Expected Results - -1. **Initial Load**: Page loads with header containing: logo, session tabs, font controls (A-/14/A+), connection status, tokens display, settings gear -2. **Font Controls**: Font controls should be to the LEFT of connection status -3. **Tab Count Stepper**: Nice stepper with −/number/+ buttons, not just a plain number input -4. **Session Creation**: Session tab appears, terminal shows Claude starting -5. **Session Options**: Modal opens with session name, directory, AND respawn settings (Update Prompt, timeouts, checkboxes) -6. **Monitor Panel**: Shows "Screen Sessions" and "Background Tasks" sections -7. **Respawn Settings**: All settings integrated into the session options modal, NO separate bottom panel - -### Verification Checklist - -- [ ] Font controls positioned left of connection status -- [ ] Tab count has nice stepper buttons (−/+) -- [ ] No "Respawn Settings" button in footer -- [ ] Respawn settings appear in Session Options modal -- [ ] Monitor panel opens and shows both sections -- [ ] Sessions are wrapped in GNU screen (check with `screen -ls`) diff --git a/.claude/tui-implementation-plan.md b/.claude/tui-implementation-plan.md deleted file mode 100644 index 29b89617..00000000 --- a/.claude/tui-implementation-plan.md +++ /dev/null @@ -1,349 +0,0 @@ -# Claudeman TUI Implementation Plan - -## Overview - -Build a full terminal user interface (TUI) for Claudeman that mirrors the web interface functionality. The TUI will allow users to: -- See all running screen sessions as tabs -- Switch between sessions with keyboard shortcuts -- View real-time terminal output from each Claude session -- Create, manage, and kill sessions -- Control respawn and Ralph loop features - ---- - -## Implementation Status - -> Last updated: 2026-01-21 - -### Completed Files - -| File | Status | Notes | -|------|--------|-------| -| `src/tui/index.tsx` | ✅ Done | Entry point with Ink render | -| `src/tui/App.tsx` | ✅ Done | Main app component with state management | -| `src/tui/components/StartScreen.tsx` | ✅ Done | Initial session discovery view | -| `src/tui/components/TabBar.tsx` | ✅ Done | Session tabs at top | -| `src/tui/components/TerminalView.tsx` | ✅ Done | PTY output display (renamed from Terminal.tsx) | -| `src/tui/components/StatusBar.tsx` | ✅ Done | Bottom status bar | -| `src/tui/components/HelpOverlay.tsx` | ✅ Done | Keyboard shortcuts help | -| `src/tui/components/index.ts` | ✅ Done | Component exports | -| `src/tui/hooks/useSessionManager.ts` | ✅ Done | Session management hook | -| `src/tui/hooks/index.ts` | ✅ Done | Hook exports | -| `src/cli.ts` | ✅ Done | `tui` command added | - -### Remaining Work - -| File | Status | Notes | -|------|--------|-------| -| `src/tui/components/RalphPanel.tsx` | ✅ Done | Inner loop/todo tracking panel | -| `src/tui/hooks/useTerminal.ts` | ⏭️ Skipped | Functionality merged into useSessionManager | -| `src/tui/hooks/useKeyboard.ts` | ⏭️ Skipped | Using Ink's useInput directly | -| `src/tui/store/tui-state.ts` | ⏭️ Skipped | Using React hooks instead | - -### Phase Completion - -- [x] **Phase 1**: Foundation (entry point, main app) -- [x] **Phase 2**: Start Screen & Session Discovery -- [x] **Phase 3**: Tab System -- [x] **Phase 4**: Terminal Display (basic) -- [x] **Phase 5**: Status Bar -- [x] **Phase 6**: Session Management (create/kill/attach) -- [x] **Phase 7**: Advanced Features (Ralph panel, respawn banner) - -### Usage - -```bash -claudeman tui # Start TUI -npx tsx src/index.ts tui # Dev mode -``` - ---- - -## Technology Choice: **Ink (React for CLI)** - -**Why Ink over alternatives:** -1. **Component-based**: Familiar React patterns, composable UI -2. **Already in ecosystem**: Claude CLI uses Ink (explains the screen input workaround) -3. **TypeScript native**: First-class TS support -4. **Active maintenance**: Regular updates, good community -5. **Handles PTY well**: Built for terminal apps with real-time output - -**Alternatives considered:** -- `blessed`/`blessed-contrib`: Legacy, unmaintained, complex API -- `terminal-kit`: Lower-level, more boilerplate -- Raw ANSI: Too low-level for complex UIs -- Existing bash script: Not extensible enough - -## Architecture - -``` -src/ -├── tui/ -│ ├── index.ts # Entry point, CLI command -│ ├── App.tsx # Main TUI app component -│ ├── components/ -│ │ ├── TabBar.tsx # Session tabs at top -│ │ ├── Terminal.tsx # PTY output display -│ │ ├── StatusBar.tsx # Bottom status bar -│ │ ├── SessionInfo.tsx # Session details panel -│ │ ├── HelpOverlay.tsx # Keyboard shortcuts help -│ │ ├── RalphPanel.tsx # Inner loop/todo tracking -│ │ └── StartScreen.tsx # Initial session discovery -│ ├── hooks/ -│ │ ├── useSession.ts # Session management hook -│ │ ├── useTerminal.ts # Terminal output handling -│ │ └── useKeyboard.ts # Global keyboard shortcuts -│ └── store/ -│ └── tui-state.ts # TUI-specific state -``` - -## Implementation Steps - -### Phase 1: Foundation (Core Infrastructure) - -#### Step 1.1: Add Dependencies -```bash -npm install ink ink-text-input ink-spinner ink-box react -npm install -D @types/react -``` - -#### Step 1.2: Create Entry Point (`src/tui/index.ts`) -- Add `tui` command to CLI in `src/cli.ts` -- Create Ink render entry point -- Handle graceful shutdown (restore terminal) - -#### Step 1.3: Create Main App Component (`src/tui/App.tsx`) -- Full-screen layout with Ink's `Box` components -- Three regions: TabBar (top), Terminal (center), StatusBar (bottom) -- Global keyboard event handling - -### Phase 2: Start Screen & Session Discovery - -#### Step 2.1: Create StartScreen Component -On launch, the TUI should: -1. Read `~/.claudeman/screens.json` for existing sessions -2. Check which screens are alive (`screen -ls`) -3. Display list of sessions with status -4. Allow user to: - - Select and attach to existing session - - Create new session - - Kill dead sessions - -#### Step 2.2: Session List Display -``` -╔═══════════════════════════════════════════════════════════╗ -║ Claudeman TUI ║ -╠═══════════════════════════════════════════════════════════╣ -║ Existing Sessions: ║ -║ ║ -║ [1] ● testcase 2h 15m idle claude ║ -║ [2] ● another-case 45m working claude ║ -║ [3] ○ old-session 3d dead claude ║ -║ ║ -║ ─────────────────────────────────────────────────────────║ -║ [n] New session [1-9] Select [d] Delete [q] Quit ║ -╚═══════════════════════════════════════════════════════════╝ -``` - -### Phase 3: Tab System - -#### Step 3.1: TabBar Component -- Horizontal tab bar at top of screen -- Shows session name + status indicator (● idle, ◐ working) -- Keyboard navigation: Ctrl+Tab (next), Ctrl+Shift+Tab (prev), Ctrl+1-9 (direct) -- Visual indication of active tab - -#### Step 3.2: Tab State Management -- Track active session ID -- Track tab order (array of session IDs) -- Handle session creation/deletion (add/remove tabs) -- Persist tab order to state - -### Phase 4: Terminal Display - -#### Step 4.1: Terminal Component -- Display PTY output for active session -- Scrollable viewport (show last N lines that fit) -- ANSI color support (Ink handles this) -- Handle terminal resize - -#### Step 4.2: Output Integration -Connect to existing Session class: -```typescript -// Subscribe to session events -session.on('terminal', (data) => { - // Append to display buffer -}); - -session.on('clearTerminal', () => { - // Clear display buffer -}); -``` - -#### Step 4.3: Input Handling -- Capture keyboard input when terminal focused -- Send to session via `session.write()` or `session.writeViaScreen()` -- Handle special keys (Ctrl+C, Ctrl+D, etc.) -- Distinguish between TUI commands and session input - -### Phase 5: Status Bar - -#### Step 5.1: StatusBar Component -Display at bottom: -- Session status (idle/working) -- Token count -- Cost -- Respawn status (if enabled) -- Ralph loop status (if active) - -#### Step 5.2: System Stats (Optional) -- CPU/Memory usage (like web UI) -- Poll periodically from `/proc` - -### Phase 6: Session Management - -#### Step 6.1: New Session Creation -- Prompt for case name (or use default) -- Create case folder if needed -- Start interactive Claude session -- Add to tab bar - -#### Step 6.2: Session Operations -- Close session (Ctrl+W): Kill screen, remove tab -- Kill all (Ctrl+Shift+K): Confirm dialog, kill all screens - -### Phase 7: Advanced Features - -#### Step 7.1: Ralph Panel -When Ralph loop active, show: -- Progress ring (iteration count) -- Todo list with status -- Completion phrase status - -#### Step 7.2: Help Overlay -- Press `?` or `F1` to show -- List all keyboard shortcuts -- Dismiss with Escape - -#### Step 7.3: Respawn Banner -When respawn enabled: -- Show current state -- Cycle count -- Controls (pause/resume) - -## Keyboard Shortcuts - -| Key | Action | -|-----|--------| -| `Ctrl+Tab` | Next tab | -| `Ctrl+Shift+Tab` | Previous tab | -| `Ctrl+1-9` | Go to tab N | -| `Ctrl+N` | New session | -| `Ctrl+W` | Close current session | -| `Ctrl+Shift+K` | Kill all sessions | -| `Ctrl+L` | Clear terminal | -| `?` or `F1` | Show help | -| `Escape` | Close overlay/panel | -| `Ctrl+C` | Exit TUI (with confirm) | - -## Data Flow - -``` -┌──────────────────────────────────────────────────────────────┐ -│ TUI App │ -│ ┌─────────────────────────────────────────────────────────┐ │ -│ │ TabBar │ │ -│ │ [testcase ●] [another ◐] [+] │ │ -│ └─────────────────────────────────────────────────────────┘ │ -│ ┌─────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ Terminal Viewport │ │ -│ │ │ │ -│ │ (PTY output from active session) │ │ -│ │ │ │ -│ └─────────────────────────────────────────────────────────┘ │ -│ ┌─────────────────────────────────────────────────────────┐ │ -│ │ StatusBar: idle | 45.2k tokens | $0.82 | respawn: off │ │ -│ └─────────────────────────────────────────────────────────┘ │ -└──────────────────────────────────────────────────────────────┘ - │ │ - │ events │ input - ▼ ▼ -┌─────────────────┐ ┌─────────────────┐ -│ Session │◄───│ PTY (node-pty) │ -│ (existing) │ └─────────────────┘ -└─────────────────┘ -``` - -## Files to Create - -| File | Purpose | LOC Est. | -|------|---------|----------| -| `src/tui/index.ts` | Entry point | 30 | -| `src/tui/App.tsx` | Main app | 150 | -| `src/tui/components/TabBar.tsx` | Tab navigation | 80 | -| `src/tui/components/Terminal.tsx` | Output display | 120 | -| `src/tui/components/StatusBar.tsx` | Status display | 60 | -| `src/tui/components/StartScreen.tsx` | Initial view | 100 | -| `src/tui/components/HelpOverlay.tsx` | Help modal | 50 | -| `src/tui/components/RalphPanel.tsx` | Loop tracking | 80 | -| `src/tui/hooks/useSession.ts` | Session management | 100 | -| `src/tui/hooks/useTerminal.ts` | Terminal handling | 80 | -| `src/tui/hooks/useKeyboard.ts` | Key shortcuts | 60 | -| `src/tui/store/tui-state.ts` | State management | 50 | - -**Total: ~960 lines of new code** - -## Files to Modify - -| File | Change | -|------|--------| -| `src/cli.ts` | Add `tui` command | -| `src/index.ts` | Export TUI if needed | -| `package.json` | Add Ink dependencies | -| `tsconfig.json` | Add JSX support for TSX files | - -## Testing Strategy - -1. **Unit tests**: Component rendering with Ink's test utilities -2. **Integration tests**: Session creation, tab switching -3. **Manual testing**: Real Claude sessions, screen attach/detach - -## Risks & Mitigations - -| Risk | Mitigation | -|------|------------| -| Terminal resize handling | Use Ink's built-in resize detection | -| PTY output performance | Reuse existing batching from Session class | -| Input conflicts (TUI vs session) | Clear mode distinction, Escape to exit input mode | -| Screen attachment complexity | Reuse existing screen-manager.ts logic | - -## Success Criteria - -1. Launch TUI and see existing sessions from `screens.json` -2. Switch between sessions with tabs -3. See real-time Claude output in terminal -4. Send input to active session -5. Create new sessions -6. Kill sessions -7. Responsive keyboard navigation -8. Clean exit (restore terminal state) - -## Implementation Order - -1. **Week 1**: Phases 1-2 (Foundation + Start Screen) -2. **Week 2**: Phases 3-4 (Tabs + Terminal) -3. **Week 3**: Phases 5-6 (Status + Session Management) -4. **Week 4**: Phase 7 (Advanced Features) - -## Commands - -After implementation: -```bash -# Start TUI -claudeman tui - -# Or via npm/tsx -npx tsx src/index.ts tui -npm run tui # After adding script -``` diff --git a/.gitignore b/.gitignore index 495203f6..0cd6fa8b 100644 --- a/.gitignore +++ b/.gitignore @@ -33,3 +33,4 @@ Thumbs.db # Temporary files *.tmp *.temp +.claude/